---
title: "The SDK"
description: "The TypeScript client library, @doorman/inbox-sdk, and the event-driven agent runtime, @doorman/inbox-agent: one client mirroring the operation ids, page iterators, typed errors, the stream, webhook verification, and event handlers."
url: https://doorman.fyi/docs/sdk
markdown: https://doorman.fyi/docs/sdk.md
area: "SDKs and tools"
section: "TypeScript SDK"
---

# The SDK

The TypeScript client library, @doorman/inbox-sdk, and the event-driven agent runtime, @doorman/inbox-agent: one client mirroring the operation ids, page iterators, typed errors, the stream, webhook verification, and event handlers.

Source: https://doorman.fyi/docs/sdk

## Installing the packages

> Note: None of the packages is on a registry yet: registry installation requires the maintainer's initial npm publish. Until that release gate clears, they are built and packed from the repository, as below.

For Python 3.11 and later, use the generated [Python SDK](https://doorman.fyi/docs/python.md). Third-party integrations should use [Apps and OAuth](https://doorman.fyi/docs/oauth.md) instead of asking a person to share an unrestricted API key.

Install `@doorman/inbox-sdk` for the HTTP and WebSocket client, `@doorman/inbox-agent` when building an event-driven agent with handlers, and `@doorman/inbox-api` when you want the contract's zod schemas, `publicSurface()`, `operationTools()` or the bundled OpenAPI document directly.

Today: build and pack from a checkout of the repository:
```sh
pnpm install
pnpm --filter "@doorman/inbox-cli..." --filter "@doorman/inbox-agent..." run build
mkdir -p /tmp/doorman-tarballs
for name in inbox-api inbox-sdk inbox-agent inbox-mcp inbox-cli; do
  (cd "packages/$name" && pnpm pack --pack-destination /tmp/doorman-tarballs)
done
```

The packages depend on each other at versions no registry has, so a project outside the repository points every `@doorman` package at its tarball, at any depth, and then runs `pnpm install`:

package.json:
```json
{
  "type": "module",
  "dependencies": {
    "@doorman/inbox-sdk": "*",
    "@doorman/inbox-agent": "*"
  },
  "pnpm": {
    "overrides": {
      "@doorman/inbox-api": "file:/tmp/doorman-tarballs/doorman-inbox-api-0.0.0.tgz",
      "@doorman/inbox-sdk": "file:/tmp/doorman-tarballs/doorman-inbox-sdk-0.0.0.tgz",
      "@doorman/inbox-agent": "file:/tmp/doorman-tarballs/doorman-inbox-agent-0.0.0.tgz"
    }
  }
}
```

After the first release:
```sh
npm install @doorman/inbox-sdk @doorman/inbox-agent

# Optional: the contract schemas, publicSurface() and operationTools()
npm install @doorman/inbox-api
```

Every package uses the web platform only (`fetch`, `URL`, `WebSocket`, `WebCrypto`, streams), so the same code runs in Node 22 and later, Cloudflare Workers, Bun, Deno and the browser. `@doorman/inbox-api` exports `publicSurface()`, the 84 operation ids for agents and their builders, and the SDK's test suite verifies that `DoormanInbox` exposes a single typed method for every id in `publicSurface()`.

## The client

`@doorman/inbox-sdk` wraps the API for TypeScript and JavaScript. One client holds the key and the API origin; its resource groups mirror the operation ids of the [reference](https://doorman.fyi/docs/reference.md), so `inboxes.create` in the reference is `client.inboxes.create(...)` in code, and the shapes it takes and returns are the contract's own types, re-exported so nothing else needs importing.

TypeScript:
```ts
import { DoormanInbox } from "@doorman/inbox-sdk";

const client = new DoormanInbox({
  apiKey: process.env.DOORMAN_API_KEY ?? "",
  baseUrl: "https://api.doorman.fyi",
});

// Issue an address with its webhook and an inbox-scoped key in one call; both secrets come back once.
const inbox = await client.inboxes.create({
  mailboxName: "concierge",
  webhookUrl: "https://agent.example.com/hooks/doorman",
  key: { name: "Acme concierge" },
});

// Reply in a thread; the idempotency key makes a retry replay the original answer.
const sent = await client.inboxes.reply(inbox.id, "thr_01jc5a1b2c3d4e5f6g7h8j9k0m", { text: "Thanks, confirming for Thursday." }, { idempotencyKey: "order-2847-reply" });

// Poll the log forward from the last seq you handled, then keep latestSeq for next time.
const poll = await client.events.poll(1042, { inboxId: inbox.id });

// Walk every page of a list.
for await (const thread of client.inboxes.threads.iterate(inbox.id, { isRead: false })) console.log(thread.subject);
```

- `client.inboxes`: Issue, list, read, update and delete inboxes; `send` and `reply` from one; `findByExternalId` for [your own identifier](https://doorman.fyi/docs/inboxes.md#external-id). `keys`, `webhook`, `threads`, `messages`, `rules`, `services` and `verifications` sit beneath it, each taking the inbox id first.
- `client.services`: The account's [passport](https://doorman.fyi/docs/passport.md): `list`, `iterate`, `get`, `update` and `delete`, paired with `client.inboxes.services.create` to declare a sign-up and `client.inboxes.verifications.list` to wait for its code or link.
- `client.threads`, `client.messages`, `client.attachments`: A thread and its messages, its read state and the trash; a message, its raw copy as bytes and its HTML as text; an attachment's bytes and its extracted text.
- `client.events`: `list` pages back through the log, `poll(after)` reads it forward, `get` is one event with its deliveries. See [Events and polling](https://doorman.fyi/docs/events.md).
- `client.webhooks`, `client.deliveries`: Account endpoints, their secrets, tests and delivery logs; retrying a delivery by hand.
- `client.domains`: The account's custom domains, for an account key or a session: `list`, `create`, `get`, `verify` and `delete`. `connectSession` belongs to the console's DNS setup. App tokens are refused.
- `client.apiKeys`: Account-wide keys, which only a console session may manage.
- `client.apps`, `client.installs`, `client.oauthRequests`: Session-only app registration, installation revocation and explicit consent. Consent is not a background agent action.
- `client.organization`: `adopt({ accountId })` moves the signed-in person's personal account into the [organization](https://doorman.fyi/docs/organizations.md#adopt) their console session is working in. Session only.
- `client.me()`, `client.overview()`, `client.metrics()`, `client.health()`: The account and the caller, the counts and the checklist, the metrics over a range, and whether the API is up. `me()` also says whether the account is a person's or an organization's, and which organization.

The client takes the key as a string and refuses an empty one when it is constructed, so a sample that falls back to an empty string fails at start when the variable is missing, not at its first call. `baseUrl` is always given; the client never assumes a deployment.

A service that holds keys for several accounts can give the client `accountId` as well. The client then names that account in the [`x-doorman-account` header](https://doorman.fyi/docs/organizations.md#account) of every request, and the API answers `409 account_mismatch` and does nothing when the key belongs to another account. A value that is not an account id is refused when the client is constructed. The stream does not carry the header.

Paged resources have async iterators, including `inboxes.iterate`, `inboxes.threads.iterate`, `events.iterate` and `inboxes.rules.iterateRuns`. Bounded lists such as rules return their complete `data` array. `send` takes attachment contents as bytes or as base64, and its answer carries `replayed`, true when the API replayed an earlier send for the same `Idempotency-Key`. Path parameters are URL-encoded; an empty id throws before any request is made.

Pass an OAuth access token as `apiKey` for delegated REST calls. The standalone `InboxOAuth` helper provides discovery, `authorizationUrl`, dynamic registration and single-use token exchange without carrying API credentials or cookies. `createPkce` and `parseOAuthCallback` handle S256, state and issuer validation; see [the authorization flow](https://doorman.fyi/docs/oauth.md#authorize).

## Metadata and thread labels

Inboxes and threads carry a `metadata` map with up to 20 keys and 2048 serialized UTF-8 bytes. Values are strings, finite numbers, booleans or null; keys are bounded ASCII identifiers. A supplied map replaces the whole map, omission preserves it and `{}` clears it. Do not store secrets in metadata.

Threads also carry up to 20 unique, case-sensitive `labels`, each at most 64 ASCII identifier characters. A supplied list replaces the list and `[]` clears it. The `label` query matches one complete label, not a substring, and narrows both the page and its total.

TypeScript:
```ts
await client.inboxes.update(inbox.id, { metadata: { customer: "42", reviewed: false } });
await client.threads.update("thr_01jc5a1b2c3d4e5f6g7h8j9k0m", { metadata: { ticket: 42 }, labels: ["billing"] });
const billing = await client.inboxes.threads.list(inbox.id, { label: "billing" });
```

## Durable inbound rules

`client.inboxes.rules` manages the rules that act on mail as it arrives, without your code running: `list`, `create`, `get`, `update`, `delete`, `runs` and `iterateRuns`. An inbox holds at most 25 rules, each with up to 5 ordered actions. [Inbound rules](https://doorman.fyi/docs/rules.md) has what a rule matches, what it does, the order rules run in and the history of every run.

TypeScript:
```ts
const rule = await client.inboxes.rules.create(inbox.id, {
  name: "Invoice triage",
  when: { category: "personal", subjectContains: "invoice" },
  then: [{ type: "label", label: "billing" }],
});
```

## Errors

An answer of `400` or more is thrown as an `ApiError` with the `operation` that answered, the `status`, the `code` from the [error catalogue](https://doorman.fyi/docs/limits.md#errors), the `message`, `details` with the extra fields some codes carry (`scope`, `limit`, `resetsAt`, `providerCode`, `permission`), and `retryAfterSeconds` from the `Retry-After` header. An answer that is not an error the contract describes, such as a proxy's HTML page, has the code `unexpected_response`.

A console session whose role in an [organization](https://doorman.fyi/docs/organizations.md#errors) does not cover an operation gets `permission_denied`, and `details.permission` names the first permission that is missing. API keys and app tokens are never refused this way.

TypeScript:
```ts
import { isApiError } from "@doorman/inbox-sdk";

try {
  await client.inboxes.send(inbox.id, { to: "sam@example.com", subject: "Thursday", text: "Thursday works." });
} catch (error) {
  if (isApiError(error, "rate_limit_exceeded")) await wait(error.retryAfterSeconds ?? 60);
  else throw error;
}
```

## The stream

`client.stream(options)` opens [the WebSocket](https://doorman.fyi/docs/stream.md) with the key as `token`, subscribes as soon as the socket opens, sends a keepalive ping every 45 seconds, and reconnects after an unexpected close with `last_event_id` for bounded replay, with a backoff that doubles from one second to thirty. It does not reconnect after `4001` (the key, the inbox or the account is gone) or `4008` (the account's connection limit), or when `reconnect` is false. Events go to `onEvent` when given, otherwise to the async iterator; leaving the loop closes the stream.

TypeScript:
```ts
const stream = client.stream({ subscribe: { inboxIds: [inbox.id] } });
for await (const event of stream) {
  if (event.event === "message.received") console.log(event.message.subject);
  if (done) break; // closes the stream
}
```

- `subscribe(subscription)` and `unsubscribe(inboxIds)` resolve with the server's acknowledgement, and reject when the server refuses the frame.
- `lastEventId` is the id of the last event received, what a reconnect resumes with. `state` is `connecting`, `open` or `closed`.
- `onOpen`, `onClose` and `onError` observe the connection; `onClose` says whether a reconnect follows.
- Replay and the live feed can overlap at the boundary, so deduplicate on `event_id` as a webhook receiver does.
- Malformed or unknown event payloads report an error without advancing `lastEventId`. Narrow on `event` before reading type-specific fields.

## Verifying webhooks

`verifyWebhook(headers, body, secret)` checks a delivery's Standard Webhooks signature over the raw request body with the `whsec_` secret, the same check the samples in [Webhooks](https://doorman.fyi/docs/webhooks.md#verify) spell out, and returns the `WebhookEvent` union for all [event types](https://doorman.fyi/docs/events.md#types). The headers may be a `Headers` object or the plain record Node's `IncomingMessage` exposes; the body is the text or bytes exactly as they arrived. Timestamps more than 300 seconds from now are refused; `toleranceSeconds` changes that. The comparison runs inside Web Crypto, in constant time.

TypeScript:
```ts
import { verifyWebhook, WebhookVerificationError } from "@doorman/inbox-sdk";

try {
  const event = await verifyWebhook(request.headers, await request.text(), process.env.DOORMAN_WEBHOOK_SECRET ?? "");
  await handle(event); // narrow on event.event for the matching payload
} catch (error) {
  if (error instanceof WebhookVerificationError) return new Response(error.reason, { status: 400 });
  throw error;
}
```

`verifyWebhookSignature` is the lower-level form: the same check, returning the body as text without parsing it, for a receiver that wants to parse the payload itself.

## Building an event-driven agent

`@doorman/inbox-agent` builds on this client with typed handlers for every event type, over a signed webhook (`agent.fetch`), the stream (`agent.listen`) or a scheduled poll (`agent.poll`). `createInboxAgent` takes the client and the handlers. A `message.received` handler is given helpers that are safe by default: `ctx.reply()` refuses mail that should not be answered automatically and uses the event's id as its idempotency key, and `ctx.fencedBody()` returns the sender's words fenced as data for a model.

[The agent runtime](https://doorman.fyi/docs/agent.md) is its guide, with every export of the package. [The front desk agent](https://doorman.fyi/docs/sample.md#desk) is a complete program built on it, with its source.

> Note: For giving an existing agent direct tool access without writing handler code, see [MCP server](https://doorman.fyi/docs/mcp.md) and [The CLI](https://doorman.fyi/docs/cli.md).

## Every method

[The TypeScript SDK reference](https://doorman.fyi/docs/sdk/reference.md) lists every method of the client with its signature and the operation it sends, on pages named as the API reference names its own. [The client, errors, stream and helpers](https://doorman.fyi/docs/sdk/reference/client.md) has everything else the package exports. Both are read from the package's source when this documentation is built.

Three topics have guides of their own, for every surface at once: [Pagination](https://doorman.fyi/docs/pagination.md), [Idempotency](https://doorman.fyi/docs/idempotency.md) and [Errors](https://doorman.fyi/docs/errors.md).
