Developer guide
WhatsApp AI Agent Human Takeover: Pause the Bot When You Reply From Your Phone
On a WhatsApp Coexistence number, Meta sends your server an smb_message_echoes webhook each time someone at the business sends a message from the WhatsApp Business app or a supported linked device. Treat that webhook as the takeover signal: pause the agent for that one conversation, and check the pause again right before every send. The webhook carries no resume signal, so you decide when the agent comes back, for example with a timer that restarts with each staff message.
The whole pattern in three rules:
- keep one pause per conversation, not one for the whole number;
- save the pause before you answer Meta with 200;
- check the pause before the model writes and again before the reply goes out.
This guide is published by Dualhook, a Meta Technology Partner. The facts about WhatsApp come from Meta's documentation. The code was run on 24 November 2026 against the example payloads in that documentation.
Which webhook tells you a person replied?
Branch on the field name of each change. Only one field is a takeover:
| Webhook field | What Meta reports | What the agent does |
|---|---|---|
smb_message_echoes | The business sent, edited or deleted a message with the WhatsApp Business app, or sent one from a companion (linked) device | Pause this conversation |
messages, with a messages array | A customer sent a message | Answer it, unless the conversation is paused |
messages, with a statuses array | The status of a message the business sent, such as sent, delivered, read or failed | Update delivery records. Never start or pause the agent |
history | Past chats, synchronized after onboarding if the business agreed to share them | Store them if you want. Never start or pause the agent |
smb_app_state_sync | Contacts of the WhatsApp Business app: synchronized, added, edited or removed | Update your contacts. Never start or pause the agent |
The Meta app that onboarded the number must be subscribed to smb_message_echoes. Do not branch on the array name: a history webhook for media messages can carry the same messages and message_echoes arrays, so code that only looks for those arrays can treat an old chat as a new one.
Can your agent's own messages come back as echoes? Meta's list of triggers names the WhatsApp Business app and companion devices. Sending with the API is not on it. Test it once before you go live: send one API message and check that no echo arrives.
Which ID should the pause use?
Use two values together: your business number (metadata.phone_number_id) and the customer's business-scoped user ID (BSUID). In an echo the BSUID is to_user_id. In a customer message it is from_user_id.
- Phone numbers can be missing. Meta omits
to,fromandwa_idwhen the customer has adopted a username and the phone number is unavailable. - A BSUID belongs to one business portfolio. Two of your numbers in that portfolio see the same BSUID for one customer, so your own number has to be in the key.
- Save the pause under both IDs. The reference says
to_user_idis always included, but the example in Meta's onboarding guide shows an echo without it. The code below uses each identifier that is present. - A BSUID can change. When a customer changes phone number, Meta sends a
systemmessage with the newuser_idand, if available,previous_user_id. Copy a running pause to the new ID. The sample does not do this.
When is the agent active, and when is it paused?
Each conversation has two states and needs two timestamps:
atis the time of the newest echo. It lets you ignore an echo that arrives late.untilis the time the pause ends. When it has passed, the next customer message finds the agent active again. You need no scheduled job.
Take both times from the echo's timestamp, not from your own clock. Then a late or repeated delivery of the same echo does not extend the pause. Compare them with the timestamp of the customer message. Then a question from during the pause stays with your team, even if its webhook arrives later.
How do you build the pause?
- Read every change. Meta can batch up to 1,000 updates in one POST, so loop over
entryandchanges. - Save the pauses. For each echo, store
atanduntilfor that conversation. - Answer 200. Do this after the pauses are saved and before the model runs.
- Claim the customer message. Record its ID. If you have seen it before, stop.
- Check the pause. If a person has the conversation, or the 24-hour window has closed, stop.
- Write the reply. Call your model.
- Check the pause again. If a person stepped in meanwhile, drop the reply.
- Send it. Make this the only step after the second check.
The module below does all of it in plain JavaScript, without dependencies:
// takeover.mjs: no dependencies. Needs Request, Response and fetch
// (Node.js 18 or later, Cloudflare Workers, Deno).
const HOLD_MS = 60 * 60 * 1000; // pause after each staff message: your choice
const WINDOW_MS = 24 * 60 * 60 * 1000; // Meta's customer service window
// One conversation = one business number + one customer. Meta can send a BSUID,
// a phone number or both, so there is one key for each identifier present.
function conversationKeys(phoneNumberId, userId, phone) {
const ids = [userId, phone && phone.replace(/\D/g, "")].filter(Boolean);
return ids.map((id) => phoneNumberId + ":" + id);
}
// Before you answer 200: save every pause, collect the customer texts.
export async function readWebhook(body, { store, phoneNumberId }) {
const questions = [];
for (const entry of body.entry ?? []) {
for (const { field, value } of entry.changes ?? []) {
if (value?.metadata?.phone_number_id !== phoneNumberId) continue;
// Branch on the field. History webhooks can carry the same arrays.
if (field === "smb_message_echoes") {
for (const echo of value.message_echoes ?? []) {
const at = Number(echo.timestamp) * 1000;
const until = at + HOLD_MS;
for (const key of conversationKeys(phoneNumberId, echo.to_user_id, echo.to)) {
await store.save(key, { at, until });
}
}
}
if (field === "messages") {
for (const message of value.messages ?? []) {
if (message.type !== "text") continue; // skips edit, revoke, system, unsupported
questions.push({
id: message.id,
at: Number(message.timestamp) * 1000,
keys: conversationKeys(phoneNumberId, message.from_user_id, message.from),
phone: message.from,
userId: message.from_user_id,
text: message.text.body,
});
}
}
}
}
return questions;
}
// True if the customer wrote during a pause, if a person wrote after this
// question, or if the 24-hour window for a free-form reply has closed.
async function leaveToStaff(question, store, now) {
for (const key of question.keys) {
const state = await store.load(key);
if (state && (question.at < state.until || question.at <= state.at)) return true;
}
return now() - question.at >= WINDOW_MS;
}
// After you answered 200.
export async function answer(question, { store, agent, send, now = Date.now }) {
if (!(await store.claim(question.id))) return "duplicate";
if (await leaveToStaff(question, store, now)) return "left to staff";
const reply = await agent(question);
if (await leaveToStaff(question, store, now)) return "left to staff"; // check again, then send
await send(question, reply);
return "sent";
}
export function createSender({ host, version, phoneNumberId, token }) {
const url = "https://" + host + "/" + version + "/" + phoneNumberId + "/messages";
return async (question, reply) => {
const response = await fetch(url, {
method: "POST",
headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" },
body: JSON.stringify({
messaging_product: "whatsapp",
recipient_type: "individual",
...(question.phone ? { to: question.phone } : { recipient: question.userId }),
type: "text",
text: { body: reply },
}),
});
if (!response.ok) throw new Error("Send failed: " + (await response.text()));
return response.json();
};
}
// For a first test only. Replace it with your database.
export function memoryStore() {
const states = new Map();
const claimed = new Set();
return {
async load(key) {
return states.get(key);
},
async save(key, state) {
const current = states.get(key);
if (!current || state.at >= current.at) states.set(key, state); // newest event wins
},
async claim(messageId) {
if (claimed.has(messageId)) return false;
claimed.add(messageId);
return true;
},
};
}This Cloudflare Worker uses it, including the GET request with which Meta verifies a callback URL:
// worker.mjs: a Cloudflare Worker that uses takeover.mjs.
import { answer, createSender, memoryStore, readWebhook } from "./takeover.mjs";
const store = memoryStore(); // your database in production
export default {
async fetch(request, env, ctx) {
const { pathname, searchParams: query } = new URL(request.url);
if (pathname !== env.WEBHOOK_PATH) return new Response("Not found", { status: 404 });
if (request.method === "GET") {
const mode = query.get("hub.mode");
const verifyToken = query.get("hub.verify_token");
if (mode !== "subscribe" || verifyToken !== env.VERIFY_TOKEN) {
return new Response("Forbidden", { status: 403 });
}
return new Response(query.get("hub.challenge"));
}
const phoneNumberId = env.PHONE_NUMBER_ID;
const questions = await readWebhook(await request.json(), { store, phoneNumberId });
const agent = async (question) => "Put your model call here. You asked: " + question.text;
const { API_HOST: host, API_VERSION: version, API_TOKEN: token } = env;
const send = createSender({ host, version, phoneNumberId, token });
for (const question of questions) {
ctx.waitUntil(answer(question, { store, agent, send }).catch(console.error));
}
return new Response("OK");
},
};Our tests run both files unchanged on Node.js 24. They cover text, edit and delete echoes, a missing phone number, duplicate, late and out-of-order delivery, a message during a pause, a closed 24-hour window, and an echo that arrives while the agent writes.
- Where to send. With your own Meta app, the request goes to
graph.facebook.com/<VERSION>/<PHONE_NUMBER_ID>/messageswith your access token. On a Dualhook connection setAPI_HOSTtoapi.dualhook.com,API_VERSIONtov25.0andAPI_TOKENto yourdh_live_key. The path and JSON stay the same. See the Runtime API. - Check who is calling. The Worker only answers on
WEBHOOK_PATH, so make that a long random path, such as/hook-plus 32 random characters. With your own Meta app, also verifyX-Hub-Signature-256, which the sample does not do. On a Dualhook connection you cannot, because Meta signs with the secret of Dualhook's app. Add the payload checks for a Dualhook connection instead. - Background time. On Cloudflare Workers,
ctx.waitUntil()allows up to 30 seconds after the response, so use a queue for a slower agent. On Supabase Edge Functions the call isEdgeRuntime.waitUntil(). - At most one reply. If the model call or the send fails, the sample does not try that message again. Log the error and tell a person.
Replace memoryStore() before you go live, because several instances of your function do not share memory. These statements do the same in Postgres:
create table takeover (
conversation text primary key,
at bigint not null,
until bigint not null
);
create table claimed (message_id text primary key);
-- save(key, { at, until }): the newest event wins, whatever the order of arrival
insert into takeover (conversation, at, until) values ($1, $2, $3)
on conflict (conversation) do update set at = excluded.at, until = excluded.until
where excluded.at >= takeover.at;
-- load(key)
select at, until from takeover where conversation = $1;
-- claim(messageId): one row back means first time, no row means duplicate
insert into claimed (message_id) values ($1)
on conflict (message_id) do nothing
returning message_id;What if the agent is already writing?
A model can need several seconds. A person may reply from the phone in that time. The second check catches it, because the echo has saved the pause while the model was still writing:
- A small gap stays. The echo reaches you after the person has sent the message. A reply that leaves in that moment cannot be stopped, so do nothing between the second check and the send.
- Do not rely on order. Meta's throughput page says it attempts to deliver webhooks concurrently. The sample compares timestamps: the newest echo wins, and a question older than the newest echo, or written during the pause, is left to the person.
- Expect duplicates. If your endpoint answers anything other than 200, Meta retries with decreasing frequency for up to 7 days. Meta says your server should handle deduplication. If the pause cannot be saved, the sample returns an error on purpose, so Meta retries.
- Answer fast. Meta's latency standard for webhook servers is a median of at most 250 ms, with less than 1% above 1 second. Run the model after the 200.
When should the agent resume?
These are design choices, not Meta rules:
- A timer. Every staff message restarts it. The sample uses one hour as an example. Pick the time your team needs to finish a chat.
- A button in your own tool. It saves
until: 0with the current time asat, and the agent answers the next customer message. The customer sees nothing of it. - The end of the window. Resume when the customer writes again after the 24-hour customer service window has closed.
Do not let the agent come back blind
The echo of a new or edited message contains its content. Add it to the agent's context, so the agent knows what was promised. The echo of a deleted message only has that message's ID, so take the message out again. The sample does not answer questions from during a pause, so alert a colleague when one stays open.
Meta's terms let you use an AI company as your provider, but WhatsApp data may not train or improve an AI model. The one exception is a model fine-tuned for your exclusive use, as long as the data improves no other model. Use a model API that excludes your data from training, and have the permissions you need to share chats with it.
WhatsApp does require a way to reach a person. Section 2 of the WhatsApp Business Messaging Policy (last updated 23 September 2026) says:
“You may use automation when responding during the 24-hour window, but must also have available prompt, clear, and direct escalation paths.”
The paths it lists are in-chat human agent transfer, phone number, email, web support, in-store visits and a support form. For Meta's other rules, see AI agents on WhatsApp.
Which edge cases should you handle?
- Unsupported devices. Meta supports all companion clients except WhatsApp for Windows and WhatsApp for WearOS. It describes echoes for the app and supported companion devices, so let staff reply from one of those. Onboarding unlinks all companion apps: link the supported ones again. Customers can use an unsupported device too. Meta says their message then triggers no
messageswebhook, so the agent does not see it. - Edits and deletes. From staff they arrive as echoes of type
editandrevoke. The sample pauses on them, because a person is working in the chat. From customers they arrive onmessageswith the same types. They are not new questions, and the sample answers only typetext. - Media and other types. Meta's reference says echo types include text, image, video, document, revoke and edit. Pause on every echo, also on a type your code does not know.
- Messages you cannot read. A
messageswebhook of typeunsupportedwith error131060can arrive when a customer writes to you for the first time, or when an unsupported companion device is involved. Meta says to check the WhatsApp Business app. Do not let the agent guess. - The 24-hour window. Messages from the app do not create, extend or affect Cloud API conversation windows. The window starts when the customer messages you. After it closes, the API can only send approved templates. The sample leaves a message that is 24 hours old to your team.
- Opt-outs. WhatsApp's policy says you must respect every request to stop, on or off WhatsApp. Check for it before the model runs, because a pause does not do this.
- Groups. Meta does not synchronize the app's group chats, so this pattern covers one-to-one chats.
- Who replied. The documented echo has no field for the staff member or the device.
- Greeting and away messages. Meta's reference does not say whether the app's automatic messages trigger an echo. Test it, because an echo would pause the agent.
- Typing indicator. The same request marks the customer's message as read, and Meta says to show it only if you are going to respond. Send it after the first check.
How do you do this in n8n?
Use the same checks with n8n's own nodes. Webhook verification and the send settings are in our n8n webhook guide.
- Receive the POST with a Webhook node. Set Respond to Using 'Respond to Webhook' Node.
- Add a Code node in its default mode, Run Once for All Items:
// One item per echo and customer ID, one per customer message. Other webhooks give no items. const HOLD_MS = 60 * 60 * 1000; const time = (message) => Number(message.timestamp) * 1000; const conversationKeys = (value, userId, phone) => { const ids = [userId, phone && phone.replace(/\D/g, "")].filter(Boolean); return ids.map((id) => value.metadata.phone_number_id + ":" + id); }; return $input.first().json.body.entry.flatMap((entry) => entry.changes.flatMap(({ field, value }) => { if (field === "smb_message_echoes") { return (value.message_echoes ?? []).flatMap((echo) => conversationKeys(value, echo.to_user_id, echo.to).map((conversation) => ({ json: { field, conversation, pausedUntil: time(echo) + HOLD_MS }, })) ); } if (field === "messages") { return (value.messages ?? []).map((message) => ({ json: { field, message, askedAt: time(message), keys: conversationKeys(value, message.from_user_id, message.from), }, })); } return []; }) ); - Connect the Code node to three branches, one above the other. In workflows created from n8n 1.0, n8n finishes the top branch before it starts the next one.
- Top branch: a Filter node keeps the items whose
fieldissmb_message_echoes. A Data Table node with the Upsert row operation savesconversationandpausedUntil, as a number. - Middle branch: a Respond to Webhook node answers 200. If saving a pause fails first, n8n answers 500 and Meta retries.
- Bottom branch: a Filter node keeps the items whose
fieldismessages, whosemessage.typeistext, and whoseaskedAtis less than 24 hours ago. - Then add two Data Table nodes with If Row Does Not Exist and Must Match set to All Conditions. Both check that
pausedUntilis greater thanaskedAt. The first checks thatconversationequals{{ $json.keys[0] }}, the second that it equals{{ $json.keys.at(-1) }}. For a paused chat they output nothing. - Run the agent, repeat the 24-hour and pause checks with the values from the Code node, then send with an HTTP Request node.
This short version lets a late echo overwrite a newer one and has no duplicate check. If you need both, keep the state in a database with the SQL above. The steps follow n8n's documentation, and we ran the snippet outside n8n.
Does this work without Coexistence?
No. Meta sends smb_message_echoes for businesses that were onboarded to Cloud API with a WhatsApp Business app number, which is commonly called Coexistence. An API-only number is not in the app, so nobody replies from a phone. Takeover happens in the inbox your team uses, and the signal has to come from that inbox. The two states and the two checks stay the same.
How does this work on Dualhook?
Dualhook connects a WhatsApp Business app number that your business owns or directly operates to Meta's Cloud API. Meta decides per number whether it can be connected. The pause logic runs on your server, with your model.
What Dualhook does
- Subscribes to
messagesandsmb_message_echoes, and sets Meta's Webhook Override, so Meta sends both straight to your endpoint. - Relays your sends through
api.dualhook.comwith adh_live_key, without storing message content. - Accepts
recipientwith a BSUID when you have no phone number.
What it does not do
- Run the agent, provide an inbox, or keep the pause for you.
- Store or replay echoes. If your endpoint misses one, only Meta's retries can deliver it again.
- Offer group messaging, Conversation Routing or thread control.
Frequently asked questions
How do I pause my WhatsApp AI agent when a person replies from the phone?
On a Coexistence number, subscribe to smb_message_echoes. Meta sends that webhook when the business sends a message with the WhatsApp Business app or a supported companion device. Save a pause for that customer, answer HTTP 200, and check the pause before you generate a reply and again right before you send it.
Do messages my agent sends through the API come back in smb_message_echoes?
Meta's triggers for smb_message_echoes are messages sent, edited or deleted with the WhatsApp Business app and messages sent from a companion device. Sending with the API is not on that list. Test it once on your own number: send one API message and check that no echo arrives.
How long should the agent stay paused?
Meta sets no pause length, so it is your decision. A simple rule is a timer that restarts with every staff message, for example one hour, plus a way for staff to hand the chat back sooner.
Does the echo tell me which staff member replied?
No. In Meta's documented payload the sender is the business phone number, and there is no field for the staff member or the device. Track the pause per conversation, not per person.
What do I key the conversation on if the phone number is missing?
Use Meta's business-scoped user ID (BSUID): to_user_id in an echo and from_user_id in a customer message. Meta omits the phone number when the customer has adopted a username and the number is unavailable. Combine the BSUID with the phone_number_id of your own number.
Does a reply from the WhatsApp Business app open the 24-hour window for my agent?
No. Meta says app messages do not create, extend or affect Cloud API conversation windows. The 24-hour customer service window starts when the customer messages you and restarts with each new customer message. When it closes, the API can only send approved templates.
Does WhatsApp require a human takeover for AI agents?
The WhatsApp Business Messaging Policy lets you automate replies in the 24-hour window, but you must have prompt, clear and direct escalation paths. In-chat transfer to a human agent is one of the paths it lists, next to phone, email, web support, in-store visits and a support form. It sets no rule for how long a bot stays quiet.
Is this the same as Meta's Conversation Routing?
No. Conversation Routing decides which responder receives each inbound message when more than one is connected to the same WhatsApp account, and it has its own webhooks and thread control API. The pattern on this page needs only smb_message_echoes and messages. Dualhook has no Conversation Routing or thread control features.
How we checked: the facts about WhatsApp come from Meta's developer documentation and the WhatsApp Business Messaging Policy, and the n8n, Cloudflare and Supabase statements from their own documentation, all read on 24 November 2026.