Give your AI agent memory: six months of WhatsApp chats and contacts
On a number connected through Coexistence, Meta can send the app's contacts and up to 180 days of one-to-one chats to your server, once, if a direct webhook destination is saved within 24 hours of connecting and the business agrees in the app. Chunks can arrive out of order and progress 100 marks the end. Store messages by id, key people by BSUID, and feed recent turns to the agent.
easyCoexistence connects the number through Meta's Coexistence flow and, when you save your endpoint as its direct webhook destination within 24 hours, asks Meta once for the contacts and up to 180 days of chats, which go straight to your server.
How far back the history sync reaches from onboarding; Meta's feature table calls it the most recent 6 months.
Time after onboarding to request contacts and history; each request can be made only once.
metadata.progress value that marks the history sync as complete; Meta says phase alone does not.
Error code in a history webhook when the business turned off history sharing in the WhatsApp Business app.
Phase 0 covers day 0 to 1 before onboarding, phase 1 days 1 to 90, phase 2 days 90 to 180.
Largest webhook payload Meta sends, which sets the body size limit your endpoint needs.
What does the import bring, and what stays behind?
Two streams, both from the WhatsApp Business app on the phone. Contacts arrive as smb_app_state_sync webhooks, one entry per contact with action add or remove, and the same field keeps reporting contacts the business later adds, edits or removes in the app. Chats arrive as history webhooks: one-to-one conversations from up to 180 days before onboarding, in both directions, with their delivery status. What does not come across is listed below, so memory built on the import should not expect it.
How do you make sure the import reaches your server?
Have the endpoint live before the number connects, then save it as the number's direct webhook destination within 24 hours of connecting: on the number's page under Route incoming messages to your own webhook, with set_webhook_destination from your AI, or as webhook_url on a Partner API connect session. Saving it is what makes easyCoexistence ask Meta for the sync, contacts first and then history, one time per onboarding; the request and Meta's request ids appear in the number's event log as history_sync_requested.
The business must agree to share history when the app asks during the connection. A number whose messages come through easyCoexistence (Through easyCoexistence in the card Where incoming messages go), even with a Forward URL, gets no import, because the request is only made for a direct destination. If you need automations later, switch after the import ends.
How do the history chunks arrive?
Out of order, in phases that run from the newest messages back: phase 0 covers the last day before onboarding, phase 1 up to day 90 and phase 2 up to day 180. Sort by metadata.chunk_order if order matters, and treat metadata.progress = 100 as the end, since Meta notes that phase does not tell you a phase is finished. A conversation's id is the customer's phone number, left out when it cannot be shared, and its context carries wa_id, user_id and username. A message the business sent has from set to the business number and a to field.
{
"messaging_product": "whatsapp",
"metadata": { "display_phone_number": "16315550142", "phone_number_id": "106540352242922" },
"history": [{
"metadata": { "phase": 1, "chunk_order": 2, "progress": 55 },
"threads": [{
"id": "5511987654321",
"context": { "wa_id": "5511987654321", "user_id": "BR.13491208655302741918" },
"messages": [
{
"from": "5511987654321",
"from_user_id": "BR.13491208655302741918",
"id": "wamid.HBgNNTUxMTk4NzY1NDMyMRUCABIYFDNBMDhFN0QxRjM2QTk4RTU2RTY0AA==",
"timestamp": "1789912800",
"type": "text",
"text": { "body": "Can I pick up the cake on Saturday?" },
"history_context": { "status": "read" }
},
{
"from": "16315550142",
"to": "5511987654321",
"id": "wamid.HBgNNTUxMTk4NzY1NDMyMRUCABEYEjQ2RDhGMkE3QjEwQzNFOTFBMgA=",
"timestamp": "1789913100",
"type": "text",
"text": { "body": "Yes, from 9 am. See you then!" },
"history_context": { "status": "read" }
}
]
}]
}]
}How should an agent's memory be stored?
Two tables are enough. People are keyed by BSUID, the user_id Meta adds to contacts, conversations and messages, with the phone number kept beside it, because a user with a username can arrive without one; Meta's own reference says to use user_id to identify a contact. Messages are keyed by their wamid, so the import, live webhooks and retried deliveries of the same message collapse into one row, and a from_business flag records who spoke. Index by person and time, since the agent asks for one person's latest turns.
-- One row per person. Key on the BSUID (user_id); keep the phone number beside it.
create table wa_contacts (
user_key text primary key, -- user_id (BSUID) when present, else the phone number
wa_id text, -- phone number in digits, when Meta shares it
username text,
name text, -- full_name from the app's address book
removed boolean not null default false,
updated_at timestamptz not null default now()
);
-- One row per message. The wamid makes history, live events and retries collapse.
create table wa_messages (
id text primary key, -- messages[].id
user_key text not null,
from_business boolean not null,
type text not null, -- text, image, media_placeholder...
body text not null, -- the text, a caption, or a [type] placeholder
sent_at timestamptz not null,
source text not null -- history | live | echo
);
create index wa_messages_by_user on wa_messages (user_key, sent_at desc);How do you load chunks and contacts into it?
With idempotent inserts, so order and redelivery stop mattering. ingestHistory reads one history change: it logs a 2593109 decline and moves on, keys a conversation by context.user_id or its id, marks a message as the business's when from equals metadata.display_phone_number, and stores a [type] placeholder when there is no text. ingestContacts upserts on user_id or phone number and flags removed contacts instead of deleting their messages. Call them with change.value on a direct destination, or with the body's value when a forward's event is history or smb_app_state_sync.
// memory.mjs: npm i pg. Feed it the value of a "history" or "smb_app_state_sync"
// change: change.value on a direct destination, delivery.value on a forward.
import pg from "pg";
const db = new pg.Pool(); // reads the PG* environment variables
export async function ingestHistory(value) {
const business = value.metadata?.display_phone_number; // digits, like messages[].from
for (const chunk of value.history ?? []) {
if (chunk.errors?.some((e) => e.code === 2593109)) {
console.log("The business turned off history sharing in the app"); // contacts still come
continue;
}
for (const thread of chunk.threads ?? []) {
const userKey = thread.context?.user_id ?? thread.id; // thread.id is the phone, when shared
for (const m of thread.messages ?? []) {
await db.query(
`insert into wa_messages (id, user_key, from_business, type, body, sent_at, source)
values ($1, $2, $3, $4, $5, to_timestamp($6), 'history')
on conflict (id) do nothing`,
[m.id, userKey, m.from === business, m.type,
m.text?.body ?? m[m.type]?.caption ?? `[${m.type}]`, Number(m.timestamp)]
);
}
}
const { phase, chunk_order, progress } = chunk.metadata ?? {};
console.log(`history: phase ${phase}, chunk ${chunk_order}, ${progress}%`);
if (Number(progress) === 100) console.log("Import complete; late chunks still insert safely");
}
}
export async function ingestContacts(value) {
for (const s of value.state_sync ?? []) {
const c = s.type === "contact" ? s.contact ?? {} : null;
const userKey = c && (c.user_id ?? c.phone_number);
if (!userKey) continue;
await db.query(
`insert into wa_contacts (user_key, wa_id, username, name, removed)
values ($1, $2, $3, $4, $5)
on conflict (user_key) do update set
wa_id = coalesce(excluded.wa_id, wa_contacts.wa_id),
username = coalesce(excluded.username, wa_contacts.username),
name = coalesce(excluded.name, wa_contacts.name),
removed = excluded.removed, updated_at = now()`,
[userKey, c.phone_number ?? null, c.username ?? null, c.full_name ?? c.first_name ?? null,
s.action === "remove"]
);
}
}
// A bounded memory for one person: who they are and their last turns, oldest first.
export async function memoryFor(userKey, turns = 20) {
const [{ rows: [contact] }, { rows }] = await Promise.all([
db.query("select name from wa_contacts where user_key = $1 and not removed", [userKey]),
db.query(
`select from_business, body from wa_messages
where user_key = $1 order by sent_at desc limit $2`, [userKey, turns]),
]);
const history = rows.reverse().map((r) => ({ role: r.from_business ? "assistant" : "user", content: r.body }));
while (history[0]?.role === "assistant") history.shift(); // open on the customer's turn
const who = contact?.name ? `The customer is ${contact.name}.` : "The customer is not in the address book.";
return { system: `${process.env.AI_INSTRUCTIONS ?? ""}\n${who}`.trim(), history };
}How do you feed that memory to the agent?
Bounded, never all at once. memoryFor returns the person's name from the address book and their last 20 turns, oldest first, opening on a customer turn as most chat APIs expect; add a stored summary of older conversations if the agent needs more. Six months of chats in every prompt costs tokens on every reply and buries the question being asked.
For comparison, the built-in Reply with AI step reads at most 20 earlier messages (10 by default), and the Call my webhook step sends the last 10. Both draw on text kept for the retention the owner picks, 30, 90 or 365 days (90 by default), from the moment automations were on, which is why the six months of imported chats have to live in your own database.
How does memory stay current after the import?
The same destination keeps receiving live traffic: messages from customers, smb_message_echoes for replies typed in the app, and smb_app_state_sync when the business edits its contacts. Insert them through the same tables with source live or echo. When a customer changes phone number, Meta sends a system message of type user_changed_number or user_changed_user_id with previous_user_id, your cue to move their rows to the new BSUID.
Turning automations on later removes the direct destination. Add the same URL as the Forward URL and read event and value from each signed POST, and wait for progress 100 before switching, or the remaining chunks reach you only through that forward.
How to set it up
- Put the endpoint onlineIt must return hub.challenge as plain text on Meta's GET handshake when hub.verify_token matches, accept POST bodies of a few megabytes and answer 200 fast.
- Connect the numberRun the connection from the dashboard, and accept sharing chat history when the WhatsApp Business app asks.
- Save the destination within 24 hoursOn the number's page, under Route incoming messages to your own webhook, fill Webhook URL (with a long random path) and Verify token, then Save; or ask your AI to call set_webhook_destination.
- Store chunks until progress 100Insert contacts and messages as they come; the event log shows history_sync_requested once the request went to Meta.
- Switch modes only afterwardsIf you want automations, choose Through easyCoexistence in the card Where incoming messages go and add the same URL as the Forward URL.
Common mistakes
- Saving the destination on day two. The sync is only requested within 24 hours of connecting, so an endpoint saved later starts from live messages only.
- Turning automations on before progress reaches 100. The direct destination is removed at once, and later chunks reach you only if a Forward URL is already set.
- Treating phase 2 as the end of the import. Only metadata.progress = 100 says the sync is complete, and chunks are not delivered in sequence.
- Keying memory on the phone number alone. Conversation ids and contacts drop the phone number when a user with a username cannot share it, while user_id is still present.
The request is recorded in the number's event log, and the number is monitored 24/7 afterwards. US$ 9 down to US$ 0.75 per number per month, falling as you add numbers, with the first 3 days free.
easyCoexistence is a multichannel API and MCP server that connects AI agents such as Claude and ChatGPT to WhatsApp, Instagram, TikTok, Facebook and more. On WhatsApp it uses Coexistence: the business keeps using its number in the WhatsApp Business app while the AI works through Meta's official API.
Frequently asked questions
Can the import run a second time?
Only through a new onboarding. Meta allows one request per onboarding, so the number has to be disconnected and connected again, and the chats then arrive again; inserting by message id keeps the second pass from adding anything twice.
Does easyCoexistence keep a copy of the imported chats?
No. History and contacts go from Meta straight to your endpoint and are not stored by default. For a number with automations on, easyCoexistence keeps message text for the period you choose, 30, 90 or 365 days (90 by default), and the Conversations screen shows it; forwarded deliveries are kept up to 7 days, and run logs 30 days.
How big can the payloads get?
A single Meta webhook can carry up to 3 MB, and a busy number sends many history chunks. Raise your framework's body limit (Express defaults to 100 kb) and acknowledge before writing to the database.
Does an agent need the import to work?
No. Without it, memory starts with the first message after connecting and grows from live traffic. The import matters when past conversations should shape answers from day one, such as a returning customer's last order.
Keep reading
Ready to get started?
Set up WhatsApp Coexistence in minutes, not months. The app keeps working on the phone.
Start Free TrialVerified on