@flowmails/flowmails-sdk 0.2.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -0
- package/README.md +89 -8
- package/dist/index.cjs +275 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +572 -52
- package/dist/index.d.ts +572 -52
- package/dist/index.js +274 -12
- package/dist/index.js.map +1 -1
- package/openapi.json +4019 -0
- package/package.json +4 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";;;AASO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA,EAE/B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,MAAA,EAAgB;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,SAAA,GAAY,MAAA,IAAU,GAAA,IAAO,MAAA,KAAW,OAAO,MAAA,KAAW,GAAA;AAAA,EACjE;AACF;AAKO,IAAM,mBAAA,GAAN,cAAkC,cAAA,CAAe;AAAA,EACtD,WAAA,CAAY,IAAA,GAAO,iBAAA,EAAmB,MAAA,GAAS,GAAA,EAAK;AAClD,IAAA,KAAA,CAAM,IAAA,EAAM,CAAA,uBAAA,EAA0B,IAAI,CAAA,CAAA,EAAI,MAAM,CAAA;AACpD,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAMO,IAAM,eAAA,GAAN,cAA8B,cAAA,CAAe;AAAA,EACzC,MAAA;AAAA,EACT,WAAA,CAAY,IAAA,EAA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ACzC;AAAA,EACF;AACA,EAAA,OAAO,IAAI,QAAA,EAAS;AACtB;AAEA,SAAS,cAAc,KAAA,EAA2B;AAGhD,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,GAAA,IAAO,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EACrC;AACA,EAAA,OAAO,KAAK,GAAG,CAAA;AACjB;AAEA,SAAS,UAAU,OAAA,EAAyB;AAE1C,EAAA,MAAM,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,GAAM,CAAA,IAAK,SAAS,GAAK,CAAA;AAC/C,EAAA,OAAO,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,IAAI,CAAA;AAC/C;AAEA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"index.cjs","sourcesContent":["/**\n * Public error hierarchy. Mirrors the SDK backend's JSON contract\n * documented in `apps/sdk-backend/src/utils/errors.js`.\n *\n * The base `FlowmailsError` carries the raw `code` string (e.g.\n * `\"validation_failed\"`) plus the HTTP status. Subclasses add\n * richer contextual fields (validation `detail`, auth `reason`)\n * that the SDK backend actually emits.\n */\nexport class FlowmailsError extends Error {\n /** Machine-readable error slug, sent back from the SDK backend. */\n readonly code: string;\n /** HTTP status from the SDK backend response. */\n readonly status: number;\n /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */\n readonly retryable: boolean;\n\n constructor(code: string, message: string, status: number) {\n super(message);\n this.name = \"FlowmailsError\";\n this.code = code;\n this.status = status;\n this.retryable = status >= 500 || status === 408 || status === 429;\n }\n}\n\n/**\n * 401 — API key missing / invalid / revoked. NOT retryable.\n */\nexport class AuthenticationError extends FlowmailsError {\n constructor(code = \"api_key_invalid\", status = 401) {\n super(code, `Authentication failed: ${code}`, status);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * 400 / 422 — request was syntactically valid but rejected by the\n * backend. NOT retryable without code changes.\n */\nexport class ValidationError extends FlowmailsError {\n readonly detail?: string;\n constructor(code: string, detail: string | undefined, status = 400) {\n super(code, `Validation failed: ${code}${detail ? ` — ${detail}` : \"\"}`, status);\n this.name = \"ValidationError\";\n this.detail = detail;\n }\n}\n\n/**\n * 408 / 429 — request was rate-limited or timed out. Retryable.\n *\n * A 429 from Flowmails is either a **quota refusal**\n * (`rate_limit_exceeded`) or a request that is **already running**\n * (`idempotency_key_in_progress`). The two need different handling,\n * so the quota facts travel on the error:\n *\n * - `limit` — the limit that was hit.\n * - `remaining` — how many sends are left in the window (`0` when the\n * quota is exhausted).\n * - `resetAt` — ISO-8601 instant the window rolls over.\n */\nexport class RateLimitError extends FlowmailsError {\n /** The limit that was hit, when the server named one. */\n readonly limit?: number;\n /** The sends left in the window, when the server named one. */\n readonly remaining?: number;\n /** ISO-8601 instant the window rolls over, when the server named one. */\n readonly resetAt?: string;\n\n constructor(\n code = \"rate_limited\",\n status = 429,\n facts?: { limit?: number; remaining?: number; resetAt?: string },\n ) {\n super(code, `Rate limited: ${code}`, status);\n this.name = \"RateLimitError\";\n this.limit = facts?.limit;\n this.remaining = facts?.remaining;\n this.resetAt = facts?.resetAt;\n }\n}\n\n/**\n * 502 / 504 — the SDK backend couldn't reach the upstream\n * receive-worker, or the upstream returned a malformed response.\n * Retryable.\n */\nexport class UpstreamError extends FlowmailsError {\n readonly upstreamMessage?: string;\n constructor(code: string, upstreamMessage: string | undefined, status = 502) {\n super(code, `Upstream failure: ${code}`, status);\n this.name = \"UpstreamError\";\n this.upstreamMessage = upstreamMessage;\n }\n}\n","/**\n * Public SDK facade. The whole shape of the package is:\n *\n * new Flowmails({ apiKey: \"fm_…\" }).send({...})\n *\n * No top-level helper functions, no globals, no implicit init.\n * Construction takes an `apiKey` and an optional `baseURL`\n * (mainly for testing / private-region deployments).\n *\n * `send` is the only public method in v0.1 — there is exactly\n * one outbound endpoint (`POST /api/v1/messages`). The\n * `request<T>` helper below it carries the retry / backoff /\n * error-mapping machinery and is private; future public methods\n * (e.g. `webhooks.send`) will call `request<T>` internally so\n * the choke point stays in one place.\n *\n * The payload DTOs (`SendOptions` / `SendResult` / `SendAttachment`)\n * mirror common email-clients (Gmail API, Resend, Postmark), NOT\n * the receive-worker's wire format. `send` does the rename to\n * wire on the way out (html → content, Uint8Array → base64).\n */\nimport {\n AuthenticationError,\n FlowmailsError,\n RateLimitError,\n UpstreamError,\n ValidationError,\n} from \"./errors.js\";\n\n// ---------- Public payload types ----------\n\n/**\n * A single file attached to the outbound message.\n *\n * `filename` and `content` are required. `mimeType` defaults to\n * `application/octet-stream` if the SDK backend cannot infer it\n * from the filename (the backend forwards `mimeType` to the\n * receive-worker which sets it on the SMTP part).\n */\nexport interface SendAttachment {\n filename: string;\n content: string | Uint8Array;\n mimeType?: string;\n}\n\n/**\n * One event in the durable log — what arrived, where, and from whom.\n *\n * The event carries **routing facts plus the subject line**, never a\n * body: that is the platform's core promise (`docs/agent-platform.md`\n * §4.2), and the body is opt-in through {@link MessageDetail}. The\n * `messageId` is the SMTP `Message-ID` — the key every content read\n * takes.\n */\nexport interface AgentEvent {\n /** The cursor value. Treat it as opaque; pass it back as `after`. */\n id: string;\n /** The SMTP `Message-ID`. Pass this to `messages.get()`. */\n messageId: string;\n /** `inbound.received` — the only event type the platform emits. */\n event: string;\n /** The mailbox the message landed in, e.g. `billing@yourapp.com`. */\n recipient: string;\n /** The sender, when the receive worker could determine it. */\n sender: string | null;\n /** The subject line — the one content field on the event. */\n subject: string | null;\n /** ISO-8601 timestamp of when the platform recorded the event. */\n createdAt: string;\n}\n\n/** Options for {@link AgentEvents.list}. */\nexport interface ListEventsOptions {\n /**\n * Cursor: return events **after** this event id. Pass the\n * `nextCursor` of the previous page. Treat it as opaque — it is an\n * event id, not a timestamp, because two events can land in the\n * same millisecond and a cursor that can skip a row loses mail.\n */\n after?: string;\n /** Page size. The platform caps it; ask for what you will drain. */\n limit?: number;\n /** Exact recipient address filter. */\n recipient?: string;\n /** Exact sender address filter. */\n sender?: string;\n /** Case-insensitive **substring** of the subject. */\n subject?: string;\n}\n\n/** One page of the event log. */\nexport interface ListEventsResult {\n events: AgentEvent[];\n /**\n * The cursor to pass as `after` on the next call. Present whenever\n * the page was not empty; absent when the log is drained.\n */\n nextCursor?: string;\n}\n\n/** Options for {@link AgentWaits.create}. */\nexport interface CreateWaitOptions {\n /** The mailbox to watch, e.g. `billing@yourapp.com`. */\n address: string;\n /** Only resolve for mail from this sender. */\n sender?: string;\n /** Only resolve for a subject containing this substring. */\n subject?: string;\n /**\n * How long to keep the wait open, in milliseconds. Defaults to 15\n * minutes; the platform caps it at 24 hours.\n */\n timeoutMs?: number;\n}\n\n/** A durable wait, as the platform reports it. */\nexport interface WaitStatus {\n waitId: string;\n /** `pending` → `resolved` (a message landed) or `expired`. */\n status: \"pending\" | \"resolved\" | \"expired\";\n address: string;\n sender: string | null;\n subject: string | null;\n /** The SMTP `Message-ID` that resolved the wait, when it resolved. */\n resolvedMessageId: string | null;\n /** ISO-8601 deadline. A wait past it reads as `expired`. */\n expiresAt: string | number;\n}\n\n/**\n * A newly-opened wait.\n *\n * Returned **immediately** — the platform writes a row and answers,\n * it never suspends the request. A verification mail arrives minutes\n * to hours later and an edge request dies long before that, so the\n * wait is durable state the agent polls with {@link AgentWaits.get}.\n */\nexport interface CreateWaitResult extends WaitStatus {\n /** A hint for the poll loop: check again in a few seconds. */\n pollAfterMs: number;\n}\n\n/** The full content of one message. Fetched, never pushed. */\nexport interface MessageDetail {\n /** The worker's numeric row id. */\n id: number | string;\n /** The SMTP `Message-ID` the event carried. */\n messageId: string;\n from: string;\n fromName: string | null;\n to: string;\n toName: string | null;\n subject: string | null;\n /** Plain-text body. Ideal for regexing a verification code out. */\n text: string | null;\n /** Rendered HTML body, when the message had one. */\n html: string | null;\n receivedAt: string | null;\n attachments: Array<{\n filename: string | null;\n mimeType: string | null;\n size: number | null;\n url: string | null;\n }>;\n}\n\n/** One address (mailbox) the platform accepts mail for. */\nexport interface AgentAddress {\n address: string;\n localPart: string;\n}\n\n/**\n * One domain on the account.\n *\n * `routingMode` decides whether a new address needs anything to\n * happen: on `catchall` every local part already delivers, on\n * `rules` only the listed ones do.\n */\nexport interface AgentDomain {\n id: string;\n name: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n /** False when the per-account receive worker is not deployed yet. */\n ready: boolean;\n}\n\n/** Result of {@link AgentAddresses.create}. */\nexport interface CreateAddressResult {\n address: string;\n localPart: string;\n domainId: string;\n domain: string;\n /** False when the address already existed — the call is idempotent. */\n created: boolean;\n routingMode?: \"catchall\" | \"rules\";\n}\n\n/**\n * One message of a conversation chain.\n *\n * It extends {@link MessageDetail} because the thread route uses the\n * **same projection** the single-message read uses — the same\n * fields, the same shape. The only addition is the truncation flag.\n */\nexport interface ThreadMessage extends MessageDetail {\n /**\n * `1` when the receive worker shortened the body.\n *\n * The worker returns a bounded window of the chain and truncates\n * the bodies of the non-current members — a long thread must not\n * become a way to pull a whole mailbox. `total` / `hasMoreOlder` /\n * `hasMoreNewer` say whether the chain extends past the window.\n */\n bodyTruncated: 0 | 1;\n}\n\n/**\n * A conversation chain — `docs/agent-platform.md` §10.8 AP-27.\n */\nexport interface ThreadDetail {\n /** The conversation **root's** SMTP `Message-ID`. */\n threadId: string;\n /** The platform domain id the chain was read from. */\n domainId: string;\n /** The domain name the chain was read from. */\n domain: string;\n /** The full chain length — not just the returned window. */\n total: number;\n /** The chain extends past the window, older side. */\n hasMoreOlder: boolean;\n /** The chain extends past the window, newer side. */\n hasMoreNewer: boolean;\n /** The chain, oldest first. */\n messages: ThreadMessage[];\n}\n\n/**\n * One search hit.\n *\n * Addressing, the subject and a short preview — never the body. The\n * body is fetched per message, through {@link AgentMessages.get},\n * when the agent decides a message matters.\n */\nexport interface SearchMessageHit {\n /** The worker's row id. Accepted by {@link AgentMessages.get}. */\n id: number | null;\n /** The SMTP `Message-ID`, when the sender supplied one. */\n messageId: string;\n from: string | null;\n fromName: string | null;\n to: string | null;\n toName: string | null;\n subject: string | null;\n receivedAt: string | null;\n /** A short plain-text preview of the body. */\n preview: string | null;\n}\n\n/**\n * The arguments of a mailbox search.\n *\n * `domainId` is required on the call (not in this shape) because the\n * receive worker's search path is domain-scoped: one domain, one\n * round-trip, one stable ordering. `GET /api/agent/domains` is the\n * call that answers it.\n */\nexport interface SearchMessagesOptions {\n /** The query. At least two characters — the platform refuses less. */\n q: string;\n /** The page size. */\n limit?: number;\n /** Which field to match. Defaults to `body` (subject + from + to + text). */\n field?: \"subject\" | \"from\" | \"to\" | \"body\";\n /** Which mailbox direction. Defaults to `receive`. */\n type?: \"receive\" | \"send\";\n}\n\n/** The result of a mailbox search. */\nexport interface SearchMessagesResult {\n messages: SearchMessageHit[];\n /** How many rows match the filter, ignoring `limit`. */\n total: number;\n domainId: string;\n}\n\n/**\n * Composed send payload.\n *\n * `to` accepts a single address or an array. `subject` is required.\n * At least one of `text` / `html` must be a non-empty string.\n */\nexport interface SendOptions {\n /**\n * Sender address. MUST land on the domain the API key is bound\n * to (the SDK backend enforces this with a 422 on mismatch).\n */\n from: string;\n /** Display name for the sender; the email-worker falls back to the\n * local-part capitalised. */\n fromName?: string;\n /** One recipient or an array. */\n to: string | string[];\n /** Optional reply-to override. */\n replyTo?: string;\n /**\n * Reply in thread: the SMTP `Message-ID` (or numeric id) of the\n * message being answered.\n *\n * When set, the SDK backend resolves the parent row and derives\n * the `In-Reply-To` / `References` headers and the thread anchor,\n * so the recipient's mail client threads your message with the\n * original conversation — and the dashboard shows it in the same\n * thread. The caller supplies the **parent**, never the headers:\n * deriving `References` by hand is how threads fork.\n *\n * A parent with no `Message-ID` header is rejected: there is\n * nothing to point `In-Reply-To` at.\n */\n replyToMessageId?: string;\n /** Subject line — required, non-empty. */\n subject: string;\n /** Plain-text body. Required iff `html` is also missing. */\n text?: string;\n /** HTML body. Required iff `text` is also missing. Inline\n * `cid:` images and remote `data:` urls are auto-extracted by\n * the email-worker into R2 embeds. */\n html?: string;\n /** Attachments. */\n attachments?: SendAttachment[];\n /**\n * Idempotency key — the same key under the same account and the\n * same request returns the **original** result and does not send\n * twice.\n *\n * Give every send a key you can rebuild after a timeout (a UUID\n * per logical mail, not per attempt) and a retry becomes free: the\n * backend replays the first answer instead of delivering a second\n * message.\n *\n * The key is scoped to the **account**, not globally — two accounts\n * may use the same string. Reusing one key for a *different* payload\n * is a client bug and is refused with `idempotency_key_conflict`\n * (409) rather than answered with the first result.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Result of a successful send.\n *\n * `id` is the platform's row id; `messageId` is the SMTP `Message-ID`\n * the relay assigned, which is the key every read path takes — pass\n * it to {@link AgentMessages.get} to read a reply, or to\n * {@link AgentMessages.status} to poll delivery.\n *\n * ## A send that failed\n *\n * The backend answers `201` for a send the relay **refused** — the\n * message row exists, the mail does not. That used to be invisible:\n * the answer was `{ id, status: \"failed\", messageId: \"\" }` with\n * nothing else, so an agent could not tell a refused send from a\n * lost one (the 2026-10-31 audit, P0-1).\n *\n * Two fields now say what happened:\n *\n * - `error` — the typed slug (`\"send_failed\"`), or `null` when the\n * send did not fail. **It is never `null` on a failed send**, so\n * \"failed with no reason\" is not a state the wire can be in.\n * - `sendFeedback` — the relay's own reason, when it gave one\n * (`null` when it did not).\n *\n * Both are optional because the SDK also talks to older backends that\n * did not send them; on those, `status` is the only signal.\n */\nexport interface SendResult {\n /** Numeric email row id (stringified for JSON safety). */\n id: string;\n /** The row's lifecycle state at send time. */\n status: string;\n /**\n * The SMTP `Message-ID` the relay assigned (the receive worker's\n * `resendEmailId`). Empty when the send failed before the relay\n * accepted it.\n */\n messageId?: string;\n /**\n * The relay's reason for the failure, when the relay gave one —\n * `null` when it did not, and `null` on a send that succeeded.\n */\n sendFeedback?: string | null;\n /**\n * The typed failure slug (`\"send_failed\"`), or `null` when the\n * send did not fail.\n *\n * A failed send always carries one: `status: \"failed\"` with\n * `error: null` is not a state the backend can answer.\n */\n error?: string | null;\n}\n\n/**\n * The outbound half of a domain — what the platform last recorded\n * about whether it can send.\n *\n * Read from `fm.me().sending`, the connection check's answer to\n * \"may this key's domain send?\". It is the same verdict the\n * dashboard shows, read from the same document, so the two cannot\n * disagree.\n */\nexport interface AccountSendingState {\n /**\n * True only when the domain can send right now.\n *\n * Read it **with** `state`: `canSend: false` with\n * `state: \"unknown\"` means \"we have not looked\", while\n * `canSend: false` with `state: \"not_onboarded\"` means the domain\n * is not on Cloudflare Email Sending and no send will succeed.\n */\n canSend: boolean;\n /**\n * The outbound verdict, in the platform's vocabulary: `ready`,\n * `not_onboarded`, `disabled`, `unconfigured`, `unlocked`,\n * `misconfigured`, `no_credential`, `unknown` or `error`.\n */\n state: string;\n /** The detail the platform recorded with the verdict. */\n detail: string | null;\n /**\n * When the sending half was last probed, in epoch milliseconds —\n * `null` when it never was. The platform probes on demand, so an\n * old stamp means the answer may be out of date.\n */\n checkedAt: number | null;\n}\n\n/**\n * What the credential behind the client is allowed to do, and which\n * account it belongs to.\n *\n * This is the **connection check** (`docs/agent-platform.md` §10.8\n * AP-05): it answers \"is my key live, which account is it, which\n * domain may it send from, and what may it do?\" without sending a\n * single message — the only two ways to get that answer before it\n * existed were to send real mail or to fail.\n */\nexport interface AccountInfo {\n /** The account the credential belongs to. */\n userId: string;\n /**\n * The domain the credential is bound to — the constraint on\n * sending. `null` when the credential carries no binding.\n */\n domain: string | null;\n /** The per-account receive worker the credential sends through. */\n workerHost: string | null;\n /**\n * Which credential type answered: `\"sdk_key\"` (the dashboard's\n * domain-bound API key) or `\"agent_credential\"` (a scoped\n * credential issued for one set of capabilities).\n */\n credentialType: string;\n /** The scopes this credential holds. */\n scopes: string[];\n /**\n * The outbound half — **may this domain actually send?**\n *\n * `null` when the answer is not knowable: the credential carries no\n * bound domain, the platform could not be read, or the domain has\n * no row. `null` means \"we do not know\", which is different from\n * \"this domain cannot send\" — read it with `state` before acting\n * on it.\n */\n sending: AccountSendingState | null;\n}\n\n/**\n * The account's receive worker, and the version of it.\n *\n * The receive worker lives in the customer's own Cloudflare account\n * and does the actual receiving and sending; it is versioned, and an\n * older one silently does less than the platform expects (no route\n * tables before `1.4.0`, no Message-ID lookup before `1.5.1`, no event\n * reporting before `1.6.0`). An agent that cannot see the version\n * cannot tell why its events are empty.\n */\nexport interface WorkerVersionInfo {\n /**\n * The version the platform last deployed for this account — `null`\n * when it has no record (a worker deployed outside the platform\n * leaves it stale, so read {@link lastDeployAt} with it).\n */\n version: string | null;\n /** The worker host this account's mail flows through. */\n workerHost: string | null;\n /** Whether the worker finished its own bootstrap (schema migrations). */\n bootstrapped: boolean;\n /** When the platform last deployed this worker (ISO-8601), or `null`. */\n lastDeployAt: string | null;\n /** The last deploy error, when one happened, or `null`. */\n lastDeployError: string | null;\n}\n\n// ---------- Options & class ----------\n\nexport interface FlowmailsOptions {\n /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */\n apiKey: string;\n /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */\n baseURL?: string;\n /**\n * The **platform** origin, used by the listen half of the surface\n * (`fm.events`, `fm.messages`, `fm.waits`, `fm.addresses`). The\n * send path goes to {@link baseURL} (the SDK backend); the event\n * log, the durable wait and the message read live on the platform\n * worker, which is a different deployment.\n *\n * Defaults to `https://flowmails.net`. Set it for a self-hosted or\n * staging deployment — the same API key authenticates both.\n */\n platformURL?: string;\n /** Inject a `fetch` implementation (Workers environments, test harnesses). */\n fetch?: typeof globalThis.fetch;\n /**\n * Number of automatic retries on transient failures (5xx, 408, and\n * a 429 that asks for another attempt). Defaults to 2. Set to 0 to\n * disable. The retry budget is bounded; doesn't apply to 4xx\n * validation / auth failures.\n *\n * A **quota** refusal (429 `rate_limit_exceeded`) is deliberately\n * NOT retried: the window is an hour, a retry inside it cannot\n * succeed, and it would only burn another slot. The error carries\n * `limit` / `remaining` / `resetAt` so the caller can wait for the\n * window instead of guessing.\n */\n maxRetries?: number;\n /**\n * Optional request-id header for cross-stack tracing. If set,\n * every outbound request carries `X-Flowmails-Request-Id`, and\n * the SDK backend echoes it back on the response so callers can\n * correlate platform logs with their own.\n */\n requestId?: string;\n}\n\nexport class Flowmails {\n private readonly apiKey: string;\n private readonly baseURL: string;\n private readonly platformURL: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly maxRetries: number;\n private readonly requestId?: string;\n\n constructor(opts: FlowmailsOptions) {\n if (!opts.apiKey) {\n throw new Error(\"Flowmails: apiKey is required\");\n }\n this.apiKey = opts.apiKey;\n this.baseURL = (opts.baseURL ?? \"https://sdk.flowmails.net\").replace(\n /\\/+$/,\n \"\",\n );\n // The listen half of the surface lives on the platform worker,\n // not the SDK backend: the event log, the durable wait and the\n // message read are platform D1 state, and the platform is where\n // the agent's key already authenticates. One key, two origins —\n // sending is the SDK backend's job, reading is the platform's.\n this.platformURL = (opts.platformURL ?? \"https://flowmails.net\").replace(\n /\\/+$/,\n \"\",\n );\n // `globalThis.fetch` MUST be bound before it is stored on an instance.\n // workerd implements `fetch` as a WebIDL operation whose `this` must be\n // the global object, so calling `this.fetchFn(url, …)` passes the\n // `Flowmails` instance instead and workerd throws\n // `TypeError: Illegal invocation`. That rejection lands in the catch\n // below and is reported as `UpstreamError(\"network_error\", …, 0)` — a\n // \"network\" failure that never touched the network, which is exactly how\n // it presented: auth mail silently never sending.\n //\n // Node's undici tolerates the detached call, so this is invisible in\n // `node --test` and in any browser; it only reproduces in the Workers\n // runtime. An *injected* `opts.fetch` is left unbound — it is the\n // caller's own function, not a WebIDL operation.\n this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);\n this.maxRetries = opts.maxRetries ?? 2;\n this.requestId = opts.requestId;\n }\n\n /**\n * Send mail through the SDK backend.\n *\n * Pass `replyToMessageId` to answer a message in thread — the SDK\n * backend resolves the parent and derives the `In-Reply-To` /\n * `References` headers and the thread anchor, so the recipient's\n * client threads it with the original conversation.\n *\n * Returns `{ id, status, messageId }` on success; throws one of\n * `AuthenticationError` / `ValidationError` / `RateLimitError` /\n * `UpstreamError` on failure (all subclasses of `FlowmailsError`).\n *\n * **A send the relay refused is not a throw.** The backend answers\n * `201` with `status: \"failed\"`, and the result carries the\n * reason: `error` is the typed slug and `sendFeedback` is the\n * relay's own words. Check `result.error` before treating a `201`\n * as \"sent\".\n */\n async send(opts: SendOptions): Promise<SendResult> {\n // The wire-shape renames (html → content, Uint8Array → base64)\n // happen here: the SDK's DTO mirrors common email clients, the\n // wire mirrors the receive worker.\n const body = {\n from: opts.from,\n fromName: opts.fromName,\n to: Array.isArray(opts.to) ? opts.to : [opts.to],\n replyTo: opts.replyTo,\n // The SDK backend resolves this to the three `threading`\n // fields. The caller names the **parent**, never the headers —\n // hand-deriving `References` is how threads fork.\n replyToMessageId: opts.replyToMessageId,\n subject: opts.subject,\n text: opts.text,\n html: opts.html,\n attachments: opts.attachments?.map((a) => ({\n filename: a.filename,\n content:\n a.content instanceof Uint8Array\n ? bytesToBase64(a.content)\n : a.content,\n mimeType: a.mimeType,\n })),\n // The idempotency key travels under the same name on the wire.\n // It is deliberately **not** renamed: the backend's body is\n // camelCase already, and a rename here would be one more place\n // for the two sides to disagree.\n idempotencyKey: opts.idempotencyKey,\n };\n\n return this.request<SendResult>(this.baseURL, \"POST\", \"/api/v1/messages\", {\n body,\n });\n }\n\n /**\n * The connection check — who the credential is.\n *\n * `flowmails test` (the CLI's documented first command) and every\n * \"is my setup right?\" question end here. It verifies the key,\n * names the account, names the bound domain and reports the\n * scopes — and it sends nothing, so running it can never mail\n * somebody by accident.\n *\n * It also answers the question the 2026-10-31 audit (P0-1) found\n * missing: **may this domain actually send?** — `info.sending`\n * carries the platform's own verdict, read from the same document\n * the dashboard reads.\n *\n * ```ts\n * const me = await fm.me();\n * if (me.sending && !me.sending.canSend) {\n * // me.sending.state says why: \"not_onboarded\", \"unknown\", …\n * }\n * ```\n *\n * @throws {AuthenticationError} when the key is missing, malformed\n * or revoked.\n */\n async me(): Promise<AccountInfo> {\n return this.request<AccountInfo>(this.baseURL, \"GET\", \"/api/v1/me\");\n }\n\n /**\n * The account's receive worker, and the version of it.\n *\n * The receive worker does the actual receiving and sending, and it\n * is versioned: `1.4.0` brought the route tables, `1.5.1` the\n * Message-ID lookup, `1.6.0` the event reporting that fills the\n * log this SDK reads. An agent whose worker is older than the\n * platform expects sees an empty event log and has no way to tell\n * \"no mail yet\" from \"my worker cannot report\".\n *\n * ```ts\n * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });\n * const worker = await fm.workerVersion();\n * if (!worker.version || worker.version < \"1.6.0\") { … }\n * ```\n *\n * @throws {AuthenticationError} when the key is missing, malformed\n * or revoked.\n */\n async workerVersion(): Promise<WorkerVersionInfo> {\n return this.request<WorkerVersionInfo>(this.baseURL, \"GET\", \"/api/v1/worker-version\");\n }\n\n /**\n * The event log — the listen half of the surface, read with a\n * cursor.\n *\n * ```ts\n * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });\n * let after: string | undefined;\n * for (;;) {\n * const page = await fm.events.list({ after, subject: \"invoice\" });\n * for (const event of page.events) { … }\n * after = page.nextCursor ?? after;\n * }\n * ```\n */\n readonly events: AgentEvents = {\n list: async (opts: ListEventsOptions = {}) => {\n const query: Record<string, string | number | undefined> = {\n after: opts.after,\n limit: opts.limit,\n recipient: opts.recipient,\n sender: opts.sender,\n subject: opts.subject,\n };\n return this.request<ListEventsResult>(\n this.platformURL,\n \"GET\",\n \"/api/agent/events\",\n { query },\n );\n },\n };\n\n /**\n * Read one message by its SMTP `Message-ID` — the id the event\n * carried.\n *\n * The event log deliberately hands over routing facts and a\n * subject and never a body (§4.2), so the content is an explicit\n * ask. This is that ask.\n */\n readonly messages: AgentMessages = {\n get: async (messageId: string, opts: { domainId?: string } = {}) => {\n if (!messageId) {\n throw new ValidationError(\"message_id_required\", \"messageId is required\");\n }\n return this.request<MessageDetail>(\n this.platformURL,\n \"GET\",\n `/api/agent/messages/${encodeURIComponent(messageId)}`,\n { query: { domainId: opts.domainId } },\n );\n },\n\n /**\n * Poll a **sent** message's delivery state.\n *\n * `id` is the value {@link send} returned as `id` (or the SMTP\n * `Message-ID`). Returns the worker's lifecycle state so an agent\n * can tell `sent` from `failed` (the two the worker writes)\n * instead of assuming success.\n */\n status: async (id: string) => {\n if (!id) {\n throw new ValidationError(\"message_id_required\", \"id is required\");\n }\n return this.request<SendStatus>(\n this.baseURL,\n \"GET\",\n `/api/v1/messages/${encodeURIComponent(id)}`,\n );\n },\n\n /**\n * Look back through the mailbox.\n *\n * The event log is the primary listen path; this is the history\n * path. A hit carries addressing, the subject and a preview — the\n * body is a separate, explicit ask.\n */\n search: async (domainId: string, opts: SearchMessagesOptions) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n if (!opts?.q || opts.q.trim().length < 2) {\n throw new ValidationError(\n \"query_too_short\",\n \"q must be at least 2 characters\",\n );\n }\n return this.request<SearchMessagesResult>(\n this.platformURL,\n \"GET\",\n \"/api/agent/emails/search\",\n {\n query: {\n q: opts.q,\n domainId,\n limit: opts.limit,\n field: opts.field,\n type: opts.type,\n },\n },\n );\n },\n };\n\n /**\n * The conversation a message belongs to.\n *\n * The core listen/reply loop can store the message ids itself;\n * this is for the agent that wants the platform to reconstruct the\n * chain. The chain is read from the **conversation root's** SMTP\n * `Message-ID`, which is exactly what `email.threadId` holds.\n */\n readonly threads: AgentThreads = {\n get: async (threadId: string, opts: { domainId?: string } = {}) => {\n if (!threadId) {\n throw new ValidationError(\"thread_id_required\", \"threadId is required\");\n }\n return this.request<ThreadDetail>(\n this.platformURL,\n \"GET\",\n `/api/agent/threads/${encodeURIComponent(threadId)}`,\n { query: { domainId: opts.domainId } },\n );\n },\n };\n\n /**\n * The durable wait — the one thing an agent cannot build for\n * itself.\n *\n * A suspended HTTP request dies on the edge long before a\n * verification mail arrives (minutes to hours later), so the wait\n * is a row on the platform and the agent polls it. `create()`\n * answers **immediately**; it does not block.\n */\n readonly waits: AgentWaits = {\n create: async (opts: CreateWaitOptions) => {\n return this.request<CreateWaitResult>(\n this.platformURL,\n \"POST\",\n \"/api/agent/waits\",\n { body: opts },\n );\n },\n get: async (waitId: string) => {\n if (!waitId) {\n throw new ValidationError(\"wait_id_required\", \"waitId is required\");\n }\n return this.request<WaitStatus>(\n this.platformURL,\n \"GET\",\n `/api/agent/waits/${encodeURIComponent(waitId)}`,\n );\n },\n };\n\n /**\n * The addresses (mailboxes) the key's account owns, and the one\n * narrow write the agent surface has: create a single one.\n */\n readonly addresses: AgentAddresses = {\n listDomains: async () => {\n const result = await this.request<{ domains: AgentDomain[] }>(\n this.platformURL,\n \"GET\",\n \"/api/agent/domains\",\n );\n return result.domains;\n },\n list: async (domainId: string) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n const result = await this.request<{\n domainId: string;\n domain: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n addresses: string[];\n acceptsAnyLocalPart: boolean;\n }>(\n this.platformURL,\n \"GET\",\n `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,\n );\n return result;\n },\n create: async (domainId: string, localPart: string) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n return this.request<CreateAddressResult>(\n this.platformURL,\n \"POST\",\n `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,\n { body: { localPart } },\n );\n },\n };\n\n /**\n * Private: the one request path, with retry + backoff + error\n * mapping shared by every public method.\n *\n * `origin` is explicit because the surface spans two deployments:\n * the SDK backend (`baseURL`) for sending, the platform\n * (`platformURL`) for reading and waiting. `method` is explicit\n * because the listen endpoints are GETs — the v0.1 helper was\n * POST-only, which is why reading used to mean hand-rolling HTTP.\n */\n private async request<T>(\n origin: string,\n method: \"GET\" | \"POST\",\n path: string,\n opts: {\n body?: unknown;\n query?: Record<string, string | number | undefined>;\n } = {},\n ): Promise<T> {\n const url = buildUrl(origin, path, opts.query);\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n };\n // A GET carries no body, and sending `Content-Type: application/json`\n // with one would be a lie some proxies act on.\n if (method === \"POST\") headers[\"Content-Type\"] = \"application/json\";\n if (this.requestId) headers[\"X-Flowmails-Request-Id\"] = this.requestId;\n\n let lastError: FlowmailsError | null = null;\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method,\n headers,\n ...(method === \"POST\" ? { body: JSON.stringify(opts.body) } : {}),\n // 15s matches the platform's upstream timeout — we want our\n // error to be \"request timed out\" rather than a generic 502.\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n lastError = new UpstreamError(\n \"network_error\",\n err instanceof Error ? err.message : undefined,\n 0,\n );\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // 2xx — happy path. Decode and return.\n if (res.ok) {\n return (await res.json()) as T;\n }\n\n // Non-2xx — render to a typed error.\n let payload: {\n error?: string;\n detail?: string;\n reason?: string;\n limit?: number;\n remaining?: number;\n resetAt?: string;\n } = {};\n try {\n payload = (await res.json()) as typeof payload;\n } catch {\n // Body wasn't JSON; fall back to status-based error.\n }\n\n const code = payload.error ?? \"request_failed\";\n\n if (res.status === 401) throw new AuthenticationError(code, res.status);\n if (\n res.status === 400 ||\n res.status === 404 ||\n res.status === 422 ||\n res.status === 409\n ) {\n // 409 is the idempotency conflict: the same key was already\n // used for a **different** payload. That is a client bug, not\n // a transient failure — answering it with a retryable error\n // would have the agent send the same wrong thing again.\n throw new ValidationError(code, payload.detail, res.status);\n }\n if (res.status === 429) {\n // Two different 429s, and they need different handling:\n //\n // - `idempotency_key_in_progress` — the *same* request is\n // already running. Retrying it is exactly right, and it\n // replays the first attempt's answer.\n // - `rate_limit_exceeded` — the quota window is exhausted. A\n // retry inside the same window cannot succeed and would\n // only burn another slot, so it is **not** retried; the\n // error carries `resetAt` so the caller can wait for the\n // window instead of guessing.\n const facts = readQuotaFacts(res, payload);\n if (code === \"idempotency_key_in_progress\") {\n lastError = new RateLimitError(code, res.status, facts);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n throw new RateLimitError(code, res.status, facts);\n }\n if (res.status >= 500 || res.status === 408) {\n lastError = new UpstreamError(code, payload.detail, res.status);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // Anything else: not retryable, throw immediately.\n throw new FlowmailsError(code, `Request failed: ${code}`, res.status);\n }\n\n // Shouldn't reach here — last iteration always throws. Type\n // assertion keeps the compiler happy without `any`.\n throw lastError ?? new FlowmailsError(\"unknown\", \"Unknown failure\", 0);\n }\n}\n\n/**\n * The event log namespace — see {@link Flowmails.events}.\n */\nexport interface AgentEvents {\n /**\n * One page of the log, oldest first, after `opts.after`.\n *\n * The cursor is an **event id**, never a timestamp: two events can\n * land in the same millisecond, and a cursor that can skip a row\n * loses mail. An unknown cursor is a `ValidationError`, never an\n * empty page — \"no new events\" would silently stop the agent\n * seeing mail.\n */\n list(opts?: ListEventsOptions): Promise<ListEventsResult>;\n}\n\n/**\n * The message-read namespace — see {@link Flowmails.messages}.\n */\nexport interface AgentMessages {\n /** Fetch the full content of one message by SMTP `Message-ID`. */\n get(\n messageId: string,\n opts?: { domainId?: string },\n ): Promise<MessageDetail>;\n /** Poll a sent message's delivery state by row id or `Message-ID`. */\n status(id: string): Promise<SendStatus>;\n /**\n * `search_emails`: look **back** through the mailbox.\n *\n * The event log is the primary listen path — a cursor over what\n * just arrived. Search is the history path: \"what did that\n * supplier mail me last quarter?\" is not an event-log question,\n * and the event log carries no body.\n *\n * A result carries addressing, the subject and a short **preview**;\n * the body is fetched per message with {@link AgentMessages.get},\n * so a search is never a way to pull the whole mailbox through a\n * query parameter.\n */\n search(\n domainId: string,\n opts: SearchMessagesOptions,\n ): Promise<SearchMessagesResult>;\n}\n\n/**\n * The conversation namespace — see {@link Flowmails.threads}.\n */\nexport interface AgentThreads {\n /**\n * Read the conversation a message belongs to.\n *\n * `threadId` is the conversation **root's** SMTP `Message-ID` —\n * the value `email.threadId` holds, never an intermediate parent's.\n * An agent that holds an intermediate message id still gets the\n * whole chain: the platform resolves it to its row and reads the\n * chain from that row's own anchor.\n */\n get(threadId: string, opts?: { domainId?: string }): Promise<ThreadDetail>;\n}\n\n/**\n * The durable-wait namespace — see {@link Flowmails.waits}.\n */\nexport interface AgentWaits {\n /** Open a wait. Answers immediately; poll {@link AgentWaits.get}. */\n create(opts: CreateWaitOptions): Promise<CreateWaitResult>;\n /** Read a wait. A wait past its deadline reads as `expired`. */\n get(waitId: string): Promise<WaitStatus>;\n}\n\n/**\n * The address namespace — see {@link Flowmails.addresses}.\n */\nexport interface AgentAddresses {\n /** `list_domains`: every domain on the key's account. */\n listDomains(): Promise<AgentDomain[]>;\n /** `list_addresses`: one domain's local parts and routing mode. */\n list(domainId: string): Promise<{\n domainId: string;\n domain: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n addresses: string[];\n /** True when every local part already delivers (catch-all mode). */\n acceptsAnyLocalPart: boolean;\n }>;\n /**\n * `create_address`: add **one** local part.\n *\n * Idempotent — creating an address that already exists answers\n * with `created: false` rather than an error. It never changes the\n * routing mode, never removes a part and never clears the table:\n * mode changes and route-table editing stay dashboard-only.\n */\n create(domainId: string, localPart: string): Promise<CreateAddressResult>;\n}\n\n/**\n * A sent message's delivery state.\n *\n * `status` is the receive worker's lifecycle literal, so an agent can\n * distinguish \"the relay took it\" from \"the recipient's server\n * accepted it\" from \"it bounced\" — the v0.1 SDK collapsed all of them\n * into `\"queued\"` and dropped the relay's `Message-ID` with them.\n */\nexport interface SendStatus {\n /** The worker's row id. */\n id: string;\n /**\n * `sent` (the relay accepted it) or `failed` (the relay rejected it)\n * — those are the two the receive worker writes for an outbound\n * message today.\n *\n * The vocabulary also holds `delivered` / `bounced` / `complained` /\n * `delayed`, and the backend maps them if they appear, but the\n * worker has no DSN or bounce ingestion and never writes them. **A\n * bounce is not observable today.**\n */\n status: string;\n /** The SMTP `Message-ID`; empty when the relay never accepted it. */\n messageId: string;\n /**\n * The relay's error string when `status` is `failed`, else null.\n *\n * The same reason the send response carries — read from the same\n * column on the same worker.\n */\n sendFeedback: string | null;\n /**\n * The typed failure slug (`\"send_failed\"`) when `status` is\n * `failed`, else `null`.\n *\n * Optional: an older backend does not send it. When it is present,\n * a `failed` status always carries one — \"failed with no reason\" is\n * not a state the wire can be in.\n */\n error?: string | null;\n /** `CURRENT_TIMESTAMP` from the worker; opaque to the SDK. */\n createdAt: string | null;\n}\n\n// ---------- Module-level helpers ----------\n\n/**\n * Read the quota facts off a rate-limited response.\n *\n * The body is the source of truth (`limit` / `remaining` / `resetAt`);\n * the headers are the fallback, because something in front of the\n * backend may strip the body but not the headers.\n *\n * `X-Flowmails-RateLimit-Reset` is epoch **seconds** (the HTTP\n * convention); the body's `resetAt` is ISO-8601. The header is\n * converted so both end up in the same shape on the error.\n */\nfunction readQuotaFacts(\n res: Response,\n payload: { limit?: number; remaining?: number; resetAt?: string },\n): { limit?: number; remaining?: number; resetAt?: string } | undefined {\n const limit =\n typeof payload.limit === \"number\" ? payload.limit : undefined;\n let remaining =\n typeof payload.remaining === \"number\" ? payload.remaining : undefined;\n let resetAt =\n typeof payload.resetAt === \"string\" ? payload.resetAt : undefined;\n\n const headerRemaining = res.headers?.get?.(\n \"X-Flowmails-RateLimit-Remaining\",\n );\n if (remaining === undefined && headerRemaining) {\n const parsed = Number(headerRemaining);\n if (Number.isFinite(parsed)) remaining = parsed;\n }\n\n const headerReset = res.headers?.get?.(\"X-Flowmails-RateLimit-Reset\");\n if (resetAt === undefined && headerReset) {\n const parsed = Number(headerReset);\n if (Number.isFinite(parsed)) {\n resetAt = new Date(parsed * 1000).toISOString();\n }\n }\n\n if (limit === undefined && remaining === undefined && resetAt === undefined) {\n return undefined;\n }\n return { limit, remaining, resetAt };\n}\n\n/**\n * Compose a request URL, dropping undefined / empty query values.\n *\n * An absent filter must not travel as `?subject=undefined` or as an\n * empty `?subject=` — the platform treats an empty string as a real\n * filter value in some places, so \"not asked for\" and \"asked for the\n * empty string\" have to stay distinguishable on the wire.\n */\nfunction buildUrl(\n origin: string,\n path: string,\n query?: Record<string, string | number | undefined>,\n): string {\n const url = new URL(`${origin}${path}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null || value === \"\") continue;\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Browser-safe base64 of a `Uint8Array`. Avoids pulling in a\n // Buffer polyfill in the worker / browser bundles.\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++) {\n bin += String.fromCharCode(bytes[i]);\n }\n return btoa(bin);\n}\n\nfunction backoffMs(attempt: number): number {\n // Exponential backoff with jitter, capped at 4 s. attempt 0 → 250 ms.\n const base = Math.min(250 * 2 ** attempt, 4_000);\n return base + Math.floor(Math.random() * base);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";;;AASO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA,EAE/B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,MAAA,EAAgB;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,SAAA,GAAY,MAAA,IAAU,GAAA,IAA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AAG,MAAM,CAAA,EAAG,IAAI,CAAA,CAAE,CAAA;AACtC,EAAA,IAAI,KAAA,EAAO;AACT,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAChD,MAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,IAAQ,UAAU,EAAA,EAAI;AAC3D,MAAA,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,GAAA,EAAK,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,IACzC;AAAA,EACF;AACA,EAAA,OAAO,IAAI,QAAA,EAAS;AACtB;AAEA,SAAS,cAAc,KAAA,EAA2B;AAGhD,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,GAAA,IAAO,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EACrC;AACA,EAAA,OAAO,KAAK,GAAG,CAAA;AACjB;AAEA,SAAS,UAAU,OAAA,EAAyB;AAE1C,EAAA,MAAM,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,GAAM,CAAA,IAAK,SAAS,GAAK,CAAA;AAC/C,EAAA,OAAO,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,IAAI,CAAA;AAC/C;AAEA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"index.cjs","sourcesContent":["/**\n * Public error hierarchy. Mirrors the SDK backend's JSON contract\n * documented in `apps/sdk-backend/src/utils/errors.js`.\n *\n * The base `FlowmailsError` carries the raw `code` string (e.g.\n * `\"validation_failed\"`) plus the HTTP status. Subclasses add\n * richer contextual fields (validation `detail`, auth `reason`)\n * that the SDK backend actually emits.\n */\nexport class FlowmailsError extends Error {\n /** Machine-readable error slug, sent back from the SDK backend. */\n readonly code: string;\n /** HTTP status from the SDK backend response. */\n readonly status: number;\n /** Suggested retry hint (`true` for transient 5xx / 408 / 429). */\n readonly retryable: boolean;\n\n constructor(code: string, message: string, status: number) {\n super(message);\n this.name = \"FlowmailsError\";\n this.code = code;\n this.status = status;\n this.retryable = status >= 500 || status === 408 || status === 429;\n }\n}\n\n/**\n * 401 — API key missing / invalid / revoked. NOT retryable.\n */\nexport class AuthenticationError extends FlowmailsError {\n constructor(code = \"api_key_invalid\", status = 401) {\n super(code, `Authentication failed: ${code}`, status);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * 400 / 422 — request was syntactically valid but rejected by the\n * backend. NOT retryable without code changes.\n */\nexport class ValidationError extends FlowmailsError {\n readonly detail?: string;\n /**\n * The rest of the platform's error body, when it carried more than\n * `error` / `detail`.\n *\n * The claim conflict is the case that matters: a `409` from\n * `POST /api/agent/messages/:messageId/claim` names the credential\n * holding the live claim (`claimedBy`, `claimedAt`). Dropping those\n * left a caller with \"Validation failed: message already claimed\" and\n * no way to tell which worker holds the message — the one fact the\n * mutex exists to communicate.\n */\n readonly extra?: Record<string, unknown>;\n constructor(\n code: string,\n detail: string | undefined,\n status = 400,\n extra?: Record<string, unknown>,\n ) {\n super(code, `Validation failed: ${code}${detail ? ` — ${detail}` : \"\"}`, status);\n this.name = \"ValidationError\";\n this.detail = detail;\n this.extra = extra;\n }\n}\n\n/**\n * 408 / 429 — request was rate-limited or timed out. Retryable.\n *\n * A 429 from Flowmails is either a **quota refusal**\n * (`rate_limit_exceeded`) or a request that is **already running**\n * (`idempotency_key_in_progress`). The two need different handling,\n * so the quota facts travel on the error:\n *\n * - `limit` — the limit that was hit.\n * - `remaining` — how many sends are left in the window (`0` when the\n * quota is exhausted).\n * - `resetAt` — ISO-8601 instant the window rolls over.\n */\nexport class RateLimitError extends FlowmailsError {\n /** The limit that was hit, when the server named one. */\n readonly limit?: number;\n /** The sends left in the window, when the server named one. */\n readonly remaining?: number;\n /** ISO-8601 instant the window rolls over, when the server named one. */\n readonly resetAt?: string;\n\n constructor(\n code = \"rate_limited\",\n status = 429,\n facts?: { limit?: number; remaining?: number; resetAt?: string },\n ) {\n super(code, `Rate limited: ${code}`, status);\n this.name = \"RateLimitError\";\n this.limit = facts?.limit;\n this.remaining = facts?.remaining;\n this.resetAt = facts?.resetAt;\n }\n}\n\n/**\n * 502 / 504 — the SDK backend couldn't reach the upstream\n * receive-worker, or the upstream returned a malformed response.\n * Retryable.\n */\nexport class UpstreamError extends FlowmailsError {\n readonly upstreamMessage?: string;\n constructor(code: string, upstreamMessage: string | undefined, status = 502) {\n super(code, `Upstream failure: ${code}`, status);\n this.name = \"UpstreamError\";\n this.upstreamMessage = upstreamMessage;\n }\n}\n","/**\n * Public SDK facade. The whole shape of the package is:\n *\n * new Flowmails({ apiKey: \"fm_…\" }).send({...})\n *\n * No top-level helper functions, no globals, no implicit init.\n * Construction takes an `apiKey` and an optional `baseURL`\n * (mainly for testing / private-region deployments).\n *\n * `send` is the only public method in v0.1 — there is exactly\n * one outbound endpoint (`POST /api/v1/messages`). The\n * `request<T>` helper below it carries the retry / backoff /\n * error-mapping machinery and is private; future public methods\n * (e.g. `webhooks.send`) will call `request<T>` internally so\n * the choke point stays in one place.\n *\n * The payload DTOs (`SendOptions` / `SendResult` / `SendAttachment`)\n * mirror common email-clients (Gmail API, Resend, Postmark), NOT\n * the receive-worker's wire format. `send` does the rename to\n * wire on the way out (html → content, Uint8Array → base64).\n */\nimport {\n AuthenticationError,\n FlowmailsError,\n RateLimitError,\n UpstreamError,\n ValidationError,\n} from \"./errors.js\";\n\n// ---------- Public payload types ----------\n\n/**\n * A single file attached to the outbound message.\n *\n * `filename` and `content` are required. `mimeType` defaults to\n * `application/octet-stream` if the SDK backend cannot infer it\n * from the filename (the backend forwards `mimeType` to the\n * receive-worker which sets it on the SMTP part).\n */\nexport interface SendAttachment {\n filename: string;\n content: string | Uint8Array;\n mimeType?: string;\n}\n\n/**\n * One event in the durable log — what arrived, where, and from whom.\n *\n * The event carries **routing facts plus the subject line**, never a\n * body: that is the platform's core promise (`docs/agent-platform.md`\n * §4.2), and the body is opt-in through {@link MessageDetail}. The\n * `messageId` is the SMTP `Message-ID` — the key every content read\n * takes.\n */\nexport interface AgentEvent {\n /** The cursor value. Treat it as opaque; pass it back as `after`. */\n id: string;\n /** The SMTP `Message-ID`. Pass this to `messages.get()`. */\n messageId: string;\n /** `inbound.received` — the only event type the platform emits. */\n event: string;\n /** The mailbox the message landed in, e.g. `billing@yourapp.com`. */\n recipient: string;\n /** The sender, when the receive worker could determine it. */\n sender: string | null;\n /** The subject line — the one content field on the event. */\n subject: string | null;\n /** ISO-8601 timestamp of when the platform recorded the event. */\n createdAt: string;\n}\n\n/** Options for {@link AgentEvents.list}. */\nexport interface ListEventsOptions {\n /**\n * Cursor: return events **after** this event id. Pass the\n * `nextCursor` of the previous page. Treat it as opaque — it is an\n * event id, not a timestamp, because two events can land in the\n * same millisecond and a cursor that can skip a row loses mail.\n */\n after?: string;\n /** Page size. The platform caps it; ask for what you will drain. */\n limit?: number;\n /** Exact recipient address filter. */\n recipient?: string;\n /** Exact sender address filter. */\n sender?: string;\n /** Case-insensitive **substring** of the subject. */\n subject?: string;\n}\n\n/** One page of the event log. */\nexport interface ListEventsResult {\n events: AgentEvent[];\n /**\n * The cursor to pass as `after` on the next call. Present whenever\n * the page was not empty; absent when the log is drained.\n */\n nextCursor?: string;\n}\n\n/** Options for {@link AgentWaits.create}. */\nexport interface CreateWaitOptions {\n /** The mailbox to watch, e.g. `billing@yourapp.com`. */\n address: string;\n /** Only resolve for mail from this sender. */\n sender?: string;\n /** Only resolve for a subject containing this substring. */\n subject?: string;\n /**\n * How long to keep the wait open, in milliseconds. Defaults to 15\n * minutes; the platform caps it at 24 hours.\n */\n timeoutMs?: number;\n}\n\n/**\n * How a wait's resolution is delivered besides the poll.\n *\n * The wait's resolution is also delivered as the `wait.resolved`\n * webhook event, on the account's verified outbound webhook — signed,\n * retried and logged. An agent with **no long-running process** (a\n * serverless function, a CI job, a webhook-driven service) therefore\n * does not have to write a polling loop to learn that a mail landed.\n * Polling the wait keeps working either way.\n *\n * ## Why the name is a literal here\n *\n * The SDK is **dependency-free** by design — it is published to npm\n * and the workspace package that holds the contract is private, so\n * this package cannot import the constant the contract file holds.\n *\n * The two are therefore kept in step by a **test**, not by an import:\n * `test/web-agent-sdk-cli-mcp-push-vocabulary.test.mjs` asserts that\n * this string, the CLI's copy and the MCP tool descriptions are all\n * the same value as the shared contract's `AGENT_WAIT_PUSH_EVENT`. A\n * rename is a failing test, not a drift.\n */\nexport const WAIT_RESOLVED_EVENT = \"wait.resolved\";\n\n/** A durable wait, as the platform reports it. */\nexport interface WaitStatus {\n waitId: string;\n /** `pending` → `resolved` (a message landed) or `expired`. */\n status: \"pending\" | \"resolved\" | \"expired\";\n address: string;\n sender: string | null;\n subject: string | null;\n /** The SMTP `Message-ID` that resolved the wait, when it resolved. */\n resolvedMessageId: string | null;\n /** ISO-8601 deadline. A wait past it reads as `expired`. */\n expiresAt: string | number;\n /**\n * How this wait's resolution is also delivered.\n *\n * The event name is the same one the CLI and the MCP tool\n * descriptions name — a client that reads one of them reads the\n * same fact as a client that reads another.\n */\n push?: {\n /** The webhook event this wait's resolution is delivered as. */\n event: typeof WAIT_RESOLVED_EVENT;\n };\n}\n\n/**\n * A newly-opened wait.\n *\n * Returned **immediately** — the platform writes a row and answers,\n * it never suspends the request. A verification mail arrives minutes\n * to hours later and an edge request dies long before that, so the\n * wait is durable state the agent polls with {@link AgentWaits.get}.\n */\nexport interface CreateWaitResult extends WaitStatus {\n /** A hint for the poll loop: check again in a few seconds. */\n pollAfterMs: number;\n}\n\n/**\n * One verification code the platform extracted **on read**.\n *\n * `source` says where it came from: a code in the subject line is the\n * strongest signal there is.\n */\nexport interface ExtractedVerificationCode {\n code: string;\n source: \"subject\" | \"body\";\n}\n\n/** One authentication-shaped link the platform extracted. */\nexport interface ExtractedMagicLink {\n url: string;\n label?: string;\n}\n\n/**\n * The structured facts a message carries.\n *\n * Deterministic — the platform runs the same rules on every read, with no\n * model and no clock — so the same message answers the same thing twice.\n * Both lists are usually empty.\n */\nexport interface ExtractedContent {\n verificationCodes: ExtractedVerificationCode[];\n magicLinks: ExtractedMagicLink[];\n}\n\n/** The full content of one message. Fetched, never pushed. */\nexport interface MessageDetail {\n /** The mailstore's UUIDv7 row id. */\n id: string;\n /** The SMTP `Message-ID` the event carried. */\n messageId: string;\n from: string;\n fromName: string | null;\n to: string;\n toName: string | null;\n subject: string | null;\n /** Plain-text body. Ideal for regexing a verification code out. */\n text: string | null;\n /**\n * Rendered HTML body, when the message had one.\n *\n * `null` when {@link GetMessageOptions.format} was `\"markdown\"` — that\n * mode omits the raw markup on purpose.\n */\n html: string | null;\n /**\n * A clean Markdown projection of the HTML body: head/style/script,\n * hidden preheader text and tracking pixels removed; headings, lists,\n * links and emphasis kept.\n */\n markdown: string | null;\n /** Verification codes and authentication links, extracted on read. */\n extracted: ExtractedContent | null;\n /**\n * The prompt-injection verdict — the firewall's read-time answer about this\n * message.\n *\n * Present when the domain's firewall mode is not `off`; absent (not `null`)\n * when the domain does not scan, so \"not scanned\" and \"scanned clean\" stay\n * distinguishable. `hidden_payload` means an instruction was concealed in\n * the HTML (a `display:none` block, an HTML comment, or a run of invisible\n * characters) — the shape a human reading the mail would never see.\n *\n * The `signals[].evidence` strings are **untrusted text**. Escape them, and\n * never treat them as an instruction.\n */\n security?: MessageSecurity;\n receivedAt: string | null;\n attachments: Array<{\n /** The attachment id — what {@link AgentMessages.attachmentText} takes. */\n id: string | null;\n filename: string | null;\n mimeType: string | null;\n size: number | null;\n url: string | null;\n }>;\n}\n\n/** One matched signal behind a message's prompt-injection verdict. */\nexport interface MessageSecuritySignal {\n /**\n * `instruction_override` | `role_hijack` | `data_exfiltration` |\n * `tool_abuse` | `hidden_payload`.\n */\n kind: string;\n /** The points this signal contributed. */\n weight: number;\n /** A bounded snippet of the matched text. Untrusted. */\n evidence: string;\n}\n\n/** The prompt-injection verdict for one message. */\nexport interface MessageSecurity {\n promptInjectionRisk: \"none\" | \"low\" | \"medium\" | \"high\";\n /** `0..=100`. */\n score: number;\n signals: MessageSecuritySignal[];\n}\n\n/** One address (mailbox) the platform accepts mail for. */\nexport interface AgentAddress {\n address: string;\n localPart: string;\n}\n\n/**\n * One domain on the account.\n *\n * `routingMode` decides whether a new address needs anything to\n * happen: on `catchall` every local part already delivers, on\n * `rules` only the listed ones do.\n */\nexport interface AgentDomain {\n id: string;\n name: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n /**\n * False when the domain's route table is not bound in the mail\n * worker yet — its mail is not being accepted.\n */\n ready: boolean;\n}\n\n/** Result of {@link AgentAddresses.create}. */\nexport interface CreateAddressResult {\n address: string;\n localPart: string;\n domainId: string;\n domain: string;\n /** False when the address already existed — the call is idempotent. */\n created: boolean;\n routingMode?: \"catchall\" | \"rules\";\n}\n\n/**\n * One message of a conversation chain.\n *\n * It extends {@link MessageDetail} because the thread route uses the\n * **same projection** the single-message read uses — the same\n * fields, the same shape. The only addition is the truncation flag.\n */\nexport interface ThreadMessage extends MessageDetail {\n /**\n * `1` when the receive worker shortened the body.\n *\n * The worker returns a bounded window of the chain and truncates\n * the bodies of the non-current members — a long thread must not\n * become a way to pull a whole mailbox. `total` / `hasMoreOlder` /\n * `hasMoreNewer` say whether the chain extends past the window.\n */\n bodyTruncated: 0 | 1;\n}\n\n/**\n * A conversation chain — `docs/agent-platform.md` §10.8 AP-27.\n */\nexport interface ThreadDetail {\n /** The conversation **root's** SMTP `Message-ID`. */\n threadId: string;\n /** The platform domain id the chain was read from. */\n domainId: string;\n /** The domain name the chain was read from. */\n domain: string;\n /** The full chain length — not just the returned window. */\n total: number;\n /** The chain extends past the window, older side. */\n hasMoreOlder: boolean;\n /** The chain extends past the window, newer side. */\n hasMoreNewer: boolean;\n /** The chain, oldest first. */\n messages: ThreadMessage[];\n}\n\n/** The four states a draft can be in. */\nexport const DRAFT_STATUS_NAMES = [\n \"pending_review\",\n \"approved\",\n \"rejected\",\n \"sent\",\n] as const;\n\nexport type DraftStatusName = (typeof DRAFT_STATUS_NAMES)[number];\n\n/**\n * A message an agent wrote that a **person** has not approved yet.\n *\n * ## Why this is not a gated send\n *\n * Sending is the agent's decision (`docs/agent-platform.md` §3), and\n * `fm.send()` still sends immediately. The draft is a **different\n * capability**: `drafts:write` (without `messages:send`) lets a\n * credential prepare a message and deliver nothing. Nothing leaves\n * until a human approves it from the dashboard, and the approval\n * dispatches through the platform's own audited send path.\n *\n * ```ts\n * const draft = await fm.drafts.create({\n * from: \"support@acme.test\",\n * to: \"customer@example.com\",\n * subject: \"Re: your invoice\",\n * replyToMessageId: event.messageId,\n * useAiContext: true,\n * });\n * // …nothing has been sent. Poll the outcome:\n * const later = await fm.drafts.get(draft.id);\n * // later.status: \"pending_review\" | \"sent\" | \"rejected\"\n * ```\n */\nexport interface EmailDraft {\n id: string;\n domainId: string;\n from: string;\n fromName: string | null;\n to: string[];\n replyTo: string | null;\n replyToMessageId: string | null;\n subject: string;\n text: string | null;\n html: string | null;\n status: DraftStatusName;\n source: \"agent\" | \"human\";\n useAiContext: boolean;\n aiRoleName: string | null;\n /** Which credential wrote it; `null` when a human wrote it. */\n createdByCredentialType: string | null;\n /** The reviewer's note, on an approved or rejected draft. */\n reviewNote: string | null;\n /** The relay's SMTP `Message-ID`, once sent. */\n sentMessageId: string | null;\n sentEmailId: string | null;\n createdAt: number;\n updatedAt: number;\n reviewedAt: number | null;\n}\n\n/**\n * Options for {@link AgentDrafts.create}.\n *\n * `text` or `html` is required for a hand-written draft. With\n * `useAiContext: true` both are optional and `replyToMessageId` is\n * required — the body is generated from the message being answered and\n * the domain's knowledge base.\n */\nexport interface CreateDraftOptions {\n from: string;\n fromName?: string;\n to: string | string[];\n subject: string;\n text?: string;\n html?: string;\n replyTo?: string;\n replyToMessageId?: string;\n /**\n * Draft the reply from the domain's AI context instead of a\n * hand-written body. A plan without AI context answers `402`.\n */\n useAiContext?: boolean;\n}\n\n/** Options for {@link AgentDrafts.list}. */\nexport interface ListDraftsOptions {\n status?: DraftStatusName;\n domainId?: string;\n limit?: number;\n}\n\n/** The answer of {@link AgentDrafts.list}. */\nexport interface ListDraftsResult {\n drafts: EmailDraft[];\n total: number;\n}\n\n/**\n * The agent's own record of what it did with one message.\n *\n * The event log says a mail arrived; this says whether the agent\n * already handled it. An agent that restarts reads it back to tell\n * \"I never saw this\" from \"I saw it and never finished\".\n */\nexport interface MessageState {\n /** The SMTP `Message-ID` — the id the event log carried. */\n messageId: string;\n /** The platform domain id whose mailbox received the message. */\n domainId: string;\n /**\n * `pending` → `processing` → `done` | `failed`.\n *\n * The platform records what the agent wrote and never moves a row\n * on its own — there is no rule engine and no sweeper behind it.\n */\n state: \"pending\" | \"processing\" | \"done\" | \"failed\";\n /** Short labels the agent attached to the message. */\n labels: string[];\n /** A free-text note about what the agent did. */\n note: string | null;\n /** Who holds the claim, when the message is `processing`. */\n claimedBy: string | null;\n /** ISO-8601 timestamp of the claim. */\n claimedAt: string | number | null;\n /** ISO-8601 timestamp of the last write. */\n updatedAt: string | number;\n /** ISO-8601 timestamp of when the row was created. */\n createdAt?: string | number;\n}\n\n/**\n * The state names the platform accepts, in the platform's order.\n *\n * The vocabulary is this one list: the {@link MessageStateName} union\n * below is derived from it, and the SDK's own validation reads it, so a\n * name cannot exist in one place and be refused in the other.\n */\nconst MESSAGE_STATE_NAMES = [\n \"pending\",\n \"processing\",\n \"done\",\n \"failed\",\n] as const;\n\n/**\n * The vocabulary of {@link MessageState.state}, as a named union so a\n * caller can pass one without re-typing the literal at every call\n * site.\n */\nexport type MessageStateName = (typeof MESSAGE_STATE_NAMES)[number];\n\n/**\n * Options for {@link AgentMessages.listStates}.\n */\nexport interface ListMessageStatesOptions {\n /**\n * Only the states in this one — `pending`, `processing`, `done` or\n * `failed`.\n *\n * The resume-after-restart read is most useful with\n * `processing`: those are the messages this agent took and never\n * finished.\n */\n state?: MessageStateName;\n /** Narrow to one message. */\n messageId?: string;\n /** The page size. */\n limit?: number;\n}\n\n/**\n * The agent's own per-message state, read back.\n */\nexport interface ListMessageStatesResult {\n /** One row per message the calling credential has a state for. */\n states: MessageState[];\n}\n\n/** Options for {@link AgentMessages.claim}. */\nexport interface ClaimMessageOptions {\n /** The platform domain id whose mailbox received the message. */\n domainId: string;\n /**\n * Which worker of yours holds the claim, e.g. `worker-1`.\n * Defaults to the credential.\n */\n claimedBy?: string;\n}\n\n/** Options for {@link AgentMessages.complete}. */\nexport interface CompleteMessageOptions {\n /** The platform domain id whose mailbox received the message. */\n domainId: string;\n /** `done` when finished with it, `failed` when it did not succeed. */\n state: \"done\" | \"failed\";\n /** Short labels to attach, e.g. `[\"invoice\"]`. */\n labels?: string[];\n /** A short free-text note about what the agent did. */\n note?: string;\n}\n\n/**\n * One search hit.\n *\n * Addressing, the subject and a short preview — never the body. The\n * body is fetched per message, through {@link AgentMessages.get},\n * when the agent decides a message matters.\n */\nexport interface SearchMessageHit {\n /** The mailstore's UUIDv7 row id. Accepted by {@link AgentMessages.get}. */\n id: string | null;\n /** The SMTP `Message-ID`, when the sender supplied one. */\n messageId: string;\n from: string | null;\n fromName: string | null;\n to: string | null;\n toName: string | null;\n subject: string | null;\n receivedAt: string | null;\n /** A short plain-text preview of the body. */\n preview: string | null;\n}\n\n/**\n * The arguments of a mailbox search.\n *\n * `domainId` is required on the call (not in this shape) because the\n * receive worker's search path is domain-scoped: one domain, one\n * round-trip, one stable ordering. `GET /api/agent/domains` is the\n * call that answers it.\n */\nexport interface SearchMessagesOptions {\n /** The query. At least two characters — the platform refuses less. */\n q: string;\n /** The page size. */\n limit?: number;\n /** Which field to match. Defaults to `body` (subject + from + to + text). */\n field?: \"subject\" | \"from\" | \"to\" | \"body\";\n /** Which mailbox direction. Defaults to `receive`. */\n type?: \"receive\" | \"send\";\n}\n\n/** The result of a mailbox search. */\nexport interface SearchMessagesResult {\n messages: SearchMessageHit[];\n /** How many rows match the filter, ignoring `limit`. */\n total: number;\n domainId: string;\n}\n\n/**\n * Composed send payload.\n *\n * `to` accepts a single address or an array. `subject` is required.\n * At least one of `text` / `html` must be a non-empty string.\n */\nexport interface SendOptions {\n /**\n * Sender address. MUST land on the domain the API key is bound\n * to (the SDK backend enforces this with a 422 on mismatch).\n */\n from: string;\n /**\n * Display name for the sender, e.g. `\"Billing\"`.\n *\n * Optional: when it is absent the mail worker stores the address's\n * local part **verbatim** (`billing@…` → `billing`), so the column is\n * never blank. It does not capitalise it — a display name is the\n * caller's choice.\n */\n fromName?: string;\n /** One recipient or an array. */\n to: string | string[];\n /** Optional reply-to override. */\n replyTo?: string;\n /**\n * Reply in thread: the SMTP `Message-ID` (or mailstore row UUID) of the\n * message being answered.\n *\n * When set, the SDK backend resolves the parent row and derives\n * the `In-Reply-To` / `References` headers and the thread anchor,\n * so the recipient's mail client threads your message with the\n * original conversation — and the dashboard shows it in the same\n * thread. The caller supplies the **parent**, never the headers:\n * deriving `References` by hand is how threads fork.\n *\n * A parent with no `Message-ID` header is rejected: there is\n * nothing to point `In-Reply-To` at.\n */\n replyToMessageId?: string;\n /** Subject line — required, non-empty. */\n subject: string;\n /** Plain-text body. Required iff `html` is also missing. */\n text?: string;\n /** HTML body. Required iff `text` is also missing. Inline\n * `cid:` images and remote `data:` urls are auto-extracted by\n * the email-worker into R2 embeds. */\n html?: string;\n /** Attachments. */\n attachments?: SendAttachment[];\n /**\n * Send **one message per recipient** — the default — or one shared\n * message for everybody.\n *\n * `true` (the default): every recipient gets their own message. They\n * cannot see each other, one refused address does not hold up the\n * others, and {@link SendResult.recipients} reports what happened to\n * **each** address. `false`: everybody is on one envelope — one\n * message, one relay call, one bill from a provider that charges per\n * message — and then a single refused address refuses the whole\n * send, because there was only ever one send.\n *\n * The default is per-recipient because a partial failure has to be\n * observable. With one shared envelope the answer is all-or-nothing\n * by construction.\n */\n perRecipient?: boolean;\n /**\n * Idempotency key — the same key under the same account and the\n * same request returns the **original** result and does not send\n * twice.\n *\n * Give every send a key you can rebuild after a timeout (a UUID\n * per logical mail, not per attempt) and a retry becomes free: the\n * backend replays the first answer instead of delivering a second\n * message.\n *\n * The key is scoped to the **account**, not globally — two accounts\n * may use the same string. Reusing one key for a *different* payload\n * is a client bug and is refused with `idempotency_key_conflict`\n * (409) rather than answered with the first result.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Result of a successful send.\n *\n * `id` is the platform's row id; `messageId` is the SMTP `Message-ID`\n * the relay assigned, which is the key every read path takes — pass\n * it to {@link AgentMessages.get} to read a reply, or to\n * {@link AgentMessages.status} to poll delivery.\n *\n * ## `status` is the send's verdict\n *\n * `status` is the **aggregate** over every recipient:\n *\n * - `\"sent\"` — everybody was accepted;\n * - `\"partial\"` — some were accepted and some were refused;\n * - `\"failed\"` — nobody was accepted.\n *\n * ## A send that failed\n *\n * The backend answers `201` for a send the relay **refused** — the\n * message row exists, the mail does not. That used to be invisible:\n * the answer was `{ id, status: \"failed\", messageId: \"\" }` with\n * nothing else, so an agent could not tell a refused send from a\n * lost one (the 2026-10-31 audit, P0-1).\n *\n * Two fields now say what happened:\n *\n * - `error` — the typed slug (`\"send_failed\"`), or `null` when every\n * recipient was accepted. **It is never `null` on a failed or a\n * partial send**, so \"failed with no reason\" is not a state the\n * wire can be in, and \"check `result.error` before treating a 201\n * as sent\" stays true.\n * - `sendFeedback` — the relay's own reason, when it gave one\n * (`null` when it did not).\n *\n * Both are optional because the SDK also talks to older backends that\n * did not send them; on those, `status` is the only signal.\n */\nexport interface SendResult {\n /** Numeric email row id (stringified for JSON safety). */\n id: string;\n /** The send's aggregate state at send time. */\n status: string;\n /**\n * The SMTP `Message-ID` the relay assigned (the receive worker's\n * `resendEmailId`). Empty when the send failed before the relay\n * accepted it.\n */\n messageId?: string;\n /**\n * The relay's reason for the failure, when the relay gave one —\n * `null` when it did not, and `null` on a send that succeeded.\n */\n sendFeedback?: string | null;\n /**\n * The typed failure slug (`\"send_failed\"`), or `null` when the send\n * did not fail.\n *\n * A failed send always carries one: `status: \"failed\"` with\n * `error: null` is not a state the backend can answer. A **partial**\n * send carries it too — `status: \"partial\"` says *some* recipients\n * were refused, and `error` says \"not all of them got through\".\n */\n error?: string | null;\n /**\n * One entry per recipient — what happened to **each** address.\n *\n * This is the per-recipient detail a multi-recipient send needs:\n * \"the first two went out and the third was refused because X\" is a\n * fact the audit log must not flatten, and the answer must not\n * flatten it either.\n *\n * Absent on a body written by an older backend, which had no such\n * field. On those, `status` is the whole answer.\n */\n recipients?: SendRecipientResult[];\n}\n\n/**\n * One recipient's outcome inside a send.\n *\n * In per-recipient mode each address is its own message, its own row\n * and its own relay call — so this entry is that message: its id, its\n * verdict, and the relay's reason when the relay refused it.\n */\nexport interface SendRecipientResult {\n /** The address this entry is about. */\n to: string;\n /** The platform's row id for the message that carried it. */\n id: string;\n /** Whether the relay accepted this recipient's message. */\n status: \"sent\" | \"failed\";\n /** The SMTP `Message-ID`, when the relay assigned one. */\n messageId?: string;\n /** The relay's reason, when the relay gave one. */\n sendFeedback?: string | null;\n}\n\n/**\n * The outbound half of a domain — what the platform last recorded\n * about whether it can send.\n *\n * Read from `fm.me().sending`, the connection check's answer to\n * \"may this key's domain send?\". It is the same verdict the\n * dashboard shows, read from the same document, so the two cannot\n * disagree.\n */\nexport interface AccountSendingState {\n /**\n * True only when the domain can send right now.\n *\n * Read it **with** `configured` and `state`: `configured: false`\n * means sending was never set up (it is optional), while a\n * configured domain can still be temporarily `canSend: false` with\n * `state: \"setup_required\"`, `\"misconfigured\"`, etc.\n */\n canSend: boolean;\n /**\n * Whether an outbound provider is configured for the bound domain.\n *\n * Sending is optional. `false` means sending was never set up — a\n * different answer from \"configured but currently broken\", which also\n * reads `canSend: false`. Enable it from the domain page in the\n * dashboard.\n */\n configured: boolean;\n /**\n * The outbound verdict, in the platform's neutral vocabulary:\n * `ready`, `setup_required`, `unverified`, `misconfigured`,\n * `disabled`, `no_credential`, `credential_rejected`, `unknown` or\n * `error`.\n */\n state: string;\n /** The detail the platform recorded with the verdict. */\n detail: string | null;\n /**\n * When the sending half was last probed, in epoch milliseconds —\n * `null` when it never was. The platform probes on demand, so an\n * old stamp means the answer may be out of date.\n */\n checkedAt: number | null;\n}\n\n/**\n * What the credential behind the client is allowed to do, and which\n * account it belongs to.\n *\n * This is the **connection check** (`docs/agent-platform.md` §10.8\n * AP-05): it answers \"is my key live, which account is it, which\n * domain may it send from, and what may it do?\" without sending a\n * single message — the only two ways to get that answer before it\n * existed were to send real mail or to fail.\n */\nexport interface AccountInfo {\n /** The account the credential belongs to. */\n userId: string;\n /**\n * The domain the credential is bound to — the constraint on\n * sending. `null` when the credential carries no binding.\n */\n domain: string | null;\n /**\n * Which credential type answered: `\"sdk_key\"` (the dashboard's\n * domain-bound API key) or `\"agent_credential\"` (a scoped\n * credential issued for one set of capabilities).\n */\n credentialType: string;\n /** The scopes this credential holds. */\n scopes: string[];\n /**\n * The outbound half — **may this domain actually send?**\n *\n * `null` when the answer is not knowable: the credential carries no\n * bound domain, the platform could not be read, or the domain has\n * no row. `null` means \"we do not know\", which is different from\n * \"this domain cannot send\" — read it with `state` before acting\n * on it.\n */\n sending: AccountSendingState | null;\n}\n\n/**\n * The shared mail worker, and the version of it.\n *\n * The mail worker is **Flowmails' own** deployment — one shared\n * worker serves every tenant, isolated by the domain id on every row.\n * It is versioned, and an older one silently does less than the\n * platform expects (no route tables before `1.4.0`, no Message-ID\n * lookup before `1.5.1`, no event reporting before `1.6.0`). An agent\n * that cannot see the version cannot tell why its events are empty.\n */\nexport interface WorkerVersionInfo {\n /**\n * The version the platform last deployed — `null` when it has no\n * record (read {@link lastDeployAt} with it).\n */\n version: string | null;\n /** Whether the shared mail worker answered (its schema is migrated before deploy). */\n bootstrapped: boolean;\n /** When the platform last deployed this worker (ISO-8601), or `null`. */\n lastDeployAt: string | null;\n /** The last deploy error, when one happened, or `null`. */\n lastDeployError: string | null;\n}\n\n// ---------- Options & class ----------\n\nexport interface FlowmailsOptions {\n /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */\n apiKey: string;\n /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */\n baseURL?: string;\n /**\n * The **platform** origin, used by the listen half of the surface\n * (`fm.events`, `fm.messages`, `fm.waits`, `fm.addresses`).\n *\n * @deprecated The whole surface is served by the SDK backend now —\n * the agent platform moved there — so this defaults to the same\n * origin as {@link baseURL}. It is kept so a client that set it\n * keeps working against a private or staging deployment that\n * splits the two. A client that does not set it gets one host.\n */\n platformURL?: string;\n /** Inject a `fetch` implementation (Workers environments, test harnesses). */\n fetch?: typeof globalThis.fetch;\n /**\n * Number of automatic retries on transient failures (5xx, 408, and\n * a 429 that asks for another attempt). Defaults to 2. Set to 0 to\n * disable. The retry budget is bounded; doesn't apply to 4xx\n * validation / auth failures.\n *\n * A **quota** refusal (429 `rate_limit_exceeded`) is deliberately\n * NOT retried: the window is an hour, a retry inside it cannot\n * succeed, and it would only burn another slot. The error carries\n * `limit` / `remaining` / `resetAt` so the caller can wait for the\n * window instead of guessing.\n */\n maxRetries?: number;\n /**\n * Optional request-id header for cross-stack tracing. If set,\n * every outbound request carries `X-Flowmails-Request-Id`, and\n * the SDK backend echoes it back on the response so callers can\n * correlate platform logs with their own.\n */\n requestId?: string;\n}\n\nexport class Flowmails {\n private readonly apiKey: string;\n private readonly baseURL: string;\n private readonly platformURL: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly maxRetries: number;\n private readonly requestId?: string;\n\n constructor(opts: FlowmailsOptions) {\n if (!opts.apiKey) {\n throw new Error(\"Flowmails: apiKey is required\");\n }\n this.apiKey = opts.apiKey;\n this.baseURL = (opts.baseURL ?? \"https://sdk.flowmails.net\").replace(\n /\\/+$/,\n \"\",\n );\n // The listen half of the surface (the event log, the durable\n // wait, the message read) used to live on the platform worker,\n // which made it two origins and two hosts for one key. The agent\n // platform moved to the SDK backend, so both halves are served\n // there now — and `platformURL` defaults to the SAME origin\n // rather than to the platform's.\n //\n // The option survives for a deployment that genuinely splits the\n // two; a client that does not set it gets one host.\n this.platformURL = (\n opts.platformURL ?? this.baseURL\n ).replace(/\\/+$/, \"\");\n // `globalThis.fetch` MUST be bound before it is stored on an instance.\n // workerd implements `fetch` as a WebIDL operation whose `this` must be\n // the global object, so calling `this.fetchFn(url, …)` passes the\n // `Flowmails` instance instead and workerd throws\n // `TypeError: Illegal invocation`. That rejection lands in the catch\n // below and is reported as `UpstreamError(\"network_error\", …, 0)` — a\n // \"network\" failure that never touched the network, which is exactly how\n // it presented: auth mail silently never sending.\n //\n // Node's undici tolerates the detached call, so this is invisible in\n // `node --test` and in any browser; it only reproduces in the Workers\n // runtime. An *injected* `opts.fetch` is left unbound — it is the\n // caller's own function, not a WebIDL operation.\n this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);\n this.maxRetries = opts.maxRetries ?? 2;\n this.requestId = opts.requestId;\n }\n\n /**\n * Send mail through the SDK backend.\n *\n * Pass `replyToMessageId` to answer a message in thread — the SDK\n * backend resolves the parent and derives the `In-Reply-To` /\n * `References` headers and the thread anchor, so the recipient's\n * client threads it with the original conversation.\n *\n * Returns `{ id, status, messageId }` on success; throws one of\n * `AuthenticationError` / `ValidationError` / `RateLimitError` /\n * `UpstreamError` on failure (all subclasses of `FlowmailsError`).\n *\n * **A send the relay refused is not a throw.** The backend answers\n * `201` with `status: \"failed\"`, and the result carries the\n * reason: `error` is the typed slug and `sendFeedback` is the\n * relay's own words. Check `result.error` before treating a `201`\n * as \"sent\".\n *\n * **A partial send is not a success either.** Several recipients\n * each get their own message, and the relay can refuse some of them.\n * `status` is then `\"partial\"` — `error` is still set, and\n * `result.recipients` says exactly which addresses were refused and\n * why:\n *\n * ```ts\n * const result = await fm.send({ from, to: [\"a@x.test\", \"b@x.test\"], subject, text });\n * if (result.status === \"partial\") {\n * const refused = result.recipients?.filter((r) => r.status === \"failed\") ?? [];\n * // retry only these\n * }\n * ```\n */\n async send(opts: SendOptions): Promise<SendResult> {\n // The wire-shape renames (html → content, Uint8Array → base64)\n // happen here: the SDK's DTO mirrors common email clients, the\n // wire mirrors the receive worker.\n const body = {\n from: opts.from,\n fromName: opts.fromName,\n to: Array.isArray(opts.to) ? opts.to : [opts.to],\n replyTo: opts.replyTo,\n // The SDK backend resolves this to the three `threading`\n // fields. The caller names the **parent**, never the headers —\n // hand-deriving `References` is how threads fork.\n replyToMessageId: opts.replyToMessageId,\n subject: opts.subject,\n text: opts.text,\n html: opts.html,\n attachments: opts.attachments?.map((a) => ({\n filename: a.filename,\n content:\n a.content instanceof Uint8Array\n ? bytesToBase64(a.content)\n : a.content,\n mimeType: a.mimeType,\n })),\n // The idempotency key travels under the same name on the wire.\n // It is deliberately **not** renamed: the backend's body is\n // camelCase already, and a rename here would be one more place\n // for the two sides to disagree.\n idempotencyKey: opts.idempotencyKey,\n // The delivery mode travels under the same name as on the wire.\n // It is deliberately **not** defaulted here: the backend owns the\n // default, so a new SDK talking to an older backend and an old\n // SDK talking to a new backend both behave the way the backend\n // says they should.\n perRecipient: opts.perRecipient,\n };\n\n return this.request<SendResult>(this.baseURL, \"POST\", \"/api/v1/messages\", {\n body,\n });\n }\n\n /**\n * The connection check — who the credential is.\n *\n * `flowmails test` (the CLI's documented first command) and every\n * \"is my setup right?\" question end here. It verifies the key,\n * names the account, names the bound domain and reports the\n * scopes — and it sends nothing, so running it can never mail\n * somebody by accident.\n *\n * It also answers the question the 2026-10-31 audit (P0-1) found\n * missing: **may this domain actually send?** — `info.sending`\n * carries the platform's own verdict, read from the same document\n * the dashboard reads.\n *\n * ```ts\n * const me = await fm.me();\n * if (me.sending && !me.sending.canSend) {\n * // me.sending.configured: false means sending was never set up;\n * // otherwise me.sending.state says why: \"setup_required\", …\n * }\n * ```\n *\n * @throws {AuthenticationError} when the key is missing, malformed\n * or revoked.\n */\n async me(): Promise<AccountInfo> {\n return this.request<AccountInfo>(this.baseURL, \"GET\", \"/api/v1/me\");\n }\n\n /**\n * The shared mail worker, and the version of it.\n *\n * The mail worker does the actual receiving and sending — it is\n * Flowmails' own deployment, one shared worker for every tenant —\n * and it is versioned: `1.4.0` brought the route tables, `1.5.1` the\n * Message-ID lookup, `1.6.0` the event reporting that fills the\n * log this SDK reads. An agent whose worker is older than the\n * platform expects sees an empty event log and has no way to tell\n * \"no mail yet\" from \"my worker cannot report\".\n *\n * ```ts\n * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });\n * const worker = await fm.workerVersion();\n * if (!worker.version || worker.version < \"1.6.0\") { … }\n * ```\n *\n * @throws {AuthenticationError} when the key is missing, malformed\n * or revoked.\n */\n async workerVersion(): Promise<WorkerVersionInfo> {\n return this.request<WorkerVersionInfo>(this.baseURL, \"GET\", \"/api/v1/worker-version\");\n }\n\n /**\n * The event log — the listen half of the surface, read with a\n * cursor.\n *\n * ```ts\n * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });\n * let after: string | undefined;\n * for (;;) {\n * const page = await fm.events.list({ after, subject: \"invoice\" });\n * for (const event of page.events) { … }\n * after = page.nextCursor ?? after;\n * }\n * ```\n */\n readonly events: AgentEvents = {\n list: async (opts: ListEventsOptions = {}) => {\n const query: Record<string, string | number | undefined> = {\n after: opts.after,\n limit: opts.limit,\n recipient: opts.recipient,\n sender: opts.sender,\n subject: opts.subject,\n };\n return this.request<ListEventsResult>(\n this.platformURL,\n \"GET\",\n \"/api/agent/events\",\n { query },\n );\n },\n };\n\n /**\n * Read one message by its SMTP `Message-ID` — the id the event\n * carried.\n *\n * The event log deliberately hands over routing facts and a\n * subject and never a body (§4.2), so the content is an explicit\n * ask. This is that ask.\n */\n readonly messages: AgentMessages = {\n get: async (messageId: string, opts: GetMessageOptions = {}) => {\n if (!messageId) {\n throw new ValidationError(\"message_id_required\", \"messageId is required\");\n }\n if (\n opts.format !== undefined &&\n opts.format !== \"full\" &&\n opts.format !== \"markdown\"\n ) {\n throw new ValidationError(\n \"invalid_format\",\n 'format must be \"full\" or \"markdown\"',\n );\n }\n return this.request<MessageDetail>(\n this.platformURL,\n \"GET\",\n `/api/agent/messages/${encodeURIComponent(messageId)}`,\n { query: { domainId: opts.domainId, format: opts.format } },\n );\n },\n\n attachmentText: async (\n messageId: string,\n attachmentId: string,\n opts: { domainId?: string } = {},\n ) => {\n if (!messageId) {\n throw new ValidationError(\"message_id_required\", \"messageId is required\");\n }\n if (!attachmentId) {\n throw new ValidationError(\n \"attachment_id_required\",\n \"attachmentId is required\",\n );\n }\n return this.request<AttachmentText>(\n this.platformURL,\n \"GET\",\n `/api/agent/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}/text`,\n { query: { domainId: opts.domainId } },\n );\n },\n\n /**\n * Poll a **sent** message's delivery state.\n *\n * `id` is the value {@link send} returned as `id` (or the SMTP\n * `Message-ID`). Returns the worker's lifecycle state so an agent\n * can tell `sent` from `failed` (the two the worker writes)\n * instead of assuming success.\n */\n status: async (id: string) => {\n if (!id) {\n throw new ValidationError(\"message_id_required\", \"id is required\");\n }\n return this.request<SendStatus>(\n this.baseURL,\n \"GET\",\n `/api/v1/messages/${encodeURIComponent(id)}`,\n );\n },\n\n /**\n * Claim a message for processing.\n *\n * The event log says a mail arrived; it does not say whether the\n * agent already handled it. This writes that fact down, so a\n * restarted agent can tell \"I never saw this\" from \"I saw it and\n * never finished\".\n *\n * The claim is a **mutex, not a decision**: the platform records\n * that this credential is working on the message and refuses a\n * second live claim by another credential of the same account. It\n * does not judge whether the mail matters and does not act on it.\n *\n * ```ts\n * await fm.messages.claim(event.messageId, { domainId });\n * // …process…\n * await fm.messages.complete(event.messageId, { domainId, state: \"done\" });\n * ```\n *\n * @throws {ValidationError} when `messageId` or `domainId` is\n * missing.\n */\n claim: async (messageId: string, opts: ClaimMessageOptions) => {\n if (!messageId) {\n throw new ValidationError(\"message_id_required\", \"messageId is required\");\n }\n if (!opts?.domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n return this.request<MessageState>(\n this.platformURL,\n \"POST\",\n `/api/agent/messages/${encodeURIComponent(messageId)}/claim`,\n { body: { domainId: opts.domainId, claimedBy: opts.claimedBy } },\n );\n },\n\n /**\n * Record how a message turned out.\n *\n * `done` or `failed`, optionally with labels and a note. The\n * platform stores what the agent said and takes no further action\n * on it.\n *\n * @throws {ValidationError} when `messageId`, `domainId` or\n * `state` is missing, or `state` is neither `done` nor `failed`.\n */\n complete: async (messageId: string, opts: CompleteMessageOptions) => {\n if (!messageId) {\n throw new ValidationError(\"message_id_required\", \"messageId is required\");\n }\n if (!opts?.domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n if (opts.state !== \"done\" && opts.state !== \"failed\") {\n throw new ValidationError(\n \"invalid_state\",\n \"state must be 'done' or 'failed'\",\n );\n }\n return this.request<MessageState>(\n this.platformURL,\n \"POST\",\n `/api/agent/messages/${encodeURIComponent(messageId)}/complete`,\n {\n body: {\n domainId: opts.domainId,\n state: opts.state,\n labels: opts.labels,\n note: opts.note,\n },\n },\n );\n },\n\n /**\n * Look back through the mailbox.\n *\n * The event log is the primary listen path; this is the history\n * path. A hit carries addressing, the subject and a preview — the\n * body is a separate, explicit ask.\n */\n search: async (domainId: string, opts: SearchMessagesOptions) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n if (!opts?.q || opts.q.trim().length < 2) {\n throw new ValidationError(\n \"query_too_short\",\n \"q must be at least 2 characters\",\n );\n }\n return this.request<SearchMessagesResult>(\n this.platformURL,\n \"GET\",\n \"/api/agent/emails/search\",\n {\n query: {\n q: opts.q,\n domainId,\n limit: opts.limit,\n field: opts.field,\n type: opts.type,\n },\n },\n );\n },\n\n /**\n * Read the agent's own per-message state back.\n *\n * The state belongs to the **calling credential** — the platform\n * stores it under a fingerprint of the bearer — so a sibling\n * credential of the same tenant does not read it by accident.\n * `domainId` is required because the state is scoped to the\n * domain whose mailbox received the message.\n */\n listStates: async (\n domainId: string,\n opts: ListMessageStatesOptions = {},\n ) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n if (opts.state !== undefined && !MESSAGE_STATE_NAMES.includes(opts.state)) {\n throw new ValidationError(\n \"invalid_state\",\n `state must be one of: ${MESSAGE_STATE_NAMES.join(\", \")}`,\n );\n }\n return this.request<ListMessageStatesResult>(\n this.platformURL,\n \"GET\",\n \"/api/agent/message-states\",\n {\n query: {\n domainId,\n state: opts.state,\n messageId: opts.messageId,\n limit: opts.limit,\n },\n },\n );\n },\n };\n\n /**\n * The conversation a message belongs to.\n *\n * The core listen/reply loop can store the message ids itself;\n * this is for the agent that wants the platform to reconstruct the\n * chain. The chain is read from the **conversation root's** SMTP\n * `Message-ID`, which is exactly what `email.threadId` holds.\n */\n readonly threads: AgentThreads = {\n get: async (threadId: string, opts: { domainId?: string } = {}) => {\n if (!threadId) {\n throw new ValidationError(\"thread_id_required\", \"threadId is required\");\n }\n return this.request<ThreadDetail>(\n this.platformURL,\n \"GET\",\n `/api/agent/threads/${encodeURIComponent(threadId)}`,\n { query: { domainId: opts.domainId } },\n );\n },\n };\n\n /**\n * The draft queue — a message written for a **person** to review.\n *\n * Nothing here sends. `create` writes a `pending_review` row and\n * `list` / `get` report what a reviewer did with it. A human\n * approves it in the dashboard, and the approval is the send — so\n * the platform's audited send path, quota and domain rules apply\n * unchanged.\n *\n * ```ts\n * const draft = await fm.drafts.create({ from, to, subject, text });\n * const queue = await fm.drafts.list({ status: \"pending_review\" });\n * ```\n */\n readonly drafts: AgentDrafts = {\n create: async (opts: CreateDraftOptions) => {\n if (!opts?.from) {\n throw new ValidationError(\"from_required\", \"from is required\");\n }\n if (!opts.to || (Array.isArray(opts.to) && opts.to.length === 0)) {\n throw new ValidationError(\"to_required\", \"to is required\");\n }\n if (!opts.subject) {\n throw new ValidationError(\"subject_required\", \"subject is required\");\n }\n if (!opts.useAiContext && !opts.text && !opts.html) {\n throw new ValidationError(\n \"body_required\",\n \"text or html is required, unless useAiContext is set\",\n );\n }\n if (opts.useAiContext && !opts.replyToMessageId) {\n throw new ValidationError(\n \"reply_parent_required\",\n \"useAiContext requires replyToMessageId\",\n );\n }\n return this.request<EmailDraft>(\n this.platformURL,\n \"POST\",\n \"/api/agent/drafts\",\n { body: opts },\n );\n },\n\n list: async (opts: ListDraftsOptions = {}) => {\n if (opts.status !== undefined && !DRAFT_STATUS_NAMES.includes(opts.status)) {\n throw new ValidationError(\n \"invalid_status\",\n `status must be one of: ${DRAFT_STATUS_NAMES.join(\", \")}`,\n );\n }\n return this.request<ListDraftsResult>(\n this.platformURL,\n \"GET\",\n \"/api/agent/drafts\",\n {\n query: {\n status: opts.status,\n domainId: opts.domainId,\n limit: opts.limit,\n },\n },\n );\n },\n\n get: async (draftId: string) => {\n if (!draftId) {\n throw new ValidationError(\"draft_id_required\", \"draftId is required\");\n }\n return this.request<EmailDraft>(\n this.platformURL,\n \"GET\",\n `/api/agent/drafts/${encodeURIComponent(draftId)}`,\n );\n },\n };\n\n /**\n * The durable wait — the one thing an agent cannot build for\n * itself.\n *\n * A suspended HTTP request dies on the edge long before a\n * verification mail arrives (minutes to hours later), so the wait\n * is a row on the platform and the agent polls it. `create()`\n * answers **immediately**; it does not block.\n */\n readonly waits: AgentWaits = {\n create: async (opts: CreateWaitOptions) => {\n return this.request<CreateWaitResult>(\n this.platformURL,\n \"POST\",\n \"/api/agent/waits\",\n { body: opts },\n );\n },\n get: async (waitId: string) => {\n if (!waitId) {\n throw new ValidationError(\"wait_id_required\", \"waitId is required\");\n }\n return this.request<WaitStatus>(\n this.platformURL,\n \"GET\",\n `/api/agent/waits/${encodeURIComponent(waitId)}`,\n );\n },\n };\n\n /**\n * The addresses (mailboxes) the key's account owns, and the one\n * narrow write the agent surface has: create a single one.\n */\n readonly addresses: AgentAddresses = {\n listDomains: async () => {\n const result = await this.request<{ domains: AgentDomain[] }>(\n this.platformURL,\n \"GET\",\n \"/api/agent/domains\",\n );\n return result.domains;\n },\n list: async (domainId: string) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n const result = await this.request<{\n domainId: string;\n domain: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n addresses: string[];\n acceptsAnyLocalPart: boolean;\n }>(\n this.platformURL,\n \"GET\",\n `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,\n );\n return result;\n },\n create: async (domainId: string, localPart: string) => {\n if (!domainId) {\n throw new ValidationError(\"domain_id_required\", \"domainId is required\");\n }\n return this.request<CreateAddressResult>(\n this.platformURL,\n \"POST\",\n `/api/agent/domains/${encodeURIComponent(domainId)}/addresses`,\n { body: { localPart } },\n );\n },\n };\n\n /**\n * Private: the one request path, with retry + backoff + error\n * mapping shared by every public method.\n *\n * `origin` is explicit because the surface spans two deployments:\n * the SDK backend (`baseURL`) for sending, the platform\n * (`platformURL`) for reading and waiting. `method` is explicit\n * because the listen endpoints are GETs — the v0.1 helper was\n * POST-only, which is why reading used to mean hand-rolling HTTP.\n */\n private async request<T>(\n origin: string,\n method: \"GET\" | \"POST\",\n path: string,\n opts: {\n body?: unknown;\n query?: Record<string, string | number | undefined>;\n } = {},\n ): Promise<T> {\n const url = buildUrl(origin, path, opts.query);\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n };\n // A GET carries no body, and sending `Content-Type: application/json`\n // with one would be a lie some proxies act on.\n if (method === \"POST\") headers[\"Content-Type\"] = \"application/json\";\n if (this.requestId) headers[\"X-Flowmails-Request-Id\"] = this.requestId;\n\n let lastError: FlowmailsError | null = null;\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method,\n headers,\n ...(method === \"POST\" ? { body: JSON.stringify(opts.body) } : {}),\n // 15s matches the platform's upstream timeout — we want our\n // error to be \"request timed out\" rather than a generic 502.\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n lastError = new UpstreamError(\n \"network_error\",\n err instanceof Error ? err.message : undefined,\n 0,\n );\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // 2xx — happy path. Decode and return.\n if (res.ok) {\n return (await res.json()) as T;\n }\n\n // Non-2xx — render to a typed error.\n let payload: {\n error?: string;\n detail?: string;\n reason?: string;\n limit?: number;\n remaining?: number;\n resetAt?: string;\n [key: string]: unknown;\n } = {};\n try {\n payload = (await res.json()) as typeof payload;\n } catch {\n // Body wasn't JSON; fall back to status-based error.\n }\n\n const code = payload.error ?? \"request_failed\";\n\n if (res.status === 401) throw new AuthenticationError(code, res.status);\n if (\n res.status === 400 ||\n res.status === 404 ||\n res.status === 422 ||\n res.status === 409\n ) {\n // 409 carries the non-retryable configuration conflicts:\n // an idempotency key reused for a **different** payload, a\n // credential with no tenant scope (`domain_scope_missing`),\n // and `sending_not_configured` (the bound domain has no\n // outbound provider). All are client/configuration bugs, not\n // transient failures — a retry would send the same wrong\n // thing again.\n //\n // The body's other fields travel with the error: the claim\n // conflict names the credential holding the message\n // (`claimedBy` / `claimedAt`), and a caller that cannot see\n // them cannot tell \"another worker took it\" from a bug.\n throw new ValidationError(\n code,\n payload.detail,\n res.status,\n readErrorExtra(payload),\n );\n }\n if (res.status === 429) {\n // Two different 429s, and they need different handling:\n //\n // - `idempotency_key_in_progress` — the *same* request is\n // already running. Retrying it is exactly right, and it\n // replays the first attempt's answer.\n // - `rate_limit_exceeded` — the quota window is exhausted. A\n // retry inside the same window cannot succeed and would\n // only burn another slot, so it is **not** retried; the\n // error carries `resetAt` so the caller can wait for the\n // window instead of guessing.\n const facts = readQuotaFacts(res, payload);\n if (code === \"idempotency_key_in_progress\") {\n lastError = new RateLimitError(code, res.status, facts);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n throw new RateLimitError(code, res.status, facts);\n }\n if (res.status >= 500 || res.status === 408) {\n lastError = new UpstreamError(code, payload.detail, res.status);\n if (attempt >= this.maxRetries) throw lastError;\n await sleep(backoffMs(attempt));\n continue;\n }\n\n // Anything else: not retryable, throw immediately.\n throw new FlowmailsError(code, `Request failed: ${code}`, res.status);\n }\n\n // Shouldn't reach here — last iteration always throws. Type\n // assertion keeps the compiler happy without `any`.\n throw lastError ?? new FlowmailsError(\"unknown\", \"Unknown failure\", 0);\n }\n}\n\n/**\n * The draft namespace — see {@link Flowmails.drafts}.\n *\n * Three operations and no sending: a draft is a message a **person**\n * approves, which is why this namespace has no `send`.\n */\nexport interface AgentDrafts {\n create(opts: CreateDraftOptions): Promise<EmailDraft>;\n list(opts?: ListDraftsOptions): Promise<ListDraftsResult>;\n get(draftId: string): Promise<EmailDraft>;\n}\n\n/**\n * The event log namespace — see {@link Flowmails.events}.\n */\nexport interface AgentEvents {\n /**\n * One page of the log, oldest first, after `opts.after`.\n *\n * The cursor is an **event id**, never a timestamp: two events can\n * land in the same millisecond, and a cursor that can skip a row\n * loses mail. An unknown cursor is a `ValidationError`, never an\n * empty page — \"no new events\" would silently stop the agent\n * seeing mail.\n */\n list(opts?: ListEventsOptions): Promise<ListEventsResult>;\n}\n\n/**\n * The message-read namespace — see {@link Flowmails.messages}.\n */\n/**\n * Options for {@link AgentMessages.get}.\n *\n * `format` trades bytes for fidelity: `\"full\"` (the default) returns the raw\n * HTML beside the plain text, `\"markdown\"` omits `html` and returns the\n * Markdown projection instead. Both modes carry `markdown` and `extracted`\n * when the message has them.\n */\nexport interface GetMessageOptions {\n /** Which of the account's domains to look in. */\n domainId?: string;\n /** `full` (default) or `markdown`. An unknown value is a `400`. */\n format?: \"full\" | \"markdown\";\n}\n\n/**\n * One attachment, read as text.\n *\n * An attachment with no text representation — an image, an encrypted PDF, a\n * scanned page — answers `supported: false` with a stable `reason`. That is\n * an answer, not an error: branch on `supported` instead of retrying.\n */\nexport interface AttachmentText {\n supported: boolean;\n /**\n * A stable slug when `supported` is false: `attachment_too_large`,\n * `unsupported_format`, `encrypted_pdf`, `suspicious_compression`,\n * `no_text`, `corrupt_attachment`.\n */\n reason: string | null;\n filename: string | null;\n mimeType: string | null;\n sizeBytes: number;\n /** The extracted text; `null` when unsupported. Untrusted input. */\n text: string | null;\n /** `true` when the text was cut at 64 KiB. */\n truncated: boolean;\n}\n\nexport interface AgentMessages {\n /** Fetch the full content of one message by SMTP `Message-ID`. */\n get(\n messageId: string,\n opts?: GetMessageOptions,\n ): Promise<MessageDetail>;\n\n /**\n * `get_attachment_text`: read one attachment as text.\n *\n * `attachmentId` is the value in `attachments[].id` of a\n * {@link AgentMessages.get} answer. Plain text, CSV, Markdown, HTML,\n * JSON, XML, `.docx` and PDF are supported; anything else answers\n * `supported: false` with a reason.\n *\n * ```ts\n * const message = await fm.messages.get(event.messageId, { format: \"markdown\" });\n * const file = await fm.messages.attachmentText(\n * event.messageId,\n * message.attachments[0].id,\n * );\n * if (file.supported) console.log(file.text);\n * ```\n */\n attachmentText(\n messageId: string,\n attachmentId: string,\n opts?: { domainId?: string },\n ): Promise<AttachmentText>;\n /** Poll a sent message's delivery state by row id or `Message-ID`. */\n status(id: string): Promise<SendStatus>;\n /**\n * `claim_message`: take a message for processing.\n *\n * The platform records that this credential is working on the\n * message now — a **mutex**, so two workers of the same account do\n * not process the same message at once. It does not judge the mail\n * and does not act on it.\n *\n * @throws {ValidationError} when `messageId` or `domainId` is\n * missing.\n */\n claim(\n messageId: string,\n opts: ClaimMessageOptions,\n ): Promise<MessageState>;\n /**\n * `complete_message`: record the outcome (`done` or `failed`).\n *\n * The platform stores what the agent said and takes no further\n * action on it.\n *\n * @throws {ValidationError} when `messageId`, `domainId` or\n * `state` is missing, or `state` is neither `done` nor `failed`.\n */\n complete(\n messageId: string,\n opts: CompleteMessageOptions,\n ): Promise<MessageState>;\n /**\n * `search_emails`: look **back** through the mailbox.\n *\n * The event log is the primary listen path — a cursor over what\n * just arrived. Search is the history path: \"what did that\n * supplier mail me last quarter?\" is not an event-log question,\n * and the event log carries no body.\n *\n * A result carries addressing, the subject and a short **preview**;\n * the body is fetched per message with {@link AgentMessages.get},\n * so a search is never a way to pull the whole mailbox through a\n * query parameter.\n */\n search(\n domainId: string,\n opts: SearchMessagesOptions,\n ): Promise<SearchMessagesResult>;\n /**\n * `list_message_states`: read the agent's **own** record back.\n *\n * The event log says a mail arrived; the claim and the completion\n * say what this agent did with it. This is the third half — the\n * read — and it is what makes the other two useful: an agent that\n * restarted reads it back to tell \"I never saw this\" from \"I saw\n * it and never finished\".\n *\n * Two facts the caller must know:\n *\n * - **The rows belong to the calling credential.** The platform\n * stores the state under a fingerprint of the bearer, so another\n * credential of the same tenant does not read them by accident.\n * - **`domainId` is required.** The state is scoped to the domain\n * whose mailbox received the message.\n *\n * ```ts\n * const { states } = await fm.messages.listStates(domainId, {\n * state: \"processing\",\n * });\n * ```\n *\n * @throws {ValidationError} when `domainId` is missing, or `state`\n * is not one of the four names.\n */\n listStates(\n domainId: string,\n opts?: ListMessageStatesOptions,\n ): Promise<ListMessageStatesResult>;\n}\n\n/**\n * The conversation namespace — see {@link Flowmails.threads}.\n */\nexport interface AgentThreads {\n /**\n * Read the conversation a message belongs to.\n *\n * `threadId` is the conversation **root's** SMTP `Message-ID` —\n * the value `email.threadId` holds, never an intermediate parent's.\n * An agent that holds an intermediate message id still gets the\n * whole chain: the platform resolves it to its row and reads the\n * chain from that row's own anchor.\n */\n get(threadId: string, opts?: { domainId?: string }): Promise<ThreadDetail>;\n}\n\n/**\n * The durable-wait namespace — see {@link Flowmails.waits}.\n */\nexport interface AgentWaits {\n /** Open a wait. Answers immediately; poll {@link AgentWaits.get}. */\n create(opts: CreateWaitOptions): Promise<CreateWaitResult>;\n /** Read a wait. A wait past its deadline reads as `expired`. */\n get(waitId: string): Promise<WaitStatus>;\n}\n\n/**\n * The address namespace — see {@link Flowmails.addresses}.\n */\nexport interface AgentAddresses {\n /** `list_domains`: every domain on the key's account. */\n listDomains(): Promise<AgentDomain[]>;\n /** `list_addresses`: one domain's local parts and routing mode. */\n list(domainId: string): Promise<{\n domainId: string;\n domain: string;\n routingMode: \"catchall\" | \"rules\";\n localParts: string[];\n addresses: string[];\n /** True when every local part already delivers (catch-all mode). */\n acceptsAnyLocalPart: boolean;\n }>;\n /**\n * `create_address`: add **one** local part.\n *\n * Idempotent — creating an address that already exists answers\n * with `created: false` rather than an error. It never changes the\n * routing mode, never removes a part and never clears the table:\n * mode changes and route-table editing stay dashboard-only.\n */\n create(domainId: string, localPart: string): Promise<CreateAddressResult>;\n}\n\n/**\n * A sent message's delivery state.\n *\n * `status` is the receive worker's lifecycle literal, so an agent can\n * distinguish \"the relay took it\" from \"the recipient's server\n * accepted it\" from \"it bounced\" — the v0.1 SDK collapsed all of them\n * into `\"queued\"` and dropped the relay's `Message-ID` with them.\n */\nexport interface SendStatus {\n /** The worker's row id. */\n id: string;\n /**\n * `sent` (the relay accepted it) or `failed` (the relay rejected it)\n * — those are the two the receive worker writes for an outbound\n * message today.\n *\n * The vocabulary also holds `delivered` / `bounced` / `complained` /\n * `delayed`, and the backend maps them if they appear, but the\n * worker has no DSN or bounce ingestion and never writes them. **A\n * bounce is not observable today.**\n */\n status: string;\n /** The SMTP `Message-ID`; empty when the relay never accepted it. */\n messageId: string;\n /**\n * The relay's error string when `status` is `failed`, else null.\n *\n * The same reason the send response carries — read from the same\n * column on the same worker.\n */\n sendFeedback: string | null;\n /**\n * The typed failure slug (`\"send_failed\"`) when `status` is\n * `failed`, else `null`.\n *\n * Optional: an older backend does not send it. When it is present,\n * a `failed` status always carries one — \"failed with no reason\" is\n * not a state the wire can be in.\n */\n error?: string | null;\n /** `CURRENT_TIMESTAMP` from the worker; opaque to the SDK. */\n createdAt: string | null;\n}\n\n// ---------- Module-level helpers ----------\n\n/**\n * Read the quota facts off a rate-limited response.\n *\n * The body is the source of truth (`limit` / `remaining` / `resetAt`);\n * the headers are the fallback, because something in front of the\n * backend may strip the body but not the headers.\n *\n * `X-Flowmails-RateLimit-Reset` is epoch **seconds** (the HTTP\n * convention); the body's `resetAt` is ISO-8601. The header is\n * converted so both end up in the same shape on the error.\n */\nfunction readQuotaFacts(\n res: Response,\n payload: { limit?: number; remaining?: number; resetAt?: string },\n): { limit?: number; remaining?: number; resetAt?: string } | undefined {\n const limit =\n typeof payload.limit === \"number\" ? payload.limit : undefined;\n let remaining =\n typeof payload.remaining === \"number\" ? payload.remaining : undefined;\n let resetAt =\n typeof payload.resetAt === \"string\" ? payload.resetAt : undefined;\n\n const headerRemaining = res.headers?.get?.(\n \"X-Flowmails-RateLimit-Remaining\",\n );\n if (remaining === undefined && headerRemaining) {\n const parsed = Number(headerRemaining);\n if (Number.isFinite(parsed)) remaining = parsed;\n }\n\n const headerReset = res.headers?.get?.(\"X-Flowmails-RateLimit-Reset\");\n if (resetAt === undefined && headerReset) {\n const parsed = Number(headerReset);\n if (Number.isFinite(parsed)) {\n resetAt = new Date(parsed * 1000).toISOString();\n }\n }\n\n if (limit === undefined && remaining === undefined && resetAt === undefined) {\n return undefined;\n }\n return { limit, remaining, resetAt };\n}\n\n/**\n * The fields of an error body beyond the code and the detail.\n *\n * The platform's error envelope is `{ error, detail? }` plus whatever\n * the route knows: a claim conflict adds `claimedBy` / `claimedAt`, a\n * quota refusal adds `limit` / `remaining` / `resetAt`. Those are facts\n * a caller branches on, so they must not be dropped when the body is\n * turned into a typed error.\n */\nfunction readErrorExtra(\n payload: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const extra: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(payload)) {\n if (key === \"error\" || key === \"detail\") continue;\n extra[key] = value;\n }\n return Object.keys(extra).length > 0 ? extra : undefined;\n}\n\n/**\n * Compose a request URL, dropping undefined / empty query values.\n *\n * An absent filter must not travel as `?subject=undefined` or as an\n * empty `?subject=` — the platform treats an empty string as a real\n * filter value in some places, so \"not asked for\" and \"asked for the\n * empty string\" have to stay distinguishable on the wire.\n */\nfunction buildUrl(\n origin: string,\n path: string,\n query?: Record<string, string | number | undefined>,\n): string {\n const url = new URL(`${origin}${path}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null || value === \"\") continue;\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Browser-safe base64 of a `Uint8Array`. Avoids pulling in a\n // Buffer polyfill in the worker / browser bundles.\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++) {\n bin += String.fromCharCode(bytes[i]);\n }\n return btoa(bin);\n}\n\nfunction backoffMs(attempt: number): number {\n // Exponential backoff with jitter, capped at 4 s. attempt 0 → 250 ms.\n const base = Math.min(250 * 2 ** attempt, 4_000);\n return base + Math.floor(Math.random() * base);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}"]}
|