An open-source, faster Devin alternative
TypeScript
sdk: address review — request serialization, idempotency/retries, type fixes
Igor Zalutski56b03b060545
diff --git a/docs/reference/typescript-sdk/agent.mdx b/docs/reference/typescript-sdk/agent.mdxindex 9d25e958..0ae2ea19 100644--- a/docs/reference/typescript-sdk/agent.mdx+++ b/docs/reference/typescript-sdk/agent.mdx@@ -1,8 +1,15 @@----title: "Agent"-description: "Start and manage Claude agent sessions"+title: "Sandbox agent"+description: "Start and manage an agent session inside a sandbox (low-level)"---+<Warning>+The in-sandbox agent (`sandbox.agent`, exported as `SandboxAgent`) is a low-level+primitive and is **deprecated**. For most use cases prefer managed **[Durable Agent+Sessions](/agent-sessions/overview)** — the `OpenComputer` client gives you durable,+streamable, steerable sessions without managing the sandbox yourself.+</Warning>+Accessed via `sandbox.agent`.## `sandbox.agent.start(opts?)`@@ -45,7 +52,7 @@ Start an agent session. [HTTP API →](/api-reference/agent/create)Resume session ID</ParamField>-<ParamField body="onEvent" type="(event: AgentEvent) => void">+<ParamField body="onEvent" type="(event: SandboxAgentEvent) => void">Event callback</ParamField>@@ -61,7 +68,7 @@ Start an agent session. [HTTP API →](/api-reference/agent/create)Scrollback done callback</ParamField>-**Returns:** `Promise<AgentSession>`+**Returns:** `Promise<SandboxAgentSession>````typescriptconst session = await sandbox.agent.start({@@ -76,7 +83,7 @@ const session = await sandbox.agent.start({Reconnect to a running agent session. Accepts `onEvent`, `onError`, `onExit`, `onScrollbackEnd`.-**Returns:** `Promise<AgentSession>`+**Returns:** `Promise<SandboxAgentSession>`---@@ -84,11 +91,11 @@ Reconnect to a running agent session. Accepts `onEvent`, `onError`, `onExit`, `oList all agent sessions. [HTTP API →](/api-reference/agent/list)-**Returns:** `Promise<AgentSessionInfo[]>`+**Returns:** `Promise<SandboxAgentSessionInfo[]>`----## AgentSession+## SandboxAgentSession| Member | Type | Description || --- | --- | --- |@@ -104,9 +111,9 @@ List all agent sessions. [HTTP API →](/api-reference/agent/list)## Types-<Accordion title="AgentEvent">+<Accordion title="SandboxAgentEvent">```typescript-interface AgentEvent {+interface SandboxAgentEvent {type: string;[key: string]: unknown;}diff --git a/docs/reference/typescript-sdk/overview.mdx b/docs/reference/typescript-sdk/overview.mdxindex cc41a1ac..74c13615 100644--- a/docs/reference/typescript-sdk/overview.mdx+++ b/docs/reference/typescript-sdk/overview.mdx@@ -36,8 +36,8 @@ import { Image, Snapshots } from "@opencomputer/sdk/node";<Card title="Exec" icon="terminal" href="/reference/typescript-sdk/exec">Run commands and manage exec sessions</Card>- <Card title="Agent" icon="robot" href="/reference/typescript-sdk/agent">- Start and manage Claude agent sessions+ <Card title="Sandbox agent" icon="robot" href="/reference/typescript-sdk/agent">+ Start and manage an agent session inside a sandbox (low-level; deprecated)</Card><Card title="Filesystem" icon="folder" href="/reference/typescript-sdk/filesystem">Read, write, and manage filesdiff --git a/docs/reference/typescript-sdk/sandbox.mdx b/docs/reference/typescript-sdk/sandbox.mdxindex ef130807..4d793937 100644--- a/docs/reference/typescript-sdk/sandbox.mdx+++ b/docs/reference/typescript-sdk/sandbox.mdx@@ -357,8 +357,8 @@ The returned `AllowedHostsInfo`:Preview URL domain for port 80 (e.g., `sb-abc123-p80.workers.opencomputer.dev`). Returns empty string if sandbox domain is not configured.</ParamField>-<ParamField body="agent" type="Agent">- [Agent sessions](/reference/typescript-sdk/agent)+<ParamField body="agent" type="SandboxAgent">+ [Sandbox agent sessions](/reference/typescript-sdk/agent)</ParamField><ParamField body="exec" type="Exec">diff --git a/sdks/typescript/src/agents/http.ts b/sdks/typescript/src/agents/http.tsindex dc6af024..a5e808e1 100644--- a/sdks/typescript/src/agents/http.ts+++ b/sdks/typescript/src/agents/http.ts@@ -1,5 +1,5 @@import { errorFromResponse } from "./errors.js";-import { normalize } from "./normalize.js";+import { normalize, serialize } from "./normalize.js";/** Either an org API key (server) or a session-scoped client token (browser/edge). */export type Auth = { apiKey: string } | { token: string };@@ -14,7 +14,7 @@ export interface HttpOptions {}export type Query = Record<string, string | number | boolean | undefined | null>;-interface RequestOptions { query?: Query; body?: unknown; idempotencyKey?: string; signal?: AbortSignal; }+interface RequestOptions { query?: Query; body?: unknown; idempotencyKey?: string; signal?: AbortSignal; idempotent?: boolean; }const DEFAULT_BASE = "https://api.opencomputer.dev/v3";@@ -40,7 +40,9 @@ export class Http {url(path: string, query?: Query): string {const u = new URL(this.base + path);- if (query) for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== null) u.searchParams.set(k, String(v));+ if (query) for (const [k, v] of Object.entries(query)) {+ if (v !== undefined && v !== null) u.searchParams.set(k.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase()), String(v));+ }return u.toString();}@@ -48,19 +50,24 @@ export class Http {const headers = this.headers(opts.body !== undefined ? { "Content-Type": "application/json" } : undefined);if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;const init: RequestInit = { method, headers, signal: opts.signal };- if (opts.body !== undefined) init.body = JSON.stringify(opts.body);+ // The SDK owns serialization both ways: camelCase → snake_case on the way out+ // (the API reads turn_seconds, include_raw, idempotency_key, …), camelCase back in.+ if (opts.body !== undefined) init.body = JSON.stringify(serialize(opts.body));const url = this.url(path, opts.query);+ // Only retry when the call is safe to repeat: reads, or writes that carry an+ // idempotency key. Otherwise a retried POST could duplicate work or messages.+ const canRetry = method === "GET" || method === "HEAD" || opts.idempotent === true;for (let attempt = 0; ; attempt++) {let res: Response;try {res = await this.doFetch(url, init);} catch (e) {- if (attempt < this.maxRetries && !opts.signal?.aborted) { await sleep(backoff(attempt)); continue; }+ if (canRetry && attempt < this.maxRetries && !opts.signal?.aborted) { await sleep(backoff(attempt)); continue; }throw e;}if (res.ok) return res.status === 204 ? (undefined as T) : normalize<T>(await res.json());- if ((res.status === 429 || res.status >= 500) && attempt < this.maxRetries) {+ if (canRetry && (res.status === 429 || res.status >= 500) && attempt < this.maxRetries) {await sleep(retryAfterMs(res) ?? backoff(attempt));continue;}diff --git a/sdks/typescript/src/agents/normalize.ts b/sdks/typescript/src/agents/normalize.tsindex 78955e09..1c304e17 100644--- a/sdks/typescript/src/agents/normalize.ts+++ b/sdks/typescript/src/agents/normalize.ts@@ -27,3 +27,20 @@ export function normalize<T = any>(value: unknown): T {}return value as T;}++// Inverse of normalize: camelCase keys → snake_case for REQUEST bodies (the API reads+// snake_case). Values are left untouched, and an opaque `raw` payload is not recursed into.+const snakeKey = (k: string): string => k.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());++export function serialize(value: unknown): unknown {+ if (Array.isArray(value)) return value.map((v) => serialize(v));+ if (value && typeof value === "object") {+ const out: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {+ const sk = snakeKey(k);+ out[sk] = sk === "raw" ? v : serialize(v);+ }+ return out;+ }+ return value;+}diff --git a/sdks/typescript/src/agents/sessions.ts b/sdks/typescript/src/agents/sessions.tsindex 881d8413..3331acd7 100644--- a/sdks/typescript/src/agents/sessions.ts+++ b/sdks/typescript/src/agents/sessions.ts@@ -11,8 +11,10 @@ export interface CreateSessionParams {/** get-or-create idempotency/routing key — one session per key. */key?: string;webhook?: string;- destinations?: Array<{ url: string; secret?: string; level?: Level }>;+ destinations?: Array<{ url: string; secret?: string; level?: Level; types?: string[]; includeRaw?: boolean; enabled?: boolean }>;limits?: Limits;+ /** Makes a keyless create retry-safe (sent as the Idempotency-Key header). */+ idempotencyKey?: string;}export interface StreamOptions {@@ -32,15 +34,22 @@ export class Sessions {constructor(private readonly http: Http) {}async create(params: CreateSessionParams): Promise<Session> {+ const { idempotencyKey, destinations, ...rest } = params;+ const body = {+ ...rest,+ // inline destinations on create take `secret_ref`; the standalone API takes `secret`.+ destinations: destinations?.map(({ secret, ...d }) => ({ ...d, secretRef: secret })),+ };const r = await this.http.request<{ session: SessionData; clientToken?: string }>(- "POST", "/sessions", { body: params },+ "POST", "/sessions",+ { body, idempotencyKey, idempotent: Boolean(idempotencyKey || rest.key) },);return new Session(this.http, r.session, r.clientToken);}async get(id: string): Promise<Session> {return new Session(this.http, await this.http.request<SessionData>("GET", `/sessions/${id}`));}- list(params: { agent?: string; status?: SessionStatus; key?: string; limit?: number; cursor?: string } = {}): Promise<ListPage<SessionData>> {+ list(params: { agent?: string; status?: SessionStatus; key?: string; after?: string; before?: string; limit?: number; cursor?: string } = {}): Promise<ListPage<SessionData>> {return this.http.request("GET", "/sessions", { query: params as Query });}}@@ -109,7 +118,7 @@ export class Session {}/** Read a page of events without streaming. */- listEvents(opts: { after?: number; level?: Level; type?: string; limit?: number } = {}): Promise<ListPage<Event>> {+ listEvents(opts: { after?: number; level?: Level; type?: string; turnId?: string; limit?: number } = {}): Promise<ListPage<Event>> {return this.http.request("GET", `/sessions/${this.id}/events`, { query: opts as Query });}@@ -142,13 +151,13 @@ export class Session {async steer(text: string, opts: { idempotencyKey?: string } = {}): Promise<{ id: string; seq: number }> {const r = await this.http.request<{ event: { id: string; seq: number } }>("POST", `/sessions/${this.id}/messages`,- { body: { text }, idempotencyKey: opts.idempotencyKey },+ { body: { text, idempotencyKey: opts.idempotencyKey }, idempotent: Boolean(opts.idempotencyKey) },);return r.event;}/** The resolved final result + last-turn summary. */- result(): Promise<{ lastTurn?: LastTurn; result?: Event }> {+ result(): Promise<{ lastTurn?: LastTurn | null; result?: Event | null }> {return this.http.request("GET", `/sessions/${this.id}/result`);}cancel(): Promise<void> { return this.http.request("POST", `/sessions/${this.id}/cancel`); }diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.tsindex b4ebd6a0..f835e81a 100644--- a/sdks/typescript/src/agents/types.ts+++ b/sdks/typescript/src/agents/types.ts@@ -1,7 +1,7 @@// Domain types for the Durable Agent Sessions API (v3). Field names are camelCase —// the client normalizes the API's snake_case at the boundary.-export type SessionStatus = "queued" | "running" | "idle" | "failed" | "archived";+export type SessionStatus = "queued" | "running" | "awaiting_input" | "idle" | "failed" | "archived";export type Level = "user" | "progress" | "internal";export type YieldReason =| "completed" | "needs_input" | "error"@@ -29,7 +29,7 @@ export interface Agent {}export interface LastTurn {- state?: "queued" | "running" | "ok" | "error";+ state?: "queued" | "accepted" | "running" | "ok" | "error";yieldReason?: YieldReason;turnId?: string;startedAt?: string;@@ -40,7 +40,7 @@ export interface LastTurn {export interface Turn {id: string;- state?: "queued" | "running" | "ok" | "error";+ state?: "queued" | "accepted" | "running" | "ok" | "error";yieldReason?: YieldReason;resultEventId?: string;error?: unknown;@@ -54,6 +54,7 @@ export interface SessionData {head?: number;inputCursor?: number;agentSnapshot?: { promptHash?: string; model?: string; runtime?: string; revision?: number };+ agentId?: string;credentialId?: string;lastTurn?: LastTurn;limits?: Limits;@@ -71,25 +72,34 @@ export interface Credential {export interface Destination {id: string;+ session: string;+ kind: string;url: string;level: Level;- types?: string[];+ types?: string[] | null;includeRaw: boolean;enabled: boolean;+ hasSecret: boolean;+ createdAfterSeq?: number;createdAt?: string;+ updatedAt?: string;}export type DeliveryStatus = "pending" | "delivering" | "delivered" | "failed" | "dead_letter";export interface Delivery {id: string;- destinationId: string;+ session: string;+ destination: string;eventId: string;+ eventSeq?: number;status: DeliveryStatus;attempts: number;lastAttemptAt?: string;responseCode?: number;error?: string;+ createdAt?: string;+ updatedAt?: string;}// ── Events ─────────────────────────────────────────────────────────────────────@@ -103,6 +113,10 @@ export interface EventBase {session: string;actor: Actor;level: Level;+ turnId?: string;+ contentRef?: string;+ bodyTruncated?: boolean;+ bodyBytes?: number;refs: Record<string, unknown>;}