# 08 — Channels

**Status:** Draft. Written 2026-11-07. WhatsApp is specified in depth; the others at the level
needed to size the work. Meta API details carry **[VERIFY]** where only secondary sources were
available; confirm against developers.facebook.com before build.

Channels are deployment surfaces for the [product families](20-product-scope.md). Choose a
channel for the job and check its eligibility and capability limits. WhatsApp is the initial
business integration; personal, learning and internal agents can use Telegram or API where
the required capabilities are ready. WhatsApp policy and window rules apply only to that
adapter. Future channels retain their delivery phases in the roadmap.

## 1. The `ChannelAdapter` contract (`packages/channels`)

```ts
interface ChannelAdapter {
  type: ChannelType
  capabilities(identity: ChannelIdentity): ChannelCapabilities
  // ingress (apps/web)
  verifyWebhook(req: Request, identity: ChannelIdentity): Promise<boolean>
  parseInbound(payload: unknown, identity: ChannelIdentity): InboundEvent[]       // messages, receipts, reactions, button/list/flow replies, call events, account updates
  // egress (apps/runtime)
  render(out: OutboundIntent, caps: ChannelCapabilities, ctx?: { locale?: string }): ProviderRequest[] | Issues | Unsupported // locale → fixed labels ("Elegir", Sí/No)
  send(req: ProviderRequest, identity: ChannelIdentity, idempotencyKey: string): Promise<SendResult>
  mapError(providerError: unknown): NormalizedDeliveryError                       // e.g. WhatsApp 131047 → recipient_reply_required
  // provisioning
  connect(flow: ConnectInput): Promise<ChannelIdentity>                            // Embedded Signup exchange, bot token validation, etc.
  disconnect(identity: ChannelIdentity): Promise<void>
  health(identity: ChannelIdentity): Promise<HealthSnapshot>                       // quality rating, tier, token validity
}

type ChannelCapabilities = {
  maxTextLength: number; maxInteractiveBody: number
  interactiveHeaderLength: number | null; interactiveFooterLength: number | null   // WhatsApp: 60 / 60
  buttons: { max: number; labelLength: number; idLength: number } | null           // WhatsApp: 3, 20, 256
  list: { maxRows: number; rowTitleLength: number; rowDescriptionLength: number; rowIdLength: number
          buttonLabelLength: number; sections: boolean; sectionTitleLength: number } | null // 10, 24, 72, 200, 20, true, 24
  ctaUrl: { labelLength: number } | null; flows: boolean; templates: boolean       // cta_url label: 20
  media: { image: number; audio: number; video: number; document: number } // byte limits
  voiceNote: { formats: string[] } | null
  typing: boolean; reactions: boolean; edit: boolean; delete: boolean; replyTo: boolean
  readReceipts: boolean; windowHours: number | null; groups: boolean
}
```

`OutboundIntent` is channel-neutral: `text`, `card` (json-render spec + text), `choice`,
`confirm`, `media`, `voice_note`, `template`, `reaction`, `edit`, `delete`, `typing`,
`location`, `contact`, `payment_request`.

## 2. WhatsApp (Meta Cloud API) — P0

### 2.1 Accounts and onboarding — launch through a BSP (decided 2026-11-07)

We do **not** become a Meta Tech Provider for launch. Customers connect their WhatsApp Business
Account through a Business Solution Provider that we integrate as a `provider` behind the
`ChannelAdapter`. This removes Meta app review and Tech Provider verification from the critical
path and gives us managed billing of Meta fees, at the cost of a per-number vendor fee and a
sub-processor in the data flow.

**Recommended primary BSP: Kapso** (kapso.ai). Reasons: developer-first API; customers onboard
their own WABA and number through Kapso's Meta app via Embedded Signup without us holding
Tech Provider status; one Kapso "customer" per tenant; Flows, interactive messages, templates
and business/user-initiated calling supported; Meta fees either billed by Meta to the tenant or
paid from our prepaid USD credits (5% managed-billing fee); plans Free → Pro (3 numbers,
$10 each extra, 100k messages) → Platform (50 numbers, $5 each extra, 1M messages) → Enterprise;
Pix accepted for credits. Keiki itself runs WhatsApp on Kapso, which validates the API for an
agent platform. **[VERIFY]**: company jurisdiction and data residency (relevant for ES/PT),
multi-tenant webhook routing, template management API, DPA availability.

**Alternative BSP for EU customers: 360dialog** (Berlin). Partner program: Starter €250/mo with
5 channels (+€49 per extra number), Growth €500/mo with 10 (+€25), Premium €1,000/mo with 20
(+€15); Meta fees at official rates with no markup; 4% card fee but Pix and boleto free;
Integrated Onboarding for partners; EUR invoicing. Use when a Spanish or Portuguese tenant
requires an EU-based processor, or as the second provider for resilience.

**Twilio** stays the provider for SMS and PSTN voice; its WhatsApp offering ($0.005/message
platform fee) is not needed.

Migration path: `channel_identities.provider ∈ { kapso | dialog360 | twilio | meta_cloud }`.
When volume justifies it (Phase 3+), we apply for Tech Provider status and add `meta_cloud` as a
direct provider, or use Kapso's Multi-partner Solution (beta) with our own Meta app. Nothing in
the agent, conversation or billing model depends on which provider a number sits on.

- Meta still bills per message to the WABA (or to our credits, re-billed to the tenant); we
  show the tenant the billing mode at connect time.
- Coexistence with the WhatsApp Business app is allowed (app ≥ 2.24.17; 20 mps cap).
- Tenants already on another BSP: Later, accept their credentials as a provider if the BSP
  exposes a compatible API.

### 2.2 Inbound
- Webhook `POST /webhooks/whatsapp/:provider` receives the BSP's forwarded payload. Kapso and
  360dialog forward Meta's Cloud API payload shape with their own signature header; the adapter
  verifies per provider (Meta direct: `X-Hub-Signature-256` HMAC-SHA256 with the app secret and
  a `GET` handshake with `verify_token`). **[VERIFY]** exact header names and whether each BSP
  preserves `statuses`, `reaction`, `nfm_reply`, `order` and `calls` events untouched.
- Dedupe on `wamid`. Providers retry if we do not return 200 (Meta: up to 7 days [VERIFY]).
- Message types: `text`, `image`, `audio` (voice notes `voice: true`), `video`, `document`,
  `sticker`, `location`, `contacts`, `reaction`, `interactive` (`button_reply`, `list_reply`,
  `nfm_reply` for Flows), `button` (template quick-reply), `order` (catalog), `system`
  (number change), `unsupported`, plus `statuses` (sent/delivered/read/failed with error codes)
  and `calls`.
- Contact identity: `wa_id` (phone) or **business-scoped user ID** when the user hides their
  number (`EG.…`). `contacts.external_id` stores whichever Meta sends; replies go to the same.
  Profile name from `contacts[].profile.name`.
- Context: quoted replies carry only the quoted `wamid`; we look up its text in our messages.
- Media: download via `GET /{media_id}?phone_number_id=…` (Kapso) → `download_url` (Kapso-hosted,
  valid 4 minutes, auth in the URL) or Meta's `url` (5 minutes) → stream to object store, in the
  `media` worker, never in the webhook (T-031, `docs/07` §8). Limits: image 5 MB, audio/video
  16 MB, document 100 MB [VERIFY]; stickers use the image limit.
- The **24 h customer-service window** opens/refreshes on every inbound message; we store
  `window_expires_at`. Clicking a click-to-WhatsApp ad or Facebook CTA opens a 72 h free
  entry-point window [VERIFY].
- **Coexistence with the WhatsApp Business app** (ISSUE-1174). The owner keeps answering from
  the app on the same number; Meta sends each of those sends as `smb_message_echoes`, which Kapso
  marks `message.kapso.origin: business_app`. Which Kapso event carries the echo is not
  documented (probably `whatsapp.message.sent`, `direction: outbound`) [VERIFY with a sandbox
  capture, ISSUE-1095], so the normaliser accepts `business_app` on any message event that does
  not claim to be inbound:
  - **Echo** (`business_echo`, ISSUE-1176): stored as an outbound `team` row, `status: sent`,
    `payload.origin: business_app`, once per `wamid` (`idempotency_key = app:<wamid>`, and its own
    receipts move it to delivered/read). The recipient is the message's `to` / `to_user_id`, else
    the Kapso conversation's contact (phone or BSUID; a contact with only a BSUID is created
    without a phone). It never opens or extends the 24 h window and never resets the AI
    disclosure clock: only the contact opens the window.
  - **The agent pauses** (ISSUE-1177): the conversation goes `held` with `held_source:
    business_app` and no member, until the echo's send time + `settings.coexistence.
    appHoldMinutes` (default 30, 5–1440). A later echo pushes `held_until` forward; a member's or
    an escalation's hold is kept. Messages waiting for a steer are settled, and a running turn
    gets an `app_hold` outbox row that sets its abort flag; `deliver` already refuses agent sends
    while `held` (`not_delivered conversation_held`). An echo whose hold would already have lapsed
    (delivered late) is stored but holds nothing; a reaction from the app never holds. The hold
    ends by expiry (`hold-sweep`, with the usual resume note quoting the owner's messages as
    `team`) or from the dashboard. Handing back from the phone is not decided.
  - **History and contacts** (`origin: history_sync`, ISSUE-1181): decision D1 (ISSUE-1175) is to
    import nothing, and Charla never calls the SMB App Data sync. Anything marked
    `history_sync`, or a sync event by name, is answered `200` and dropped before validation: no
    contact, conversation, message, steer or window, and `inbound_events` keeps only
    `{ redacted: "history_sync", events: [{ eventType, item }] }`.

### 2.3 Outbound rendering rules
| Intent | WhatsApp payload |
|---|---|
| text ≤ 4,096 | `type: text` with `preview_url` on when a URL is present |
| text > 4,096 | split at sentence boundaries into several `text` messages (`splitText`) |
| `choice` with 1–3 options | `interactive.type: button` (labels ≤ 20 chars, unique and not blank, ids `pi_<presentationId>:<optionId>`, or the bare option id when the intent has no `presentationId`; an option id may not start with `pi_`/`act_` then) |
| `choice` with 4–10 options, or any option with `description`/`section` | `interactive.type: list` (button "Elegir"/"Escolher"/"Scegli"/"Choose" by contact locale, rows ≤ 10, titles ≤ 24, descriptions ≤ 72, sections ≤ 24 when every option has one; text header only) |
| `choice` with 0 or > 10 options | `issues` |
| `confirm` | `interactive.type: button` with Sí / No (Sim / Não, Sì / No, Yes / No by locale) unless `confirmLabel`/`cancelLabel` (a blank one falls back to the default); ids `pi_<presentationId>:yes|no` |
| `card` (json-render) | per Keiki's mapping: 1–3 `Button` → buttons; 4–10 → list; exactly one `LinkButton` → `cta_url`; else text. Body = title + subtitle + texts + `Label: value` fields + table rows joined by ` \| `, ≤ 1,024; header (`Card.header`: text ≤ 60, or `{ type: image|video|document, url }`; lists take text only) and footer (≤ 60) added — Keiki lacks these. Plain-text fallback keeps `LinkButton`s as `label: url` and is one message ≤ 4,096 (over → `issues`, not split). Card `Button` ids may not start with `pi_`/`act_`. `send_card` (T-041) refuses, with `issues`, a card the fallback would strip of its `Button`s (more than 10, or mixed with a `LinkButton`); the stored `rendered_text` is the flattened view (`renderedTextOf`), e.g. `*Title*\nBody\n[Sí] [No]` |
| governed-action approval (`approval` intent, T-062) | `interactive.type: button`: text header `Aprobación necesaria · <tool>` (≤ 60, cut with `…`), body = the action's `ApprovalCard` flattened (`*header*`, `label: value`, texts, `_note_`; images left out) ≤ 1,024 — over that, the first lines that fit plus a localised "summary" note —, footer `Ejecuta <tool>` (or, when the tool name does not fit in 60, last body line), exactly two buttons Approve/Decline (ids `act_<id>:approve|decline`). Queued by the platform at proposal (`<actionId>:ask`, `actionReply`, a `system` message), never by the model; unlike other intents the render cuts instead of returning `issues`. With `approvalProof: verified` the button does not decide (Flow, Phase 2) |
| `media` | type from the MIME and `capabilities.mediaFormats`: `image` (JPEG, PNG ≤ 5 MB), `video` (MP4, 3GP ≤ 16 MB), `audio` (AAC, AMR, MP3, M4A, OGG/Opus ≤ 16 MB); `document` ≤ 100 MB with `filename` only for Meta's document types (PDF, plain text, Word, Excel, PowerPoint). Anything else (WebP, WAV, ZIP…) cannot be sent: Meta rejects it on upload, so `send_file` refuses it up front. Caption ≤ 1,024 on image/video/document; audio has no caption → dropped, and `send_file` returns `caption_delivered: false` so the agent sends it as text. Over a limit → `issues`, no send. Bytes uploaded with `POST /{phone_number_id}/media` (multipart, `type` = bare MIME such as `audio/ogg`) on every send; the id is not stored, because `attachments.provider_media_id` holds the inbound id that `downloadMedia` needs (T-044) |
| `voice_note` | `audio` with `voice: true`, OGG/Opus only (an MP3 with `voice: true` shows as a file). Other sources are transcoded first: `ffmpeg -c:a libopus -b:a 24k -ac 1 -ar 48000 -f ogg`. TTS output goes the same way (TTS itself: follow-up of T-044) |
| `template` | `type: template` with `name`, `language.code`, `components` variables |
| `reaction` | `type: reaction` (`emoji` empty string removes; exactly one emoji, otherwise `issues`) |
| `edit` / `delete` | **unsupported on WhatsApp** → `400 unsupported` before send [VERIFY edit support status] |
| `typing` | mark the last inbound `wamid` read with `typing_indicator`: `{ messaging_product, status: 'read', message_id, typing_indicator: { type: 'text' } }` on `/messages`; response `{ success: true }`, no `wamid`, not stored in `messages`; sent via `WhatsAppProvider.markRead` before the turn's first reply (T-045) [VERIFY on Kapso sandbox] |
| `location` | `type: location` |
| `payment_request` | Brazil: `interactive.type: order_details` with Pix/card `payment_settings` [VERIFY tech-provider eligibility]; elsewhere `cta_url` to checkout |
| product carousel / catalog | `interactive.type: product_list` from the WABA catalog (Later) |
| template carousel | template with `carousel` component, ≤ 10 cards (Later) |

Reply taps arrive as `interactive.button_reply.id/title` (Cloud API) or `button.text`
(Direct Send); the adapter reads both and normalises into `[Button pressed by <name>;
action=<id>]` on the next turn, exactly as Keiki does across channels. The row is stored as
`kind: button_reply | list_reply`, `text = title`, `payload = { id, title[, description] }`; the
model line adds `; label=<title>`, `message_id` and `reply_to` for context and names the contact by `displayName`, falling
back to `externalId`. The `id` prefix routes the tap: `pi_` → presentations, `act_` → governed
actions, anything else → a normal message (`replyRoute` in `@charla/channels`). A `pi_<intent
id>:<option id>` tap on an intent of the same conversation (T-042) answers it if it is `open`
and the option is in its set (first answer wins), and the stored payload gains `action =
<presentation id>:<option id>`, so the model line reads `action=slot:jueves` instead of the row
id; any other tap still reaches the agent unchanged.

### 2.4 Templates
- Synced from the WABA via the BSP's template API (Kapso / 360dialog) or Meta's Business
  Management API when direct; stored in `templates` with status. The `maintenance` task
  `template-sync` runs hourly and for one number when it connects (`templateSyncJob`); Kapso
  sends no template status webhook, so Meta's review reaches us through this sync (T-080).
- Sending (`OutboundIntent` `template`): `name`, `language`, `variables` for the body's
  `{{1}}…{{n}}`, an optional `header` (text variable, or an HTTPS `link` for an image, video or
  document header) and `buttons` (`quick_reply` payload or `url` suffix, by index). The render
  checks them against the synced definition: the template must be `approved`, the variable count
  must match, and no value may be empty, contain line breaks or tabs, or have more than 4
  consecutive spaces (Meta error 132018). Named variables (`{{name}}`) are not sent yet.
- Base catalog (`packages/channels/src/whatsapp/templates/base/{es,pt_BR,pt_PT,it}.json`), all
  `UTILITY`: `recordatorio_cita` (3 variables, Confirm / Reschedule quick replies),
  `actualizacion_pedido` (3), `handoff_notificacion` (2, to the team), `solicitud_caducada` (2),
  `seguimiento_conversacion` (2, one quick reply). `pnpm templates:submit --org <id> --lang es`
  sends them to review for the org's numbers and stores them `pending`; it needs a number with a
  WABA (the Kapso sandbox cannot create or sync templates). `templateDraftIssues` checks a draft
  against Meta's rules first: no variable at the start or end of the body, `{{n}}` without gaps,
  examples for every variable, length limits, no promotional wording in a utility template.
- Agent templates bring their own messages (T-154): installing one (gallery or onboarding)
  writes its `whatsappTemplates` to `template_message_requests`, for the families that may use
  WhatsApp. The `maintenance` task `template-submit` sends them to review: for one org
  (`templateSubmitJob`, queued by the dashboard after an install and when a number connects or
  reconnects) and hourly at :30 for the orgs with `pending` ones. An org without a connected
  number with a WABA keeps them `pending`. Nothing is sent twice: one request per org, name and
  language; each WABA's list is read first and a message it already has is only mirrored into
  `templates`; one run per org at a time (Redis lock). A draft that fails
  `templateDraftIssues` is `failed` without spending a review; a failed send is retried by the
  hourly run, up to 5 times. With an explicit org, every request is checked against every WABA
  of the org, so a number connected later on another WABA gets them too. The files' language
  codes are the locale's (`templates:lint`), so a message is always in the template's language.
- Agents reference templates by name for alerts, notices, human replies outside the window,
  and `windowPolicy.defaultTemplate` (T-081: only an approved `UTILITY` one; the agent's text
  goes in the body's last variable). A team message outside the window answers `409
  window_closed` with `details.templates`: the number's approved templates (`name`,
  `language`, `category`, `variables`, `body`) for the dashboard's template mode (T-134).
- A template builder in the dashboard submits for Meta approval (T-138, the channels page:
  utility only, checked with `templateDraftIssues` first, stored `pending`; its "refresh status"
  lists the number's templates from Kapso at once); pre-made es/pt utility
  templates ship with each vertical template (e.g. `recordatorio_cita`, `actualizacion_pedido`).
- Marketing templates are opt-in only, with per-contact consent proof required.

### 2.5 WhatsApp Flows
- Flow JSON stored per org; published to the WABA via API; versioned.
- Used for: approval with `approvalProof: verified` (screen shows the action summary blocks,
  Approve/Decline), KYC captures (CPF/CURP/DNI), booking forms with live slots (data endpoint
  hosted by `apps/runtime` with Flows encryption and health checks), lead forms (no endpoint).
- Response arrives as `interactive.nfm_reply.response_json`, mapped to a `presentation_intent`
  answer or an action decision.

### 2.6 Quality, limits and health
- Poll/subscribe quality rating and messaging tier per number; show Green/Yellow/Red and tier in
  the dashboard; warn at 70–80% of tier. Implemented (T-085): the hourly `quality-poll`
  maintenance task (`:45`) calls `provider.health()` (Kapso: `GET phone_numbers/{id}` for
  `quality_rating` and `whatsapp_business_manager_messaging_limit`, plus `/health`), stores
  `channel_identities.quality` and `channel_quality_history`, and publishes `line.quality_changed`
  / `line.tier_changed`. Usage = distinct conversations that got an outbound template in the last
  24 h. The owner is emailed (`organizations.settings.notifications.ownerEmail` until T-130 brings
  user accounts) when the rating drops to yellow/red, the tier goes down, or usage passes 80 %.
- Platform ceilings analogous to Keiki's: `daily_line_volume_reached` per number per UTC day
  (configurable, default 7,000 sends), `new_conversation_limit` = Meta tier; `opted_out` refusals.
- Warm-up guidance for new numbers; prefer user-initiated entry (`wa.me/<number>?text=`, QR,
  click-to-WhatsApp ads); 2–3 spaced follow-ups max.
- Error mapping table: `131047` re-engagement → `recipient_reply_required`; `131026` undeliverable;
  `130429` rate limit → backoff; `131042` payment issue on WABA → alert owner; `132000`
  template param mismatch; `131056` pair rate limit [VERIFY codes].

### 2.6a Platform policy and country-specific charges
- Meta's **"AI Providers" clause** (WhatsApp Business Solution Terms, October 2025) bars
  general-purpose AI assistants from the Business API and allows business-specific
  customer-service agents. Our agents are business-bound by construction; the dashboard and
  templates must not let a tenant publish a general assistant on a WhatsApp number (allowed on
  Telegram and API).
- **Italy**: AGCM interim measures (2025-12-24) suspended those terms in Italy; Meta reportedly
  introduced a per-message charge for non-template AI replies in Italy (≈ €0.0572 from
  2026-02-16) and the European Commission signalled EEA-wide interim measures in June 2026
  **[VERIFY, secondary sources]**. The delivery service must be able to tag outbound messages
  with a per-country Meta charge class so billing can pass it through.
- **Charge classes (T-105).** `deliver` tags every WhatsApp send it marks `sent` with
  `messages.charge_class` and `recipient_country`, from the **recipient's** E.164 number
  (`libphonenumber-js`), never the business's: a template is `utility_template` (authentication
  too) or `marketing_template`; a free-form message is `ai_reply_charge` when it is the agent's
  own reply and the country's rule charges AI replies (Italy from 2026-02-16), `service_paid` where
  the rule charges service messages, else `service_free`. Team and platform messages are never
  AI replies. Rules and prices live in the dated table `billing/meta-charges.ts` of
  `@charla/domain` (every figure `TODO verify`); utility templates inside an open window are
  free. A costed class writes a `usage_events` row with the send (`docs/06` §2.9).

### 2.7 Consent
- Opt-out keyword sets per locale: es `BAJA`, `CANCELAR`, `STOP`, `NO MÁS`, `DETENER`; pt
  `SAIR`, `PARAR`, `CANCELAR`, `STOP`; it `STOP`, `CANCELLA`, `DISISCRIVI`, `BASTA`; en `STOP`,
  `UNSUBSCRIBE`. Restore: `ALTA`, `INICIAR`, `VOLTAR`, `RIATTIVA`, `START`. Exact match after
  normalising accents and case.
- Scope (ISSUE-1169): these words act on the **number written to** only; the confirmation says so
  («desde este número») and offers the org-wide word. Org-wide opt-out, every number of the
  business: es `BAJA TOTAL`, pt `SAIR TUDO`, it `STOP TUTTO`, en `STOP ALL`, `UNSUBSCRIBE ALL`
  (agent's language plus `en`); org-wide restore, any locale: `ALTA TOTAL`, `VOLTAR TUDO`,
  `RIATTIVA TUTTO`, `START ALL`. Organisations do not extend the org-wide sets yet. An operator
  acts org-wide with `scope: organization` on the consent endpoint. Rules in `docs/06` §2.7.
- Opt-in evidence for marketing templates is required and stored (checkbox on web, keyword,
  ad click).
- Organisations extend (never shrink) the locale sets with `settings.consentKeywords.optOut |
  optIn`; the agent's language plus `en` are evaluated.
- Every transition emits `conversation.opt_status_changed` to tenant webhooks (T-084), in the
  same transaction as its `consent_events` row; a repeated BAJA is no transition and emits
  nothing. `reason`: `keyword` (BAJA…), `verified_restoration` (ALTA…), `provider` (Kapso
  `whatsapp.contact.marketing_preference_changed`: `stopped` / `resumed`), `operator`
  (`POST /api/webapp/conversations/:id/consent { optedOut }`), `health`, `import`.
- Restoration: an opt-out is lifted only by a source allowed to (`canLiftOptOut` in
  `@charla/domain`). ALTA lifts a keyword, operator or import opt-out; WhatsApp's own marketing
  stop is lifted only by its `resumed` (ALTA is then ordinary chat and the operator gets
  `409 provider_opt_out`); `resumed` does not lift the contact's BAJA; `health` is lifted by
  `health` or an operator. An ALTA on a line also lifts a BAJA TOTAL for that line only; an ALTA
  TOTAL lifts every line's opt-out it may lift (never the provider's or health's).

### 2.8 Calling
- Inbound (user-initiated) calls: free; answered by the voice runtime (same agent config, voice
  settings per number). Outbound business-initiated calls where available (not US/CA), ≤ 100 per
  user per day; require a permission request message first [VERIFY]. Kapso exposes both
  directions plus recording and transcription; 360dialog bills calls at Meta's voice rate card.
- Voice pipeline: WebRTC/SIP from Meta → media server → STT stream → agent turn in speech mode
  (short answers, `approvalProof: verified` tools refuse, conversation search off) → TTS.
  Provider options: self-hosted media with LiveKit; or a carrier that terminates WhatsApp
  calls (Telnyx). **[DECISION NEEDED]**, Later phase.

### 2.9 Provider abstraction
`packages/channels/whatsapp/providers/{kapso,dialog360,meta}.ts` implement one interface:
`verify(req)`, `normalizeInbound(payload)`, `send(message)`, `uploadMedia`, `downloadMedia`,
`listTemplates`, `submitTemplate`, `getQuality`, `connectFlow(tenant)` (returns the provider's
Embedded Signup URL or hosted onboarding link), `disconnect`. The WhatsApp adapter itself never
branches on provider; rendering rules (§2.3) are Meta's and identical across BSPs. Contract tests
run the same recorded Meta payloads through each provider's normaliser.

## 3. Instagram DM and Messenger — P1/P2
- Same Meta webhook infrastructure (`instagram` and `page` objects). Requires the business's
  Instagram professional account linked to a Facebook Page; OAuth with
  `instagram_business_manage_messages`, `pages_messaging` scopes [VERIFY current scope names].
- Capabilities: text, quick replies (≤ 13), generic templates (carousel ≤ 10), buttons (≤ 3),
  media, reactions, story replies and mentions (IG), ice breakers, persistent menu (Messenger).
  24 h messaging window with limited tags for Messenger; IG allows human-agent tag 7 days
  [VERIFY].
- Contact identity: IG-scoped user id (IGSID) / page-scoped id (PSID). No phone number.

## 4. Telegram — P1
- Bot API via long polling in `apps/runtime` or webhook to `apps/web` (webhook preferred;
  secret token header). No fees, no window.
- Capabilities: text 4,096, inline keyboards (buttons with callback data → `[Button
  pressed…]`), reply keyboards, media, voice notes (OGG/Opus, MP3, M4A), edit/delete own
  messages (48 h in private chats), reactions, groups with mention gating, `/start=<slug>`
  deep links for return links, typing action.
- Identity: Telegram user id; username optional. Groups: one conversation per chat by default.

### 4.1 Inbound and connection (T-110)

- **Connect** (`connectTelegramBot`, `apps/web/src/server/channels/telegram.ts`; API and
  dashboard in T-113): `getMe` validates the BotFather token; the token and a random 32-byte
  `secret_token` are stored as `channel` secrets of the org (`TELEGRAM_BOT_TOKEN_<ID>`,
  `TELEGRAM_WEBHOOK_SECRET_<ID>`, scoped to the identity); the identity is
  `address: @username`, `provider_config: { bot_id, bot_username, webhook_secret_ref }`,
  `credentials_secret_ref` = the token secret. `setWebhook` points the bot at
  `PUBLIC_BASE_URL/webhooks/telegram/:identityId` with that secret and
  `allowed_updates: message, edited_message, callback_query, message_reaction`; only then is the
  identity `connected`. Reconnecting the same bot rotates the secret. Manual check:
  `pnpm --filter @charla/web telegram-connect <orgId> <agentId> < token.txt`.
- **API and dashboard (T-113)**: `POST /api/v1/developer/lines/telegram`, `DELETE
  /api/v1/developer/lines/:lineId` and their dashboard twins (`docs/10` §2.3). The plan must
  include Telegram (Starter+); one live bot per agent and one agent per bot. Disconnecting
  (`disconnectTelegramBot`) calls `deleteWebhook`, leaves the identity `disconnected` without
  credentials or `webhook_secret_ref` (the webhook then answers `401`) and deletes both secrets.
- **Webhook** `POST /webhooks/telegram/:identityId`: `404` unknown identity, `401` when
  `X-Telegram-Bot-Api-Secret-Token` does not match (constant-time comparison of SHA-256 digests;
  Telegram does not sign the body). Dedupe on `<identityId>:<update_id>`, then the shared ingress
  (same as WhatsApp, `inbound_events.provider = telegram`). A `callback_query` is answered in the
  webhook response body (`{"method":"answerCallbackQuery","callback_query_id":…}`), so the
  button stops spinning without a second request.
- **Ids**: `message_id` is only unique per chat, so `provider_message_id` is
  `<chat.id>:<message_id>` for inbound and outbound messages (replies and reactions link through
  it); `edited_message` → `<chat>:<id>:edit:<edit_date>` (a new message for the agent); button
  press → `callback:<callback_query.id>`; reaction →
  `<chat>:<id>:reaction:<user.id>:<date>`. Contact `external_id` = `from.id`; in a private chat it
  is also the `chat_id` replies go to.
- **Normalized**: text (`/start` included), caption, photo (largest size, `image/jpeg`), voice
  (`audio`, `voice: true`), audio, video / video note / animation (`video`), document, sticker,
  location, contact, `reply_to_message`; `callback_query` → `button_reply` with `data` as id and
  the pressed button's label as title; `message_reaction` (first plain emoji; empty = removed).
  Files go through the `media` worker: `getFile` → `/file/bot<token>/<file_path>` (Bot API
  download limit 20 MB; larger or expired files end as `[Adjunto no disponible]`).
- **Ignored** (raw `inbound_events` row only): channel posts and chats (`chat.type: channel`),
  button presses and reactions in groups (until T-111), messages from bots, polls, dice, games, payments, stories and service messages, custom-emoji
  reactions, `callback_query` without `data`, and every other update type.
- **Bot API errors**: `429` → `rate_limited` with `retry_after` (`retryAfterMs`); `403` (bot
  blocked) and `400 chat not found` → `invalid_recipient`; any other `400` → `invalid_request`
  with Telegram's `description`; `401` → `auth_failed`; `5xx` and lost responses are never resent
  (the Bot API does not deduplicate). Calls time out after 10 s (file uploads 120 s).

### 4.2 Outbound rendering (T-111)

`renderTelegram(intent, caps)` (`packages/channels/src/telegram/render.ts`) returns Bot API calls
(`{ channel: 'telegram', method, params }`); `TelegramProvider.send` executes them and the
`deliver` worker adds `chat_id` (the contact's user id in a private chat). Every text goes with
`parse_mode: HTML`, escaping `<`, `>` and `&` (never `Markdown`: unescaped user text fails at
random). Limits count after entity parsing, so escaping does not shorten the budget.

| Intent | Bot API call |
|---|---|
| text ≤ 4,096 | `sendMessage`, link preview only when the text has a URL |
| text > 4,096 | split at sentence ends (`splitText`), one `sendMessage` each |
| `choice` (1–10) | `sendMessage` + `InlineKeyboardMarkup`, 2 buttons per row (6 options → 3 rows); with any `description`, one button per row and `• label: description` lines in the text. Labels ≤ 40, ids as on WhatsApp (`pi_<presentationId>:<optionId>`) |
| `confirm` | one row: Sí / No by locale (or `confirmLabel` / `cancelLabel`; a blank one falls back to the default) |
| `card` | one `sendMessage`: text header `<b>`, body (title `<b>`, notes `<i>`), footer `<i>`; `Button`s as callback buttons (rows of 2) and `LinkButton`s as URL buttons (one per row) — they can be mixed, unlike WhatsApp; an image/video/document header is the link preview above the text |
| `approval` | `<b>Aprobación necesaria · tool</b>`, the card lines (cut to fit), `<i>Ejecuta tool</i>`, buttons Approve / Decline (`act_<id>:approve\|decline`) |
| `media` | `sendPhoto` (JPEG, PNG, WebP ≤ 10 MB), `sendVideo` (MP4 ≤ 50 MB), `sendAudio` (MP3, M4A ≤ 50 MB, no caption, as on WhatsApp), `sendDocument` (≤ 50 MB); caption ≤ 1,024 in HTML |
| `voice_note` | `sendVoice` with OGG/Opus, MP3 or M4A; anything else is transcoded to OGG/Opus first |
| `reaction` | `setMessageReaction` on `<chat>:<message_id>`; only Telegram's reaction emoji (`TELEGRAM_REACTION_EMOJI`, variation selector dropped), else `issues`; `""` removes |
| `edit` | `editMessageText` (HTML) on `<chat>:<message_id>`; the row is stored as `[edited <id>] text` |
| `delete` | `deleteMessage` (own messages, < 48 h); row `[deleted <id>]` |
| `typing` | `sendChatAction` `typing`, nothing stored |
| `location` | `sendVenue` with `name` and `address`, else `sendLocation` |
| `template`, `handoff` | unsupported (no templates; the handoff notice goes to the team's WhatsApp number) |
| `contact`, `payment_request` | `issues` (not rendered yet) |

- **`callback_data` is 1–64 bytes.** A longer id (a `pi_` id with a long presentation row id, a
  card button id) goes out as `cb~<32 chars of base64url SHA-256>`; the send stores key → id in
  Redis (`tg:cb:<identityId>:<key>`, TTL 24 h) before calling the Bot API, and the webhook
  resolves the pressed key back to the id before ingress, so presentations, actions and the agent
  only see the original id. An expired key reaches the agent as a normal button message with
  the label the contact read.
- **Files**: the Bot API has no upload-only call, so `uploadMedia` keeps the prepared bytes in
  memory (handle `attach:<uuid>`, 10 min) and `send` uploads them as `multipart/form-data` in the
  same `deliver` attempt; a `file_id` or URL goes as JSON.
- **Ids returned**: sends → `<chat>:<message_id>`; reaction / delete / edit →
  `<chat>:<message_id>:reaction|delete|edit`.
- **Pending (follow-ups)**: the model tools that would produce these intents on Telegram
  (`send_card`, presentations, `update_message`, `delete_message`) are still WhatsApp-only;
  `react_to_message` and `send_file` are offered from the capabilities.

### 4.2 Groups (T-112)

- **Which messages wake the agent** (`classifyTelegramGroupMessage`, `@charla/channels`), for
  `chat.type` `group` and `supergroup`: a `mention` entity equal to `@<bot_username>` (any case;
  `entities` or `caption_entities`, UTF-16 offsets) or a `text_mention` of the bot; a reply to one
  of the bot's messages (`reply_to_message.from.id` = `bot_id`); a `bot_command` at offset 0 that
  is `/cmd` or `/cmd@<bot_username>` (never `/cmd@otherbot`); a text starting with an alias as a
  whole word (`Charla, …`, any case); with `replyMode: always`, every message.
- **Everything else is silent context**: stored like any contact message with
  `payload.silentContext: true`, no steer, no file download, no consent keyword, no presentation
  answer. The next turn of the conversation carries the silent messages stored since the last
  message the Mastra thread holds, before its batch, as `[Platform note; context only, do not
  reply; …]` (`pendingSilentContext`, steer worker), so the thread keeps them afterwards.
- **Author label**: the stored `text` starts with the sender's name (`Lucía: …`; first + last
  name, else `@username`, else `Usuario <id>`; one line, no `:`, ≤ 64 characters).
- **Conversation**: `kind: group`, `channel_thread_ref` = `chat.id`. Its contact is the chat
  (`external_id` = `chat.id`, negative; `display_name` = title) by default, or each member with
  `identity: user` (one conversation per member and chat). Replies go to `channel_thread_ref`.
- **Settings** (`channel_identities.settings.groups`, `groupSettingsOf` in `@charla/domain`):
  `replyMode` `mention` (default) | `always`; `identity` `group` (default) | `user`;
  `mentionAliases` up to 20 strings. Each key falls back to its default on its own when invalid.
- **Tools**: the conversation is `kind: group`, so no principal is resolved and every tool with
  `requiredScopes` is refused with `group_not_allowed` (`docs/09` §2.3, T-055).
- With BotFather privacy mode on (the default) Telegram only sends the bot commands, mentions and
  replies; silent context needs privacy mode off or the bot as group admin.

## 5. SMS and RCS — P3
- Twilio (or regional aggregator) numbers in MX, BR, CO, AR, CL, ES, US. Costly; 160-char
  segments; no buttons (RCS has). US requires 10DLC registration and TCPA consent.
- Used mainly as fallback and for OTP; opt-out keywords per carrier rules.

## 6. Email — P2
- Resend inbound (MX record on a subdomain) and outbound; one inbox per agent identity.
  Threads by `In-Reply-To`/`References`. Markdown → HTML. Attachments through the media
  pipeline. No window, no buttons (links instead).

## 7. Voice (PSTN) — P2
- Twilio Programmable Voice with ConversationRelay (or Telnyx) for numbers in LatAm/Spain;
  same speech-mode turn as WhatsApp calling. Monthly number cost shown before purchase; per-minute
  usage metered as credits.

## 8. Web chat and API — P0 (API), P2 (widget)
- `api` channel: the OpenAI/Anthropic-compatible endpoints and the SDK; `x-conversation-id`
  threads; `[Button pressed…]` emulated via tool results.
- Implemented for OpenAI (T-123, [ADR-0011](adr/0011-openai-compatible-endpoint.md)): one
  implicit `channel_identities` row per agent (`type = api`, `provider = api`, `address = agent
  id`), created on the first call; capabilities are plain text only (no buttons, lists, files,
  typing or window), so `send_card` and `send_file` are not offered. Replies are stored as
  `delivered` messages; nothing goes through `deliver`.
- Web widget (embeddable, es/pt/en) later; renders buttons/lists natively.

## 9. Slack and Teams — P3
- Copy Keiki's ingress classification, stay-quiet contract, handoff threads and one-app-many-
  workspaces model when we get there. Not in the first two phases.

## 10. Channel comparison

| | WhatsApp | Instagram | Messenger | Telegram | SMS | Email | Voice |
|---|---|---|---|---|---|---|---|
| Per-message cost | Service free-ish; templates paid | Free | Free | Free | Paid | Low | Per minute |
| Buttons | 3 / list 10 / Flows | 3 / quick replies 13 | 3 / quick replies 13 | unlimited inline | none | links | spoken |
| Window | 24 h | 24 h (+7 d human tag) | 24 h (+tags) | none | none | none | n/a |
| Voice notes | yes | yes | yes | yes | no | no | n/a |
| Edit/delete own | no/no [VERIFY] | no | no | yes/yes | no | no | n/a |
| Identity | wa_id or BSUID | IGSID | PSID | user id | E.164 | email | E.164 |
| Groups | yes (mention-gated) | no | no | yes | no | n/a | n/a |
