Skip to content

An open-source, faster Devin alternative

TypeScript

sdk 0.7.0: managed Durable Agent Sessions in @opencomputer/sdk + rename sandbox agent

Igor Zalutski254a1561edec
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 5497f268..f208164e 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.6.3",
+ "version": "0.7.0",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",
diff --git a/sdks/typescript/src/agent.ts b/sdks/typescript/src/agent.ts
index 6daf46ee..7b133101 100644
--- a/sdks/typescript/src/agent.ts
+++ b/sdks/typescript/src/agent.ts
@@ -1,4 +1,4 @@
-export interface AgentEvent {
+export interface SandboxAgentEvent {
type:
| "ready"
| "configured"
@@ -19,7 +19,7 @@ export interface McpServerConfig {
env?: Record<string, string>;
}
-export interface AgentConfig {
+export interface SandboxAgentConfig {
model?: string;
systemPrompt?: string;
allowedTools?: string[];
@@ -30,25 +30,29 @@ export interface AgentConfig {
resume?: string;
}
-export interface AgentStartOpts extends AgentConfig {
+export interface SandboxAgentStartOpts extends SandboxAgentConfig {
prompt?: string;
- onEvent?: (event: AgentEvent) => void;
+ onEvent?: (event: SandboxAgentEvent) => void;
onError?: (data: string) => void;
onExit?: (exitCode: number) => void;
onScrollbackEnd?: () => void;
}
-export interface AgentSession {
+export interface SandboxAgentSession {
sessionId: string;
done: Promise<number>;
sendPrompt(text: string): void;
interrupt(): void;
- configure(config: AgentConfig): void;
+ configure(config: SandboxAgentConfig): void;
kill(signal?: number): Promise<void>;
close(): void;
}
-export class Agent {
+/**
+ * @deprecated The in-sandbox agent is a low-level primitive and is being phased out.
+ * Prefer managed agents via the `OpenComputer` client — durable, streamable sessions.
+ */
+export class SandboxAgent {
constructor(
private apiUrl: string,
private apiKey: string,
@@ -66,7 +70,7 @@ export class Agent {
return h;
}
- async start(opts: AgentStartOpts = {}): Promise<AgentSession> {
+ async start(opts: SandboxAgentStartOpts = {}): Promise<SandboxAgentSession> {
const body: Record<string, unknown> = {};
if (opts.prompt) body.prompt = opts.prompt;
if (opts.model) body.model = opts.model;
@@ -95,7 +99,7 @@ export class Agent {
return this.attach(sessionId, opts);
}
- async attach(sessionId: string, opts: Omit<AgentStartOpts, "prompt" | keyof AgentConfig> = {}): Promise<AgentSession> {
+ async attach(sessionId: string, opts: Omit<SandboxAgentStartOpts, "prompt" | keyof SandboxAgentConfig> = {}): Promise<SandboxAgentSession> {
// Connect via the existing exec session WebSocket endpoint
const wsUrl = this.apiUrl
.replace("http://", "ws://")
@@ -126,7 +130,7 @@ export class Agent {
const trimmed = line.trim();
if (!trimmed) continue;
try {
- const event: AgentEvent = JSON.parse(trimmed);
+ const event: SandboxAgentEvent = JSON.parse(trimmed);
opts.onEvent?.(event);
} catch {
// Not JSON — treat as raw output
@@ -173,7 +177,7 @@ export class Agent {
// Flush remaining line buffer
if (lineBuf.trim()) {
try {
- const event: AgentEvent = JSON.parse(lineBuf.trim());
+ const event: SandboxAgentEvent = JSON.parse(lineBuf.trim());
opts.onEvent?.(event);
} catch {
opts.onError?.(`non-JSON stdout: ${lineBuf.trim()}`);
@@ -213,7 +217,7 @@ export class Agent {
interrupt(): void {
sendStdin(JSON.stringify({ type: "interrupt" }) + "\n");
},
- configure(config: AgentConfig): void {
+ configure(config: SandboxAgentConfig): void {
sendStdin(JSON.stringify({ type: "configure", ...config }) + "\n");
},
async kill(signal?: number): Promise<void> {
diff --git a/sdks/typescript/src/agents/agents.ts b/sdks/typescript/src/agents/agents.ts
new file mode 100644
index 00000000..070da0eb
--- /dev/null
+++ b/sdks/typescript/src/agents/agents.ts
@@ -0,0 +1,41 @@
+import type { Http, Query } from "./http.js";
+import type { Agent, Limits } from "./types.js";
+
+export interface CreateAgentParams {
+ name: string;
+ prompt: string;
+ model: string;
+ runtime?: string;
+ /** Anthropic key, stored as a sealed credential. Or pass `credential`, or rely on the org default. */
+ key?: string;
+ credential?: string;
+ limits?: Limits;
+}
+
+export interface UpdateAgentParams {
+ prompt?: string;
+ model?: string;
+ key?: string;
+ credential?: string;
+ limits?: Limits;
+}
+
+export interface Page<T> { data: T[]; nextCursor?: string | null; }
+
+/** Reusable agents — the "what" a session runs. */
+export class Agents {
+ constructor(private readonly http: Http) {}
+
+ create(params: CreateAgentParams): Promise<Agent> {
+ return this.http.request("POST", "/agents", { body: params });
+ }
+ get(id: string): Promise<Agent> {
+ return this.http.request("GET", `/agents/${id}`);
+ }
+ update(id: string, params: UpdateAgentParams): Promise<Agent> {
+ return this.http.request("PATCH", `/agents/${id}`, { body: params });
+ }
+ list(params: { limit?: number; cursor?: string } = {}): Promise<Page<Agent>> {
+ return this.http.request("GET", "/agents", { query: params as Query });
+ }
+}
diff --git a/sdks/typescript/src/agents/client.ts b/sdks/typescript/src/agents/client.ts
new file mode 100644
index 00000000..f8af6377
--- /dev/null
+++ b/sdks/typescript/src/agents/client.ts
@@ -0,0 +1,30 @@
+import { Http, type HttpOptions } from "./http.js";
+import { Agents } from "./agents.js";
+import { Sessions } from "./sessions.js";
+import { Credentials } from "./credentials.js";
+
+export interface OpenComputerOptions extends HttpOptions {
+ /** Your OpenComputer org API key (server-side only — never ship it to a browser). */
+ apiKey: string;
+}
+
+/**
+ * Server-side client for Durable Agent Sessions. Holds the org API key and exposes the
+ * management surface. For the browser, mint a client token and use `connectSession`.
+ *
+ * const oc = new OpenComputer({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
+ * const agent = await oc.agents.create({ name, prompt, model, key });
+ * const session = await oc.sessions.create({ agent: agent.id, input });
+ */
+export class OpenComputer {
+ readonly agents: Agents;
+ readonly sessions: Sessions;
+ readonly credentials: Credentials;
+
+ constructor(opts: OpenComputerOptions) {
+ const http = new Http({ apiKey: opts.apiKey }, opts);
+ this.agents = new Agents(http);
+ this.sessions = new Sessions(http);
+ this.credentials = new Credentials(http);
+ }
+}
diff --git a/sdks/typescript/src/agents/connect.ts b/sdks/typescript/src/agents/connect.ts
new file mode 100644
index 00000000..7d574e7d
--- /dev/null
+++ b/sdks/typescript/src/agents/connect.ts
@@ -0,0 +1,22 @@
+import { Http, type HttpOptions } from "./http.js";
+import { Session } from "./sessions.js";
+import type { SessionData } from "./types.js";
+
+export interface ConnectSessionOptions extends HttpOptions {
+ sessionId: string;
+ /** A session-scoped client token (read + steer). Safe in a browser; never the org key. */
+ clientToken: string;
+}
+
+/**
+ * Browser/edge entry point: connect to one session with a client token. Returns a
+ * `Session` handle that can stream and steer that session — and nothing else.
+ *
+ * const session = await connectSession({ sessionId, clientToken });
+ * for await (const ev of session.events()) render(ev);
+ */
+export async function connectSession(opts: ConnectSessionOptions): Promise<Session> {
+ const http = new Http({ token: opts.clientToken }, opts);
+ const data = await http.request<SessionData>("GET", `/sessions/${opts.sessionId}`);
+ return new Session(http, data, opts.clientToken);
+}
diff --git a/sdks/typescript/src/agents/credentials.ts b/sdks/typescript/src/agents/credentials.ts
new file mode 100644
index 00000000..56b2d63a
--- /dev/null
+++ b/sdks/typescript/src/agents/credentials.ts
@@ -0,0 +1,28 @@
+import type { Http } from "./http.js";
+import type { Credential } from "./types.js";
+
+export interface CreateCredentialParams {
+ provider: "anthropic" | (string & {});
+ /** Write-only — never returned by the API. */
+ key: string;
+ name?: string;
+}
+
+/** Provider keys (e.g. Anthropic), stored in the secret store; sessions run on them. */
+export class Credentials {
+ constructor(private readonly http: Http) {}
+
+ create(params: CreateCredentialParams): Promise<Credential> {
+ return this.http.request("POST", "/credentials", { body: params });
+ }
+ async list(): Promise<Credential[]> {
+ const r = await this.http.request<{ data?: Credential[] } | Credential[]>("GET", "/credentials");
+ return Array.isArray(r) ? r : r.data ?? [];
+ }
+ delete(id: string): Promise<void> {
+ return this.http.request("DELETE", `/credentials/${id}`);
+ }
+ setDefault(params: { provider: string; credential: string }): Promise<void> {
+ return this.http.request("PUT", "/credentials/default", { body: params });
+ }
+}
diff --git a/sdks/typescript/src/agents/errors.ts b/sdks/typescript/src/agents/errors.ts
new file mode 100644
index 00000000..23efbbbe
--- /dev/null
+++ b/sdks/typescript/src/agents/errors.ts
@@ -0,0 +1,59 @@
+/** The error envelope the API returns: `{ error: { type, message, code, param?, request_id } }`. */
+export interface ApiErrorBody {
+ type?: string;
+ message?: string;
+ code?: string;
+ param?: string;
+ request_id?: string;
+}
+
+/** Base error for every failed API call. Thrown (never returned). */
+export class OpenComputerError extends Error {
+ readonly status: number;
+ readonly code?: string;
+ readonly type?: string;
+ readonly param?: string;
+ readonly requestId?: string;
+
+ constructor(status: number, body: ApiErrorBody | undefined, fallback: string) {
+ super(body?.message || fallback);
+ this.name = "OpenComputerError";
+ this.status = status;
+ this.code = body?.code;
+ this.type = body?.type;
+ this.param = body?.param;
+ this.requestId = body?.request_id;
+ }
+}
+
+export class AuthError extends OpenComputerError { name = "AuthError"; } // 401 / 403
+export class NotFoundError extends OpenComputerError { name = "NotFoundError"; } // 404
+export class ConflictError extends OpenComputerError { name = "ConflictError"; } // 409
+export class ValidationError extends OpenComputerError { name = "ValidationError"; } // 422
+
+export class RateLimitError extends OpenComputerError {
+ name = "RateLimitError";
+ /** Seconds to wait, from the `Retry-After` header, if present. */
+ readonly retryAfter?: number;
+ constructor(status: number, body: ApiErrorBody | undefined, fallback: string, retryAfter?: number) {
+ super(status, body, fallback);
+ this.retryAfter = retryAfter;
+ }
+}
+
+export function errorFromResponse(
+ status: number,
+ body: ApiErrorBody | undefined,
+ retryAfter?: number,
+): OpenComputerError {
+ const fallback = `OpenComputer request failed (${status})`;
+ switch (status) {
+ case 401:
+ case 403: return new AuthError(status, body, fallback);
+ case 404: return new NotFoundError(status, body, fallback);
+ case 409: return new ConflictError(status, body, fallback);
+ case 422: return new ValidationError(status, body, fallback);
+ case 429: return new RateLimitError(status, body, fallback, retryAfter);
+ default: return new OpenComputerError(status, body, fallback);
+ }
+}
diff --git a/sdks/typescript/src/agents/http.ts b/sdks/typescript/src/agents/http.ts
new file mode 100644
index 00000000..6cd9170e
--- /dev/null
+++ b/sdks/typescript/src/agents/http.ts
@@ -0,0 +1,95 @@
+import { errorFromResponse } from "./errors.js";
+import { normalize } from "./normalize.js";
+
+/** Either an org API key (server) or a session-scoped client token (browser/edge). */
+export type Auth = { apiKey: string } | { token: string };
+
+export interface HttpOptions {
+ /** Defaults to https://api.opencomputer.dev/v3 */
+ baseUrl?: string;
+ /** Override fetch (for runtimes without a global, or for testing). */
+ fetch?: typeof fetch;
+ /** Retries on 429 / 5xx / network error. Default 2. */
+ maxRetries?: number;
+}
+
+export type Query = Record<string, string | number | boolean | undefined | null>;
+interface RequestOptions { query?: Query; body?: unknown; idempotencyKey?: string; signal?: AbortSignal; }
+
+const DEFAULT_BASE = "https://api.opencomputer.dev/v3";
+
+/** Tiny fetch wrapper: auth, JSON, normalization, typed errors, retry. The whole HTTP layer. */
+export class Http {
+ readonly base: string;
+ private readonly doFetch: typeof fetch;
+ private readonly maxRetries: number;
+ private readonly bearer: string;
+
+ constructor(auth: Auth, opts: HttpOptions = {}) {
+ this.bearer = "token" in auth ? auth.token : auth.apiKey;
+ this.base = (opts.baseUrl ?? DEFAULT_BASE).replace(/\/+$/, "");
+ const f = opts.fetch ?? (typeof fetch !== "undefined" ? fetch : undefined);
+ if (!f) throw new Error("global fetch is unavailable — pass { fetch } in the client options.");
+ this.doFetch = f.bind(globalThis) as typeof fetch;
+ this.maxRetries = opts.maxRetries ?? 2;
+ }
+
+ private headers(extra?: Record<string, string>): Record<string, string> {
+ return { Authorization: `Bearer ${this.bearer}`, ...extra };
+ }
+
+ 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));
+ return u.toString();
+ }
+
+ async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {
+ 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);
+ const url = this.url(path, opts.query);
+
+ 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; }
+ 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) {
+ await sleep(retryAfterMs(res) ?? backoff(attempt));
+ continue;
+ }
+ throw errorFromResponse(res.status, (await safeJson(res))?.error, retryAfterSec(res));
+ }
+ }
+
+ /** Open an SSE stream (caller reads the body). Auth via the Authorization header. */
+ async stream(path: string, query?: Query, signal?: AbortSignal): Promise<Response> {
+ const res = await this.doFetch(this.url(path, query), {
+ method: "GET",
+ headers: this.headers({ Accept: "text/event-stream" }),
+ signal,
+ });
+ if (!res.ok) throw errorFromResponse(res.status, (await safeJson(res))?.error, retryAfterSec(res));
+ return res;
+ }
+}
+
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+const backoff = (attempt: number) => Math.min(500 * 2 ** attempt, 8000);
+const retryAfterSec = (res: Response): number | undefined => {
+ const v = Number(res.headers.get("retry-after"));
+ return Number.isFinite(v) && v > 0 ? v : undefined;
+};
+const retryAfterMs = (res: Response): number | undefined => {
+ const s = retryAfterSec(res);
+ return s ? s * 1000 : undefined;
+};
+async function safeJson(res: Response): Promise<any> {
+ try { return await res.json(); } catch { return undefined; }
+}
diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.ts
new file mode 100644
index 00000000..7b5064df
--- /dev/null
+++ b/sdks/typescript/src/agents/index.ts
@@ -0,0 +1,12 @@
+export { OpenComputer, type OpenComputerOptions } from "./client.js";
+export { connectSession, type ConnectSessionOptions } from "./connect.js";
+
+export { Sessions, Session } from "./sessions.js";
+export type { CreateSessionParams, StreamOptions, Envelope, ListPage } from "./sessions.js";
+export { Agents } from "./agents.js";
+export type { CreateAgentParams, UpdateAgentParams, Page } from "./agents.js";
+export { Credentials } from "./credentials.js";
+export type { CreateCredentialParams } from "./credentials.js";
+
+export * from "./types.js";
+export * from "./errors.js";
diff --git a/sdks/typescript/src/agents/normalize.ts b/sdks/typescript/src/agents/normalize.ts
new file mode 100644
index 00000000..b733fcc4
--- /dev/null
+++ b/sdks/typescript/src/agents/normalize.ts
@@ -0,0 +1,29 @@
+// Normalize API responses to idiomatic TS: snake_case keys → camelCase, and a known set
+// of numeric fields that the API serializes as strings (bigints) → numbers. Leaves the
+// opaque `raw` payload (source-specific adapter data) untouched.
+
+const NUMERIC = new Set([
+ "seq", "head", "inputCursor", "inputFromSeq", "inputToSeq", "exitCode", "bytes", "port",
+ "numTurns", "revision", "tokens", "turnSeconds", "turns", "activeSeconds", "usd",
+ "attempts", "responseCode",
+]);
+
+const camel = (k: string): string => k.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());
+
+export function normalize<T = any>(value: unknown): T {
+ if (Array.isArray(value)) return value.map((v) => normalize(v)) as T;
+ if (value && typeof value === "object") {
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
+ const ck = camel(k);
+ if (ck === "raw") { out[ck] = v; continue; }
+ let nv: unknown = normalize(v);
+ if (NUMERIC.has(ck) && typeof nv === "string" && nv !== "" && !Number.isNaN(Number(nv))) {
+ nv = Number(nv);
+ }
+ out[ck] = nv;
+ }
+ return out as T;
+ }
+ return value as T;
+}
diff --git a/sdks/typescript/src/agents/sessions.ts b/sdks/typescript/src/agents/sessions.ts
new file mode 100644
index 00000000..1e112815
--- /dev/null
+++ b/sdks/typescript/src/agents/sessions.ts
@@ -0,0 +1,136 @@
+import type { Http, Query } from "./http.js";
+import type { Event, Level, Limits, LastTurn, SessionData, SessionStatus } from "./types.js";
+import { parseEventStream } from "./sse.js";
+
+export type Envelope = { text?: string; [k: string]: unknown };
+
+export interface CreateSessionParams {
+ agent: string;
+ input: string | Envelope;
+ /** get-or-create idempotency/routing key — one session per key. */
+ key?: string;
+ webhook?: string;
+ destinations?: Array<{ url: string; secret?: string; level?: Level }>;
+ limits?: Limits;
+}
+
+export interface StreamOptions {
+ /** Visibility threshold; default `internal` (the full build trace). */
+ level?: Level;
+ /** Filter by event type (exact or `prefix.*`). */
+ type?: string;
+ /** Resume from this seq (default 0 — replays the whole log). */
+ after?: number;
+ signal?: AbortSignal;
+}
+
+export interface ListPage<T> { data: T[]; nextCursor?: string | null; }
+
+/** Sessions — durable runs of an agent. */
+export class Sessions {
+ constructor(private readonly http: Http) {}
+
+ async create(params: CreateSessionParams): Promise<Session> {
+ const r = await this.http.request<{ session: SessionData; clientToken?: string }>(
+ "POST", "/sessions", { body: params },
+ );
+ 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>> {
+ return this.http.request("GET", "/sessions", { query: params as Query });
+ }
+}
+
+/**
+ * A handle to one session. Returned by `sessions.create`/`get` (org key) and by
+ * `connectSession` (browser, client token) — same type, both auth modes.
+ */
+export class Session {
+ /** Present after create / connectSession — safe to hand to a browser. */
+ readonly clientToken?: string;
+ private data: SessionData;
+
+ constructor(private readonly http: Http, data: SessionData, clientToken?: string) {
+ this.data = data;
+ this.clientToken = clientToken;
+ }
+
+ get id(): string { return this.data.id; }
+ get status(): SessionStatus { return this.data.status; }
+ get lastTurn(): LastTurn | undefined { return this.data.lastTurn; }
+ /** The latest fetched session record. */
+ get snapshot(): SessionData { return this.data; }
+
+ async refresh(): Promise<this> {
+ this.data = await this.http.request<SessionData>("GET", `/sessions/${this.id}`);
+ return this;
+ }
+
+ /**
+ * Stream events as an async iterator. Reconnects from the last seq on a dropped
+ * connection and keeps tailing until the `signal` aborts. Replays the log from `after`
+ * (default 0) on first connect, so opening a session shows its whole history.
+ *
+ * for await (const ev of session.events({ signal })) { switch (ev.type) { … } }
+ */
+ async *events(opts: StreamOptions = {}): AsyncGenerator<Event> {
+ let after = opts.after ?? 0;
+ const base: Query = { stream: "sse", level: opts.level ?? "internal", type: opts.type };
+ for (;;) {
+ if (opts.signal?.aborted) return;
+ let res: Response;
+ try {
+ res = await this.http.stream(`/sessions/${this.id}/events`, { ...base, after }, opts.signal);
+ } catch (e) {
+ if (opts.signal?.aborted) return;
+ throw e; // auth/404/etc. — surface it
+ }
+ try {
+ for await (const ev of parseEventStream(res)) {
+ after = ev.seq;
+ yield ev;
+ }
+ } catch {
+ if (opts.signal?.aborted) return;
+ // network drop mid-stream — fall through and reconnect from `after`
+ }
+ if (opts.signal?.aborted) return;
+ await sleep(1000); // stream ended (caught up / closed) — pause before re-tailing
+ }
+ }
+
+ /** Read a page of events without streaming. */
+ listEvents(opts: { after?: number; level?: Level; type?: string; limit?: number } = {}): Promise<ListPage<Event>> {
+ return this.http.request("GET", `/sessions/${this.id}/events`, { query: opts as Query });
+ }
+
+ /** Send a message; wakes the 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 },
+ );
+ return r.event;
+ }
+
+ /** The resolved final result + last-turn summary. */
+ result(): Promise<{ lastTurn?: LastTurn; result?: Event }> {
+ return this.http.request("GET", `/sessions/${this.id}/result`);
+ }
+ cancel(): Promise<void> { return this.http.request("POST", `/sessions/${this.id}/cancel`); }
+ archive(): Promise<void> { return this.http.request("POST", `/sessions/${this.id}/archive`); }
+
+ /** Mint a browser-safe client token for this session (org key only). */
+ async mintClientToken(opts: { scopes?: Array<"read" | "steer">; ttlSeconds?: number } = {}): Promise<string> {
+ const r = await this.http.request<{ clientToken?: string; token?: string }>(
+ "POST", `/sessions/${this.id}/client-tokens`,
+ { body: { scopes: opts.scopes, ttl: opts.ttlSeconds } },
+ );
+ return (r.clientToken ?? r.token)!;
+ }
+}
+
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
diff --git a/sdks/typescript/src/agents/sse.ts b/sdks/typescript/src/agents/sse.ts
new file mode 100644
index 00000000..8ab84f7b
--- /dev/null
+++ b/sdks/typescript/src/agents/sse.ts
@@ -0,0 +1,38 @@
+import type { Event } from "./types.js";
+import { normalize } from "./normalize.js";
+
+// Parse a `text/event-stream` Response body into normalized events. Web-standard only
+// (ReadableStream + TextDecoder) — works in Node 18+, browsers, Workers, and Deno. No
+// EventSource (can't set auth headers) and no dependencies.
+export async function* parseEventStream(res: Response): AsyncGenerator<Event> {
+ const body = res.body;
+ if (!body) return;
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buf = "";
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let i: number;
+ while ((i = buf.indexOf("\n\n")) !== -1) {
+ const frame = buf.slice(0, i);
+ buf = buf.slice(i + 2);
+ const data = frameData(frame);
+ if (data) yield normalize<Event>(JSON.parse(data));
+ }
+ }
+ } finally {
+ try { await reader.cancel(); } catch { /* already closed */ }
+ }
+}
+
+function frameData(frame: string): string | null {
+ const data = frame
+ .split("\n")
+ .filter((l) => l.startsWith("data:"))
+ .map((l) => l.slice(5).replace(/^ /, ""))
+ .join("\n");
+ return data || null;
+}
diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.ts
new file mode 100644
index 00000000..1f32ae29
--- /dev/null
+++ b/sdks/typescript/src/agents/types.ts
@@ -0,0 +1,87 @@
+// 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 Level = "user" | "progress" | "internal";
+export type YieldReason =
+ | "completed" | "needs_input" | "error"
+ | "budget_exceeded" | "deadline_exceeded" | "max_turns" | "canceled";
+
+export interface Limits { tokens?: number; turnSeconds?: number; turns?: number; }
+
+export interface Actor {
+ id?: string;
+ kind?: "human" | "agent" | "system" | (string & {});
+ display?: string;
+}
+
+export interface Agent {
+ id: string;
+ name: string;
+ promptHash?: string;
+ model: string;
+ runtime: string;
+ revision?: number;
+ credentialId?: string | null;
+ limits?: Limits;
+ createdAt?: string;
+ updatedAt?: string;
+}
+
+export interface LastTurn {
+ state?: "queued" | "running" | "ok" | "error";
+ yieldReason?: YieldReason;
+ turnId?: string;
+ startedAt?: string;
+ completedAt?: string;
+ resultEventId?: string;
+ error?: unknown;
+}
+
+export interface SessionUsage { activeSeconds?: number; usd?: number; tokens?: number; }
+
+export interface SessionData {
+ id: string;
+ status: SessionStatus;
+ head?: number;
+ inputCursor?: number;
+ agentSnapshot?: { promptHash?: string; model?: string; runtime?: string; revision?: number };
+ credentialId?: string;
+ lastTurn?: LastTurn;
+ usage?: SessionUsage;
+ limits?: Limits;
+ key?: string;
+ createdAt?: string;
+}
+
+export interface Credential {
+ id: string;
+ provider: string;
+ name?: string;
+ last4?: string;
+ createdAt?: string;
+}
+
+// ── Events ─────────────────────────────────────────────────────────────────────
+// Discriminated on `type`. Switch on it; don't parse prose. Unknown types fall through
+// the open member and still carry `body.text`/`summary`, so new types are non-breaking.
+
+export interface EventBase {
+ id: string;
+ seq: number;
+ ts: string;
+ session: string;
+ actor: Actor;
+ level: Level;
+ refs: Record<string, unknown>;
+}
+
+export type Event =
+ | (EventBase & { type: "user.message"; body: { text: string } })
+ | (EventBase & { type: "agent.message"; body: { text: string } })
+ | (EventBase & { type: "turn.started"; body: { turnId: string; inputFromSeq?: number; inputToSeq?: number } })
+ | (EventBase & { type: "turn.completed"; body: { turnId: string; yieldReason: YieldReason; resultEventId?: string } })
+ | (EventBase & { type: "tool.call"; body: { tool: string; argsSummary?: string } })
+ | (EventBase & { type: "exec.completed"; body: { command: string; exitCode: number; summary?: string; contentRef?: string; bytes?: number } })
+ | (EventBase & { type: "preview.url"; body: { url: string; port?: number } })
+ | (EventBase & { type: string; body: Record<string, any> }); // forward-compat catch-all
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index 82a5302d..42cc994a 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -13,7 +13,9 @@ export {
type ScalingLockStatus,
type AllowedHostsInfo,
} from "./sandbox.js";
-export { Agent, type AgentEvent, type AgentConfig, type AgentStartOpts, type AgentSession, type McpServerConfig } from "./agent.js";
+export { SandboxAgent, type SandboxAgentEvent, type SandboxAgentConfig, type SandboxAgentStartOpts, type SandboxAgentSession, type McpServerConfig } from "./agent.js";
+// Managed Durable Agent Sessions (the OpenComputer client + Session handle).
+export * from "./agents/index.js";
export { Filesystem, type EntryInfo } from "./filesystem.js";
export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";
export { Mounts, type AddMountOpts, type MountInfo, type MountBackend } from "./mounts.js";
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 173d4ece..d191e2b4 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -1,4 +1,4 @@
-import { Agent } from "./agent.js";
+import { SandboxAgent } from "./agent.js";
import { Filesystem } from "./filesystem.js";
import { Exec } from "./exec.js";
import { Mounts } from "./mounts.js";
@@ -228,7 +228,8 @@ export interface AllowedHostsInfo {
export class Sandbox {
readonly sandboxId: string;
readonly id: string;
- readonly agent: Agent;
+ /** @deprecated The in-sandbox agent is legacy — prefer managed agents (the `OpenComputer` client). */
+ readonly agent: SandboxAgent;
readonly files: Filesystem;
readonly exec: Exec;
readonly mounts: Mounts;
@@ -268,7 +269,7 @@ export class Sandbox {
this._sandboxDomain = data.sandboxDomain || "";
// Always route through the CP — it handles readiness waiting and proxies to workers.
- this.agent = new Agent(apiUrl, apiKey, this.sandboxId, "");
+ this.agent = new SandboxAgent(apiUrl, apiKey, this.sandboxId, "");
this.files = new Filesystem(apiUrl, apiKey, this.sandboxId, "");
this.exec = new Exec(apiUrl, apiKey, this.sandboxId, "");
this.commands = this.exec; // backwards-compatible alias
@@ -456,7 +457,7 @@ export class Sandbox {
this.token = data.token || "";
// Always route through the CP
- (this as any).agent = new Agent(this.apiUrl, this.apiKey, this.sandboxId, "");
+ (this as any).agent = new SandboxAgent(this.apiUrl, this.apiKey, this.sandboxId, "");
(this as any).files = new Filesystem(this.apiUrl, this.apiKey, this.sandboxId, "");
(this as any).exec = new Exec(this.apiUrl, this.apiKey, this.sandboxId, "");
(this as any).mounts = new Mounts(this.apiUrl, this.apiKey, this.sandboxId, "");
@@ -724,7 +725,7 @@ export class Sandbox {
this.token = data.token || "";
// Always route through the CP
- (this as any).agent = new Agent(this.apiUrl, this.apiKey, this.sandboxId, "");
+ (this as any).agent = new SandboxAgent(this.apiUrl, this.apiKey, this.sandboxId, "");
(this as any).files = new Filesystem(this.apiUrl, this.apiKey, this.sandboxId, "");
(this as any).exec = new Exec(this.apiUrl, this.apiKey, this.sandboxId, "");
(this as any).mounts = new Mounts(this.apiUrl, this.apiKey, this.sandboxId, "");