# A reliable email-agent outbox

This Bun example receives signed Shipmail webhooks, stores one job per inbound message, freezes
a reply and requires a person to approve its content hash. It calls the real TypeScript SDK.
The tests replace HTTP responses and send no email.

The reply draft lives in this example's SQLite outbox. It is not a mutable draft in a mail
client. The send uses the exact approved text. If you use Shipmail reply drafts instead, approve
their content hash and send with `expected_content_sha256` so an edit invalidates approval.

## Set up

For a downloaded copy, put `workflow.ts`, `cli.ts` and this README in one directory. Run
`bun add shipmail zod` there. In the Shipmail checkout, run
`bun install --frozen-lockfile --ignore-scripts` at the repository root, then change to
`public/examples/reliable-agent`. Run the commands below from the example directory.

Use Bun, a persistent local volume and a private directory for the SQLite database. Do not put it on a network share.
It contains customer addresses and proposed email text; apply the same access, encryption,
backup and retention rules as your application database.

Configure these values through your deployment's secret manager. Never print API keys or signing
secrets in logs:

- `SHIPMAIL_OUTBOX_PATH`: the absolute database path, such as `/var/lib/agent/outbox.sqlite`.
- `SHIPMAIL_MAILBOX_ID`: the one mailbox this receiver serves.
- `SHIPMAIL_FROM`: that mailbox's exact full address.
- `SHIPMAIL_ALLOWED_SENDERS`: comma-separated exact addresses. A domain match is not enough here.
- `SHIPMAIL_WEBHOOK_SECRET`: the secret for a `message.received` webhook on that mailbox.
- `SHIPMAIL_READ_API_KEY`: the mailbox-scoped read key used for reconciliation.
- `SHIPMAIL_SEND_API_KEY`: the separate mailbox-scoped sending key.
- `SHIPMAIL_APPROVER`: the operator label used by the separate human approval process.

Create the webhook with `authenticated_senders_only: true` and the same `allowed_senders` list.
The receiver checks both again and ignores test events. Configure TLS and a public URL through
your normal application ingress. It listens on port 3101 at `/webhooks/shipmail`.

Keep credentials in separate processes:

- The webhook receiver needs only the webhook secret, not an API key.
- The agent's read key needs `mailboxes:read` and `messages:read`, limited to this mailbox. It
  cannot approve or send.
- The sending process uses `SHIPMAIL_SEND_API_KEY`, with `mailboxes:read`, `messages:read` and
  `messages:send`, limited to the same mailbox and allowed recipients.
- A separate human process sets `SHIPMAIL_APPROVER` to an operator label and may approve the
  local outbox. That label is a local audit annotation, not an authentication mechanism.

Do not give the model a shell, database-write access, approval credentials or the sending key.
Separate operating-system accounts or application authorization must enforce that boundary.
Protect both the database file and its directory. The receiver and worker belong to one trusted
application; this example does not sandbox mutually untrusted processes.

## Run the workflow

Start the receiver:

```sh
bun cli.ts listen
```

It verifies the raw signature, checks the sender and mailbox, and commits the job before returning 204. It prints only a job ID. A retried event or a different event for the same mailbox/message
does not create another job. No model or outbound call runs inside the HTTP request.

Have your worker read the message through `shipmail.mailboxes.getInboxMessage`. Treat the body
and attachment names as untrusted data. The receiver queues only a `not_flagged` security verdict;
it ignores flagged, unscanned and legacy events with no verdict so a person can review them. The
scanner is deterministic pattern matching, not a guarantee that content is safe. It scans body
text and attachment names, not attachment contents. This example does not download attachments:
add explicit count, type and byte limits before a worker does so. The receiver also rejects webhook
bodies over 256 KB. The human must review the original message as well as the proposed reply.

Generate the reply once and save the proposed text in a private file. Freeze it in the outbox:

```sh
bun cli.ts draft JOB_ID /private/proposed-reply.txt
bun cli.ts show JOB_ID
```

Review the mailbox, recipient and complete text in `draft_json`. Check the original message in
Shipmail for its subject and context. Pass the printed `draft_hash` to the approval command:

```sh
bun cli.ts approve JOB_ID EXACT_DRAFT_HASH
```

The separate sending process verifies the mailbox's From address before sending:

```sh
bun cli.ts send JOB_ID
```

The outbox claims the approved job atomically. Two workers cannot both dispatch it. The reply
uses a fixed `client_reference` and `Idempotency-Key` derived from the mailbox/message job. The
reference survives API-key rotation and the response-cache lifetime. An already frozen reply
cannot acquire new text by repeating `draft`.

## Recover an interrupted send

```sh
bun cli.ts reconcile JOB_ID
```

If Shipmail returned a reconciliation message ID, the command reads it. Otherwise, it searches
by the permanent client reference. It records completion only after it sees positive send evidence
for this mailbox and reference. A bounce or complaint also proves dispatch, so it never resends
those messages.

If Shipmail still reports `queued`, leave the job held and run `reconcile` again later. A queued
record is not positive evidence of dispatch.

If the result is absent or inconclusive, leave the job in `sending` or `needs_review`. Check
Shipmail's activity and contact support with the logical reference. Do not clear that state,
regenerate the text, change the key or create another job just because a request timed out. A
process can die after dispatch but before recording the result. This example deliberately requires
an operator when it cannot prove the outcome.

SQLite is suitable for this single-host example. Use your database's transactional outbox and
claims when moving to several application hosts. Keep receipts and logical-send records for the
entire period in which your application might replay events; a short cache is not sufficient.

## Test without sending

In the Shipmail checkout, run this from the repository root:

```sh
bun test ./examples/reliable-agent/workflow.test.ts
```

The tests cover duplicate events, authenticated and `not_flagged` admission, exact approval,
concurrent senders, interrupted processes, ambiguous provider results and recovery after API-key
rotation.
