Skip to content

An open-source, faster Devin alternative

TypeScript

feat(webhooks): sandbox lifecycle webhooks — docs + SDK (Preview)

Igor Zalutski1f26d5cd9cc6
diff --git a/docs/agent-sessions/webhooks.mdx b/docs/agent-sessions/webhooks.mdx
index a906136b..946fa742 100644
--- a/docs/agent-sessions/webhooks.mdx
+++ b/docs/agent-sessions/webhooks.mdx
@@ -161,4 +161,6 @@ function verify(headers, rawBody, secret) {
}
```
+<Note>These deliver a **session's** events (turns, messages, results). To react to **sandbox lifecycle** — boot, hibernate, stop, scale — see [Sandbox webhooks](/sandboxes/webhooks): the same envelope shape, Standard Webhooks signing, and the same `verifyWebhook` helper.</Note>
+
<Note>Today, delivery is over **generic webhooks**. Slack, GitHub comments, Jira, and email are coming soon — all on this same event and delivery model.</Note>
diff --git a/docs/docs.json b/docs/docs.json
index e105dc93..7f21929c 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -46,6 +46,7 @@
"sandboxes/secrets",
"sandboxes/patches",
"sandboxes/preview-urls",
+ "sandboxes/webhooks",
"sandboxes/elasticity",
"sandboxes/burst-sandboxes",
{
diff --git a/docs/sandboxes/webhooks.mdx b/docs/sandboxes/webhooks.mdx
new file mode 100644
index 00000000..9046a0cb
--- /dev/null
+++ b/docs/sandboxes/webhooks.mdx
@@ -0,0 +1,202 @@
+---
+mode: "wide"
+title: "Webhooks"
+description: "Subscribe to sandbox lifecycle events — signed, retried, and redeliverable"
+tag: "Preview"
+---
+
+<Note>**Preview** — sandbox webhooks are newly available and still evolving; the shape may change. We'd love your feedback.</Note>
+
+Register a **destination** and OpenComputer delivers a sandbox's lifecycle events to it as a small, signed **delivery envelope** — at-least-once, retried, and redeliverable. Use it to react when a sandbox boots, hibernates, stops, or scales, without polling.
+
+The envelope is camelCase, with top-level routing fields, your sandbox [`metadata`](/api-reference/sandboxes/create), and the full event nested under `event`:
+
+```json
+{
+ "type": "sandbox.stopped",
+ "sandboxId": "sb-3f9a…",
+ "eventId": "sb-3f9a…:3:142",
+ "deliveryId": "whd_…", // == webhook-id (dedupe on it)
+ "metadata": { "team": "acme", "job": "build-1421" },
+ "event": {
+ "id": "sb-3f9a…:3:142", "ts": "2026-06-24T12:00:00Z",
+ "orgId": "…", "sandboxId": "sb-3f9a…",
+ "type": "sandbox.stopped", "data": { "reason": "user_requested" }
+ }
+}
+```
+
+`metadata` is the sandbox's metadata, delivered **verbatim on every send and redelivery**, so a handler can route the callback without a second lookup. Dedupe on **`deliveryId`** (it equals the `webhook-id` header).
+
+## Events
+
+Subscribe to all events, or filter with `event_types` (exact like `sandbox.stopped`, or a prefix like `sandbox.*`).
+
+| Event | When | `event.data` |
+| --- | --- | --- |
+| `sandbox.created` | the sandbox resource is accepted | `template`, `cpuCount`, `memoryMB` |
+| `sandbox.ready` | the VM has booted and can run commands | — |
+| `sandbox.hibernated` | the sandbox was paused (disk persisted) | — |
+| `sandbox.resumed` | a hibernated sandbox woke | — |
+| `sandbox.stopped` | the sandbox stopped | `reason`: `user_requested` \| `expired` \| `crash` |
+| `sandbox.migrated` | the sandbox moved to new infrastructure | — |
+| `sandbox.checkpoint.created` | a checkpoint was taken | `checkpointId` |
+| `sandbox.forked` | a sandbox was forked from a checkpoint | `parentId` |
+| `sandbox.scaled` | the sandbox's resources changed | `cpuCount`, `memoryMB` |
+| `sandbox.preview_url.changed` | a preview-URL port mapping changed | `port`, `url` |
+
+## Destinations
+
+A destination is **org-scoped** by default (all your sandboxes), or pinned to one sandbox with `sandbox_id`.
+
+<CodeGroup>
+
+```ts TypeScript SDK
+import { Webhooks } from "@opencomputer/sdk";
+
+const webhooks = new Webhooks({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
+
+const { id, secret } = await webhooks.create({
+ url: "https://app.example.com/oc-webhook",
+ eventTypes: ["sandbox.stopped", "sandbox.ready"],
+ name: "prod", // optional; makes create idempotent
+});
+// `secret` (whsec_…) is returned ONCE — store it now; you need it to verify deliveries.
+```
+
+```http REST API
+POST https://app.opencomputer.dev/api/webhooks
+X-API-Key: $OPENCOMPUTER_API_KEY
+Content-Type: application/json
+
+{
+ "url": "https://app.example.com/oc-webhook",
+ "event_types": ["sandbox.stopped", "sandbox.ready"],
+ "name": "prod"
+}
+```
+
+</CodeGroup>
+
+Every destination is **signed**. If you don't pass a `secret`, OpenComputer generates one (`whsec_…`) and returns it **once** on create — store it then; it's never shown again (reads return only `has_secret`). Pass `name` (unique per org) or an `Idempotency-Key` header to make create safe to retry: the same request returns the same destination instead of a duplicate; a different config under the same `name` is rejected with `409`.
+
+<Tabs>
+
+<Tab title="TypeScript SDK">
+
+| Call | Purpose |
+| --- | --- |
+| `webhooks.create(params)` | Register a destination (returns `secret` once if generated). |
+| `webhooks.list()` | List destinations. |
+| `webhooks.get(id)` | Fetch one (`has_secret`, never the secret). |
+| `webhooks.update(id, params)` | Pause/resume (`enabled`), retune `eventTypes`, change `url`, rotate `secret`. |
+| `webhooks.delete(id)` | Soft-delete — history is retained, pending deliveries canceled. |
+| `webhooks.test(id)` | Send a synthetic `sandbox.test` event and return the result inline. |
+
+</Tab>
+
+<Tab title="REST API">
+
+| Method · Path | Purpose |
+| --- | --- |
+| `POST /api/webhooks` | Register a destination. |
+| `GET /api/webhooks` | List destinations. |
+| `GET /api/webhooks/:id` | Fetch one. |
+| `PATCH /api/webhooks/:id` | Pause/resume, retune `event_types`, change `url`, rotate `secret`. |
+| `DELETE /api/webhooks/:id` | Soft-delete (history retained). |
+| `POST /api/webhooks/:id/test` | Send a synthetic `sandbox.test` event. |
+
+</Tab>
+
+</Tabs>
+
+### Subscribe at create
+
+`sandbox.created` and `sandbox.ready` fire before a separate `webhooks.create` call could know the sandbox id. To capture a sandbox's **full** lifecycle, register the webhook **with** the sandbox — it's pinned to that sandbox and gets every event from `created` on:
+
+<CodeGroup>
+
+```ts TypeScript SDK
+import { Sandbox } from "@opencomputer/sdk";
+
+const sandbox = await Sandbox.create({
+ webhooks: [{ url: "https://app.example.com/oc-webhook" }],
+});
+// the generated signing secret is on the create response: sandbox.webhooks[0].secret
+```
+
+```http REST API
+POST https://app.opencomputer.dev/api/sandboxes
+X-API-Key: $OPENCOMPUTER_API_KEY
+Content-Type: application/json
+
+{ "template": "base", "webhooks": [{ "url": "https://app.example.com/oc-webhook" }] }
+```
+
+</CodeGroup>
+
+## Deliveries
+
+Every send and its outcome — the data behind a deliveries dashboard.
+
+<Tabs>
+
+<Tab title="TypeScript SDK">
+
+| Call | Purpose |
+| --- | --- |
+| `webhooks.deliveries.list(id, opts)` | List a destination's deliveries (cursor-paginated). |
+| `webhooks.deliveries.get(id, deliveryId)` | One delivery, in detail. |
+| `webhooks.deliveries.redeliver(id, deliveryId)` | Re-send any delivery (not only dead-lettered). |
+
+</Tab>
+
+<Tab title="REST API">
+
+| Method · Path | Purpose |
+| --- | --- |
+| `GET /api/webhooks/:id/deliveries?status=&cursor=&limit=` | List deliveries (paginated). |
+| `GET /api/webhooks/:id/deliveries/:deliveryId` | One delivery, in detail. |
+| `POST /api/webhooks/:id/deliveries/:deliveryId/redeliver` | Re-send any delivery. |
+
+</Tab>
+
+</Tabs>
+
+A delivery moves `pending → delivering → delivered`, or `failed` (retrying) → `dead_letter` after the max attempts. Deleting a destination moves its in-flight deliveries to `canceled`. List responses are cursor-paginated: `{ data, next_cursor, has_more }`.
+
+```
+Delivery = {
+ id, destination, event_id, event_type, status, attempts, retry_count,
+ last_attempt_at, response_code?, error?, created_at, updated_at, delivered_at?
+}
+```
+
+Redelivery re-sends the **same** delivery (same `webhook-id`) with a fresh retry budget — for when the original never landed. A receiver that dedupes on `webhook-id` will treat it as the same message.
+
+## Signing, retries, and dedupe
+
+- **HTTPS only.** Private, loopback, link-local, and cloud-metadata addresses are refused (at registration and at send).
+- **Always signed** with [Standard Webhooks](https://www.standardwebhooks.com). Every request carries `webhook-id` (= `deliveryId`), `webhook-timestamp`, and `webhook-signature` = `v1,<base64(HMAC-SHA256(secret, "{webhook-id}.{webhook-timestamp}.{rawBody}"))>`. Verify against the **raw request body, before parsing it**; the timestamp guards replay. Plus `X-OC-Delivery-ID` and `X-OC-Sandbox-ID` for correlation. Your `secret` is write-only.
+- **At-least-once.** Retried with exponential backoff; after the max attempts a delivery is **dead-lettered** (inspect and redeliver it). A duplicate can still arrive, so **dedupe on `webhook-id`** (= `deliveryId`).
+- A delivery succeeds on HTTP `2xx`.
+
+### Verify a webhook
+
+The SDK ships a verifier — no extra dependency, runs in Node / Cloudflare Workers / browsers — that checks the signature and returns the parsed envelope. It's the **same `verifyWebhook`** used for [session webhooks](/agent-sessions/webhooks); pass `SandboxLifecycleEvent` to type the nested event:
+
+```ts
+import { verifyWebhook, type SandboxLifecycleEvent } from "@opencomputer/sdk";
+
+// rawBody = the RAW request body string, read BEFORE JSON.parse.
+// Throws on a missing / expired / invalid signature.
+const delivery = await verifyWebhook<SandboxLifecycleEvent>(rawBody, request.headers, process.env.OC_WEBHOOK_SECRET!);
+
+if (delivery.type === "sandbox.stopped") {
+ console.log(delivery.sandboxId, delivery.event.data.reason); // route via delivery.metadata
+}
+```
+
+Or verify with any [Standard Webhooks](https://www.standardwebhooks.com) library directly, against the raw body and the `webhook-id` / `webhook-timestamp` / `webhook-signature` headers.
+
+<Note>Webhooks here cover **sandbox lifecycle**. To deliver an agent's *session* events (turns, messages, results), see [Agent Sessions webhooks](/agent-sessions/webhooks) — same envelope shape, signing, and verifier.</Note>
diff --git a/sdks/typescript/README.md b/sdks/typescript/README.md
index 18a8adab..3cfc8d09 100644
--- a/sdks/typescript/README.md
+++ b/sdks/typescript/README.md
@@ -60,11 +60,33 @@ await session.destinations.create({ url: "https://app.example.com/oc-callback",
// 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 session = await oc.sessions.get(delivery.sessionId!);
const { result } = await session.result();
}
```
+## 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.**
+
+```typescript
+import { Webhooks, verifyWebhook, type SandboxLifecycleEvent } from "@opencomputer/sdk";
+
+const webhooks = new Webhooks({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
+
+// `secret` (whsec_…) is returned ONCE on create — store it; you need it to verify.
+const { secret } = await webhooks.create({
+ url: "https://app.example.com/oc-webhook",
+ eventTypes: ["sandbox.stopped"],
+});
+
+// In your handler — verify against the RAW body, then route:
+const delivery = await verifyWebhook<SandboxLifecycleEvent>(rawBody, request.headers, secret);
+if (delivery.type === "sandbox.stopped") {
+ console.log(delivery.sandboxId, delivery.event.data.reason);
+}
+```
+
## Configuration
**Sandboxes** (`Sandbox`):
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index d1879d58..c2cca828 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/sdk",
- "version": "0.7.6",
+ "version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "0.7.6",
+ "version": "0.8.0",
"license": "MIT",
"devDependencies": {
"@types/node": "^25.3.0",
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 6d076221..2ad6da60 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.7.6",
+ "version": "0.8.0",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",
diff --git a/sdks/typescript/src/agents/webhooks.ts b/sdks/typescript/src/agents/webhooks.ts
index 229c0a59..62193798 100644
--- a/sdks/typescript/src/agents/webhooks.ts
+++ b/sdks/typescript/src/agents/webhooks.ts
@@ -1,4 +1,5 @@
-// Webhook verification for Durable Agent Sessions destinations.
+// Webhook verification for OpenComputer destinations — shared across **session** webhooks
+// (Durable Agent Sessions) and **sandbox lifecycle** webhooks. One verifier, one envelope.
//
// Deliveries are signed with the Standard Webhooks scheme (https://www.standardwebhooks.com):
// headers `webhook-id`, `webhook-timestamp`, `webhook-signature`, where
@@ -13,16 +14,29 @@
import type { Event } from "./types.js";
import { normalize } from "./normalize.js";
-/** The envelope OpenComputer POSTs to a destination (see the Webhooks docs). */
+/**
+ * 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.
+ */
export interface WebhookDelivery<E = Event> {
- /** The event type — route on this (e.g. `turn.completed`). */
+ /** The event type — route on this (e.g. `turn.completed`, `sandbox.stopped`). */
type: string;
- sessionId: string;
- /** Equals the `webhook-id` header — dedupe on it. */
+ /** Set on **session** webhooks. */
+ sessionId?: string;
+ /** Set on **sandbox lifecycle** webhooks. */
+ sandboxId?: string;
+ /** The underlying event id — app-level correlation. */
eventId: string;
- /** The session's opaque routing state, verbatim (`null` when unset). */
+ /**
+ * The delivery id. On **sandbox** webhooks this equals the `webhook-id` header — dedupe on
+ * it (stable across retries and redelivery). On **session** webhooks today `webhook-id`
+ * equals `eventId`; `deliveryId` is also provided via the `X-OC-Delivery-ID` header.
+ */
+ deliveryId?: string;
+ /** Opaque routing metadata, verbatim (`null` when unset). */
metadata: Record<string, unknown> | null;
- /** The full event — the same shape the SSE stream emits. */
+ /** The full event — the same shape the SSE stream emits (session) or the lifecycle event (sandbox). */
event: E;
}
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index 42cc994a..90f02327 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -22,6 +22,21 @@ export { Mounts, type AddMountOpts, type MountInfo, type MountBackend } from "./
export { type Shell, type ShellOpts, type ShellRunOpts, ShellBusyError, ShellClosedError } from "./shell.js";
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
export { Templates, type TemplateInfo } from "./template.js";
+export {
+ Webhooks,
+ WebhookDeliveries,
+ type WebhooksOptions,
+ type CreateWebhookParams,
+ type CreateWebhookResult,
+ type UpdateWebhookParams,
+ type WebhookDestination,
+ type WebhookDeliveryRecord,
+ type WebhookDeliveryStatus,
+ type WebhookTestResult,
+ type SandboxWebhookDelivery,
+ type SandboxLifecycleEvent,
+ type SandboxWebhookEventType,
+} from "./webhooks.js";
export { SecretStore, type SecretStoreInfo, type SecretEntryInfo, type SecretStoreOpts, type CreateSecretStoreOpts, type UpdateSecretStoreOpts } from "./project.js";
export {
Usage,
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index d191e2b4..b88aa8ee 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -60,6 +60,15 @@ export interface SandboxOpts {
* one (the old one stops working immediately).
*/
previewAuth?: { scheme?: "bearer"; token?: "auto" | string };
+ /**
+ * Register webhook destination(s) for this sandbox's lifecycle events, atomically with
+ * create — so you receive `sandbox.created` / `sandbox.ready`, which fire before a separate
+ * `webhooks.create` call could know the sandbox id. Each is pinned to this sandbox and
+ * receives its full lifecycle. A generated signing secret is returned once on the create
+ * response (`webhooks[].secret`). For fleet-wide subscriptions, use a standalone org
+ * destination (`new Webhooks().create(...)`) instead.
+ */
+ webhooks?: Array<{ url: string; secret?: string; eventTypes?: string[] }>;
}
interface SandboxData {
@@ -312,6 +321,7 @@ export class Sandbox {
if (opts.secretStore) body.secretStore = opts.secretStore;
if (opts.image) body.image = opts.image.toJSON();
if (opts.snapshot) body.snapshot = opts.snapshot;
+ if (opts.webhooks?.length) body.webhooks = opts.webhooks;
if (opts.previewAuth) {
body.previewAuth = {
scheme: opts.previewAuth.scheme ?? "bearer",
diff --git a/sdks/typescript/src/webhooks.ts b/sdks/typescript/src/webhooks.ts
new file mode 100644
index 00000000..886909f2
--- /dev/null
+++ b/sdks/typescript/src/webhooks.ts
@@ -0,0 +1,290 @@
+// Sandbox lifecycle webhooks — the account-level control surface.
+//
+// PREVIEW: newly available functionality; the surface may change.
+//
+// Register a destination and OpenComputer delivers sandbox lifecycle events to it as a
+// small, signed envelope — at-least-once, retried, dead-lettered, and redeliverable. This is
+// the management client (org API key, server-side); to VERIFY an incoming delivery in your
+// handler use `verifyWebhook` (exported from the package root, shared with session webhooks).
+//
+// import { Webhooks } from "@opencomputer/sdk";
+// const webhooks = new Webhooks({ apiKey: process.env.OPENCOMPUTER_API_KEY });
+// const { id, secret } = await webhooks.create({ url: "https://app.example.com/oc" });
+// // `secret` is shown ONCE — store it now; you'll need it to verify deliveries.
+
+import type { WebhookDelivery } from "./agents/webhooks.js";
+
+function resolveApiUrl(url: string): string {
+ const base = url.replace(/\/+$/, "");
+ return base.endsWith("/api") ? base : `${base}/api`;
+}
+
+// ---- the delivered envelope (what your endpoint receives; verify with `verifyWebhook`) ----
+
+export type SandboxWebhookEventType =
+ | "sandbox.created"
+ | "sandbox.ready"
+ | "sandbox.hibernated"
+ | "sandbox.resumed"
+ | "sandbox.stopped"
+ | "sandbox.migrated"
+ | "sandbox.checkpoint.created"
+ | "sandbox.forked"
+ | "sandbox.scaled"
+ | "sandbox.preview_url.changed"
+ | "sandbox.test";
+
+/** The lifecycle event nested under `event` in a delivery. */
+export interface SandboxLifecycleEvent {
+ id: string;
+ ts: string;
+ orgId: string;
+ sandboxId: string;
+ type: SandboxWebhookEventType;
+ /** Event-specific fields, e.g. `{ reason }` on stopped, `{ parentId }` on forked. */
+ data: Record<string, unknown>;
+}
+
+/**
+ * The delivered envelope for sandbox webhooks: the shared {@link WebhookDelivery} carrying a
+ * {@link SandboxLifecycleEvent} under `event`. On these deliveries `sandboxId` and `deliveryId`
+ * are always set, and `deliveryId` equals the `webhook-id` header (dedupe on it).
+ *
+ * Verify an incoming request with: `verifyWebhook<SandboxLifecycleEvent>(rawBody, headers, secret)`.
+ */
+export type SandboxWebhookDelivery = WebhookDelivery<SandboxLifecycleEvent>;
+
+// ---- destinations ----
+
+export interface WebhookDestination {
+ id: string;
+ name: string | null;
+ url: string;
+ /** Event-type allow-list (exact or `prefix.*`); empty = all. */
+ eventTypes: string[];
+ /** Scoped to one sandbox, or `null` for all of the org's sandboxes. */
+ sandboxId: string | null;
+ enabled: boolean;
+ /** Whether a signing secret is set (the secret itself is never returned after create). */
+ hasSecret: boolean;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface CreateWebhookParams {
+ url: string;
+ /** Optional unique name (per org) — makes create get-or-create / idempotent. */
+ name?: string;
+ /** Signing secret. Omit and OpenComputer generates a `whsec_…` one, returned ONCE on create. */
+ secret?: string;
+ /** Event-type allow-list (exact or `prefix.*`); default all. */
+ eventTypes?: string[];
+ /** Scope to one sandbox; omit for all of the org's sandboxes. */
+ sandboxId?: string;
+ enabled?: boolean;
+ /** Idempotency-Key header — a timed-out retry returns the same destination, never a duplicate. */
+ idempotencyKey?: string;
+}
+
+/** The create response — the only time `secret` is ever returned (and only when generated). */
+export interface CreateWebhookResult extends WebhookDestination {
+ /** The signing secret (`whsec_…`). Returned ONCE, only when OpenComputer generated it. Store it now. */
+ secret?: string;
+}
+
+export interface UpdateWebhookParams {
+ url?: string;
+ /** Pass `null` to clear the allow-list (deliver all types). */
+ eventTypes?: string[] | null;
+ enabled?: boolean;
+ /** Rotate the signing secret; a generated rotation is returned once (see {@link CreateWebhookResult}). */
+ secret?: string;
+ name?: string;
+}
+
+// ---- deliveries (the control surface behind a deliveries dashboard) ----
+
+export type WebhookDeliveryStatus =
+ | "pending"
+ | "delivering"
+ | "delivered"
+ | "failed"
+ | "dead_letter"
+ | "canceled";
+
+export interface WebhookDeliveryRecord {
+ id: string;
+ destination: string;
+ eventId: string;
+ eventType: string;
+ status: WebhookDeliveryStatus;
+ /** Lifetime attempt count (audit). */
+ attempts: number;
+ /** Retry budget consumed since the last (re)enqueue; reset by a manual redeliver. */
+ retryCount: number;
+ lastAttemptAt: string | null;
+ responseCode: number | null;
+ error: string | null;
+ createdAt: string;
+ updatedAt: string;
+ deliveredAt: string | null;
+}
+
+export interface WebhookTestResult {
+ delivered: boolean;
+ responseCode: number | null;
+ error?: string;
+}
+
+export interface ListPage<T> {
+ data: T[];
+ nextCursor: string | null;
+ hasMore: boolean;
+}
+
+export interface WebhooksOptions {
+ /** Defaults to `process.env.OPENCOMPUTER_API_KEY`. */
+ apiKey?: string;
+ /** Defaults to `process.env.OPENCOMPUTER_API_URL` or `https://app.opencomputer.dev`. */
+ apiUrl?: string;
+}
+
+async function fail(resp: Response, what: string): Promise<never> {
+ let detail = "";
+ try {
+ const body = (await resp.json()) as { error?: { message?: string } | string };
+ detail = typeof body.error === "string" ? body.error : body.error?.message ?? "";
+ } catch {
+ /* no JSON body */
+ }
+ throw new Error(`${what}: HTTP ${resp.status}${detail ? ` — ${detail}` : ""}`);
+}
+
+/** Delivery records for the org's webhook destinations. Reached via `webhooks.deliveries`. */
+export class WebhookDeliveries {
+ constructor(
+ private readonly apiUrl: string,
+ private readonly apiKey: string,
+ ) {}
+
+ private get headers(): Record<string, string> {
+ const h: Record<string, string> = { "Content-Type": "application/json" };
+ if (this.apiKey) h["X-API-Key"] = this.apiKey;
+ return h;
+ }
+
+ /** List deliveries for a destination (cursor-paginated). */
+ async list(
+ destinationId: string,
+ params: { status?: WebhookDeliveryStatus; cursor?: string; limit?: number } = {},
+ ): Promise<ListPage<WebhookDeliveryRecord>> {
+ const q = new URLSearchParams();
+ if (params.status) q.set("status", params.status);
+ if (params.cursor) q.set("cursor", params.cursor);
+ if (params.limit != null) q.set("limit", String(params.limit));
+ const qs = q.toString();
+ const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries${qs ? `?${qs}` : ""}`, {
+ headers: this.headers,
+ });
+ if (!resp.ok) return fail(resp, "list deliveries");
+ return resp.json();
+ }
+
+ /** Fetch one delivery in detail. */
+ async get(destinationId: string, deliveryId: string): Promise<WebhookDeliveryRecord> {
+ const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}`, {
+ headers: this.headers,
+ });
+ if (!resp.ok) return fail(resp, "get delivery");
+ return resp.json();
+ }
+
+ /**
+ * Re-send any delivery (not only dead-lettered ones). Gives the delivery a fresh retry
+ * budget; the redelivery carries the **same** `webhook-id`, so a receiver that dedupes will
+ * treat it as the same message — redelivery is for cases where the original never landed.
+ */
+ async redeliver(destinationId: string, deliveryId: string): Promise<void> {
+ const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}/redeliver`, {
+ method: "POST",
+ headers: this.headers,
+ });
+ if (!resp.ok) return fail(resp, "redeliver");
+ }
+}
+
+/**
+ * Manage webhook destinations for sandbox lifecycle events. Server-side only — uses the org
+ * API key. To verify an incoming delivery, use `verifyWebhook` (package root).
+ *
+ * **Preview:** newly available; the surface may change.
+ */
+export class Webhooks {
+ readonly deliveries: WebhookDeliveries;
+ private readonly apiUrl: string;
+ private readonly apiKey: string;
+
+ constructor(opts: WebhooksOptions = {}) {
+ this.apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
+ this.apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
+ this.deliveries = new WebhookDeliveries(this.apiUrl, this.apiKey);
+ }
+
+ private headers(extra?: Record<string, string>): Record<string, string> {
+ const h: Record<string, string> = { "Content-Type": "application/json", ...extra };
+ if (this.apiKey) h["X-API-Key"] = this.apiKey;
+ return h;
+ }
+
+ /** Register a destination. The response includes `secret` once iff OpenComputer generated it. */
+ async create(params: CreateWebhookParams): Promise<CreateWebhookResult> {
+ const { idempotencyKey, ...body } = params;
+ const resp = await fetch(`${this.apiUrl}/webhooks`, {
+ method: "POST",
+ headers: this.headers(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined),
+ body: JSON.stringify(body),
+ });
+ if (!resp.ok) return fail(resp, "create webhook");
+ return resp.json();
+ }
+
+ async list(): Promise<WebhookDestination[]> {
+ const resp = await fetch(`${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() });
+ if (!resp.ok) return fail(resp, "get webhook");
+ return resp.json();
+ }
+
+ /** 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}`, {
+ method: "PATCH",
+ headers: this.headers(),
+ body: JSON.stringify(params),
+ });
+ if (!resp.ok) return fail(resp, "update webhook");
+ return resp.json();
+ }
+
+ /** Soft-delete a destination. Its delivery history is retained; pending deliveries are canceled. */
+ async delete(id: string): Promise<void> {
+ const resp = await fetch(`${this.apiUrl}/webhooks/${id}`, { method: "DELETE", headers: this.headers() });
+ if (!resp.ok) return fail(resp, "delete webhook");
+ }
+
+ /**
+ * Send a synthetic `sandbox.test` event to the destination and return the result inline.
+ * It bypasses the `eventTypes` filter, is not retried, and does not appear in delivery history.
+ */
+ async test(id: string): Promise<WebhookTestResult> {
+ const resp = await fetch(`${this.apiUrl}/webhooks/${id}/test`, { method: "POST", headers: this.headers() });
+ if (!resp.ok) return fail(resp, "test webhook");
+ return resp.json();
+ }
+}