An open-source, faster Devin alternative
TypeScript
Session list filters, cursor pagination and externalReference in api-edge, SDK, CLI, dashboard and docs (OCFR-04) (#801)
devin-ai-integration[bot]c4e418f14193
diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex d11aa404..cae575f0 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.7.13",+ "version": "0.7.14","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.7.13",+ "version": "0.7.14","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",diff --git a/cli/package.json b/cli/package.jsonindex af28771d..28af15d5 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.7.13",+ "version": "0.7.14","description": "Build, test, deploy, and share OpenComputer agents as code.","type": "module","bin": {diff --git a/cli/src/api.test.ts b/cli/src/api.test.tsindex 5448316f..9c63d2d1 100644--- a/cli/src/api.test.ts+++ b/cli/src/api.test.ts@@ -418,3 +418,30 @@ test("database queries use the project read endpoint with positional parameters"parameters: ["pricing", 20],});});++test("session list sends exact filters, the page size and the cursor as query parameters", async (context) => {+ const requests: Request[] = [];+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ requests.push(request);+ return Response.json({ sessions: [], nextCursor: null });+ });+ const client = new OpenComputerClient({ apiUrl: "https://app.opencomputer.dev", apiKey: "test" });++ await client.sessions();+ await client.sessions({+ status: "suspended",+ agent: "reviewer",+ externalReference: "order 42/α",+ limit: 2,+ cursor: "eyJjIjoxfQ",+ });++ assert.equal(new URL(requests[0]!.url).search, "");+ const query = new URL(requests[1]!.url).searchParams;+ assert.equal(query.get("status"), "suspended");+ assert.equal(query.get("agentId"), "reviewer");+ assert.equal(query.get("externalReference"), "order 42/α");+ assert.equal(query.get("limit"), "2");+ assert.equal(query.get("cursor"), "eyJjIjoxfQ");+});diff --git a/cli/src/api.ts b/cli/src/api.tsindex 557bc99a..1e76c614 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -285,6 +285,8 @@ export interface ManagedSessionSnapshot {agentId?: string;deploymentId?: string;microvmState?: string;+ /** The caller's own reference from creation, when one was given. */+ externalReference?: string;createdAt?: string;updatedAt?: string;turns?: Array<{@@ -306,6 +308,8 @@ export interface ManagedSessionSummary {source: string;status: string;labels: Record<string, string>;+ /** The caller's own reference from creation, when one was given. */+ externalReference?: string;createdAt: string;updatedAt: string;revision: number;@@ -327,6 +331,18 @@ export interface ManagedSessionPage {nextCursor: string | null;}+/** Exact-match filters and paging of `GET /sessions` (docs/agents/api.mdx, "Get and list"). */+export interface ManagedSessionListOptions {+ status?: string;+ /** The agent's id. */+ agent?: string;+ externalReference?: string;+ /** `nextCursor` of the previous page; only valid with the same filters. */+ cursor?: string;+ /** Page size, default 50, at most 100. */+ limit?: number;+}+export type MemoryEnvironment = "development" | "production";export type MemoryWriter =@@ -1371,9 +1387,14 @@ export class OpenComputerClient {/** One page of session rows, newest created first; pass `cursor` for the next page. */async sessions(- options: { cursor?: string; limit?: number } = {},+ options: ManagedSessionListOptions = {},): Promise<ManagedSessionPage> {const query = new URLSearchParams();+ if (options.status) query.set("status", options.status);+ if (options.agent) query.set("agentId", options.agent);+ if (options.externalReference !== undefined) {+ query.set("externalReference", options.externalReference);+ }if (options.cursor) query.set("cursor", options.cursor);if (options.limit) query.set("limit", String(options.limit));const suffix = query.size ? `?${query.toString()}` : "";diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex d0faff03..ee086553 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -39,6 +39,7 @@ import {import {developmentAgentReference,parseSessionCommand,+ parseSessionListOptions,resolveProjectAgent,} from "./session-command.js";import {@@ -432,9 +433,13 @@ function printSession(.map(([key, value]) => `${key}=${value}`).join(","): "";+ const reference =+ session.externalReference !== undefined+ ? ` ref=${session.externalReference}`+ : "";process.stdout.write(`${session.id} ${session.status.padEnd(15)} ` +- `${session.agentId ?? "—"} ${deployment.slice(0, 12)}${labels}\n`,+ `${session.agentId ?? "—"} ${deployment.slice(0, 12)}${labels}${reference}\n`,);}@@ -2645,12 +2650,16 @@ export async function runCommand(const session = parseSessionCommand(args);const sessionArgs = session.args;if (session.action === "list") {- const cursor = option(sessionArgs, "--cursor");+ const filters = parseSessionListOptions(sessionArgs);if (sessionArgs.length)throw new Error(`Unexpected argument: ${sessionArgs[0]}`);- // One page of rows, newest created first. The page carries the- // cursor of the next one; `--cursor` continues from it.- const page = await client.sessions(cursor ? { cursor } : {});+ // One page of rows, newest created first, narrowed by the exact+ // filters. The page carries the cursor of the next one; `--cursor`+ // continues from it with the same filters.+ const page = await client.sessions({+ ...filters,+ ...(session.agent ? { agent: session.agent } : {}),+ });if (globals.json) printJSON(page);else if (!page.sessions.length) process.stdout.write("No sessions.\n");else {diff --git a/cli/src/index.ts b/cli/src/index.tsindex ba2d1c75..93495dfb 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -66,7 +66,8 @@ Usage:--memory binds a document (read-write by default) or a collection; --create-documentcreates each bound document that does not exist yet; with --idempotency-key a retryreturns the same session- opencomputer session list+ opencomputer session list [--status <status>] [--agent <agent-id>] [--external-reference <ref>]+ [--limit <1-100>] [--cursor <next-cursor>]opencomputer session inspect <session-id>opencomputer session attach <session-id>opencomputer session send <session-id> <prompt> [--keep]diff --git a/cli/src/session-command.test.ts b/cli/src/session-command.test.tsindex b7291588..715af53c 100644--- a/cli/src/session-command.test.ts+++ b/cli/src/session-command.test.ts@@ -5,6 +5,7 @@ import {developmentAgentReference,parseMemoryBinding,parseSessionCommand,+ parseSessionListOptions,resolveProjectAgent,} from "./session-command.js";@@ -121,3 +122,51 @@ test("session create rejects malformed memory bindings", () => {assert.throws(() => parseSessionCommand(["--create-document"]), /needs at least one --memory/);assert.throws(() => parseSessionCommand(["--memory", "notes", "--create-document"]), /applies to document bindings/);});++test("session list accepts an agent id filter", () => {+ assert.deepEqual(parseSessionCommand(["list", "--agent", "reviewer"]), {+ action: "list",+ args: [],+ keep: false,+ agent: "reviewer",+ });+ assert.throws(+ () => parseSessionCommand(["inspect", "ses_1", "--agent", "reviewer"]),+ /only supported when creating or listing/,+ );+});++test("session list takes exact filters, a page size and a cursor", () => {+ const args = [+ "--status",+ "suspended",+ "--external-reference=order-42",+ "--limit",+ "2",+ "--cursor",+ "eyJjIjoxfQ",+ ];+ assert.deepEqual(parseSessionListOptions(args), {+ status: "suspended",+ externalReference: "order-42",+ cursor: "eyJjIjoxfQ",+ limit: 2,+ });+ assert.deepEqual(args, []);+ assert.deepEqual(parseSessionListOptions([]), {});+});++test("session list rejects a page size outside 1..100 and empty filters", () => {+ for (const limit of ["0", "101", "2.5", "-1", "many"]) {+ assert.throws(+ () => parseSessionListOptions(["--limit", limit]),+ /--limit must be a whole number from 1 to 100/,+ );+ }+ assert.throws(() => parseSessionListOptions(["--status"]), /--status requires a value/);+ assert.throws(+ () => parseSessionListOptions(["--external-reference="]),+ /--external-reference requires a value/,+ );+ assert.throws(() => parseSessionListOptions(["--cursor", "--limit", "2"]), /--cursor requires a value/);+});diff --git a/cli/src/session-command.ts b/cli/src/session-command.tsindex 4302c3eb..f44ca16b 100644--- a/cli/src/session-command.ts+++ b/cli/src/session-command.ts@@ -12,6 +12,7 @@ export type SessionCommand = {action: SessionAction;args: string[];keep: boolean;+ /** `--agent`: the project agent to create on, or the agent id to list by. */agent?: string;/** `--memory` bindings for `create`, keyed by resource. */memory?: MemoryBindings;@@ -139,6 +140,63 @@ function takeAgentOption(args: string[]): string | undefined {return value;}+const SESSION_LIST_MAX_LIMIT = 100;++function takeValueOption(args: string[], name: string): string | undefined {+ const equalsIndex = args.findIndex((argument) =>+ argument.startsWith(`${name}=`),+ );+ if (equalsIndex >= 0) {+ const value = args[equalsIndex]!.slice(name.length + 1);+ args.splice(equalsIndex, 1);+ return value;+ }+ const index = args.indexOf(name);+ if (index < 0) return undefined;+ const value = args[index + 1];+ if (value === undefined || value.startsWith("--")) {+ throw new Error(`${name} requires a value`);+ }+ args.splice(index, 2);+ return value;+}++/**+ * The filters of `session list`: `--status`, `--external-reference`,+ * `--limit` and `--cursor` (`--agent` is taken with the command). Each is an+ * exact match; the values are sent as given and the API answers `400` for+ * one it does not accept. Consumes the options it recognises from `args`.+ */+export function parseSessionListOptions(args: string[]): {+ status?: string;+ externalReference?: string;+ cursor?: string;+ limit?: number;+} {+ const status = takeValueOption(args, "--status");+ if (status === "") throw new Error("--status requires a value");+ const externalReference = takeValueOption(args, "--external-reference");+ if (externalReference === "") {+ throw new Error("--external-reference requires a value");+ }+ const cursor = takeValueOption(args, "--cursor");+ if (cursor === "") throw new Error("--cursor requires a value");+ const limitValue = takeValueOption(args, "--limit");+ let limit: number | undefined;+ if (limitValue !== undefined) {+ limit = /^\d+$/.test(limitValue) ? Number.parseInt(limitValue, 10) : NaN;+ if (!Number.isInteger(limit) || limit < 1 || limit > SESSION_LIST_MAX_LIMIT) {+ throw new Error(`--limit must be a whole number from 1 to ${SESSION_LIST_MAX_LIMIT}`);+ }+ }+ return {+ ...(status !== undefined ? { status } : {}),+ ...(externalReference !== undefined ? { externalReference } : {}),+ ...(cursor !== undefined ? { cursor } : {}),+ ...(limit !== undefined ? { limit } : {}),+ };+}+export function parseSessionCommand(rawArgs: string[]): SessionCommand {const deprecated = rawArgs.find((argument) =>DEPRECATED_ROUTING_OPTIONS.some(@@ -167,8 +225,8 @@ export function parseSessionCommand(rawArgs: string[]): SessionCommand {shorthand && ACTIONS.has(shorthand)? (args.shift()! as SessionAction): "create";- if (agent && action !== "create") {- throw new Error("--agent is only supported when creating a session.");+ if (agent && action !== "create" && action !== "list") {+ throw new Error("--agent is only supported when creating or listing sessions.");}if (memory && action !== "create") {throw new Error("--memory is only supported when creating a session.");diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex c837c282..285522eb 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -3580,6 +3580,244 @@ describe("managed agents proxy", () => {);});+ it("passes session filters through and keeps the owner's externalReference on create, list rows, inspect and events", async () => {+ const fetchSpy = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (init?.method === "POST") {+ return Response.json(+ {+ session: {+ id: "session-1",+ executionMode: "workerd",+ status: "connecting",+ createdAt: "2026-09-15T00:00:00.000Z",+ externalReference: "cypen/order/42",+ accountId: "org_test",+ },+ },+ { status: 201 },+ );+ }+ if (url.endsWith("/events")) {+ return Response.json({+ events: [+ {+ id: "evt-1",+ seq: 1,+ timestamp: "2026-09-15T00:00:00.000Z",+ sessionId: "session-1",+ turnId: null,+ type: "session.created",+ data: { externalReference: "cypen/order/42", accountId: "org_test" },+ },+ {+ id: "evt-2",+ seq: 2,+ timestamp: "2026-09-15T00:00:01.000Z",+ sessionId: "session-1",+ turnId: null,+ type: "session.failed",+ data: {+ reason: "runtime_lost",+ error: "internal stack trace org_test",+ externalReference: "cypen/order/42",+ },+ },+ ],+ });+ }+ if (url.includes("/sessions/session-1")) {+ return Response.json({+ id: "session-1",+ status: "idle",+ externalReference: "cypen/order/42",+ labels: {},+ revision: 1,+ result: null,+ turns: [],+ accountId: "org_test",+ });+ }+ return Response.json({+ sessions: [+ {+ id: "session-1",+ projectId: "prj_test",+ agentId: "reviewer",+ deploymentId: "reviewer:digest",+ environment: "development",+ source: "api",+ status: "idle",+ labels: {},+ externalReference: "cypen/order/42",+ createdAt: "2026-09-15T00:00:00.000Z",+ updatedAt: "2026-09-15T00:00:00.000Z",+ revision: 1,+ activity: { activeTurnId: null, queued: 0, lastSettledTurn: null },+ result: null,+ accountId: "org_test",+ },+ {+ id: "session-2",+ projectId: "prj_test",+ agentId: "reviewer",+ deploymentId: "reviewer:digest",+ environment: "development",+ source: "api",+ status: "idle",+ labels: {},+ createdAt: "2026-09-15T00:00:00.000Z",+ updatedAt: "2026-09-15T00:00:00.000Z",+ revision: 1,+ activity: { activeTurnId: null, queued: 0, lastSettledTurn: null },+ result: null,+ },+ ],+ nextCursor: null,+ });+ });+ vi.stubGlobal("fetch", fetchSpy);+ const env = {+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ };+ const identity = { orgID: "org_test", userID: "user_test" };++ const created = await proxyManagedAgents(+ new Request("https://app.opencomputer.dev/api/managed-agents/sessions", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "idempotency-key": "order-42",+ },+ body: JSON.stringify({+ agentId: "reviewer",+ externalReference: "cypen/order/42",+ }),+ }),+ env,+ identity,+ "/api/managed-agents",+ );+ expect(created.status).toBe(201);+ const [, createInit] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];+ expect(await new Response(createInit.body).json()).toMatchObject({+ externalReference: "cypen/order/42",+ });+ expect(new Headers(createInit.headers).get("idempotency-key")).toBe("order-42");+ expect(await created.json()).toEqual({+ session: {+ id: "session-1",+ executionMode: "workerd",+ status: "connecting",+ createdAt: "2026-09-15T00:00:00.000Z",+ externalReference: "cypen/order/42",+ },+ });++ const query =+ "projectId=prj_test&environment=development&agentId=reviewer&status=idle&deploymentId=reviewer%3Adigest&externalReference=cypen%2Forder%2F42&createdAfter=2026-09-14T00%3A00%3A00Z&createdBefore=2026-09-16T00%3A00%3A00Z&updatedAfter=2026-09-14T00%3A00%3A00Z&limit=2&cursor=abc";+ const listed = await proxyManagedAgents(+ new Request(+ `https://app.opencomputer.dev/api/managed-agents/sessions?${query}`,+ ),+ env,+ identity,+ "/api/managed-agents",+ );+ expect(listed.status).toBe(200);+ const [listTarget] = fetchSpy.mock.calls[1] as unknown as [URL];+ expect(String(listTarget)).toBe(+ `https://managedagents.test/v1/sessions?${query}`,+ );+ const page = (await listed.json()) as {+ sessions: Array<Record<string, unknown>>;+ nextCursor: string | null;+ };+ expect(page.nextCursor).toBeNull();+ expect(page.sessions[0]).toMatchObject({+ id: "session-1",+ externalReference: "cypen/order/42",+ });+ expect(page.sessions[1]).not.toHaveProperty("externalReference");+ expect(JSON.stringify(page)).not.toContain("org_test");++ const inspected = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1",+ ),+ env,+ identity,+ "/api/managed-agents",+ );+ expect(await inspected.json()).toMatchObject({+ id: "session-1",+ externalReference: "cypen/order/42",+ });++ const events = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events",+ ),+ env,+ identity,+ "/api/managed-agents",+ );+ const eventBody = (await events.json()) as {+ events: Array<{ type: string; data: Record<string, unknown> }>;+ };+ expect(eventBody.events[0]).toMatchObject({+ type: "session.created",+ data: { externalReference: "cypen/order/42" },+ });+ expect(eventBody.events[1]?.type).toBe("session.failed");+ expect(eventBody.events[1]?.data.externalReference).toBe("cypen/order/42");+ expect(eventBody.events[1]?.data).not.toHaveProperty("error");+ expect(eventBody.events[1]?.data).not.toHaveProperty("reason");+ expect(JSON.stringify(eventBody)).not.toContain("org_test");+ });++ it("explains rejected external references and mismatched cursors", async () => {+ for (const [code, status, expected] of [+ [+ "invalid_external_reference",+ 400,+ /externalReference must be a non-empty string/,+ ],+ ["invalid_cursor", 400, /issued for different filters/],+ ["idempotency_conflict", 409, /conflicts with the current state/],+ ] as const) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json(+ { error: { code, message: "backend detail" } },+ { status },+ ),+ ),+ );+ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/sessions",+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ agentId: "reviewer", externalReference: "" }),+ },+ ),+ { OC_MANAGED_AGENTS_SECRET: "test-secret" },+ { orgID: "org_test", userID: "user_test" },+ "/api/managed-agents",+ );+ expect(response.status).toBe(status);+ const body = (await response.json()) as {+ error: { code: string; message: string };+ };+ expect(body.error.code).toBe(code);+ expect(body.error.message).toMatch(expected);+ }+ });+it("patches session labels and returns the sanitized session with its labels", async () => {const fetchSpy = vi.fn(async () =>Response.json({diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex da449ea6..2a7be504 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -259,7 +259,11 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {message =backendCode === "invalid_agent_name"? "Agent names must use lowercase letters, numbers, and hyphens."- : "The agent request was invalid.";+ : backendCode === "invalid_external_reference"+ ? "externalReference must be a non-empty string of at most 256 bytes of UTF-8 without control characters."+ : backendCode === "invalid_cursor"+ ? "The cursor is invalid or was issued for different filters. Start again from the first page."+ : "The agent request was invalid.";} else if (upstream.status === 401 || upstream.status === 403) {message = "The agent request was not authorized.";} else if (upstream.status === 404) {@@ -1095,6 +1099,19 @@ function publicSessionSnapshot(value: unknown): unknown {);}+/**+ * The caller's own `externalReference`, when the session has one. The value is+ * the caller's opaque string and is read from the source, never from a+ * stripped copy, for the same reason labels are.+ */+function ownerExternalReference(+ source: Record<string, unknown>,+): { externalReference: string } | Record<never, never> {+ return typeof source.externalReference === "string"+ ? { externalReference: source.externalReference }+ : {};+}+/** One list row as documented: nothing private is in it, and the labels and result are the owner's. */function publicSessionSummary(value: unknown): unknown {const source = record(value);@@ -1109,6 +1126,7 @@ function publicSessionSummary(value: unknown): unknown {source: row.source,status: row.status,labels: ownerLabels(source),+ ...ownerExternalReference(source),createdAt: row.createdAt,updatedAt: row.updatedAt,revision: row.revision,@@ -1383,7 +1401,13 @@ function publicEventData(value: unknown,): Record<string, unknown> {if (type.startsWith("runtime.") && type !== "runtime.log") return {};- if (type === "session.failed" || type === "turn.failed") {+ if (type === "session.failed") {+ return {+ ...publicFailure(value),+ ...ownerExternalReference(record(value) ?? {}),+ };+ }+ if (type === "turn.failed") {return { ...publicFailure(value) };}const data = record(value) ?? {};@@ -1937,6 +1961,7 @@ function publicSuccessBody(executionMode: session.executionMode,status: session.status,createdAt: session.createdAt,+ ...ownerExternalReference(session),},deployment: body.deployment? publicDeployment(body.deployment)diff --git a/create-start/package.json b/create-start/package.jsonindex 16e6216b..c7968c6b 100644--- a/create-start/package.json+++ b/create-start/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/create-start",- "version": "0.7.13",+ "version": "0.7.14","description": "Create a hello-world OpenComputer agent application.","type": "module","bin": {@@ -18,7 +18,7 @@"node": ">=22.0.0"},"dependencies": {- "@opencomputer/cli": "0.7.13"+ "@opencomputer/cli": "0.7.14"},"publishConfig": {"access": "public"diff --git a/docs/agents/api.mdx b/docs/agents/api.mdxindex 6b1a55f7..8e9bca2c 100644--- a/docs/agents/api.mdx+++ b/docs/agents/api.mdx@@ -84,8 +84,9 @@ curl -X POST 'https://app.opencomputer.dev/api/managed-agents/sessions' \| `memory` | Bindings keyed by resource ID, at most eight. Needs a deployed agent and an environment. Shapes on [Document memory](/agents/document-memory#session-bindings). || `source` | `api` (default), `playground` or `webhook`. The dashboard groups sessions by it. || `labels` | Your own metadata on the session, an object of strings; see [Labels](#labels). Applied at creation and ignored on a replay of the same `Idempotency-Key`. |+| `externalReference` | Your own reference for the session, such as the id of the record it works for: a string of 1 to 256 bytes of UTF-8 without control characters. Stored as given and never interpreted; it is not shown to the agent, grants nothing and does not replace the session id or the `Idempotency-Key`. Returned on the session, its list row and every `session.*` event; see [External references](#external-references). |-The response is `{ session: { id, executionMode, status, createdAt }, deployment }`.+The response is `{ session: { id, executionMode, status, createdAt, externalReference? }, deployment }`.The session starts without a turn; send one with the turns route.`Idempotency-Key` (at most 256 characters) makes a retry safe. The key@@ -99,7 +100,8 @@ identifies the session within your organization:need to know which one that was. A new session under a new key gets thedeployment active at that time.- Anything else under that key is `409 idempotency_conflict`: another- agent, environment or pinned deployment, or different memory bindings.+ agent, environment or pinned deployment, different memory bindings, or a+ different `externalReference` (including adding or dropping one).Pinning the deployment the session already holds counts as the samerequest.- Two identical requests under one key that arrive together create one@@ -117,9 +119,9 @@ identifies the session within your organization:way.Other codes: `400 invalid_environment`, `400 invalid_memory_binding`,-`400 invalid_labels`, `404 deployment_not_found`, `409 deployment_not_promoted`-(a pinned deployment is not active in the named environment), `402-insufficient_credits`.+`400 invalid_labels`, `400 invalid_external_reference`, `404+deployment_not_found`, `409 deployment_not_promoted` (a pinned deployment is+not active in the named environment), `402 insufficient_credits`.### Get and list@@ -133,6 +135,7 @@ insufficient_credits`.| `status` | `new`, `connecting`, `idle`, `running`, `stopping`, `waiting_runtime`, `suspending`, `suspended`, `resuming`, `failed` or `ended` || `source` | The `source` given at creation || `labels`, `labelsUpdatedAt` | Your metadata, and when it last changed; see [Labels](#labels) |+| `externalReference` | The reference given at creation; absent when none was given || `memory` | Bindings with `resource`, `scope`, `id`, `access` and `writable`; present when the session was created with bindings || `turns` | Every turn: `id`, `input`, `mode`, `status`, `createdAt`, `updatedAt`, and `deliveries` when an [event subscription](#event-subscriptions) selected its outcome || `result` | The latest committed output of the agent's [result tool](/agents/tools#the-session-result), or `null`: `{ turnId, callId, reportedAt, data }`. `turnId` and `callId` name the call that reported `data`, so a reader can tell which turn it came from and whether a later turn changed things without reporting. A failed or cancelled turn never clears it. |@@ -149,27 +152,45 @@ curl 'https://app.opencomputer.dev/api/managed-agents/sessions?project=<project-| Parameter | Meaning || --- | --- |-| `project` | A project id or slug |+| `project` or `projectId` | A project id or slug || `environment` | `development` or `production` |-| `agent` | An agent id |+| `agent` or `agentId` | An agent id || `status` | One session status |+| `deploymentId` | A deployment id |+| `externalReference` | Sessions created with exactly this [external reference](#external-references) |+| `createdAfter`, `createdBefore` | RFC 3339 timestamps: sessions with `createdAt >= createdAfter` and `createdAt < createdBefore` |+| `updatedAfter` | An RFC 3339 timestamp: sessions with `updatedAt >= updatedAfter` || `label.<key>=<value>` | Sessions whose label `<key>` equals `<value>` exactly; at most three || `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.+Every filter is an exact match; there is no prefix, substring or wildcard+search. Filters combine with AND. Naming both spellings of a parameter+(`project` and `projectId`, `agent` and `agentId`), any other parameter or a+malformed value is `400 invalid_query`.++Filters select among the sessions the API key can already see: an+organization key sees the organization's sessions, a project-scoped key+only its project's, and a filter naming another project is `403+project_scope_violation`. A `development` filter never returns Production+sessions, and a reference created in one project is not found from another.A row is `id`, `projectId`, `agentId`, `deploymentId`, `environment` (`null`-when the session has none), `source`, `status`, `labels`, `createdAt`,-`updatedAt`, `revision`, `activity` and `result`. `activity` is+when the session has none), `source`, `status`, `labels`,+`externalReference` (when one was given), `createdAt`, `updatedAt`,+`revision`, `activity` and `result`. `activity` is`{ activeTurnId, queued, lastSettledTurn }`: the running turn's id or `null`,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.+`{ id, status, at }` or `null`. Rows carry no `turns`, no `memory` and no+prompt or message text; read `GET /sessions/<id>` for those.-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.+Rows are ordered by `createdAt`, newest first, then by `id`, so sessions+created in the same millisecond have a fixed order and none is skipped.+Updates do not move rows. `nextCursor` is an opaque string, valid only with+the filters of the page that returned it: sending it with different filters+is `400 invalid_cursor`, and so is a cursor that cannot be read. `limit` may+change between pages. `null` means there are no more matches after that+cursor.Pagination is not a snapshot: each request applies the filters to thecurrent rows. New sessions and sessions that newly match a status or label@@ -178,6 +199,37 @@ them. Sorting fetched rows by `updatedAt` orders only those rows, not allmatching sessions. A successful create response confirms the session islisted.+### External references++`externalReference` is one opaque string your application chooses when it+creates a session, for example the id of the order, ticket or job the+session works for. It is 1 to 256 bytes of UTF-8 with no control characters;+anything else is `400 invalid_external_reference`. Omitting it, or sending+`null`, creates a session without one; it cannot be changed afterwards, and+it is not required to be unique.++The platform stores the reference as given. It is not sent to the agent or+the model, does not grant access, and does not replace the session id or the+`Idempotency-Key`. Keep your own mapping from reference to session id as the+authoritative record; the reference is there for recovery and audit when+that record is incomplete:++- If a create response was lost, retry with the same `Idempotency-Key`+ first; it returns the same session with `200`. The reference makes+ a second recovery path available: `GET /sessions?externalReference=<ref>`+ finds the session however many unrelated sessions were created since.+- A retry of the key with a different reference is `409+ idempotency_conflict`, so two records can never share one session by+ accident.+- The reference is returned on the session, on its list row and in the+ `data` of every `session.*` [event](/agents/events), so a consumer of the+ event log can route each event to the record it belongs to without+ another lookup.++A reference is metadata, not a credential: do not put secrets, tokens or+signed URLs in it. It is visible to every API key that can read the+session.+### LabelsLabels are your own metadata on a session: at most 16 keys, each matchingdiff --git a/docs/agents/events.mdx b/docs/agents/events.mdxindex 037060ac..720eb51d 100644--- a/docs/agents/events.mdx+++ b/docs/agents/events.mdx@@ -47,6 +47,10 @@ unknown type as informational and keep reading.| `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) |+When the session was created with an [external+reference](/agents/api#external-references), every `session.*` event's+`data` also carries it as `externalReference`.+`stopping` follows an [interrupt](/agents/api#end-and-interrupt) or aninterrupt-mode turn: the session stays there until the stopped turn'scommands are confirmed stopped or its computer is terminated, then `idle`diff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdxindex caac4f4e..00c3c73b 100644--- a/docs/agents/sessions.mdx+++ b/docs/agents/sessions.mdx@@ -32,11 +32,30 @@ debug inspector.## Finding sessionsGive a session labels when you create it, such as the ticket, repository or-user it works for, and list sessions by project, environment, agent, status-and label instead of keeping your own index of session ids. The list returns-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).+user it works for, and list sessions by project, environment, agent,+deployment, status, creation or update time and label instead of keeping+your own index of session ids. The list returns rows with the session's+status, its current turn activity and its latest result, and never the+prompts or messages; 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).++When one session stands for one record in your application, give it that+record's id as its `externalReference` at creation. The reference is stored+as given, returned on the session and its lifecycle events, and is an exact+list filter: after a lost create response, retry with the same request key+first, then `GET /sessions?externalReference=<ref>` finds the session+however many unrelated sessions have been created since. Retrying the key+with a different reference is refused, so a record cannot be attached to+the wrong session. Bounds and semantics are on the [API+reference](/agents/api#external-references).++The list is paged: at most 100 rows per request, 50 by default, newest+created first. Follow `nextCursor` with the same filters until it is+`null`; every session matching the filters appears exactly once, however+many were created in the same instant. The [TypeScript+client](/reference/typescript-sdk/agents#sessions) does this for you with+`sessions.iterate(filters)`.## Execution, labels and results@@ -109,6 +128,19 @@ npm run session -- send <session-id> "Continue"npm run session -- end <session-id>```+`list` shows the newest sessions first, one page at a time; narrow it with+exact filters and continue from the cursor the previous page printed. With+`--json` the page is printed as `{ sessions, nextCursor }` for scripts:++```bash+opencomputer session list --status suspended --agent reviewer --limit 20+opencomputer session list --external-reference order-42 --json+opencomputer session list --limit 2 --cursor <next-cursor> --json+```++`--agent` takes the agent's id, `--limit` is 1 to 100, and `--cursor`+continues only with the filters that produced it.+Bind [memory](/agents/memory) documents when creating a session; add`--create-document` to create the ones that do not exist yet:diff --git a/docs/reference/typescript-sdk/agents.mdx b/docs/reference/typescript-sdk/agents.mdxindex 52df9905..4d4857e3 100644--- a/docs/reference/typescript-sdk/agents.mdx+++ b/docs/reference/typescript-sdk/agents.mdx@@ -111,7 +111,8 @@ its contents affect application correctness or access.| --- | --- | --- || `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.list(query?)` | `GET /sessions` | `{ sessions, nextCursor }`: one page |+| `sessions.iterate(query?)` | `GET /sessions`, page by page | An async iterator over every matching row || `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 |@@ -119,16 +120,29 @@ its contents affect application correctness or access.| `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`,+`create` takes `agentId`, `deploymentId`, `environment`, `memory`, `source`,+`labels` and `externalReference` as [documented](/agents/api#create). `turns.send` takes `input`,`idempotencyKey`, `mode` and `payload`; both `create` and `turns.send` sendthe key as the `Idempotency-Key` header. The receipt carries the turn'spersisted `status`: `queued` or `running` for a new turn, and for a repeatedkey the existing turn's status, `completed`, `failed` or `cancelled` once ithas settled, with `duplicate: true`. The client maps nothing, so a retry-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`.+after a lost reply learns what became of the turn. `list` takes the exact+filters of [`GET /sessions`](/agents/api#get-and-list): `project` or+`projectId`, `environment`, `agent` or `agentId`, `status`, `deploymentId`,+`externalReference`, `createdAfter`, `createdBefore`, `updatedAfter`,+`labels` (up to three, sent as `label.<key>=<value>`), plus `cursor` and+`limit` (1 to 100, default 50). `iterate` takes the same query and requests+the next page whenever the previous one is consumed, stopping when+`nextCursor` is `null`; it reads live rows, so a session created while you+iterate may or may not be seen.++```typescript+const recovered = await oc.sessions.list({ externalReference: orderId });+for await (const row of oc.sessions.iterate({ status: "suspended", limit: 100 })) {+ console.log(row.id, row.externalReference);+}+```### Create and submitdiff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.jsonindex 557305db..a3a2f9cd 100644--- a/sdks/typescript/package-lock.json+++ b/sdks/typescript/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/sdk",- "version": "2.1.2",+ "version": "2.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/sdk",- "version": "2.1.2",+ "version": "2.2.0","license": "MIT","dependencies": {"undici": "^6.0.0 || ^7.0.0"diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex 060ba1d3..ad81c3ce 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "2.1.2",+ "version": "2.2.0","description": "TypeScript SDK for OpenComputer - cloud sandboxes and the Serverless Agents management API","type": "module","main": "dist/index.js",diff --git a/sdks/typescript/src/agents/client.test.ts b/sdks/typescript/src/agents/client.test.tsindex 8e46f935..6587b89d 100644--- a/sdks/typescript/src/agents/client.test.ts+++ b/sdks/typescript/src/agents/client.test.ts@@ -99,6 +99,70 @@ describe("OpenComputer client", () => {expect(api.last().path).toBe("/api/managed-agents/sessions");});+ it("sends externalReference on create and reads it back from the session, the row and the create answer", async () => {+ const api = fakeApi({+ "POST /api/managed-agents/sessions": (call) => Response.json(+ { session: { id: "ses_1", status: "connecting", createdAt: "t", externalReference: (call.body as { externalReference: string }).externalReference } },+ { status: 201 },+ ),+ "GET /api/managed-agents/sessions/ses_1": () => Response.json({+ id: "ses_1", agentId: "worker", deploymentId: "dep_1", status: "idle", source: "api", turns: [],+ externalReference: "order/42", createdAt: "t", updatedAt: "t",+ }),+ });+ const client = oc(api);+ const created = await client.sessions.create({ agentId: "worker", externalReference: "order/42" }, { idempotencyKey: "k1" });+ expect(api.last()).toMatchObject({ body: { agentId: "worker", externalReference: "order/42" }, headers: { "idempotency-key": "k1" } });+ expect(created.session.externalReference).toBe("order/42");+ expectTypeOf(created.session.externalReference).toEqualTypeOf<string | undefined>();+ expect((await client.sessions.get("ses_1")).externalReference).toBe("order/42");+ });++ it("sends every exact filter of the list and walks all pages with iterate, stopping at nextCursor null", async () => {+ const row = (id: string, externalReference?: string) => ({+ id, projectId: "prj_1", agentId: "worker", deploymentId: "dep_1", environment: "development", source: "api", status: "idle",+ labels: {}, ...(externalReference === undefined ? {} : { externalReference }), createdAt: "t", updatedAt: "t", revision: 1,+ activity: { activeTurnId: null, queued: 0, lastSettledTurn: null }, result: null,+ });+ const pages: Record<string, { sessions: unknown[]; nextCursor: string | null }> = {+ first: { sessions: [row("ses_5", "order/5"), row("ses_4")], nextCursor: "c2" },+ c2: { sessions: [row("ses_3"), row("ses_2", "order/2")], nextCursor: "c3" },+ c3: { sessions: [row("ses_1")], nextCursor: null },+ };+ const api = fakeApi({+ "GET /api/managed-agents/sessions": (call) => {+ const cursor = new URL(`https://x${call.path}`).searchParams.get("cursor") ?? "first";+ return Response.json(pages[cursor]);+ },+ });+ const filters = {+ projectId: "prj_1", environment: "development" as const, agentId: "worker", status: "idle" as const,+ deploymentId: "dep_1", externalReference: "order/5", createdAfter: "2026-09-24T00:00:00Z",+ createdBefore: "2026-09-25T00:00:00Z", updatedAfter: "2026-09-24T12:00:00Z", labels: { team: "a" },+ };+ const page = await oc(api).sessions.list({ ...filters, limit: 2 });+ expect(page.sessions[0]?.externalReference).toBe("order/5");+ expect(page.sessions[1]).not.toHaveProperty("externalReference");+ expect(Object.fromEntries(new URL(`https://x${api.last().path}`).searchParams.entries())).toEqual({+ projectId: "prj_1", environment: "development", agentId: "worker", status: "idle", deploymentId: "dep_1",+ externalReference: "order/5", createdAfter: "2026-09-24T00:00:00Z", createdBefore: "2026-09-25T00:00:00Z",+ updatedAfter: "2026-09-24T12:00:00Z", "label.team": "a", limit: "2",+ });++ const seen: string[] = [];+ for await (const session of oc(api).sessions.iterate({ status: "idle", limit: 2 })) seen.push(session.id);+ expect(seen).toEqual(["ses_5", "ses_4", "ses_3", "ses_2", "ses_1"]);+ const cursors = api.calls.slice(1).map((call) => new URL(`https://x${call.path}`).searchParams.get("cursor"));+ expect(cursors).toEqual([null, "c2", "c3"]);+ for (const call of api.calls.slice(1)) {+ expect(new URL(`https://x${call.path}`).searchParams.get("status")).toBe("idle");+ }++ const resumed: string[] = [];+ for await (const session of oc(api).sessions.iterate({ cursor: "c3" })) resumed.push(session.id);+ expect(resumed).toEqual(["ses_1"]);+ });+it("sends a turn with its key as the Idempotency-Key header, its mode and payload, and reads the receipt from 202 and 200", async () => {let duplicate = false;const api = fakeApi({diff --git a/sdks/typescript/src/agents/client.ts b/sdks/typescript/src/agents/client.tsindex eded8e8f..4e4a7361 100644--- a/sdks/typescript/src/agents/client.ts+++ b/sdks/typescript/src/agents/client.ts@@ -43,6 +43,7 @@ import type {SessionCreated,SessionEvent,SessionPage,+ SessionSummary,SetLabelsParams,TurnReceipt,UpdateWebhookParams,@@ -62,9 +63,9 @@ export interface CallOptions {export interface CreateSessionOptions extends CallOptions {/*** At most 256 characters. The same key with the same agent (or the same- * pinned deployment), environment and memory bindings returns the- * existing session with the deployment it started on, after a redeploy- * too; anything else under the key is `409 idempotency_conflict`.+ * pinned deployment), environment, memory bindings and `externalReference`+ * returns the existing session with the deployment it started on, after a+ * redeploy too; anything else under the key is `409 idempotency_conflict`.*/idempotencyKey?: string;}@@ -154,9 +155,12 @@ export class Sessions {}/**- * `GET /sessions`: rows ordered by `createdAt` descending then `id`, with- * `nextCursor` for the next page. Sort the pages you hold by `updatedAt`- * for recent activity first.+ * `GET /sessions`: one page of rows matching the exact filters, ordered by+ * `createdAt` descending then `id` ascending, with `nextCursor` for the+ * next page and `null` on the last. A cursor is bound to the filters it+ * was issued with; sending it with different filters is `400+ * invalid_cursor`. Sort the pages you hold by `updatedAt` for recent+ * activity first, or use `iterate` to walk every page.*/list(query: ListSessionsQuery = {}, options: CallOptions = {}): Promise<SessionPage> {const { labels, ...rest } = query;@@ -165,6 +169,27 @@ export class Sessions {return this.http.request("GET", "/sessions", shapes.sessionPage, { query: q, signal: options.signal });}+ /**+ * Every row matching the filters, page by page, until `nextCursor` is+ * `null`. `limit` is the page size; `cursor` is where to start. Paging is+ * live: a session created while you iterate appears only if it sorts+ * after your position.+ *+ * ```ts+ * for await (const row of oc.sessions.iterate({ status: "idle", limit: 100 })) {+ * console.log(row.id, row.externalReference);+ * }+ * ```+ */+ async *iterate(query: ListSessionsQuery = {}, options: CallOptions = {}): AsyncGenerator<SessionSummary, void, undefined> {+ let cursor = query.cursor;+ do {+ const page = await this.list({ ...query, cursor }, options);+ yield* page.sessions;+ cursor = page.nextCursor ?? undefined;+ } while (cursor !== undefined);+ }+/** `POST /sessions/<id>/end`: cancels queued and running turns and revokes memory writes. */end(sessionId: string, options: CallOptions = {}): Promise<Session> {return this.http.request("POST", `/sessions/${segment(sessionId)}/end`, shapes.session, { signal: options.signal });diff --git a/sdks/typescript/src/agents/shapes.ts b/sdks/typescript/src/agents/shapes.tsindex 8515648a..3acc31f7 100644--- a/sdks/typescript/src/agents/shapes.ts+++ b/sdks/typescript/src/agents/shapes.ts@@ -257,6 +257,7 @@ export const session: Shape<Session> = object({turns: array(turn),labels: optional(labels),labelsUpdatedAt: optional(string),+ externalReference: optional(string),revision: optional(number),result: optional(nullable(sessionResult)),createdAt: string,@@ -269,6 +270,7 @@ export const sessionCreated: Shape<Omit<SessionCreated, "created">> = object({status: stringAs<SessionStatus>(),createdAt: string,executionMode: optional(string),+ externalReference: optional(string),}),deployment: optional((value, path) => deployment(value, path)),});@@ -282,6 +284,7 @@ export const sessionSummary: Shape<SessionSummary> = object({source: optional(string),status: stringAs<SessionStatus>(),labels: optional(labels),+ externalReference: optional(string),createdAt: string,updatedAt: string,revision: optional(number),diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.tsindex 0824eae7..2ceb135b 100644--- a/sdks/typescript/src/agents/types.ts+++ b/sdks/typescript/src/agents/types.ts@@ -96,6 +96,8 @@ export interface Session {labels?: SessionLabels;/** When the labels last changed. */labelsUpdatedAt?: string;+ /** Your opaque reference from `create`, returned as given; absent when none was set. */+ externalReference?: string;/** Monotonic; every listed mutation increments it. */revision?: number;/** The latest committed output of the result tool, or `null` when none was committed. */@@ -133,6 +135,15 @@ export interface CreateSessionParams {source?: SessionSource;/** Applied at creation and ignored on an idempotent replay. */labels?: SessionLabels;+ /**+ * Your opaque reference to the session (an order id, a ticket key): at most+ * 256 bytes of UTF-8, no control characters, stored as given and never shown+ * to the agent. Returned on the session, its list row and its `session.*`+ * events, and filterable by exact match with `list({ externalReference })`.+ * Part of the creation identity: a replay of the same `idempotencyKey`+ * with a different reference is `409 idempotency_conflict`.+ */+ externalReference?: string;}/** Turn admission, as `POST /sessions/<id>/turns` answers it. */@@ -185,6 +196,8 @@ export interface SessionSummary {source: SessionSource;status: SessionStatus;labels?: SessionLabels;+ /** Present when the session was created with one. */+ externalReference?: string;createdAt: string;updatedAt: string;revision?: number;@@ -192,16 +205,40 @@ export interface SessionSummary {result?: SessionResult | null;}-/** Filters and paging for `GET /sessions`; any other parameter is `400 invalid_query`. */-export interface ListSessionsQuery {+/**+ * Exact-match filters for `GET /sessions`; any other parameter is+ * `400 invalid_query`. Filters narrow the sessions your key can already see,+ * never widen them.+ */+export interface SessionFilters {+ /** Project id or slug. */project?: string;+ /** Same filter as `project`. */+ projectId?: string;environment?: Environment;+ /** Agent id. */agent?: string;+ /** Same filter as `agent`. */+ agentId?: string;status?: SessionStatus;+ deploymentId?: string;+ /** The exact `externalReference` the session was created with. */+ externalReference?: string;+ /** RFC 3339 timestamp; sessions created at or after it. */+ createdAfter?: string;+ /** RFC 3339 timestamp; sessions created strictly before it. */+ createdBefore?: string;+ /** RFC 3339 timestamp; sessions last updated at or after it. */+ updatedAfter?: string;/** Up to three equality filters, sent as `label.<key>=<value>`. */labels?: SessionLabels;+}++/** Filters and paging for `GET /sessions`. */+export interface ListSessionsQuery extends SessionFilters {+ /** `nextCursor` of the previous page; valid only with the same filters. */cursor?: string;- /** Default 50, at most 100. */+ /** Page size: default 50, at most 100. */limit?: number;}diff --git a/sdks/typescript/src/version.ts b/sdks/typescript/src/version.tsindex 01a7ba35..d1be6181 100644--- a/sdks/typescript/src/version.ts+++ b/sdks/typescript/src/version.ts@@ -27,7 +27,7 @@ export const SDK_VERSION_HEADER = "x-oc-sdk-version";* only failure mode that matters — a stale constant here would silently route a* v2 caller to the old runtime.*/-export const SDK_VERSION = "2.1.2";+export const SDK_VERSION = "2.2.0";/** The identifying header, as a spreadable object. */export function sdkVersionHeaders(): Record<string, string> {diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex 7383379c..b3cf90e6 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -1,6 +1,10 @@import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'import { useChat } from '@ai-sdk/react'-import { useQuery, useQueryClient } from '@tanstack/react-query'+import {+ useInfiniteQuery,+ useQuery,+ useQueryClient,+} from '@tanstack/react-query'import { isDynamicToolUIPart, type DynamicToolUIPart, type UIMessage } from 'ai'import {Link,@@ -30,6 +34,7 @@ import {Panel,PanelContent,PanelDescription,+ PanelFooter,PanelHeader,PanelTitle,} from '@/components/panel'@@ -55,6 +60,7 @@ import {getManagedAgentSessionEvents,getManagedAgents,getManagedAgentSessions,+ getManagedAgentSessionsPage,type ManagedAgentEvent,type ManagedAgentInputMode,type ManagedAgentSession,@@ -695,12 +701,50 @@ export default function ManagedAgentDetail({queryFn: () => getManagedAgentSessions(agentId),refetchInterval: 5_000,})- const projectSessions = useQuery({+ // The loaded pages re-walk from the newest cursor so the chain stays+ // contiguous and every loaded row refreshes, at an interval that grows with+ // the page count so polling stays at roughly one request per five seconds.+ // Once more than one page is open, a separate newest-page poll keeps the+ // head of the list at the five-second cadence.+ const projectSessions = useInfiniteQuery({queryKey: ['managed-agent-sessions', 'project', projectId],- queryFn: () => getManagedAgentSessions(undefined, { projectId }),+ initialPageParam: undefined as string | undefined,+ queryFn: ({ pageParam }) =>+ getManagedAgentSessionsPage({+ projectId,+ ...(pageParam ? { cursor: pageParam } : {}),+ }),+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,enabled: Boolean(projectId),+ refetchInterval: (query) =>+ 5_000 * Math.max(1, query.state.data?.pages.length ?? 1),+ })+ const projectSessionPageCount = projectSessions.data?.pages.length ?? 0+ const newestProjectSessions = useQuery({+ queryKey: ['managed-agent-sessions', 'project', projectId, 'newest'],+ queryFn: () => getManagedAgentSessionsPage({ projectId }),+ enabled: Boolean(projectId) && projectSessionPageCount > 1,refetchInterval: 5_000,})+ const projectSessionRows = useMemo(() => {+ const seen = new Set<string>()+ const rows: ManagedAgentSessionSummary[] = []+ for (const session of [+ ...(newestProjectSessions.data?.sessions ?? []),+ ...(projectSessions.data?.pages.flatMap((page) => page.sessions) ?? []),+ ]) {+ if (seen.has(session.id)) continue+ seen.add(session.id)+ rows.push(session)+ }+ return rows+ }, [newestProjectSessions.data, projectSessions.data])+ const loadMoreProjectSessions = async () => {+ const result = await projectSessions.fetchNextPage()+ if (result.isError) {+ notifyError("Couldn't load more sessions.", result.error)+ }+ }const environmentSessions = project? sessionsForEnvironment(sessions.data ?? [],@@ -715,7 +759,7 @@ export default function ManagedAgentDetail({const externalSessions = (project? sessionsForEnvironment(- projectSessions.data ?? [],+ projectSessionRows,project.deployments,sessionsAgentFilter,environment,@@ -1245,6 +1289,21 @@ export default function ManagedAgentDetail({/>}/>+ {project && projectSessions.hasNextPage ? (+ <PanelFooter>+ <Button+ size="sm"+ variant="outline"+ disabled={projectSessions.isFetchingNextPage}+ onClick={() => void loadMoreProjectSessions()}+ >+ {projectSessions.isFetchingNextPage ? (+ <Loader2 className="animate-spin" />+ ) : null}+ Load more+ </Button>+ </PanelFooter>+ ) : null}</Panel>) : null}diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex 47a1cb1d..3ea92de4 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -1597,22 +1597,33 @@ export async function getManagedAgentDeployments(agentId: string) {}/**- * The newest page of session rows, filtered by the API rather than here.- * Rows are ordered by creation time; one page of a hundred is what the- * agent view shows.+ * One page of session rows, newest first, filtered by the API rather than+ * here. `nextCursor` is null on the last page; pass it back as `cursor` to+ * continue with the same filters.*/-export async function getManagedAgentSessions(- agentId?: string,- options: { projectId?: string } = {},+export function getManagedAgentSessionsPage(+ options: { agentId?: string; projectId?: string; cursor?: string } = {},) {const query = new URLSearchParams({ limit: '100' })- if (agentId) query.set('agent', agentId)+ if (options.agentId) query.set('agent', options.agentId)if (options.projectId) query.set('project', options.projectId)- const { sessions } = await apiFetch(+ if (options.cursor) query.set('cursor', options.cursor)+ return apiFetch(`/managed-agents/sessions?${query.toString()}`,undefined,sessionsResponseSchema,)+}++/** The newest page of session rows; what the single-agent view shows. */+export async function getManagedAgentSessions(+ agentId?: string,+ options: { projectId?: string } = {},+) {+ const { sessions } = await getManagedAgentSessionsPage({+ agentId,+ projectId: options.projectId,+ })return sessions}