# Inbox — messages

`inbox.messages.*` · see [connection.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/connection.md) first

| Action | Event | Scope |
|---|---|---|
| `list` | `message.list` | `messages:read` |
| `get` | `message.fetch` | `messages:read` |
| `send` | `message.send` | `messages:write` |
| `delete` | `message.delete` | `messages:write` |
| `retryDownload` | `message.retry_download` | `messages:write` |

## The message shape

```ts
interface Message<C extends MessageContent = MessageContent, X = JsonObject> {
  id: string;
  contact: string;
  channel: string;              // id only: channels live in another service
  content: C;                   // open; see below
  context: X;                   // replied-to id, forwarding, CTWA referral
  identifier: string;           // the contact's identity on this channel
  message_id: string;           // the provider's id, unique per account
  status: 'received' | 'sent' | 'delivered' | 'read' | 'failed';
  timestamp: number;            // unix seconds, as the provider reported it
  direction: 'inbound' | 'outbound';
  source: 'contact' | 'agent' | 'bot' | 'campaign' | 'api' | 'business_app';
  sent_by_api: boolean;
  sent_by_biz_app: boolean;
  sent_by_campaign: boolean;
  sent_by_bot: boolean;
  agent: string | null;
  receipts: { sent; read; failed; replied; received; delivered };  // unix seconds, 0 = not yet
  meta: { bookmarked: boolean; hide: boolean };
  campaign: { id: string | null; cmid: number };
  bot: { id: string | null; node: string };
  error: string;
  createdAt: string;
  updatedAt: string;
}
```

### direction and source are derived

The stored document has no direction field: `received` is the only inbound state,
and the sender is encoded as four booleans where an agent send is the *absence*
of all of them. `direction` and `source` are computed for you so no consumer has
to re-derive that. The raw flags are still there if you need them.

| `status` | `sent_by_*` | `direction` | `source` |
|---|---|---|---|
| `received` | — | `inbound` | `contact` |
| anything else | `sent_by_campaign` | `outbound` | `campaign` |
| | `sent_by_bot` | `outbound` | `bot` |
| | `sent_by_api` | `outbound` | `api` |
| | `sent_by_biz_app` | `outbound` | `business_app` |
| | none set | `outbound` | `agent` |

### receipts are timestamps, not counts

Each is the unix second at which the message reached that state, and `0` means it
never did. `receipts.read` is the "seen at 10:42" a chat window renders.

### content is open, on purpose

This is a multi-channel platform. A WhatsApp interactive reply, an email part
tree and an RCS card share no structure worth forcing into one schema, so
`content` is whatever the channel says it is.

One thing is promised: **`content.type` is always present**, and by convention the
body for that kind sits under a key of the same name.

```ts
{ type: 'text',  text: { body: 'Hello' } }
{ type: 'image', image: { id: '123', link: 'https://...', caption: 'Invoice' } }
{ type: 'interactive', interactive: { type: 'button_reply', button_reply: { id, title } } }
```

That single field is what makes previews, renderer selection, filtering and
narrowing possible. Everything else is yours.

Narrow it where you know the channel:

```ts
type WhatsAppText = { type: 'text'; text: { body: string } };
type WhatsAppImage = { type: 'image'; image: { id: string; link?: string; caption?: string } };

const page = await inbox.messages.list<WhatsAppText | WhatsAppImage>(chatId);

for (const message of page) {
  if (message.content.type === 'text') render(message.content.text.body);
}
```

Observed shapes are per channel kind and not normative — they are whatever the
provider sent. Treat an unrecognised `content.type` as something to skip, not as
an error.

## list

```ts
const page = await inbox.messages.list(chatId, { limit: 20 });
```

`message.list` · scope `messages:read`

| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `id` | `string` | yes | — | Contact whose thread to read. |
| `limit` | `number` | no | `20` | Max 100. |
| `last_message_id` | `string` | no | — | The `id` of the oldest message you hold. |

Returns **oldest-first**, ready to prepend above what you already have.

Also **subscribes to the thread**: whatever arrives next lands on this socket
without asking again.

### Walking back through history

```ts
let oldest: string | undefined;
const thread: Message[] = [];

for (;;) {
  const page = await inbox.messages.list(chatId, { limit: 50, last_message_id: oldest });
  if (!page.length) break;

  thread.unshift(...page);
  oldest = page[0].id;      // oldest-first, so the first element is the cursor
}
```

Paging is keyset on `(timestamp, id)`, which matches the ordering exactly. A
message that arrives out of order — a redelivered webhook, a backdated provider
timestamp — cannot be skipped or served twice.

## get

```ts
const message = await inbox.messages.get('wamid.HBgM...');
```

`message.fetch` · scope `messages:read` · `404` if no such message for this account

Takes the **provider id**, not the document id — that is what a webhook or a
delivery receipt quotes.

## send

```ts
const echo = await inbox.messages.send({
  channel: channelId,
  contact: { id: chatId, identifier: '919000000000' },
  content: { type: 'text', text: { body: 'On it, checking now.' } },
});
```

`message.send` · scope `messages:write`

| Field | Type | Required | Notes |
|---|---|---|---|
| `channel` | `string` | yes | Channel to send over. |
| `contact.id` | `string` | yes | |
| `contact.identifier` | `string` | yes | The contact's identity on that channel. |
| `content` | `MessageContent` | yes | Must carry `type`. Otherwise passed through. |
| `context` | `JsonObject` | no | `{ message_id }` to reply to a specific message. |
| `agent` | `string` | no | Attribute to another member. Needs `live_chat.send.AS_OTHER`, else `403`. |

### What comes back is not the stored message

The reply is an **echo** for drawing the bubble immediately. Its `message_id` is
a queue id, not a provider id, and nothing has been written yet.

The real row arrives moments later as a `message.received` push, carrying the
provider's id. **Correlate on the queue id you got back here** — the final
`message_id` is different by design:

```ts
const echo = await inbox.messages.send({ /* ... */ });
draw(echo, { pending: true });

const off = inbox.on('message.received', (message) => {
  if (message.contact === chatId) replacePending(echo.id, message);
});
```

Why: the provider's id is uniquely indexed, and it is not known until the
provider answers. Writing a placeholder row first would mean a null id that the
index refuses for every concurrent send.

The echo goes to the sender only. Other agents see the message when the stored
row is pushed, so nobody is shown a bubble that is about to be replaced.

### The full lifecycle of one send

| Step | What happens | What you can observe |
|---|---|---|
| 1 | `send()` validates, checks `AS_OTHER`, records the send | the echo, with a queue id |
| 2 | The chat comes off its bot | `chat.action` / `pause_automation`, account-wide |
| 3 | The send is handed to the service that holds provider credentials | — |
| 4 | That service calls the provider and writes the row | `message.received` with the provider's `message_id` |
| 5 | The provider reports delivery | `message.status`, once per state change |
| 6 | The pause expires | `chat.action` / `resume_automation` |

Step 3 is durable: the send is recorded before it is handed over, so a broker
that is briefly away delays a message rather than losing it. A send is never
dropped silently.

### Delivery ticks

`message.status` is a separate push from `message.received` so you can update the
ticks in place without re-rendering the bubble:

```ts
inbox.on('message.status', (update) => {
  setTicks(update.message_id, update.status);
  if (update.status === 'failed') showError(update.message_id, update.error);
});
```

| Field | Type | Notes |
|---|---|---|
| `message_id` | `string` | The provider's id — what the echo's queue id became. |
| `status` | `MessageStatus` | `sent` `delivered` `read` `failed` `received` |
| `receipts` | `Partial<MessageReceipts>` | Unix second each state was reached. |
| `error` | `string` | Provider text, when `status` is `failed`. |

### Sending takes the chat off its bot

An agent replying by hand pauses automation. That arrives as a `chat.action` with
`action: 'pause_automation'`, broadcast to the whole account — the automation
badge has to change on every open inbox, not just the sender's.

An already-paused chat keeps its original pause: re-stamping on every message
would push the resume out indefinitely while an agent types.

The pause lifts itself after `chat_metadata.pause_duration` seconds (an hour
unless the chat says otherwise), and arrives as the matching
`chat.action` / `resume_automation` — the same name and shape, so one handler
covers both directions:

```ts
inbox.on('chat.action', ({ action, chat }) => {
  if (action === 'pause_automation' || action === 'resume_automation') {
    setAutomationBadge(chat.id, chat.bot?.pause === true);
  }
});
```

You do not have to call `resumeAutomation()` to end an agent-reply pause; that
method is for lifting one early.

### Media

Use `sendMedia()` rather than assembling the content yourself — it uploads the
file if you hand it one, and puts the caption and filename where the provider
expects them. See
[media.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/media.md).

```ts
const link = await crm.inboxMedia.upload(file, { kind: 'image' });
await inbox.messages.sendMedia({ channel, contact, kind: 'image', link, caption: 'Your order' });
```

### Templates

A template send carries parameters, not prose. Pass the approved definition
alongside them and the echo comes back rendered — header and body variables
substituted, dynamic button urls filled in:

```ts
await inbox.messages.send({
  channel: channelId,
  contact: { id: chatId, identifier: '919000000000' },
  content: {
    type: 'template',
    template: {
      name: 'order_update',
      language: { code: 'en' },
      components: [{ type: 'body', parameters: [{ text: 'Asha' }, { text: '4821' }] }],
    },
    json: approvedTemplate,    // from channels.templates.get()
  },
});
```

`json` (or `components`) is the approved template. Without it the echo carries the
parameters unrendered — the send itself still works.

Three fields are stripped from `template` before the provider sees it: `json`,
`order`, and `isOrder`. They belong to the composer, not the message. Your own
payload object is left untouched, so you can reuse it.

## delete

```ts
await inbox.messages.delete(chatId, messageId);
```

`message.delete` · scope `messages:write` · `404` if not in that thread

| Field | Type | Required | Notes |
|---|---|---|---|
| `id` | `string` | yes | Contact whose thread the message belongs to. |
| `message_id` | `string` | yes | Either the document id or the provider id. |

A **hard delete** — the row is gone. `meta.hide` exists for messages the UI
should skip, and is not what this sets.

Broadcast to everyone with the thread open: a message still rendered after it is
gone is worse than a missing one.

## retryDownload

```ts
const message = await inbox.messages.retryDownload(messageId);
```

`message.retry_download` · scope `messages:write`

| Field | Type | Required | Notes |
|---|---|---|---|
| `message_id` | `string` | yes | The **document** id — a retry targets a stored row. |

Re-fetches media whose first download failed, through the channels service, which
owns the provider credentials. On success the stored link is replaced at
`content.<type>.link` and the updated message is returned and broadcast to the
thread.

| Condition | Result |
|---|---|
| `content.type` not one of `image` `video` `audio` `document` `voice` `sticker` | `422` |
| `status` is not `received` | `422` — an outbound attachment was ours to begin with |
| no `content.<type>.id` | `422` — no provider media id to fetch |
| the re-fetch declines | the message comes back unchanged, no error |

A failed re-fetch is an outcome, not an error: the message keeps its broken link
and the agent can ask again.
