← All @molecule/* packages · App templates

@molecule/api-emails-inbound-agentmail

Provider bond · emails-inbound · API (Node) · v1.0.0 · Apache-2.0

AgentMail inbound email provider for agent inboxes

npm install @molecule/api-emails-inbound-agentmail

npm · Source on GitHub · Implements @molecule/api-emails-inbound

How it works

@molecule/api-emails-inbound-agentmail is a provider bond on the API (Node) side: it implements the emails-inbound core interface (@molecule/api-emails-inbound) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

import { setProvider } from '@molecule/api-emails-inbound'
import { provider as agentMailInbound } from '@molecule/api-emails-inbound-agentmail'

setProvider(agentMailInbound)

Works with: @molecule/api-emails-inbound, @molecule/api-secrets

Secrets: AGENTMAIL_API_KEY, AGENTMAIL_WEBHOOK_SECRET, AGENTMAIL_INBOX_ID (optional)

Reference

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

AgentMail inbound-email provider for molecule.dev.

Implements @molecule/api-emails-inbound's InboundEmailProvider interface against AgentMail's message.received webhook. Verifies the Svix signature headers (svix-id / svix-timestamp / svix-signature, HMAC-SHA256 over id.timestamp.body keyed by the whsec_ secret) with replay protection, normalizes the JSON payload, hydrates through the AgentMail API what the webhook leaves out (attachment bytes; bodies over the 1 MB cap), and replies through AgentMail's own reply endpoint. Built on the global fetch — no SDK.

Quick Start

import { setProvider } from '@molecule/api-emails-inbound'
import { provider as agentMailInbound } from '@molecule/api-emails-inbound-agentmail'

setProvider(agentMailInbound)

Type

provider

Installation

npm install @molecule/api-emails-inbound-agentmail @molecule/api-emails-inbound @molecule/api-secrets

API

Interfaces

AgentMailAttachmentDownload

Response of GET /v0/inboxes/{inbox_id}/messages/{message_id}/attachments/{attachment_id}: the attachment's metadata plus a presigned, time-limited download_url from which the raw bytes are fetched.

interface AgentMailAttachmentDownload extends AgentMailAttachmentMeta {
  /** Presigned URL serving the raw attachment bytes (no auth header needed). */
  download_url: string
  /** When `download_url` stops working. */
  expires_at?: string
}

AgentMailAttachmentMeta

Attachment METADATA as carried by a webhook payload or a GET message response. The bytes are never inline — see {@link AgentMailAttachmentDownload}.

interface AgentMailAttachmentMeta {
  /** AgentMail's identifier for the attachment. */
  attachment_id: string
  /** Size of the attachment in bytes. */
  size: number
  /** Original filename, when the sender supplied one. */
  filename?: string
  /** MIME type, when known. */
  content_type?: string
  /** `inline` for `cid:`-referenced parts, `attachment` otherwise. */
  content_disposition?: 'inline' | 'attachment'
  /** Content-ID for inline parts referenced from the HTML body. */
  content_id?: string
}

AgentMailErrorBody

AgentMail's error envelope.

interface AgentMailErrorBody {
  /** Legacy error type name (e.g. `NotFoundError`). */
  name?: string
  /** Machine-readable error code (e.g. `unknown_api_key`, `rate_limit_exceeded`). */
  code?: string
  /** Human-readable description. */
  message?: string
  /** Concrete remediation steps, when AgentMail supplied them. */
  fix?: string
  /** Link to the error's documentation. */
  docs?: string
}

AgentMailMessage

An AgentMail message as it appears in a message.received webhook payload and in the GET message response (same schema).

message_id is the RFC 5322 Message-ID, INCLUDING its angle brackets (<abc@agentmail.to>); AgentMail uses that exact string as the path parameter of every per-message endpoint.

interface AgentMailMessage {
  /** Opaque id of the inbox that received the message (NOT its address). */
  inbox_id: string
  /** Opaque id of the conversation thread. */
  thread_id?: string
  /** RFC 5322 Message-ID, with angle brackets. */
  message_id: string
  /** AgentMail labels, e.g. `['received']`. */
  labels?: string[]
  /** ISO 8601 time AgentMail received the message. */
  timestamp?: string
  /**
   * Sender mailbox (`Alice <alice@example.com>`). The API reference spells
   * this `from`; the webhooks guide's example spells it `from_` — both are
   * documented, so both are read.
   */
  from?: string
  /** Alternate documented spelling of {@link AgentMailMessage.from}. */
  from_?: string
  /** `To:` recipients. */
  to?: string[]
  /** `Cc:` recipients. */
  cc?: string[]
  /** `Bcc:` recipients. */
  bcc?: string[]
  /** `Reply-To:` addresses. */
  reply_to?: string[]
  /** Subject line. */
  subject?: string
  /** Short body preview. */
  preview?: string
  /**
   * Plain-text body. Omitted (together with `html`) when the webhook payload
   * would exceed AgentMail's 1 MB cap — fetch the message via the API then.
   */
  text?: string
  /** HTML body. Omitted under the same 1 MB rule as `text`. */
  html?: string
  /** Attachment metadata only — bytes come from the attachment endpoint. */
  attachments?: AgentMailAttachmentMeta[]
  /** `In-Reply-To` header value, with angle brackets. */
  in_reply_to?: string
  /** `References` header values, with angle brackets. */
  references?: string[]
  /** Raw message headers as a name → value map. */
  headers?: Record<string, string>
  /** Message size in bytes. */
  size?: number
  /** ISO 8601 creation time. */
  created_at?: string
  /** ISO 8601 last-update time. */
  updated_at?: string
}

AgentMailReplyAttachment

One attachment in an {@link AgentMailReplyRequest}.

interface AgentMailReplyAttachment {
  /** Filename shown to the recipient. */
  filename?: string
  /** MIME type. */
  content_type?: string
  /** `inline` for `cid:`-referenced parts. */
  content_disposition?: 'inline' | 'attachment'
  /** Content-ID for inline parts. */
  content_id?: string
  /** Base64-encoded attachment bytes. */
  content?: string
}

AgentMailReplyRequest

Request body of POST /v0/inboxes/{inbox_id}/messages/{message_id}/reply. Every field is optional on the wire; AgentMail threads the reply itself (there is no subject — the original's is reused).

interface AgentMailReplyRequest {
  /** Recipient(s). */
  to?: string | string[]
  /** CC recipient(s). */
  cc?: string | string[]
  /** BCC recipient(s). */
  bcc?: string | string[]
  /** Reply-To address(es). */
  reply_to?: string | string[]
  /** Plain-text body. */
  text?: string
  /** HTML body. */
  html?: string
  /** Attachments; `content` is the base64-encoded payload. */
  attachments?: AgentMailReplyAttachment[]
  /** Custom message headers. */
  headers?: Record<string, string>
  /** Message labels. */
  labels?: string[]
}

AgentMailReplyResponse

Response of the reply endpoint.

interface AgentMailReplyResponse {
  /** Message-ID of the created reply. */
  message_id: string
  /** Thread the reply belongs to. */
  thread_id?: string
}

AgentMailWebhookEvent

Top-level shape of an AgentMail webhook delivery for the message.received* event family.

interface AgentMailWebhookEvent {
  /** Always `event`. */
  type?: string
  /**
   * `message.received`, `message.received.spam`,
   * `message.received.blocked`, or `message.received.unauthenticated`.
   */
  event_type: string
  /** Unique id of this event. */
  event_id?: string
  /** The received message. */
  message: AgentMailMessage
}

InboundEmail

A normalized inbound email, produced by parsing a provider webhook payload through {@link InboundEmailProvider.parseWebhookPayload}.

All providers (Mailgun Routes, SES Inbound, fixtures, etc.) return this same shape so handler code can treat inbound mail uniformly. Provider specifics (raw MIME, signing tokens, etc.) MUST NOT leak into this type.

interface InboundEmail {
  /**
   * Stable provider-supplied identifier for the message. Used for
   * deduplication when the same webhook is retried.
   */
  id: string
  /**
   * Sender address (RFC 5322 mailbox), e.g. `'alice@example.com'`.
   */
  from: string
  /**
   * Primary recipient addresses (the values from the `To:` header).
   */
  to: string[]
  /**
   * Carbon-copy recipient addresses, if present.
   */
  cc?: string[]
  /**
   * Subject line, decoded to a plain string. May be empty.
   */
  subject: string
  /**
   * Plain-text body of the message, if present.
   */
  textBody?: string
  /**
   * HTML body of the message, if present.
   */
  htmlBody?: string
  /**
   * Decoded attachments. An empty array when the message has none.
   */
  attachments?: InboundEmailAttachment[]
  /**
   * All headers from the raw message, lowercased keys to canonicalize the
   * many capitalizations that mail servers use. Multi-value headers
   * (`Received:`, etc.) are joined with newlines or returned as arrays at
   * provider discretion — see provider docs.
   */
  headers: Record<string, string | string[]>
  /**
   * Server-side timestamp the inbound provider received the message.
   */
  receivedAt: Date
  /**
   * Optional `Message-ID` header value for threading. Surfaced separately
   * from {@link headers} because helpdesk handlers almost always need it.
   */
  messageId?: string
  /**
   * Optional `In-Reply-To` header value for threading replies into an
   * existing ticket.
   */
  inReplyTo?: string
  /**
   * Optional `References` header values for threading.
   */
  references?: string[]
}

InboundEmailAttachment

A binary attachment carried by an inbound email.

Providers normalize whatever multipart/MIME representation they receive into this neutral shape. The body is base64-encoded so the type is JSON-serializable across IPC, queue, and webhook boundaries.

interface InboundEmailAttachment {
  /**
   * The original filename as supplied by the sender, or a provider-derived
   * fallback when the sender omitted one.
   */
  name: string
  /**
   * MIME type of the attachment (e.g. `'application/pdf'`, `'image/png'`).
   * Defaults to `'application/octet-stream'` when the provider cannot
   * determine the type.
   */
  contentType: string
  /**
   * Attachment payload, base64-encoded.
   */
  contentBase64: string
  /**
   * Optional size hint in bytes of the decoded payload. Providers MAY set
   * this from upstream headers without decoding the payload themselves.
   */
  sizeBytes?: number
  /**
   * Optional Content-ID, used for inline images referenced from the HTML
   * body via `cid:` URLs.
   */
  contentId?: string
}

InboundEmailProvider

Inbound-email provider interface.

Implementations (Mailgun Routes, SES Inbound, etc.) live in separate bond packages (@molecule/api-emails-inbound-mailgun-routes, @molecule/api-emails-inbound-ses). The interface is deliberately minimal: a webhook arrives at the host application's HTTP layer, the raw headers and body are handed to the provider, and the provider returns a normalized {@link InboundEmail}.

Signature verification is mandatory for any provider that runs against a public webhook endpoint; {@link verifySignature} is the hook for that. Providers without signed webhooks SHOULD return false rather than true so callers can decide whether to accept unsigned mail.

interface InboundEmailProvider {
  /**
   * Parses the raw webhook payload (HTTP headers + body) into a
   * normalized {@link InboundEmail}.
   *
   * @param headers - HTTP request headers received by the webhook
   *   endpoint. Lowercased keys are recommended but not required;
   *   implementations MUST handle either casing.
   * @param body - Raw HTTP request body. May be a `Buffer` (e.g. from a
   *   raw body parser), a `string`, or an already-parsed object provided
   *   by an upstream JSON middleware.
   * @returns The normalized inbound email.
   */
  parseWebhookPayload(
    headers: Record<string, string | string[] | undefined>,
    body: Buffer | string | Record<string, unknown>,
  ): Promise<InboundEmail>
  /**
   * Verifies the signature of a webhook request, using whatever scheme
   * the provider exposes (Mailgun HMAC, SES SNS subscription
   * confirmation, etc.). Implementations MUST be constant-time when
   * comparing secrets.
   *
   * A genuinely invalid webhook (forged, stale, malformed, tampered
   * signature) resolves `false` — that is the normal, expected failure
   * path and callers map it to a `401`. Implementations MAY instead THROW
   * a tagged configuration error (e.g. via `configNotConfiguredError()`
   * from `@molecule/api-secrets`) when the provider itself is
   * misconfigured — for example a missing signing key/secret. This is a
   * DISTINCT failure class from a `false` return: a misconfigured server
   * is not the same problem as a forged request, and collapsing both into
   * the same `false` makes a broken deployment indistinguishable from an
   * attack, with no trace either way. `@molecule/api-emails-inbound-mailgun`
   * follows this pattern — `verifySignature` throws the tagged
   * `config.notConfigured` error when `MAILGUN_API_KEY` is unset, and
   * resolves `false` for every other verification failure.
   *
   * @param headers - HTTP request headers received by the webhook
   *   endpoint.
   * @param body - Raw HTTP request body. Implementations that need the
   *   exact bytes (e.g. for HMAC) MUST be passed a `Buffer`.
   * @returns `true` when the signature is valid, `false` for an
   *   invalid/forged/stale/malformed webhook.
   * @throws {Error} Implementations MAY throw a tagged configuration error
   *   when the provider is missing required configuration (e.g. an unset
   *   signing key) — a server misconfiguration, not an invalid request.
   * @example
   * ```typescript
   * // In an HTTP handler bound to the inbound webhook URL:
   * const ok = await verifySignature(req.headers, req.rawBody)
   * if (!ok) return res.status(401).end()
   * // A thrown configuration error (server misconfigured) is deliberately
   * // NOT caught above — do not wrap this call in a try/catch that maps
   * // every failure to the same 401. Let it propagate to standard error
   * // middleware, which maps a tagged config error to a 503, distinct
   * // from the 401 an invalid/forged webhook gets.
   * ```
   */
  verifySignature(
    headers: Record<string, string | string[] | undefined>,
    body: Buffer | string,
  ): Promise<boolean>
  /**
   * Optional: dispatches an outbound reply through the provider's own
   * reply mechanism. Providers that do not support reply dispatch (e.g.
   * pure inbound-only adapters) SHOULD omit this method; callers MUST
   * use {@link InboundEmailProvider.supportsReply} to detect support.
   *
   * @param email - The original inbound email being replied to.
   * @param reply - The reply payload.
   * @returns Result of the dispatch.
   */
  replyTo?(email: InboundEmail, reply: InboundEmailReply): Promise<InboundEmailReplyResult>
  /**
   * Indicates whether the provider supports outbound reply dispatch via
   * {@link replyTo}. Implementations SHOULD return a stable `true` /
   * `false` based on their own configuration; the property is a function
   * so providers can defer to runtime configuration if needed.
   *
   * @returns `true` when {@link replyTo} is implemented and ready to use.
   */
  supportsReply(): boolean
}

InboundEmailReply

Outgoing reply produced by handler code in response to an {@link InboundEmail}. Providers that support the optional {@link InboundEmailProvider.replyTo} method translate this into whatever outbound mechanism their upstream offers (Mailgun reply route, SES SendEmail, etc.).

For providers that do NOT expose an outbound reply path, handler code SHOULD fall back to the regular @molecule/api-emails outbound bond.

interface InboundEmailReply {
  /**
   * Subject line for the outbound reply. If omitted, providers SHOULD
   * default to the original subject prefixed with `'Re: '` (locale-aware
   * prefixing is the caller's responsibility).
   */
  subject?: string
  /**
   * Plain-text body of the reply, if any.
   */
  textBody?: string
  /**
   * HTML body of the reply, if any.
   */
  htmlBody?: string
  /**
   * Attachments to send with the reply.
   */
  attachments?: InboundEmailAttachment[]
  /**
   * Optional override for the `From:` address. Defaults to the address
   * the original message was sent to (the inbound mailbox).
   */
  from?: string
  /**
   * Optional additional headers to set on the outbound message.
   */
  headers?: Record<string, string>
}

InboundEmailReplyResult

Result of a successful reply dispatch via {@link InboundEmailProvider.replyTo}.

interface InboundEmailReplyResult {
  /**
   * Provider-supplied identifier for the dispatched outbound message.
   */
  id: string
}

Classes

AgentMailApiError

A non-2xx response from the AgentMail API, carrying the documented error envelope's code / name / fix and — for 429 — the Retry-After delay. The message never includes the API key.

Functions

_resetInboxMemo()

Clears the in-process inbox record. Exposed for tests.

function _resetInboxMemo(): void

agentMailRequest(method, path, body)

Performs one authenticated JSON call against the AgentMail API.

function agentMailRequest(method: 'GET' | 'POST', path: string, body?: unknown): Promise<T>
  • method — HTTP method.
  • path — Path under the base URL (must start with /).
  • body — Optional JSON request body.

Returns: The parsed JSON response.

bodyToString(body)

Coerces the request body into a UTF-8 string. Buffers are decoded as UTF-8 (AgentMail POSTs application/json), strings are returned as-is.

function bodyToString(body: string | Buffer<ArrayBufferLike>): string
  • body — The raw body.

Returns: The body as a UTF-8 string.

buildSignedContent(id, timestamp, body)

Builds the exact bytes Svix signs: ${id}.${timestamp}. followed by the raw request body, unchanged. Returned as a Buffer so a body that is not valid UTF-8 still signs byte-for-byte.

function buildSignedContent(
  id: string,
  timestamp: string,
  body: string | Buffer<ArrayBufferLike>,
): Buffer<ArrayBufferLike>
  • id — The svix-id header value.
  • timestamp — The svix-timestamp header value (as received).
  • body — The raw request body.

Returns: The signed content.

decodeWebhookSecret(secret)

Decodes a Svix-style signing secret into raw key bytes: strip the whsec_ prefix, then base64-decode the remainder. A secret without the prefix is base64-decoded as-is (the Svix libraries do the same).

function decodeWebhookSecret(secret: string): Buffer<ArrayBufferLike>
  • secret — The signing secret as configured.

Returns: The HMAC key bytes (empty when the secret decodes to nothing).

downloadAttachment(inboxId, messageId, attachmentId)

Downloads an attachment's bytes: resolves the presigned download_url via {@link getAttachmentDownload}, then GETs it. The presigned request deliberately carries NO Authorization header — the URL is self- authenticating, and object stores reject a request that presents two auth mechanisms at once.

function downloadAttachment(
  inboxId: string,
  messageId: string,
  attachmentId: string,
): Promise<{ meta: AgentMailAttachmentDownload; content: Buffer }>
  • inboxId — The inbox id.
  • messageId — The message id, exactly as AgentMail supplied it.
  • attachmentId — The attachment id from the message's metadata.

Returns: The metadata and the raw bytes.

getApiKey()

Reads the AgentMail API key from the environment, throwing the tagged config.notConfigured error (never revealing any value) when unset.

function getApiKey(): string

Returns: The API key.

getAttachmentDownload(inboxId, messageId, attachmentId)

Fetches an attachment's metadata + presigned download_url.

function getAttachmentDownload(
  inboxId: string,
  messageId: string,
  attachmentId: string,
): Promise<AgentMailAttachmentDownload>
  • inboxId — The inbox id.
  • messageId — The message id, exactly as AgentMail supplied it.
  • attachmentId — The attachment id from the message's metadata.

Returns: The attachment metadata and download URL.

getBaseUrl()

Resolves the API base URL: AGENTMAIL_BASE_URL when set (trailing slashes stripped), else {@link DEFAULT_BASE_URL}.

function getBaseUrl(): string

Returns: The base URL without a trailing slash.

getHeader(headers, name)

Returns the value of headers[name] (case-insensitive) coerced to a single string.

function getHeader(
  headers: Record<string, string | string[] | undefined>,
  name: string,
): string | undefined
  • headers — The headers object.
  • name — The header name (case-insensitive).

Returns: The header value as a single string, or undefined if absent.

getMessage(inboxId, messageId)

Fetches a full message — used to hydrate text / html when the webhook payload omitted them (AgentMail drops both once the payload would exceed 1 MB).

function getMessage(inboxId: string, messageId: string): Promise<AgentMailMessage>
  • inboxId — The inbox id.
  • messageId — The message id, exactly as AgentMail supplied it.

Returns: The message.

headerToString(value)

Coerces an HTTP header value (which may be string, string[], or undefined) to a single string. Multi-value headers are joined with , per RFC 9110 §5.2.

function headerToString(value: string | string[] | undefined): string | undefined
  • value — The header value to coerce.

Returns: The header value as a single string, or undefined when the header was not present.

isRecord(value)

Narrowing guard for a plain JSON object.

function isRecord(value: unknown): boolean
  • value — Any value.

Returns: true when value is a non-null, non-array object.

lowercaseHeaderMap(value)

Recovers the core's normalized headers map (lowercased names, multi-value headers as arrays) from AgentMail's headers object. Any non-string value is skipped; a missing or malformed map yields {}.

function lowercaseHeaderMap(value: unknown): Record<string, string | string[]>
  • value — The raw headers field.

Returns: Normalized headers map.

messagePath(inboxId, messageId)

Path of a message resource. Both ids are URL-encoded — AgentMail's message_id is the RFC 5322 Message-ID INCLUDING angle brackets and @.

function messagePath(inboxId: string, messageId: string): string
  • inboxId — The inbox id.
  • messageId — The message id, exactly as AgentMail supplied it.

Returns: /v0/inboxes/{inbox_id}/messages/{message_id}.

normalizeAddressList(value)

Normalizes an address field that AgentMail types as string in one place and string[] in another into a trimmed, non-empty string array.

function normalizeAddressList(value: unknown): string[]
  • value — The raw field value.

Returns: The addresses (empty when the field is absent or malformed).

parseJsonBody(body)

Parses a JSON request body. Accepts the raw bytes/string of the request or an already-parsed object (Express's JSON middleware gives us the latter when a JSON route captures the webhook).

function parseJsonBody(body: string | Buffer<ArrayBufferLike> | Record<string, unknown>): unknown
  • body — Raw body or pre-parsed object.

Returns: The parsed JSON value.

parseRetryAfterSeconds(value)

Parses a Retry-After header, which is equally valid as delta-seconds ('30') or an HTTP-date, into whole seconds from now.

function parseRetryAfterSeconds(value: string | null | undefined): number | undefined
  • value — The raw header value.

Returns: Seconds to wait (never negative), or undefined when absent or unparseable.

parseSignatureHeader(value)

Splits a svix-signature header — a space-delimited list of <version>,<base64> entries (e.g. v1,abc v1,def) — into the v1 signatures. Entries of any other version are ignored, not rejected: Svix may add versions and a receiver is expected to match on any one it understands.

function parseSignatureHeader(value: string | undefined): string[]
  • value — The raw header value.

Returns: The base64 v1 signatures (empty when none are present).

parseTimestamp(value)

Parses an ISO 8601 timestamp into a Date.

function parseTimestamp(value: unknown): Date | undefined
  • value — The raw field value.

Returns: The date, or undefined when absent or unparseable.

parseWebhookPayload(_headers, body)

Parses an AgentMail message.received webhook payload into a normalized {@link InboundEmail}, hydrating through the API whatever the webhook left out:

  • Bodies. When BOTH text and html are absent (AgentMail drops them once the payload would exceed 1 MB), the message is fetched via GET /v0/inboxes/{inbox_id}/messages/{message_id}.
  • Attachments. The webhook carries metadata only; each attachment's bytes are downloaded (metadata → presigned URL → bytes).

Either needs AGENTMAIL_API_KEY; a message that needs neither makes no network call at all. When AGENTMAIL_INBOX_ID is set, an event for any other inbox is rejected.

id is AgentMail's message_id VERBATIM (the Message-ID with its angle brackets — the exact string every per-message endpoint takes as its path parameter); messageId is the same value without the brackets, for threading headers. Both are stable across Svix redeliveries, so dedupe on id.

function parseWebhookPayload(
  _headers: Record<string, string | string[] | undefined>,
  body: string | Buffer<ArrayBufferLike> | Record<string, unknown>,
): Promise<InboundEmail>
  • _headers — HTTP headers (unused — AgentMail puts everything in the body).
  • body — The raw JSON body, a string, or an already-parsed object.

Returns: The normalized inbound email.

replyTo(email, reply)

Dispatches a reply through AgentMail's reply endpoint from the inbox that received the original message. AgentMail threads the reply itself (In-Reply-To, References, subject), so reply.subject and reply.from have no effect — the reply always comes from the inbox, under the original subject.

function replyTo(email: InboundEmail, reply: InboundEmailReply): Promise<InboundEmailReplyResult>
  • email — The original inbound email being replied to.
  • reply — The reply payload.

Returns: The reply dispatch result (id = the new message's Message-ID).

replyToMessage(inboxId, messageId, body)

Sends a reply to a message from the inbox that received it. AgentMail threads the reply (In-Reply-To / References / subject) itself.

function replyToMessage(
  inboxId: string,
  messageId: string,
  body: AgentMailReplyRequest,
): Promise<AgentMailReplyResponse>
  • inboxId — The inbox id.
  • messageId — The message id, exactly as AgentMail supplied it.
  • body — The reply.

Returns: The created message's ids.

safeEqualBase64(a, b)

Constant-time comparison of two base64-encoded digests.

function safeEqualBase64(a: string, b: string): boolean
  • a — The first digest.
  • b — The second digest.

Returns: true when the decoded bytes are equal.

supportsReply()

Indicates that this provider supports outbound reply dispatch via {@link replyTo}. Replies use AgentMail's own API — no outbound @molecule/api-emails transport is involved.

function supportsReply(): boolean

Returns: Always true.

unwrapMessageId(value)

Strips surrounding angle brackets from a Message-ID value.

function unwrapMessageId(value: unknown): string | undefined
  • value — The raw value (with or without angle brackets).

Returns: The value without angle brackets, or undefined if input was empty or not a string.

verifySignature(headers, body)

Verifies an AgentMail (Svix) webhook signature: HMAC-SHA256 over ${svix-id}.${svix-timestamp}.${rawBody} keyed by the base64-decoded whsec_ secret, base64-encoded, matched against ANY v1,… entry of the svix-signature header in constant time. The Standard-Webhooks aliases webhook-id / webhook-timestamp / webhook-signature are accepted too. Timestamps outside the replay window are rejected.

body MUST be the exact bytes received — a parsed-then-re-serialized JSON body will not verify.

Distinguishes SERVER MISCONFIGURATION from a genuinely invalid webhook: an unset AGENTMAIL_WEBHOOK_SECRET THROWS the tagged config.notConfigured error (mapped by the API error middleware to a clean 503) instead of returning false. Missing signature headers, a stale timestamp and a tampered signature all resolve false (401) — those ARE the "this request is not from AgentMail" class.

function verifySignature(
  headers: Record<string, string | string[] | undefined>,
  body: string | Buffer<ArrayBufferLike>,
): Promise<boolean>
  • headers — HTTP headers; the three svix-* signing headers.
  • body — Raw HTTP request body (JSON bytes, unchanged).

Returns: true when the signature verifies and the timestamp is fresh; false for a malformed/stale/forged webhook.

Constants

agentMailInboundSecretDefinitions

Secret definitions required by the AgentMail inbound-email bond.

const agentMailInboundSecretDefinitions: SecretDefinition[]

API_REQUEST_TIMEOUT_MS

Timeout (ms) for a JSON API call. Bounds a hanging AgentMail endpoint so the webhook handler fails (and AgentMail retries) instead of stalling.

const API_REQUEST_TIMEOUT_MS: 15000

ATTACHMENT_DOWNLOAD_TIMEOUT_MS

Timeout (ms) for downloading one attachment's bytes from its presigned URL. Larger than {@link API_REQUEST_TIMEOUT_MS} because it moves the attachment payload, not a small JSON document.

const ATTACHMENT_DOWNLOAD_TIMEOUT_MS: 60000

DEFAULT_BASE_URL

Default AgentMail API base URL (production).

const DEFAULT_BASE_URL: 'https://api.agentmail.to'

DEFAULT_REPLAY_WINDOW_SECONDS

Default replay window for inbound webhook timestamps, in seconds.

AgentMail delivers webhooks through Svix, whose documented default tolerance for svix-timestamp is five minutes.

const DEFAULT_REPLAY_WINDOW_SECONDS: 300

provider

The AgentMail inbound-email provider implementing the {@link InboundEmailProvider} interface.

const provider: InboundEmailProvider

SIGNATURE_VERSION

The only signature-scheme version this bond understands.

const SIGNATURE_VERSION: 'v1'

WEBHOOK_SECRET_PREFIX

Prefix Svix puts on webhook signing secrets before the base64 key.

const WEBHOOK_SECRET_PREFIX: 'whsec_'

Core Interface

Implements @molecule/api-emails-inbound interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setProvider } from '@molecule/api-emails-inbound'
import { provider } from '@molecule/api-emails-inbound-agentmail'

export function setupEmailsInboundAgentmail(): void {
  setProvider(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-emails-inbound ^1.0.1
  • @molecule/api-secrets ^1.0.1

Environment Variables

  • AGENTMAIL_API_KEY (required) — AgentMail API key
    • Setup: AgentMail console → API keys. The key must have access to the inbox that receives mail.
    • Get it here: https://console.agentmail.to
    • Example: am_...
  • AGENTMAIL_WEBHOOK_SECRET (required) — AgentMail webhook signing secret
  • AGENTMAIL_INBOX_ID (optional) — Inbox id
    • Setup: Optional: the inbox replies are sent from when the webhook payload does not carry one.
    • Get it here: https://console.agentmail.to
    • Example: inbox_...

Runtime Dependencies

  • @molecule/api-emails-inbound

  • @molecule/api-secrets

  • The webhook route is PUBLIC and needs the RAW body. Mount it outside any auth middleware and hand verifySignature() the exact bytes received — express.raw({ type: 'application/json' }) on that route, or the body-parser bond's req.rawBody. A body that went through express.json() and was re-stringified will NOT verify.

  • Nothing arrives until BOTH exist at AgentMail: the inbox (POST /v0/inboxes) and a webhook registered for it (POST /v0/webhooks with url + event_types: ['message.received'], optionally scoped by inbox_ids). The create-webhook response's secret IS AGENTMAIL_WEBHOOK_SECRET. Subscribe this URL to message.received* only — any other event type (message.sent, message.bounced, …) makes parseWebhookPayload() throw.

  • verifySignature() THROWS the tagged config.notConfigured error (→ 503 via the API error middleware) when AGENTMAIL_WEBHOOK_SECRET is unset, and resolves false for a missing/stale/forged signature. Let the throw propagate — mapping it to the same 401 as a forged webhook hides a misconfigured server behind "invalid signature".

  • parseWebhookPayload() may call the AgentMail API. Attachments arrive as metadata only and are downloaded (metadata → presigned download_url → bytes); when both text and html are missing (the 1 MB payload cap) the message is fetched. Both need AGENTMAIL_API_KEY (tagged config error if unset) and count against AgentMail's per-key rate limit. A 429 surfaces as an AgentMailApiError with retryAfterSeconds — let it propagate as a 5xx so AgentMail redelivers later; never swallow it into a 200, which loses the mail. A message with bodies and no attachments makes no network call.

  • Replies use AgentMail's reply endpoint, not @molecule/api-emails. The reply is sent from the inbox that received the message and AgentMail threads it itself, so reply.subject and reply.from are ignored. The inbox is resolved from AGENTMAIL_INBOX_ID, else from the in-process record parseWebhookPayload() kept — set AGENTMAIL_INBOX_ID whenever a reply is sent from a later request or after a restart. When set it also makes parseWebhookPayload() reject events for any other inbox.

  • InboundEmail.id is AgentMail's message_id verbatim — the Message-ID INCLUDING angle brackets, which is also the path parameter of every per-message endpoint; messageId is the same value without brackets. Dedupe on id.

  • The sender field is documented under two spellings (from in the API reference, from_ in the webhooks guide); both are read.

E2E Tests

Integration checklist — drive the real inbound endpoint (live preview, no mocks), adapt each item to this app's actual inbox/ticket/thread flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip. COUNTERPARTY: the app can't receive a real email in the sandbox, so YOU play the mail provider — POST a realistic inbound-email webhook to the app's inbound endpoint with sandbox_fetch (curl runs inside the container). Model the payload on the BONDED provider's real format (Mailgun: form fields sender/recipient/subject/body-plain/body-html/ attachment-N plus the timestamp/token/signature triple; SES/Postmark: their JSON), and the happy-path POST must carry a VALID signature — compute it the way the provider does (Mailgun signs HMAC-SHA256 of timestamp+token with MAILGUN_API_KEY inside the replay window; read the key from the Environment panel / .env.molecule). Never disable verifySignature() or mock parseWebhookPayload() to go green — that proves nothing.

  • A signed sample webhook to the inbound endpoint parses into the normalized fields (from / to / subject / textBody / htmlBody) AND the app ACTS on it — it files the mail into the right place (creates a ticket, a comment on a thread, or a reply-thread) keyed off the recipient (support@) or a plus-address / thread token (reply+<id>@). Verify the CREATED record (a DB row, and it shows up in the UI) — not just a 200.
  • Routing is correct: an email to support@ opens a NEW ticket, while reply+<id>@ (or an In-Reply-To / References match) threads onto the EXISTING one — each lands in the right user's / conversation's place, never a stranger's.
  • Attachments survive: an inbound message with an attachment has it decoded from attachments[].contentBase64 and stored on the app's OWN storage (the uploads bond), not left as a provider link — the stored file opens from the ticket.
  • Retries don't duplicate: re-POST the SAME webhook (providers retry slow / 5xx deliveries) and confirm handling is idempotent — one ticket, not two (dedupe on id / messageId).
  • Malformed / empty payloads (missing body-plain, no attachments, absent headers) are handled without a crash — a clean response, not a 500 stack trace.
  • SECURITY — the endpoint is AUTHENTICATED: a forged POST with a bad or missing signature (or a timestamp outside the replay window) is REJECTED (401) and creates NO record, so an attacker can't inject mail into another user's thread. A missing signing key is a DISTINCT 503, not a 401 — a server misconfig must not masquerade as an accepted or forged webhook.
  • SECURITY — the parsed htmlBody is sanitized before it is rendered anywhere: a <script> / onerror= in an inbound body must NOT execute when the ticket is viewed (no stored XSS from an inbound email body).