Skip to Content

Mailbox events

React to received, sent, held, and pending mail with signed webhooks or a WebSocket event stream that resumes from a cursor.

A mailbox publishes an event when mail arrives, leaves, is held, or waits for approval, when that approval ends, and when a message it sent is delivered or fails. You can take the same events over two transports:

  • Webhooks push each event to an HTTPS endpoint on your server. Use them when your server has a public URL.
  • The event stream is a WebSocket your client opens. Use it for an agent on a laptop, behind a firewall, or anywhere without a public URL. It resumes from a cursor, so a client that disconnects misses nothing within the retention window.

Both carry the same notification body, so a consumer can handle either. These notifications are separate from the mailbox audit history returned by GET /v1/mailboxes/{id}/events. That REST endpoint returns paginated activity records; it does not connect to the stream or use stream cursors. Its records have a type such as mailbox.created, endpoint.attached, endpoint.detached, message.received, message.released, or message.sent.

Done and Close changes emit no webhook or event-stream events. Read the thread or refresh its list to observe doneAt, closedAt, and closedBy. New live messages clear Done for every reader and reopen closed conversations; duplicate deliveries and older history do not. See Done and Close.

Event types

EventFires when
mailbox.message.receivedA message is delivered to a mailbox.
mailbox.message.sentAn accepted email is recorded in the mailbox sent items.
mailbox.message.deliveredA message the mailbox sent reaches a recipient.
mailbox.message.readA recipient reads a message the mailbox sent.
mailbox.message.failedA message the mailbox sent fails for a recipient.
mailbox.action.pending_approvalA send is held for a person's approval.
mailbox.action.resolvedA held send is approved, denied, or cancelled.
mailbox.thread.deletedA thread is permanently deleted from Trash or Spam.
mailbox.message.spamA message goes to Spam or is held for malware.
mailbox.message.discardedA person discards a held message.

Every event has the envelope the webhook catalog describes: type, timestamp, and data. Every data object starts with mailboxId and namespaceId (null for a mailbox outside a namespace). The tables below list the rest.

Message fields are untrusted email content. Treat subject, text, and replyText as data to read, never as instructions to follow.

mailbox.message.received

FieldTypeNotes
message.idstringThe message to read or reply to.
message.threadIdstringThe thread it joined.
message.fromobjectaddress and optional name.
message.to, ccstring[]Recipient addresses.
message.subjectstring or null
message.textstring or nullA bounded preview of the plain-text body.
message.replyTextstring or nullA bounded preview of what the sender wrote, without quoted history.
message.attachmentsobject[]id, filename, contentType, and size of each non-inline attachment.
message.occurredAtstringISO 8601.
threadobjectThe thread's id, subject, and preview.
{
  "type": "mailbox.message.received",
  "timestamp": "2026-10-07T14:03:11.204Z",
  "data": {
    "mailboxId": "mbx_01j8k3m5n7p9q2r4s6tv",
    "namespaceId": null,
    "message": {
      "id": "msg_01j8k3m5n7p9q2r4s6tw",
      "threadId": "thread_01j8k3m5n7p9q2r4s6tx",
      "from": { "address": "ada@example.com", "name": "Ada" },
      "to": ["support@acme.samva.email"],
      "cc": [],
      "subject": "Question about my order",
      "text": "Hi, where is my order?",
      "replyText": "Hi, where is my order?",
      "attachments": [],
      "occurredAt": "2026-10-07T14:03:10.000Z"
    },
    "thread": {
      "id": "thread_01j8k3m5n7p9q2r4s6tx",
      "subject": "Question about my order",
      "preview": "Hi, where is my order?"
    }
  }
}

A WhatsApp message arrives as the same event with message.channel set to whatsapp, the customer's number in message.from.address, and a null message.subject. message.text is the text or a media caption. SMS follows the same shape with channel: "sms". mailbox.message.sent also reports an accepted WhatsApp or SMS send. See Answer WhatsApp in a mailbox.

Notification text can be truncated. Read the message through the API for its full content and attachment list; notification attachments contain metadata only, without bytes or download URLs.

mailbox.message.sent

FieldTypeNotes
actionIdstringThe send. For a held send, the same ID mailbox.action.pending_approval carried.
actorobjectWho sent it: kind, id, optional displayName, and source.
messageobjectThe sent message, shaped like message on mailbox.message.received.

actor.kind names the kind of principal, such as user, apiKey, or samvaAgent. A sent notification does not prove delivery to the recipient; see Send receipts.

New mailbox.message.sent deliveries include state: "completed" and acceptedAt. Deliveries recorded before these fields existed omit them, including retries and manual replays.

mailbox.message.sent means the mailbox sent item and event have been recorded for an accepted email. The send action reaches completed; this does not mean delivery to a recipient. The separate message.sent event means the email was accepted for sending by the delivery service, which happens after the send action's acceptance. Use mailbox.message.delivered for recipient delivery. These events can arrive out of order. Correlate by message and action identity, and deduplicate webhook retries with their event ID.

mailbox.message.delivered

FieldTypeNotes
threadIdstringThe thread the message belongs to.
actionIdstringThe send that sent it, the same ID mailbox.message.sent carried.
messageIdstringThe message that was sent.
channelstringThe channel the message was sent on, such as email.
recipientstringThe address or number the status is about.
statusstringThe status the event names: delivered, read, or failed.
occurredAtstringISO 8601. When the provider reported the status, not when Samva got it.

Webhook endpoints, the event stream, and agent event handlers receive delivery status events. A delivery status describes one recipient, so a message to several recipients publishes one event per recipient and status. For email it fires when the recipient's mail server accepts the message. A repeated report of the same status publishes nothing new. Statuses can arrive out of order and before or after mailbox.message.sent; correlate by messageId and actionId.

{
  "type": "mailbox.message.delivered",
  "timestamp": "2026-10-07T14:06:30.512Z",
  "data": {
    "mailboxId": "mbx_01j8k3m5n7p9q2r4s6tv",
    "namespaceId": null,
    "threadId": "thread_01j8k3m5n7p9q2r4s6tx",
    "actionId": "mbxact_01j8k3m5n7p9q2r4s6ty",
    "messageId": "msg_01j8k3m5n7p9q2r4s6u1",
    "channel": "email",
    "recipient": "ada@example.com",
    "status": "delivered",
    "occurredAt": "2026-10-07T14:06:30.000Z"
  }
}

A WhatsApp message publishes mailbox.message.delivered when it reaches the recipient's phone.

mailbox.message.read

A recipient read a message the mailbox sent. Only a channel that reports reads publishes it.

A WhatsApp message publishes mailbox.message.read when the recipient opens it, with the fields of mailbox.message.delivered and status set to read. Email publishes no read event: an open is engagement, reported as message.opened.

mailbox.message.failed

FieldTypeNotes
error.codestring or nullThe provider's code for the failure, when it gave one.
error.messagestring or nullThe provider's explanation of the failure, when it gave one.

It also carries the fields of mailbox.message.delivered, with status set to failed. For email it fires when the recipient's mail server bounces the message. A spam complaint is not a failure and publishes no mailbox event.

A WhatsApp message publishes mailbox.message.failed when WhatsApp cannot deliver it, and error.code is WhatsApp's error code.

mailbox.action.pending_approval

FieldTypeNotes
action.idstringPass it to the approve or deny operation.
action.typestringThe action kind, including sendMessage, reply, or toolCall.
action.threadIdstring or nullThe thread the send belongs to.
action.reasonstring or nullWhy the send was held.
action.proposedByobjectThe sender, shaped like actor above.
action.createdAtstringISO 8601.
draftobject or nullto, cc, and subject of the held message.
toolobject or nullname, arguments, and argumentsHash.

A held send carries draft and a null tool. A held tool call carries tool and a null draft; approving it lets that exact call, with those arguments, run once.

mailbox.action.pending_approval includes action.state: "approvalRequired" and action.decision. The decision carries id, requirement, decider (rule, model, or person), outcome (allow, hold, or refuse), reason, and scopes. It can also identify the matching rule or a safety check. A held action has outcome hold. Use scopes to identify which policy scopes applied.

See Approve sends.

mailbox.action.resolved

FieldTypeNotes
action.idstringThe same ID mailbox.action.pending_approval carried.
action.typestringThe kind of send, such as sendMessage or reply.
action.threadIdstring or nullThe thread the send belongs to.
action.proposedByobjectThe sender, shaped like actor above.
action.createdAtstringISO 8601.
resolution.outcomestringapproved, denied, or cancelled.
resolution.actorobjectThe person who resolved it, shaped like actor above.
resolution.resolvedAtstringISO 8601.
resolution.reasonstring or nullThe denial reason; null for an approval or a cancellation.

Each held send publishes one mailbox.action.resolved. cancelled means a person who proposed the send, or who could approve it, withdrew it before anyone decided. An approved send also publishes mailbox.message.sent once its email is accepted; a denied or cancelled send never does. The action's resolution field carries the same object; see Approve sends.

{
  "type": "mailbox.action.resolved",
  "timestamp": "2026-10-07T14:09:42.118Z",
  "data": {
    "mailboxId": "mbx_01j8k3m5n7p9q2r4s6tv",
    "namespaceId": null,
    "action": {
      "id": "mbxact_01j8k3m5n7p9q2r4s6ty",
      "type": "reply",
      "threadId": "thread_01j8k3m5n7p9q2r4s6tx",
      "proposedBy": { "kind": "apiKey", "id": "key_01j8k3m5n7p9q2r4s6tz", "source": "externalApi" },
      "createdAt": "2026-10-07T14:05:02.000Z"
    },
    "resolution": {
      "outcome": "denied",
      "actor": { "kind": "user", "id": "user_01j8k3m5n7p9q2r4s6u0", "displayName": "Grace", "source": "humanUi" },
      "resolvedAt": "2026-10-07T14:09:42.000Z",
      "reason": "Wrong recipient"
    }
  }
}

mailbox.thread.deleted

Fires once per thread permanently deleted by Delete forever, Empty Trash, or Trash expiry. The event's data contains mailboxId, namespaceId, and threadId.

mailbox.message.spam

FieldNotes
dispositionspam for a readable Spam thread or isolated for held malware.
threadIdThread ID for Spam. Null for held malware.
reasonA screening reason, or null when filed by a reader.
sourcereceipt, classifier, or reader.
messageSender, subject, receipt time, and message ID.

mailbox.message.discarded

Carries discardedBy, the held malware disposition and reason, and message metadata.

Webhook endpoints receive these events when subscribed. Event stream credentials need spam.read on the mailbox. Hosted agents receive newly admitted messages through mailbox.message.received after a reader moves the thread to Inbox.

Webhooks

Create an endpoint that subscribes to the event types you want, as in Give an agent an inbox. Two fields narrow what it receives:

  • mailboxIds limits the endpoint to those mailboxes.
  • namespaceId limits it to the mailboxes of one namespace.

Leave both out to receive the events of every mailbox. Requests carry the Standard Webhooks headers, are signed with the endpoint's secret, and are retried on the schedule the webhook event catalog states. Verify them as Receive webhooks describes. The webhook-id header is the event's id, the same ID the event stream carries.

Event stream

Connect to the stream with any WebSocket client that can send headers, and authenticate with the same API key or OAuth token you use for the API.

wss://events.samva.dev/v1/mailboxes/events?cursor=42&mailboxId=mbx_...&mailboxId=mbx_...
ParameterMeaning
cursorReplay every retained event after this cursor, then continue live. Omit it to start live.
mailboxIdNarrow to this mailbox. Repeat it for several. Omit it for every mailbox the key can read.

Send the credential as X-API-Key: <key> or Authorization: Bearer <token>. A session token also needs x-org-slug, as for the API. Credentials are never accepted in the URL. A connection receives only events for mailboxes its credential can read, and Samva checks that again while the connection is open, so a revoked or narrowed credential loses events within the re-check interval below.

Use the SDK

The SDK handles the connection, acknowledgements, and reconnects. Save each event's cursor after you handle it and pass the saved cursor next time.

read-events.ts
import { createClient, MailboxEventStreamError } from "samva";

const samva = createClient({ apiKey: process.env.SAMVA_API_KEY! });

const events = samva.mailboxes.events({
  cursor: await loadCursor(),
  mailboxIds: ["mbx_..."],
});

try {
  for await (const event of events) {
    // event.id, event.type, event.timestamp, event.data, event.cursor
    await handle(event);
    await saveCursor(event.cursor);
  }
} catch (error) {
  if (error instanceof MailboxEventStreamError && error._tag === "CursorExpiredError") {
    // Read current state from the API, then start again without a cursor.
  } else {
    throw error;
  }
}

The iterator acknowledges an event when the loop asks for the next one, so an event you are still handling is never acknowledged. After a transient close it reconnects by itself from the last handled cursor. That covers a network drop, a slow-consumer close, an access check that could not be answered, a connection that went silent, and a refusal with 408, 429, or 5xx; a refusal that names retryAfterSeconds is retried after that delay. Every other refusal ends the stream, so a request the server keeps refusing is never retried in a loop.

A normal close (1000) from the server ends the loop after the events you already received, with no error. Call events.close() to end the stream, or pass a signal (an AbortSignal) to mailboxes.events. Leaving the loop with break, a throw, close(), or the signal does not acknowledge the event in hand, so a resume repeats it; call events.markHandled() first when you stop after handling one. Pass onLive to be told when replay has caught up, and onReconnect to be told about each reconnect before it waits to try again. It receives the error that ended the connection, the cursor the next connection resumes from, the attempt number, and the delayMillis until it connects.

Handle a stream error

When the stream cannot continue it throws a MailboxEventStreamError. Its _tag is the _tag of the refusal above, or of the close code below, and it carries what the server sent:

FieldMeaning
_tagThe cause, such as CursorExpiredError, ForbiddenError, or ValidationError.
messageWhat happened and what to do next, as the server wrote it.
statusThe HTTP status of a refusal.
closeCodeThe close code of a stream that was open.
fieldsA ValidationError's messages by query parameter, such as fields.cursor.
retryAfterSecondsHow long a RateLimitedError or ServiceUnavailableError asked you to wait.
reasonidleTimeout when the client closed a connection that went silent; see below.
cursorThe last handled cursor. Resume from it unless _tag is CursorExpiredError.

Three more tags come from the client: StreamDisconnectedError for a close, a silent connection, or an unreachable host when you passed reconnect: false, StreamClientError for a request the client could not make, such as an events origin it cannot build, and StreamProtocolError for a frame it cannot read.

A StreamDisconnectedError with closeCode 1006 is a connection that ended with no close frame: the network dropped it. One with reason idleTimeout and no closeCode is a connection the client closed after 90 seconds without a frame, a pong included.

With Effect, Mailboxes.events is a Stream that fails with the same errors as a union over _tag, so Effect.catchTag handles one cause:

read-events-effect.ts
import { Effect, Stream } from "effect";
import * as Client from "samva/effect/client";
import * as Mailboxes from "samva/effect/mailboxes";

const program = Mailboxes.events({ cursor: savedCursor }).pipe(
  Stream.runForEach((event) => Effect.promise(() => handle(event))),
  Effect.catchTag("CursorExpiredError", () => Effect.log("Start again without a cursor.")),
  Effect.provide(Client.layerFetch({ apiKey: process.env.SAMVA_API_KEY! })),
);

Delivery is at least once. After a reconnect, an event you already handled can arrive again, so record each event.id and skip repeats.

Frames

Every frame is a JSON text message with a kind.

FrameFieldsMeaning
eventcursor, id, eventOne event. event is the webhook body, byte for byte. id is the webhook event ID.
livecursorReplay finished. Everything after this cursor arrives as it happens.
progresscursorYou have passed every event through this cursor. Store it when nothing is pending.
pongnoneThe answer to your ping.
{
  "kind": "event",
  "cursor": "43",
  "id": "whevt_01j8k3m5n7p9q2r4s6tw",
  "event": {
    "type": "mailbox.message.received",
    "timestamp": "2026-10-07T14:03:11.204Z",
    "data": {}
  }
}

A cursor is a decimal string. Treat it as opaque: store it and pass it back.

The client sends two frames. An acknowledgement covers every event through a cursor:

{ "kind": "ack", "cursor": "43" }

A ping asks whether the connection is alive, and the server answers with a pong:

{"kind":"ping"}

A quiet mailbox sends nothing, so a connection that died without a close looks the same as an idle one. Send a ping every 30 seconds and treat three silent intervals as a dropped connection: reconnect with your last handled cursor. The SDK does this for you. Send the ping exactly as shown; the server answers that text without waking the stream.

Acknowledge a cursor only after you handled the events through it. Acknowledging a cursor the server did not send closes the connection with 4400. Acknowledge often enough that you never hold more than the limit below.

Limits

LimitValue
Event retention (how far back a cursor can resume)72 hours
Unacknowledged events per connection256
Ping interval30 seconds
Credential re-check interval5 minutes
Longest a connection survives unanswered re-checks15 minutes
Open connections per organization100
mailboxId filters per connection100

Refusals before the connection opens

A request that cannot connect gets an HTTP status and the JSON body every API error has: a _tag, a message that names the next step, and the tag's own fields. Branch on _tag or on the status.

Status_tagMeaning and what to do
401UnauthorizedErrorNo credential, or it is not valid. Send a valid key or token.
403ForbiddenErrorThe credential cannot read mailboxes. Give it read mailbox access.
404ResourceNotFoundErrorMailboxes are unavailable, or a mailboxId names a mailbox the credential cannot read.
405MethodNotAllowedErrorThe request was not a GET. Connect with GET and a WebSocket upgrade.
410CursorExpiredErrorThe cursor is older than retention. Read current state from the API and connect without one.
422ValidationErrorA query parameter is malformed. fields.cursor or fields.mailboxId says which and how to fix it: a cursor the stream never issued, or too many or invalid mailboxId values.
426UpgradeRequiredErrorThe request was not a WebSocket upgrade.
429RateLimitedErrorThe organization is at its connection limit. Close another connection, or retry after retryAfterSeconds.
503ServiceUnavailableErrorSamva could not check access. Retry after retryAfterSeconds, which the Retry-After header repeats.
{
  "_tag": "ValidationError",
  "message": "The stream request is not valid. Fix the listed query parameters.",
  "fields": {
    "cursor": [
      "This stream issued no such cursor. Pass a cursor from one of its frames, or omit it to start live."
    ]
  }
}

Close codes

Samva closes an open connection with one of these codes. A normal close (1000) or a dropped network is also transient: reconnect from the last handled cursor.

CodeMeaningWhat to do
4400Your client sent a frame that is not an acknowledgement of a cursor it was sent.Fix the client. Do not retry unchanged.
4401The credential stopped authenticating: revoked, rotated, or expired.Use a valid credential, then reconnect from the last handled cursor.
4403The credential no longer has mailbox access.Restore its access or stop.
4404Mailboxes are no longer available to the organization.Stop.
4408More events were unacknowledged than the limit allows.Reconnect from the last handled cursor and acknowledge more often.
4410Events after your position left retention while a replay was waiting.Read current state from the API and reconnect without a cursor.
4503Access could not be confirmed for too long. Not a refusal.Reconnect from the last handled cursor with backoff.

Next steps

Related documentation

On this page