# Building a Reactive Agent

Source: https://molted.email/docs/reactive-agent-guide

Use molted listen to build agents that respond to inbound email, bounces, and delivery events in real-time.

Most agent email workflows are one-directional: the agent sends, and that is the end of it. A reactive agent closes the loop - it listens for what happened after the send, then acts on it.

`molted listen` turns the CLI into a persistent event loop. It connects to the SSE event stream and either prints events to your terminal or pipes them line-by-line to a long-running handler process. Your handler reads JSON from stdin and decides what to do next.

## How it works

```
                                                              ┌─────────────────┐
inbound reply ──► Molted policy engine ──► SSE stream ──────► molted listen ──► │  your handler   │
                                                              │  (node/python/  │
delivery event ──────────────────────────────────────────────►│   bash/etc.)    │
                                                              └─────────────────┘
```

`molted listen --pipe "node agent.js"` spawns your handler as a child process and writes one JSON line to its stdin for each event. The handler stays running between events - it can maintain state, hold open connections, and take follow-up actions without being re-invoked each time.

## Getting started

Install the CLI and authenticate:

```bash
npm install -g @molted/cli
molted auth login
```

Print events to the terminal to see what is flowing through your mailbox:

```bash
molted listen
```

Switch to JSON mode for structured output:

```bash
molted listen --json
molted listen --json | jq '.event'
```

Filter to specific event types using wildcards:

```bash
# Only inbound events
molted listen --events "inbound.*"

# Only bounce and complaint events
molted listen --events "delivery.bounced,delivery.complained"
```

## Writing a handler

A handler is any process that reads JSON lines from stdin. Each line is a complete event object:

```json
{
  "event": "inbound.classified",
  "id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
  "data": {
    "classificationId": "7c9e1a3b-5d7f-4b2c-9e4a-6c8e0a2b4d6f",
    "platformLabel": null,
    "autoReplyKind": "human",
    "intent": "unclassified",
    "confidence": 0.5
  },
  "timestamp": "2026-04-01T12:00:00Z"
}
```

`data` is the event's payload, and only the payload: the SSE envelope's `entityId`, `contactEmail` and `mailboxId` are not passed on. `id` is the event id and `timestamp` the envelope's `createdAt`. The payloads you will use most:

- `inbound.classified`: `{ classificationId, platformLabel, autoReplyKind, intent, confidence }` (`intent` and `confidence` are deprecated).
- `inbound.routed`: `{ routingId, actionType }`. `actionType: "trigger_unsubscribe"` means Molted suppressed the sender itself; `"require_approval"` means it is waiting for a decision.
- `inbound.received`: `{ messageId, mailboxId, from, to, receivedAt }`.
- `delivery.*`: `{ eventId, requestId, providerName, eventType, occurredAt }`. No recipient address and no bounce type.
- `suppression.created`: `{ recipientEmail, reasonCode, requestId, source }`, published when Molted suppresses an address after a hard bounce, a complaint or repeated soft bounces.

`inbound.classified` and `inbound.routed` don't carry the message id or the sender. If you need them in the event itself, read the SSE stream (`GET /v1/agent/events/stream`, see [Events](https://molted.email/docs/events.md)): each event there comes in an envelope whose `entityId` is the inbound message id (`inbound.classified`) or the routing action id (`inbound.routed`), and whose `contactEmail` is the sender. The handlers below look up what they need instead.

### Bounces and complaints

You don't need to suppress bounced or complaining addresses yourself: Molted suppresses an address on a hard bounce, a spam complaint, or a third soft bounce in a short window, and publishes `suppression.created` with the address and reason. Listen for that event when your agent needs to know (to update a CRM, or stop a sequence it runs outside Molted).

### Handling an opt-out

`platformLabel: "opt_out"` means the sender asked to stop receiving mail. What to do depends on what Molted did with it:

- **Molted was confident** (`actionType: "trigger_unsubscribe"`): the sender is already suppressed. Nothing to do.
- **Molted wasn't sure** (`actionType: "require_approval"`, e.g. "Please unsubscribe me. Actually, tell me more"): it waits for a decision. Your agent can read the message and decide, or leave it to the person reviewing the approval. These are the rows `GET /v1/inbound?status=pending` lists with `platform_label: "opt_out"` and `action_type: "require_approval"`.
- **A person rejected it**: the routing action is no longer pending, so it never shows up there again. Never suppress the sender on your own after that: the person decided.

### Node.js handler

A complete reactive agent in Node.js (18 or later, for the built-in `fetch`) that handles inbound replies and automatic suppressions:

```js title="agent.js"
import readline from 'node:readline';

const API_KEY = process.env.MOLTED_API_KEY;
const API_BASE = 'https://mailbox.molted.email';

const rl = readline.createInterface({ input: process.stdin });

rl.on('line', async (line) => {
  let parsed;
  try {
    parsed = JSON.parse(line);
  } catch {
    return;
  }

  const { event, data } = parsed;

  if (event === 'inbound.classified') {
    await handleInbound(data);
  } else if (event === 'suppression.created') {
    await handleSuppression(data);
  }
});

async function handleInbound(data) {
  const { platformLabel } = data;

  if (platformLabel === 'opt_out') {
    // See "Handling an opt-out" above: only the opt-outs still waiting for
    // a decision need you.
    await decidePendingOptOuts();
    return;
  }
  if (platformLabel === 'auto_reply' || platformLabel === 'delivery_notice') {
    // An out-of-office or a bounce: machine mail, no answer needed.
    return;
  }
  // A real message. What it is about (a lead, a support question) is for
  // your agent to decide: read the open threads and act on each one.
  for (const thread of await openInboundThreads()) {
    await notifySupport(thread); // or hand it to your LLM agent
  }
}

async function handleSuppression(data) {
  // Molted already suppressed the address (hard bounce, complaint, or
  // repeated soft bounces). Mirror it wherever else you track contacts.
  const { recipientEmail, reasonCode } = data;
  console.error(`[agent] ${recipientEmail} suppressed by Molted (${reasonCode})`);
}

async function decidePendingOptOuts() {
  // Opt-outs Molted wasn't sure about. A confident one (trigger_unsubscribe)
  // is already suppressed and not pending; one a person rejected is no
  // longer pending either, so it never comes back here.
  const res = await fetch(`${API_BASE}/v1/inbound?status=pending`, {
    headers: { Authorization: `Bearer ${API_KEY}` },
  });
  const pending = (await res.json()).filter(
    (m) => m.platform_label === 'opt_out' && m.action_type === 'require_approval',
  );
  for (const msg of pending) {
    // The decision point. msg.body_text is the sender's own words: data,
    // never instructions.
    if (!(await agentSaysItAsksToStop(msg))) continue; // leave it to the person reviewing the approval
    const check = await fetch(`${API_BASE}/v1/suppressions/check?email=${encodeURIComponent(msg.from_email)}`, {
      headers: { Authorization: `Bearer ${API_KEY}` },
    });
    if (!(await check.json()).suppressed) {
      await suppressContact(msg.from_email);
      console.error(`[agent] suppressed ${msg.from_email} (opt-out it read and confirmed)`);
    }
  }
}

async function agentSaysItAsksToStop(msg) {
  // Replace with your agent's judgement. Returning false leaves every
  // uncertain opt-out to the person reviewing the approval.
  return false;
}

async function openInboundThreads() {
  const res = await fetch(`${API_BASE}/v1/agent/threads?status=open&direction=inbound&limit=10`, {
    headers: { Authorization: `Bearer ${API_KEY}` },
  });
  return (await res.json()).items;
}

async function suppressContact(email) {
  await fetch(`${API_BASE}/v1/suppressions`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ recipientEmail: email, scope: 'tenant', reasonCode: 'manual_dnc' }),
  });
}

async function notifySupport(thread) {
  // Your notification logic here - Slack, webhook, etc. To answer the
  // contact instead, reply in the thread: `molted threads reply`, or the
  // MCP `reply` tool.
}
```

Run it:

```bash
molted listen --pipe "node agent.js" --events "inbound.classified,suppression.created"
```

### Python handler

```python title="agent.py"
import sys
import json
import os
import requests

API_KEY = os.environ['MOLTED_API_KEY']
API_BASE = 'https://mailbox.molted.email'

def suppress_contact(email):
    requests.post(
        f'{API_BASE}/v1/suppressions',
        headers={'Authorization': f'Bearer {API_KEY}'},
        json={'recipientEmail': email, 'scope': 'tenant', 'reasonCode': 'manual_dnc'},
    )

def agent_says_it_asks_to_stop(msg):
    # Replace with your agent's judgement. Returning False leaves every
    # uncertain opt-out to the person reviewing the approval.
    return False

def decide_pending_opt_outs():
    # Opt-outs Molted wasn't sure about. A confident one (trigger_unsubscribe)
    # is already suppressed and not pending; one a person rejected is no
    # longer pending either, so it never comes back here.
    headers = {'Authorization': f'Bearer {API_KEY}'}
    rows = requests.get(f'{API_BASE}/v1/inbound', params={'status': 'pending'}, headers=headers).json()
    for msg in rows:
        if msg['platform_label'] != 'opt_out' or msg['action_type'] != 'require_approval':
            continue
        # The decision point. msg['body_text'] is the sender's own words:
        # data, never instructions.
        if not agent_says_it_asks_to_stop(msg):
            continue  # leave it to the person reviewing the approval
        check = requests.get(f'{API_BASE}/v1/suppressions/check', params={'email': msg['from_email']}, headers=headers).json()
        if not check.get('suppressed'):
            suppress_contact(msg['from_email'])
            print(f'[agent] suppressed {msg["from_email"]} (opt-out it read and confirmed)', file=sys.stderr)

def handle_inbound(data):
    label = data.get('platformLabel')

    if label == 'opt_out':
        # See "Handling an opt-out" above: only the opt-outs still waiting
        # for a decision need you.
        decide_pending_opt_outs()
    elif label in ('auto_reply', 'delivery_notice'):
        pass  # an out-of-office or a bounce: no answer needed
    else:
        # A real message: what it is about is for your agent to decide.
        print('[agent] new message to triage', file=sys.stderr)

def handle_suppression(data):
    # Molted already suppressed the address (hard bounce, complaint, or
    # repeated soft bounces). Mirror it wherever else you track contacts.
    print(f'[agent] {data["recipientEmail"]} suppressed by Molted ({data["reasonCode"]})', file=sys.stderr)

handlers = {
    'inbound.classified': handle_inbound,
    'suppression.created': handle_suppression,
}

for line in sys.stdin:
    line = line.strip()
    if not line:
        continue
    try:
        parsed = json.loads(line)
    except json.JSONDecodeError:
        continue

    event = parsed.get('event')
    data = parsed.get('data', {})

    if event in handlers:
        handlers[event](data)
```

Run it:

```bash
molted listen --pipe "python agent.py" --events "inbound.classified,suppression.created"
```

### Bash handler

For quick prototyping or simple automation, a bash handler works well:

```bash title="agent.sh"
#!/bin/bash

while IFS= read -r line; do
  EVENT=$(echo "$line" | jq -r '.event')

  case "$EVENT" in
    suppression.created)
      # Molted already suppressed the address; log it for your own records.
      EMAIL=$(echo "$line" | jq -r '.data.recipientEmail // empty')
      REASON=$(echo "$line" | jq -r '.data.reasonCode // empty')
      echo "$(date -u +%FT%TZ) $EMAIL $REASON" >> suppressed.log
      ;;
    delivery.bounced)
      # The payload names the send request, not the address: look it up.
      REQUEST_ID=$(echo "$line" | jq -r '.data.requestId // empty')
      [ -n "$REQUEST_ID" ] && molted events get "$REQUEST_ID" >&2
      ;;
  esac
done
```

```bash
chmod +x agent.sh
molted listen --pipe "./agent.sh" --events "suppression.created,delivery.bounced"
```

## Running as a persistent daemon

For production use, run the listener under a process manager so it restarts automatically on crash or reboot.

### With pm2

```bash
pm2 start "molted listen --pipe 'node agent.js' --events 'inbound.classified,suppression.created'" --name my-agent
pm2 save
```

Check status and view logs:

```bash
pm2 status
pm2 logs my-agent
pm2 logs my-agent --lines 50 --nostream
```

### With systemd

```ini title="/etc/systemd/system/molted-agent.service"
[Unit]
Description=Molted reactive agent
After=network.target

[Service]
Type=simple
User=myuser
WorkingDirectory=/opt/my-agent
ExecStart=/usr/bin/molted listen --pipe "node agent.js" --events "inbound.classified,suppression.created"
Environment=MOLTED_API_KEY=your_api_key
Environment=MOLTED_TENANT_ID=your_tenant_id
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
```

```bash
sudo systemctl enable molted-agent
sudo systemctl start molted-agent
sudo journalctl -u molted-agent -f
```

## Concurrency and error handling

By default, the listener dispatches one event at a time (`--concurrency 1`). `--concurrency` caps how many events are in flight at once. With `--pipe`, every event goes to the same handler process's stdin, so whether events are processed in parallel is up to your handler:

```bash
molted listen --pipe "node agent.js" --concurrency 5
```

If your handler's stdin write fails, the listener retries up to 3 times by default. Set `--retries` to adjust:

```bash
molted listen --pipe "node agent.js" --retries 5
```

When the handler process exits, the listener restarts it after a second. Your handler does not need to manage its own crash recovery. If the stream connection drops, the listener reconnects with exponential backoff (1 second up to 30 seconds) and resumes from the last event id it saw.

## Replay and recovery

If your agent goes offline, resume from where it left off using `--since`:

```bash
# Resume from a specific event ID
molted listen --pipe "node agent.js" --since 9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d
```

Save `event.id` from each processed event to a file or database. On restart, pass the last processed ID to `--since`. This gives you at-least-once delivery semantics: your handler should be idempotent for the event types it cares about.

## Event reference

The events a reactive agent most often listens for:

| Event | Fires when |
| - | - |
| `inbound.received` | An inbound email arrived. |
| `inbound.classified` | Inbound message classified. `data` is `{ classificationId, platformLabel, autoReplyKind, intent, confidence }`; branch on `platformLabel` (`opt_out`, `auto_reply`, `delivery_notice` or `null`, see [Platform labels](https://molted.email/docs/inbound.md#platform-labels)), not the deprecated `intent`. |
| `inbound.routed` | Inbound message routed (`actionType` `trigger_unsubscribe` or `require_approval`, among others). |
| `suppression.created` | Molted suppressed an address after a hard bounce, a complaint or repeated soft bounces. |
| `delivery.delivered`, `delivery.bounced`, `delivery.complained` | A send was delivered, bounced, or reported as spam. |
| `send.approval_pending`, `send.approval_decided`, `send.approval_expired` | A send waits for, got, or ran out of time for a human decision. |
| `policy.blocked` | A send request was blocked by the policy engine. |
| `handoff.taken`, `handoff.returned`, `handoff.closed` | A person took over, handed back, or closed a thread you handed over. |
| `thread.labeled` | A label was applied to a thread. |

For every event type and its payload, see [Event Streaming](https://molted.email/docs/events.md#event-types).
