# Channels

Every way Herald delivers the briefing, how to set each one up, how to test a channel without an
account, and what happens when a run fails.

Turn on one or more channels in the `notifiers` list in `config.json` (`"enabled": true`), or
with `herald config set channels telegram slack` (the types listed go on, every other one off). Each
channel picks its own `languages` from `output.languages` (`pt-BR`, `en`, `es`, `fr`, `it`, `de`;
see [Output languages](configuration.md#output-languages)); without `languages` it gets
`output.primary`.

| Channel | You get | Config keys |
|---|---|---|
| `telegram` | A message from your own bot, split at story boundaries; with `subscribers`, a personal briefing for everyone who subscribed to the bot ([below](#telegram-bot-for-subscribers)) | `bot_token`, `chat_id`, `subscribers`, `privacy_url` |
| `email` | A daily email to confirmed subscribers (double opt-in, LGPD), over SMTP or the Resend API ([below](#email-subscribers)) | `transport`, `from`, `unsubscribe_base_url`, `privacy_url`, `logo_url`; SMTP: `smtp_host`, `smtp_port`, `starttls`/`ssl`, `username`, `password`; Resend: `api_key` |
| `slack` | A post in a channel ([below](#slack-and-discord)) | `webhook_url` (incoming webhook) |
| `discord` | A post in a channel; link previews suppressed ([below](#slack-and-discord)) | `webhook_url` |
| `teams` | Adaptive Cards in a Microsoft Teams channel through a Workflows webhook ([below](#microsoft-teams-workflows-webhook)) | `webhook_url`, `interval_s` |
| `google_chat` | Cards in a Google Chat space, one thread per day ([below](#google-chat-space-webhook)) | `webhook_url`, `interval_s` |
| `webhook` | Versioned JSON events for any agent platform or your own service ([below](#webhook-for-agents)) | `url`, `auth`, `headers`, `events`, `format`/`template` |
| `whatsapp` | An approved template (date, story count, top 3 headlines, optional link) or the full text, through Meta's official Cloud API ([below](#whatsapp-official-cloud-api)) | `phone_number_id`, `access_token`, `recipients`, `template`, `mode` |
| `matrix` | A message in a room on any homeserver, HTML formatted, split under the event size limit ([below](#matrix)) | `homeserver`, `access_token`, `room_id` |
| `ntfy` | A phone push: date, story count, top 3 headlines, a link to the page ([below](#phone-push-ntfy-and-pushover)) | `server`, `topic`, `token`, `priority` |
| `pushover` | The same push through Pushover ([below](#phone-push-ntfy-and-pushover)) | `token`, `user`, `device`, `priority` |
| static site | HTML pages plus RSS, Atom and JSON Feed per language ([below](#static-site-and-feeds)) | `site.enabled`, `base_url`, `feed_days` |

## When a run fails

You get a short alert instead of silence: Telegram, Slack, Discord, Teams,
Google Chat, Matrix, ntfy and Pushover channels that are enabled receive the error (the push channels at a
higher priority) and the path of the run report (Telegram only at `chat_id`, never bot
subscribers), and each webhook
receives a `run.failed` event (drop it from its `events` to opt out). Email (your subscribers)
and WhatsApp never get alerts unless you set `"alerts": true` on them (for WhatsApp, see the
24-hour caveat [below](#whatsapp-official-cloud-api)); set `"alerts": false` to silence a
channel. A run also counts as failed when the AI provider
answers none of the scoring or writing calls (expired sign-in, no credit), so you never get an
empty briefing. Each channel gets the alert in the first of its `languages` (default
`output.primary`).

## Test a channel without an account

`herald notify preview` prints the exact requests each enabled channel would send (method, URL,
headers and body, or the email for SMTP) without touching the network. Every channel runs its
normal code against a recording fake that answers like the vendor; any other connection attempt
is refused. Tokens, signatures and webhook URLs are redacted, and phone numbers, chat ids and
email addresses are masked, so the output is safe to paste in an issue.

```bash
# the latest stored briefing, every enabled channel
uv run herald notify preview
# a bundled sample briefing (and sample subscribers), one channel even if it is disabled
WHATSAPP_TOKEN=dummy WHATSAPP_PHONE_NUMBER_ID=123 \
  uv run herald --config config.example.json notify preview --sample --channel whatsapp
# the failed-run alert instead of the briefing
uv run herald notify preview --sample --alert
```

Credentials only need to be set, not valid, so you can check what WhatsApp or any other channel
would send before you open a vendor account. Each channel ends with `-> ok: N requests built, not
sent`, or `-> failed:` and the setting it misses: the preview resolves and checks the same
settings a send needs (an email `from`, the SMTP login), and exits with code 1 when a channel
fails. Without `--sample` it reads
`data/briefings/<date>.<lang>.md` (`--date`, default the latest), the stories of that day's run
and a read-only copy of your subscribers; nothing is written. `--sample` ignores `--date`; its
briefing is written in all six output languages, so every channel `languages` setting has
something to show.

`herald notify send` takes the same options and delivers for real, printing only the outcome of
each delivery (exit code 1 when one fails, or reaches nobody: `-> warning: no active pt-BR
subscribers` means the email list has no confirmed address in that language yet). With `--sample` it sends the sample briefing but never
sample subscribers: recipients come from your store, so use a throwaway `--data-dir` for a test.
The per-channel steps for a release are in [`docs/release-checklist.md`](release-checklist.md).

## Telegram in five minutes

1. In Telegram, message **@BotFather**, send `/newbot` and pick a name. It replies with a token
   like `123456:ABC...`.
2. Open your new bot and send it any message, so it is allowed to write to you.
3. Open `https://api.telegram.org/bot<TOKEN>/getUpdates` in a browser and copy the number in
   `"chat":{"id": ...}`.
4. Add both values to `.env`:
   ```
   TELEGRAM_BOT_TOKEN=123456:ABC...
   TELEGRAM_CHAT_ID=12345678
   ```
5. Set `"enabled": true` on the `telegram` block in `config.json`, then run `uv run herald`
   without `--dry-run`, which sends nothing.

## Telegram bot for subscribers

The same bot can take subscribers: anyone who opens it can subscribe, pick categories and ask
for the latest briefing, and each subscriber gets the daily briefing in their language with only
the categories they follow.

1. Set `"subscribers": true` (and `"enabled": true`) on the `telegram` block. `chat_id` becomes
   optional: if set, it still gets the full briefing in its `languages` plus the failure alerts.
   Subscribers get every language in `output.languages`, whichever they chose.
2. Start the bot, which answers commands over long polling (no public URL needed):
   ```bash
   uv run herald bot telegram
   ```
3. Run the daily briefing on the same machine (or Docker volume), since subscribers live in
   `data/subscribers.db`. The GitHub Actions workflow does not keep that file.

| Command | What it does |
|---|---|
| `/start` | Explains what the bot sends and stores, with a confirm button (double opt-in). Only `/start confirm` from the same chat within 24 hours subscribes, so a link cannot skip the explanation |
| `/stop` | Unsubscribe |
| `/today` | The latest briefing, limited to your categories |
| `/categories` | The categories this Herald publishes, marked with the ones you follow |
| `/follow <id>`, `/unfollow <id>` | Change your categories; ids or groups (`br`, `us`, `eu`, `global`, `sports`, `all`). While you follow everything, the first `/follow` narrows to what you pick |
| `/lang pt`, `/lang en`, `/lang es`, `/lang fr`, `/lang it` or `/lang de` | Language of the briefing and the replies (only the ones in `output.languages`) |
| `/privacy`, `/export`, `/delete` | What is stored, a copy of it, and erasure |
| `/help` | The list of commands |

The bot reads only commands sent to it in private chats and replies in the subscriber's
language. If someone blocks the bot, the next delivery marks that chat unsubscribed. As the
operator you can answer data requests with `herald subscribers export|unsubscribe|delete
telegram:<chat_id>`. Consent and retention rules are in [`docs/privacy.md`](privacy.md).

To keep the bot running, use a systemd user unit, `~/.config/systemd/user/herald-bot.service`:

```ini
[Unit]
Description=Herald Telegram bot
After=network-online.target

[Service]
WorkingDirectory=%h/herald
ExecStart=%h/.local/bin/uv run herald bot telegram
Restart=on-failure
RestartSec=10

[Install]
WantedBy=default.target
```

```bash
systemctl --user daemon-reload
systemctl --user enable --now herald-bot
loginctl enable-linger "$USER"      # keep it running after you log out
journalctl --user -u herald-bot -f  # logs
```

Or with Docker (it shares the `herald-data` volume with the daily run):

```bash
docker compose --profile bot up -d bot
docker compose logs -f bot
```

## WhatsApp (official Cloud API)

Herald talks only to Meta's official WhatsApp Business Cloud API
(`POST https://graph.facebook.com/<version>/<phone_number_id>/messages`). There is no WhatsApp
Web automation and no unofficial library: those break the terms of service and get numbers
banned.

**The 24-hour rule.** A business can send free-form messages only within 24 hours of the
recipient's last message to it (the customer service window). Outside that window, which is
the normal case for a morning briefing, only an **approved template** goes through. So there are
two modes:

- `"mode": "template"` (default): a short template with the date, the story count, the top 3
  headlines and, optionally, a button that opens the briefing's page.
- `"mode": "text"`: the full briefing as plain text, split under the 4096-character limit. Meta
  delivers it only to recipients who wrote to your number in the last 24 hours; everyone else
  gets error 131047 (re-engagement required).

**Set up Meta (once):**

1. Create a Meta Business account and an app of type *Business* at
   [developers.facebook.com](https://developers.facebook.com/), then add the **WhatsApp**
   product. Meta gives you a free **test number** for development. It can send only to
   the numbers you add and verify in *WhatsApp > API Setup*; any other number gets error 131030.
2. Copy the **Phone number ID** from *API Setup*. The temporary access token there expires in
   about a day. For daily runs, create a **System User** in Business Settings, give it the app
   and the WhatsApp account, and generate a token with `whatsapp_business_messaging` and
   `whatsapp_business_management`.
3. In WhatsApp Manager, create a template named `herald_daily` with category *Utility* (Meta may
   reclassify it as *Marketing*, which costs more) and one translation per briefing language:
   *English (US)* (`en_US`) and/or *Portuguese (BR)* (`pt_BR`). The body must have exactly five
   variables, in this order: date, story count, headlines 1 to 3. Suggested text:

   ```
   Your Herald briefing for {{1}} is ready: {{2}} stories.

   1. {{3}}
   2. {{4}}
   3. {{5}}

   Reply STOP to stop receiving it.
   ```

   ```
   Seu Herald de {{1}} está pronto: {{2}} notícias.

   1. {{3}}
   2. {{4}}
   3. {{5}}

   Responda PARAR para não receber mais.
   ```

   Optional link button: if you publish the static site with `site.base_url`, add a *Visit
   website* button with a dynamic URL `<site.base_url>/{{1}}` (example value
   `2026-11-30.en.html`) and set `"url_button": true`. The URL prefix in the template must be
   exactly `site.base_url` without its trailing slash, followed by `/`. Herald sends only the page
   name (`<date>.<lang>.html`) and Meta appends it. `url_button` needs `site.base_url`, and a
   template without that button rejects the extra parameter (error 132000). Review can take up
   to 24 hours.
4. Add the values to `.env` and enable the `whatsapp` block in `config.json`:
   ```
   WHATSAPP_TOKEN=EAAG...
   WHATSAPP_PHONE_NUMBER_ID=106540352242922
   ```
   ```json
   {
     "type": "whatsapp", "enabled": true, "languages": ["pt-BR"],
     "phone_number_id": "${WHATSAPP_PHONE_NUMBER_ID}", "access_token": "${WHATSAPP_TOKEN}",
     "recipients": ["+5511999990000"], "mode": "template", "template": "herald_daily"
   }
   ```

Other keys: `api_version` (Graph API version, default `v27.0`), `template_languages` (Herald
language to Meta code, default `{"pt-BR": "pt_BR", "en": "en_US", "es": "es", "fr": "fr",
"it": "it", "de": "de"}`; the template needs an approved translation in each), `url_button` (default
`false`) and `alert_template` (below). Each recipient gets every language in `languages`, so set
one language per block.

**Alerts.** WhatsApp gets run-failure alerts only with `"alerts": true`. Without more setup the
alert is a free-form text, and Meta rejects it (error 131047) unless the recipient wrote to your
number in the last 24 hours, which is usually not the case. For alerts that always arrive, create
a second *Utility* template, for example `herald_alert` with the text
`Herald failed on {{1}}: {{2}}. Check the run report.`, and set
`"alert_template": "herald_alert"`. Its two variables are the date and the alert text (on one
line, at most 500 characters).

**Recipients and consent.** Write numbers in E.164 (`+` country code, area code, number, as in
`+5511999990000`). Add a number only after that person has explicitly agreed to receive the
briefing on WhatsApp. Keep a record of when and how they agreed. Herald does not yet handle
`STOP` / `PARAR` replies automatically (that comes with the interactive bot). Until then, when
someone opts out, remove their number from `recipients` the same day.

**Errors.** Meta error codes become a readable line in the run report: 131047 (24-hour window
closed), 131026 (undeliverable), 131030 (not on the test number's list), 132001 (template missing
or not approved in that language), 132000/132018 (variables do not match the template), 190
(token expired) and 130429 (rate limit). 429 and 5xx answers, connection failures and Meta's
transient codes (2, 4, 80007, 130429, 131000, 131016, 131056, 133004) are retried at most twice
with backoff, honoring `Retry-After`. A timeout after the request was sent is not retried, so
nobody gets the message twice, and redirects are never followed. Phone numbers are masked in
logs and reports, and the token is never logged.

**Cost.** Meta charges per delivered template message, at a rate that depends on the
recipient's country and the template category (utility is cheaper than marketing). Free-form
replies inside the 24-hour window count as service messages, and each number gets 1,000 free
service messages a month. The test number is free. See
[WhatsApp pricing](https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing)
for current rates.

## Matrix

Herald posts to a Matrix room on any homeserver through the client-server API
(`PUT /_matrix/client/v3/rooms/{roomId}/send/m.room.message/{txnId}`). Each message is an
`m.text` event with an HTML `formatted_body` and a plain-text `body`. A long briefing is split at
story boundaries, so each event stays well under Matrix's 64 KiB event limit.

1. Create a user for the bot on your homeserver, log in once, and copy its access token (in
   Element: *Settings > Help & About > Access Token*). A dedicated bot account is better than
   your own, because the token can do anything that account can.
2. Invite the bot to the room and join with it. Copy the **room ID**, which starts with `!`
   (in Element: *Room settings > Advanced*). An alias like `#news:example.org` is not accepted.
3. Add the token to `.env` and enable the `matrix` block in `config.json`:
   ```
   MATRIX_TOKEN=syt_...
   ```
   ```json
   {
     "type": "matrix", "enabled": true, "languages": ["pt-BR"],
     "homeserver": "https://matrix.org", "access_token": "${MATRIX_TOKEN}",
     "room_id": "!abcdefghijklmnop:matrix.org"
   }
   ```

Each event's transaction id comes from the day, language, part and text. A retried request, or a
rerun of the same briefing, is deduplicated by the homeserver instead of posted twice. 429
answers (honoring `Retry-After` or `retry_after_ms`), 5xx answers, timeouts and connection
failures are retried at most twice. Redirects are never followed, and the token is never logged.
The homeserver must use `https://`; plain `http://` is accepted only for localhost and
private-network hosts, so the token never crosses the internet in cleartext. Matrix gets run-failure alerts by default (`"alerts": false` turns them off). Encrypted rooms are
not supported: use a room without end-to-end encryption. To try it against a local homeserver,
see [`docs/matrix.md`](matrix.md).

## Phone push (ntfy and Pushover)

The lightest option: one short push per language when the briefing is ready, such as
"Your Herald for Monday, November 30, 2026 is ready" with the story count and the top 3
headlines. With `site.base_url` set, tapping it opens the day's page.

**ntfy.** Install the ntfy app, subscribe to a topic, and put the same topic in the `ntfy`
block. On the public server (`https://ntfy.sh`, the default) anyone who knows the topic name can
read it, so pick a long, random one and keep it in `.env`. For your own server, set `server`
and, if it requires a login, an access token (`tk_...`) in `NTFY_TOKEN`. Herald posts JSON to
the server root (`topic`, `title`, `message`, `click`, `tags`, `priority`).

```
NTFY_TOPIC=herald-7f3a9c2e1b
NTFY_TOKEN=
```
```json
{
  "type": "ntfy", "enabled": true, "languages": ["pt-BR"],
  "server": "https://ntfy.sh", "topic": "${NTFY_TOPIC}", "token": "${NTFY_TOKEN:-}",
  "priority": 3, "alert_priority": 4
}
```

**Pushover.** Create an application at [pushover.net](https://pushover.net/apps/build) to get
an API token, and copy your user key from the dashboard (both are 30 letters and digits). Herald
posts to `https://api.pushover.net/1/messages.json` with the title, the message (cut at 1024
characters) and, with `site.base_url`, the page link. `device` limits the push to one of your
devices, and `sound` picks a sound.

```
PUSHOVER_TOKEN=your-pushover-app-token
PUSHOVER_USER=your-pushover-user-key
```
```json
{
  "type": "pushover", "enabled": true, "languages": ["pt-BR"],
  "token": "${PUSHOVER_TOKEN}", "user": "${PUSHOVER_USER}", "priority": 0, "alert_priority": 1
}
```

Both get run-failure alerts by default, at `alert_priority` (ntfy `4`, high; Pushover `1`,
high); `"alerts": false` turns them off. Pushover's emergency priority (`2`) is not used, because
it needs acknowledgment receipts. Connection failures are retried at most twice. For ntfy, so are
429 and 503 answers, honoring `Retry-After`; other 5xx answers are not retried, because the push
may already be out. Pushover retries 5xx answers at least 5 seconds apart, as its API asks; its
429 means the monthly quota is used up, so it is not retried. A timeout after the request was
sent is not retried, so nobody gets the push twice, and redirects are never followed. The ntfy
server must use `https://`; plain `http://` is accepted only for localhost and private-network
hosts. Tokens, keys and the ntfy topic are kept out of logs and reports.

## Slack and Discord

Both post the briefing to a channel through an incoming webhook.

1. **Slack:** create an app at [api.slack.com/apps](https://api.slack.com/apps), turn on
   *Incoming Webhooks*, add a webhook to the channel and copy its URL. **Discord:** in the
   channel's settings choose *Integrations > Webhooks > New Webhook* and copy its URL. Anyone with
   the URL can post to the channel, so treat it as a secret.
2. Add it to `.env` and enable the block in `config.json`:
   ```
   SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
   DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
   ```
   ```json
   { "type": "slack", "enabled": true, "languages": ["en"], "webhook_url": "${SLACK_WEBHOOK_URL}" },
   { "type": "discord", "enabled": true, "languages": ["en"], "webhook_url": "${DISCORD_WEBHOOK_URL}" }
   ```

Slack gets Slack-formatted sections, split under its 3,000-character block limit. Discord renders
the Markdown as is, split under its 2,000-character message limit, with link previews suppressed
so a briefing does not turn into a wall of embeds and with mentions turned off, so text from a
feed never pings anyone. A long briefing is 20 to 40 Discord messages: when either service
answers "too many requests", Herald waits the time it asks for (up to a minute) and sends the
same message again, up to three tries. Both get run-failure alerts by default (`"alerts": false`
turns them off).

## Microsoft Teams (Workflows webhook)

Herald posts Adaptive Cards to a Teams channel through a Workflows (Power Automate) webhook. The
old Office 365 connector webhooks (`*.webhook.office.com`, MessageCard) were retired by Microsoft
in May 2026; Herald refuses those URLs with a hint to create a Workflows webhook instead.

1. In Teams, open the channel, choose **⋯ > Workflows** and pick the template
   **Post to a channel when a webhook request is received**. Choose the team and channel and
   finish. Teams shows the webhook URL: copy it. Anyone with the URL can post to the channel, so
   treat it as a secret.
2. Add it to `.env` and enable the `teams` block in `config.json`:
   ```
   TEAMS_WEBHOOK_URL=https://...powerplatform.com/.../triggers/manual/paths/invoke?...&sig=...
   ```
   ```json
   { "type": "teams", "enabled": true, "languages": ["pt-BR"], "webhook_url": "${TEAMS_WEBHOOK_URL}" }
   ```

Teams rejects messages over 28 KB, so the briefing usually arrives as a few cards, each holding
whole sections. Cards go out one second apart (`interval_s`), because each webhook call starts a
separate flow run and calls sent together can land out of order. Posts show the Workflows
identity; Teams does not let a webhook pick its own name or icon.

Run-failure alerts are on by default (`"alerts": false` to turn them off). A Workflows call is not
idempotent: Herald retries only connection failures and 429 (honoring `Retry-After`), never 5xx
or timeouts, so a card is never posted twice. Errors show the flow's error code (for example
`WorkflowNotFound` after the flow was deleted), the `sig` in the URL is redacted, and redirects
are never followed.

## Google Chat (space webhook)

Herald posts the briefing to a Google Chat space through the space's incoming webhook, one card
per section. Webhooks need a Google Workspace account whose admin allows them.

1. In Google Chat, open the space, click its name and choose **Apps & integrations > Webhooks >
   Add webhook**. Name it (for example Herald) and save. Copy the URL: it carries a `key` and a
   `token`, and anyone with it can post to the space, so treat it as a secret.
2. Add it to `.env` and enable the `google_chat` block in `config.json`:
   ```
   GOOGLE_CHAT_WEBHOOK_URL=https://chat.googleapis.com/v1/spaces/AAAA.../messages?key=...&token=...
   ```
   ```json
   { "type": "google_chat", "enabled": true, "languages": ["pt-BR"], "webhook_url": "${GOOGLE_CHAT_WEBHOOK_URL}" }
   ```

All messages of a day (every language and a failure alert) go into one thread, keyed
`herald-<date>`. In a space without threads they simply follow each other. Chat caps a message at
32,000 bytes, so a long briefing is split into several messages at section boundaries, sent 1.1
seconds apart (`interval_s`) because Chat accepts one message per second per space.

Run-failure alerts are on by default (`"alerts": false` to turn them off). Herald retries only
connection failures and 429 (up to 3 attempts, honoring `Retry-After`), never 5xx or timeouts,
because the message may already be in the space. Every message also carries a `requestId` that
stays the same across those retries, so Chat can return the message it already created instead
of posting it twice. Errors show Google's status (for example
`UNAUTHENTICATED` for a wrong key or token), the `key` and `token` are redacted, and redirects are
never followed.

## Email subscribers

Email goes only to people who confirmed their subscription, so add at least your own address,
with `--confirmed` since you consent for yourself (without it Herald mails a confirmation link
first). Each address gets one language; adding it again with another `--lang` changes it.

```bash
uv run herald subscribers add someone@example.com --lang pt-BR --source "site form"
uv run herald subscribers confirm <token>       # usually triggered by the confirmation link
uv run herald subscribers list|export|unsubscribe|delete|prune
```

A run or a `notify send` that finds no confirmed address in a language reports a warning (the
run report lists it under `warnings:`) instead of a silent success.

See [`docs/privacy.md`](privacy.md) for consent, unsubscribe and retention rules.

The email is a responsive HTML page in the Herald look (serif type on paper, one warm accent)
that reads well in Gmail, Outlook and Apple Mail, light or dark, with a plain-text alternative
and a preview line made of the first headlines. It stays under Gmail's 102 KB clipping limit:
a briefing too long for it shows its first whole sections and links to the full page on the
static site. The logo is a PNG: set `logo_url`, or publish
the [static site](#static-site-and-feeds) with `site.base_url` and Herald uses the copy it puts
next to the briefings. Without either, the email shows the name as text. Every email carries an
unsubscribe link and `List-Unsubscribe` headers; with an `https://` `unsubscribe_base_url`,
Gmail and Yahoo show a one-click unsubscribe button (RFC 8058). The endpoint is optional: without
it (`HERALD_UNSUBSCRIBE_URL` empty) the link is a `mailto:` to the sender, enough when you mail
yourself; a list of other people should have one ([email.md](email.md)).

Two transports send the same message:

| `transport` | Keys | Notes |
|---|---|---|
| `smtp` (default) | `smtp_host`, `smtp_port` (default 587), `starttls` (default `true`) or `ssl` (port 465), `username`, `password` | Any provider or your own server. Set the port and TLS fields in the block for a server that is not on 587 with STARTTLS. With `username` empty (`SMTP_USER` unset, as `${SMTP_USER:-}` allows) Herald does not log in |
| `resend` | `api_key: "${RESEND_API_KEY}"` | [Resend](https://resend.com) API; retries 429, 5xx and network errors with an idempotency key, so a retry within Resend's 24-hour idempotency window never sends the email twice |

```json
{ "type": "email", "enabled": true, "transport": "resend", "api_key": "${RESEND_API_KEY}",
  "from": "Herald <briefing@news.example.com>",
  "unsubscribe_base_url": "${HERALD_UNSUBSCRIBE_URL}", "privacy_url": "https://example.com/privacy" }
```

**Bounces.** When the server refuses an address for good (an SMTP `5xx` such as "user unknown",
or Resend rejecting the `to` address), Herald marks the subscriber `bounced` and stops mailing
it; the run stays green and says how many bounced. A temporary refusal (`4xx`) is not retried:
that address misses today's email, the delivery is reported as failed and the subscriber stays
active for the next run. Policy and authentication refusals (`5.7.x`, `530`, `535`) blame the
sender, not the address, so they fail the delivery without marking anyone; the same goes for a
run in which nothing was delivered at all. Run reports show only status codes (such as
`SMTP 550 5.1.1`), never the server's reply text or addresses. To bring an address back, add it
again with `--confirmed`.

Before the first send, set up SPF, DKIM and DMARC for the `from` domain and test locally with
Mailpit: [`docs/email.md`](email.md) has the DNS records and a deliverability checklist.

## Webhook for agents

The `webhook` channel POSTs versioned JSON events that any agent platform (or your own service)
can consume. Add one entry per target; each has its own `languages`, `events`, auth and format.

```json
{
  "type": "webhook",
  "enabled": true,
  "name": "agent",
  "languages": ["en"],
  "url": "${HERALD_WEBHOOK_URL}",
  "auth": { "type": "hmac", "secret": "${HERALD_WEBHOOK_SECRET}" },
  "events": ["briefing.published", "run.failed"],
  "format": "full"
}
```

Each delivery (`"format": "full"`, the default) is an envelope:

```json
{
  "spec": "herald.event/v1",
  "id": "evt_3f1c...",
  "type": "briefing.published",
  "created_at": "2026-11-30T09:00:12Z",
  "data": {
    "date": "2026-11-30", "language": "en", "title": "Herald — Monday, November 30, 2026",
    "url": null, "markdown": "# Herald — ...", "story_count": 12,
    "sections": [{ "profile": "markets-br", "name": "Brazil markets", "stories": [
      { "score": 8.5, "headline": "...", "summary": "...", "why_it_matters": "...",
        "sources": [{ "name": "Valor", "url": "https://...", "paywall": true }] }
    ] }]
  }
}
```

- **Events:** `briefing.published` (one per language) and `run.failed` (`date`, `language`,
  `run_id` and the error with secrets redacted). `events` defaults to both.
- **`id`** is the same for the same day, type and language (for `run.failed`: the same run), so
  drop events whose `id` you have already seen. The `X-Herald-Event` and `X-Herald-Event-Id`
  headers carry the type and id in every format.
- **Auth:** `{"type": "hmac", "secret": ...}` adds `X-Herald-Signature: t=<ts>,v1=<hex>`, an
  HMAC-SHA256 of `"<ts>." + body`; `{"type": "standard-webhooks", "secret": "whsec_..."}` signs
  per [Standard Webhooks](https://www.standardwebhooks.com/) (`webhook-id` = the event `id`,
  `webhook-timestamp`, `webhook-signature: v1,<base64>`), which OpenBot and Hermes accept;
  `{"type": "bearer", "token": ...}` sends
  `Authorization: Bearer <token>`; `headers` adds static headers. Values come from `.env` as
  `${VAR}`. If any of them is still an unresolved `${VAR}`, nothing is sent and the run report
  says which variable is missing. A top-level `secret` (older configs) still means HMAC.
- **Format:** `"full"` (the envelope), `"markdown"` or `"text"` (`{id, type, title, markdown}`
  or `{..., text}`), or a `template` for platforms that want their own shape, such as
  `"template": "{\"message\": \"$text\"}"`. Variables: `$date`, `$language`, `$title`,
  `$markdown`, `$text`, `$url`, `$count`, inserted JSON-escaped; any other `$` stays as is
  (write `$date`, not `${date}`, which is read as an environment variable). The result must be
  valid JSON or the delivery fails. `$url` and `data.url` link to the briefing's page when `site.base_url`
  is set.
- **Size cap:** `max_body_bytes` (optional, per target; OpenBot accepts 65536). A larger body is
  sent as `markdown` instead, cut at a section boundary and ending with a link to the full
  briefing when `site.base_url` is set; if even that is too large, nothing is sent and the run
  report says why.
- **Delivery:** `timeout_s` (default 10). Up to 3 retries with exponential backoff (2, 4, 8 s,
  or the receiver's `Retry-After`) on 5xx, 429 and network errors; never on other 4xx.
  Redirects are not followed: a 3xx counts as a failure.
  Failures go to the run report.

The JSON Schema is [`docs/schemas/herald-event-v1.json`](schemas/herald-event-v1.json);
signature checks in Python and Node are in [`docs/webhooks.md`](webhooks.md). To try it
without any agent platform, run the local receiver and point `url` at it:

```bash
uv run herald dev sink --port 8787 --secret "$HERALD_WEBHOOK_SECRET" --out herald-sink
# HERALD_WEBHOOK_URL=http://127.0.0.1:8787/ in .env, then: uv run herald
```

It checks the signature (`--standard-webhooks-secret` for Standard Webhooks, `--token` for
bearer), validates the envelope, prints one line per
event and saves each one as JSON in `--out`. Without `--secret` it accepts any signature, which is
enough to see the events arrive without putting the secret in your shell.

With the Docker image, `127.0.0.1` inside Herald's container is the container itself. Run the
receiver in a container of its own with the port published, listening on every interface, and
point the URL at the Docker bridge's gateway, which the second command prints:

```bash
docker run -d --name herald-sink --user "$(id -u):$(id -g)" -p 8787:8787 -v "$PWD/data:/app/data" ghcr.io/felipebossolani/herald:beta dev sink --host 0.0.0.0 --port 8787 --out /app/data/sink
docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}'
# HERALD_WEBHOOK_URL=http://172.17.0.1:8787/ in .env (that gateway address)
```

Step-by-step recipes for agent platforms (OpenBot, Hermes, OpenClaw, Claude Desktop / Claude
Code, n8n) are in [`docs/integrations/README.md`](integrations/README.md).

## Static site and feeds

With `site.enabled`, every briefing is also published to `site.dir` (default `docs/briefings`)
as plain HTML that any static host can serve: one page per day and language
(`2026-11-30.en.html`), its Markdown source (`2026-11-30.en.md`) and an `index.html` archive,
plus the PNG logos the email uses (`email-logo.png`, `email-logo-dark.png`).

Set `site.base_url` to the public URL of that folder and each language also gets three feeds,
one entry per day, with the latest `site.feed_days` briefings (default 30):

| File | Format |
|---|---|
| `<lang>/feed.xml` | RSS 2.0 |
| `<lang>/atom.xml` | Atom 1.0 |
| `<lang>/feed.json` | JSON Feed 1.1 |

```json
"site": {
  "enabled": true,
  "dir": "docs/briefings",
  "base_url": "https://you.github.io/herald/briefings",
  "feed_days": 30
}
```

For example, `https://you.github.io/herald/briefings/en/feed.xml`. Every page links its feeds
from `<head>`, so feed readers find them from the page address. Without `base_url` there are no
feeds, since feeds need absolute links. Pages and feeds are rebuilt from the Markdown sources on
every run; delete a `.md` file and its page goes too. An entry's update time changes only when
its text changes (tracked in `.feed-state.json`), so readers don't see old days as new. The
folder also gets a `.nojekyll`: when it is the root of a GitHub Pages branch deploy, Pages then
serves the files as they are instead of rendering the `.md` files over the `.html` pages (with
a parent folder such as `/docs` as the source, put a `.nojekyll` there). The daily GitHub
Actions workflow commits the folder.

**GitHub Pages.** `.github/workflows/pages.yml` publishes the project site (`site/`), the
brand assets and `docs/briefings` (as `briefings/`) on every push to `main` that touches them
and after each daily run. Turn it on once in Settings → Pages → Source: "GitHub Actions",
then set `base_url` to `https://<user>.github.io/<repo>/briefings`.
