Skip to content

An open-source, faster Devin alternative

TypeScript

sdk: one management client on a portable subpath; retire the /v3 client; client-owned transport

Igor Zalutski329552efe44f
diff --git a/sdks/typescript/CHANGELOG.md b/sdks/typescript/CHANGELOG.md
new file mode 100644
index 00000000..3154eba6
--- /dev/null
+++ b/sdks/typescript/CHANGELOG.md
@@ -0,0 +1,29 @@
+# Changelog
+
+## 2.0.0
+
+Breaking. The `OpenComputer` class that wrapped the Durable Agent Sessions
+API at `api.opencomputer.dev/v3`, `connectSession`, and their agents,
+sessions, credentials, repos, GitHub apps, hooks, watches, schedules and
+destinations resources are removed. Customers of that API pin the last
+published version that has it, `1.1.1`.
+
+- `@opencomputer/sdk/managed-agents` is a new subpath export: the
+ `OpenComputer` client for the Serverless Agents management API at
+ `app.opencomputer.dev/api/managed-agents`, mirroring the documented routes
+ (`sessions`, `sessions.turns`, `sessions.events`, `projects`,
+ `projects.memory`, `projects.webhooks`, `projects.eventSubscriptions`,
+ `projects.github`, `agents`, `deployments`), with one `OpenComputerError`
+ of `{ code, status, message }`. Its module graph has no Node dependency and
+ runs nothing at import, so it loads in Cloudflare Workers without Node
+ compatibility.
+- `startSessionOnDocument`, the memory types and the event subscription types
+ move to that subpath; `oc.sessions.startOnDocument` is the same call on the
+ client. Its `NotFoundError` and `ConflictError` become `OpenComputerError`
+ with codes `memory_document_deleted` and `idempotency_key_reused`.
+- The package root keeps the sandbox client and `verifyWebhook`. Importing it
+ no longer replaces Node's global fetch dispatcher and no longer opens
+ connections: the sandbox client owns its HTTP/2 pool and passes it to each
+ request, creates it on the first request, and warms it on the first
+ `Sandbox.create`. Programs that measured creates after a bare import call the
+ exported `prewarmConnections()` before their loop.
diff --git a/sdks/typescript/README.md b/sdks/typescript/README.md
index 2bec0f63..5704c05b 100644
--- a/sdks/typescript/README.md
+++ b/sdks/typescript/README.md
@@ -1,8 +1,8 @@
# @opencomputer/sdk
-The official TypeScript SDK for [OpenComputer](https://github.com/diggerhq/opencomputer): **cloud sandboxes** and **Durable Agent Sessions** (managed background agents).
+The official TypeScript SDK for [OpenComputer](https://github.com/diggerhq/opencomputer): the **cloud sandbox** client at the package root, and the **Serverless Agents** management client on the portable `@opencomputer/sdk/managed-agents` subpath.
-> This one package covers both surfaces — install **`@opencomputer/sdk`**. (The older `@opencomputer/agents-sdk` is superseded; use this instead.)
+> Versions before 2.0.0 also carried a client for the retired Durable Agent Sessions API; see [CHANGELOG](./CHANGELOG.md).
## Install
@@ -29,156 +29,46 @@ const content = await sandbox.files.read("/tmp/test.txt");
await sandbox.kill();
```
-## Durable Agent Sessions
+## Serverless Agents management client
-Run a managed background agent: define an agent once, then create sessions that stream durable events and call back on completion.
+Serverless Agents (`opencomputer deploy`) are managed over the [management API](https://opencomputer.dev/agents/api). The client for it is a separate subpath export whose module graph has no Node dependency and runs nothing at import, so the same code serves a Cloudflare Worker without Node compatibility, Vercel, Deno and Node. Use it from trusted server code; the API key must not reach a browser.
```typescript
-import { OpenComputer, verifyWebhook } from "@opencomputer/sdk";
+import { OpenComputer, OpenComputerError } from "@opencomputer/sdk/managed-agents";
const oc = new OpenComputer({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
-// Bootstrap once — idempotent by name (safe on every deploy):
-const agent = await oc.agents.create({
- name: "reviewer",
- runtime: "claude", // or "codex"
- model: "anthropic/claude-opus-4-8",
- prompt: "Review the diff. Run tests. Explain risks.",
- credential: "managed", // run via OpenComputer, billed to credits — no key
- // …or bring your own: key: process.env.ANTHROPIC_API_KEY! (sealed; never enters the sandbox)
-});
-
-// Per request — hand off durable work, route the callback via metadata:
-const session = await oc.sessions.create({
- agent: agent.id,
- input: "Review PR #42",
- metadata: { pullNumber: 42 }, // echoed back verbatim in the webhook
- idempotencyKey: deliveryId, // retry-safe
-});
-// Register a SIGNED callback (inline create-time destinations can't carry a secret):
-await session.destinations.create({ url: "https://app.example.com/oc-callback", secret: process.env.OC_WEBHOOK_SECRET! });
-
-// In your webhook handler — verify the signature, then fetch the result:
-const delivery = await verifyWebhook(rawBody, request.headers, process.env.OC_WEBHOOK_SECRET!);
-if (delivery.type === "turn.completed") {
- const session = await oc.sessions.get(delivery.sessionId!);
- const { result } = await session.result();
-}
-```
-
-### Invoke through an Agent URL
-
-Every agent has a permanent HTTP address. Use it from a trusted backend with
-your org API key; the accepted response includes a session-scoped token for
-streaming or steering that session.
-
-```typescript
-const agent = await oc.agents.get("agt_...");
-const response = await fetch(`${agent.invokeUrl}/`, {
- method: "POST",
- headers: {
- Authorization: `Bearer ${process.env.OPENCOMPUTER_API_KEY}`,
- "Content-Type": "application/json",
- "Idempotency-Key": "incoming-event-id",
- },
- body: JSON.stringify({ task: "Review PR #42" }),
-});
-const receipt = await response.json();
-console.log(receipt.session.id);
-```
-
-For an external system that cannot hold an org key, create an independently
-revocable Hook URL. The complete URL is returned only once.
-
-```typescript
-const created = await oc.agents.hooks.create(agent.id, {
- name: "grafana-prod",
-});
-console.log(created.hookUrl);
-```
-
-[Agent URL guide](https://docs.opencomputer.dev/agent-sessions/agent-urls) ·
-[Hook URL guide](https://docs.opencomputer.dev/agent-sessions/hooks)
-
-### Create an agent from a repository
-
-Repository creation is a two-phase review/import so a moving branch cannot change underneath the
-confirmation. Only an exact review is importable; invalid or unrecognized source should be fixed or
-reviewed at another root.
-
-```typescript
-const review = await oc.agents.repository.review({
- repo: "repo_...",
- path: "agents/support",
- productionRef: "main",
-});
-
-if (review.interpretation.disposition !== "exact") {
- throw new Error(review.interpretation.summary);
-}
-
-const { agent, deployment } = await oc.agents.repository.import({
- name: "Support triage",
- credential: "managed",
- idempotencyKey: crypto.randomUUID(),
- source: {
- type: "github",
- repo: review.repository.id,
- path: review.root,
- productionRef: review.productionRef,
- },
- review: {
- sha: review.sha,
- sourceProfile: review.interpretation.sourceProfile,
- fingerprint: review.reviewFingerprint,
- },
-});
-```
-
-### Configure repository access
-
-Flue agents can use repositories granted to your OpenComputer GitHub App as working sources. Read
-the current grant and policy, or narrow the agent to explicit repository ids from that view:
-
-```typescript
-const access = await oc.agents.getRepositoryAccess(agent.id);
-const target = access.effectiveRepositories?.find(
- (repo) => repo.fullName === "your-org/your-repo",
+// Create a session, then admit its first turn; one key per call makes a retry safe.
+const { session } = await oc.sessions.create(
+ { agentId: "worker@development", labels: { request: taskId } },
+ { idempotencyKey: taskId },
);
-if (!target) throw new Error("Repository is not currently available to this agent");
-
-await oc.agents.updateRepositoryAccess(agent.id, {
- mode: "selected",
- repositoryIds: [target.id],
+const receipt = await oc.sessions.turns.send(session.id, {
+ input: "Review the pull request.",
+ idempotencyKey: `${taskId}/start`,
});
-```
-Use `{ mode: "all" }` for every currently and subsequently granted repository, or
-`{ mode: "selected", repositoryIds: [] }` to disable repository work. An `unavailable` grant has
-`effectiveRepositories: null`; an empty array is a successfully read, known-empty view.
+// Follow the durable event log from a cursor.
+const events = await oc.sessions.events.list(session.id, { after: 0 });
-### Credentials
+// List rows, filtered and paged.
+const page = await oc.sessions.list({ environment: "development", limit: 20 });
-Sessions run **Managed** (via OpenComputer, billed to your credits — `credential: "managed"`, no key, the default for new orgs) or on **your own** model-provider key (Anthropic for `claude`, OpenAI for `codex`). An inline `key` stores one and attaches it to the agent; manage keys directly to reuse one across agents, set an org default, or rotate/remove:
-
-```typescript
-await oc.credentials.create({ provider: "anthropic", key: process.env.ANTHROPIC_API_KEY!, name: "prod", isDefault: true });
-const creds = await oc.credentials.list(); // metadata only — keys are write-only
-await oc.credentials.setDefault({ credential: creds[0].id });
-await oc.credentials.delete(creds[0].id);
+try {
+ await oc.sessions.get("missing");
+} catch (error) {
+ if (error instanceof OpenComputerError) console.log(error.code, error.status, error.message);
+}
```
-Or reference one by id when creating an agent: `oc.agents.create({ …, credential: "cred_…" })`. A key isn't required — `credential: "managed"` needs none; a session fails with `422 no_credential` only when it resolves to neither Managed nor a usable key. Full guide: [Credentials](https://docs.opencomputer.dev/agent-sessions/credentials).
+The method tree mirrors the API one to one: `sessions.create|get|list|end|interrupt|setLabels|startOnDocument`, `sessions.turns.send`, `sessions.events.list`, `projects.list|get|create`, `projects.memory`, `projects.webhooks`, `projects.eventSubscriptions`, `projects.github.repositories`, `agents.list`, `deployments.get|list`. Every failed call throws `OpenComputerError` with `{ code, status, message }`.
-### Serverless Agents memory
+### Start a session on a memory document
-Serverless Agents (`opencomputer deploy`) keep notes in [memory](https://opencomputer.dev/agents/memory). This package types its management API and ships one helper for the moment an application opens a topic: create the document if it is new, then create a session bound to it, both converging under one key on retry:
+Applications that keep notes in [memory](https://opencomputer.dev/agents/memory) open a topic as "these notes, this session". `oc.sessions.startOnDocument` creates the document if it is new, then a session bound to it, both converging under one key on retry:
```typescript
-import { startSessionOnDocument } from "@opencomputer/sdk";
-
-const { document, session } = await startSessionOnDocument({
- apiKey: process.env.OPENCOMPUTER_API_KEY!,
+const { document, session } = await oc.sessions.startOnDocument({
projectId: "prj_…", environment: "development", agent: "topic-worker",
resource: "topics", documentId: "workshop", document: { title: "Workshop" },
idempotencyKey: `topic/workshop/${deploymentId}`,
@@ -186,9 +76,11 @@ const { document, session } = await startSessionOnDocument({
// document.created, session.created: false when they already existed.
```
+`startSessionOnDocument({ apiKey, ...params })` from the same subpath is the standalone form of the call.
+
## Sandbox webhooks (Preview)
-Subscribe to sandbox lifecycle events (`sandbox.ready`, `sandbox.stopped`, …) — signed, retried, and redeliverable. The same `verifyWebhook` helper verifies both session and sandbox deliveries. **Preview: newly available; the surface may change.**
+Subscribe to sandbox lifecycle events (`sandbox.ready`, `sandbox.stopped`, …) — signed, retried, and redeliverable. `verifyWebhook` checks a delivery's signature and returns its envelope. **Preview: newly available; the surface may change.**
```typescript
import { Webhooks, verifyWebhook, type SandboxLifecycleEvent } from "@opencomputer/sdk";
@@ -217,12 +109,15 @@ if (delivery.type === "sandbox.stopped") {
| `apiUrl` | `OPENCOMPUTER_API_URL` | `https://app.opencomputer.dev` |
| `apiKey` | `OPENCOMPUTER_API_KEY` | (none) |
-**Durable Agent Sessions** (`OpenComputer`):
+**Serverless Agents** (`OpenComputer` from `@opencomputer/sdk/managed-agents`):
+
+| Option | Default |
+|-----------|----------------------------------------------------|
+| `baseUrl` | `https://app.opencomputer.dev/api/managed-agents` |
+| `apiKey` | required |
+| `fetch` | the global `fetch` |
-| Option | Env Variable | Default |
-|-----------|------------------------|------------------------------------|
-| `baseUrl` | — | `https://api.opencomputer.dev/v3` |
-| `apiKey` | `OPENCOMPUTER_API_KEY` | (none) |
+Importing the package root installs nothing globally and opens no connection. The sandbox client keeps its own HTTP/2 pool, created on the first request and warmed on the first `Sandbox.create`; call `prewarmConnections()` earlier to pay that cost before a timing loop.
## Releasing
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index cb533548..086a00de 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/sdk",
- "version": "1.1.1",
+ "version": "2.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "1.1.1",
+ "version": "2.0.0",
"license": "MIT",
"dependencies": {
"undici": "^6.0.0 || ^7.0.0"
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 7935221b..edf56adc 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,7 +1,7 @@
{
"name": "@opencomputer/sdk",
- "version": "1.1.1",
- "description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
+ "version": "2.0.0",
+ "description": "TypeScript SDK for OpenComputer - cloud sandboxes and the Serverless Agents management API",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@@ -10,6 +10,10 @@
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
+ "./managed-agents": {
+ "types": "./dist/managed-agents/index.d.ts",
+ "import": "./dist/managed-agents/index.js"
+ },
"./node": {
"types": "./dist/node.d.ts",
"import": "./dist/node.js"
diff --git a/sdks/typescript/src/agent.ts b/sdks/typescript/src/agent.ts
index a2eba8c9..47674b54 100644
--- a/sdks/typescript/src/agent.ts
+++ b/sdks/typescript/src/agent.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
import { openWebSocket } from "./websocket.js";
export interface SandboxAgentEvent {
type:
@@ -83,7 +84,7 @@ export class SandboxAgent {
if (opts.mcpServers) body.mcpServers = opts.mcpServers;
if (opts.resume) body.resume = opts.resume;
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/agent`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/agent`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body),
@@ -224,7 +225,7 @@ export class SandboxAgent {
const body: Record<string, unknown> = {};
if (signal != null) body.signal = signal;
- const resp = await fetch(`${agent.apiUrl}/sandboxes/${agent.sandboxId}/agent/${sessionId}/kill`, {
+ const resp = await apiFetch(`${agent.apiUrl}/sandboxes/${agent.sandboxId}/agent/${sessionId}/kill`, {
method: "POST",
headers: agent.headers,
body: JSON.stringify(body),
@@ -242,7 +243,7 @@ export class SandboxAgent {
}
async list(): Promise<Array<{ sessionID: string; sandboxID: string; running: boolean; startedAt: string }>> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/agent`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/agent`, {
headers: this.headers,
});
diff --git a/sdks/typescript/src/agents/agents.test.ts b/sdks/typescript/src/agents/agents.test.ts
deleted file mode 100644
index 6f7b2674..00000000
--- a/sdks/typescript/src/agents/agents.test.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { OpenComputer } from "./client.js";
-
-describe("Agents Slack", () => {
- it("exposes the builder-owned app deep link", async () => {
- const fetcher = vi.fn(async () =>
- Response.json({
- id: "sla_1",
- agent_id: "agt_1",
- status: "active",
- slack_app_id: "A1",
- team_id: "T1",
- open_url: "https://slack.com/app_redirect?app=A1&team=T1",
- }),
- );
- const oc = new OpenComputer({
- apiKey: "test-key",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher as typeof fetch,
- maxRetries: 0,
- });
-
- const result = await oc.agents.getSlack("agt_1");
-
- expect(result.openUrl).toBe(
- "https://slack.com/app_redirect?app=A1&team=T1",
- );
- });
-
- it("starts OAuth with validated deployment return context", async () => {
- const fetcher = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) =>
- Response.json({
- mode: "managed",
- status: "pending",
- authorize_url: "https://slack.com/oauth/v2/authorize?state=opaque",
- expires_at: "2026-07-16T18:00:00Z",
- }),
- );
- const oc = new OpenComputer({
- apiKey: "test-key",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher as typeof fetch,
- maxRetries: 0,
- });
-
- const result = await oc.agents.authorizeManagedSlack("agt_1", {
- returnDeploymentId: "dep_1",
- });
-
- expect("authorizeUrl" in result).toBe(true);
- expect("authorizeUrl" in result ? result.authorizeUrl : undefined).toContain(
- "slack.com/oauth/v2/authorize",
- );
- expect(fetcher).toHaveBeenCalledWith(
- "https://api.example.test/v3/agents/agt_1/slack/managed/authorize",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({ return_deployment_id: "dep_1" }),
- }),
- );
- });
-
- it("reads the browser-safe managed connection", async () => {
- const fetcher = vi.fn(async () =>
- Response.json({
- mode: "managed",
- status: "active",
- workspace: { id: "T1", name: "Acme" },
- app: { id: "A1", handle: "OpenComputer" },
- open_url: "https://slack.com/app_redirect?app=A1&team=T1",
- connected_at: "2026-07-16T17:00:00Z",
- }),
- );
- const oc = new OpenComputer({
- apiKey: "test-key",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher as typeof fetch,
- maxRetries: 0,
- });
-
- const result = await oc.agents.getManagedSlack("agt_1");
-
- expect(result).toMatchObject({
- mode: "managed",
- status: "active",
- openUrl: "https://slack.com/app_redirect?app=A1&team=T1",
- });
- expect(JSON.stringify(result)).not.toContain("xoxb-");
- });
-
- it("returns an already-active connection from a raced authorize", async () => {
- const fetcher = vi.fn(async () =>
- Response.json({
- mode: "managed",
- status: "active",
- workspace: { id: "T1", name: "Acme" },
- app: { id: "A1", handle: "OpenComputer" },
- open_url: "https://slack.com/app_redirect?app=A1&team=T1",
- connected_at: "2026-07-16T17:00:00Z",
- }),
- );
- const oc = new OpenComputer({
- apiKey: "test-key",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher as typeof fetch,
- maxRetries: 0,
- });
-
- const result = await oc.agents.authorizeManagedSlack("agt_1");
-
- expect(result).toMatchObject({ status: "active" });
- expect("openUrl" in result ? result.openUrl : undefined).toContain(
- "slack.com/app_redirect",
- );
- });
-
- it("lists current owner workspace claims before OAuth", async () => {
- const fetcher = vi.fn(async () =>
- Response.json({
- data: [
- {
- mode: "managed",
- status: "active",
- workspace: { id: "T1", name: "Acme" },
- app: { id: "A1", handle: "OpenComputer" },
- open_url: "https://slack.com/app_redirect?app=A1&team=T1",
- connected_at: "2026-07-16T17:00:00Z",
- agent: { id: "agt_1", name: "Support triage" },
- },
- ],
- }),
- );
- const oc = new OpenComputer({
- apiKey: "test-key",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher as typeof fetch,
- maxRetries: 0,
- });
-
- const result = await oc.agents.listManagedSlackConnections();
-
- expect(result.data[0]).toMatchObject({
- workspace: { id: "T1", name: "Acme" },
- agent: { id: "agt_1", name: "Support triage" },
- });
- expect(fetcher).toHaveBeenCalledWith(
- "https://api.example.test/v3/slack/managed/connections",
- expect.objectContaining({ method: "GET" }),
- );
- });
-
- it("disconnects the managed connection without uninstalling the app", async () => {
- const fetcher = vi.fn(async () =>
- Response.json({ ok: true, status: "disconnected" }),
- );
- const oc = new OpenComputer({
- apiKey: "test-key",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher as typeof fetch,
- maxRetries: 0,
- });
-
- await expect(
- oc.agents.disconnectManagedSlack("agt_1"),
- ).resolves.toEqual({ ok: true, status: "disconnected" });
- expect(fetcher).toHaveBeenCalledWith(
- "https://api.example.test/v3/agents/agt_1/slack/managed",
- expect.objectContaining({ method: "DELETE" }),
- );
- });
-});
diff --git a/sdks/typescript/src/agents/agents.ts b/sdks/typescript/src/agents/agents.ts
deleted file mode 100644
index f1592796..00000000
--- a/sdks/typescript/src/agents/agents.ts
+++ /dev/null
@@ -1,298 +0,0 @@
-import type { Http, Query } from "./http.js";
-import type { Agent, CredentialRef, Limits, Runtime } from "./types.js";
-import {
- Deployments, Revisions, Activations, Skills, DeploymentSourceResource,
- type Deployment, type InlineSkillFile,
-} from "./deployments.js";
-import { Schedules } from "./schedules.js";
-import { AgentRepository } from "./repository-agents.js";
-import { AgentHooks } from "./hooks.js";
-
-export interface CreateAgentParams {
- name: string;
- prompt: string;
- /** `provider/model` id; the provider must be one the runtime can drive (`anthropic/…` for `claude`, `openai/…` for `codex`, any catalog provider for `pi`). */
- model: string;
- /** Defaults to `claude`. Determines which providers the model may use (see `model`); immutable after create. */
- runtime?: Runtime;
- /** Model provider key, stored as a sealed credential — Anthropic for `claude`, OpenAI for `codex`, the model's provider for `pi`. Mutually exclusive with `credential`. */
- key?: string;
- /** Model source: `"managed"` (run via OpenComputer, no provider key) or a `cred_…` id. Omit for the org default. Mutually exclusive with `key`. */
- credential?: CredentialRef;
- limits?: Limits;
-}
-
-export interface UpdateAgentParams {
- prompt?: string;
- /** Stay within what the agent's runtime can drive (`anthropic/…` for `claude`, `openai/…` for `codex`, any catalog provider for `pi`); the runtime itself is immutable. */
- model?: string;
- key?: string;
- /** Re-point the model source: `"managed"`, a `cred_…` id, or `null` to clear (org default). Mutually exclusive with `key`. */
- credential?: CredentialRef | null;
- limits?: Limits;
-}
-
-export interface Page<T> { data: T[]; nextCursor?: string | null; }
-
-/** The Slack app manifest to create in Slack (from `slackManifest`). */
-export interface SlackManifest {
- manifest: Record<string, unknown>;
- createUrl: string;
- steps?: unknown;
- status: string;
-}
-
-/** A Slack connection's public state — never carries the bot token / signing secret. */
-export interface SlackConnection {
- id: string;
- agentId: string;
- status: string; // pending | active | revoked | error
- slackAppId?: string | null;
- teamId?: string | null;
- accountLogin?: string | null;
- openUrl?: string | null;
-}
-
-/** The three values pasted back from Slack to finalize a connection. */
-export interface ConnectSlackParams {
- appId: string;
- botToken: string;
- signingSecret: string;
-}
-
-/** One browser-safe OAuth start for the OpenComputer-operated Slack app. */
-export interface ManagedSlackAuthorization {
- mode: "managed";
- status: "pending";
- authorizeUrl: string;
- expiresAt: string;
-}
-
-/** Public state for the OpenComputer-operated Slack app. Never includes credentials. */
-export interface ManagedSlackConnection {
- mode: "managed";
- status: "active" | "disconnected" | "error" | "revoked";
- workspace?: { id: string; name?: string | null } | null;
- app?: { id: string; handle?: string | null } | null;
- openUrl?: string | null;
- connectedAt?: string | null;
- errorCode?: string | null;
-}
-
-/** One current owner-scoped workspace claim for pre-OAuth conflict discovery. */
-export interface ManagedSlackWorkspaceConnection extends ManagedSlackConnection {
- agent: { id: string; name: string };
-}
-
-/** Which repositories an agent may use as working sources. */
-export type RepositoryAccessPolicy =
- | { mode: "all" }
- | { mode: "selected"; repositoryIds: string[] };
-
-/** Current state of the owner-bound OpenComputer GitHub App grant. */
-export interface RepositoryAccessGrant {
- status: "active" | "not_installed" | "unavailable";
- account: string | null;
- repositorySelection: "all" | "selected" | null;
- installUrl: string;
- configureUrl: string | null;
- truncated: boolean;
-}
-
-/** One repository currently usable under both the GitHub grant and agent policy. */
-export interface RepositoryAccessRepository {
- id: string;
- fullName: string;
- defaultBranch: string;
- private: boolean;
-}
-
-/** A selected repository absent from the current complete GitHub grant view. */
-export interface UnavailableSelectedRepository {
- id: string;
- fullName: string;
-}
-
-/** Agent policy composed with the owner's current GitHub App grant. */
-export interface RepositoryAccess {
- policy: RepositoryAccessPolicy;
- grant: RepositoryAccessGrant;
- /** `null` means the grant could not be read; an empty array is a known-empty view. */
- effectiveRepositories: RepositoryAccessRepository[] | null;
- /** Authoritative only when `grant.truncated` is false. */
- unavailableSelectedRepositories: UnavailableSelectedRepository[];
-}
-
-/** Reusable agents — the "what" a session runs. */
-export class Agents {
- /** Deploy behavior (inline or from a linked repo) — each deployment produces a revision. */
- readonly deployments: Deployments;
- /** Immutable, numbered revisions + rollback / promote (set the active revision). */
- readonly revisions: Revisions;
- /** Active-pointer audit log. */
- readonly activations: Activations;
- /** The active revision's skills (zip upload / remove). */
- readonly skills: Skills;
- /** Repo linkage for push-to-deploy. */
- readonly deploymentSource: DeploymentSourceResource;
- /** Cron for agents — schedules that fire a session per slot (015). */
- readonly schedules: Schedules;
- /** Review and import an agent from an existing repository. */
- readonly repository: AgentRepository;
- /** Named, revocable URLs for external systems that should only start this agent. */
- readonly hooks: AgentHooks;
-
- constructor(private readonly http: Http) {
- this.deployments = new Deployments(http);
- this.revisions = new Revisions(http);
- this.activations = new Activations(http);
- this.skills = new Skills(http);
- this.deploymentSource = new DeploymentSourceResource(http);
- this.schedules = new Schedules(http);
- this.repository = new AgentRepository(http);
- this.hooks = new AgentHooks(http);
- }
-
- create(params: CreateAgentParams): Promise<Agent> {
- // Idempotent by name server-side → safe to auto-retry transient failures.
- return this.http.request("POST", "/agents", { body: params, idempotent: true });
- }
- 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 });
- }
-
- // ── Working repositories (agent policy ∩ owner GitHub App grant) ──
-
- /** Read the agent's working-repository policy and current effective grant view. */
- getRepositoryAccess(agentId: string): Promise<RepositoryAccess> {
- return this.http.request("GET", `/agents/${agentId}/repository-access`);
- }
-
- /** Atomically replace the agent's working-repository policy. */
- updateRepositoryAccess(
- agentId: string,
- policy: RepositoryAccessPolicy,
- ): Promise<RepositoryAccess> {
- return this.http.request("PUT", `/agents/${agentId}/repository-access`, {
- body: policy,
- idempotent: true,
- });
- }
-
- // ── Slack (give the agent its own @handle; BYO app, 1 app ⟷ 1 agent ⟷ 1 workspace) ──
-
- /** Start the connect intent → returns the app manifest to create in Slack. Pass
- * `reconnect: true` to replace an already-active connection (otherwise 409). */
- slackManifest(id: string, opts: { reconnect?: boolean } = {}): Promise<SlackManifest> {
- return this.http.request("POST", `/agents/${id}/slack/manifest`, { body: opts });
- }
- /** Finalize the connection with the three values Slack shows after install.
- * (The HTTP layer converts appId → app_id, etc. on the wire.) */
- connectSlack(id: string, params: ConnectSlackParams): Promise<SlackConnection> {
- return this.http.request("POST", `/agents/${id}/slack`, { body: params });
- }
- /** Current connection (no secrets). */
- getSlack(id: string): Promise<SlackConnection> {
- return this.http.request("GET", `/agents/${id}/slack`);
- }
- /** Disconnect — purges the stored secrets and stops routing. */
- disconnectSlack(id: string): Promise<{ ok: boolean }> {
- return this.http.request("DELETE", `/agents/${id}/slack`);
- }
-
- // ── Managed Slack (OpenComputer-operated onboarding app) ──
-
- /** Start managed Slack OAuth. The optional deployment id is validated return
- * context, never a caller-controlled redirect. */
- authorizeManagedSlack(
- id: string,
- opts: { returnDeploymentId?: string } = {},
- ): Promise<ManagedSlackAuthorization | ManagedSlackConnection> {
- return this.http.request("POST", `/agents/${id}/slack/managed/authorize`, {
- body: opts,
- });
- }
- /** Current managed installation/connection state. */
- getManagedSlack(id: string): Promise<ManagedSlackConnection> {
- return this.http.request("GET", `/agents/${id}/slack/managed`);
- }
- /** Current workspaces already routed to this owner's agents. */
- listManagedSlackConnections(): Promise<Page<ManagedSlackWorkspaceConnection>> {
- return this.http.request("GET", "/slack/managed/connections");
- }
- /** Disconnect this agent without uninstalling the shared app from Slack. */
- disconnectManagedSlack(id: string): Promise<{ ok: true; status: "disconnected" }> {
- return this.http.request("DELETE", `/agents/${id}/slack/managed`);
- }
-
- /**
- * Node-only sugar: bundle a local agent directory (`agent.toml` + `prompt.md` + optional
- * `skills/`) and deploy it inline. Resolve the target agent from `opts.agentId` or the manifest's
- * `[agent].id`. Uses dynamic `node:fs`/`node:path` imports so the browser build never loads them.
- */
- async deploy(dir = ".", opts: { agentId?: string; activate?: boolean } = {}): Promise<{ deployment: Deployment }> {
- const fs = await import("node:fs/promises");
- const path = await import("node:path");
- const read = (rel: string) => fs.readFile(path.join(dir, rel), "utf8");
-
- let toml = "";
- try { toml = await read("agent.toml"); } catch { /* optional when agentId is passed */ }
- const agentId = opts.agentId ?? tomlSectionValue(toml, "agent", "id");
- if (!agentId) throw new Error("oc.agents.deploy: pass { agentId } or set [agent].id in agent.toml");
-
- let prompt: string;
- try { prompt = await read("prompt.md"); }
- catch { throw new Error("oc.agents.deploy: prompt.md is required in the agent directory"); }
- const model = tomlTopLevel(toml, "model");
-
- const skills: InlineSkillFile[] = [];
- await walkSkills(fs, path, path.join(dir, "skills"), path.join(dir, "skills"), skills);
-
- return this.deployments.create(agentId, {
- input: { type: "inline", prompt, model, skills: skills.length ? skills : undefined },
- activate: opts.activate,
- });
- }
-}
-
-// ── agent.toml helpers (minimal — the manifest is flat; no TOML dep) ──
-
-/** A top-level `key = "value"` before the first [section]. */
-function tomlTopLevel(toml: string, key: string): string | undefined {
- const head = toml.split(/^\s*\[/m)[0];
- return new RegExp(`^\\s*${key}\\s*=\\s*["']([^"']*)["']`, "m").exec(head)?.[1];
-}
-
-/** A `key = "value"` inside `[section]`. */
-function tomlSectionValue(toml: string, section: string, key: string): string | undefined {
- const sec = new RegExp(`\\[${section}\\]([\\s\\S]*?)(?:\\n\\s*\\[|$)`).exec(toml)?.[1];
- if (!sec) return undefined;
- return new RegExp(`^\\s*${key}\\s*=\\s*["']([^"']*)["']`, "m").exec(sec)?.[1];
-}
-
-/** Recursively read `skills/` into InlineSkillFile[] (paths relative to the skills root). */
-async function walkSkills(
- fs: typeof import("node:fs/promises"),
- path: typeof import("node:path"),
- root: string,
- dir: string,
- out: InlineSkillFile[],
-): Promise<void> {
- let entries: import("node:fs").Dirent[];
- try { entries = await fs.readdir(dir, { withFileTypes: true }); }
- catch { return; } // no skills/ directory
- for (const e of entries) {
- const full = path.join(dir, e.name);
- if (e.isDirectory()) { await walkSkills(fs, path, root, full, out); continue; }
- if (!e.isFile()) continue;
- const content = await fs.readFile(full, "utf8");
- const st = await fs.stat(full);
- out.push({ path: path.relative(root, full).split(path.sep).join("/"), content, mode: (st.mode & 0o111) ? 0o755 : 0o644 });
- }
-}
diff --git a/sdks/typescript/src/agents/client.ts b/sdks/typescript/src/agents/client.ts
deleted file mode 100644
index 52ff9fe8..00000000
--- a/sdks/typescript/src/agents/client.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { Http, type HttpOptions } from "./http.js";
-import { Agents } from "./agents.js";
-import { Sessions } from "./sessions.js";
-import { Credentials } from "./credentials.js";
-import { Repos, GitHub } from "./repos.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;
- readonly repos: Repos;
- /** GitHub integration (`oc.github.apps.list()`). Connect via a GitHub App. */
- readonly github: GitHub;
-
- 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);
- this.repos = new Repos(http);
- this.github = new GitHub(http);
- }
-}
diff --git a/sdks/typescript/src/agents/connect.ts b/sdks/typescript/src/agents/connect.ts
deleted file mode 100644
index 0e4b76d0..00000000
--- a/sdks/typescript/src/agents/connect.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { Http, type HttpOptions } from "./http.js";
-import { ClientSession } from "./sessions.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
- * `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<ClientSession> {
- const http = new Http({ token: opts.clientToken }, opts);
- // 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.ts
deleted file mode 100644
index 64ed46cc..00000000
--- a/sdks/typescript/src/agents/credentials.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { Http } from "./http.js";
-import type { Credential } from "./types.js";
-
-export interface CreateCredentialParams {
- /** The model provider this key is for — `anthropic` for `claude` and `pi`, `openai` for `codex`. Defaults to `anthropic`. */
- provider?: "anthropic" | "openai" | (string & {});
- /** Write-only — never returned by the API. */
- key: string;
- name?: string;
- /** Make this the org default for its provider (sent as `is_default`). */
- isDefault?: boolean;
-}
-
-/** Provider keys (e.g. Anthropic, OpenAI), 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}`);
- }
- /** Rotate the key VALUE behind a credential (versioned) — flows to running sessions. */
- rotate(id: string, key: string): Promise<Credential> {
- return this.http.request("PATCH", `/credentials/${id}`, { body: { key } });
- }
- setDefault(params: { credential: string; provider?: string }): Promise<void> {
- return this.http.request("PUT", "/credentials/default", { body: params });
- }
-}
diff --git a/sdks/typescript/src/agents/deployments.ts b/sdks/typescript/src/agents/deployments.ts
deleted file mode 100644
index 75c70943..00000000
--- a/sdks/typescript/src/agents/deployments.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-// Deploy / revision / skills / deployment-source sub-resources of `oc.agents` (deploy-from-github).
-// You DEPLOY an agent's behavior (inline or from a linked repo); each deployment produces an
-// immutable REVISION, and the ACTIVE revision is what new sessions run. The HTTP layer converts
-// camelCase ⟷ snake_case on the wire, so params/results here are camelCase.
-
-import type { Http } from "./http.js";
-import type { Page } from "./agents.js";
-
-// ── Types ──────────────────────────────────────────────────────────────────────
-
-export interface InlineSkillFile { path: string; content: string; mode?: number | string; }
-
-/** Behavior sent directly (the complete behavior — omitted `skills` means none). */
-export interface InlineDeployInput {
- type: "inline";
- prompt?: string;
- model?: string;
- skills?: InlineSkillFile[];
- runtime?: { type?: "default" | "custom" };
-}
-
-/** Deploy the agent's linked repo at a ref/sha (repo/path come from the deployment source). */
-export interface GithubDeployInput { type: "github"; ref?: string; sha?: string; }
-
-export type DeployInput = InlineDeployInput | GithubDeployInput;
-
-export interface CreateDeploymentParams {
- input: DeployInput;
- /** Honored for inline only; github deploys are branch-driven (ignored). Default true. */
- activate?: boolean;
- /** CI-safe: a re-run with the same key returns the existing deployment. */
- idempotencyKey?: string;
- /** Free-form caller note (not provenance). */
- clientContext?: Record<string, unknown>;
-}
-
-export interface Deployment {
- id: string;
- state: string; // accepted|queued|fetching|validating|uploading|ready|failed|superseded|skipped
- result?: string | null;
- revisionId?: string | null;
- active?: boolean;
- inputType?: string;
- ref?: string | null;
- sha?: string | null;
- error?: unknown;
- errorClass?: string | null;
- createdAt?: string;
-}
-
-export interface RevisionFile { path: string; mode: number; size: number; }
-
-export interface Revision {
- id: string;
- number: number;
- digest: string;
- prompt?: string;
- model?: string | null;
- skillBundleDigest?: string | null;
- runtimeRef?: unknown;
- active?: boolean;
- createdAt?: string;
- files?: RevisionFile[];
-}
-
-export interface Activation {
- id: string;
- from?: string | null;
- to: string;
- actor?: string | null;
- reason: string;
- createdAt?: string;
-}
-
-export interface SkillSummary {
- name: string;
- description: string | null;
- files: { path: string; mode: number; size: number }[];
-}
-
-export interface AgentSkills {
- revision: { id: string; number: number; digest: string } | null;
- skillBundleDigest: string | null;
- skills: SkillSummary[];
-}
-
-export interface DeploymentSource {
- agentId: string;
- ownerId?: string;
- repoId: string;
- path: string;
- productionRef: string;
- status: string; // active|source_profile_changed|path_missing|ref_missing|auth_required|repo_not_selected|app_suspended|error
- latestSeenSha?: string | null;
- activeDeployedSha?: string | null;
- sourceProfile?: "flue-app-v1" | null;
- sourceProfileVersion?: 1 | null;
- reviewFingerprint?: string | null;
-}
-
-export interface LinkParams {
- /** "owner/repo" slug or a `repo_…` id. */
- repo: string;
- /** Agent dir within the repo ("" for the repo root). */
- path: string;
- /** Branch that auto-activates on push (default "main"). */
- productionRef?: string;
- /** Deploy the production HEAD immediately on link (default true). */
- deployNow?: boolean;
-}
-
-export interface LinkResult { source: DeploymentSource; deploymentId?: string; deployError?: { type: string; message: string }; }
-
-/** Skill .zip body — a Blob (browser) or bytes (Node). */
-export type SkillZip = Blob | ArrayBuffer | Uint8Array;
-
-// ── Sub-resources ────────────────────────────────────────────────────────────
-
-/** Deploy an agent's behavior; read the deployment history. */
-export class Deployments {
- constructor(private readonly http: Http) {}
-
- /** Deploy (`input.type: "inline" | "github"`). Returns the deployment (inline is usually `ready`). */
- create(agentId: string, params: CreateDeploymentParams): Promise<{ deployment: Deployment }> {
- return this.http.request("POST", `/agents/${agentId}/deployments`, {
- body: { input: params.input, activate: params.activate, clientContext: params.clientContext },
- idempotencyKey: params.idempotencyKey,
- idempotent: params.idempotencyKey !== undefined,
- });
- }
- list(agentId: string): Promise<Page<Deployment>> {
- return this.http.request("GET", `/agents/${agentId}/deployments`);
- }
- get(agentId: string, deploymentId: string): Promise<Deployment> {
- return this.http.request("GET", `/agents/${agentId}/deployments/${deploymentId}`);
- }
-}
-
-/** Immutable, numbered revisions + the active pointer (rollback / promote). */
-export class Revisions {
- constructor(private readonly http: Http) {}
-
- list(agentId: string): Promise<Page<Revision>> {
- return this.http.request("GET", `/agents/${agentId}/revisions`);
- }
- /** A revision by number or `rev_…` id (includes its skill file manifest). */
- get(agentId: string, rev: number | string): Promise<Revision> {
- return this.http.request("GET", `/agents/${agentId}/revisions/${rev}`);
- }
- /** Set the active revision — rollback (an earlier one) or promote (a staged one). */
- activate(agentId: string, rev: number | string): Promise<{ activeRevisionId: string }> {
- return this.http.request("POST", `/agents/${agentId}/revisions/${rev}/activate`, { idempotent: true });
- }
-}
-
-/** Active-pointer audit log. */
-export class Activations {
- constructor(private readonly http: Http) {}
- list(agentId: string): Promise<Page<Activation>> {
- return this.http.request("GET", `/agents/${agentId}/activations`);
- }
-}
-
-/** The active revision's skills; replace/remove them (each is a deployment → a new revision). */
-export class Skills {
- constructor(private readonly http: Http) {}
-
- get(agentId: string): Promise<AgentSkills> {
- return this.http.request("GET", `/agents/${agentId}/skills`);
- }
- /** Replace skills from a `.zip` (one folder per skill, each with a SKILL.md). */
- put(agentId: string, zip: SkillZip): Promise<unknown> {
- return this.http.upload("PUT", `/agents/${agentId}/skills`, zip as unknown as BodyInit, "application/zip");
- }
- /** Remove all skills (deploys a revision with none). */
- delete(agentId: string): Promise<unknown> {
- return this.http.request("DELETE", `/agents/${agentId}/skills`);
- }
-}
-
-/** Bind the agent to a repo directory for push-to-deploy (always the OpenComputer App). */
-export class DeploymentSourceResource {
- constructor(private readonly http: Http) {}
-
- link(agentId: string, params: LinkParams): Promise<LinkResult> {
- return this.http.request("POST", `/agents/${agentId}/deployment-source`, { body: params });
- }
- get(agentId: string): Promise<{ source: DeploymentSource }> {
- return this.http.request("GET", `/agents/${agentId}/deployment-source`);
- }
- unlink(agentId: string): Promise<{ ok: boolean }> {
- return this.http.request("DELETE", `/agents/${agentId}/deployment-source`);
- }
-}
diff --git a/sdks/typescript/src/agents/destinations.ts b/sdks/typescript/src/agents/destinations.ts
deleted file mode 100644
index c5f5aeb9..00000000
--- a/sdks/typescript/src/agents/destinations.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import type { Http, Query } from "./http.js";
-import type { Destination, Delivery, DeliveryStatus, Level } from "./types.js";
-
-export interface CreateDestinationParams {
- url: string;
- /** Signing secret (write-only). */
- secret?: string;
- level?: Level;
- /** Event-type allow-list (exact or `prefix.*`); default all. */
- types?: string[];
- includeRaw?: boolean;
- enabled?: boolean;
-}
-
-export interface UpdateDestinationParams {
- enabled?: boolean;
- level?: Level;
- /** Pass `null` to clear the allow-list (deliver all types). */
- types?: string[] | null;
- url?: string;
- includeRaw?: boolean;
- secret?: string;
-}
-
-/** Webhook destinations for one session. Management — needs the org key. */
-export class Destinations {
- constructor(private readonly http: Http, private readonly sessionId: string) {}
-
- create(params: CreateDestinationParams): Promise<Destination> {
- return this.http.request("POST", `/sessions/${this.sessionId}/destinations`, { body: params });
- }
- async list(): Promise<Destination[]> {
- const r = await this.http.request<{ data?: Destination[] } | Destination[]>("GET", `/sessions/${this.sessionId}/destinations`);
- return Array.isArray(r) ? r : r.data ?? [];
- }
- get(id: string): Promise<Destination> {
- return this.http.request("GET", `/sessions/${this.sessionId}/destinations/${id}`);
- }
- update(id: string, params: UpdateDestinationParams): Promise<Destination> {
- return this.http.request("PATCH", `/sessions/${this.sessionId}/destinations/${id}`, { body: params });
- }
- delete(id: string): Promise<void> {
- return this.http.request("DELETE", `/sessions/${this.sessionId}/destinations/${id}`);
- }
-}
-
-/** Delivery records (the deliveries control surface) for one session. Needs the org key. */
-export class Deliveries {
- constructor(private readonly http: Http, private readonly sessionId: string) {}
-
- 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 },
- );
- return Array.isArray(r) ? r : r.data ?? [];
- }
- get(id: string): Promise<Delivery> {
- return this.http.request("GET", `/sessions/${this.sessionId}/deliveries/${id}`);
- }
- /** Re-send any delivery (not just dead-lettered). */
- redeliver(id: string): Promise<void> {
- return this.http.request("POST", `/sessions/${this.sessionId}/deliveries/${id}/redeliver`);
- }
-}
diff --git a/sdks/typescript/src/agents/errors.ts b/sdks/typescript/src/agents/errors.ts
deleted file mode 100644
index 23efbbbe..00000000
--- a/sdks/typescript/src/agents/errors.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-/** 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/hooks.test.ts b/sdks/typescript/src/agents/hooks.test.ts
deleted file mode 100644
index 0f7cbc7a..00000000
--- a/sdks/typescript/src/agents/hooks.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { OpenComputer } from "./client.js";
-
-function client(fetcher: typeof fetch) {
- return new OpenComputer({
- apiKey: "test-key",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher,
- maxRetries: 0,
- });
-}
-
-describe("Agent URLs and Hooks", () => {
- it("maps the canonical Agent URL without adding an invoke helper", async () => {
- const fetcher = vi.fn(async () => Response.json({
- id: "agt_0123456789abcdef01234567",
- name: "triage",
- invoke_url: "https://agt-0123456789abcdef01234567.agents.opencomputer.dev",
- model: "anthropic/claude-sonnet-5",
- runtime: "claude",
- }));
- const oc = client(fetcher as typeof fetch);
-
- const agent = await oc.agents.get("agt_0123456789abcdef01234567");
-
- expect(agent.invokeUrl).toBe(
- "https://agt-0123456789abcdef01234567.agents.opencomputer.dev",
- );
- expect("invoke" in oc.agents).toBe(false);
- });
-
- it("returns the complete Hook URL only from create", async () => {
- const fetcher = vi.fn(async () => Response.json({
- hook: {
- id: "hk_0123456789abcdef01234567",
- agent_id: "agt_0123456789abcdef01234567",
- name: "grafana-prod",
- status: "active",
- secret_last4: "dHh8",
- revoked_reason: null,
- expires_at: null,
- created_at: "2026-07-22T12:00:00.000Z",
- },
- hook_url: "https://agt-0123456789abcdef01234567.agents.opencomputer.dev/hooks/ochk_v1_secret",
- }, { status: 201 }));
- const oc = client(fetcher as typeof fetch);
-
- const created = await oc.agents.hooks.create(
- "agt_0123456789abcdef01234567",
- { name: "grafana-prod", expiresAt: null },
- );
-
- expect(created.hookUrl).toContain("/hooks/ochk_v1_");
- expect(created.hook).toMatchObject({
- agentId: "agt_0123456789abcdef01234567",
- secretLast4: "dHh8",
- revokedReason: null,
- });
- expect(JSON.stringify(created.hook)).not.toContain("ochk_v1_");
- expect(fetcher).toHaveBeenCalledWith(
- "https://api.example.test/v3/agents/agt_0123456789abcdef01234567/hooks",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({ name: "grafana-prod", expires_at: null }),
- }),
- );
- });
-
- it("lists, gets, and revokes without a credential recovery surface", async () => {
- const responses = [
- Response.json({
- data: [{
- id: "hk_0123456789abcdef01234567",
- agent_id: "agt_0123456789abcdef01234567",
- name: "grafana-prod",
- status: "revoked",
- secret_last4: "dHh8",
- revoked_reason: "secret_exposure",
- expires_at: null,
- created_at: "2026-07-22T12:00:00.000Z",
- }],
- next_cursor: "cursor-2",
- }),
- Response.json({
- id: "hk_0123456789abcdef01234567",
- agent_id: "agt_0123456789abcdef01234567",
- name: "grafana-prod",
- status: "revoked",
- secret_last4: "dHh8",
- revoked_reason: "secret_exposure",
- expires_at: null,
- created_at: "2026-07-22T12:00:00.000Z",
- }),
- new Response(null, { status: 204 }),
- ];
- const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
- responses.shift()!
- );
- const oc = client(fetcher as typeof fetch);
-
- const page = await oc.agents.hooks.list(
- "agt_0123456789abcdef01234567",
- { includeRevoked: true, cursor: "cursor-1", limit: 10 },
- );
- const hook = await oc.agents.hooks.get(
- "agt_0123456789abcdef01234567",
- "hk_0123456789abcdef01234567",
- );
- await oc.agents.hooks.delete(
- "agt_0123456789abcdef01234567",
- "hk_0123456789abcdef01234567",
- );
-
- expect(page.nextCursor).toBe("cursor-2");
- expect(page.data[0].revokedReason).toBe("secret_exposure");
- expect(hook).not.toHaveProperty("hookUrl");
- expect(fetcher.mock.calls[0][0]).toContain(
- "include_revoked=true&cursor=cursor-1&limit=10",
- );
- expect(fetcher.mock.calls[2][1]).toMatchObject({ method: "DELETE" });
- });
-});
diff --git a/sdks/typescript/src/agents/hooks.ts b/sdks/typescript/src/agents/hooks.ts
deleted file mode 100644
index 5ec9f644..00000000
--- a/sdks/typescript/src/agents/hooks.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import type { Http, Query } from "./http.js";
-import type { Page } from "./agents.js";
-
-export type HookStatus = "active" | "expired" | "revoked";
-export type HookRevokedReason = "manual" | "secret_exposure";
-
-export interface AgentHook {
- id: string;
- agentId: string;
- name: string;
- status: HookStatus;
- secretLast4: string;
- revokedReason: HookRevokedReason | null;
- expiresAt: string | null;
- createdAt: string;
-}
-
-export interface CreateAgentHookParams {
- name: string;
- expiresAt?: string | null;
-}
-
-export interface ListAgentHooksParams {
- includeRevoked?: boolean;
- cursor?: string;
- limit?: number;
-}
-
-export interface CreatedAgentHook {
- hook: AgentHook;
- /** Complete secret URL. Returned once, only by create. */
- hookUrl: string;
-}
-
-/** Named, independently revocable URLs that can only start this agent. */
-export class AgentHooks {
- constructor(private readonly http: Http) {}
-
- create(agentId: string, params: CreateAgentHookParams): Promise<CreatedAgentHook> {
- return this.http.request("POST", `/agents/${agentId}/hooks`, { body: params });
- }
-
- list(agentId: string, params: ListAgentHooksParams = {}): Promise<Page<AgentHook>> {
- return this.http.request("GET", `/agents/${agentId}/hooks`, {
- query: params as Query,
- });
- }
-
- get(agentId: string, hookId: string): Promise<AgentHook> {
- return this.http.request("GET", `/agents/${agentId}/hooks/${hookId}`);
- }
-
- delete(agentId: string, hookId: string): Promise<void> {
- return this.http.request("DELETE", `/agents/${agentId}/hooks/${hookId}`);
- }
-}
diff --git a/sdks/typescript/src/agents/http.ts b/sdks/typescript/src/agents/http.ts
deleted file mode 100644
index 1ab504a1..00000000
--- a/sdks/typescript/src/agents/http.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { errorFromResponse } from "./errors.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 };
-
-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; idempotent?: boolean; }
-
-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.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase()), 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 };
- // 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 (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 (canRetry && (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;
- }
-
- /** Raw GET (no JSON parse) — e.g. blob-backed event content. Returns the checked Response. */
- async raw(method: string, path: string, opts: { query?: Query; signal?: AbortSignal } = {}): Promise<Response> {
- const res = await this.doFetch(this.url(path, opts.query), { method, headers: this.headers(), signal: opts.signal });
- if (!res.ok) throw errorFromResponse(res.status, (await safeJson(res))?.error, retryAfterSec(res));
- return res;
- }
-
- /** Upload a raw (non-JSON) body — e.g. a skill `.zip`. Normalizes the JSON response. */
- async upload<T>(method: string, path: string, body: BodyInit, contentType: string, signal?: AbortSignal): Promise<T> {
- const res = await this.doFetch(this.url(path), { method, headers: this.headers({ "Content-Type": contentType }), body, signal });
- if (!res.ok) throw errorFromResponse(res.status, (await safeJson(res))?.error, retryAfterSec(res));
- return res.status === 204 ? (undefined as T) : normalize<T>(await res.json());
- }
-}
-
-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
deleted file mode 100644
index 58a3ad5d..00000000
--- a/sdks/typescript/src/agents/index.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-export { OpenComputer, type OpenComputerOptions } from "./client.js";
-export { connectSession, type ConnectSessionOptions } from "./connect.js";
-
-export { Sessions, Session, ClientSession } from "./sessions.js";
-export type {
- CreateSessionParams, StreamOptions, Envelope, ListPage,
- SessionSource, RegisteredRepoSource, InlineRepoSource, SourceAuth, SourceStatus,
- SourceErrorCode, SourceSummary,
-} from "./sessions.js";
-export { Agents } from "./agents.js";
-export type {
- CreateAgentParams, UpdateAgentParams, Page,
- SlackManifest, SlackConnection, ConnectSlackParams,
- ManagedSlackAuthorization, ManagedSlackConnection, ManagedSlackWorkspaceConnection,
- RepositoryAccessPolicy, RepositoryAccessGrant, RepositoryAccessRepository,
- UnavailableSelectedRepository, RepositoryAccess,
-} from "./agents.js";
-export { AgentHooks } from "./hooks.js";
-export type {
- AgentHook, HookStatus, HookRevokedReason, CreateAgentHookParams,
- ListAgentHooksParams, CreatedAgentHook,
-} from "./hooks.js";
-export { AgentRepository } from "./repository-agents.js";
-export type {
- SourceProfileId, RepositoryAgentSource, ReviewRepositoryAgentParams,
- RepositoryReviewIssue, RepositoryCandidateRoot, FlueSourceProfile,
- RepositorySourceInterpretation, RepositoryAgentReview, RepositoryReviewReceipt,
- ImportRepositoryAgentParams, ImportRepositoryAgentResult,
-} from "./repository-agents.js";
-export {
- Deployments, Revisions, Activations, Skills, DeploymentSourceResource,
-} from "./deployments.js";
-export type {
- DeployInput, InlineDeployInput, GithubDeployInput, InlineSkillFile, CreateDeploymentParams,
- Deployment, Revision, RevisionFile, Activation, AgentSkills, SkillSummary,
- DeploymentSource, LinkParams, LinkResult, SkillZip,
-} from "./deployments.js";
-export { Repos, GitHub, GitHubApps, GitHubInstallations } from "./repos.js";
-export type {
- CreateRepoParams, UpdateRepoParams, Repo,
- GitHubApp, GitHubAppMode, GitHubAppStatus, GitHubInstallation,
- ListGitHubInstallationsParams,
-} from "./repos.js";
-export { Credentials } from "./credentials.js";
-export type { CreateCredentialParams } from "./credentials.js";
-export { Destinations, Deliveries } from "./destinations.js";
-export type { CreateDestinationParams, UpdateDestinationParams } from "./destinations.js";
-export { Watches } from "./watches.js";
-export type { Watch, WatchStatus, WakeOn, CreateWatchParams } from "./watches.js";
-export { Schedules } from "./schedules.js";
-export type {
- Schedule, ScheduleRun, ScheduleState, RunOutcome, Overlap,
- CreateScheduleParams, UpdateScheduleParams, RunsPage,
-} from "./schedules.js";
-export { verifyWebhook, WebhookVerificationError } from "./webhooks.js";
-export type { WebhookDelivery, VerifyWebhookOptions } from "./webhooks.js";
-export { startSessionOnDocument, sessionIdempotencyKey } from "./memory-sessions.js";
-export type { StartSessionOnDocumentParams, StartSessionOnDocumentResult } from "./memory-sessions.js";
-export type {
- OutcomeEventType, SessionDestination, CreateEventSubscriptionBody, EventSubscription,
- OutcomeEvent, EventInput, TurnOutcomeDelivery, EventSubscriptionErrorCode,
-} from "./event-subscriptions.js";
-export type {
- MemoryEnvironment, MemoryAccess, MemoryAgentWrites, MemoryBinding, MemoryBindings,
- SessionMemoryBinding, MemoryWriter, MemoryDocumentMeta, MemoryDocument, MemoryDocumentPage,
- MemoryResource, MemoryResourceInventory,
- CreateMemoryDocumentBody, ReplaceMemoryDocumentBody, PatchMemoryDocumentBody,
- MemorySavedEvent, MemoryErrorCode,
-} from "./memory.js";
-
-export * from "./types.js";
-export * from "./errors.js";
diff --git a/sdks/typescript/src/agents/memory-sessions.ts b/sdks/typescript/src/agents/memory-sessions.ts
deleted file mode 100644
index 884e3e6c..00000000
--- a/sdks/typescript/src/agents/memory-sessions.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-// Start a session on a memory document in one call (docs/agents/document-memory.mdx,
-// "Start a session on a new document"). The management API keeps the two
-// objects separate on purpose: a document is owner data with its own
-// lifetime, a session binding is admission to it, and nothing creates one as
-// a side effect of the other. What an application wants at the moment it
-// opens a topic is still "these notes, this session", so this helper does the
-// two calls in order and makes the pair converge under one key.
-//
-// This helper speaks to the project-scoped Serverless Agents surface
-// (`/api/managed-agents/...`) with an API key, not to the Durable Agent
-// Sessions client in this package. Use it from trusted server code only.
-
-import { ConflictError, errorFromResponse, NotFoundError, OpenComputerError, type ApiErrorBody } from "./errors.js";
-import type { MemoryAccess, MemoryAgentWrites, MemoryBindings, MemoryDocument, MemoryEnvironment } from "./memory.js";
-
-const DEFAULT_MANAGED_AGENTS_URL = "https://app.opencomputer.dev";
-
-export interface StartSessionOnDocumentParams {
- /** An OpenComputer API key with access to the project. Server-side only. */
- apiKey: string;
- /** The project whose memory holds the document. */
- projectId: string;
- /** Development and Production have separate memory; the session runs in the same environment. */
- environment: MemoryEnvironment;
- /** The deployed agent's id (not `agent@alias`; the environment above supplies the alias). */
- agent: string;
- /** The declared memory resource and the document id to bind. */
- resource: string;
- documentId: string;
- /** What to create when the document does not exist yet. Ignored when it does. */
- document: {
- title: string;
- /** Default `""`. */
- text?: string;
- /** Default `""`. */
- summary?: string;
- /** Default `"enabled"`. */
- agentWrites?: MemoryAgentWrites;
- };
- /** The binding's access. Default `read-write`. */
- access?: MemoryAccess;
- /** Further bindings for the session, keyed by resource id. */
- memory?: MemoryBindings;
- /**
- * One key for the whole operation. A retry with the same key returns the
- * same session; the document converges on its id regardless.
- */
- idempotencyKey: string;
- /** The session's `source`. Default `api`. */
- source?: string;
- /** The Serverless Agents API. Default `https://app.opencomputer.dev`. */
- baseUrl?: string;
- /** Override fetch (runtimes without a global, or testing). */
- fetch?: typeof fetch;
- signal?: AbortSignal;
-}
-
-export interface StartSessionOnDocumentResult {
- document: {
- id: string;
- /** False when the document already existed; its content was left as it was. */
- created: boolean;
- /** The current revision, for a later conditional owner write. */
- revision: string;
- title: string;
- };
- session: {
- id: string;
- /** False when the key had already created this session. */
- created: boolean;
- status?: string;
- executionMode?: string;
- };
-}
-
-/**
- * The session-create `Idempotency-Key` derived from the caller's key: stable
- * for a retry, distinct from any other use of the same caller key.
- */
-export async function sessionIdempotencyKey(idempotencyKey: string): Promise<string> {
- const bytes = new TextEncoder().encode(`opencomputer.memory.session\0${idempotencyKey}`);
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
- let hex = "";
- for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
- return hex;
-}
-
-async function readBody(response: Response): Promise<unknown> {
- try { return await response.json(); } catch { return undefined; }
-}
-
-function errorBody(body: unknown): ApiErrorBody | undefined {
- if (!body || typeof body !== "object") return undefined;
- const error = (body as { error?: unknown }).error;
- if (typeof error === "string") return { message: error };
- if (error && typeof error === "object") return error as ApiErrorBody;
- return undefined;
-}
-
-/**
- * Creates the document if it does not exist, then creates the session bound
- * to it, and reports both ids and whether each already existed.
- *
- * - The document is created with `If-None-Match: *`; an existing document is
- * kept as it is and reported with `created: false`. An id that was deleted
- * is reserved and fails with a `NotFoundError`, since a binding to it would
- * fail admission.
- * - The session is created with an `Idempotency-Key` derived from
- * `idempotencyKey`; the same key with the same agent, deployment,
- * environment and bindings returns the existing session with
- * `created: false`. Anything else under the same key is a `ConflictError`.
- */
-export async function startSessionOnDocument(
- params: StartSessionOnDocumentParams,
-): Promise<StartSessionOnDocumentResult> {
- const doFetch = params.fetch ?? (typeof fetch !== "undefined" ? fetch : undefined);
- if (!doFetch) throw new Error("global fetch is unavailable — pass { fetch }.");
- const base = (params.baseUrl ?? DEFAULT_MANAGED_AGENTS_URL).replace(/\/+$/, "");
- const headers = { "x-api-key": params.apiKey, accept: "application/json", "content-type": "application/json" };
- const documentUrl =
- `${base}/api/managed-agents/projects/${encodeURIComponent(params.projectId)}` +
- `/memory/${encodeURIComponent(params.resource)}/documents/${encodeURIComponent(params.documentId)}` +
- `?environment=${encodeURIComponent(params.environment)}`;
-
- const createResponse = await doFetch(documentUrl, {
- method: "PUT",
- headers: { ...headers, "if-none-match": "*" },
- body: JSON.stringify({
- title: params.document.title,
- text: params.document.text ?? "",
- ...(params.document.summary !== undefined ? { summary: params.document.summary } : {}),
- ...(params.document.agentWrites ? { agentWrites: params.document.agentWrites } : {}),
- }),
- signal: params.signal,
- });
- let document: MemoryDocument;
- let documentCreated: boolean;
- if (createResponse.status === 201) {
- document = (await createResponse.json()) as MemoryDocument;
- documentCreated = true;
- } else if (createResponse.status === 412) {
- const readResponse = await doFetch(documentUrl, { method: "GET", headers, signal: params.signal });
- if (readResponse.status === 404) {
- throw new NotFoundError(
- 404,
- {
- code: "memory_document_deleted",
- message:
- `Document ${params.resource}/${params.documentId} was deleted and its id is reserved; ` +
- "a session cannot bind it. Use a new document id.",
- },
- "document deleted",
- );
- }
- if (!readResponse.ok) throw errorFromResponse(readResponse.status, errorBody(await readBody(readResponse)));
- document = (await readResponse.json()) as MemoryDocument;
- documentCreated = false;
- } else {
- throw errorFromResponse(createResponse.status, errorBody(await readBody(createResponse)));
- }
-
- const sessionResponse = await doFetch(`${base}/api/managed-agents/sessions`, {
- method: "POST",
- headers: { ...headers, "idempotency-key": await sessionIdempotencyKey(params.idempotencyKey) },
- body: JSON.stringify({
- agentId: `${params.agent}@${params.environment}`,
- source: params.source ?? "api",
- memory: {
- ...params.memory,
- [params.resource]: { scope: "document", id: params.documentId, access: params.access ?? "read-write" },
- },
- }),
- signal: params.signal,
- });
- const sessionBody = await readBody(sessionResponse);
- if (sessionResponse.status === 409) {
- throw new ConflictError(
- 409,
- {
- code: "idempotency_key_reused",
- message:
- `Idempotency key ${JSON.stringify(params.idempotencyKey)} already created a session with a different ` +
- "agent, deployment, environment or memory bindings. Use a new key to start another session; " +
- "the document was left as it is.",
- },
- "idempotency key reused",
- );
- }
- if (!sessionResponse.ok) throw errorFromResponse(sessionResponse.status, errorBody(sessionBody));
- const session = (sessionBody as { session?: { id?: string; status?: string; executionMode?: string } })?.session;
- if (!session?.id) throw new OpenComputerError(sessionResponse.status, undefined, "session create returned no session id");
- return {
- document: { id: document.id, created: documentCreated, revision: document.revision, title: document.title },
- session: {
- id: session.id,
- created: sessionResponse.status === 201,
- ...(session.status ? { status: session.status } : {}),
- ...(session.executionMode ? { executionMode: session.executionMode } : {}),
- },
- };
-}
diff --git a/sdks/typescript/src/agents/normalize.ts b/sdks/typescript/src/agents/normalize.ts
deleted file mode 100644
index 9a696ad9..00000000
--- a/sdks/typescript/src/agents/normalize.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-// 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. Opaque
-// subtrees are passed through untouched: `raw` (source-specific adapter data),
-// `metadata`, `refs`, and `vars` (caller/source-owned maps — must round-trip verbatim,
-// keys included).
-
-const NUMERIC = new Set([
- "seq", "head", "inputCursor", "inputFromSeq", "inputToSeq", "exitCode", "bytes", "port",
- "numTurns", "revision", "tokens", "turnSeconds", "turns",
- "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" || ck === "metadata" || ck === "refs" || ck === "vars") { out[ck] = v; continue; } // opaque: verbatim, keys untouched
- 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;
-}
-
-// Inverse of normalize: camelCase keys → snake_case for REQUEST bodies (the API reads
-// snake_case). Values are left untouched, and opaque/user-owned subtrees (raw, body,
-// metadata, refs, vars, 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", "vars", "input"]);
-
-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] = OPAQUE.has(sk) ? v : serialize(v);
- }
- return out;
- }
- return value;
-}
diff --git a/sdks/typescript/src/agents/repos.ts b/sdks/typescript/src/agents/repos.ts
deleted file mode 100644
index 53bcabdc..00000000
--- a/sdks/typescript/src/agents/repos.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-import type { Http, Query } from "./http.js";
-
-export interface CreateRepoParams {
- provider?: "github"; // default: github
- owner: string;
- repo: string;
- /** Optional handle for your own reference; identity is (provider, owner, repo). */
- name?: string;
-}
-
-export interface UpdateRepoParams {
- name?: string;
-}
-
-export interface Repo {
- id: string; // repo_…
- provider: string;
- owner: string;
- repo: string;
- name?: string;
- createdAt?: string;
- updatedAt?: string;
-}
-
-/**
- * How a GitHub App mints operation-scoped tokens:
- * - `oc_app`: the built-in OpenComputer App owns the key and mints. Default if you register
- * nothing.
- * - `byo_stored_key`: your own GitHub App; OpenComputer stores the App private key encrypted
- * and mints with it. Register it directly ({@link GitHubApps.register}) or one-click via the
- * manifest flow ({@link GitHubApps.createManifest} / {@link GitHubApps.completeManifest}).
- * - `byo_broker`: your backend owns the key and returns short-lived tokens — registrable now,
- * but token minting through a broker is still coming, so it is not yet used for operations.
- * Left as an open string so future modes don't break clients.
- */
-export type GitHubAppMode = "oc_app" | "byo_stored_key" | "byo_broker" | (string & {});
-export type GitHubAppStatus = "active" | "suspended" | "revoked" | (string & {});
-
-/**
- * A GitHub App authority for repo operations. The built-in OpenComputer App (`oc_app`) is
- * always present; registering your own adds `byo_stored_key` / `byo_broker` apps. The Repo and
- * Source shapes are identical regardless of which App authorizes them.
- */
-export interface GitHubApp {
- id: string; // gha_…
- provider: "github" | (string & {});
- mode: GitHubAppMode;
- status: GitHubAppStatus;
- /** The GitHub numeric App id (App-key modes). Not a secret. */
- githubAppId?: string;
- appSlug?: string;
- appName?: string;
- isDefault?: boolean;
- createdAt?: string;
-}
-
-/**
- * Register your own GitHub App. `byo_stored_key` needs the GitHub numeric App id + the App
- * private key (PEM) — OpenComputer encrypts the key at rest and never returns it. `byo_broker`
- * needs your HTTPS mint endpoint + a shared secret. Set `isDefault` to make it the App used
- * when a repo doesn't pin one.
- */
-export interface RegisterGitHubAppParams {
- mode: "byo_stored_key" | "byo_broker";
- /** byo_stored_key: the GitHub numeric App id. */
- githubAppId?: string;
- /** byo_stored_key: the App private key, PEM (PKCS#1 or PKCS#8). Encrypted at rest. */
- privateKey?: string;
- /** byo_broker: your HTTPS token-mint endpoint. */
- brokerUrl?: string;
- /** byo_broker: shared secret OpenComputer presents to your broker. Encrypted at rest. */
- brokerSecret?: string;
- appName?: string;
- appSlug?: string;
- isDefault?: boolean;
-}
-
-/** Update a registered App. Setting `privateKey` / `brokerSecret` rotates that secret in place. */
-export interface UpdateGitHubAppParams {
- status?: GitHubAppStatus;
- appName?: string;
- appSlug?: string;
- isDefault?: boolean;
- privateKey?: string;
- brokerUrl?: string;
- brokerSecret?: string;
-}
-
-/** Parameters for the hosted one-click flow (OpenComputer hosts the start page + callback). */
-export interface CreateAppManifestUrlParams {
- /** Suggested App name (GitHub requires global uniqueness; the user can change it). */
- name?: string;
- /** Org login to create an org-owned App; omit for a user-owned App. */
- organization?: string;
- /** Make the new App your org's default. */
- isDefault?: boolean;
-}
-
-/** A short-lived link to open in a browser to create + connect a GitHub App. */
-export interface AppManifestUrl {
- /** Open this in a browser: it sends the user to GitHub, and OpenComputer's callback captures
- * the key and registers the App. No form to render, no code to handle. */
- startUrl: string;
- expiresAt: string;
-}
-
-/** Parameters for building a GitHub App-creation manifest (developer-driven; you host the
- * redirect and exchange the code yourself). For the one-click path use
- * {@link GitHubApps.createManifestUrl} instead. */
-export interface CreateAppManifestParams {
- /** Where GitHub returns `?code=&state=` after the App is created (must be https). */
- redirectUrl: string;
- /** Suggested App name (GitHub requires global uniqueness; the user can change it). */
- name?: string;
- /** App homepage URL; defaults to the redirect URL's origin. */
- url?: string;
- /** Org login to create an org-owned App; omit for a user-owned App. */
- organization?: string;
-}
-
-/** The manifest + where to submit it. POST `manifest` (JSON) as form field `field` to `postUrl`. */
-export interface AppManifest {
- manifest: Record<string, unknown>;
- postUrl: string;
- field: "manifest";
- /** CSRF/correlation token — echo it from your redirect handler and verify it matches. */
- state: string;
-}
-
-/** Complete the manifest flow: exchange the `code` GitHub returned for a registered App. */
-export interface CompleteAppManifestParams {
- /** The one-time `code` GitHub appended to your redirect URL (~1h TTL, single use). */
- code: string;
- isDefault?: boolean;
-}
-
-/**
- * A GitHub App installation visible to OpenComputer. Installations are useful for setup
- * status and preflight. In preview this may be empty for orgs using only the OpenComputer
- * App; it surfaces bring-your-own App installations once those modes are available.
- */
-export interface GitHubInstallation {
- id: string; // ghi_…
- appId: string; // gha_…
- status: GitHubAppStatus;
- /** The GitHub org/user the App is installed on. */
- accountLogin: string;
- /** GitHub's raw installation id, when exposed for audit/debug. */
- githubInstallationId?: number;
- repositorySelection?: "all" | "selected";
- createdAt?: string;
-}
-
-export interface Page<T> { data: T[]; nextCursor?: string | null; }
-
-export interface ListGitHubInstallationsParams {
- appId?: string;
- limit?: number;
- cursor?: string;
-}
-
-/**
- * Repos — provider-neutral repository identity (the "where" a session works).
- * Auth for GitHub repos resolves through a GitHub App; no credential is passed here.
- * Register once and reference from `sources: [{ repo, ref, sha }]`. A session can also
- * reference `"owner/repo"` directly without creating a Repo handle. See the
- * [Repos & GitHub guide](https://docs.opencomputer.dev/agent-sessions/repos).
- */
-export class Repos {
- constructor(private readonly http: Http) {}
-
- /** Get-or-create, owner-scoped, idempotent by (provider, owner, repo). */
- create(params: CreateRepoParams): Promise<Repo> {
- return this.http.request("POST", "/repos", { body: params, idempotent: true });
- }
- get(id: string): Promise<Repo> {
- return this.http.request("GET", `/repos/${encodeURIComponent(id)}`);
- }
- update(id: string, params: UpdateRepoParams): Promise<Repo> {
- return this.http.request("PATCH", `/repos/${id}`, { body: params });
- }
- list(params: { limit?: number; cursor?: string } = {}): Promise<Page<Repo>> {
- return this.http.request("GET", "/repos", { query: params as Query });
- }
-}
-
-/** GitHub integration surface (`oc.github`). */
-export class GitHub {
- readonly apps: GitHubApps;
- readonly installations: GitHubInstallations;
- constructor(http: Http) {
- this.apps = new GitHubApps(http);
- this.installations = new GitHubInstallations(http);
- }
-}
-
-/**
- * GitHub Apps available to your org — the built-in OpenComputer App plus any you register.
- * Use your own App (`byo_stored_key`) so PRs, comments, and statuses come from your App
- * identity. Easiest is {@link createManifestUrl} (one link, OpenComputer hosts the rest); if
- * you already have an App, {@link register} it directly.
- */
-export class GitHubApps {
- constructor(private readonly http: Http) {}
-
- list(params: { limit?: number; cursor?: string } = {}): Promise<Page<GitHubApp>> {
- return this.http.request("GET", "/github/apps", { query: params as Query });
- }
-
- /** Register your own GitHub App (`byo_stored_key` or `byo_broker`). Secrets are encrypted at
- * rest and never returned. */
- register(params: RegisterGitHubAppParams): Promise<GitHubApp> {
- return this.http.request("POST", "/github/apps", { body: params });
- }
-
- /** Update an App: rename, change status, set as default, or rotate the key/secret. */
- update(id: string, params: UpdateGitHubAppParams): Promise<GitHubApp> {
- return this.http.request("PATCH", `/github/apps/${encodeURIComponent(id)}`, { body: params });
- }
-
- /** Remove a registered App, its installations, and its encrypted secrets. */
- delete(id: string): Promise<{ id: string; deleted: boolean }> {
- return this.http.request("DELETE", `/github/apps/${encodeURIComponent(id)}`);
- }
-
- /**
- * **One-click (recommended).** Returns a `startUrl` to open in a browser. It sends the user
- * to GitHub to create the App, and OpenComputer's hosted callback captures the key and
- * registers it as `byo_stored_key` — you don't render a form or handle the redirect code.
- * Creating an App from a manifest is inherently a GitHub-UI flow, so this is a link to open,
- * not a fully programmatic call. The link is short-lived.
- */
- createManifestUrl(params: CreateAppManifestUrlParams = {}): Promise<AppManifestUrl> {
- return this.http.request("POST", "/github/apps/manifest", { body: params });
- }
-
- /**
- * Developer-driven manifest flow (use {@link createManifestUrl} unless you need to host the
- * redirect yourself — e.g. to attach the App to your own user in your UI). Builds a manifest
- * pre-scoped to what OpenComputer needs; render a form that POSTs `result.manifest` (JSON) as
- * field `result.field` to `result.postUrl`. GitHub redirects to your `redirectUrl` with a
- * `code` — finish with {@link completeManifest}.
- */
- createManifest(params: CreateAppManifestParams): Promise<AppManifest> {
- return this.http.request("POST", "/github/apps/manifest", { body: params });
- }
-
- /**
- * Finish the developer-driven flow: exchange the `code` GitHub returned for a registered App.
- * OpenComputer captures the new App's private key server-side, encrypts it, and registers the
- * App as `byo_stored_key`. The key is never exposed to your code. (Not needed for
- * {@link createManifestUrl}, whose callback does this for you.)
- */
- completeManifest(params: CompleteAppManifestParams): Promise<GitHubApp> {
- return this.http.request("POST", "/github/apps/manifest/conversions", { body: params });
- }
-}
-
-/** GitHub App installations visible to OpenComputer. In preview this may be empty for orgs
- * using only the OpenComputer App; it surfaces BYO installations once available. */
-export class GitHubInstallations {
- constructor(private readonly http: Http) {}
- list(params: ListGitHubInstallationsParams = {}): Promise<Page<GitHubInstallation>> {
- return this.http.request("GET", "/github/installations", { query: params as Query });
- }
-}
diff --git a/sdks/typescript/src/agents/repository-access.test.ts b/sdks/typescript/src/agents/repository-access.test.ts
deleted file mode 100644
index c896031e..00000000
--- a/sdks/typescript/src/agents/repository-access.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import type { RepositoryAccessPolicy } from "../index.js";
-import { OpenComputer } from "./client.js";
-import { ConflictError, NotFoundError } from "./errors.js";
-
-// @ts-expect-error selected policy requires an explicit repository list
-const selectedWithoutRepositories: RepositoryAccessPolicy = { mode: "selected" };
-void selectedWithoutRepositories;
-
-const allWithRepositories: RepositoryAccessPolicy = {
- mode: "all",
- // @ts-expect-error all policy cannot carry a selected repository list
- repositoryIds: ["repo_0123456789abcdef01234567"],
-};
-void allWithRepositories;
-
-const wireAccess = {
- policy: {
- mode: "selected",
- repository_ids: ["repo_0123456789abcdef01234567"],
- },
- grant: {
- status: "active",
- account: "example",
- repository_selection: "selected",
- install_url: "https://github.com/apps/opencomputer/installations/new?state=opaque",
- configure_url: "https://github.com/settings/installations/123",
- truncated: false,
- },
- effective_repositories: [
- {
- id: "repo_0123456789abcdef01234567",
- full_name: "example/support-agent",
- default_branch: "main",
- private: true,
- },
- ],
- unavailable_selected_repositories: [
- {
- id: "repo_89abcdef0123456701234567",
- full_name: "example/retired-agent",
- },
- ],
-};
-
-function client(fetcher: typeof fetch): OpenComputer {
- return new OpenComputer({
- apiKey: "oc_test",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher,
- maxRetries: 0,
- });
-}
-
-describe("agent repository access", () => {
- it("reads and camel-cases policy, grant, and repository state", async () => {
- const fetcher = vi.fn(async () => Response.json(wireAccess));
- const oc = client(fetcher as typeof fetch);
-
- const access = await oc.agents.getRepositoryAccess("agt_1");
-
- expect(access).toEqual({
- policy: {
- mode: "selected",
- repositoryIds: ["repo_0123456789abcdef01234567"],
- },
- grant: {
- status: "active",
- account: "example",
- repositorySelection: "selected",
- installUrl: "https://github.com/apps/opencomputer/installations/new?state=opaque",
- configureUrl: "https://github.com/settings/installations/123",
- truncated: false,
- },
- effectiveRepositories: [
- {
- id: "repo_0123456789abcdef01234567",
- fullName: "example/support-agent",
- defaultBranch: "main",
- private: true,
- },
- ],
- unavailableSelectedRepositories: [
- {
- id: "repo_89abcdef0123456701234567",
- fullName: "example/retired-agent",
- },
- ],
- });
- expect(fetcher).toHaveBeenCalledWith(
- "https://api.example.test/v3/agents/agt_1/repository-access",
- expect.objectContaining({ method: "GET" }),
- );
- });
-
- it("preserves an unavailable grant's null effective view", async () => {
- const fetcher = vi.fn(async () => Response.json({
- ...wireAccess,
- grant: {
- ...wireAccess.grant,
- status: "unavailable",
- account: null,
- repository_selection: null,
- configure_url: null,
- },
- effective_repositories: null,
- unavailable_selected_repositories: [],
- }));
- const oc = client(fetcher as typeof fetch);
-
- const access = await oc.agents.getRepositoryAccess("agt_1");
-
- expect(access.grant.status).toBe("unavailable");
- expect(access.effectiveRepositories).toBeNull();
- expect(access.unavailableSelectedRepositories).toEqual([]);
- });
-
- it("replaces the policy with the exact snake-case wire body", async () => {
- const fetcher = vi.fn(async () => Response.json(wireAccess));
- const oc = client(fetcher as typeof fetch);
-
- const access = await oc.agents.updateRepositoryAccess("agt_1", {
- mode: "selected",
- repositoryIds: ["repo_0123456789abcdef01234567"],
- });
-
- expect(access.policy).toEqual({
- mode: "selected",
- repositoryIds: ["repo_0123456789abcdef01234567"],
- });
- expect(fetcher).toHaveBeenCalledWith(
- "https://api.example.test/v3/agents/agt_1/repository-access",
- expect.objectContaining({
- method: "PUT",
- body: JSON.stringify({
- mode: "selected",
- repository_ids: ["repo_0123456789abcdef01234567"],
- }),
- }),
- );
- });
-
- it("sends the all policy without a repository list", async () => {
- const fetcher = vi.fn(async () => Response.json({
- ...wireAccess,
- policy: { mode: "all" },
- }));
- const oc = client(fetcher as typeof fetch);
-
- const access = await oc.agents.updateRepositoryAccess("agt_1", {
- mode: "all",
- });
-
- expect(access.policy).toEqual({ mode: "all" });
- expect(fetcher).toHaveBeenCalledWith(
- "https://api.example.test/v3/agents/agt_1/repository-access",
- expect.objectContaining({
- method: "PUT",
- body: JSON.stringify({ mode: "all" }),
- }),
- );
- });
-
- it.each([
- [404, "not_found", NotFoundError],
- [409, "repository_access_not_supported", ConflictError],
- ] as const)("maps a %s boundary error through the standard SDK error", async (
- status,
- type,
- ErrorClass,
- ) => {
- const fetcher = vi.fn(async () => Response.json(
- { error: { type, message: "repository access unavailable", request_id: "req_1" } },
- { status },
- ));
- const oc = client(fetcher as typeof fetch);
-
- const request = oc.agents.getRepositoryAccess("agt_1");
-
- await expect(request).rejects.toBeInstanceOf(ErrorClass);
- await expect(request).rejects.toMatchObject({
- status,
- type,
- requestId: "req_1",
- });
- });
-});
diff --git a/sdks/typescript/src/agents/repository-agents.test.ts b/sdks/typescript/src/agents/repository-agents.test.ts
deleted file mode 100644
index 04db988c..00000000
--- a/sdks/typescript/src/agents/repository-agents.test.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { OpenComputer } from "./client.js";
-import type { RepositorySourceInterpretation } from "./repository-agents.js";
-
-// @ts-expect-error invalid profile identity must be a known profile at v1 or null/null
-const crossedInvalidProfile: RepositorySourceInterpretation = {
- disposition: "invalid",
- sourceProfile: "flue-app-v1",
- sourceProfileVersion: null,
- summary: "Invalid source",
- reasonCode: "manifest_invalid",
- issues: [],
-};
-void crossedInvalidProfile;
-
-const reviewResponse = {
- repository: {
- id: "repo_0123456789abcdef01234567",
- full_name: "example/support-agent",
- default_branch: "main",
- },
- root: "agents/support",
- production_ref: "main",
- sha: "a".repeat(40),
- interpretation: {
- disposition: "exact",
- source_profile: "flue-app-v1",
- source_profile_version: 1,
- summary: "Flue agent detected",
- reason_code: "flue_detected",
- assumptions: [],
- agent: { runtime: "flue", model: "anthropic/claude-haiku-4-5" },
- },
- profile: {
- source_profile: "flue-app-v1",
- source_profile_version: 1,
- manifest: {
- schema_version: 1,
- entrypoint: "support-triage",
- model: "anthropic/claude-haiku-4-5",
- runtime: { family: "flue", type: "default" },
- vars: {},
- },
- package: {
- name: "support-agent",
- node_engine: ">=22.19 <23",
- flue_cli: "^1.0.0",
- },
- lockfile: { version: 3 },
- builder: { node: "22.19.0" },
- source: { files: 12, bytes: 4096 },
- variable_names: [],
- warnings: [],
- },
- review_fingerprint: `sha256:${"b".repeat(64)}` as const,
- candidate_roots: [],
- candidate_roots_truncated: false,
-};
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe("agent repository review/import", () => {
- it("normalizes prompt-profile synthesis metadata", async () => {
- vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(Response.json({
- ...reviewResponse,
- interpretation: {
- ...reviewResponse.interpretation,
- source_profile: "flue-prompt-v1",
- summary: "Prompt-defined Flue agent detected",
- reason_code: "flue_prompt_detected",
- },
- profile: {
- ...reviewResponse.profile,
- source_profile: "flue-prompt-v1",
- builder: {
- node: "22.19.0",
- synthesis_template: "flue-prompt-template-v1",
- },
- prompt: { bytes: 256 },
- skills: { count: 2, bytes: 1024, names: ["review", "triage"] },
- },
- }));
- const oc = new OpenComputer({
- apiKey: "oc_test",
- baseUrl: "https://api.example.test/v3",
- maxRetries: 0,
- });
-
- const review = await oc.agents.repository.review({
- repo: reviewResponse.repository.id,
- path: reviewResponse.root,
- productionRef: reviewResponse.production_ref,
- });
- expect(review.interpretation.sourceProfile).toBe("flue-prompt-v1");
- expect(review.profile?.sourceProfile).toBe("flue-prompt-v1");
- if (review.profile?.sourceProfile === "flue-prompt-v1") {
- expect(review.profile.builder.synthesisTemplate).toBe(
- "flue-prompt-template-v1",
- );
- expect(review.profile.skills.names).toEqual(["review", "triage"]);
- }
- });
-
- it("normalizes a source-profile review and replays its receipt on import", async () => {
- const fetchMock = vi
- .spyOn(globalThis, "fetch")
- .mockResolvedValueOnce(Response.json(reviewResponse))
- .mockResolvedValueOnce(
- Response.json({
- agent: {
- id: "agt_imported",
- name: "Support triage",
- model: "anthropic/claude-haiku-4-5",
- runtime: "flue",
- },
- source: {
- agent_id: "agt_imported",
- repo_id: reviewResponse.repository.id,
- path: reviewResponse.root,
- production_ref: reviewResponse.production_ref,
- status: "active",
- },
- deployment: { id: "dep_first", state: "accepted" },
- }),
- );
- const oc = new OpenComputer({
- apiKey: "oc_test",
- baseUrl: "https://api.example.test/v3",
- maxRetries: 0,
- });
-
- const review = await oc.agents.repository.review({
- repo: reviewResponse.repository.id,
- path: reviewResponse.root,
- productionRef: reviewResponse.production_ref,
- });
- expect(review.interpretation.disposition).toBe("exact");
- expect(review.interpretation.sourceProfile).toBe("flue-app-v1");
- expect(review.profile?.manifest.entrypoint).toBe("support-triage");
-
- if (review.interpretation.disposition !== "exact") {
- throw new Error("fixture must be importable");
- }
- await oc.agents.repository.import({
- name: "Support triage",
- credential: "managed",
- idempotencyKey: "import-command-1",
- source: {
- type: "github",
- repo: review.repository.id,
- path: review.root,
- productionRef: review.productionRef,
- },
- review: {
- sha: review.sha,
- sourceProfile: review.interpretation.sourceProfile,
- fingerprint: review.reviewFingerprint,
- },
- });
-
- expect(fetchMock).toHaveBeenNthCalledWith(
- 1,
- "https://api.example.test/v3/github/deploy-app/inspect",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({
- repo: reviewResponse.repository.id,
- path: "agents/support",
- production_ref: "main",
- }),
- }),
- );
- expect(fetchMock).toHaveBeenNthCalledWith(
- 2,
- "https://api.example.test/v3/agents/import",
- expect.objectContaining({
- method: "POST",
- headers: expect.objectContaining({
- "Idempotency-Key": "import-command-1",
- }),
- }),
- );
- const importInit = fetchMock.mock.calls[1]?.[1] as RequestInit;
- expect(JSON.parse(String(importInit.body))).toEqual({
- name: "Support triage",
- credential: "managed",
- source: {
- type: "github",
- repo: reviewResponse.repository.id,
- path: "agents/support",
- production_ref: "main",
- },
- review: {
- sha: reviewResponse.sha,
- source_profile: "flue-app-v1",
- fingerprint: `sha256:${"b".repeat(64)}`,
- },
- });
- });
-});
diff --git a/sdks/typescript/src/agents/repository-agents.ts b/sdks/typescript/src/agents/repository-agents.ts
deleted file mode 100644
index e3640dac..00000000
--- a/sdks/typescript/src/agents/repository-agents.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-// Two-phase repository agent creation. Review is read-only and pins the exact
-// source interpretation the user confirmed; import revalidates that review
-// before creating an agent or deployment.
-
-import type { Http } from "./http.js";
-import type { Agent, CredentialRef } from "./types.js";
-import type { Deployment, DeploymentSource } from "./deployments.js";
-
-export type SourceProfileId = "flue-app-v1" | "flue-prompt-v1";
-
-export interface RepositoryAgentSource {
- type: "github";
- /** An owner-scoped `repo_…` id. */
- repo: string;
- /** Repository-relative root; use an empty string for the repository root. */
- path: string;
- /** The production branch OpenComputer resolves and follows for push-to-deploy. */
- productionRef: string;
-}
-
-export interface ReviewRepositoryAgentParams {
- repo: string;
- path: string;
- productionRef: string;
-}
-
-export interface RepositoryReviewIssue {
- code: string;
- message: string;
- path?: string;
-}
-
-export interface RepositoryCandidateRoot {
- path: string;
- sourceProfile: SourceProfileId | null;
- summary: string;
- marker:
- | "agent.toml"
- | "flue.config.ts"
- | "flue.config.js"
- | "flue.config.mjs"
- | "flue.config.cjs";
-}
-
-interface FlueSourceProfileBase {
- sourceProfile: SourceProfileId;
- sourceProfileVersion: 1;
- manifest: {
- schemaVersion: 1;
- entrypoint: string;
- model: string;
- runtime: { family: "flue"; type: string };
- /** Non-secret manifest variables. */
- vars: Record<string, string>;
- };
- package: {
- name: string | null;
- nodeEngine: string;
- flueCli: string;
- };
- lockfile: { version: number };
- builder: { node: string; synthesisTemplate?: string };
- source: { files: number; bytes: number };
- variableNames: string[];
- warnings: RepositoryReviewIssue[];
-}
-
-export type FlueSourceProfile =
- | (FlueSourceProfileBase & {
- sourceProfile: "flue-app-v1";
- })
- | (FlueSourceProfileBase & {
- sourceProfile: "flue-prompt-v1";
- prompt: { bytes: number };
- skills: { count: number; bytes: number; names: string[] };
- builder: { node: string; synthesisTemplate: string };
- });
-
-export type RepositorySourceInterpretation =
- | {
- disposition: "exact";
- sourceProfile: SourceProfileId;
- sourceProfileVersion: 1;
- summary: string;
- reasonCode: "flue_detected" | "flue_prompt_detected";
- assumptions: string[];
- agent: { runtime: "flue"; model: string };
- }
- | ({
- disposition: "invalid";
- summary: string;
- reasonCode: string;
- issues: RepositoryReviewIssue[];
- } & (
- | { sourceProfile: SourceProfileId; sourceProfileVersion: 1 }
- | { sourceProfile: null; sourceProfileVersion: null }
- ))
- | {
- disposition: "unrecognized";
- sourceProfile: null;
- sourceProfileVersion: null;
- summary: string;
- reasonCode: "unrecognized_source";
- };
-
-interface RepositoryAgentReviewBase {
- repository: {
- id: string;
- fullName: string;
- defaultBranch: string | null;
- };
- root: string;
- productionRef: string;
- sha: string;
- reviewFingerprint: `sha256:${string}`;
- candidateRoots: RepositoryCandidateRoot[];
- candidateRootsTruncated: boolean;
-}
-
-export type RepositoryAgentReview =
- | (RepositoryAgentReviewBase & {
- interpretation: Extract<
- RepositorySourceInterpretation,
- { disposition: "exact" }
- >;
- profile: FlueSourceProfile;
- })
- | (RepositoryAgentReviewBase & {
- interpretation: Extract<
- RepositorySourceInterpretation,
- { disposition: "invalid" }
- >;
- profile: null;
- })
- | (RepositoryAgentReviewBase & {
- interpretation: Extract<
- RepositorySourceInterpretation,
- { disposition: "unrecognized" }
- >;
- profile: null;
- });
-
-export interface RepositoryReviewReceipt {
- sha: string;
- sourceProfile: SourceProfileId;
- fingerprint: `sha256:${string}`;
-}
-
-export interface ImportRepositoryAgentParams {
- name: string;
- source: RepositoryAgentSource;
- review: RepositoryReviewReceipt;
- /** Repository imports currently use Managed model access. */
- credential: Extract<CredentialRef, "managed">;
- /** Stable for one logical import; conflicting reuse fails safely. */
- idempotencyKey: string;
-}
-
-export interface ImportRepositoryAgentResult {
- agent: Agent;
- source: DeploymentSource;
- deployment: Deployment;
-}
-
-/** Review and import an agent from a repository (`oc.agents.repository`). */
-export class AgentRepository {
- constructor(private readonly http: Http) {}
-
- /**
- * Resolve one exact commit and interpret its selected root without executing
- * repository code. Only an `exact` result can be imported.
- */
- review(params: ReviewRepositoryAgentParams): Promise<RepositoryAgentReview> {
- return this.http.request("POST", "/github/deploy-app/inspect", {
- body: params,
- });
- }
-
- /**
- * Revalidate a reviewed source plan, then atomically create its agent, source
- * link, and first deployment. The idempotency key is sent as a header.
- */
- import(
- params: ImportRepositoryAgentParams,
- ): Promise<ImportRepositoryAgentResult> {
- const { idempotencyKey, ...body } = params;
- return this.http.request("POST", "/agents/import", {
- body,
- idempotencyKey,
- idempotent: true,
- });
- }
-}
diff --git a/sdks/typescript/src/agents/schedules.ts b/sdks/typescript/src/agents/schedules.ts
deleted file mode 100644
index a0873427..00000000
--- a/sdks/typescript/src/agents/schedules.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-// Schedules sub-resource of `oc.agents` (design 015) — cron for agents. A schedule fires an agent on
-// a cron; each firing starts one session on the active revision with a fixed input. The HTTP layer
-// converts camelCase ⟷ snake_case on the wire, so params/results here are camelCase.
-
-import type { Http, Query } from "./http.js";
-
-export type Overlap = "skip" | "allow";
-export type ScheduleState = "active" | "paused" | "auto_paused";
-export type RunOutcome = "enacted" | "skipped" | "failed";
-
-export interface CreateScheduleParams {
- name: string; // ^[a-z0-9][a-z0-9-]{0,63}$, unique per agent
- cron: string; // 5-field cron (1-minute resolution)
- tz?: string | null; // IANA name; omit for UTC
- input: string; // first user message of every run (≤ 32 KiB)
- overlap?: Overlap; // default "skip"
-}
-
-export interface UpdateScheduleParams {
- cron?: string;
- tz?: string | null;
- input?: string;
- overlap?: Overlap;
- paused?: boolean; // true = pause, false = resume (recomputes next fire, resets failures)
-}
-
-export interface Schedule {
- id: string; // sch_…
- agentId: string;
- name: string;
- cron: string;
- tz: string | null;
- input: string;
- overlap: Overlap;
- state: ScheduleState;
- nextFireAt: string; // UTC ISO
- lastFiredAt: string | null;
- consecutiveFailures: number;
- lastError: string | null;
- createdAt: string;
- updatedAt: string;
-}
-
-export interface ScheduleRun {
- id: string; // srn_…
- scheduleId: string;
- scheduledFor: string | null; // the cron slot; null for a manual fire
- firedAt: string;
- outcome: RunOutcome;
- sessionId: string | null; // chain into oc.sessions.get(sessionId)
- error: string | null;
-}
-
-export interface RunsPage { runs: ScheduleRun[]; nextCursor?: string | null; }
-
-/** Cron for agents. Schedules live on the agent — every method takes the agent id first.
- * `oc.agents.schedules.create(agentId, { name, cron, input })`. */
-export class Schedules {
- constructor(private readonly http: Http) {}
-
- create(agentId: string, params: CreateScheduleParams): Promise<{ schedule: Schedule }> {
- return this.http.request("POST", `/agents/${agentId}/schedules`, { body: params });
- }
- list(agentId: string): Promise<{ schedules: Schedule[] }> {
- return this.http.request("GET", `/agents/${agentId}/schedules`);
- }
- get(agentId: string, scheduleId: string): Promise<{ schedule: Schedule }> {
- return this.http.request("GET", `/agents/${agentId}/schedules/${scheduleId}`);
- }
- update(agentId: string, scheduleId: string, params: UpdateScheduleParams): Promise<{ schedule: Schedule }> {
- return this.http.request("PATCH", `/agents/${agentId}/schedules/${scheduleId}`, { body: params });
- }
- delete(agentId: string, scheduleId: string): Promise<void> {
- return this.http.request("DELETE", `/agents/${agentId}/schedules/${scheduleId}`);
- }
- /** Test-fire now — enacts synchronously in any state (paused included), does not advance the cron.
- * Returns the run; branch on `run.outcome` (a failed fire is still a 201 with `outcome:"failed"`). */
- fire(agentId: string, scheduleId: string): Promise<{ run: ScheduleRun }> {
- return this.http.request("POST", `/agents/${agentId}/schedules/${scheduleId}/fire`);
- }
- /** Run history, newest-first. Each run carries `sessionId` to chain into `oc.sessions.get`. */
- runs(agentId: string, scheduleId: string, opts: { cursor?: string; limit?: number } = {}): Promise<RunsPage> {
- return this.http.request("GET", `/agents/${agentId}/schedules/${scheduleId}/runs`, { query: opts as Query });
- }
-}
-
-
diff --git a/sdks/typescript/src/agents/session-create-contract.test.ts b/sdks/typescript/src/agents/session-create-contract.test.ts
deleted file mode 100644
index 6dd6652a..00000000
--- a/sdks/typescript/src/agents/session-create-contract.test.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { describe, expect, it } from "vitest";
-import type { CreateSessionParams } from "./sessions.js";
-
-type HasRevisionOverride = "revision" extends keyof CreateSessionParams ? true : false;
-const hasRevisionOverride: HasRevisionOverride = false;
-
-describe("session create contract", () => {
- it("does not expose unsupported revision selection", () => {
- expect(hasRevisionOverride).toBe(false);
- });
-});
diff --git a/sdks/typescript/src/agents/session-sources.test.ts b/sdks/typescript/src/agents/session-sources.test.ts
deleted file mode 100644
index 586e06af..00000000
--- a/sdks/typescript/src/agents/session-sources.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { OpenComputer } from "./client.js";
-
-const wireSource = {
- name: "target",
- status: "resolved",
- path: "/workspace/sources/target",
- repo_id: "repo_0123456789abcdef01234567",
- full_name: "example/support-agent",
- requested_ref: "main",
- sha: "a".repeat(40),
- resolved_sha: "a".repeat(40),
-};
-
-describe("managed session source summaries", () => {
- it("camel-cases repository identity on create and live source reads", async () => {
- const fetcher = vi
- .fn()
- .mockResolvedValueOnce(Response.json({
- session: { id: "ses_1", status: "queued" },
- sources: [wireSource],
- }))
- .mockResolvedValueOnce(Response.json([wireSource]));
- const oc = new OpenComputer({
- apiKey: "oc_test",
- baseUrl: "https://api.example.test/v3",
- fetch: fetcher as typeof fetch,
- maxRetries: 0,
- });
-
- const session = await oc.sessions.create({
- agent: "agt_1",
- input: "Inspect the target repository",
- });
-
- expect(session.sources[0]).toMatchObject({
- repoId: "repo_0123456789abcdef01234567",
- fullName: "example/support-agent",
- requestedRef: "main",
- resolvedSha: "a".repeat(40),
- });
- await expect(session.listSources()).resolves.toEqual([
- expect.objectContaining({
- repoId: "repo_0123456789abcdef01234567",
- fullName: "example/support-agent",
- requestedRef: "main",
- }),
- ]);
- expect(fetcher).toHaveBeenNthCalledWith(
- 2,
- "https://api.example.test/v3/sessions/ses_1/sources",
- expect.objectContaining({ method: "GET" }),
- );
- });
-});
diff --git a/sdks/typescript/src/agents/sessions.ts b/sdks/typescript/src/agents/sessions.ts
deleted file mode 100644
index 7eb68ce1..00000000
--- a/sdks/typescript/src/agents/sessions.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-import type { Http, Query } from "./http.js";
-import type { Event, Level, Limits, LastTurn, SessionData, SessionStatus, Turn } from "./types.js";
-import { parseEventStream } from "./sse.js";
-import { Destinations, Deliveries } from "./destinations.js";
-import { Watches } from "./watches.js";
-
-export type Envelope = { text?: string; [k: string]: unknown };
-
-export interface CreateSessionParams {
- agent: string;
- input: string | Envelope;
- /**
- * Override the agent's model for this session — the session runs this model instead of the
- * one pinned by the agent's revision. Same `provider/model` form as the agent's model, and
- * must resolve to the agent's runtime's provider. Defaults to the agent's model. Not
- * supported for `flue` agents (their model is fixed in the deployed artifact).
- */
- model?: string;
- /** get-or-create idempotency/routing key — one session per key. */
- key?: string;
- webhook?: string;
- /**
- * 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;
- /**
- * Opaque application routing state stored on the session — a JSON object (≤ 16 KB).
- * Returned on `get`/`list` (as `session.metadata`) and delivered verbatim in
- * webhooks, so a callback handler can route to the right record without a lookup. It is
- * never shown to the model and not indexed/queryable. Distinct from `key`
- * (get-or-create) and `idempotencyKey` (dedupe).
- */
- metadata?: Record<string, unknown>;
- /** Makes a keyless create retry-safe (sent as the Idempotency-Key header). */
- idempotencyKey?: string;
- /**
- * Repositories to check out for the agent at the start of the session. Each source
- * is materialized into `/workspace/sources/<name>` before the agent's first turn;
- * the checkout credential never enters the agent's sandbox. See {@link Repos} and
- * the [Repos guide](https://docs.opencomputer.dev/agent-sessions/repos).
- *
- * Reference a registered repo (preferred — auth lives on the repo), or pass an
- * inline source with per-session auth (no registration).
- */
- sources?: SessionSource[];
-}
-
-/** A repo to check out for a session. Either a reference to a registered {@link Repo},
- * or an inline source with its own per-session auth. */
-export type SessionSource = RegisteredRepoSource | InlineRepoSource;
-
-export interface RegisteredRepoSource {
- /** A registered repo id (`repo_…`) or `owner/repo` slug. Auth comes from your GitHub
- * App — no per-source credential. */
- repo: string;
- url?: never;
- auth?: never;
- /** Fetch ref (branch or `refs/pull/N/head`). */
- ref: string;
- /**
- * Exact commit to pin. OPTIONAL for a registered repo: omit it and the control plane resolves
- * `ref`→HEAD and pins that sha at create. Pass it to pin an exact commit yourself.
- */
- sha?: string;
- /** Checkout slug → `/workspace/sources/<name>`. Defaults to the repo name. */
- name?: string;
-}
-
-export interface InlineRepoSource {
- repo?: never;
- /** Clone URL (https, no embedded credentials). */
- url: string;
- ref: string;
- sha: string;
- name?: string;
- /** Inline auth (registered repos use the resolved GitHub App instead). */
- auth: SourceAuth;
-}
-
-/**
- * Inline-source auth — the **no-setup workaround**, and **checkout-only**. Pass a real
- * short-lived token; it is used once to check the repo out and then **purged immediately**,
- * so it **cannot publish or open PRs** — publishing requires a configured GitHub App (the
- * OpenComputer App). Prefer connecting a GitHub App (durable). Held encrypted, used once
- * for checkout, then purged.
- */
-export type SourceAuth =
- | { type: "risky_short_lived_token"; token: string; expiresAt: string };
-
-export type SourceStatus =
- | "pending" | "materializing" | "resolved" | "failed" | "unavailable" | "auth_required";
-
-export type SourceErrorCode =
- | "source.auth_required"
- | "source.auth_ambiguous"
- | "source.app_suspended"
- | "source.app_revoked"
- | "source.repo_not_selected"
- | "source.permission_missing"
- | "source.mint_failed"
- | "source.mint_rate_limited"
- | "source.ref_not_found"
- | "source.sha_mismatch"
- | "source.unsupported_submodule"
- | "source.unsupported_lfs"
- | "source.too_large"
- | "source.timeout"
- | (string & {});
-
-/** Sanitized per-source status returned on a session (never exposes url/auth). */
-export interface SourceSummary {
- name: string;
- status: SourceStatus;
- path: string;
- /** Stable registered repository id when the source came from a managed repository. */
- repoId?: string;
- /** Current provider coordinates for a managed repository. */
- fullName?: string;
- /** Branch, tag, or commit expression requested before it was pinned. */
- requestedRef?: string;
- /** Requested commit from create; kept for correlation while materialization is pending. */
- sha: string;
- /** Actual checked-out commit after materialization succeeds. Usually equals `sha`. */
- resolvedSha?: string;
- /** Machine-readable reason when status is `failed` / `unavailable` / `auth_required`. */
- errorCode?: SourceErrorCode;
- /** Human-readable diagnostic safe to show in operator/debug UI. */
- errorMessage?: string;
- retryable?: boolean;
-}
-
-export interface StreamOptions {
- /** Visibility threshold; default `internal` (the full build trace). */
- level?: Level;
- /** Filter by event type (exact or `prefix.*`). Applied client-side as the stream arrives. */
- 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 { idempotencyKey, ...body } = params;
- const r = await this.http.request<{ session: SessionData; clientToken?: string; sources?: SourceSummary[] }>(
- "POST", "/sessions",
- { body, idempotencyKey, idempotent: Boolean(idempotencyKey || params.key) },
- );
- return new Session(this.http, r.session, r.clientToken, r.sources);
- }
- 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; after?: string; before?: string; limit?: number; cursor?: string } = {}): Promise<ListPage<SessionData>> {
- return this.http.request("GET", "/sessions", { query: params as Query });
- }
-}
-
-/**
- * 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 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.
- */
- 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; // advance the cursor on every event, even filtered-out ones
- // The SSE endpoint streams by level+seq; apply the type filter here (exact or `prefix.*`).
- if (opts.type && !(opts.type.endsWith(".*") ? ev.type.startsWith(opts.type.slice(0, -1)) : ev.type === opts.type)) continue;
- 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; turnId?: string; limit?: number } = {}): Promise<ListPage<Event>> {
- return this.http.request("GET", `/sessions/${this.id}/events`, { query: opts as Query });
- }
-
- /** Fetch a single event by id. */
- event(eventId: string): Promise<Event> {
- return this.http.request("GET", `/sessions/${this.id}/events/${eventId}`);
- }
-
- /** Fetch a blob-backed event body (large outputs) as text. */
- async eventContent(eventId: string): Promise<string> {
- return (await this.http.raw("GET", `/sessions/${this.id}/events/${eventId}/content`)).text();
- }
-
- /** User-message history (alias for level=user + type=*.message). */
- messages(opts: { after?: number; limit?: number } = {}): Promise<ListPage<Event>> {
- return this.http.request("GET", `/sessions/${this.id}/messages`, { 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 }, idempotent: Boolean(opts.idempotencyKey) },
- );
- 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;
- /** PR watches for this session — wake it when a PR it opened changes (org key). */
- readonly watches: Watches;
- private data: SessionData;
- private _sources: SourceSummary[];
-
- constructor(http: Http, data: SessionData, clientToken?: string, sources?: SourceSummary[]) {
- super(http, data.id, clientToken);
- this.data = data;
- this._sources = sources ?? [];
- this.destinations = new Destinations(http, data.id);
- this.deliveries = new Deliveries(http, data.id);
- this.watches = new Watches(http, data.id);
- }
-
- get status(): SessionStatus { return this.data.status; }
- get lastTurn(): LastTurn | undefined { return this.data.lastTurn; }
- /** Durable rollup of terminal-turn usage; absent cost is unknown, not zero. */
- get usage(): SessionData["usage"] { return this.data.usage; }
- /** Source checkout status from the create response — `{ name, status, path, sha, ... }[]`
- * (empty when none). For **live** status, call {@link Session.listSources}. */
- get sources(): SourceSummary[] { return this._sources; }
- /** Fetch live source checkout status — poll this to watch materialization
- * (`pending`→`materializing`→`resolved`/`failed`/`auth_required`). */
- listSources(): Promise<SourceSummary[]> {
- return this.http.request("GET", `/sessions/${this.id}/sources`);
- }
- /** Opaque app routing state set at create (`null` when unset). See {@link CreateSessionParams.metadata}. */
- get metadata(): Record<string, unknown> | null { return this.data.metadata ?? null; }
- /** 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. `cursor` = `nextCursor` from the previous page. */
- turns(opts: { cursor?: 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 }> {
- 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
deleted file mode 100644
index 8ab84f7b..00000000
--- a/sdks/typescript/src/agents/sse.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-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
deleted file mode 100644
index 99badbff..00000000
--- a/sdks/typescript/src/agents/types.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-// 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" | "awaiting_input" | "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 type UsageAttribution = "exact" | "best_effort";
-
-/** A terminal turn with at least one trustworthy normalized usage observation. */
-export interface ReportedTurnUsage {
- reported: true;
- /** False means the token/cost values present are lower bounds. */
- complete?: false;
- inputTokens: number;
- outputTokens: number;
- cacheCreationInputTokens: number;
- cacheReadInputTokens: number;
- tokens: number;
- /** Runtime/provider-reported visibility; absent means unknown, not zero. */
- totalCostUsd?: number;
- attribution?: UsageAttribution;
-}
-
-/** A terminal turn for which no trustworthy usage observation was available. */
-export interface UnreportedTurnUsage {
- reported: false;
- attribution?: UsageAttribution;
-}
-
-/** Historical rows created before usage rollups were populated remain empty. */
-export type HistoricalUsage = { [key: string]: never };
-export type TurnUsage = ReportedTurnUsage | UnreportedTurnUsage | HistoricalUsage;
-
-export interface SessionUsageSummary {
- activeSeconds: number;
- reportedTurns: number;
- unreportedTurns: number;
- /** False means any token/cost totals present are lower bounds. */
- complete: boolean;
- inputTokens?: number;
- outputTokens?: number;
- cacheCreationInputTokens?: number;
- cacheReadInputTokens?: number;
- tokens?: number;
- /** Runtime/provider-reported visibility; absent means unknown, not zero. */
- totalCostUsd?: number;
- attribution?: UsageAttribution;
-}
-
-export type SessionUsage = SessionUsageSummary | HistoricalUsage;
-
-// The runtime an agent runs on. `claude` and `pi` run `anthropic/…` models today and
-// `codex` runs `openai/…`. `pi` is built provider-agnostic (the provider comes from the
-// model's `provider/` prefix, not the runtime) — more providers land next. The union
-// keeps known values discoverable while still accepting future ones.
-export type Runtime = "claude" | "codex" | "pi" | (string & {});
-
-// A credential id (`newId("cred")` → `cred_…`). The template keeps the shape
-// checkable while still accepting any concrete id.
-export type CredentialId = `cred_${string}`;
-// How an agent picks its model source: the reserved "managed" sentinel (run via
-// OpenComputer, no provider key) or a specific BYO credential id. Omit/null to
-// inherit the org default.
-export type CredentialRef = "managed" | CredentialId;
-
-export interface Actor {
- id?: string;
- type?: "human" | "agent" | "system" | (string & {});
- display?: string;
-}
-
-export interface Agent {
- id: string;
- name: string;
- /** Canonical application URL for trusted-backend JSON invocation. */
- invokeUrl: string;
- promptHash?: string;
- model: string;
- runtime: Runtime;
- revision?: number;
- /** The agent's active revision (what new sessions run); `prompt`/`model` are served from it. */
- activeRevision?: { id: string; number: number; digest: string } | null;
- credentialId?: CredentialRef | null;
- limits?: Limits;
- createdAt?: string;
- updatedAt?: string;
-}
-
-export interface LastTurn {
- /** The turn id (the API/SSE field is `last_turn.id`). */
- id?: string;
- state?: "queued" | "accepted" | "running" | "ok" | "error";
- yieldReason?: YieldReason;
- startedAt?: string;
- completedAt?: string;
- resultEventId?: string;
- error?: unknown;
-}
-
-export interface Turn {
- id: string;
- state?: "queued" | "accepted" | "running" | "ok" | "error";
- yieldReason?: YieldReason;
- resultEventId?: string;
- error?: unknown;
- startedAt?: string;
- completedAt?: string;
- activeSeconds?: number;
- usage?: TurnUsage | null;
-}
-
-export interface SessionData {
- id: string;
- status: SessionStatus;
- head?: number;
- inputCursor?: number;
- agentSnapshot?: { promptHash?: string; model?: string; runtime?: string; revision?: number };
- agentId?: string;
- credentialId?: string;
- lastTurn?: LastTurn;
- usage?: SessionUsage | null;
- limits?: Limits;
- /** Opaque app routing state set at create (`null` when unset). See {@link CreateSessionParams.metadata}. */
- metadata?: Record<string, unknown> | null;
- key?: string;
- createdAt?: string;
-}
-
-export interface Credential {
- id: CredentialId;
- provider: string;
- name?: string;
- last4?: string;
- isDefault?: boolean;
- createdAt?: string;
-}
-
-export interface Destination {
- id: string;
- session: string;
- kind: string;
- url: string;
- level: Level;
- 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;
- session: string;
- destination: string;
- eventId: string;
- eventSeq?: number;
- status: DeliveryStatus;
- attempts: number;
- lastAttemptAt?: string;
- responseCode?: number;
- error?: string;
- createdAt?: string;
- updatedAt?: 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;
- turnId?: string;
- contentRef?: string;
- bodyTruncated?: boolean;
- bodyBytes?: number;
- 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/agents/watches.ts b/sdks/typescript/src/agents/watches.ts
deleted file mode 100644
index 7704d3ea..00000000
--- a/sdks/typescript/src/agents/watches.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import type { Http } from "./http.js";
-
-/** The wake condition — the PR state change that wakes the session. */
-export type WakeOn = "checks" | "review" | "comment" | "merge";
-
-/** Watch lifecycle status. */
-export type WatchStatus = "active" | "closed" | "revoked" | "auth_required";
-
-export interface CreateWatchParams {
- /** Only `"github_pr"` today (the default). */
- type?: "github_pr";
- /** `"owner/repo"` — omitted, resolves to the PR this session opened. */
- repo?: string;
- /** PR number — omitted, resolves to the session's sole owned PR. */
- pr?: number;
- /** Wake condition. Default `"checks"`. */
- wakeOn?: WakeOn;
- /** Freeform note ("why"), replayed to the agent on wake. */
- intent?: string;
-}
-
-export interface Watch {
- id: string;
- /** `"github_pr"`. */
- type: string;
- /** Watched repo (`"owner/repo"`). */
- repo: string;
- /** Watched PR number. */
- pr: number;
- wakeOn: WakeOn;
- /** Freeform note, replayed on wake. */
- intent?: string;
- status: WatchStatus;
- /** How it was declared (runtime tool / management API). */
- origin: string;
- /** Last authoritative PR re-read. */
- lastSnapshotAt?: string;
- /** When the 30-day TTL lapses; past this the watch stops firing (status stays `active`). */
- expiresAt: string;
- createdAt: string;
-}
-
-/**
- * Watches for one session — wake the session when a PR it opened changes (checks finish, a review
- * or comment lands, the PR merges/closes). Management surface; needs the org key.
- *
- * A watch only fires on a PR the **same session** opened via `github_publish_pull_request`, on
- * OpenComputer-App (`oc_app`) repos. See the [Watches guide](https://docs.opencomputer.dev/agent-sessions/watches).
- */
-export class Watches {
- constructor(private readonly http: Http, private readonly sessionId: string) {}
-
- /** Declare a watch. `repo`/`pr` omitted → the PR this session opened. */
- async create(params: CreateWatchParams = {}): Promise<Watch> {
- const r = await this.http.request<{ watch: Watch }>(
- "POST", `/sessions/${this.sessionId}/watches`, { body: params },
- );
- return r.watch;
- }
-
- /** List this session's watches. */
- async list(): Promise<Watch[]> {
- const r = await this.http.request<{ data?: Watch[] } | Watch[]>(
- "GET", `/sessions/${this.sessionId}/watches`,
- );
- return Array.isArray(r) ? r : r.data ?? [];
- }
-
- /** Remove a watch (equivalent to the agent's `unwatch_pull_request`). */
- delete(id: string): Promise<void> {
- return this.http.request("DELETE", `/sessions/${this.sessionId}/watches/${id}`);
- }
-}
diff --git a/sdks/typescript/src/browser.ts b/sdks/typescript/src/browser.ts
index 0c21678a..394916b8 100644
--- a/sdks/typescript/src/browser.ts
+++ b/sdks/typescript/src/browser.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
const DEFAULT_BROWSER_API_URL = "https://browser.opencomputer.dev";
function resolveBrowserApiUrl(url?: string): string {
@@ -133,7 +134,7 @@ export class Browser {
static async create(opts: BrowserCreateOpts = {}): Promise<Browser> {
const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await fetch(`${apiUrl}/v1/browsers`, {
+ const resp = await apiFetch(`${apiUrl}/v1/browsers`, {
method: "POST",
headers: headers(apiKey),
body: JSON.stringify(toCreateBody(opts)),
@@ -147,7 +148,7 @@ export class Browser {
static async connect(id: string, opts: { apiKey?: string; apiUrl?: string } = {}): Promise<Browser> {
const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await fetch(`${apiUrl}/v1/browsers/${encodeURIComponent(id)}`, {
+ const resp = await apiFetch(`${apiUrl}/v1/browsers/${encodeURIComponent(id)}`, {
headers: headers(apiKey),
});
if (!resp.ok) {
@@ -157,7 +158,7 @@ export class Browser {
}
async delete(): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/v1/browsers/${encodeURIComponent(this.id)}`, {
+ const resp = await apiFetch(`${this.apiUrl}/v1/browsers/${encodeURIComponent(this.id)}`, {
method: "DELETE",
headers: headers(this.apiKey),
});
@@ -202,7 +203,7 @@ export class BrowserProfile {
const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
const body: Record<string, unknown> = {};
if (opts.name !== undefined) body.name = opts.name;
- const resp = await fetch(`${apiUrl}/v1/profiles`, {
+ const resp = await apiFetch(`${apiUrl}/v1/profiles`, {
method: "POST",
headers: headers(apiKey),
body: JSON.stringify(body),
@@ -216,7 +217,7 @@ export class BrowserProfile {
static async list(opts: { apiKey?: string; apiUrl?: string } = {}): Promise<BrowserProfile[]> {
const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await fetch(`${apiUrl}/v1/profiles`, {
+ const resp = await apiFetch(`${apiUrl}/v1/profiles`, {
headers: headers(apiKey),
});
if (!resp.ok) {
@@ -229,7 +230,7 @@ export class BrowserProfile {
static async connect(idOrName: string, opts: { apiKey?: string; apiUrl?: string } = {}): Promise<BrowserProfile> {
const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await fetch(`${apiUrl}/v1/profiles/${encodeURIComponent(idOrName)}`, {
+ const resp = await apiFetch(`${apiUrl}/v1/profiles/${encodeURIComponent(idOrName)}`, {
headers: headers(apiKey),
});
if (!resp.ok) {
@@ -239,7 +240,7 @@ export class BrowserProfile {
}
async delete(): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/v1/profiles/${encodeURIComponent(this.id)}`, {
+ const resp = await apiFetch(`${this.apiUrl}/v1/profiles/${encodeURIComponent(this.id)}`, {
method: "DELETE",
headers: headers(this.apiKey),
});
@@ -249,7 +250,7 @@ export class BrowserProfile {
}
async checkAuth(opts: BrowserProfileAuthCheckCreateOpts): Promise<BrowserProfileAuthCheck> {
- const resp = await fetch(`${this.apiUrl}/v1/profiles/${encodeURIComponent(this.id)}/auth-checks`, {
+ const resp = await apiFetch(`${this.apiUrl}/v1/profiles/${encodeURIComponent(this.id)}/auth-checks`, {
method: "POST",
headers: headers(this.apiKey),
body: JSON.stringify(toAuthCheckBody(opts)),
@@ -306,7 +307,7 @@ export class BrowserProfileAuthCheck {
static async connect(id: string, opts: { apiKey?: string; apiUrl?: string } = {}): Promise<BrowserProfileAuthCheck> {
const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await fetch(`${apiUrl}/v1/profile-auth-checks/${encodeURIComponent(id)}`, {
+ const resp = await apiFetch(`${apiUrl}/v1/profile-auth-checks/${encodeURIComponent(id)}`, {
headers: headers(apiKey),
});
if (!resp.ok) {
diff --git a/sdks/typescript/src/exec.ts b/sdks/typescript/src/exec.ts
index 29d12b43..81162899 100644
--- a/sdks/typescript/src/exec.ts
+++ b/sdks/typescript/src/exec.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
import { openWebSocket } from "./websocket.js";
import { ShellImpl, type Shell, type ShellOpts } from "./shell.js";
@@ -141,7 +142,7 @@ export class Exec {
if (opts.timeout != null) body.timeout = opts.timeout;
if (opts.maxRunAfterDisconnect != null) body.maxRunAfterDisconnect = opts.maxRunAfterDisconnect;
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body),
@@ -250,7 +251,7 @@ export class Exec {
}
async list(): Promise<ExecSessionInfo[]> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec`, {
headers: this.headers,
});
@@ -265,7 +266,7 @@ export class Exec {
const body: Record<string, unknown> = {};
if (signal != null) body.signal = signal;
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/${sessionId}/kill`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/${sessionId}/kill`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body),
@@ -353,7 +354,7 @@ export class Exec {
if (opts.cwd) body.cwd = opts.cwd;
body.timeout = opts.timeout != null ? opts.timeout : 60;
- let resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run-async`, {
+ let resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run-async`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body),
@@ -365,7 +366,7 @@ export class Exec {
// "sandbox not found" 404s here too and re-404s below, surfacing the same
// error.)
if (resp.status === 404) {
- resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run`, {
+ resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body),
@@ -427,7 +428,7 @@ export class Exec {
/** Fetch the current result of an exec session (poll target for run()). */
private async result(execId: string): Promise<ExecRunResult> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/${execId}/result`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/${execId}/result`, {
headers: this.headers,
});
diff --git a/sdks/typescript/src/filesystem.ts b/sdks/typescript/src/filesystem.ts
index f55d882d..cba88e4d 100644
--- a/sdks/typescript/src/filesystem.ts
+++ b/sdks/typescript/src/filesystem.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
export interface EntryInfo {
name: string;
isDir: boolean;
@@ -33,7 +34,7 @@ export class Filesystem {
const deadline = Date.now() + 120_000;
let delay = 500;
for (;;) {
- const resp = await fetch(url, init);
+ const resp = await apiFetch(url, init);
if (resp.status !== 503) return resp;
let waking = false;
try { waking = (await resp.clone().json())?.waking === true; } catch { /* not JSON */ }
@@ -83,7 +84,7 @@ export class Filesystem {
}
const url = `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`;
// A stream body can't be replayed across a wake retry; string/bytes can.
- const resp = isStream ? await fetch(url, opts) : await this.wfetch(url, opts);
+ const resp = isStream ? await apiFetch(url, opts) : await this.wfetch(url, opts);
if (!resp.ok) throw new Error(`Failed to write ${path}: ${resp.status}`);
}
diff --git a/sdks/typescript/src/http2.ts b/sdks/typescript/src/http2.ts
index 8714d076..0f6fb188 100644
--- a/sdks/typescript/src/http2.ts
+++ b/sdks/typescript/src/http2.ts
@@ -1,18 +1,27 @@
-// Connection pre-warming for the Node global fetch dispatcher.
+// The sandbox client's transport: an HTTP/2 connection pool it owns and
+// passes to every request it makes, plus the pre-warming of that pool.
//
-// WHY: under a concurrent burst, the dominant cost of a sandbox create is not
-// our API — it is opening ~100 TLS connections at once from one process.
-// Measured against prod from an in-region client, 100 concurrent creates:
+// Client-owned, not global. The pool is an undici Agent handed to fetch as the
+// per-request `dispatcher`; the process's global dispatcher is never touched,
+// so an application's own fetch traffic, and any other library's, keeps its
+// own settings. Nothing here runs at import: the Agent is created on the
+// first request the sandbox client makes, and the pool is warmed on the
+// first `Sandbox.create` (or on an explicit `prewarmConnections` call from a
+// program that wants the cost paid before its timing loop).
+//
+// WHY a warm pool: under a concurrent burst, the dominant cost of a sandbox
+// create is not our API but opening ~100 TLS connections at once from one
+// process. Measured against prod from an in-region client, 100 concurrent
+// creates:
//
// cold connections min 686 median 716 p95 731 (flat: all pay the same)
// warm connections min 390 median 412 p95 436 (-304ms, -42%)
//
-// The flatness is the tell — every request in the burst pays the same fixed
-// cost, so it is admission/setup, not queueing behind our server. Corroborated
-// end to end: a raw TLS test measured 100 concurrent handshakes at ~301ms
-// (a single handshake is ~27ms), and the server-side phases sum to ~20ms
-// (edge CPU 2ms, pool claim 10ms, control-plane finalize 1ms, worker claim 6ms)
-// against a ~350ms client-observed create. The ~300ms gap is the handshakes.
+// The flatness is the tell: every request in the burst pays the same fixed
+// cost, so it is admission/setup, not queueing behind our server. A raw TLS
+// test measured 100 concurrent handshakes at ~301ms (a single handshake is
+// ~27ms), and the server-side phases sum to ~20ms against a ~350ms
+// client-observed create. The ~300ms gap is the handshakes.
//
// WHAT: hold a pool of already-established connections open so a later burst
// reuses them instead of negotiating TLS inside the latency it is measuring.
@@ -25,12 +34,11 @@
// undici tried the dead sockets first. The warm pool must be kept alive.)
//
// `allowH2` negotiates per-origin via ALPN, so HTTP/1.1-only origins keep
-// working unchanged. Browser-guarded (no global dispatcher there). Opt out of
-// HTTP/2 with OPENCOMPUTER_DISABLE_HTTP2=1, or of warming with
+// working unchanged. Outside Node (browsers, Workers) there is no undici and
+// requests go to the global fetch untouched. Opt out of HTTP/2 with
+// OPENCOMPUTER_DISABLE_HTTP2=1, or of warming with
// OPENCOMPUTER_DISABLE_PREWARM=1 / OPENCOMPUTER_PREWARM_CONNECTIONS=0.
-let configurePromise: Promise<void> | null = null;
-
// How many connections to hold open, and how often to keep them alive.
//
// 48. Swept against prod from an IAD runner (4 vCPU) at burst-100, TTI p50:
@@ -38,28 +46,30 @@ let configurePromise: Promise<void> | null = null;
// prewarm=100 23,990ms opening 100 TLS connections while 100 creates are
// in flight starves the event loop; everything
// unblocks together at the end
-// prewarm=0 624ms the opposite failure — undici marks an h2 session
+// prewarm=0 624ms the opposite failure: undici marks an h2 session
// busy per in-flight POST, so 100 concurrent creates
// queue behind each other on one connection
// prewarm=32 338ms
// prewarm=48 301ms / 328ms (two runs)
// prewarm=64 312ms
//
-// The curve is flat between 32 and 64 — run-to-run variance on TTI p50 is ~27ms,
-// so 48 vs 64 is not a real difference — and turns back up past that because
-// establishing the pool starts costing more than it saves (424ms to open 64
-// versus 153ms for 48, paid inside the measured window). 48 sits at the bottom
-// with margin on both sides.
-//
-// Note the 100 figure is not a typo: this was shipped as the default on the
-// theory that a smaller pool merely warms fewer connections. It is worth 34x in
-// the exact shape it was written for.
+// The curve is flat between 32 and 64 (run-to-run variance on TTI p50 is
+// ~27ms) and turns back up past that because establishing the pool starts
+// costing more than it saves (424ms to open 64 versus 153ms for 48, paid
+// inside the measured window). 48 sits at the bottom with margin on both sides.
const DEFAULT_PREWARM = 48;
const KEEPALIVE_INTERVAL_MS = 30_000;
// Above undici's 4s default so an idle connection survives between phases of a
// workload; still far below any sane server-side idle close.
const KEEP_ALIVE_TIMEOUT_MS = 600_000;
+const DEFAULT_API_URL = "https://app.opencomputer.dev";
+
+/** The non-standard init undici's fetch reads: which pool serves the request. */
+type DispatchedInit = RequestInit & { dispatcher?: unknown };
+
+const isNode = (): boolean => typeof process !== "undefined" && !!process.versions?.node;
+
function intFromEnv(name: string, fallback: number): number {
const raw = process.env?.[name];
if (raw === undefined || raw === "") return fallback;
@@ -67,56 +77,69 @@ function intFromEnv(name: string, fallback: number): number {
return Number.isFinite(n) && n >= 0 ? n : fallback;
}
-// configureHttp2 installs the global dispatcher on Node and RESOLVES ONLY ONCE
-// IT IS INSTALLED. The entry point (index.ts) awaits it at module load, so by
-// the time an importer can issue a request the dispatcher is already swapped —
-// otherwise the first burst races the async `import("undici")` and leaks onto
-// the default dispatcher (the exact failure that made this a silent no-op).
-// Memoized + never rejects, so importing the SDK can safely `await` it.
-export function configureHttp2(): Promise<void> {
- if (configurePromise) return configurePromise;
- configurePromise = (async () => {
- const isNode = typeof process !== "undefined" && !!process.versions?.node;
- if (isNode !== true) return; // browser: no global dispatcher to set
- if (process.env?.OPENCOMPUTER_DISABLE_HTTP2) return;
+let dispatcherPromise: Promise<unknown> | null = null;
+
+// The pool, created once on first use. Resolves to `undefined` outside Node,
+// when HTTP/2 is disabled, or when undici cannot be loaded; requests then use
+// the global fetch as it is. Never rejects.
+function dispatcher(): Promise<unknown> {
+ if (dispatcherPromise) return dispatcherPromise;
+ dispatcherPromise = (async () => {
+ if (!isNode()) return undefined;
+ if (process.env?.OPENCOMPUTER_DISABLE_HTTP2) return undefined;
try {
// Dynamic import so browser bundlers never pull undici into the graph.
// undici is a hard dependency on Node (see package.json) so this resolves;
- // the catch keeps a stripped-down/browser install on the default agent.
- const { Agent, setGlobalDispatcher } = await import("undici");
- setGlobalDispatcher(
- new Agent({
- allowH2: true,
- keepAliveTimeout: KEEP_ALIVE_TIMEOUT_MS,
- keepAliveMaxTimeout: KEEP_ALIVE_TIMEOUT_MS,
- }),
- );
+ // the catch keeps a stripped-down install on the default transport.
+ const { Agent } = await import("undici");
+ return new Agent({
+ allowH2: true,
+ keepAliveTimeout: KEEP_ALIVE_TIMEOUT_MS,
+ keepAliveMaxTimeout: KEEP_ALIVE_TIMEOUT_MS,
+ });
} catch {
- /* undici unavailable — keep the default dispatcher */
+ return undefined;
}
})();
- return configurePromise;
+ return dispatcherPromise;
+}
+
+/**
+ * fetch over the sandbox client's own connection pool. The global fetch is
+ * called (so a test that replaces it sees every request) with the pool as the
+ * per-request dispatcher; the global dispatcher is left alone.
+ */
+export async function apiFetch(input: string | URL, init?: RequestInit): Promise<Response> {
+ const pool = await dispatcher();
+ if (!pool) return fetch(input, init);
+ const dispatched: DispatchedInit = { ...init, dispatcher: pool };
+ return fetch(input, dispatched);
}
let warmPromise: Promise<void> | null = null;
let keepAliveTimer: ReturnType<typeof setInterval> | null = null;
-// prewarmConnections opens `count` connections to `apiUrl` and keeps them alive,
-// so a later burst reuses them instead of paying ~300ms of concurrent TLS
-// handshakes inside its own latency. Idempotent, never rejects, and safe to call
-// on a hot path: callers may fire-and-forget it.
-//
-// The keepalive timer is unref'd — a warm pool must never be the reason a
-// process stays alive.
-export function prewarmConnections(apiUrl: string, count?: number): Promise<void> {
+/**
+ * Opens `count` connections to the API and keeps them alive, so a later burst
+ * reuses them instead of paying ~300ms of concurrent TLS handshakes inside
+ * its own latency. Idempotent, never rejects, and safe to call on a hot path:
+ * `Sandbox.create` fires it on first use and callers may fire-and-forget it
+ * earlier, before a timing loop.
+ *
+ * `apiUrl` defaults to `OPENCOMPUTER_API_URL` or `https://app.opencomputer.dev`.
+ * The keepalive timer is unref'd: a warm pool is never the reason a process
+ * stays alive.
+ */
+export function prewarmConnections(apiUrl?: string, count?: number): Promise<void> {
if (warmPromise) return warmPromise;
warmPromise = (async () => {
- const isNode = typeof process !== "undefined" && !!process.versions?.node;
- if (isNode !== true) return;
+ if (!isNode()) return;
if (process.env?.OPENCOMPUTER_DISABLE_PREWARM) return;
const n = count ?? intFromEnv("OPENCOMPUTER_PREWARM_CONNECTIONS", DEFAULT_PREWARM);
if (n <= 0) return;
- await configureHttp2(); // warm onto the configured dispatcher, not the default
+ const origin = (apiUrl ?? process.env?.OPENCOMPUTER_API_URL ?? DEFAULT_API_URL)
+ .replace(/\/+$/, "")
+ .replace(/\/api$/, "");
// The warm MUST use the same method class as the traffic it is warming for.
// undici refuses to multiplex non-idempotent requests over one HTTP/2
@@ -124,17 +147,15 @@ export function prewarmConnections(apiUrl: string, count?: number): Promise<void
// flight), so N concurrent POSTs need N separate connections, while N
// concurrent GETs happily share ONE h2 session. Warming with GET therefore
// warms a single connection and leaves a POST burst to pay ~100 handshakes
- // anyway — which is exactly why the first version of this measured as a
- // no-op end to end. POST to a path that costs the server nothing (405/404
- // is fine — we only want the socket).
- const base = apiUrl.replace(/\/+$/, "");
+ // anyway. POST to a path that costs the server nothing (405/404 is fine;
+ // only the socket matters).
const ping = (): Promise<unknown> =>
- fetch(`${base}/health`, { method: "POST" })
+ apiFetch(`${origin}/health`, { method: "POST" })
.then((r) => r.arrayBuffer())
.catch(() => undefined);
// Fire them together: a connection is only created while another is still
- // busy, so the pings must overlap — sequential pings would reuse one socket.
+ // busy, so the pings must overlap; sequential pings would reuse one socket.
await Promise.all(Array.from({ length: n }, ping));
if (keepAliveTimer === null) {
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index ff493795..a658f5c5 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -1,29 +1,12 @@
-import { configureHttp2, prewarmConnections } from "./http2.js";
-
-// Switch the Node global fetch dispatcher to HTTP/2 on import (browser-safe
-// no-op). Multiplexes concurrent requests over one connection — a large burst
-// win for create(). Top-level await so the dispatcher is installed BEFORE the
-// importer can issue any request (a dynamic `import("@opencomputer/sdk")` — how
-// the leaderboard adapter loads us — fully settles this first); otherwise the
-// first burst races the async undici import and leaks onto HTTP/1.1. The SDK is
-// ESM-only, so top-level await breaks no existing (already-ESM) consumer, and
-// configureHttp2 never rejects. See http2.ts.
-await configureHttp2();
-
-// Open the connection pool at IMPORT, not at the first create.
+// @opencomputer/sdk: the sandbox client. Node-only: the image builder reads
+// the filesystem and the transport pools HTTP/2 connections through undici.
+// Nothing runs at import; the connection pool is created on the first
+// request and warmed on the first `Sandbox.create`.
//
-// prewarmConnections used to fire from Sandbox.create(), which put the pool's
-// own setup INSIDE the window a burst measures — 48 connections cost ~153ms to
-// establish, and the first creates race them. Starting here means an importer
-// that loads the SDK before its timing loop (the leaderboard adapter does) has
-// the pool ready by the time it matters. Same connection count, just earlier.
-//
-// Deliberately NOT awaited: import must not block on the network. It is
-// memoized (warmPromise), so Sandbox.create()'s own call remains as the path
-// that covers a programmatically-supplied apiUrl, and becomes a no-op here.
-void prewarmConnections(
- (process.env?.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev").replace(/\/api\/?$/, ""),
-);
+// The management API client for Serverless Agents lives on its own portable
+// subpath, `@opencomputer/sdk/managed-agents`, whose module graph has no Node
+// dependency. It is not re-exported here so that importing it never drags
+// this graph along.
export {
Sandbox,
@@ -56,8 +39,6 @@ export {
type BrowserProfileData
} from "./browser.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, ExecTimeoutError, 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";
@@ -65,6 +46,9 @@ export { type Shell, type ShellOpts, type ShellRunOpts, ShellBusyError, ShellClo
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
export { Templates, type TemplateInfo } from "./template.js";
export { SDK_VERSION, SDK_VERSION_HEADER } from "./version.js";
+// Warm the sandbox client's connection pool ahead of a burst. `Sandbox.create`
+// does this on first use; a program that measures creates calls it earlier.
+export { prewarmConnections } from "./http2.js";
export {
Webhooks,
WebhookDeliveries,
@@ -83,6 +67,13 @@ export {
type SandboxStopReason,
type SandboxWebhookEventType,
} from "./webhooks.js";
+export {
+ verifyWebhook,
+ WebhookVerificationError,
+ type WebhookDelivery,
+ type WebhookEvent,
+ type VerifyWebhookOptions,
+} from "./verify-webhook.js";
export { SecretStore, type SecretStoreInfo, type SecretEntryInfo, type SecretStoreOpts, type CreateSecretStoreOpts, type UpdateSecretStoreOpts } from "./project.js";
export {
Usage,
@@ -100,7 +91,7 @@ export {
type SandboxUsageTotals,
type TagKeyInfo,
} from "./usage.js";
-// Node.js-only modules (use crypto, fs, path) — import via "@opencomputer/sdk/node".
+// Node.js-only modules (use crypto, fs, path) — also exported via "@opencomputer/sdk/node".
// The Image builder and the Snapshots client are exported as VALUES, not only
// as types. Both were type-only, so `import { Image } from "@opencomputer/sdk"`
// — which the Image reference documents — failed at runtime with "does not
diff --git a/sdks/typescript/src/managed-agents/client.test.ts b/sdks/typescript/src/managed-agents/client.test.ts
new file mode 100644
index 00000000..b263fadf
--- /dev/null
+++ b/sdks/typescript/src/managed-agents/client.test.ts
@@ -0,0 +1,256 @@
+import { describe, expect, it } from "vitest";
+import { OpenComputer } from "./client.js";
+import { OpenComputerError } from "./errors.js";
+
+interface Call { method: string; path: string; headers: Record<string, string>; body?: unknown }
+
+// A fake of the management API that records every call and answers from a
+// table keyed by `METHOD /path`. Unlisted routes answer 404 with the API's
+// error envelope.
+function fakeApi(routes: Record<string, (call: Call) => Response> = {}) {
+ const calls: Call[] = [];
+ const fetch: typeof globalThis.fetch = async (input, init) => {
+ const url = new URL(String(input));
+ const headers: Record<string, string> = {};
+ new Headers(init?.headers).forEach((value, name) => { headers[name] = value; });
+ const call: Call = { method: init?.method ?? "GET", path: `${url.pathname}${url.search}`, headers };
+ if (typeof init?.body === "string") call.body = JSON.parse(init.body) as unknown;
+ calls.push(call);
+ const route = routes[`${call.method} ${url.pathname}`];
+ if (route) return route(call);
+ return Response.json({ error: { code: "not_found", message: `no route ${call.method} ${url.pathname}` } }, { status: 404 });
+ };
+ return { calls, fetch, last: () => calls[calls.length - 1] };
+}
+
+const oc = (api: ReturnType<typeof fakeApi>) => new OpenComputer({ apiKey: "osb_test", fetch: api.fetch });
+
+describe("OpenComputer client", () => {
+ it("sends the API key, JSON and the Idempotency-Key on create, and reports 200 as not created", async () => {
+ const api = fakeApi({
+ "POST /api/managed-agents/sessions": (call) =>
+ Response.json(
+ { session: { id: "ses_1", status: "new", createdAt: "t" }, deployment: { id: "dep_1", agentId: "worker", alias: "development", createdAt: "t" } },
+ { status: call.headers["idempotency-key"] === "again" ? 200 : 201 },
+ ),
+ });
+ const created = await oc(api).sessions.create(
+ { agentId: "worker@development", labels: { request: "task_1" } },
+ { idempotencyKey: "task_1" },
+ );
+ expect(created).toEqual({
+ session: { id: "ses_1", status: "new", createdAt: "t" },
+ deployment: { id: "dep_1", agentId: "worker", alias: "development", createdAt: "t" },
+ created: true,
+ });
+ expect(api.last()).toMatchObject({
+ method: "POST",
+ path: "/api/managed-agents/sessions",
+ headers: { "x-api-key": "osb_test", "content-type": "application/json", "idempotency-key": "task_1" },
+ body: { agentId: "worker@development", labels: { request: "task_1" } },
+ });
+ const replay = await oc(api).sessions.create({ agentId: "worker@development" }, { idempotencyKey: "again" });
+ expect(replay.created).toBe(false);
+ const bare = await oc(api).sessions.create({ agentId: "worker@development" });
+ expect(bare.created).toBe(true);
+ expect(api.last().headers["idempotency-key"]).toBeUndefined();
+ });
+
+ it("gets, ends, interrupts and labels a session on the documented routes", 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/ses_1": () => Response.json(session),
+ "POST /api/managed-agents/sessions/ses_1/end": () => Response.json({ ...session, status: "ended" }),
+ "POST /api/managed-agents/sessions/ses_1/interrupt": () => Response.json(session),
+ "PATCH /api/managed-agents/sessions/ses_1/labels": (call) => Response.json({ ...session, labels: (call.body as { set: unknown }).set }),
+ });
+ const client = oc(api);
+ expect(await client.sessions.get("ses_1")).toEqual(session);
+ expect((await client.sessions.end("ses_1")).status).toBe("ended");
+ expect((await client.sessions.interrupt("ses_1")).id).toBe("ses_1");
+ const labelled = await client.sessions.setLabels("ses_1", { set: { title: "Fix login" }, unset: ["archived"] });
+ expect(labelled.labels).toEqual({ title: "Fix login" });
+ expect(api.last()).toMatchObject({ method: "PATCH", body: { set: { title: "Fix login" }, unset: ["archived"] } });
+ });
+
+ it("lists sessions with filters, label filters and paging, and normalizes a missing cursor", async () => {
+ const rows = [{ id: "ses_2" }, { id: "ses_1" }];
+ let withCursor = true;
+ const api = fakeApi({
+ "GET /api/managed-agents/sessions": () => Response.json(withCursor ? { sessions: rows, nextCursor: "c2" } : { sessions: rows }),
+ });
+ const page = await oc(api).sessions.list({
+ project: "prj_1", environment: "development", agent: "worker", status: "idle",
+ labels: { request: "task_1", archived: "false" }, cursor: "c1", limit: 20,
+ });
+ expect(page).toEqual({ sessions: rows, nextCursor: "c2" });
+ const query = new URL(`https://x${api.last().path}`).searchParams;
+ expect(Object.fromEntries(query.entries())).toEqual({
+ project: "prj_1", environment: "development", agent: "worker", status: "idle",
+ "label.request": "task_1", "label.archived": "false", cursor: "c1", limit: "20",
+ });
+ withCursor = false;
+ expect(await oc(api).sessions.list()).toEqual({ sessions: rows, nextCursor: null });
+ expect(api.last().path).toBe("/api/managed-agents/sessions");
+ });
+
+ it("sends a turn with its key, mode and payload, and reads the receipt from 202 and 200", async () => {
+ let duplicate = false;
+ const api = fakeApi({
+ "POST /api/managed-agents/sessions/ses_1/turns": () =>
+ Response.json({ turnId: "turn_1", status: duplicate ? "running" : "queued", duplicate }, { status: duplicate ? 200 : 202 }),
+ });
+ const client = oc(api);
+ const receipt = await client.sessions.turns.send("ses_1", {
+ input: "Fix the login page.",
+ idempotencyKey: "task_1/start",
+ payload: { repo: "acme/web", ref: "main" },
+ });
+ expect(receipt).toEqual({ turnId: "turn_1", status: "queued", duplicate: false });
+ expect(api.last().body).toEqual({
+ input: "Fix the login page.",
+ idempotencyKey: "task_1/start",
+ payload: { repo: "acme/web", ref: "main" },
+ });
+ duplicate = true;
+ expect(await client.sessions.turns.send("ses_1", { input: "again", mode: "steer" })).toEqual({
+ turnId: "turn_1", status: "running", duplicate: true,
+ });
+ expect(api.last().body).toEqual({ input: "again", mode: "steer" });
+ });
+
+ it("reads the event log from a cursor", async () => {
+ const events = [{ id: "e1", seq: 1, type: "session.created", data: {} }];
+ 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");
+ await oc(api).sessions.events.list("ses_1");
+ expect(api.last().path).toBe("/api/managed-agents/sessions/ses_1/events?after=0");
+ });
+
+ it("covers projects, agents and deployments", async () => {
+ const project = { id: "prj_1", slug: "p", name: "P", environments: [], agents: [], createdAt: "t", updatedAt: "t" };
+ const api = fakeApi({
+ "GET /api/managed-agents/projects": () => Response.json({ projects: [project] }),
+ "POST /api/managed-agents/projects": () => Response.json(project, { status: 201 }),
+ "GET /api/managed-agents/projects/prj_1": () =>
+ Response.json({ project, deployments: [], sessions: [], connections: [], channels: [], schedules: [] }),
+ "GET /api/managed-agents/agents": () => Response.json({ agents: [{ id: "worker", name: "Worker", activeAlias: "development" }] }),
+ "GET /api/managed-agents/deployments": () => Response.json({ deployments: [{ id: "dep_1", agentId: "worker", alias: "development", createdAt: "t" }] }),
+ "GET /api/managed-agents/deployments/dep_1": () => Response.json({ id: "dep_1", agentId: "worker", alias: "development", createdAt: "t" }),
+ });
+ const client = oc(api);
+ expect(await client.projects.list()).toEqual([project]);
+ expect((await client.projects.create({ name: "P" })).id).toBe("prj_1");
+ expect((await client.projects.get("prj_1")).project).toEqual(project);
+ expect((await client.agents.list())[0].activeAlias).toBe("development");
+ expect((await client.deployments.list({ agentId: "worker" }))[0].id).toBe("dep_1");
+ expect(api.last().path).toBe("/api/managed-agents/deployments?agentId=worker");
+ expect((await client.deployments.get("dep_1")).alias).toBe("development");
+ });
+
+ it("drives memory documents with the conditional headers the API requires", async () => {
+ const doc = { id: "workshop", title: "W", text: "", summary: "", agentWrites: "enabled", revision: "r1", bytes: 0, maxBytes: 8192, updatedAt: "t", writer: { kind: "owner" } };
+ const api = fakeApi({
+ "GET /api/managed-agents/projects/prj_1/memory": () => Response.json({ resources: [] }),
+ "GET /api/managed-agents/projects/prj_1/memory/notes/documents": () => Response.json({ documents: [doc], nextCursor: null }),
+ "GET /api/managed-agents/projects/prj_1/memory/notes/documents/workshop": () => Response.json(doc),
+ "PUT /api/managed-agents/projects/prj_1/memory/notes/documents/workshop": () => Response.json(doc, { status: 201 }),
+ "PATCH /api/managed-agents/projects/prj_1/memory/notes/documents/workshop": () => Response.json(doc),
+ "DELETE /api/managed-agents/projects/prj_1/memory/notes/documents/workshop": () => new Response(null, { status: 204 }),
+ });
+ const memory = oc(api).projects.memory;
+ const env = { environment: "development" as const };
+ expect(await memory.resources("prj_1", env)).toEqual({ resources: [] });
+ expect(api.last().path).toBe("/api/managed-agents/projects/prj_1/memory?environment=development");
+ expect((await memory.documents.list("prj_1", "notes", { ...env, cursor: "c" })).documents).toEqual([doc]);
+ expect(api.last().path).toContain("cursor=c");
+ expect(await memory.documents.get("prj_1", "notes", "workshop", env)).toEqual(doc);
+ await memory.documents.create("prj_1", "notes", "workshop", { title: "W", text: "" }, env);
+ expect(api.last()).toMatchObject({ method: "PUT", headers: { "if-none-match": "*" }, body: { title: "W", text: "" } });
+ await memory.documents.replace("prj_1", "notes", "workshop", { text: "new" }, { ...env, revision: "r1" });
+ expect(api.last()).toMatchObject({ method: "PUT", headers: { "if-match": '"r1"' }, body: { text: "new" } });
+ await memory.documents.patch("prj_1", "notes", "workshop", { agentWrites: "disabled" }, { ...env, revision: '"r1"' });
+ expect(api.last()).toMatchObject({ method: "PATCH", headers: { "if-match": '"r1"' } });
+ await memory.documents.delete("prj_1", "notes", "workshop", { ...env, revision: "r1" });
+ expect(api.last()).toMatchObject({ method: "DELETE", headers: { "if-match": '"r1"' } });
+ });
+
+ it("covers webhooks, event subscriptions and the repository listing", async () => {
+ const webhook = { id: "wh_1", projectId: "prj_1", environment: "development", agentId: "worker", name: "gh", enabled: true, invocationUrl: "https://x/wh_1/tok", token: "tok", createdAt: "t", updatedAt: "t" };
+ const subscription = { id: "evs_1", projectId: "prj_1", events: ["turn.completed"], destination: { type: "session", sessionId: "ses_c" }, createdAt: "t" };
+ const api = fakeApi({
+ "GET /api/managed-agents/projects/prj_1/webhooks": () => Response.json({ webhooks: [webhook] }),
+ "POST /api/managed-agents/projects/prj_1/webhooks": () => Response.json({ webhook }, { status: 201 }),
+ "PATCH /api/managed-agents/projects/prj_1/webhooks/wh_1": () => Response.json({ webhook: { ...webhook, enabled: false } }),
+ "POST /api/managed-agents/projects/prj_1/webhooks/wh_1/rotate-token": () => Response.json({ webhook }),
+ "DELETE /api/managed-agents/projects/prj_1/webhooks/wh_1": () => new Response(null, { status: 204 }),
+ "GET /api/managed-agents/projects/prj_1/webhooks/wh_1/requests": () => Response.json({ requests: [{ id: "req_1" }] }),
+ "POST /api/managed-agents/projects/prj_1/event-subscriptions": () => Response.json({ subscription }, { status: 201 }),
+ "GET /api/managed-agents/projects/prj_1/event-subscriptions": () => Response.json({ subscriptions: [subscription] }),
+ "GET /api/managed-agents/projects/prj_1/event-subscriptions/evs_1": () => Response.json({ subscription }),
+ "DELETE /api/managed-agents/projects/prj_1/event-subscriptions/evs_1": () => new Response(null, { status: 204 }),
+ "GET /api/managed-agents/projects/prj_1/github/repositories": () =>
+ Response.json({ repositories: [{ id: 1, fullName: "acme/web", private: true, defaultBranch: "main", archived: false }] }),
+ });
+ const projects = oc(api).projects;
+ expect(await projects.webhooks.list("prj_1", { environment: "development" })).toEqual([webhook]);
+ expect(api.last().path).toBe("/api/managed-agents/projects/prj_1/webhooks?environment=development");
+ expect(await projects.webhooks.create("prj_1", { name: "gh", agentId: "worker", environment: "development" })).toEqual(webhook);
+ expect((await projects.webhooks.update("prj_1", "wh_1", { enabled: false, identity: null })).enabled).toBe(false);
+ expect(api.last().body).toEqual({ enabled: false, identity: null });
+ expect((await projects.webhooks.rotateToken("prj_1", "wh_1")).token).toBe("tok");
+ await projects.webhooks.delete("prj_1", "wh_1");
+ expect(await projects.webhooks.requests("prj_1", "wh_1")).toEqual([{ id: "req_1" }]);
+
+ expect(await projects.eventSubscriptions.create("prj_1", { events: ["turn.completed"], destination: { type: "session", sessionId: "ses_c" } })).toEqual(subscription);
+ expect(await projects.eventSubscriptions.list("prj_1")).toEqual([subscription]);
+ expect(await projects.eventSubscriptions.get("prj_1", "evs_1")).toEqual(subscription);
+ await projects.eventSubscriptions.delete("prj_1", "evs_1");
+ expect(api.last().method).toBe("DELETE");
+
+ const repositories = await projects.github.repositories("prj_1", { environment: "development", limit: 50 });
+ expect(repositories).toEqual({
+ repositories: [{ id: 1, fullName: "acme/web", private: true, defaultBranch: "main", archived: false }],
+ nextCursor: null,
+ });
+ expect(api.last().path).toBe("/api/managed-agents/projects/prj_1/github/repositories?environment=development&limit=50");
+ });
+
+ it("throws one error shape for every failure: the API's code, a status-derived code, or the bare text", async () => {
+ const api = fakeApi({
+ "GET /api/managed-agents/sessions/conflict": () =>
+ Response.json({ error: { code: "idempotency_conflict", message: "different inputs" } }, { status: 409 }),
+ "GET /api/managed-agents/sessions/bare": () => Response.json({ error: "Unauthorized" }, { status: 401 }),
+ "GET /api/managed-agents/sessions/text": () => new Response("Bad Gateway", { status: 502 }),
+ "GET /api/managed-agents/sessions/limited": () =>
+ Response.json({ error: { code: "rate_limited", message: "slow down" } }, { status: 429, headers: { "retry-after": "3" } }),
+ });
+ const client = oc(api);
+ const conflict = await client.sessions.get("conflict").catch((cause: unknown) => cause);
+ expect(conflict).toBeInstanceOf(OpenComputerError);
+ expect(conflict).toMatchObject({ code: "idempotency_conflict", status: 409, message: "different inputs" });
+ expect(await client.sessions.get("bare").catch((cause: unknown) => cause)).toMatchObject({
+ code: "unauthorized", status: 401, message: "Unauthorized",
+ });
+ expect(await client.sessions.get("text").catch((cause: unknown) => cause)).toMatchObject({
+ code: "unavailable", status: 502, message: "Bad Gateway",
+ });
+ expect(await client.sessions.get("missing").catch((cause: unknown) => cause)).toMatchObject({
+ code: "not_found", status: 404,
+ });
+ expect(await client.sessions.get("limited").catch((cause: unknown) => cause)).toMatchObject({
+ code: "rate_limited", status: 429, retryAfter: 3,
+ });
+ });
+
+ 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 });
+ void client.sessions.get("x").catch(() => undefined);
+ expect(() => new OpenComputer({ apiKey: "", fetch: api.fetch })).toThrow(/API key/);
+ return new Promise<void>((resolve) => setTimeout(resolve, 0)).then(() => {
+ expect(api.last().path).toBe("/mgmt/sessions/x");
+ });
+ });
+});
diff --git a/sdks/typescript/src/managed-agents/client.ts b/sdks/typescript/src/managed-agents/client.ts
new file mode 100644
index 00000000..a1830f66
--- /dev/null
+++ b/sdks/typescript/src/managed-agents/client.ts
@@ -0,0 +1,524 @@
+// 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.
+
+import { Http, type HttpOptions, segment } from "./http.js";
+import {
+ startOnDocument,
+ type StartOnDocumentParams,
+ type StartOnDocumentResult,
+} from "./start-on-document.js";
+import type {
+ CreateEventSubscriptionBody,
+ EventSubscription,
+} from "./event-subscriptions.js";
+import type {
+ CreateMemoryDocumentBody,
+ MemoryDocument,
+ MemoryDocumentPage,
+ MemoryResourceInventory,
+ PatchMemoryDocumentBody,
+ ReplaceMemoryDocumentBody,
+} from "./memory.js";
+import type {
+ AgentSummary,
+ CreateProjectParams,
+ CreateSessionParams,
+ CreateWebhookParams,
+ Deployment,
+ Environment,
+ ListDeploymentsQuery,
+ ListEventsQuery,
+ ListRepositoriesQuery,
+ ListSessionsQuery,
+ ListWebhooksQuery,
+ Project,
+ ProjectDetail,
+ RepositoryPage,
+ SendTurnParams,
+ Session,
+ SessionCreated,
+ SessionEvent,
+ SessionPage,
+ SetLabelsParams,
+ TurnReceipt,
+ UpdateWebhookParams,
+ Webhook,
+ WebhookRequest,
+} from "./types.js";
+
+export interface OpenComputerOptions extends HttpOptions {
+ /** An OpenComputer API key. Server-side only; it must not reach a browser. */
+ apiKey: string;
+}
+
+export interface CallOptions {
+ signal?: AbortSignal;
+}
+
+export interface CreateSessionOptions extends CallOptions {
+ /**
+ * At most 256 characters. The same key with the same agent, deployment,
+ * environment and memory bindings returns the existing session; anything
+ * else under the key is `409 idempotency_conflict`.
+ */
+ idempotencyKey?: string;
+}
+
+export interface EnvironmentOptions extends CallOptions {
+ environment: Environment;
+}
+
+export interface DocumentWriteOptions extends EnvironmentOptions {
+ /** The revision the write is conditional on; sent as `If-Match`. */
+ revision: string;
+}
+
+export interface ListDocumentsOptions extends EnvironmentOptions {
+ cursor?: string;
+}
+
+// ── Sessions ──────────────────────────────────────────────────────────────────
+
+export class Turns {
+ constructor(private readonly http: Http) {}
+
+ /** `POST /sessions/<id>/turns`: admits a turn; follow it in the event log. */
+ async send(sessionId: string, params: SendTurnParams, options: CallOptions = {}): Promise<TurnReceipt> {
+ const body: Record<string, unknown> = { input: params.input };
+ 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 },
+ );
+ return {
+ turnId: answer.body.turnId,
+ status: answer.body.status === "running" ? "running" : "queued",
+ duplicate: answer.body.duplicate ?? answer.status === 200,
+ };
+ }
+}
+
+export class Events {
+ constructor(private readonly http: Http) {}
+
+ /**
+ * `GET /sessions/<id>/events?after=<seq>`: up to 500 events with a greater
+ * `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`, {
+ query: { after: query.after ?? 0 },
+ signal: options.signal,
+ });
+ return page.events;
+ }
+}
+
+export class Sessions {
+ readonly turns: Turns;
+ readonly events: Events;
+
+ constructor(private readonly http: Http) {
+ this.turns = new Turns(http);
+ this.events = new Events(http);
+ }
+
+ /** `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,
+ },
+ );
+ 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 });
+ }
+
+ /**
+ * `GET /sessions`: rows ordered by `createdAt` descending then `id`, with
+ * `nextCursor` for the next page. Sort the pages you hold by `updatedAt`
+ * for recent activity first.
+ */
+ async 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 };
+ }
+
+ /** `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 });
+ }
+
+ /** `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 });
+ }
+
+ /** `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`, {
+ body: params,
+ signal: options.signal,
+ });
+ }
+
+ /** Creates a memory document if needed, then a session bound to it, under one key. */
+ startOnDocument(params: StartOnDocumentParams): Promise<StartOnDocumentResult> {
+ return startOnDocument(this.http, params);
+ }
+}
+
+// ── Projects ──────────────────────────────────────────────────────────────────
+
+export class MemoryDocuments {
+ constructor(private readonly http: Http) {}
+
+ private path(projectId: string, resource: string, documentId?: string): string {
+ const base = `/projects/${segment(projectId)}/memory/${segment(resource)}/documents`;
+ return documentId === undefined ? base : `${base}/${segment(documentId)}`;
+ }
+
+ /** `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), {
+ query: { environment: options.environment, cursor: options.cursor },
+ signal: options.signal,
+ });
+ }
+
+ /** `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), {
+ query: { environment: options.environment },
+ signal: options.signal,
+ });
+ }
+
+ /** `PUT .../documents/<id>` with `If-None-Match: *`; `412` when the id is already used. */
+ create(
+ projectId: string,
+ resource: string,
+ documentId: string,
+ body: CreateMemoryDocumentBody,
+ options: EnvironmentOptions,
+ ): Promise<MemoryDocument> {
+ return this.http.request<MemoryDocument>("PUT", this.path(projectId, resource, documentId), {
+ query: { environment: options.environment },
+ headers: { "if-none-match": "*" },
+ body,
+ signal: options.signal,
+ });
+ }
+
+ /** `PUT .../documents/<id>` with `If-Match`: replaces text, and summary when given. */
+ replace(
+ projectId: string,
+ resource: string,
+ documentId: string,
+ body: ReplaceMemoryDocumentBody,
+ options: DocumentWriteOptions,
+ ): Promise<MemoryDocument> {
+ return this.http.request<MemoryDocument>("PUT", this.path(projectId, resource, documentId), {
+ query: { environment: options.environment },
+ headers: { "if-match": quote(options.revision) },
+ body,
+ signal: options.signal,
+ });
+ }
+
+ /** `PATCH .../documents/<id>` with `If-Match`: title or write policy. */
+ patch(
+ projectId: string,
+ resource: string,
+ documentId: string,
+ body: PatchMemoryDocumentBody,
+ options: DocumentWriteOptions,
+ ): Promise<MemoryDocument> {
+ return this.http.request<MemoryDocument>("PATCH", this.path(projectId, resource, documentId), {
+ query: { environment: options.environment },
+ headers: { "if-match": quote(options.revision) },
+ body,
+ signal: options.signal,
+ });
+ }
+
+ /** `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), {
+ query: { environment: options.environment },
+ headers: { "if-match": quote(options.revision) },
+ signal: options.signal,
+ });
+ }
+}
+
+export class Memory {
+ readonly documents: MemoryDocuments;
+
+ constructor(private readonly http: Http) {
+ this.documents = new MemoryDocuments(http);
+ }
+
+ /** `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`, {
+ query: { environment: options.environment },
+ signal: options.signal,
+ });
+ }
+}
+
+export class Webhooks {
+ constructor(private readonly http: Http) {}
+
+ private path(projectId: string, webhookId?: string): string {
+ const base = `/projects/${segment(projectId)}/webhooks`;
+ return webhookId === undefined ? base : `${base}/${segment(webhookId)}`;
+ }
+
+ /** `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), {
+ query: { ...query },
+ signal: options.signal,
+ });
+ return page.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), {
+ body: params,
+ signal: options.signal,
+ });
+ return answer.webhook;
+ }
+
+ /** `PATCH /projects/<p>/webhooks/<id>`. */
+ async update(
+ projectId: string,
+ webhookId: string,
+ params: UpdateWebhookParams,
+ options: CallOptions = {},
+ ): Promise<Webhook> {
+ const answer = await this.http.request<{ webhook: Webhook }>("PATCH", this.path(projectId, webhookId), {
+ body: params,
+ signal: options.signal,
+ });
+ return answer.webhook;
+ }
+
+ /** `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 }>(
+ "POST",
+ `${this.path(projectId, webhookId)}/rotate-token`,
+ { signal: options.signal },
+ );
+ return answer.webhook;
+ }
+
+ /** `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 });
+ }
+
+ /** `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[] }>(
+ "GET",
+ `${this.path(projectId, webhookId)}/requests`,
+ { signal: options.signal },
+ );
+ return page.requests;
+ }
+}
+
+export class EventSubscriptions {
+ constructor(private readonly http: Http) {}
+
+ private path(projectId: string, subscriptionId?: string): string {
+ const base = `/projects/${segment(projectId)}/event-subscriptions`;
+ return subscriptionId === undefined ? base : `${base}/${segment(subscriptionId)}`;
+ }
+
+ /** `POST /projects/<p>/event-subscriptions`. */
+ async create(
+ projectId: string,
+ params: CreateEventSubscriptionBody,
+ options: CallOptions = {},
+ ): Promise<EventSubscription> {
+ const answer = await this.http.request<{ subscription: EventSubscription }>("POST", this.path(projectId), {
+ body: params,
+ signal: options.signal,
+ });
+ return answer.subscription;
+ }
+
+ /** `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), {
+ signal: options.signal,
+ });
+ return page.subscriptions;
+ }
+
+ /** `GET /projects/<p>/event-subscriptions/<id>`. */
+ async get(projectId: string, subscriptionId: string, options: CallOptions = {}): Promise<EventSubscription> {
+ const answer = await this.http.request<{ subscription: EventSubscription }>(
+ "GET",
+ this.path(projectId, subscriptionId),
+ { signal: options.signal },
+ );
+ return answer.subscription;
+ }
+
+ /** `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 });
+ }
+}
+
+export class GitHub {
+ constructor(private readonly http: Http) {}
+
+ /**
+ * `GET /projects/<p>/github/repositories?environment=`: the repositories
+ * the environment's installation covers, read live (per design 1c07584,
+ * 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 }>(
+ "GET",
+ `/projects/${segment(projectId)}/github/repositories`,
+ { query: { ...query }, signal: options.signal },
+ );
+ return { repositories: page.repositories, nextCursor: page.nextCursor ?? null };
+ }
+}
+
+export class Projects {
+ readonly memory: Memory;
+ readonly webhooks: Webhooks;
+ readonly eventSubscriptions: EventSubscriptions;
+ readonly github: GitHub;
+
+ constructor(private readonly http: Http) {
+ this.memory = new Memory(http);
+ this.webhooks = new Webhooks(http);
+ this.eventSubscriptions = new EventSubscriptions(http);
+ this.github = new GitHub(http);
+ }
+
+ /** `GET /projects`. */
+ async list(options: CallOptions = {}): Promise<Project[]> {
+ const page = await this.http.request<{ projects: Project[] }>("GET", "/projects", { 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 });
+ }
+
+ /** `POST /projects`. */
+ create(params: CreateProjectParams, options: CallOptions = {}): Promise<Project> {
+ return this.http.request<Project>("POST", "/projects", { body: params, signal: options.signal });
+ }
+}
+
+// ── Agents and deployments ────────────────────────────────────────────────────
+
+export class Agents {
+ constructor(private readonly http: Http) {}
+
+ /** `GET /agents`. */
+ async list(options: CallOptions = {}): Promise<AgentSummary[]> {
+ const page = await this.http.request<{ agents: AgentSummary[] }>("GET", "/agents", { signal: options.signal });
+ return page.agents;
+ }
+}
+
+export class Deployments {
+ constructor(private readonly http: Http) {}
+
+ /** `GET /deployments/<id>`. */
+ get(deploymentId: string, options: CallOptions = {}): Promise<Deployment> {
+ return this.http.request<Deployment>("GET", `/deployments/${segment(deploymentId)}`, { signal: options.signal });
+ }
+
+ /** `GET /deployments?agentId=`. */
+ async list(query: ListDeploymentsQuery, options: CallOptions = {}): Promise<Deployment[]> {
+ const page = await this.http.request<{ deployments: Deployment[] }>("GET", "/deployments", {
+ query: { ...query },
+ signal: options.signal,
+ });
+ return page.deployments;
+ }
+}
+
+// ── The client ────────────────────────────────────────────────────────────────
+
+/**
+ * The management API client.
+ *
+ * ```ts
+ * import { OpenComputer } from "@opencomputer/sdk/managed-agents";
+ * const oc = new OpenComputer({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
+ * const { session } = await oc.sessions.create({ agentId: "worker@development" }, { idempotencyKey: taskId });
+ * await oc.sessions.turns.send(session.id, { input: "Plan the workshop.", idempotencyKey: `${taskId}/start` });
+ * ```
+ */
+export class OpenComputer {
+ readonly sessions: Sessions;
+ readonly projects: Projects;
+ readonly agents: Agents;
+ readonly deployments: Deployments;
+
+ constructor(options: OpenComputerOptions) {
+ const http = new Http(options.apiKey, options);
+ this.sessions = new Sessions(http);
+ this.projects = new Projects(http);
+ this.agents = new Agents(http);
+ this.deployments = new Deployments(http);
+ }
+}
+
+/** `startOnDocument` as a standalone call, for code that holds a key and no client. */
+export interface StartSessionOnDocumentParams extends StartOnDocumentParams, HttpOptions {
+ /** An OpenComputer API key with access to the project. Server-side only. */
+ apiKey: string;
+}
+
+export type StartSessionOnDocumentResult = StartOnDocumentResult;
+
+/** The same call as `oc.sessions.startOnDocument`, building the client from `apiKey`, `baseUrl` and `fetch`. */
+export function startSessionOnDocument(params: StartSessionOnDocumentParams): Promise<StartSessionOnDocumentResult> {
+ const { apiKey, baseUrl, fetch, ...rest } = params;
+ return new OpenComputer({ apiKey, baseUrl, fetch }).sessions.startOnDocument(rest);
+}
+
+/** Quotes a revision for `If-Match`, as the API returns it in `ETag`. */
+function quote(revision: string): string {
+ return revision.startsWith('"') ? revision : `"${revision}"`;
+}
diff --git a/sdks/typescript/src/managed-agents/errors.ts b/sdks/typescript/src/managed-agents/errors.ts
new file mode 100644
index 00000000..3e899308
--- /dev/null
+++ b/sdks/typescript/src/managed-agents/errors.ts
@@ -0,0 +1,54 @@
+// The one error the management client throws. The API answers every failure
+// with `{ error: { code, message } }` (docs/agents/api.mdx, "Errors"); a
+// missing key or an unknown route answers `{ error: "<text>" }` without a
+// code. Both land here as `{ code, status, message }`, with `code` filled from
+// the status when the body carried none, so a caller always has one string to
+// branch on.
+
+/** The wire envelope: `{ error: { code, message } }` or `{ error: "<text>" }`. */
+export interface ApiErrorEnvelope {
+ error?: { code?: string; message?: string } | string;
+}
+
+const CODE_BY_STATUS: Record<number, string> = {
+ 400: "invalid_request",
+ 401: "unauthorized",
+ 402: "insufficient_credits",
+ 403: "forbidden",
+ 404: "not_found",
+ 409: "conflict",
+ 429: "rate_limited",
+};
+
+export class OpenComputerError extends Error {
+ /** The API's stable error code, or one derived from the status when the body had none. */
+ readonly code: string;
+ /** The HTTP status. */
+ readonly status: number;
+ /** Seconds to wait before retrying, from `Retry-After`, when the API sent one. */
+ readonly retryAfter?: number;
+
+ constructor(status: number, code: string | undefined, message: string | undefined, retryAfter?: number) {
+ super(message || `OpenComputer request failed (${status})`);
+ this.name = "OpenComputerError";
+ this.status = status;
+ this.code = code || CODE_BY_STATUS[status] || (status >= 500 ? "unavailable" : "request_failed");
+ if (retryAfter !== undefined) this.retryAfter = retryAfter;
+ }
+}
+
+/** Builds the error for a failed response from its status, parsed body and headers. */
+export function errorFromResponse(status: number, body: unknown, headers?: Headers): OpenComputerError {
+ const envelope = body && typeof body === "object" ? (body as ApiErrorEnvelope) : undefined;
+ const error = envelope?.error;
+ const code = typeof error === "object" && error ? error.code : undefined;
+ const message = typeof error === "string" ? error : typeof error === "object" && error ? error.message : undefined;
+ const retryAfterHeader = headers?.get("retry-after");
+ const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : Number.NaN;
+ return new OpenComputerError(
+ status,
+ code,
+ message,
+ Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined,
+ );
+}
diff --git a/sdks/typescript/src/agents/event-subscriptions.test.ts b/sdks/typescript/src/managed-agents/event-subscriptions.test.ts
similarity index 100%
rename from sdks/typescript/src/agents/event-subscriptions.test.ts
rename to sdks/typescript/src/managed-agents/event-subscriptions.test.ts
diff --git a/sdks/typescript/src/agents/event-subscriptions.ts b/sdks/typescript/src/managed-agents/event-subscriptions.ts
similarity index 92%
rename from sdks/typescript/src/agents/event-subscriptions.ts
rename to sdks/typescript/src/managed-agents/event-subscriptions.ts
index c6e22066..876ecb26 100644
--- a/sdks/typescript/src/agents/event-subscriptions.ts
+++ b/sdks/typescript/src/managed-agents/event-subscriptions.ts
@@ -1,11 +1,7 @@
// Event subscription types — the shapes of the management API documented at
// docs/agents/api.mdx ("Event subscriptions") and the input an agent reads
// through `useInput()` when a subscribed outcome is delivered to it.
-//
-// These are types only. The subscription routes live on the project-scoped
-// Serverless Agents surface (`/api/managed-agents/projects/<id>/event-subscriptions`),
-// which this package does not call. Use them to type the bodies you send
-// with your own HTTP client and the objects it returns.
+// `oc.projects.eventSubscriptions` sends and returns them.
import type { MemoryEnvironment } from "./memory.js";
diff --git a/sdks/typescript/src/managed-agents/http.ts b/sdks/typescript/src/managed-agents/http.ts
new file mode 100644
index 00000000..dae8bf60
--- /dev/null
+++ b/sdks/typescript/src/managed-agents/http.ts
@@ -0,0 +1,95 @@
+// The HTTP layer of the management client: the API key header, JSON both
+// ways, the error envelope, `Idempotency-Key`, and nothing else. Web
+// standards only (fetch, URL, Headers), so the same code runs on Node,
+// Workers, Deno and browsers-with-a-proxy. No retries: the API's idempotency
+// keys make a caller's retry safe, and the caller knows which calls to
+// repeat; a client that retried on its own would hide that decision.
+
+import { errorFromResponse } from "./errors.js";
+
+export const DEFAULT_BASE_URL = "https://app.opencomputer.dev/api/managed-agents";
+
+export interface HttpOptions {
+ /** Base URL of the management API. Default `https://app.opencomputer.dev/api/managed-agents`. */
+ baseUrl?: string;
+ /** The fetch to use. Default: the global. */
+ fetch?: typeof fetch;
+}
+
+export type Query = Record<string, string | number | boolean | undefined | null>;
+
+export interface RequestOptions {
+ query?: Query;
+ body?: unknown;
+ headers?: Record<string, string>;
+ signal?: AbortSignal;
+}
+
+/** A response with its status kept, for callers that branch on 200 versus 201. */
+export interface Answer<T> {
+ status: number;
+ body: T;
+ headers: Headers;
+}
+
+export class Http {
+ readonly baseUrl: string;
+ private readonly apiKey: string;
+ private readonly doFetch: typeof fetch;
+
+ constructor(apiKey: string, options: HttpOptions = {}) {
+ if (!apiKey) throw new Error("An OpenComputer API key is required.");
+ this.apiKey = apiKey;
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
+ const f = options.fetch ?? (typeof fetch === "function" ? fetch : undefined);
+ if (!f) throw new Error("No global fetch is available; pass { fetch } to the client.");
+ this.doFetch = f;
+ }
+
+ url(path: string, query?: Query): string {
+ const url = new URL(this.baseUrl + path);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
+ }
+ }
+ 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>> {
+ const headers: Record<string, string> = {
+ "x-api-key": this.apiKey,
+ accept: "application/json",
+ ...options.headers,
+ };
+ const init: RequestInit = { method, headers, signal: options.signal };
+ if (options.body !== undefined) {
+ headers["content-type"] = "application/json";
+ init.body = JSON.stringify(options.body);
+ }
+ const response = await this.doFetch(this.url(path, options.query), init);
+ 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 };
+ }
+
+ /** `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 function readJson(response: Response): Promise<unknown> {
+ if (response.status === 204) return undefined;
+ const text = await response.text();
+ if (!text) return undefined;
+ try {
+ return JSON.parse(text) as unknown;
+ } catch {
+ return { error: text };
+ }
+}
+
+/** URL-encodes one path segment. */
+export const segment = (value: string): string => encodeURIComponent(value);
diff --git a/sdks/typescript/src/managed-agents/index.ts b/sdks/typescript/src/managed-agents/index.ts
new file mode 100644
index 00000000..60f726b7
--- /dev/null
+++ b/sdks/typescript/src/managed-agents/index.ts
@@ -0,0 +1,63 @@
+// @opencomputer/sdk/managed-agents: the management API client and its types.
+//
+// This module graph is portable: fetch, URL, Headers and Web Crypto only, no
+// Node built-ins, nothing run at import. It loads the same in a Cloudflare
+// Worker without Node compatibility, on Vercel, on Deno and on Node. The
+// sandbox client at the package root is Node-only and lives apart on purpose.
+
+export {
+ OpenComputer,
+ Sessions,
+ Turns,
+ Events,
+ Projects,
+ Memory,
+ MemoryDocuments,
+ Webhooks,
+ EventSubscriptions,
+ GitHub,
+ Agents,
+ Deployments,
+ startSessionOnDocument,
+ type OpenComputerOptions,
+ type CallOptions,
+ type CreateSessionOptions,
+ type EnvironmentOptions,
+ type DocumentWriteOptions,
+ type ListDocumentsOptions,
+ type StartSessionOnDocumentParams,
+ type StartSessionOnDocumentResult,
+} from "./client.js";
+export { sessionIdempotencyKey, type StartOnDocumentParams, type StartOnDocumentResult } from "./start-on-document.js";
+export { OpenComputerError, type ApiErrorEnvelope } from "./errors.js";
+export { DEFAULT_BASE_URL, type HttpOptions } from "./http.js";
+export type * from "./types.js";
+export type {
+ MemoryEnvironment,
+ MemoryAccess,
+ MemoryAgentWrites,
+ MemoryBinding,
+ MemoryBindings,
+ SessionMemoryBinding,
+ MemoryWriter,
+ MemoryDocumentMeta,
+ MemoryDocument,
+ MemoryDocumentPage,
+ MemoryResource,
+ MemoryResourceInventory,
+ CreateMemoryDocumentBody,
+ ReplaceMemoryDocumentBody,
+ PatchMemoryDocumentBody,
+ MemorySavedEvent,
+ MemoryErrorCode,
+} from "./memory.js";
+export type {
+ OutcomeEventType,
+ SessionDestination,
+ CreateEventSubscriptionBody,
+ EventSubscription,
+ OutcomeEvent,
+ EventInput,
+ TurnOutcomeDelivery,
+ EventSubscriptionErrorCode,
+} from "./event-subscriptions.js";
diff --git a/sdks/typescript/src/agents/memory.ts b/sdks/typescript/src/managed-agents/memory.ts
similarity index 88%
rename from sdks/typescript/src/agents/memory.ts
rename to sdks/typescript/src/managed-agents/memory.ts
index f9e136dc..e3ff0b3e 100644
--- a/sdks/typescript/src/agents/memory.ts
+++ b/sdks/typescript/src/managed-agents/memory.ts
@@ -1,15 +1,13 @@
// Project memory types — the shapes of the management API documented at
// docs/agents/document-memory.mdx ("Session bindings", "Management API") and
-// the `memory` field a session carries.
-//
-// These are types only. This client wraps the Durable Agent Sessions API
-// (`/v3`); the memory management routes live on the project-scoped
-// Serverless Agents surface (`/api/managed-agents/projects/<id>/memory/...`),
-// which this package does not call. Use them to type the bodies you send with
-// your own HTTP client, the CLI's `--json` output (`opencomputer memory ...`),
-// or an export produced by `opencomputer memory export`.
-
-export type MemoryEnvironment = "development" | "production";
+// the `memory` field a session carries. `oc.projects.memory` sends and
+// returns them; they also type the CLI's `--json` output
+// (`opencomputer memory ...`) and an export produced by
+// `opencomputer memory export`.
+
+import type { Environment } from "./types.js";
+
+export type MemoryEnvironment = Environment;
export type MemoryAccess = "read" | "read-write";
diff --git a/sdks/typescript/src/managed-agents/portability.test.ts b/sdks/typescript/src/managed-agents/portability.test.ts
new file mode 100644
index 00000000..e7933985
--- /dev/null
+++ b/sdks/typescript/src/managed-agents/portability.test.ts
@@ -0,0 +1,87 @@
+// The subpath's promise: its module graph loads anywhere fetch exists. Two
+// checks. The static one walks every module reachable from the entry and
+// refuses any import that is not a relative file, any top-level await, and
+// any reference to Node's globals; the dynamic one imports the entry with
+// the global fetch replaced by a trap and confirms nothing was called.
+
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it, vi } from "vitest";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+const stripComments = (source: string): string =>
+ source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
+
+function moduleGraph(entry: string): Map<string, string> {
+ const seen = new Map<string, string>();
+ const visit = (file: string) => {
+ if (seen.has(file)) return;
+ const source = readFileSync(file, "utf8");
+ seen.set(file, source);
+ for (const match of stripComments(source).matchAll(/(?:import|export)\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g)) {
+ const specifier = match[1];
+ if (!specifier.startsWith(".")) throw new Error(`${file} imports a non-relative module: ${specifier}`);
+ visit(resolve(dirname(file), specifier.replace(/\.js$/, ".ts")));
+ }
+ };
+ visit(entry);
+ return seen;
+}
+
+describe("@opencomputer/sdk/managed-agents", () => {
+ const graph = moduleGraph(resolve(here, "index.ts"));
+
+ it("reaches only relative modules inside its own directory", () => {
+ for (const file of graph.keys()) expect(file.startsWith(here)).toBe(true);
+ expect([...graph.keys()].map((file) => file.slice(here.length + 1)).sort()).toEqual([
+ "client.ts",
+ "errors.ts",
+ "event-subscriptions.ts",
+ "http.ts",
+ "index.ts",
+ "memory.ts",
+ "start-on-document.ts",
+ "types.ts",
+ ]);
+ });
+
+ it("has no top-level await, dynamic import, or Node global in any module", () => {
+ for (const [file, source] of graph) {
+ const code = stripComments(source);
+ // Top-level statements are unindented; an `await` at column 0 is one.
+ expect(code, file).not.toMatch(/^await\s/m);
+ expect(code, file).not.toMatch(/\bimport\s*\(/);
+ expect(code, file).not.toMatch(/\bprocess\b/);
+ expect(code, file).not.toMatch(/\brequire\s*\(/);
+ expect(code, file).not.toMatch(/\bBuffer\b/);
+ expect(code, file).not.toMatch(/["']node:/);
+ }
+ });
+
+ it("performs no network activity at import and constructs a client that lists sessions", async () => {
+ const trap = vi.fn(() => {
+ throw new Error("fetch called at import");
+ });
+ const original = globalThis.fetch;
+ globalThis.fetch = trap as unknown as typeof fetch;
+ try {
+ const mod = await import("./index.js");
+ expect(trap).not.toHaveBeenCalled();
+ const calls: string[] = [];
+ const oc = new mod.OpenComputer({
+ apiKey: "k",
+ fetch: async (input) => {
+ calls.push(String(input));
+ return Response.json({ sessions: [], nextCursor: null });
+ },
+ });
+ expect(await oc.sessions.list()).toEqual({ sessions: [], nextCursor: null });
+ expect(calls).toEqual(["https://app.opencomputer.dev/api/managed-agents/sessions"]);
+ expect(trap).not.toHaveBeenCalled();
+ } finally {
+ globalThis.fetch = original;
+ }
+ });
+});
diff --git a/sdks/typescript/src/agents/memory-sessions.test.ts b/sdks/typescript/src/managed-agents/start-on-document.test.ts
similarity index 76%
rename from sdks/typescript/src/agents/memory-sessions.test.ts
rename to sdks/typescript/src/managed-agents/start-on-document.test.ts
index 21b55e16..71c4b736 100644
--- a/sdks/typescript/src/agents/memory-sessions.test.ts
+++ b/sdks/typescript/src/managed-agents/start-on-document.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
-import { ConflictError, NotFoundError } from "./errors.js";
-import { sessionIdempotencyKey, startSessionOnDocument } from "./memory-sessions.js";
+import { OpenComputer, startSessionOnDocument } from "./client.js";
+import { OpenComputerError } from "./errors.js";
+import { sessionIdempotencyKey } from "./start-on-document.js";
interface Call { method: string; url: string; headers: Record<string, string>; body?: Record<string, unknown> }
@@ -46,14 +47,16 @@ function fakeApi(state: { document: "absent" | "present" | "deleted"; sessions?:
}
const params = {
- apiKey: "osb_test", projectId: "prj_1", environment: "development" as const, agent: "openmuse-dev--topic-worker",
+ projectId: "prj_1", environment: "development" as const, agent: "openmuse-dev--topic-worker",
resource: "topics", documentId: "workshop", document: { title: "Workshop" }, idempotencyKey: "topic/workshop/1",
};
-describe("startSessionOnDocument", () => {
+const client = (fetch: typeof globalThis.fetch) => new OpenComputer({ apiKey: "osb_test", fetch });
+
+describe("sessions.startOnDocument", () => {
it("creates the document, then the session bound to it, under derived keys", async () => {
const api = fakeApi({ document: "absent" });
- const result = await startSessionOnDocument({ ...params, fetch: api.fetch });
+ const result = await client(api.fetch).sessions.startOnDocument(params);
expect(result).toEqual({
document: { id: "workshop", created: true, revision: "r1", title: "Workshop" },
@@ -77,8 +80,9 @@ describe("startSessionOnDocument", () => {
it("converges on a retry: the document and the session both already exist", async () => {
const api = fakeApi({ document: "absent" });
- await startSessionOnDocument({ ...params, fetch: api.fetch });
- const retry = await startSessionOnDocument({ ...params, fetch: api.fetch });
+ const oc = client(api.fetch);
+ await oc.sessions.startOnDocument(params);
+ const retry = await oc.sessions.startOnDocument(params);
expect(retry.document).toEqual({ id: "workshop", created: false, revision: "r7", title: "Workshop" });
expect(retry.session).toMatchObject({ id: "ses-1", created: false });
@@ -92,9 +96,10 @@ describe("startSessionOnDocument", () => {
it("keeps different keys apart and carries extra bindings, access and source", async () => {
const api = fakeApi({ document: "present" });
- const first = await startSessionOnDocument({ ...params, fetch: api.fetch, idempotencyKey: "a" });
- const second = await startSessionOnDocument({
- ...params, fetch: api.fetch, idempotencyKey: "b", access: "read", source: "openmuse",
+ const oc = client(api.fetch);
+ const first = await oc.sessions.startOnDocument({ ...params, idempotencyKey: "a" });
+ const second = await oc.sessions.startOnDocument({
+ ...params, idempotencyKey: "b", access: "read", source: "openmuse",
memory: { profile: { scope: "document", id: "owner", access: "read" } },
});
expect(first.session.id).not.toBe(second.session.id);
@@ -113,13 +118,23 @@ describe("startSessionOnDocument", () => {
it("reports a reused key with different bindings as a conflict", async () => {
const sessions = new Map([[await sessionIdempotencyKey("topic/workshop/1"), "other-bindings"]]);
const api = fakeApi({ document: "present", sessions });
- await expect(startSessionOnDocument({ ...params, fetch: api.fetch })).rejects.toThrow(ConflictError);
- await expect(startSessionOnDocument({ ...params, fetch: api.fetch })).rejects.toThrow(/different agent, deployment, environment or memory bindings/);
+ const failure = await client(api.fetch).sessions.startOnDocument(params).catch((cause: unknown) => cause);
+ expect(failure).toBeInstanceOf(OpenComputerError);
+ expect(failure).toMatchObject({ status: 409, code: "idempotency_key_reused" });
+ expect((failure as Error).message).toMatch(/different agent, deployment, environment or memory bindings/);
});
it("refuses a deleted document id instead of creating a session that cannot bind it", async () => {
const api = fakeApi({ document: "deleted" });
- await expect(startSessionOnDocument({ ...params, fetch: api.fetch })).rejects.toThrow(NotFoundError);
+ const failure = await client(api.fetch).sessions.startOnDocument(params).catch((cause: unknown) => cause);
+ expect(failure).toMatchObject({ status: 404, code: "memory_document_deleted" });
expect(api.calls.some((call) => call.url === "/api/managed-agents/sessions")).toBe(false);
});
+
+ it("is the same call as the standalone startSessionOnDocument", async () => {
+ const api = fakeApi({ document: "absent" });
+ const result = await startSessionOnDocument({ ...params, apiKey: "osb_test", fetch: api.fetch });
+ expect(result.session).toMatchObject({ id: "ses-1", created: true });
+ expect(api.calls[0].headers["x-api-key"]).toBe("osb_test");
+ });
});
diff --git a/sdks/typescript/src/managed-agents/start-on-document.ts b/sdks/typescript/src/managed-agents/start-on-document.ts
new file mode 100644
index 00000000..ebe85085
--- /dev/null
+++ b/sdks/typescript/src/managed-agents/start-on-document.ts
@@ -0,0 +1,168 @@
+// Start a session on a memory document in one call (docs/agents/document-memory.mdx,
+// "Start a session on a new document"). The management API keeps the two
+// objects separate on purpose: a document is owner data with its own
+// lifetime, a session binding is admission to it, and nothing creates one as
+// a side effect of the other. What an application wants at the moment it
+// opens a topic is still "these notes, this session", so this helper does the
+// 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 { MemoryAccess, MemoryAgentWrites, MemoryBindings, MemoryDocument } from "./memory.js";
+import type { Environment, SessionSource } from "./types.js";
+
+export interface StartOnDocumentParams {
+ /** The project whose memory holds the document. */
+ projectId: string;
+ /** Development and Production have separate memory; the session runs in the same environment. */
+ environment: Environment;
+ /** The deployed agent's id (not `agent@alias`; the environment above supplies the alias). */
+ agent: string;
+ /** The declared memory resource and the document id to bind. */
+ resource: string;
+ documentId: string;
+ /** What to create when the document does not exist yet. Ignored when it does. */
+ document: {
+ title: string;
+ /** Default `""`. */
+ text?: string;
+ /** Default `""`. */
+ summary?: string;
+ /** Default `"enabled"`. */
+ agentWrites?: MemoryAgentWrites;
+ };
+ /** The binding's access. Default `read-write`. */
+ access?: MemoryAccess;
+ /** Further bindings for the session, keyed by resource id. */
+ memory?: MemoryBindings;
+ /**
+ * One key for the whole operation. A retry with the same key returns the
+ * same session; the document converges on its id regardless.
+ */
+ idempotencyKey: string;
+ /** The session's `source`. Default `api`. */
+ source?: SessionSource;
+ signal?: AbortSignal;
+}
+
+export interface StartOnDocumentResult {
+ document: {
+ id: string;
+ /** False when the document already existed; its content was left as it was. */
+ created: boolean;
+ /** The current revision, for a later conditional owner write. */
+ revision: string;
+ title: string;
+ };
+ session: {
+ id: string;
+ /** False when the key had already created this session. */
+ created: boolean;
+ status?: string;
+ executionMode?: string;
+ };
+}
+
+/**
+ * The session-create `Idempotency-Key` derived from the caller's key: stable
+ * for a retry, distinct from any other use of the same caller key.
+ */
+export async function sessionIdempotencyKey(idempotencyKey: string): Promise<string> {
+ const bytes = new TextEncoder().encode(`opencomputer.memory.session\0${idempotencyKey}`);
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
+ let hex = "";
+ for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
+ return hex;
+}
+
+/**
+ * Creates the document if it does not exist, then creates the session bound
+ * to it, and reports both ids and whether each already existed.
+ *
+ * - The document is created with `If-None-Match: *`; an existing document is
+ * kept as it is and reported with `created: false`. An id that was deleted
+ * is reserved and fails with code `memory_document_deleted`, since a
+ * binding to it would fail admission.
+ * - The session is created with an `Idempotency-Key` derived from
+ * `idempotencyKey`; the same key with the same agent, deployment,
+ * environment and bindings returns the existing session with
+ * `created: false`. Anything else under the same key fails with code
+ * `idempotency_key_reused`.
+ */
+export async function startOnDocument(http: Http, params: StartOnDocumentParams): Promise<StartOnDocumentResult> {
+ const documentPath =
+ `/projects/${segment(params.projectId)}/memory/${segment(params.resource)}/documents/${segment(params.documentId)}`;
+ const query = { environment: params.environment };
+
+ let document: MemoryDocument;
+ let documentCreated: boolean;
+ try {
+ const created = await http.send<MemoryDocument>("PUT", documentPath, {
+ query,
+ headers: { "if-none-match": "*" },
+ body: {
+ title: params.document.title,
+ text: params.document.text ?? "",
+ ...(params.document.summary !== undefined ? { summary: params.document.summary } : {}),
+ ...(params.document.agentWrites ? { agentWrites: params.document.agentWrites } : {}),
+ },
+ signal: params.signal,
+ });
+ document = created.body;
+ documentCreated = true;
+ } catch (cause) {
+ if (!(cause instanceof OpenComputerError) || cause.status !== 412) throw cause;
+ try {
+ document = await http.request<MemoryDocument>("GET", documentPath, { query, signal: params.signal });
+ } catch (readCause) {
+ if (readCause instanceof OpenComputerError && readCause.status === 404) {
+ throw new OpenComputerError(
+ 404,
+ "memory_document_deleted",
+ `Document ${params.resource}/${params.documentId} was deleted and its id is reserved; ` +
+ "a session cannot bind it. Use a new document id.",
+ );
+ }
+ throw readCause;
+ }
+ documentCreated = false;
+ }
+
+ let created: { status: number; body: { session?: { id?: string; status?: string; executionMode?: string } } };
+ try {
+ created = await http.send("POST", "/sessions", {
+ headers: { "idempotency-key": await sessionIdempotencyKey(params.idempotencyKey) },
+ body: {
+ agentId: `${params.agent}@${params.environment}`,
+ source: params.source ?? "api",
+ memory: {
+ ...params.memory,
+ [params.resource]: { scope: "document", id: params.documentId, access: params.access ?? "read-write" },
+ },
+ },
+ signal: params.signal,
+ });
+ } catch (cause) {
+ if (cause instanceof OpenComputerError && cause.status === 409) {
+ throw new OpenComputerError(
+ 409,
+ "idempotency_key_reused",
+ `Idempotency key ${JSON.stringify(params.idempotencyKey)} already created a session with a different ` +
+ "agent, deployment, environment or memory bindings. Use a new key to start another session; " +
+ "the document was left as it is.",
+ );
+ }
+ throw cause;
+ }
+ const session = created.body?.session;
+ if (!session?.id) throw new OpenComputerError(created.status, "invalid_response", "session create returned no session id");
+ return {
+ document: { id: document.id, created: documentCreated, revision: document.revision, title: document.title },
+ session: {
+ id: session.id,
+ created: created.status === 201,
+ ...(session.status ? { status: session.status } : {}),
+ ...(session.executionMode ? { executionMode: session.executionMode } : {}),
+ },
+ };
+}
diff --git a/sdks/typescript/src/managed-agents/types.ts b/sdks/typescript/src/managed-agents/types.ts
new file mode 100644
index 00000000..03d856f2
--- /dev/null
+++ b/sdks/typescript/src/managed-agents/types.ts
@@ -0,0 +1,460 @@
+// The shapes of the management API (docs/agents/api.mdx) and of the session
+// event log (docs/agents/events.mdx), as the client sends and returns them.
+// Field names are the API's own; nothing is renamed at the boundary.
+//
+// Fields marked "per design 1c07584, backend in flight" belong to routes and
+// objects the API is gaining (session labels, filtered listing, the typed
+// result, turn payloads, repository listing). They are typed here so an
+// application compiles against the final shape; until the backend lands, the
+// API leaves them absent and the routes answer 404 or 400.
+
+import type { MemoryBindings, SessionMemoryBinding } from "./memory.js";
+import type { TurnOutcomeDelivery } from "./event-subscriptions.js";
+
+/** Development and Production are separate environments of a project. */
+export type Environment = "development" | "production";
+
+/**
+ * A JSON value: what a turn payload, a tool input or output, and a result
+ * carry. Strings, numbers, booleans, null, arrays and objects of the same.
+ */
+export type DataValue = string | number | boolean | null | DataValue[] | { [key: string]: DataValue };
+
+// ── Sessions ──────────────────────────────────────────────────────────────────
+
+/**
+ * Where a session is in its life. `stopping` is the state between an
+ * interrupt and the settlement of the stopped turn's work (per design
+ * 1c07584, backend in flight).
+ */
+export type SessionStatus =
+ | "new"
+ | "connecting"
+ | "idle"
+ | "running"
+ | "waiting_runtime"
+ | "suspending"
+ | "suspended"
+ | "resuming"
+ | "stopping"
+ | "failed"
+ | "ended";
+
+/** The `source` given at creation; the dashboard groups sessions by it. */
+export type SessionSource = "api" | "playground" | "channel" | "webhook" | (string & {});
+
+export type TurnMode = "queue" | "steer" | "interrupt";
+
+export type TurnStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | (string & {});
+
+/** One entry of a session's `turns`. */
+export interface Turn {
+ id: string;
+ /** The user text for the turn. */
+ input: string;
+ mode: TurnMode;
+ status: TurnStatus;
+ /** The structured input sent with the turn (per design 1c07584, backend in flight). */
+ payload?: DataValue;
+ /** Present when an event subscription selected the turn's outcome. */
+ deliveries?: TurnOutcomeDelivery[];
+ createdAt: string;
+ updatedAt: string;
+}
+
+/**
+ * The latest committed output of the agent's result tool, with its
+ * provenance (per design 1c07584, backend in flight).
+ */
+export interface SessionResult {
+ /** The turn whose tool call reported it. */
+ turnId: string;
+ callId: string;
+ reportedAt: string;
+ /** The tool's output as committed; at most 8 KB of JSON. */
+ data: DataValue;
+}
+
+/** Application metadata on a session. Not authorization, not visible to the agent. */
+export type SessionLabels = Record<string, string>;
+
+/** A session as `GET /sessions/<id>` returns it. */
+export interface Session {
+ id: string;
+ agentId: string;
+ /** The deployment the session pins. */
+ deploymentId: string;
+ /** Present when the request named an environment. */
+ environment?: Environment;
+ status: SessionStatus;
+ source: SessionSource;
+ /** How the runtime hosts the session, as the create response reports it. */
+ executionMode?: string;
+ /** Present when the session was created with bindings. */
+ memory?: SessionMemoryBinding[];
+ /** Every turn, oldest first. */
+ turns: Turn[];
+ /** Per design 1c07584, backend in flight. */
+ labels?: SessionLabels;
+ /** Per design 1c07584, backend in flight. */
+ labelsUpdatedAt?: string;
+ /** Monotonic; every listed mutation increments it (per design 1c07584, backend in flight). */
+ revision?: number;
+ /** Per design 1c07584, backend in flight. */
+ result?: SessionResult | null;
+ createdAt: string;
+ updatedAt: string;
+}
+
+/** What `POST /sessions` returns. */
+export interface SessionCreated {
+ session: Pick<Session, "id" | "status" | "createdAt"> & Partial<Session>;
+ /** The deployment the session pinned. */
+ deployment?: Deployment;
+ /**
+ * `true` when this call created the session (`201`); `false` when the
+ * `Idempotency-Key` had already created it (`200`).
+ */
+ created: boolean;
+}
+
+export interface CreateSessionParams {
+ /** `<agent-id>@development` or `<agent-id>@production`; a bare id means `production`. */
+ agentId?: string;
+ /** Pin one deployment instead of resolving an alias. Send `environment` with it. */
+ deploymentId?: string;
+ environment?: Environment;
+ /** Bindings keyed by resource id, at most eight. */
+ memory?: MemoryBindings;
+ source?: SessionSource;
+ /** Applied at creation and ignored on an idempotent replay (per design 1c07584, backend in flight). */
+ labels?: SessionLabels;
+}
+
+/** Turn admission, as `POST /sessions/<id>/turns` answers it. */
+export interface TurnReceipt {
+ turnId: string;
+ /** `queued` behind earlier turns, or `running` at once. */
+ status: "queued" | "running";
+ /** `true` when the `idempotencyKey` had already created the turn. */
+ duplicate: boolean;
+}
+
+export interface SendTurnParams {
+ /** The user text. Required, not empty. */
+ input: string;
+ /** The same key returns the existing turn; without one every request starts a turn. */
+ idempotencyKey?: string;
+ /** `queue` (default), `steer` or `interrupt`. */
+ mode?: TurnMode;
+ /** Structured input the agent reads as `useInput().payload`; at most 32 KB of JSON (per design 1c07584, backend in flight). */
+ payload?: DataValue;
+}
+
+/** What a session's activity looks like from a list row (per design 1c07584, backend in flight). */
+export interface SessionActivity {
+ activeTurnId: string | null;
+ /** Turns admitted and not yet started. */
+ queued: number;
+ lastSettledTurn: { id: string; status: TurnStatus; at: string } | null;
+}
+
+/**
+ * A row of `GET /sessions`. Rows carry no `turns` and no `memory`;
+ * `GET /sessions/<id>` has those. `activity`, `revision`, `result` and
+ * `labels` are per design 1c07584, backend in flight.
+ */
+export interface SessionSummary {
+ id: string;
+ projectId?: string;
+ agentId: string;
+ deploymentId: string;
+ environment?: Environment;
+ source: SessionSource;
+ status: SessionStatus;
+ labels?: SessionLabels;
+ createdAt: string;
+ updatedAt: string;
+ revision?: number;
+ activity?: SessionActivity;
+ result?: SessionResult | null;
+}
+
+/**
+ * Filters and paging for `GET /sessions` (per design 1c07584, backend in
+ * flight; the API without them returns the fifty most recently updated
+ * sessions and ignores nothing, so pass none until they land).
+ */
+export interface ListSessionsQuery {
+ project?: string;
+ environment?: Environment;
+ agent?: string;
+ status?: SessionStatus;
+ /** Up to three equality filters, sent as `label.<key>=<value>`. */
+ labels?: SessionLabels;
+ cursor?: string;
+ /** Default 50, at most 100. */
+ limit?: number;
+}
+
+export interface SessionPage {
+ sessions: SessionSummary[];
+ /** Pass as `cursor` for the next page; `null` on the last. */
+ nextCursor: string | null;
+}
+
+/** Body of `PATCH /sessions/<id>/labels` (per design 1c07584, backend in flight). */
+export interface SetLabelsParams {
+ set?: SessionLabels;
+ unset?: string[];
+}
+
+// ── Events ────────────────────────────────────────────────────────────────────
+
+export interface EventBase {
+ id: string;
+ /** Position in the log, starting at 1. */
+ seq: number;
+ timestamp: string;
+ sessionId: string;
+ /** Absent on session-level events. */
+ turnId?: string;
+}
+
+/** A public failure: a stable code, a fixed message and at most one parameter. */
+export type FailureCode =
+ | "interrupted"
+ | "session_ended"
+ | "runtime_lost"
+ | "runtime_failed"
+ | "deployment_invalid"
+ | "model_unavailable"
+ | "model_rejected"
+ | "context_too_long"
+ | "tool_failed"
+ | "sandbox_timeout"
+ | "sandbox_failed"
+ | "agent_failed"
+ | (string & {});
+
+export interface Failure {
+ code: FailureCode;
+ message: string;
+ model?: string;
+ tool?: string;
+}
+
+/**
+ * One entry of `GET /sessions/<id>/events`, discriminated on `type`. New
+ * types can appear; the last member keeps them readable.
+ */
+export type SessionEvent =
+ | (EventBase & { type: "session.created"; data: { agentId: string; deploymentId: string } })
+ | (EventBase & { type: "session.status_changed"; data: { from: SessionStatus; to: SessionStatus } })
+ | (EventBase & { type: "session.ended"; data: Record<string, never> })
+ | (EventBase & { type: "session.failed"; data: Failure })
+ | (EventBase & { type: "message.received"; data: { input: string; mode: TurnMode; payload?: DataValue } })
+ | (EventBase & { type: "turn.queued"; data: { mode: TurnMode } })
+ | (EventBase & { type: "turn.steered"; data: { activeTurnId: string } })
+ | (EventBase & { type: "turn.interrupted"; data: { interruptedTurnIds: string[] } })
+ | (EventBase & { type: "turn.started"; data: Record<string, never> })
+ | (EventBase & { type: "turn.completed"; data: Record<string, never> })
+ | (EventBase & { type: "turn.failed"; data: Failure })
+ | (EventBase & { type: "turn.cancelled"; data: { reason: "interrupted" | (string & {}); replacementTurnId?: string } })
+ | (EventBase & { type: "message.delta"; data: { text: string } })
+ | (EventBase & { type: "message.completed"; data: { text: string } })
+ | (EventBase & { type: "reasoning.delta"; data: { text: string } })
+ | (EventBase & { type: "reasoning.completed"; data: { text: string } })
+ | (EventBase & { type: "tool.started"; data: { tool: string; callId?: string; title?: string; input?: DataValue } })
+ | (EventBase & { type: "tool.progress"; data: Record<string, unknown> })
+ | (EventBase & {
+ type: "tool.completed";
+ data: {
+ tool: string;
+ callId?: string;
+ title?: string;
+ output?: DataValue;
+ /** `true` on the call that committed the session's result (per design 1c07584, backend in flight). */
+ result?: boolean;
+ };
+ })
+ | (EventBase & { type: "tool.failed"; data: { tool: string; callId?: string; title?: string; message?: string } })
+ | (EventBase & { type: "memory.saved"; data: { resource: string; documentId: string; revision: string; bytes: number } })
+ | (EventBase & {
+ type: "model.route_resolved";
+ data: {
+ providerCallId: string;
+ requested: { provider: string; model: string };
+ effective: { provider: string; model: string };
+ runtime?: string;
+ access?: string;
+ };
+ })
+ | (EventBase & {
+ type: "model.access_fallback";
+ data: { providerCallId: string; requested: { provider: string; model: string }; from: string; reason: string };
+ })
+ | (EventBase & {
+ type: "usage.recorded";
+ data: {
+ provider: string;
+ model: string;
+ inputTokens: number;
+ outputTokens: number;
+ reasoningTokens?: number;
+ cachedTokens?: number;
+ cacheWriteTokens?: number;
+ costUsd?: number;
+ payer?: string;
+ };
+ })
+ | (EventBase & { type: "egress.request"; data: { connectionId: string; method: string; path: string } })
+ | (EventBase & {
+ type: "egress.response";
+ data: { connectionId: string; method: string; path: string; status: number; durationMs: number };
+ })
+ | (EventBase & { type: "egress.failed"; data: { connectionId: string; method: string; path: string; message: string } })
+ | (EventBase & { type: "runtime.connected"; data: Record<string, never> })
+ | (EventBase & { type: "runtime.disconnected"; data: Record<string, never> })
+ | (EventBase & { type: "runtime.suspended"; data: Record<string, never> })
+ | (EventBase & { type: "runtime.resumed"; data: Record<string, never> })
+ | (EventBase & { type: "runtime.log"; data: { level?: string; stream?: string; phase?: string; message: string } })
+ | (EventBase & { type: "agent.rendered"; data: Record<string, unknown> })
+ | (EventBase & { type: string; data: Record<string, unknown> });
+
+export type SessionEventType = SessionEvent["type"];
+
+export interface ListEventsQuery {
+ /** Return events with a greater `seq`; start at 0. */
+ after?: number;
+}
+
+// ── Projects, agents and deployments ──────────────────────────────────────────
+
+export interface ProjectEnvironment {
+ name: Environment;
+ agentId?: string;
+ activeDeploymentId?: string;
+ updatedAt?: string;
+}
+
+export interface Project {
+ id: string;
+ slug: string;
+ name: string;
+ environments: ProjectEnvironment[];
+ agents: Array<{ id: string; name: string }>;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface CreateProjectParams {
+ name: string;
+ slug?: string;
+}
+
+/** What `GET /projects/<p>` returns. */
+export interface ProjectDetail {
+ project: Project;
+ deployments: Deployment[];
+ sessions: SessionSummary[];
+ connections: unknown[];
+ channels: unknown[];
+ schedules: unknown[];
+}
+
+/** A row of `GET /agents`. */
+export interface AgentSummary {
+ id: string;
+ name: string;
+ activeAlias?: string;
+ activeDeploymentId?: string;
+ deploymentCount?: number;
+ createdAt?: string;
+ updatedAt?: string;
+}
+
+/** A memory resource as a deployment declares it. */
+export interface MemoryDeclaration {
+ id: string;
+ description?: string;
+ provider: { kind: string; [key: string]: unknown };
+}
+
+export interface Deployment {
+ id: string;
+ agentId: string;
+ alias: string;
+ memory?: MemoryDeclaration[];
+ createdAt: string;
+ [key: string]: unknown;
+}
+
+export interface ListDeploymentsQuery {
+ agentId: string;
+}
+
+// ── Webhooks ──────────────────────────────────────────────────────────────────
+
+export interface Webhook {
+ id: string;
+ projectId: string;
+ environment: Environment;
+ agentId: string;
+ name: string;
+ enabled: boolean;
+ /** `header:<name>` or `body:<json-pointer>`. */
+ identity?: string;
+ /** Without its token on list, get and update; with it once on create and rotate. */
+ invocationUrl: string;
+ /** Present once, on create and on rotate. */
+ token?: string;
+ createdAt: string;
+ updatedAt: string;
+ lastInvokedAt?: string;
+}
+
+export interface ListWebhooksQuery {
+ environment?: Environment;
+ agentId?: string;
+}
+
+export interface CreateWebhookParams {
+ name: string;
+ agentId: string;
+ environment: Environment;
+ identity?: string;
+}
+
+export interface UpdateWebhookParams {
+ name?: string;
+ enabled?: boolean;
+ /** `null` removes the identity source. */
+ identity?: string | null;
+}
+
+/** One entry of a webhook's request ledger. */
+export type WebhookRequest = Record<string, unknown>;
+
+// ── GitHub connection ─────────────────────────────────────────────────────────
+
+/** A repository the environment's GitHub installation covers (per design 1c07584, backend in flight). */
+export interface Repository {
+ id: number | string;
+ fullName: string;
+ private: boolean;
+ defaultBranch: string;
+ archived: boolean;
+}
+
+export interface ListRepositoriesQuery {
+ environment: Environment;
+ cursor?: string;
+ /** At most 100. */
+ limit?: number;
+}
+
+export interface RepositoryPage {
+ repositories: Repository[];
+ nextCursor: string | null;
+}
diff --git a/sdks/typescript/src/mounts.ts b/sdks/typescript/src/mounts.ts
index bdf66fa9..7066dbd0 100644
--- a/sdks/typescript/src/mounts.ts
+++ b/sdks/typescript/src/mounts.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
/**
* Backends supported by the typed `creds` shape. For any backend not in this
* list (or for advanced rclone tuning), pass `rcloneConfig` instead — the raw
@@ -140,7 +141,7 @@ export class Mounts {
* ```
*/
async add(opts: AddMountOpts): Promise<MountInfo> {
- const resp = await fetch(
+ const resp = await apiFetch(
`${this.apiUrl}/sandboxes/${this.sandboxId}/mounts`,
{
method: "POST",
@@ -160,7 +161,7 @@ export class Mounts {
* after hibernate/wake — re-issue `add()` for any mounts you need back.
*/
async list(): Promise<MountInfo[]> {
- const resp = await fetch(
+ const resp = await apiFetch(
`${this.apiUrl}/sandboxes/${this.sandboxId}/mounts`,
{ headers: this.headers },
);
@@ -173,7 +174,7 @@ export class Mounts {
/** Unmount a path previously passed to `add()`. No-op if not mounted. */
async remove(path: string): Promise<void> {
- const resp = await fetch(
+ const resp = await apiFetch(
`${this.apiUrl}/sandboxes/${this.sandboxId}/mounts?path=${encodeURIComponent(path)}`,
{ method: "DELETE", headers: this.headers },
);
diff --git a/sdks/typescript/src/agents/normalize.test.ts b/sdks/typescript/src/normalize.test.ts
similarity index 73%
rename from sdks/typescript/src/agents/normalize.test.ts
rename to sdks/typescript/src/normalize.test.ts
index 17921e30..97c9a443 100644
--- a/sdks/typescript/src/agents/normalize.test.ts
+++ b/sdks/typescript/src/normalize.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { normalize, serialize } from "./normalize.js";
+import { normalize } from "./normalize.js";
describe("normalize (API response → idiomatic TS)", () => {
it("camelCases nested keys — last_turn → lastTurn, and the field is `id`", () => {
@@ -67,21 +67,3 @@ describe("normalize (API response → idiomatic TS)", () => {
expect(out.vars).toEqual({ api_url: "https://example.test", nested_value: { keep_me: true } });
});
});
-
-describe("serialize (request body → snake_case)", () => {
- it("snake_cases keys but leaves metadata opaque", () => {
- const out = serialize({ idempotencyKey: "k1", metadata: { pullNumber: 42 } }) as Record<string, unknown>;
- expect(out.idempotency_key).toBe("k1");
- expect(out.metadata).toEqual({ pullNumber: 42 }); // verbatim
- });
-
- it("leaves refs opaque on request bodies", () => {
- const out = serialize({ refs: { pullNumber: 42, owner_repo: "acme/widgets" } }) as Record<string, unknown>;
- expect(out.refs).toEqual({ pullNumber: 42, owner_repo: "acme/widgets" });
- });
-
- it("leaves vars opaque on request bodies", () => {
- const out = serialize({ vars: { apiUrl: "https://example.test", keep_me: true } }) as Record<string, unknown>;
- expect(out.vars).toEqual({ apiUrl: "https://example.test", keep_me: true });
- });
-});
diff --git a/sdks/typescript/src/normalize.ts b/sdks/typescript/src/normalize.ts
new file mode 100644
index 00000000..b93253cc
--- /dev/null
+++ b/sdks/typescript/src/normalize.ts
@@ -0,0 +1,32 @@
+// Normalize a delivered webhook envelope to idiomatic TS: snake_case keys → camelCase,
+// and a known set of numeric fields that the wire serializes as strings (bigints) →
+// numbers. Opaque subtrees are passed through untouched: `raw` (source-specific adapter
+// data), `metadata`, `refs`, and `vars` (caller/source-owned maps — must round-trip
+// verbatim, keys included). Used by `verifyWebhook` only; the management client speaks
+// camelCase on the wire and needs no normalization.
+
+const NUMERIC = new Set([
+ "seq", "head", "inputCursor", "inputFromSeq", "inputToSeq", "exitCode", "bytes", "port",
+ "numTurns", "revision", "tokens", "turnSeconds", "turns",
+ "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" || ck === "metadata" || ck === "refs" || ck === "vars") { out[ck] = v; continue; } // opaque: verbatim, keys untouched
+ 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/project.ts b/sdks/typescript/src/project.ts
index 3392d2b3..fe56a85a 100644
--- a/sdks/typescript/src/project.ts
+++ b/sdks/typescript/src/project.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
function resolveApiUrl(url: string): string {
const base = url.replace(/\/+$/, "");
return base.endsWith("/api") ? base : `${base}/api`;
@@ -53,7 +54,7 @@ export class SecretStore {
const body: Record<string, unknown> = { name: opts.name };
if (opts.egressAllowlist) body.egressAllowlist = opts.egressAllowlist;
- const resp = await fetch(`${apiUrl}/secret-stores`, {
+ const resp = await apiFetch(`${apiUrl}/secret-stores`, {
method: "POST",
headers,
body: JSON.stringify(body),
@@ -70,7 +71,7 @@ export class SecretStore {
static async list(opts: SecretStoreOpts = {}): Promise<SecretStoreInfo[]> {
const { apiUrl, headers } = getConfig(opts);
- const resp = await fetch(`${apiUrl}/secret-stores`, { headers });
+ const resp = await apiFetch(`${apiUrl}/secret-stores`, { headers });
if (!resp.ok) {
throw new Error(`Failed to list secret stores: ${resp.status}`);
@@ -82,7 +83,7 @@ export class SecretStore {
static async get(storeId: string, opts: SecretStoreOpts = {}): Promise<SecretStoreInfo> {
const { apiUrl, headers } = getConfig(opts);
- const resp = await fetch(`${apiUrl}/secret-stores/${storeId}`, { headers });
+ const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}`, { headers });
if (!resp.ok) {
throw new Error(`Failed to get secret store: ${resp.status}`);
@@ -98,7 +99,7 @@ export class SecretStore {
if (opts.name) body.name = opts.name;
if (opts.egressAllowlist) body.egressAllowlist = opts.egressAllowlist;
- const resp = await fetch(`${apiUrl}/secret-stores/${storeId}`, {
+ const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}`, {
method: "PUT",
headers,
body: JSON.stringify(body),
@@ -115,7 +116,7 @@ export class SecretStore {
static async delete(storeId: string, opts: SecretStoreOpts = {}): Promise<void> {
const { apiUrl, headers } = getConfig(opts);
- const resp = await fetch(`${apiUrl}/secret-stores/${storeId}`, {
+ const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}`, {
method: "DELETE",
headers,
});
@@ -133,7 +134,7 @@ export class SecretStore {
const body: Record<string, unknown> = { value };
if (opts.allowedHosts) body.allowedHosts = opts.allowedHosts;
- const resp = await fetch(`${apiUrl}/secret-stores/${storeId}/secrets/${name}`, {
+ const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}/secrets/${name}`, {
method: "PUT",
headers,
body: JSON.stringify(body),
@@ -148,7 +149,7 @@ export class SecretStore {
static async deleteSecret(storeId: string, name: string, opts: SecretStoreOpts = {}): Promise<void> {
const { apiUrl, headers } = getConfig(opts);
- const resp = await fetch(`${apiUrl}/secret-stores/${storeId}/secrets/${name}`, {
+ const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}/secrets/${name}`, {
method: "DELETE",
headers,
});
@@ -161,7 +162,7 @@ export class SecretStore {
static async listSecrets(storeId: string, opts: SecretStoreOpts = {}): Promise<SecretEntryInfo[]> {
const { apiUrl, headers } = getConfig(opts);
- const resp = await fetch(`${apiUrl}/secret-stores/${storeId}/secrets`, { headers });
+ const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}/secrets`, { headers });
if (!resp.ok) {
throw new Error(`Failed to list secrets: ${resp.status}`);
diff --git a/sdks/typescript/src/pty.ts b/sdks/typescript/src/pty.ts
index 0c7bdf25..ac004f68 100644
--- a/sdks/typescript/src/pty.ts
+++ b/sdks/typescript/src/pty.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
import { openWebSocket } from "./websocket.js";
export interface PtyOpts {
cols?: number;
@@ -31,7 +32,7 @@ export class Pty {
async create(opts: PtyOpts = {}): Promise<PtySession> {
// Create session via REST
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/pty`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/pty`, {
method: "POST",
headers: this.headers,
body: JSON.stringify({
diff --git a/sdks/typescript/src/retry.ts b/sdks/typescript/src/retry.ts
index 7838e9ab..c017eed3 100644
--- a/sdks/typescript/src/retry.ts
+++ b/sdks/typescript/src/retry.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
// Transient-failure retry for SDK HTTP calls.
//
// One retry, short fixed delay, and a deliberately narrow predicate: network
@@ -17,17 +18,17 @@ function sleep(ms: number): Promise<void> {
}
/**
- * fetch() with a single retry on transient transport failures.
+ * apiFetch() with a single retry on transient transport failures.
* Non-retryable responses (including 4xx) are returned as-is for the caller's
* normal error handling.
*/
export async function transientFetch(url: string, init?: RequestInit): Promise<Response> {
try {
- const resp = await fetch(url, init);
+ const resp = await apiFetch(url, init);
if (!RETRY_STATUSES.has(resp.status)) return resp;
} catch {
// network-level failure — retry below
}
await sleep(RETRY_DELAY_MS);
- return fetch(url, init);
+ return apiFetch(url, init);
}
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 8633bd79..0f0f5985 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -1,6 +1,6 @@
import { SandboxAgent } from "./agent.js";
import { sdkVersionHeaders } from "./version.js";
-import { prewarmConnections } from "./http2.js";
+import { apiFetch, prewarmConnections } from "./http2.js";
import { Filesystem } from "./filesystem.js";
import { Exec } from "./exec.js";
import { Mounts } from "./mounts.js";
@@ -414,7 +414,7 @@ export class Sandbox {
headers["Accept"] = "text/event-stream";
}
- const resp = await fetch(`${apiUrl}/sandboxes`, {
+ const resp = await apiFetch(`${apiUrl}/sandboxes`, {
method: "POST",
headers,
body: JSON.stringify(body),
@@ -439,7 +439,7 @@ export class Sandbox {
const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- const resp = await fetch(`${apiUrl}/sandboxes/${sandboxId}`, {
+ const resp = await apiFetch(`${apiUrl}/sandboxes/${sandboxId}`, {
headers: apiKey ? { "X-API-Key": apiKey } : {},
});
@@ -478,7 +478,7 @@ export class Sandbox {
const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
const query = opts.deleteSecretStore ? "?deleteSecretStore=true" : "";
- const resp = await fetch(`${apiUrl}/sandboxes/${sandboxId}${query}`, {
+ const resp = await apiFetch(`${apiUrl}/sandboxes/${sandboxId}${query}`, {
method: "DELETE",
headers: apiKey ? { "X-API-Key": apiKey } : {},
});
@@ -500,7 +500,7 @@ export class Sandbox {
* auth gate from that point on.
*/
async rotatePreviewAuthToken(): Promise<string> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview/rotate`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview/rotate`, {
method: "POST",
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
@@ -515,7 +515,7 @@ export class Sandbox {
async kill(opts: SandboxKillOptions = {}): Promise<void> {
const query = opts.deleteSecretStore ? "?deleteSecretStore=true" : "";
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}${query}`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}${query}`, {
method: "DELETE",
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
@@ -528,7 +528,7 @@ export class Sandbox {
async isRunning(): Promise<boolean> {
try {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
if (!resp.ok) return false;
@@ -541,7 +541,7 @@ export class Sandbox {
}
async hibernate(): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/hibernate`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/hibernate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -557,7 +557,7 @@ export class Sandbox {
}
async wake(opts: { timeout?: number } = {}): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/wake`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -598,7 +598,7 @@ export class Sandbox {
* unresponsive), use `powerCycle()` instead.
*/
async reboot(): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/reboot`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/reboot`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -620,7 +620,7 @@ export class Sandbox {
* `reboot()` doesn't recover.
*/
async powerCycle(): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/power-cycle`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/power-cycle`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -649,7 +649,7 @@ export class Sandbox {
* [HTTP API →](/api-reference/sandboxes/scale)
*/
async scale(opts: { memoryMB: number }): Promise<ScaleResult> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scale`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scale`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -683,7 +683,7 @@ export class Sandbox {
if (opts.minMemoryMB != null) body.minMemoryMB = opts.minMemoryMB;
if (opts.maxMemoryMB != null) body.maxMemoryMB = opts.maxMemoryMB;
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
@@ -703,7 +703,7 @@ export class Sandbox {
* Get the current autoscale configuration for the sandbox.
*/
async getAutoscale(): Promise<AutoscaleStatus> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
if (!resp.ok) {
@@ -726,7 +726,7 @@ export class Sandbox {
* explicitly if you want it back.
*/
async setScalingLock(locked: boolean): Promise<ScalingLockStatus> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
@@ -745,7 +745,7 @@ export class Sandbox {
* Get the current scaling-lock state for the sandbox.
*/
async getScalingLock(): Promise<ScalingLockStatus> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
if (!resp.ok) {
@@ -766,7 +766,7 @@ export class Sandbox {
* per-store egress restriction.
*/
async getAllowedHosts(): Promise<AllowedHostsInfo> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/allowed-hosts`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/allowed-hosts`, {
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
if (!resp.ok) {
@@ -782,7 +782,7 @@ export class Sandbox {
headers["X-API-Key"] = this.apiKey;
}
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/timeout`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/timeout`, {
method: "POST",
headers,
body: JSON.stringify({ timeout }),
@@ -805,7 +805,7 @@ export class Sandbox {
body.retentionPolicy = opts.retentionPolicy;
}
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -823,7 +823,7 @@ export class Sandbox {
}
async listCheckpoints(): Promise<CheckpointInfo[]> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
@@ -835,7 +835,7 @@ export class Sandbox {
}
async restoreCheckpoint(checkpointId: string): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints/${checkpointId}/restore`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints/${checkpointId}/restore`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -849,7 +849,7 @@ export class Sandbox {
}
// After restore, rebuild ops clients since the VM was rebooted
- const data: SandboxData = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {
+ const data: SandboxData = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
}).then((r) => r.json());
@@ -873,7 +873,7 @@ export class Sandbox {
if (opts.envs) body.envs = opts.envs;
if (opts.secretStore) body.secretStore = opts.secretStore;
- const resp = await fetch(`${apiUrl}/sandboxes/from-checkpoint/${checkpointId}`, {
+ const resp = await apiFetch(`${apiUrl}/sandboxes/from-checkpoint/${checkpointId}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -892,7 +892,7 @@ export class Sandbox {
}
async deleteCheckpoint(checkpointId: string): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints/${checkpointId}`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints/${checkpointId}`, {
method: "DELETE",
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
@@ -909,7 +909,7 @@ export class Sandbox {
const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- const resp = await fetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches`, {
+ const resp = await apiFetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -936,7 +936,7 @@ export class Sandbox {
const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- const resp = await fetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches`, {
+ const resp = await apiFetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches`, {
headers: apiKey ? { "X-API-Key": apiKey } : {},
});
@@ -955,7 +955,7 @@ export class Sandbox {
const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- const resp = await fetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches/${patchId}`, {
+ const resp = await apiFetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches/${patchId}`, {
method: "DELETE",
headers: apiKey ? { "X-API-Key": apiKey } : {},
});
@@ -972,7 +972,7 @@ export class Sandbox {
* @param opts.expiresIn - URL validity in seconds (default: 3600, max: 86400)
*/
async downloadUrl(path: string, opts?: { expiresIn?: number }): Promise<string> {
- const resp = await fetch(
+ const resp = await apiFetch(
`${this.apiUrl}/sandboxes/${this.sandboxId}/files/download-url`,
{
method: "POST",
@@ -1000,7 +1000,7 @@ export class Sandbox {
* @param opts.expiresIn - URL validity in seconds (default: 3600, max: 86400)
*/
async uploadUrl(path: string, opts?: { expiresIn?: number }): Promise<string> {
- const resp = await fetch(
+ const resp = await apiFetch(
`${this.apiUrl}/sandboxes/${this.sandboxId}/files/upload-url`,
{
method: "POST",
@@ -1022,7 +1022,7 @@ export class Sandbox {
}
async createPreviewURL(opts: { port: number; domain?: string; authConfig?: Record<string, unknown> }): Promise<PreviewURLResult> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -1040,7 +1040,7 @@ export class Sandbox {
}
async listPreviewURLs(): Promise<PreviewURLResult[]> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
@@ -1052,7 +1052,7 @@ export class Sandbox {
}
async deletePreviewURL(port: number): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview/${port}`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview/${port}`, {
method: "DELETE",
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
diff --git a/sdks/typescript/src/snapshot.ts b/sdks/typescript/src/snapshot.ts
index 4e9083b1..13f8d4e2 100644
--- a/sdks/typescript/src/snapshot.ts
+++ b/sdks/typescript/src/snapshot.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
import { Image } from "./image.js";
import { sdkVersionHeaders } from "./version.js";
import { parseSSEStream } from "./sse.js";
@@ -90,7 +91,7 @@ export class Snapshots {
Accept: "text/event-stream",
};
- const resp = await fetch(`${this.apiUrl}/snapshots`, {
+ const resp = await apiFetch(`${this.apiUrl}/snapshots`, {
method: "POST",
headers,
body: JSON.stringify({
@@ -116,7 +117,7 @@ export class Snapshots {
* List all named snapshots for the current org.
*/
async list(): Promise<SnapshotInfo[]> {
- const resp = await fetch(`${this.apiUrl}/snapshots`, {
+ const resp = await apiFetch(`${this.apiUrl}/snapshots`, {
headers: this.headers,
});
@@ -131,7 +132,7 @@ export class Snapshots {
* Get a snapshot by name.
*/
async get(name: string): Promise<SnapshotInfo> {
- const resp = await fetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
+ const resp = await apiFetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
headers: this.headers,
});
@@ -168,7 +169,7 @@ export class Snapshots {
throw new Error(`Snapshot ${name} not ready after ${opts.timeoutMs}ms`);
}
- const resp = await fetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
+ const resp = await apiFetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
headers: this.headers,
});
if (resp.ok) {
@@ -190,7 +191,7 @@ export class Snapshots {
* Delete a named snapshot.
*/
async delete(name: string): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
+ const resp = await apiFetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
method: "DELETE",
headers: this.headers,
});
diff --git a/sdks/typescript/src/template.ts b/sdks/typescript/src/template.ts
index 8864cae9..91da6ab9 100644
--- a/sdks/typescript/src/template.ts
+++ b/sdks/typescript/src/template.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
import { sdkVersionHeaders } from "./version.js";
export interface TemplateInfo {
@@ -22,7 +23,7 @@ export class Templates {
}
async build(name: string, dockerfile: string): Promise<TemplateInfo> {
- const resp = await fetch(`${this.apiUrl}/templates`, {
+ const resp = await apiFetch(`${this.apiUrl}/templates`, {
method: "POST",
headers: this.headers,
body: JSON.stringify({ name, dockerfile }),
@@ -36,7 +37,7 @@ export class Templates {
}
async list(): Promise<TemplateInfo[]> {
- const resp = await fetch(`${this.apiUrl}/templates`, {
+ const resp = await apiFetch(`${this.apiUrl}/templates`, {
headers: this.headers,
});
@@ -48,7 +49,7 @@ export class Templates {
}
async get(name: string): Promise<TemplateInfo> {
- const resp = await fetch(`${this.apiUrl}/templates/${name}`, {
+ const resp = await apiFetch(`${this.apiUrl}/templates/${name}`, {
headers: this.headers,
});
@@ -60,7 +61,7 @@ export class Templates {
}
async delete(name: string): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/templates/${name}`, {
+ const resp = await apiFetch(`${this.apiUrl}/templates/${name}`, {
method: "DELETE",
headers: this.headers,
});
diff --git a/sdks/typescript/src/transport.test.ts b/sdks/typescript/src/transport.test.ts
new file mode 100644
index 00000000..d891a5d4
--- /dev/null
+++ b/sdks/typescript/src/transport.test.ts
@@ -0,0 +1,44 @@
+// The root's transport contract: importing the package installs nothing and
+// opens nothing; a sandbox request goes to the global fetch with the client's
+// own undici Agent as its per-request dispatcher; the process's global
+// dispatcher is the one Node started with, before and after.
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Agent, getGlobalDispatcher } from "undici";
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("sandbox client transport", () => {
+ it("leaves the global dispatcher alone and passes its own pool per request", async () => {
+ const before = getGlobalDispatcher();
+ const fetchMock = vi.spyOn(globalThis, "fetch");
+ const { Sandbox } = await import("./index.js");
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(getGlobalDispatcher()).toBe(before);
+
+ fetchMock.mockResolvedValue(
+ new Response(JSON.stringify({ sandboxID: "sb_1", status: "running" }), { status: 200 }),
+ );
+ const sandbox = await Sandbox.connect("sb_1", { apiKey: "k", apiUrl: "https://api.example.test" });
+ expect(sandbox.sandboxId).toBe("sb_1");
+
+ const [, init] = fetchMock.mock.calls[0] as [unknown, { dispatcher?: unknown }];
+ expect(init.dispatcher).toBeInstanceOf(Agent);
+ expect(init.dispatcher).not.toBe(before);
+ expect(getGlobalDispatcher()).toBe(before);
+ });
+
+ it("reuses one pool across requests", async () => {
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockImplementation(async () => new Response(JSON.stringify({ sandboxID: "sb_2", status: "running" }), { status: 200 }));
+ const { Sandbox } = await import("./index.js");
+ await Sandbox.connect("sb_2", { apiKey: "k", apiUrl: "https://api.example.test" });
+ await Sandbox.connect("sb_2", { apiKey: "k", apiUrl: "https://api.example.test" });
+ const pools = fetchMock.mock.calls.map(([, init]) => (init as { dispatcher?: unknown }).dispatcher);
+ expect(pools[0]).toBeInstanceOf(Agent);
+ expect(pools[1]).toBe(pools[0]);
+ });
+});
diff --git a/sdks/typescript/src/usage.ts b/sdks/typescript/src/usage.ts
index bb57e154..d4c60286 100644
--- a/sdks/typescript/src/usage.ts
+++ b/sdks/typescript/src/usage.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
// Usage + tags — TypeScript SDK surface.
//
// All numeric fields are GB-seconds. Dollars live in Stripe; the SDK
@@ -172,7 +173,7 @@ export class Usage {
limit: opts.limit?.toString(),
cursor: opts.cursor,
}, opts.filter);
- const resp = await fetch(`${this.apiUrl}/usage${qs}`, { headers: this.headers });
+ const resp = await apiFetch(`${this.apiUrl}/usage${qs}`, { headers: this.headers });
if (!resp.ok) await throwApiError(resp, "fetch usage");
return resp.json();
}
@@ -187,7 +188,7 @@ export class Usage {
limit: opts.limit?.toString(),
cursor: opts.cursor,
}, opts.filter);
- const resp = await fetch(`${this.apiUrl}/usage${qs}`, { headers: this.headers });
+ const resp = await apiFetch(`${this.apiUrl}/usage${qs}`, { headers: this.headers });
if (!resp.ok) await throwApiError(resp, "fetch usage");
return resp.json();
}
@@ -195,7 +196,7 @@ export class Usage {
/** `GET /sandboxes/:id/usage` — per-sandbox drilldown. */
async forSandbox(sandboxId: string, opts: Pick<UsageQueryOpts, "from" | "to"> = {}): Promise<SandboxUsageResponse> {
const qs = this.buildQueryString({ from: opts.from, to: opts.to });
- const resp = await fetch(`${this.apiUrl}/sandboxes/${sandboxId}/usage${qs}`, { headers: this.headers });
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${sandboxId}/usage${qs}`, { headers: this.headers });
if (!resp.ok) await throwApiError(resp, "fetch sandbox usage");
return resp.json();
}
@@ -219,7 +220,7 @@ export class Tags {
/** `GET /tags` — discovery of all tag keys across the org. */
async listKeys(): Promise<TagKeyInfo[]> {
- const resp = await fetch(`${this.apiUrl}/tags`, { headers: this.headers });
+ const resp = await apiFetch(`${this.apiUrl}/tags`, { headers: this.headers });
if (!resp.ok) await throwApiError(resp, "list tag keys");
const body = await resp.json();
return body.keys;
@@ -227,14 +228,14 @@ export class Tags {
/** `GET /sandboxes/:id/tags` — current tag set. */
async get(sandboxId: string): Promise<{ tags: Record<string, string>; tagsLastUpdatedAt: string | null }> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${sandboxId}/tags`, { headers: this.headers });
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${sandboxId}/tags`, { headers: this.headers });
if (!resp.ok) await throwApiError(resp, "get tags");
return resp.json();
}
/** `PUT /sandboxes/:id/tags` — full replace. `{}` clears all tags. */
async set(sandboxId: string, tags: Record<string, string>): Promise<{ tags: Record<string, string>; tagsLastUpdatedAt: string | null }> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${sandboxId}/tags`, {
+ const resp = await apiFetch(`${this.apiUrl}/sandboxes/${sandboxId}/tags`, {
method: "PUT",
headers: this.headers,
body: JSON.stringify(tags),
diff --git a/sdks/typescript/src/agents/webhooks.test.ts b/sdks/typescript/src/verify-webhook.test.ts
similarity index 98%
rename from sdks/typescript/src/agents/webhooks.test.ts
rename to sdks/typescript/src/verify-webhook.test.ts
index 32976821..5b940cdc 100644
--- a/sdks/typescript/src/agents/webhooks.test.ts
+++ b/sdks/typescript/src/verify-webhook.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { verifyWebhook, WebhookVerificationError } from "./webhooks.js";
+import { verifyWebhook, WebhookVerificationError } from "./verify-webhook.js";
const SECRET = "whsec_" + btoa("super-secret-key-bytes-123456");
diff --git a/sdks/typescript/src/agents/webhooks.ts b/sdks/typescript/src/verify-webhook.ts
similarity index 94%
rename from sdks/typescript/src/agents/webhooks.ts
rename to sdks/typescript/src/verify-webhook.ts
index e5e9f929..3fe70b5a 100644
--- a/sdks/typescript/src/agents/webhooks.ts
+++ b/sdks/typescript/src/verify-webhook.ts
@@ -1,5 +1,5 @@
-// Webhook verification for OpenComputer destinations — shared across **session** webhooks
-// (Durable Agent Sessions) and **sandbox lifecycle** webhooks. One verifier, one envelope.
+// Webhook verification for OpenComputer destinations: **sandbox lifecycle** webhooks, and
+// **session** webhooks delivered under the `webhook-` header dialect. One verifier, one envelope.
//
// Deliveries are signed with the Standard Webhooks scheme (https://www.standardwebhooks.com).
// Sandbox webhooks are delivered by Svix, which uses the same scheme under `svix-`-prefixed
@@ -13,15 +13,17 @@
// browsers, Deno, and Node 16+ — the same places the SDK runs. Verify against the RAW
// request body, BEFORE JSON-parsing it.
-import type { Event } from "./types.js";
import { normalize } from "./normalize.js";
+/** The nested event when the caller names no type: whatever the delivery carried, keyed by `type`. */
+export type WebhookEvent = { type: string; [key: string]: unknown };
+
/**
* The envelope OpenComputer POSTs to a destination (camelCase). One shape for both products;
* the product-specific id is set accordingly. `E` is the nested event type — pass
- * `SandboxLifecycleEvent` for sandbox webhooks, leave it as the session `Event` otherwise.
+ * `SandboxLifecycleEvent` for sandbox webhooks.
*/
-export interface WebhookDelivery<E = Event> {
+export interface WebhookDelivery<E = WebhookEvent> {
/** The event type — route on this (e.g. `turn.completed`, `sandbox.stopped`). */
type: string;
/** Set on **session** webhooks. */
@@ -126,7 +128,7 @@ function timingSafeEqual(a: string, b: string): boolean {
* if (delivery.type === "turn.completed") { /* route via delivery.metadata *\/ }
* ```
*/
-export async function verifyWebhook<E = Event>(
+export async function verifyWebhook<E = WebhookEvent>(
rawBody: string,
headers: HeaderBag | Headers,
secret: string,
diff --git a/sdks/typescript/src/version.ts b/sdks/typescript/src/version.ts
index 427e9d67..6a27461a 100644
--- a/sdks/typescript/src/version.ts
+++ b/sdks/typescript/src/version.ts
@@ -27,7 +27,7 @@ export const SDK_VERSION_HEADER = "x-oc-sdk-version";
* only failure mode that matters — a stale constant here would silently route a
* v2 caller to the old runtime.
*/
-export const SDK_VERSION = "1.1.1";
+export const SDK_VERSION = "2.0.0";
/** The identifying header, as a spreadable object. */
export function sdkVersionHeaders(): Record<string, string> {
diff --git a/sdks/typescript/src/webhooks.ts b/sdks/typescript/src/webhooks.ts
index 994a59d0..41c40a29 100644
--- a/sdks/typescript/src/webhooks.ts
+++ b/sdks/typescript/src/webhooks.ts
@@ -1,3 +1,4 @@
+import { apiFetch } from "./http2.js";
// Sandbox lifecycle webhooks — the account-level control surface.
//
// PREVIEW: newly available functionality; the surface may change.
@@ -13,7 +14,7 @@
// const { id, secret } = await webhooks.create({ url: "https://app.example.com/oc" });
// // `secret` verifies deliveries; it's returned here and re-fetchable via webhooks.getSecret(id).
-import type { WebhookDelivery } from "./agents/webhooks.js";
+import type { WebhookDelivery } from "./verify-webhook.js";
function resolveApiUrl(url: string): string {
const base = url.replace(/\/+$/, "");
@@ -201,7 +202,7 @@ export class WebhookDeliveries {
/** List recent delivery attempts for a destination. */
async list(destinationId: string): Promise<WebhookDeliveryRecord[]> {
- const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries`, {
+ const resp = await apiFetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries`, {
headers: this.headers,
});
if (!resp.ok) return fail(resp, "list deliveries");
@@ -211,7 +212,7 @@ export class WebhookDeliveries {
/** Fetch one delivered message by id. */
async get(destinationId: string, deliveryId: string): Promise<WebhookMessage> {
- const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}`, {
+ const resp = await apiFetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}`, {
headers: this.headers,
});
if (!resp.ok) return fail(resp, "get delivery");
@@ -223,7 +224,7 @@ export class WebhookDeliveries {
* receiver that dedupes treats it as the same message — for when the original never landed.
*/
async redeliver(destinationId: string, deliveryId: string): Promise<{ ok: boolean }> {
- const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}/redeliver`, {
+ const resp = await apiFetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}/redeliver`, {
method: "POST",
headers: this.headers,
});
@@ -263,7 +264,7 @@ export class Webhooks {
*/
async create(params: CreateWebhookParams): Promise<CreateWebhookResult> {
const { idempotencyKey, ...body } = params;
- const resp = await fetch(`${this.apiUrl}/webhooks`, {
+ const resp = await apiFetch(`${this.apiUrl}/webhooks`, {
method: "POST",
headers: this.headers(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined),
body: JSON.stringify(body),
@@ -273,14 +274,14 @@ export class Webhooks {
}
async list(): Promise<WebhookDestination[]> {
- const resp = await fetch(`${this.apiUrl}/webhooks`, { headers: this.headers() });
+ const resp = await apiFetch(`${this.apiUrl}/webhooks`, { headers: this.headers() });
if (!resp.ok) return fail(resp, "list webhooks");
const body = (await resp.json()) as { data?: WebhookDestination[] } | WebhookDestination[];
return Array.isArray(body) ? body : body.data ?? [];
}
async get(id: string): Promise<WebhookDestination> {
- const resp = await fetch(`${this.apiUrl}/webhooks/${id}`, { headers: this.headers() });
+ const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}`, { headers: this.headers() });
if (!resp.ok) return fail(resp, "get webhook");
return resp.json();
}
@@ -290,7 +291,7 @@ export class Webhooks {
* owner (API key) — use it to verify deliveries. Rotate with `update(id, { rotateSecret: true })`.
*/
async getSecret(id: string): Promise<string> {
- const resp = await fetch(`${this.apiUrl}/webhooks/${id}/secret`, { headers: this.headers() });
+ const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}/secret`, { headers: this.headers() });
if (!resp.ok) return fail(resp, "get webhook secret");
const body = (await resp.json()) as { secret: string };
return body.secret;
@@ -298,7 +299,7 @@ export class Webhooks {
/** Update a destination — pause/resume (`enabled`), retune `eventTypes`, change `url`, or rotate `secret`. */
async update(id: string, params: UpdateWebhookParams): Promise<CreateWebhookResult> {
- const resp = await fetch(`${this.apiUrl}/webhooks/${id}`, {
+ const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}`, {
method: "PATCH",
headers: this.headers(),
body: JSON.stringify(params),
@@ -309,7 +310,7 @@ export class Webhooks {
/** Delete a destination (removes its Svix endpoint). Delivery history for a deleted destination is no longer queryable. */
async delete(id: string): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/webhooks/${id}`, { method: "DELETE", headers: this.headers() });
+ const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}`, { method: "DELETE", headers: this.headers() });
if (!resp.ok) return fail(resp, "delete webhook");
}
@@ -318,7 +319,7 @@ export class Webhooks {
* Returns the queued Svix message; delivery is asynchronous — check `deliveries` for the result.
*/
async test(id: string): Promise<WebhookTestResult> {
- const resp = await fetch(`${this.apiUrl}/webhooks/${id}/test`, { method: "POST", headers: this.headers() });
+ const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}/test`, { method: "POST", headers: this.headers() });
if (!resp.ok) return fail(resp, "test webhook");
return resp.json();
}
diff --git a/sdks/typescript/src/websocket.ts b/sdks/typescript/src/websocket.ts
index ac3eb944..faded21c 100644
--- a/sdks/typescript/src/websocket.ts
+++ b/sdks/typescript/src/websocket.ts
@@ -1,21 +1,21 @@
// websocket.ts — opening a WebSocket without tripping over our own HTTP/2 agent.
//
-// configureHttp2 installs a GLOBAL undici dispatcher with `allowH2: true`,
-// which is right for the REST surface: h2 multiplexes a burst of creates down
-// one connection. But Node's built-in WebSocket is undici's, and it uses that
-// same global dispatcher — so it negotiates h2 via ALPN and then tries to
-// upgrade. A WebSocket over h2 needs RFC 8441 extended CONNECT, which the
-// server's WebSocket library does not implement (nor do most), so the upgrade
-// simply fails.
+// The REST surface runs on an undici Agent with `allowH2: true` (http2.ts):
+// h2 multiplexes a burst of creates down one connection. A WebSocket must not
+// use that agent: it would negotiate h2 via ALPN and then try to upgrade, and
+// a WebSocket over h2 needs RFC 8441 extended CONNECT, which the server's
+// WebSocket library does not implement (nor do most), so the upgrade simply
+// fails.
//
// Measured against dev, same URL, back to back:
//
// default dispatcher (no allowH2): OPEN
// allowH2:true dispatcher : ERROR
//
-// So WebSockets get their own dispatcher with h2 off. The REST path keeps h2
-// and its prewarmed pool; only the upgrade is forced down HTTP/1.1, which is
-// what an upgrade requires anyway.
+// So WebSockets get their own dispatcher with h2 off, passed per connection.
+// The REST path keeps h2 and its prewarmed pool; only the upgrade is forced
+// down HTTP/1.1, which is what an upgrade requires anyway. Neither agent is
+// ever installed as the process's global dispatcher.
let wsDispatcher: unknown | null = null;
let wsCtor: typeof WebSocket | null = null;