# Email for agents

An agent does not read a dashboard. It needs a decision it can act on: accepted
or refused, why, and whether a retry is safe. Everything below exists so an
agent can send, wait and react without a human watching a screen.

## The four things an agent needs

1. **A fast accept.** A send returns `202` with a message id as soon as the
   message is durable. Delivery happens after that, so the agent never blocks on
   a mail server.
2. **A retry key.** Send `Idempotency-Key: <key>`. The same key twice returns
   the same message id and sends nothing twice, which is what makes a retry safe
   after a timeout the agent cannot interpret.
3. **Stable codes, not prose.** Every refusal carries `code`, `error`, `hint`
   and `retryable`. Branch on `code`, never on the message text.
4. **A way to learn the outcome.** Poll the message, or subscribe to the signed
   webhook, or point an alert sink at Slack, Teams or Discord.

## Give the agent its own key, with limits

Create a workspace key with `kind: agent`. Three fields matter:

- `daily_send_cap` counts sends per calendar day in UTC. Zero means unlimited
  but still counted.
- `recipient_allowlist` limits who the key may write to. A foreign recipient is
  refused with `422 recipient_not_allowed`, before any content is built.
- `approval_threshold` refuses a send with more recipients than the threshold,
  with `422 approval_required`, and raises the `approval.required` event. The
  agent then waits for a human instead of retrying in a loop.

A rotated key inherits all three limits, so rotation never widens access.

## A minimal loop

```
# once, server side
POST /api/practices/{id}/api-tokens
{ "name": "agent", "kind": "agent", "daily_send_cap": 500,
  "recipient_allowlist": ["customer.example"], "approval_threshold": 25 }

# per message
POST /api/transactional.send
{ "workspace_id": "...", "template": "magic-link",
  "contact": { "email": "user@customer.example" },
  "data": { "link": "https://app.example/login/abc" },
  "external_id": "login-42" }
Idempotency-Key: login-42-1
```

`external_id` is the agent's own key for the business event, so a second attempt
for the same event does not become a second mail.

## How the gates answer an agent

| Situation | Answer | What the agent should do |
| --- | --- | --- |
| Recipient outside the allowlist | `422 recipient_not_allowed` | Stop. This is a configuration decision, not a transient error. |
| More recipients than the threshold | `422 approval_required` plus `approval.required` | Wait for the approval, do not split the audience to dodge the gate. |
| Daily cap reached | `429 token_daily_cap_reached` | Stop for the day. Splitting across keys to bypass a cap is abuse. |
| Recipient suppressed | `422 suppressed` | Stop. A suppression is a person's decision or a hard bounce. |
| Domain not verified | `422 send_failed` with `domain_not_verified` | Stop. Fix the sender, do not rotate the key. |
| Rate limited | `429` with `Retry-After` | Sleep the given time and retry with the same idempotency key. |
| Provider or queue unavailable | `5xx` with `retryable: true` | Retry with backoff and the same idempotency key. |

A `4xx` that is not `408` or `429` is permanent. Retrying it only burns quota
and, for a bounced address, damages reputation.

## Reading the outcome

`GET /api/practices/{id}/messages/{messageID}` moves `processed` to `delivered`
or to a failure. `GET .../messages/{messageID}/timeline` and `/events` show the
stages, so an agent can explain a delay instead of guessing.

The signed webhook carries the same events asynchronously, with a signature the
agent verifies before trusting the body. The alert sinks carry the events that
need a human: hard bounce, complaint, automatic pause, approval required,
webhook degraded.

## Reading replies as structured data

An agent that only sends is half a loop. Inbound replies arrive as JSON, not as
raw MIME:

- `from_address`, `to_addresses`, `subject`, `text_body`, `html_body`
- `in_reply_to`, `references_header` exactly as the sender wrote them
- `reply_to_message_id` pointing at the message that was answered
- `reply_match` with `exact`, `reference` or `window`, so the agent knows how
  confident the match is
- `is_auto_reply`, so an out-of-office message does not trigger a workflow
- SPF, DKIM, DMARC, spam and virus verdicts

Matching is scoped to one workspace and never crosses tenants. No match means
an empty field, not a guess.

## What an agent must never do

- **Never put several unrelated recipients in one `to`.** The envelope limit is
  50 addresses, and everyone in the envelope sees the others. Audiences go on a
  list or a broadcast.
- **Never send marketing to a contact without consent.** The newsletter channel
  is a separate grant and the send is refused with `newsletter_consent_missing`.
  A refusal is a veto, not a hint to try another route.
- **Never invent a sender.** `from` is a bare address on a verified domain. The
  display name goes in `from_name`.
- **Never parse a bounce out of a message body.** The event carries the verdict.
- **Never create a key per request.** Keys are audited and limited; a key per
  call defeats both.

## Where the limits are visible

- `GET /api/meta` shows the environment, sandbox state and allowlist length.
- `GET /api/practices/{id}/deliverability` shows the gate state before a send.
- `POST /api/practices/{id}/send/score` is the free pre flight. It returns the
  content score, the scanner verdict, the size grade and the reasons, without
  sending anything.
- `/errors` lists every stable code with its retryability.
