An open-source, faster Devin alternative
TypeScript
SDK: check every response against its documented shape
Igor Zalutskic4ed7f39bbd6
diff --git a/docs/reference/typescript-sdk/managed-agents.mdx b/docs/reference/typescript-sdk/managed-agents.mdxindex 75e7275f..7ccf5bba 100644--- a/docs/reference/typescript-sdk/managed-agents.mdx+++ b/docs/reference/typescript-sdk/managed-agents.mdx@@ -70,6 +70,23 @@ to no other origin: a redirect answer fails the call with code `redirected`and the redirect's status, and nothing is sent to the address it named.Check `baseUrl` when you see it.+Two codes come from the client rather than the API:++| `code` | Meaning |+| --- | --- |+| `redirected` | The call was answered with a redirect; the client never follows one with the API key. `status` is the redirect's status. |+| `invalid_response` | The call succeeded but its body is not JSON or does not match the documented shape of the route. `status` is the HTTP status; the message names the route and the first field that did not match. |++## Validation++Every response is checked against the documented shape of its route before+the method returns: the fields the [API reference](/agents/api) lists, with+their types. A field the documentation does not list passes through as it+came, so an addition to the API never fails a call. Application data, that+is a session's `result.data`, a turn's `payload`, and a tool call's `input`+and `output`, is checked only as a JSON value; what it contains is yours to+validate.+## Sessions| Method | Route | Returns |diff --git a/sdks/typescript/src/managed-agents/client.test.ts b/sdks/typescript/src/managed-agents/client.test.tsindex b263fadf..d7320a43 100644--- a/sdks/typescript/src/managed-agents/client.test.ts+++ b/sdks/typescript/src/managed-agents/client.test.ts@@ -74,7 +74,12 @@ describe("OpenComputer client", () => {});it("lists sessions with filters, label filters and paging, and normalizes a missing cursor", async () => {- const rows = [{ id: "ses_2" }, { id: "ses_1" }];+ const row = (id: string) => ({+ id, projectId: "prj_1", agentId: "worker", deploymentId: "dep_1", environment: null, source: "api", status: "idle",+ labels: {}, createdAt: "t", updatedAt: "t", revision: 1,+ activity: { activeTurnId: null, queued: 0, lastSettledTurn: null }, result: null,+ });+ const rows = [row("ses_2"), row("ses_1")];let withCursor = true;const api = fakeApi({"GET /api/managed-agents/sessions": () => Response.json(withCursor ? { sessions: rows, nextCursor: "c2" } : { sessions: rows }),@@ -120,7 +125,7 @@ describe("OpenComputer client", () => {});it("reads the event log from a cursor", async () => {- const events = [{ id: "e1", seq: 1, type: "session.created", data: {} }];+ const events = [{ id: "e1", seq: 1, timestamp: "t", sessionId: "ses_1", type: "session.created", data: { agentId: "worker", deploymentId: "dep_1" } }];const api = fakeApi({ "GET /api/managed-agents/sessions/ses_1/events": () => Response.json({ events }) });expect(await oc(api).sessions.events.list("ses_1", { after: 7 })).toEqual(events);expect(api.last().path).toBe("/api/managed-agents/sessions/ses_1/events?after=7");@@ -244,6 +249,33 @@ describe("OpenComputer client", () => {});});+ it("fails a success whose body is not JSON or not the documented shape with invalid_response, and passes unknown fields through", async () => {+ const session = { id: "ses_1", agentId: "worker", deploymentId: "dep_1", status: "idle", source: "api", turns: [], createdAt: "t", updatedAt: "t" };+ const api = fakeApi({+ "GET /api/managed-agents/sessions/text": () => new Response("ok", { status: 200, headers: { "content-type": "text/plain" } }),+ "GET /api/managed-agents/sessions/shape": () => Response.json({ ...session, turns: "none" }),+ "GET /api/managed-agents/sessions/extra": () => Response.json({ ...session, nextThing: { added: true } }),+ });+ const client = oc(api);+ // A 200 with a text body is not a session; before validation it came back typed as one.+ const text = await client.sessions.get("text").catch((cause: unknown) => cause);+ expect(text).toBeInstanceOf(OpenComputerError);+ expect(text).toMatchObject({ code: "invalid_response", status: 200 });+ expect((text as Error).message).toMatch(/GET \/sessions\/text/);+ const shape = await client.sessions.get("shape").catch((cause: unknown) => cause);+ expect(shape).toMatchObject({ code: "invalid_response", status: 200 });+ expect((shape as Error).message).toMatch(/turns/);+ expect(await client.sessions.get("extra")).toEqual({ ...session, nextThing: { added: true } });+ });++ it("accepts every persisted turn status on an admission receipt", async () => {+ const api = fakeApi({+ "POST /api/managed-agents/sessions/ses_1/turns": () => Response.json({ turnId: "turn_1", status: "completed", duplicate: true }),+ });+ const receipt = await oc(api).sessions.turns.send("ses_1", { input: "again", idempotencyKey: "task_1/start" });+ expect(receipt).toMatchObject({ turnId: "turn_1", duplicate: true });+ });+it("honours a custom base URL and requires a key", () => {const api = fakeApi();const client = new OpenComputer({ apiKey: "k", baseUrl: "https://edge.example.test/mgmt/", fetch: api.fetch });diff --git a/sdks/typescript/src/managed-agents/client.ts b/sdks/typescript/src/managed-agents/client.tsindex a1830f66..1a16b67a 100644--- a/sdks/typescript/src/managed-agents/client.ts+++ b/sdks/typescript/src/managed-agents/client.ts@@ -1,8 +1,11 @@// The management client: one class per API section, each method one route// of docs/agents/api.mdx. Server-side only; the API key reaches every-// project, agent and session of the organization.+// project, agent and session of the organization. Every call names the+// documented shape of its answer (shapes.ts); the transport checks the body+// against it before the method returns.import { Http, type HttpOptions, segment } from "./http.js";+import * as shapes from "./shapes.js";import {startOnDocument,type StartOnDocumentParams,@@ -89,11 +92,10 @@ export class Turns {if (params.idempotencyKey !== undefined) body.idempotencyKey = params.idempotencyKey;if (params.mode !== undefined) body.mode = params.mode;if (params.payload !== undefined) body.payload = params.payload;- const answer = await this.http.send<{ turnId: string; status: string; duplicate?: boolean }>(- "POST",- `/sessions/${segment(sessionId)}/turns`,- { body, signal: options.signal },- );+ const answer = await this.http.send("POST", `/sessions/${segment(sessionId)}/turns`, shapes.turnReceipt, {+ body,+ signal: options.signal,+ });return {turnId: answer.body.turnId,status: answer.body.status === "running" ? "running" : "queued",@@ -110,7 +112,7 @@ export class Events {* `seq`, ascending. Repeat from the last `seq` until a page is empty.*/async list(sessionId: string, query: ListEventsQuery = {}, options: CallOptions = {}): Promise<SessionEvent[]> {- const page = await this.http.request<{ events: SessionEvent[] }>("GET", `/sessions/${segment(sessionId)}/events`, {+ const page = await this.http.request("GET", `/sessions/${segment(sessionId)}/events`, shapes.eventsPage, {query: { after: query.after ?? 0 },signal: options.signal,});@@ -129,21 +131,17 @@ export class Sessions {/** `POST /sessions`: creates a session without a turn. `created` is false when the key had already created it. */async create(params: CreateSessionParams, options: CreateSessionOptions = {}): Promise<SessionCreated> {- const answer = await this.http.send<{ session: SessionCreated["session"]; deployment?: Deployment }>(- "POST",- "/sessions",- {- body: params,- headers: options.idempotencyKey !== undefined ? { "idempotency-key": options.idempotencyKey } : undefined,- signal: options.signal,- },- );+ const answer = await this.http.send("POST", "/sessions", shapes.sessionCreated, {+ body: params,+ headers: options.idempotencyKey !== undefined ? { "idempotency-key": options.idempotencyKey } : undefined,+ signal: options.signal,+ });return { session: answer.body.session, deployment: answer.body.deployment, created: answer.status === 201 };}/** `GET /sessions/<id>`. */get(sessionId: string, options: CallOptions = {}): Promise<Session> {- return this.http.request<Session>("GET", `/sessions/${segment(sessionId)}`, { signal: options.signal });+ return this.http.request("GET", `/sessions/${segment(sessionId)}`, shapes.session, { signal: options.signal });}/**@@ -151,31 +149,28 @@ export class Sessions {* `nextCursor` for the next page. Sort the pages you hold by `updatedAt`* for recent activity first.*/- async list(query: ListSessionsQuery = {}, options: CallOptions = {}): Promise<SessionPage> {+ list(query: ListSessionsQuery = {}, options: CallOptions = {}): Promise<SessionPage> {const { labels, ...rest } = query;const q: Record<string, string | number | undefined> = { ...rest };for (const [key, value] of Object.entries(labels ?? {})) q[`label.${key}`] = value;- const page = await this.http.request<{ sessions: SessionPage["sessions"]; nextCursor?: string | null }>(- "GET",- "/sessions",- { query: q, signal: options.signal },- );- return { sessions: page.sessions, nextCursor: page.nextCursor ?? null };+ return this.http.request("GET", "/sessions", shapes.sessionPage, { query: q, signal: options.signal });}/** `POST /sessions/<id>/end`: cancels queued and running turns and revokes memory writes. */end(sessionId: string, options: CallOptions = {}): Promise<Session> {- return this.http.request<Session>("POST", `/sessions/${segment(sessionId)}/end`, { signal: options.signal });+ return this.http.request("POST", `/sessions/${segment(sessionId)}/end`, shapes.session, { signal: options.signal });}/** `POST /sessions/<id>/interrupt`: stops the running turn; the next queued turn starts. */interrupt(sessionId: string, options: CallOptions = {}): Promise<Session> {- return this.http.request<Session>("POST", `/sessions/${segment(sessionId)}/interrupt`, { signal: options.signal });+ return this.http.request("POST", `/sessions/${segment(sessionId)}/interrupt`, shapes.session, {+ signal: options.signal,+ });}/** `PATCH /sessions/<id>/labels`: per-key last-write-wins (per design 1c07584, backend in flight). */setLabels(sessionId: string, params: SetLabelsParams, options: CallOptions = {}): Promise<Session> {- return this.http.request<Session>("PATCH", `/sessions/${segment(sessionId)}/labels`, {+ return this.http.request("PATCH", `/sessions/${segment(sessionId)}/labels`, shapes.session, {body: params,signal: options.signal,});@@ -199,7 +194,7 @@ export class MemoryDocuments {/** `GET .../documents`: metadata without `text`; follow `nextCursor`. */list(projectId: string, resource: string, options: ListDocumentsOptions): Promise<MemoryDocumentPage> {- return this.http.request<MemoryDocumentPage>("GET", this.path(projectId, resource), {+ return this.http.request("GET", this.path(projectId, resource), shapes.memoryDocumentPage, {query: { environment: options.environment, cursor: options.cursor },signal: options.signal,});@@ -207,7 +202,7 @@ export class MemoryDocuments {/** `GET .../documents/<id>`. */get(projectId: string, resource: string, documentId: string, options: EnvironmentOptions): Promise<MemoryDocument> {- return this.http.request<MemoryDocument>("GET", this.path(projectId, resource, documentId), {+ return this.http.request("GET", this.path(projectId, resource, documentId), shapes.memoryDocument, {query: { environment: options.environment },signal: options.signal,});@@ -221,7 +216,7 @@ export class MemoryDocuments {body: CreateMemoryDocumentBody,options: EnvironmentOptions,): Promise<MemoryDocument> {- return this.http.request<MemoryDocument>("PUT", this.path(projectId, resource, documentId), {+ return this.http.request("PUT", this.path(projectId, resource, documentId), shapes.memoryDocument, {query: { environment: options.environment },headers: { "if-none-match": "*" },body,@@ -237,7 +232,7 @@ export class MemoryDocuments {body: ReplaceMemoryDocumentBody,options: DocumentWriteOptions,): Promise<MemoryDocument> {- return this.http.request<MemoryDocument>("PUT", this.path(projectId, resource, documentId), {+ return this.http.request("PUT", this.path(projectId, resource, documentId), shapes.memoryDocument, {query: { environment: options.environment },headers: { "if-match": quote(options.revision) },body,@@ -253,7 +248,7 @@ export class MemoryDocuments {body: PatchMemoryDocumentBody,options: DocumentWriteOptions,): Promise<MemoryDocument> {- return this.http.request<MemoryDocument>("PATCH", this.path(projectId, resource, documentId), {+ return this.http.request("PATCH", this.path(projectId, resource, documentId), shapes.memoryDocument, {query: { environment: options.environment },headers: { "if-match": quote(options.revision) },body,@@ -263,7 +258,7 @@ export class MemoryDocuments {/** `DELETE .../documents/<id>` with `If-Match`. The id stays reserved. */async delete(projectId: string, resource: string, documentId: string, options: DocumentWriteOptions): Promise<void> {- await this.http.request<void>("DELETE", this.path(projectId, resource, documentId), {+ await this.http.request("DELETE", this.path(projectId, resource, documentId), shapes.none, {query: { environment: options.environment },headers: { "if-match": quote(options.revision) },signal: options.signal,@@ -279,8 +274,8 @@ export class Memory {}/** `GET /projects/<p>/memory`: the environment's resource inventory. */- async resources(projectId: string, options: EnvironmentOptions): Promise<MemoryResourceInventory> {- return this.http.request<MemoryResourceInventory>("GET", `/projects/${segment(projectId)}/memory`, {+ resources(projectId: string, options: EnvironmentOptions): Promise<MemoryResourceInventory> {+ return this.http.request("GET", `/projects/${segment(projectId)}/memory`, shapes.memoryResourceInventory, {query: { environment: options.environment },signal: options.signal,});@@ -297,7 +292,7 @@ export class Webhooks {/** `GET /projects/<p>/webhooks`: URLs without tokens. */async list(projectId: string, query: ListWebhooksQuery = {}, options: CallOptions = {}): Promise<Webhook[]> {- const page = await this.http.request<{ webhooks: Webhook[] }>("GET", this.path(projectId), {+ const page = await this.http.request("GET", this.path(projectId), shapes.webhooksPage, {query: { ...query },signal: options.signal,});@@ -306,7 +301,7 @@ export class Webhooks {/** `POST /projects/<p>/webhooks`: `token` and the full `invocationUrl` appear once. */async create(projectId: string, params: CreateWebhookParams, options: CallOptions = {}): Promise<Webhook> {- const answer = await this.http.request<{ webhook: Webhook }>("POST", this.path(projectId), {+ const answer = await this.http.request("POST", this.path(projectId), shapes.webhookEnvelope, {body: params,signal: options.signal,});@@ -320,7 +315,7 @@ export class Webhooks {params: UpdateWebhookParams,options: CallOptions = {},): Promise<Webhook> {- const answer = await this.http.request<{ webhook: Webhook }>("PATCH", this.path(projectId, webhookId), {+ const answer = await this.http.request("PATCH", this.path(projectId, webhookId), shapes.webhookEnvelope, {body: params,signal: options.signal,});@@ -329,9 +324,10 @@ export class Webhooks {/** `POST /projects/<p>/webhooks/<id>/rotate-token`: the webhook with its new token. */async rotateToken(projectId: string, webhookId: string, options: CallOptions = {}): Promise<Webhook> {- const answer = await this.http.request<{ webhook: Webhook }>(+ const answer = await this.http.request("POST",`${this.path(projectId, webhookId)}/rotate-token`,+ shapes.webhookEnvelope,{ signal: options.signal },);return answer.webhook;@@ -339,14 +335,15 @@ export class Webhooks {/** `DELETE /projects/<p>/webhooks/<id>`. */async delete(projectId: string, webhookId: string, options: CallOptions = {}): Promise<void> {- await this.http.request<void>("DELETE", this.path(projectId, webhookId), { signal: options.signal });+ await this.http.request("DELETE", this.path(projectId, webhookId), shapes.none, { signal: options.signal });}/** `GET /projects/<p>/webhooks/<id>/requests`: the request ledger. */async requests(projectId: string, webhookId: string, options: CallOptions = {}): Promise<WebhookRequest[]> {- const page = await this.http.request<{ requests: WebhookRequest[] }>(+ const page = await this.http.request("GET",`${this.path(projectId, webhookId)}/requests`,+ shapes.webhookRequestsPage,{ signal: options.signal },);return page.requests;@@ -367,7 +364,7 @@ export class EventSubscriptions {params: CreateEventSubscriptionBody,options: CallOptions = {},): Promise<EventSubscription> {- const answer = await this.http.request<{ subscription: EventSubscription }>("POST", this.path(projectId), {+ const answer = await this.http.request("POST", this.path(projectId), shapes.eventSubscriptionEnvelope, {body: params,signal: options.signal,});@@ -376,7 +373,7 @@ export class EventSubscriptions {/** `GET /projects/<p>/event-subscriptions`. */async list(projectId: string, options: CallOptions = {}): Promise<EventSubscription[]> {- const page = await this.http.request<{ subscriptions: EventSubscription[] }>("GET", this.path(projectId), {+ const page = await this.http.request("GET", this.path(projectId), shapes.eventSubscriptionsPage, {signal: options.signal,});return page.subscriptions;@@ -384,9 +381,10 @@ export class EventSubscriptions {/** `GET /projects/<p>/event-subscriptions/<id>`. */async get(projectId: string, subscriptionId: string, options: CallOptions = {}): Promise<EventSubscription> {- const answer = await this.http.request<{ subscription: EventSubscription }>(+ const answer = await this.http.request("GET",this.path(projectId, subscriptionId),+ shapes.eventSubscriptionEnvelope,{ signal: options.signal },);return answer.subscription;@@ -394,7 +392,7 @@ export class EventSubscriptions {/** `DELETE /projects/<p>/event-subscriptions/<id>`: pending deliveries stop. */async delete(projectId: string, subscriptionId: string, options: CallOptions = {}): Promise<void> {- await this.http.request<void>("DELETE", this.path(projectId, subscriptionId), { signal: options.signal });+ await this.http.request("DELETE", this.path(projectId, subscriptionId), shapes.none, { signal: options.signal });}}@@ -407,13 +405,13 @@ export class GitHub {* backend in flight). `404 github_connection_not_found` without an* installation; `502 github_unavailable` when GitHub fails.*/- async repositories(projectId: string, query: ListRepositoriesQuery, options: CallOptions = {}): Promise<RepositoryPage> {- const page = await this.http.request<{ repositories: RepositoryPage["repositories"]; nextCursor?: string | null }>(+ repositories(projectId: string, query: ListRepositoriesQuery, options: CallOptions = {}): Promise<RepositoryPage> {+ return this.http.request("GET",`/projects/${segment(projectId)}/github/repositories`,+ shapes.repositoryPage,{ query: { ...query }, signal: options.signal },);- return { repositories: page.repositories, nextCursor: page.nextCursor ?? null };}}@@ -432,18 +430,20 @@ export class Projects {/** `GET /projects`. */async list(options: CallOptions = {}): Promise<Project[]> {- const page = await this.http.request<{ projects: Project[] }>("GET", "/projects", { signal: options.signal });+ const page = await this.http.request("GET", "/projects", shapes.projectsPage, { signal: options.signal });return page.projects;}/** `GET /projects/<p>`: the project with its deployments, sessions, connections, channels and schedules. */get(projectId: string, options: CallOptions = {}): Promise<ProjectDetail> {- return this.http.request<ProjectDetail>("GET", `/projects/${segment(projectId)}`, { signal: options.signal });+ return this.http.request("GET", `/projects/${segment(projectId)}`, shapes.projectDetail, {+ signal: options.signal,+ });}/** `POST /projects`. */create(params: CreateProjectParams, options: CallOptions = {}): Promise<Project> {- return this.http.request<Project>("POST", "/projects", { body: params, signal: options.signal });+ return this.http.request("POST", "/projects", shapes.project, { body: params, signal: options.signal });}}@@ -454,7 +454,7 @@ export class Agents {/** `GET /agents`. */async list(options: CallOptions = {}): Promise<AgentSummary[]> {- const page = await this.http.request<{ agents: AgentSummary[] }>("GET", "/agents", { signal: options.signal });+ const page = await this.http.request("GET", "/agents", shapes.agentsPage, { signal: options.signal });return page.agents;}}@@ -464,12 +464,14 @@ export class Deployments {/** `GET /deployments/<id>`. */get(deploymentId: string, options: CallOptions = {}): Promise<Deployment> {- return this.http.request<Deployment>("GET", `/deployments/${segment(deploymentId)}`, { signal: options.signal });+ return this.http.request("GET", `/deployments/${segment(deploymentId)}`, shapes.deployment, {+ signal: options.signal,+ });}/** `GET /deployments?agentId=`. */async list(query: ListDeploymentsQuery, options: CallOptions = {}): Promise<Deployment[]> {- const page = await this.http.request<{ deployments: Deployment[] }>("GET", "/deployments", {+ const page = await this.http.request("GET", "/deployments", shapes.deploymentsPage, {query: { ...query },signal: options.signal,});diff --git a/sdks/typescript/src/managed-agents/http.ts b/sdks/typescript/src/managed-agents/http.tsindex 4c6da8b9..014003ba 100644--- a/sdks/typescript/src/managed-agents/http.ts+++ b/sdks/typescript/src/managed-agents/http.ts@@ -9,8 +9,14 @@// else: fetch runs with `redirect: "manual"`, and a 3xx answer is an error// with code `redirected`, because following it would carry the key to// whatever origin the response names.+//+// Every success is checked against the documented shape of its route+// (shapes.ts) before it is returned: a body that is not JSON, or does not+// have the fields the docs promise, is an error with code `invalid_response`+// rather than a value typed by assumption.import { errorFromResponse, OpenComputerError } from "./errors.js";+import { ShapeError, type Shape } from "./shapes.js";export const DEFAULT_BASE_URL = "https://app.opencomputer.dev/api/managed-agents";@@ -61,8 +67,12 @@ export class Http {return url.toString();}- /** Sends a request and returns the parsed body with the status; throws `OpenComputerError` on a failed status. */- async send<T>(method: string, path: string, options: RequestOptions = {}): Promise<Answer<T>> {+ /**+ * Sends a request and returns the body, checked against `shape`, with the+ * status. Throws `OpenComputerError` on a failed status, on a redirect, and+ * on a success whose body is not JSON or not the documented shape.+ */+ async send<T>(method: string, path: string, shape: Shape<T>, options: RequestOptions = {}): Promise<Answer<T>> {const headers: Record<string, string> = {"x-api-key": this.apiKey,accept: "application/json",@@ -82,14 +92,36 @@ export class Http {"the client does not follow redirects with the API key. Check baseUrl.",);}- const body = await readJson(response);- if (!response.ok) throw errorFromResponse(response.status, body, response.headers);- return { status: response.status, body: body as T, headers: response.headers };+ const text = response.status === 204 ? "" : await response.text();+ if (!response.ok) {+ throw errorFromResponse(response.status, parseJson(text) ?? (text ? { error: text } : undefined), response.headers);+ }+ let body: unknown;+ if (text) {+ body = parseJson(text);+ if (body === undefined) {+ throw new OpenComputerError(+ response.status,+ "invalid_response",+ `${method} ${path} returned a body that is not JSON`,+ );+ }+ }+ try {+ return { status: response.status, body: shape(body, "body"), headers: response.headers };+ } catch (cause) {+ if (!(cause instanceof ShapeError)) throw cause;+ throw new OpenComputerError(+ response.status,+ "invalid_response",+ `${method} ${path} returned a body that is not the documented shape: ${cause.message}`,+ );+ }}/** `send` for callers that need only the body. */- async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {- return (await this.send<T>(method, path, options)).body;+ async request<T>(method: string, path: string, shape: Shape<T>, options: RequestOptions = {}): Promise<T> {+ return (await this.send(method, path, shape, options)).body;}}@@ -102,14 +134,13 @@ function isRedirect(response: Response): boolean {return response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400);}-async function readJson(response: Response): Promise<unknown> {- if (response.status === 204) return undefined;- const text = await response.text();+/** The parsed JSON of a body, or undefined when the text is not JSON. */+function parseJson(text: string): unknown {if (!text) return undefined;try {return JSON.parse(text) as unknown;} catch {- return { error: text };+ return undefined;}}diff --git a/sdks/typescript/src/managed-agents/portability.test.ts b/sdks/typescript/src/managed-agents/portability.test.tsindex e7933985..c513e6f8 100644--- a/sdks/typescript/src/managed-agents/portability.test.ts+++ b/sdks/typescript/src/managed-agents/portability.test.ts@@ -42,6 +42,7 @@ describe("@opencomputer/sdk/managed-agents", () => {"http.ts","index.ts","memory.ts",+ "shapes.ts","start-on-document.ts","types.ts",]);diff --git a/sdks/typescript/src/managed-agents/shapes.ts b/sdks/typescript/src/managed-agents/shapes.tsnew file mode 100644index 00000000..e694283f--- /dev/null+++ b/sdks/typescript/src/managed-agents/shapes.ts@@ -0,0 +1,457 @@+// The documented shapes of the management API, as checks a response body+// passes before it is typed. Hand-written and small on purpose: the subpath+// carries no dependency, and the shapes it needs are a few dozen fields of+// strings, numbers, arrays and objects. A body that does not match fails the+// call with code `invalid_response` (see http.ts) rather than flowing inward+// under a type it does not have.+//+// Unknown fields pass through: the API adds fields, and a client that+// rejected them would break on every addition. Application data — a result's+// `data`, a turn's `payload`, a tool's `input` and `output` — is checked only+// as a JSON value; its content belongs to the application.++import type { EventSubscription, OutcomeEventType, TurnOutcomeDelivery } from "./event-subscriptions.js";+import type {+ MemoryDocument,+ MemoryDocumentMeta,+ MemoryDocumentPage,+ MemoryResourceInventory,+ MemoryWriter,+ SessionMemoryBinding,+} from "./memory.js";+import type {+ AgentSummary,+ DataValue,+ Deployment,+ Environment,+ Project,+ ProjectDetail,+ ProjectEnvironment,+ Repository,+ RepositoryPage,+ Session,+ SessionCreated,+ SessionEvent,+ SessionPage,+ SessionResult,+ SessionStatus,+ SessionSummary,+ Turn,+ TurnStatus,+ Webhook,+ WebhookRequest,+} from "./types.js";++/** Checks `value` at `path` and returns it typed, or throws a `ShapeError`. */+export type Shape<T> = (value: unknown, path: string) => T;++/** Where a body stopped matching its documented shape, and what was expected there. */+export class ShapeError extends Error {+ constructor(+ readonly path: string,+ readonly expected: string,+ ) {+ super(`${path}: expected ${expected}`);+ this.name = "ShapeError";+ }+}++const at = (path: string, key: string | number): string =>+ typeof key === "number" ? `${path}[${String(key)}]` : path === "body" ? key : `${path}.${key}`;++export const string: Shape<string> = (value, path) => {+ if (typeof value !== "string") throw new ShapeError(path, "a string");+ return value;+};++export const nonEmptyString: Shape<string> = (value, path) => {+ if (typeof value !== "string" || !value) throw new ShapeError(path, "a non-empty string");+ return value;+};++export const number: Shape<number> = (value, path) => {+ if (typeof value !== "number" || !Number.isFinite(value)) throw new ShapeError(path, "a number");+ return value;+};++export const boolean: Shape<boolean> = (value, path) => {+ if (typeof value !== "boolean") throw new ShapeError(path, "a boolean");+ return value;+};++/**+ * A string whose documented values form an open set (session and turn+ * statuses, sources, failure codes): checked as a non-empty string, typed+ * as the union the docs list today, so a value the API adds later reaches+ * the caller as itself instead of failing the call.+ */+export const stringAs = <T extends string>(): Shape<T> => nonEmptyString as Shape<T>;++/** A string from a closed set of documented values. */+export function oneOf<T extends string>(...values: readonly T[]): Shape<T> {+ return (value, path) => {+ if (typeof value !== "string" || !(values as readonly string[]).includes(value)) {+ throw new ShapeError(path, `one of ${values.map((v) => JSON.stringify(v)).join(", ")}`);+ }+ return value as T;+ };+}++export function optional<T>(shape: Shape<T>): Shape<T | undefined> {+ return (value, path) => (value === undefined ? undefined : shape(value, path));+}++export function nullable<T>(shape: Shape<T>): Shape<T | null> {+ return (value, path) => (value === null ? null : shape(value, path));+}++export function array<T>(item: Shape<T>): Shape<T[]> {+ return (value, path) => {+ if (!Array.isArray(value)) throw new ShapeError(path, "an array");+ return value.map((entry, index) => item(entry, at(path, index)));+ };+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null && !Array.isArray(value);++/** Any object; its fields are not looked at. */+export const anyRecord: Shape<Record<string, unknown>> = (value, path) => {+ if (!isRecord(value)) throw new ShapeError(path, "an object");+ return value;+};++/** An object whose values all match `item`, keyed by strings. */+export function record<T>(item: Shape<T>): Shape<Record<string, T>> {+ return (value, path) => {+ if (!isRecord(value)) throw new ShapeError(path, "an object");+ const result: Record<string, T> = {};+ for (const [key, entry] of Object.entries(value)) result[key] = item(entry, at(path, key));+ return result;+ };+}++type Fields = Record<string, Shape<unknown>>;+type Inferred<F extends Fields> = { [K in keyof F]: F[K] extends Shape<infer T> ? T : never };++/**+ * An object with the named fields checked and every other field passed+ * through as it came. A field whose shape is `optional(...)` may be absent.+ */+export function object<F extends Fields>(fields: F): Shape<Inferred<F>> {+ return (value, path) => {+ if (!isRecord(value)) throw new ShapeError(path, "an object");+ const result: Record<string, unknown> = { ...value };+ for (const [key, shape] of Object.entries(fields)) {+ const checked = shape(value[key], at(path, key));+ if (checked === undefined) delete result[key];+ else result[key] = checked;+ }+ return result as Inferred<F>;+ };+}++/** A JSON value: strings, numbers, booleans, null, arrays and objects of the same. Application data is checked as this and nothing more. */+export const jsonValue: Shape<DataValue> = (value, path) => {+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;+ if (typeof value === "number") {+ if (!Number.isFinite(value)) throw new ShapeError(path, "a JSON value");+ return value;+ }+ if (Array.isArray(value)) return value.map((entry, index) => jsonValue(entry, at(path, index)));+ if (isRecord(value)) {+ const result: Record<string, DataValue> = {};+ for (const [key, entry] of Object.entries(value)) result[key] = jsonValue(entry, at(path, key));+ return result;+ }+ throw new ShapeError(path, "a JSON value");+};++/** A `204` or an empty body. */+export const none: Shape<void> = (value, path) => {+ if (value !== undefined) throw new ShapeError(path, "no body");+};++// ── Sessions ──────────────────────────────────────────────────────────────────++export const environment: Shape<Environment> = oneOf("development", "production");++const labels = record(string);++export const sessionResult: Shape<SessionResult> = object({+ turnId: string,+ callId: string,+ reportedAt: string,+ data: jsonValue,+});++const outcomeEventType: Shape<OutcomeEventType> = oneOf("turn.completed", "turn.failed", "turn.cancelled");++const sessionDestination = object({ type: oneOf("session"), sessionId: string });++const turnOutcomeDelivery: Shape<TurnOutcomeDelivery> = object({+ id: string,+ subscriptionId: string,+ eventId: string,+ eventType: outcomeEventType,+ destination: sessionDestination,+ status: oneOf("pending", "delivered", "failed"),+ attempt: number,+ receipt: optional(object({ sessionId: string, turnId: string })),+ nextAttemptAt: optional(string),+ error: optional(oneOf("subscription_unavailable", "target_missing", "target_ended", "delivery_failed")),+ updatedAt: string,+});++export const turn: Shape<Turn> = object({+ id: string,+ input: string,+ mode: oneOf("queue", "steer", "interrupt"),+ status: stringAs<TurnStatus>(),+ payload: optional(jsonValue),+ deliveries: optional(array(turnOutcomeDelivery)),+ createdAt: string,+ updatedAt: string,+});++const sessionMemoryBinding: Shape<SessionMemoryBinding> = (value, path) => {+ const binding = object({+ resource: string,+ scope: oneOf("document", "collection"),+ id: optional(string),+ access: oneOf("read", "read-write"),+ writable: boolean,+ })(value, path);+ if (binding.scope === "document") {+ if (binding.id === undefined) throw new ShapeError(at(path, "id"), "a string");+ return { ...binding, scope: "document", id: binding.id };+ }+ if (binding.access !== "read") throw new ShapeError(at(path, "access"), '"read"');+ return { resource: binding.resource, scope: "collection", access: "read", writable: binding.writable };+};++export const session: Shape<Session> = object({+ id: string,+ agentId: string,+ deploymentId: string,+ environment: optional(environment),+ status: stringAs<SessionStatus>(),+ source: optional(string),+ executionMode: optional(string),+ memory: optional(array(sessionMemoryBinding)),+ turns: array(turn),+ labels: optional(labels),+ labelsUpdatedAt: optional(string),+ revision: optional(number),+ result: optional(nullable(sessionResult)),+ createdAt: string,+ updatedAt: string,+}) as Shape<Session>;++export const sessionCreated: Shape<Omit<SessionCreated, "created">> = object({+ session: object({+ id: string,+ status: stringAs<SessionStatus>(),+ createdAt: string,+ executionMode: optional(string),+ }),+ deployment: optional((value, path) => deployment(value, path)),+});++export const sessionSummary: Shape<SessionSummary> = object({+ id: string,+ projectId: optional(string),+ agentId: string,+ deploymentId: string,+ environment: optional(nullable(environment)),+ source: optional(string),+ status: stringAs<SessionStatus>(),+ labels: optional(labels),+ createdAt: string,+ updatedAt: string,+ revision: optional(number),+ activity: optional(+ object({+ activeTurnId: nullable(string),+ queued: number,+ lastSettledTurn: nullable(object({ id: string, status: stringAs<TurnStatus>(), at: string })),+ }),+ ),+ result: optional(nullable(sessionResult)),+}) as Shape<SessionSummary>;++export const sessionPage: Shape<SessionPage> = (value, path) => {+ const page = object({ sessions: array(sessionSummary), nextCursor: optional(nullable(string)) })(value, path);+ return { sessions: page.sessions, nextCursor: page.nextCursor ?? null };+};++export const turnReceipt = object({+ turnId: string,+ status: nonEmptyString,+ duplicate: optional(boolean),+});++/**+ * One log entry. `seq`, `type` and `data` are what a reader keys on and are+ * required; the identity fields are checked when present.+ */+export const sessionEvent: Shape<SessionEvent> = object({+ id: optional(string),+ seq: number,+ timestamp: optional(string),+ sessionId: optional(string),+ turnId: optional(string),+ type: string,+ data: anyRecord,+}) as unknown as Shape<SessionEvent>;++export const eventsPage = object({ events: array(sessionEvent) });++// ── Projects, agents and deployments ──────────────────────────────────────────++const projectEnvironment: Shape<ProjectEnvironment> = object({+ name: environment,+ agentId: optional(string),+ activeDeploymentId: optional(string),+ updatedAt: optional(string),+});++export const project: Shape<Project> = object({+ id: string,+ slug: string,+ name: string,+ environments: array(projectEnvironment),+ agents: array(object({ id: string, name: string })),+ createdAt: string,+ updatedAt: string,+});++export const projectsPage = object({ projects: array(project) });++export const deployment: Shape<Deployment> = object({+ id: string,+ agentId: string,+ alias: string,+ memory: optional(array(object({ id: string, description: optional(string), provider: object({ kind: string }) }))),+ createdAt: string,+});++export const deploymentsPage = object({ deployments: array(deployment) });++export const projectDetail: Shape<ProjectDetail> = object({+ project,+ deployments: array(deployment),+ sessions: array(sessionSummary),+ connections: array(jsonValue),+ channels: array(jsonValue),+ schedules: array(jsonValue),+});++export const agentSummary: Shape<AgentSummary> = object({+ id: string,+ name: string,+ activeAlias: optional(string),+ activeDeploymentId: optional(string),+ deploymentCount: optional(number),+ createdAt: optional(string),+ updatedAt: optional(string),+});++export const agentsPage = object({ agents: array(agentSummary) });++// ── Webhooks and event subscriptions ──────────────────────────────────────────++export const webhook: Shape<Webhook> = object({+ id: string,+ projectId: string,+ environment,+ agentId: string,+ name: string,+ enabled: boolean,+ identity: optional(string),+ invocationUrl: optional(string),+ token: optional(string),+ createdAt: string,+ updatedAt: string,+ lastInvokedAt: optional(string),+}) as Shape<Webhook>;++export const webhooksPage = object({ webhooks: array(webhook) });+export const webhookEnvelope = object({ webhook });++export const webhookRequest: Shape<WebhookRequest> = anyRecord;+export const webhookRequestsPage = object({ requests: array(webhookRequest) });++export const eventSubscription: Shape<EventSubscription> = object({+ id: string,+ projectId: string,+ agentId: optional(string),+ environment: optional(environment),+ events: array(outcomeEventType),+ destination: sessionDestination,+ createdAt: string,+});++export const eventSubscriptionsPage = object({ subscriptions: array(eventSubscription) });+export const eventSubscriptionEnvelope = object({ subscription: eventSubscription });++// ── Memory ────────────────────────────────────────────────────────────────────++const memoryWriter: Shape<MemoryWriter> = (value, path) => {+ const writer = object({ kind: oneOf("owner", "agent"), sessionId: optional(string) })(value, path);+ if (writer.kind === "owner") return { kind: "owner" };+ if (writer.sessionId === undefined) throw new ShapeError(at(path, "sessionId"), "a string");+ return { kind: "agent", sessionId: writer.sessionId };+};++const memoryDocumentFields = {+ id: string,+ title: string,+ summary: string,+ agentWrites: oneOf("enabled", "disabled"),+ revision: string,+ bytes: number,+ maxBytes: number,+ updatedAt: string,+ writer: memoryWriter,+};++export const memoryDocumentMeta: Shape<MemoryDocumentMeta> = object(memoryDocumentFields);++export const memoryDocument: Shape<MemoryDocument> = object({ ...memoryDocumentFields, text: string });++export const memoryDocumentPage: Shape<MemoryDocumentPage> = (value, path) => {+ const page = object({ documents: array(memoryDocumentMeta), nextCursor: optional(nullable(string)) })(value, path);+ return { ...page, nextCursor: page.nextCursor ?? null };+};++export const memoryResourceInventory: Shape<MemoryResourceInventory> = object({+ resources: array(+ object({+ id: string,+ provider: object({ kind: string, maxBytes: optional(number) }),+ declared: boolean,+ documents: number,+ }),+ ),+});++// ── GitHub repositories ───────────────────────────────────────────────────────++const numberOrString: Shape<number | string> = (value, path) => {+ if (typeof value === "number" || typeof value === "string") return value;+ throw new ShapeError(path, "a number or a string");+};++export const repository: Shape<Repository> = object({+ id: numberOrString,+ fullName: string,+ private: boolean,+ defaultBranch: string,+ archived: boolean,+});++export const repositoryPage: Shape<RepositoryPage> = (value, path) => {+ const page = object({ repositories: array(repository), nextCursor: optional(nullable(string)) })(value, path);+ return { repositories: page.repositories, nextCursor: page.nextCursor ?? null };+};diff --git a/sdks/typescript/src/managed-agents/start-on-document.test.ts b/sdks/typescript/src/managed-agents/start-on-document.test.tsindex 71c4b736..b3ef4bd8 100644--- a/sdks/typescript/src/managed-agents/start-on-document.test.ts+++ b/sdks/typescript/src/managed-agents/start-on-document.test.ts@@ -36,10 +36,10 @@ function fakeApi(state: { document: "absent" | "present" | "deleted"; sessions?: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 });+ if (existing) return Response.json({ session: { id: existing, status: "idle", executionMode: "workerd", createdAt: "2026-09-10T12:00:00.000Z" } }, { 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({ session: { id, status: "connecting", executionMode: "workerd", createdAt: "2026-09-10T12:00:00.000Z" } }, { status: 201 });}return Response.json({ error: { code: "not_found", message: "no route" } }, { status: 404 });};diff --git a/sdks/typescript/src/managed-agents/start-on-document.ts b/sdks/typescript/src/managed-agents/start-on-document.tsindex ebe85085..8ac4094a 100644--- a/sdks/typescript/src/managed-agents/start-on-document.ts+++ b/sdks/typescript/src/managed-agents/start-on-document.ts@@ -7,9 +7,10 @@// two calls in order and makes the pair converge under one key.import { OpenComputerError } from "./errors.js";-import { type Http, segment } from "./http.js";+import { type Answer, type Http, segment } from "./http.js";+import * as shapes from "./shapes.js";import type { MemoryAccess, MemoryAgentWrites, MemoryBindings, MemoryDocument } from "./memory.js";-import type { Environment, SessionSource } from "./types.js";+import type { Environment, SessionCreated, SessionSource } from "./types.js";export interface StartOnDocumentParams {/** The project whose memory holds the document. */@@ -97,7 +98,7 @@ export async function startOnDocument(http: Http, params: StartOnDocumentParams)let document: MemoryDocument;let documentCreated: boolean;try {- const created = await http.send<MemoryDocument>("PUT", documentPath, {+ const created = await http.send("PUT", documentPath, shapes.memoryDocument, {query,headers: { "if-none-match": "*" },body: {@@ -113,7 +114,7 @@ export async function startOnDocument(http: Http, params: StartOnDocumentParams)} catch (cause) {if (!(cause instanceof OpenComputerError) || cause.status !== 412) throw cause;try {- document = await http.request<MemoryDocument>("GET", documentPath, { query, signal: params.signal });+ document = await http.request("GET", documentPath, shapes.memoryDocument, { query, signal: params.signal });} catch (readCause) {if (readCause instanceof OpenComputerError && readCause.status === 404) {throw new OpenComputerError(@@ -128,9 +129,9 @@ export async function startOnDocument(http: Http, params: StartOnDocumentParams)documentCreated = false;}- let created: { status: number; body: { session?: { id?: string; status?: string; executionMode?: string } } };+ let created: Answer<Omit<SessionCreated, "created">>;try {- created = await http.send("POST", "/sessions", {+ created = await http.send("POST", "/sessions", shapes.sessionCreated, {headers: { "idempotency-key": await sessionIdempotencyKey(params.idempotencyKey) },body: {agentId: `${params.agent}@${params.environment}`,@@ -154,8 +155,7 @@ export async function startOnDocument(http: Http, params: StartOnDocumentParams)}throw cause;}- const session = created.body?.session;- if (!session?.id) throw new OpenComputerError(created.status, "invalid_response", "session create returned no session id");+ const { session } = created.body;return {document: { id: document.id, created: documentCreated, revision: document.revision, title: document.title },session: {diff --git a/sdks/typescript/src/managed-agents/types.ts b/sdks/typescript/src/managed-agents/types.tsindex 54795ab2..18e1e682 100644--- a/sdks/typescript/src/managed-agents/types.ts+++ b/sdks/typescript/src/managed-agents/types.ts@@ -169,7 +169,8 @@ export interface SessionSummary {projectId?: string;agentId: string;deploymentId: string;- environment?: Environment;+ /** `null` when the session has no environment. */+ environment?: Environment | null;source: SessionSource;status: SessionStatus;labels?: SessionLabels;