An open-source, faster Devin alternative
TypeScript
sdk: review round 2 — connectSession, Session surface split, serialize, P2s
Igor Zalutski282d60b989d9
diff --git a/docs/agent-sessions/authentication.mdx b/docs/agent-sessions/authentication.mdxindex b39b2247..84991f6d 100644--- a/docs/agent-sessions/authentication.mdx+++ b/docs/agent-sessions/authentication.mdx@@ -103,10 +103,7 @@ Content-Type: application/json<CodeGroup>```ts TypeScript SDK-await oc.credentials.setDefault({- provider: "anthropic",- credential: "cred_...",-});+await oc.credentials.setDefault({ credential: "cred_..." });``````http REST APIdiff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.jsonindex b6db8e83..58477b0f 100644--- a/sdks/typescript/package-lock.json+++ b/sdks/typescript/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/sdk",- "version": "0.6.3",+ "version": "0.7.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/sdk",- "version": "0.6.3",+ "version": "0.7.0","license": "MIT","devDependencies": {"@types/node": "^25.3.0",diff --git a/sdks/typescript/src/agents/connect.ts b/sdks/typescript/src/agents/connect.tsindex 7d574e7d..0e4b76d0 100644--- a/sdks/typescript/src/agents/connect.ts+++ b/sdks/typescript/src/agents/connect.ts@@ -1,6 +1,5 @@import { Http, type HttpOptions } from "./http.js";-import { Session } from "./sessions.js";-import type { SessionData } from "./types.js";+import { ClientSession } from "./sessions.js";export interface ConnectSessionOptions extends HttpOptions {sessionId: string;@@ -10,13 +9,14 @@ export interface ConnectSessionOptions extends HttpOptions {/*** 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.+ * `ClientSession` 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> {+export async function connectSession(opts: ConnectSessionOptions): Promise<ClientSession> {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);+ // No metadata fetch: GET /sessions/:id is org-key scoped, so a client token can't read it.+ // The handle streams + steers directly — the routes a client token is authorized for.+ return new ClientSession(http, opts.sessionId, opts.clientToken);}diff --git a/sdks/typescript/src/agents/credentials.ts b/sdks/typescript/src/agents/credentials.tsindex 56b2d63a..c068d15f 100644--- a/sdks/typescript/src/agents/credentials.ts+++ b/sdks/typescript/src/agents/credentials.ts@@ -2,7 +2,8 @@ import type { Http } from "./http.js";import type { Credential } from "./types.js";export interface CreateCredentialParams {- provider: "anthropic" | (string & {});+ /** Defaults to `anthropic`. */+ provider?: "anthropic" | (string & {});/** Write-only — never returned by the API. */key: string;name?: string;@@ -22,7 +23,7 @@ export class Credentials {delete(id: string): Promise<void> {return this.http.request("DELETE", `/credentials/${id}`);}- setDefault(params: { provider: string; credential: string }): Promise<void> {+ setDefault(params: { credential: string; provider?: string }): Promise<void> {return this.http.request("PUT", "/credentials/default", { body: params });}}diff --git a/sdks/typescript/src/agents/destinations.ts b/sdks/typescript/src/agents/destinations.tsindex bfe6cace..c5f5aeb9 100644--- a/sdks/typescript/src/agents/destinations.ts+++ b/sdks/typescript/src/agents/destinations.ts@@ -15,7 +15,10 @@ export interface CreateDestinationParams {export interface UpdateDestinationParams {enabled?: boolean;level?: Level;- types?: string[];+ /** Pass `null` to clear the allow-list (deliver all types). */+ types?: string[] | null;+ url?: string;+ includeRaw?: boolean;secret?: string;}@@ -45,7 +48,7 @@ export class Destinations {export class Deliveries {constructor(private readonly http: Http, private readonly sessionId: string) {}- async list(params: { destination?: string; status?: DeliveryStatus } = {}): Promise<Delivery[]> {+ async list(params: { destination?: string; status?: DeliveryStatus; after?: string; limit?: number } = {}): Promise<Delivery[]> {const r = await this.http.request<{ data?: Delivery[] } | Delivery[]>("GET", `/sessions/${this.sessionId}/deliveries`, { query: params as Query },);diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.tsindex 67e82933..75002eae 100644--- a/sdks/typescript/src/agents/index.ts+++ b/sdks/typescript/src/agents/index.ts@@ -1,7 +1,7 @@export { OpenComputer, type OpenComputerOptions } from "./client.js";export { connectSession, type ConnectSessionOptions } from "./connect.js";-export { Sessions, Session } from "./sessions.js";+export { Sessions, Session, ClientSession } 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";diff --git a/sdks/typescript/src/agents/normalize.ts b/sdks/typescript/src/agents/normalize.tsindex 1c304e17..296d1938 100644--- a/sdks/typescript/src/agents/normalize.ts+++ b/sdks/typescript/src/agents/normalize.ts@@ -29,8 +29,10 @@ export function normalize<T = any>(value: unknown): 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.+// snake_case). Values are left untouched, and opaque/user-owned subtrees (raw, body,+// metadata, refs, input) are passed through without key-mangling.const snakeKey = (k: string): string => k.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());+const OPAQUE = new Set(["raw", "body", "metadata", "refs", "input"]);export function serialize(value: unknown): unknown {if (Array.isArray(value)) return value.map((v) => serialize(v));@@ -38,7 +40,7 @@ export function serialize(value: unknown): unknown {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);+ out[sk] = OPAQUE.has(sk) ? v : serialize(v);}return out;}diff --git a/sdks/typescript/src/agents/sessions.ts b/sdks/typescript/src/agents/sessions.tsindex 3331acd7..73924b38 100644--- a/sdks/typescript/src/agents/sessions.ts+++ b/sdks/typescript/src/agents/sessions.ts@@ -11,7 +11,11 @@ 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; types?: string[]; includeRaw?: boolean; enabled?: boolean }>;+ /**+ * Inline webhook destinations. These can't carry a signing `secret` — to sign+ * deliveries, register the destination with `session.destinations.create({ secret })`.+ */+ destinations?: Array<{ url: 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;@@ -34,15 +38,10 @@ 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 { idempotencyKey, ...body } = params;const r = await this.http.request<{ session: SessionData; clientToken?: string }>("POST", "/sessions",- { body, idempotencyKey, idempotent: Boolean(idempotencyKey || rest.key) },+ { body, idempotencyKey, idempotent: Boolean(idempotencyKey || params.key) },);return new Session(this.http, r.session, r.clientToken);}@@ -55,41 +54,18 @@ export class Sessions {}/**- * A handle to one session. Returned by `sessions.create`/`get` (org key) and by- * `connectSession` (browser, client token) — same type, both auth modes.+ * Read + steer surface for one session. Works with a session **client token** (browser-safe,+ * `read`+`steer` scopes) or an org key, and is what `connectSession` returns. For management+ * (lifecycle, destinations, deliveries, minting tokens) use the full {@link Session} returned+ * by `sessions.create`/`get` with the org key.*/-export class Session {- /** Present after create / connectSession — safe to hand to a browser. */- readonly clientToken?: string;- /** Webhook destinations + delivery records for this session (management — need the org key). */- readonly destinations: Destinations;- readonly deliveries: Deliveries;- private data: SessionData;-- constructor(private readonly http: Http, data: SessionData, clientToken?: string) {- this.data = data;- this.clientToken = clientToken;- this.destinations = new Destinations(http, data.id);- this.deliveries = new Deliveries(http, data.id);- }-- 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;- }+export class ClientSession {+ constructor(protected readonly http: Http, readonly id: string, readonly clientToken?: string) {}/*** 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) { … } }+ * (default 0) on first connect.*/async *events(opts: StreamOptions = {}): AsyncGenerator<Event> {let after = opts.after ?? 0;@@ -137,16 +113,6 @@ export class Session {return this.http.request("GET", `/sessions/${this.id}/messages`, { query: opts as Query });}- /** Per-turn history (timing + outcome). */- turns(): Promise<Turn[]> {- return this.http- .request<{ data?: Turn[] } | Turn[]>("GET", `/sessions/${this.id}/turns`)- .then((r) => (Array.isArray(r) ? r : r.data ?? []));- }- turn(turnId: string): Promise<Turn> {- return this.http.request("GET", `/sessions/${this.id}/turns/${turnId}`);- }-/** 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 } }>(@@ -155,6 +121,43 @@ export class Session {);return r.event;}+}++/**+ * Full handle to one session — everything in {@link ClientSession} plus management+ * (lifecycle, destinations, deliveries, client tokens). Needs the **org key**; returned by+ * `sessions.create`/`get`.+ */+export class Session extends ClientSession {+ /** Webhook destinations + delivery records for this session (org key). */+ readonly destinations: Destinations;+ readonly deliveries: Deliveries;+ private data: SessionData;++ constructor(http: Http, data: SessionData, clientToken?: string) {+ super(http, data.id, clientToken);+ this.data = data;+ this.destinations = new Destinations(http, data.id);+ this.deliveries = new Deliveries(http, 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;+ }++ /** Per-turn history (timing + outcome), paginated. */+ turns(opts: { after?: string; limit?: number } = {}): Promise<ListPage<Turn>> {+ return this.http.request("GET", `/sessions/${this.id}/turns`, { query: opts as Query });+ }+ turn(turnId: string): Promise<Turn> {+ return this.http.request("GET", `/sessions/${this.id}/turns/${turnId}`);+ }/** The resolved final result + last-turn summary. */result(): Promise<{ lastTurn?: LastTurn | null; result?: Event | null }> {diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.tsindex f835e81a..f9ac4629 100644--- a/sdks/typescript/src/agents/types.ts+++ b/sdks/typescript/src/agents/types.ts@@ -11,7 +11,7 @@ export interface Limits { tokens?: number; turnSeconds?: number; turns?: number;export interface Actor {id?: string;- kind?: "human" | "agent" | "system" | (string & {});+ type?: "human" | "agent" | "system" | (string & {});display?: string;}@@ -67,6 +67,7 @@ export interface Credential {provider: string;name?: string;last4?: string;+ isDefault?: boolean;createdAt?: string;}