# Hand a WhatsApp AI agent conversation to a human in Chatwoot

> A handoff contract for WhatsApp AI agents in Chatwoot. The bot owns pending conversations, opens them for a person, and stays silent until they return.

Published 2026-11-02. Z-API Omni team.

Connect the AI agent to the WhatsApp inbox as a Chatwoot Agent Bot and let the conversation status carry the ownership. With a bot attached, "new conversations are automatically assigned a _pending_ status" ([How to use Agent bots](https://www.chatwoot.com/hc/user-guide/articles/1677497472-how-to-use-agent-bots)). The bot answers only while a conversation is `pending`. To hand off, it calls the status API with `open`, which the same guide says will "make the conversation available to a human". A person gives the conversation back by setting it to `pending` again.

## The handoff contract

Write down when the bot stops before you write code. Use three triggers.

The customer asks for a person. Match it in code on the raw message, before the model runs, so a model that misreads the request cannot keep the customer in a loop.

The model is not sure. The system message in [How to put an AI agent on WhatsApp with n8n](/academy/articles/whatsapp-ai-agent-n8n-step-by-step/) makes the model reply with the single word `HANDOFF` when it is unsure. Treat that word, an empty answer or a tool error the same way.

The topic is one you never want automated. Refunds, chargebacks, legal threats and account closure are common entries. Keep the list in code as well as in the prompt, because a prompt is a request to the model and a regex is a rule.

The contract also says what happens after the handoff. The bot sends one fixed sentence that a person will continue, leaves a private note with the reason, and goes silent. A model never writes the customer-facing sentence, so it cannot promise a time or a refund.

## The conversation status is the state

Chatwoot's toggle status endpoint takes one of four values: `open`, `resolved`, `pending` and `snoozed` ([Toggle Status](https://developers.chatwoot.com/api-reference/conversations/toggle-status)). Read them as ownership. `pending` means the bot owns the conversation. `open` means a person owns it. `resolved` and `snoozed` mean nobody is answering right now.

Keep no second "bot paused" flag in your own database. Two flags drift apart the first time an agent changes the status in the UI and your copy doesn't hear about it. The webhook guide notes that `conversation_status_changed` "is not supported yet" for agent bot APIs ([How to use webhooks](https://www.chatwoot.com/hc/user-guide/articles/1677693021-how-to-use-webhooks)), so you could miss that event. The conversation object in each payload carries a `status`. Check it on every event and act only on `pending`.

## Attach the bot to the inbox

1. In Chatwoot, go to Settings > Bots, click Add Bot, and enter a name and your webhook URL.
2. Open the WhatsApp inbox, pick the bot under Bot Configuration and click Save. The API equivalent is `POST /api/v1/accounts/{account_id}/inboxes/{id}/set_agent_bot` with the bot's ID in `agent_bot` ([Add or remove agent bot](https://developers.chatwoot.com/api-reference/inboxes/add-or-remove-agent-bot)).
3. Copy the bot's access token and its secret. Chatwoot generates a secret for each bot "that you can use to verify the payload your application receives".

The bot receives events such as `message_created` and `message_updated`. Each signed request carries `X-Chatwoot-Timestamp` and `X-Chatwoot-Signature`. Chatwoot's source computes the signature as `sha256=` plus the hex HMAC-SHA256 of the timestamp, a dot and the raw body ([lib/webhooks/trigger.rb, develop branch, accessed 2026-11-02](https://github.com/chatwoot/chatwoot/blob/develop/lib/webhooks/trigger.rb)).

The same file explains why the handler must answer fast. The request timeout defaults to 5 seconds. Failed agent bot deliveries other than HTTP 429 and 500 go to a failure handler. For `message_created`, it reopens the pending conversation unless `keep_pending_on_bot_failure` is set. A slow model call therefore hands the customer to a person by accident. Answer 200 first and call the model afterwards.

## The bot's webhook handler

This Node.js 18+ handler verifies the signature, ignores anything it does not own, and either replies or hands off. Save it as `bot.mjs`. Replace `askAgent` with your model call.

```javascript
import http from 'node:http';
import { createHmac, timingSafeEqual } from 'node:crypto';

const BASE = process.env.CHATWOOT_URL;          // https://app.chatwoot.com or your install
const TOKEN = process.env.CHATWOOT_BOT_TOKEN;   // agent bot access token
const SECRET = process.env.CHATWOOT_BOT_SECRET; // agent bot secret
const TEAM_ID = Number(process.env.HANDOFF_TEAM_ID || 0);

const ASKS_FOR_HUMAN = /\b(human|person|real agent|talk to someone)\b/i;
const SENSITIVE = /\b(refund|chargeback|lawyer|cancel my account)\b/i;

function signatureOk(rawBuf, ts, sig) {
  if (!SECRET || !ts || !sig) return false;
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const mac = createHmac('sha256', SECRET).update(`${ts}.`).update(rawBuf).digest('hex');
  const expected = Buffer.from(`sha256=${mac}`);
  const got = Buffer.from(sig);
  return got.length === expected.length && timingSafeEqual(got, expected);
}

async function chatwoot(path, body) {
  const res = await fetch(`${BASE}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', api_access_token: TOKEN },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`${path} returned ${res.status}`);
}

async function askAgent(text) {
  return { text: `You wrote: ${text}` }; // replace with your model call
}

async function handle(evt) {
  if (evt.event !== 'message_created' || evt.message_type !== 'incoming') return;
  if (evt.conversation?.status !== 'pending') return; // a person owns it
  const conv = `/api/v1/accounts/${evt.account.id}/conversations/${evt.conversation.display_id}`;
  const text = evt.content ?? '';

  let reason = ASKS_FOR_HUMAN.test(text) ? 'customer asked for a person'
    : SENSITIVE.test(text) ? 'sensitive topic' : null;
  let answer = null;
  if (!reason) {
    try { answer = await askAgent(text); } catch { reason = 'model error'; }
    if (answer && (!answer.text || answer.text.includes('HANDOFF'))) reason = 'model unsure';
  }

  if (reason) {
    await chatwoot(`${conv}/messages`, { content: `Bot handoff: ${reason}`, message_type: 'outgoing', private: true });
    await chatwoot(`${conv}/messages`, { content: 'A person from our team will continue here.', message_type: 'outgoing' });
    if (TEAM_ID) await chatwoot(`${conv}/assignments`, { team_id: TEAM_ID });
    await chatwoot(`${conv}/toggle_status`, { status: 'open' });
    return;
  }
  await chatwoot(`${conv}/messages`, { content: answer.text, message_type: 'outgoing' });
}

http.createServer((req, res) => {
  const chunks = [];
  req.on('data', (c) => chunks.push(c));
  req.on('end', () => {
    const rawBuf = Buffer.concat(chunks);
    const ok = signatureOk(rawBuf, req.headers['x-chatwoot-timestamp'], req.headers['x-chatwoot-signature']);
    res.writeHead(ok ? 200 : 401).end();
    if (!ok) return;
    let evt;
    try { evt = JSON.parse(rawBuf.toString('utf8')); } catch { return; }
    handle(evt).catch((err) => console.error(err));
  });
}).listen(3000);
```

The `message_type` check drops the bot's own replies, which come back as `outgoing` events. The URL uses `display_id` because Chatwoot's conversation controllers look conversations up by `display_id` within the account ([base_controller.rb](https://github.com/chatwoot/chatwoot/blob/develop/app/controllers/api/v1/accounts/conversations/base_controller.rb)). The messages, assignments and toggle status endpoints all accept agent bot tokens ([Create New Message](https://developers.chatwoot.com/api-reference/messages/create-new-message), [Assign Conversation](https://developers.chatwoot.com/api-reference/conversation-assignments/assign-conversation)). The `api_access_token` header still works but is marked for deprecation. From v4.19.0, `Authorization: Bearer` is the recommended form. When you send both `assignee_id` and `team_id`, the assignment API ignores `team_id`.

## Give the conversation back

An agent returns the conversation by setting its status to `pending` in the UI, and the bot picks up on the customer's next message. Agree on two habits with the team. Agents set a conversation to Open before they type, so the bot is never mid-reply when a person starts. They resolve a conversation instead of leaving it open once the issue is closed, so the inbox shows real ownership.

## WhatsApp-specific limits

On a WhatsApp Cloud API inbox, the human takeover inherits Meta's 24-hour window. Once it closes, Chatwoot's reply box shows "You can only reply using a template message due to 24-hour message window restriction" ([Templates and the 24-hour window](https://www.chatwoot.com/hc/user-guide/articles/1754940076-whatsapp-templates)). A handoff late on a Friday can reach a person after the window has closed. [WhatsApp error 131047: the 24-hour window and templates](/academy/articles/whatsapp-error-131047-24-hour-window-templates/) covers the rule.

Chatwoot's WhatsApp inbox supports the WhatsApp Cloud API and Twilio, and "360dialog is no longer offered for new inboxes" ([How to setup a WhatsApp channel](https://www.chatwoot.com/hc/user-guide/articles/1677832735-how-to-setup-a-whats_app-channel)). A QR connection goes in through an API channel inbox instead. You create the contact, conversation and incoming messages through the API, and Chatwoot posts `message_created` to the inbox's callback URL ([API channel inbox](https://www.chatwoot.com/hc/user-guide/articles/1677839703-how-to-create-an-api-channel-inbox)). Your bridge sends the `outgoing`, non-private messages to WhatsApp. Private notes stay in Chatwoot.

*Z-API Omni team*
