An open-source, faster Devin alternative
TypeScript
sdk: startSessionOnDocument creates a document if absent, then a session bound to it
Igor Zalutski25e9a5daa4f3
diff --git a/sdks/typescript/README.md b/sdks/typescript/README.mdindex d2f57e5a..2bec0f63 100644--- a/sdks/typescript/README.md+++ b/sdks/typescript/README.md@@ -170,6 +170,22 @@ await oc.credentials.delete(creds[0].id);Or reference one by id when creating an agent: `oc.agents.create({ …, credential: "cred_…" })`. A key isn't required — `credential: "managed"` needs none; a session fails with `422 no_credential` only when it resolves to neither Managed nor a usable key. Full guide: [Credentials](https://docs.opencomputer.dev/agent-sessions/credentials).+### Serverless Agents memory++Serverless Agents (`opencomputer deploy`) keep notes in [memory](https://opencomputer.dev/agents/memory). This package types its management API and ships one helper for the moment an application opens a topic: create the document if it is new, then create a session bound to it, both converging under one key on retry:++```typescript+import { startSessionOnDocument } from "@opencomputer/sdk";++const { document, session } = await startSessionOnDocument({+ apiKey: process.env.OPENCOMPUTER_API_KEY!,+ projectId: "prj_…", environment: "development", agent: "topic-worker",+ resource: "topics", documentId: "workshop", document: { title: "Workshop" },+ idempotencyKey: `topic/workshop/${deploymentId}`,+});+// document.created, session.created: false when they already existed.+```+## Sandbox webhooks (Preview)Subscribe to sandbox lifecycle events (`sandbox.ready`, `sandbox.stopped`, …) — signed, retried, and redeliverable. The same `verifyWebhook` helper verifies both session and sandbox deliveries. **Preview: newly available; the surface may change.**diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.tsindex b7b3d731..e7801674 100644--- a/sdks/typescript/src/agents/index.ts+++ b/sdks/typescript/src/agents/index.ts@@ -54,6 +54,8 @@ export type {} from "./schedules.js";export { verifyWebhook, WebhookVerificationError } from "./webhooks.js";export type { WebhookDelivery, VerifyWebhookOptions } from "./webhooks.js";+export { startSessionOnDocument, sessionIdempotencyKey } from "./memory-sessions.js";+export type { StartSessionOnDocumentParams, StartSessionOnDocumentResult } from "./memory-sessions.js";export type {MemoryEnvironment, MemoryAccess, MemoryAgentWrites, MemoryBinding, MemoryBindings,SessionMemoryBinding, MemoryWriter, MemoryDocumentMeta, MemoryDocument, MemoryDocumentPage,diff --git a/sdks/typescript/src/agents/memory-sessions.test.ts b/sdks/typescript/src/agents/memory-sessions.test.tsnew file mode 100644index 00000000..21b55e16--- /dev/null+++ b/sdks/typescript/src/agents/memory-sessions.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "vitest";+import { ConflictError, NotFoundError } from "./errors.js";+import { sessionIdempotencyKey, startSessionOnDocument } from "./memory-sessions.js";++interface Call { method: string; url: string; headers: Record<string, string>; body?: Record<string, unknown> }++const document = (id: string, revision: string) => ({+ id, title: "Workshop", text: "", summary: "", agentWrites: "enabled", revision,+ bytes: 0, maxBytes: 8192, updatedAt: "2026-09-10T12:00:00.000Z", writer: { kind: "owner" },+});++// The two routes the helper touches, with a switchable document state and a+// session store keyed by Idempotency-Key.+function fakeApi(state: { document: "absent" | "present" | "deleted"; sessions?: Map<string, string> }) {+ const calls: Call[] = [];+ const sessions = state.sessions ?? new Map<string, string>();+ const fetch: typeof globalThis.fetch = async (input, init) => {+ const url = new URL(String(input));+ const headers: Record<string, string> = {};+ new Headers(init?.headers).forEach((value, name) => { headers[name] = value; });+ const call: Call = { method: init?.method ?? "GET", url: `${url.pathname}${url.search}`, headers };+ if (typeof init?.body === "string") call.body = JSON.parse(init.body) as Record<string, unknown>;+ calls.push(call);+ if (url.pathname.endsWith("/documents/workshop")) {+ if (call.method === "PUT") {+ if (state.document === "absent") { state.document = "present"; return Response.json(document("workshop", "r1"), { status: 201 }); }+ return Response.json({ error: { code: "precondition_failed", message: "id already used" } }, { status: 412 });+ }+ if (state.document === "present") return Response.json(document("workshop", "r7"));+ return Response.json({ error: { code: "not_found", message: "deleted" } }, { status: 404 });+ }+ if (url.pathname === "/api/managed-agents/sessions" && call.method === "POST") {+ const key = headers["idempotency-key"];+ const existing = sessions.get(key);+ if (existing === "other-bindings") {+ return Response.json({ error: { code: "idempotency_conflict", message: "Idempotency-Key was already used with different session input" } }, { status: 409 });+ }+ if (existing) return Response.json({ session: { id: existing, status: "idle", executionMode: "workerd" } }, { status: 200 });+ const id = `ses-${sessions.size + 1}`;+ sessions.set(key, id);+ return Response.json({ session: { id, status: "connecting", executionMode: "workerd" } }, { status: 201 });+ }+ return Response.json({ error: { code: "not_found", message: "no route" } }, { status: 404 });+ };+ return { calls, fetch, sessions };+}++const params = {+ apiKey: "osb_test", projectId: "prj_1", environment: "development" as const, agent: "openmuse-dev--topic-worker",+ resource: "topics", documentId: "workshop", document: { title: "Workshop" }, idempotencyKey: "topic/workshop/1",+};++describe("startSessionOnDocument", () => {+ it("creates the document, then the session bound to it, under derived keys", async () => {+ const api = fakeApi({ document: "absent" });+ const result = await startSessionOnDocument({ ...params, fetch: api.fetch });++ expect(result).toEqual({+ document: { id: "workshop", created: true, revision: "r1", title: "Workshop" },+ session: { id: "ses-1", created: true, status: "connecting", executionMode: "workerd" },+ });+ expect(api.calls.map((call) => `${call.method} ${call.url}`)).toEqual([+ "PUT /api/managed-agents/projects/prj_1/memory/topics/documents/workshop?environment=development",+ "POST /api/managed-agents/sessions",+ ]);+ const [create, session] = api.calls;+ expect(create.headers["if-none-match"]).toBe("*");+ expect(create.headers["x-api-key"]).toBe("osb_test");+ expect(create.body).toEqual({ title: "Workshop", text: "" });+ expect(session.headers["idempotency-key"]).toBe(await sessionIdempotencyKey("topic/workshop/1"));+ expect(session.body).toEqual({+ agentId: "openmuse-dev--topic-worker@development",+ source: "api",+ memory: { topics: { scope: "document", id: "workshop", access: "read-write" } },+ });+ });++ it("converges on a retry: the document and the session both already exist", async () => {+ const api = fakeApi({ document: "absent" });+ await startSessionOnDocument({ ...params, fetch: api.fetch });+ const retry = await startSessionOnDocument({ ...params, fetch: api.fetch });++ expect(retry.document).toEqual({ id: "workshop", created: false, revision: "r7", title: "Workshop" });+ expect(retry.session).toMatchObject({ id: "ses-1", created: false });+ // The retry read the existing document after its conditional create was refused.+ expect(api.calls.slice(2).map((call) => `${call.method} ${call.url.split("?")[0]}`)).toEqual([+ "PUT /api/managed-agents/projects/prj_1/memory/topics/documents/workshop",+ "GET /api/managed-agents/projects/prj_1/memory/topics/documents/workshop",+ "POST /api/managed-agents/sessions",+ ]);+ });++ it("keeps different keys apart and carries extra bindings, access and source", async () => {+ const api = fakeApi({ document: "present" });+ const first = await startSessionOnDocument({ ...params, fetch: api.fetch, idempotencyKey: "a" });+ const second = await startSessionOnDocument({+ ...params, fetch: api.fetch, idempotencyKey: "b", access: "read", source: "openmuse",+ memory: { profile: { scope: "document", id: "owner", access: "read" } },+ });+ expect(first.session.id).not.toBe(second.session.id);+ expect(api.calls.at(-1)?.body).toEqual({+ agentId: "openmuse-dev--topic-worker@development",+ source: "openmuse",+ memory: {+ profile: { scope: "document", id: "owner", access: "read" },+ topics: { scope: "document", id: "workshop", access: "read" },+ },+ });+ expect(await sessionIdempotencyKey("a")).not.toBe(await sessionIdempotencyKey("b"));+ expect(await sessionIdempotencyKey("a")).toBe(await sessionIdempotencyKey("a"));+ });++ it("reports a reused key with different bindings as a conflict", async () => {+ const sessions = new Map([[await sessionIdempotencyKey("topic/workshop/1"), "other-bindings"]]);+ const api = fakeApi({ document: "present", sessions });+ await expect(startSessionOnDocument({ ...params, fetch: api.fetch })).rejects.toThrow(ConflictError);+ await expect(startSessionOnDocument({ ...params, fetch: api.fetch })).rejects.toThrow(/different agent, deployment, environment or memory bindings/);+ });++ it("refuses a deleted document id instead of creating a session that cannot bind it", async () => {+ const api = fakeApi({ document: "deleted" });+ await expect(startSessionOnDocument({ ...params, fetch: api.fetch })).rejects.toThrow(NotFoundError);+ expect(api.calls.some((call) => call.url === "/api/managed-agents/sessions")).toBe(false);+ });+});diff --git a/sdks/typescript/src/agents/memory-sessions.ts b/sdks/typescript/src/agents/memory-sessions.tsnew file mode 100644index 00000000..884e3e6c--- /dev/null+++ b/sdks/typescript/src/agents/memory-sessions.ts@@ -0,0 +1,201 @@+// Start a session on a memory document in one call (docs/agents/document-memory.mdx,+// "Start a session on a new document"). The management API keeps the two+// objects separate on purpose: a document is owner data with its own+// lifetime, a session binding is admission to it, and nothing creates one as+// a side effect of the other. What an application wants at the moment it+// opens a topic is still "these notes, this session", so this helper does the+// two calls in order and makes the pair converge under one key.+//+// This helper speaks to the project-scoped Serverless Agents surface+// (`/api/managed-agents/...`) with an API key, not to the Durable Agent+// Sessions client in this package. Use it from trusted server code only.++import { ConflictError, errorFromResponse, NotFoundError, OpenComputerError, type ApiErrorBody } from "./errors.js";+import type { MemoryAccess, MemoryAgentWrites, MemoryBindings, MemoryDocument, MemoryEnvironment } from "./memory.js";++const DEFAULT_MANAGED_AGENTS_URL = "https://app.opencomputer.dev";++export interface StartSessionOnDocumentParams {+ /** An OpenComputer API key with access to the project. Server-side only. */+ apiKey: string;+ /** The project whose memory holds the document. */+ projectId: string;+ /** Development and Production have separate memory; the session runs in the same environment. */+ environment: MemoryEnvironment;+ /** The deployed agent's id (not `agent@alias`; the environment above supplies the alias). */+ agent: string;+ /** The declared memory resource and the document id to bind. */+ resource: string;+ documentId: string;+ /** What to create when the document does not exist yet. Ignored when it does. */+ document: {+ title: string;+ /** Default `""`. */+ text?: string;+ /** Default `""`. */+ summary?: string;+ /** Default `"enabled"`. */+ agentWrites?: MemoryAgentWrites;+ };+ /** The binding's access. Default `read-write`. */+ access?: MemoryAccess;+ /** Further bindings for the session, keyed by resource id. */+ memory?: MemoryBindings;+ /**+ * One key for the whole operation. A retry with the same key returns the+ * same session; the document converges on its id regardless.+ */+ idempotencyKey: string;+ /** The session's `source`. Default `api`. */+ source?: string;+ /** The Serverless Agents API. Default `https://app.opencomputer.dev`. */+ baseUrl?: string;+ /** Override fetch (runtimes without a global, or testing). */+ fetch?: typeof fetch;+ signal?: AbortSignal;+}++export interface StartSessionOnDocumentResult {+ document: {+ id: string;+ /** False when the document already existed; its content was left as it was. */+ created: boolean;+ /** The current revision, for a later conditional owner write. */+ revision: string;+ title: string;+ };+ session: {+ id: string;+ /** False when the key had already created this session. */+ created: boolean;+ status?: string;+ executionMode?: string;+ };+}++/**+ * The session-create `Idempotency-Key` derived from the caller's key: stable+ * for a retry, distinct from any other use of the same caller key.+ */+export async function sessionIdempotencyKey(idempotencyKey: string): Promise<string> {+ const bytes = new TextEncoder().encode(`opencomputer.memory.session\0${idempotencyKey}`);+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));+ let hex = "";+ for (const byte of digest) hex += byte.toString(16).padStart(2, "0");+ return hex;+}++async function readBody(response: Response): Promise<unknown> {+ try { return await response.json(); } catch { return undefined; }+}++function errorBody(body: unknown): ApiErrorBody | undefined {+ if (!body || typeof body !== "object") return undefined;+ const error = (body as { error?: unknown }).error;+ if (typeof error === "string") return { message: error };+ if (error && typeof error === "object") return error as ApiErrorBody;+ return undefined;+}++/**+ * Creates the document if it does not exist, then creates the session bound+ * to it, and reports both ids and whether each already existed.+ *+ * - The document is created with `If-None-Match: *`; an existing document is+ * kept as it is and reported with `created: false`. An id that was deleted+ * is reserved and fails with a `NotFoundError`, since a binding to it would+ * fail admission.+ * - 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 with+ * `created: false`. Anything else under the same key is a `ConflictError`.+ */+export async function startSessionOnDocument(+ params: StartSessionOnDocumentParams,+): Promise<StartSessionOnDocumentResult> {+ const doFetch = params.fetch ?? (typeof fetch !== "undefined" ? fetch : undefined);+ if (!doFetch) throw new Error("global fetch is unavailable — pass { fetch }.");+ const base = (params.baseUrl ?? DEFAULT_MANAGED_AGENTS_URL).replace(/\/+$/, "");+ const headers = { "x-api-key": params.apiKey, accept: "application/json", "content-type": "application/json" };+ const documentUrl =+ `${base}/api/managed-agents/projects/${encodeURIComponent(params.projectId)}` ++ `/memory/${encodeURIComponent(params.resource)}/documents/${encodeURIComponent(params.documentId)}` ++ `?environment=${encodeURIComponent(params.environment)}`;++ const createResponse = await doFetch(documentUrl, {+ method: "PUT",+ headers: { ...headers, "if-none-match": "*" },+ body: JSON.stringify({+ title: params.document.title,+ text: params.document.text ?? "",+ ...(params.document.summary !== undefined ? { summary: params.document.summary } : {}),+ ...(params.document.agentWrites ? { agentWrites: params.document.agentWrites } : {}),+ }),+ signal: params.signal,+ });+ let document: MemoryDocument;+ let documentCreated: boolean;+ if (createResponse.status === 201) {+ document = (await createResponse.json()) as MemoryDocument;+ documentCreated = true;+ } else if (createResponse.status === 412) {+ const readResponse = await doFetch(documentUrl, { method: "GET", headers, signal: params.signal });+ if (readResponse.status === 404) {+ throw new NotFoundError(+ 404,+ {+ code: "memory_document_deleted",+ message:+ `Document ${params.resource}/${params.documentId} was deleted and its id is reserved; ` ++ "a session cannot bind it. Use a new document id.",+ },+ "document deleted",+ );+ }+ if (!readResponse.ok) throw errorFromResponse(readResponse.status, errorBody(await readBody(readResponse)));+ document = (await readResponse.json()) as MemoryDocument;+ documentCreated = false;+ } else {+ throw errorFromResponse(createResponse.status, errorBody(await readBody(createResponse)));+ }++ const sessionResponse = await doFetch(`${base}/api/managed-agents/sessions`, {+ method: "POST",+ headers: { ...headers, "idempotency-key": await sessionIdempotencyKey(params.idempotencyKey) },+ body: JSON.stringify({+ agentId: `${params.agent}@${params.environment}`,+ source: params.source ?? "api",+ memory: {+ ...params.memory,+ [params.resource]: { scope: "document", id: params.documentId, access: params.access ?? "read-write" },+ },+ }),+ signal: params.signal,+ });+ const sessionBody = await readBody(sessionResponse);+ if (sessionResponse.status === 409) {+ throw new ConflictError(+ 409,+ {+ code: "idempotency_key_reused",+ message:+ `Idempotency key ${JSON.stringify(params.idempotencyKey)} already created a session with a different ` ++ "agent, deployment, environment or memory bindings. Use a new key to start another session; " ++ "the document was left as it is.",+ },+ "idempotency key reused",+ );+ }+ if (!sessionResponse.ok) throw errorFromResponse(sessionResponse.status, errorBody(sessionBody));+ const session = (sessionBody as { session?: { id?: string; status?: string; executionMode?: string } })?.session;+ if (!session?.id) throw new OpenComputerError(sessionResponse.status, undefined, "session create returned no session id");+ return {+ document: { id: document.id, created: documentCreated, revision: document.revision, title: document.title },+ session: {+ id: session.id,+ created: sessionResponse.status === 201,+ ...(session.status ? { status: session.status } : {}),+ ...(session.executionMode ? { executionMode: session.executionMode } : {}),+ },+ };+}