WhatsApp AI Agent
How one inbound WhatsApp message becomes an AI reply, a booking, or a handoff to staff, including queueing, limits, tools, guards and escalation.
21 min read
Overview
The WhatsApp AI agent (default persona name "Aria", renamed per brand) answers clients who message a brand's WhatsApp Business number. It is a tool-calling LLM loop wrapped in a lot of code-side guards: the model proposes, but code decides what may be written to the database and what may be sent to the client.

The agent runs inside the web app on the OCI VM(s), not in a separate service (apps/ai-services/ is dormant). The same core (runAgentTurn in lib/ai/gateway.ts) also serves the website widget, Meta DMs and voice (the Zylu inbox poller was retired in SALO-3006 and removed in SALO-3041); this page covers the WhatsApp path. For the other channels see social-dms.md and voice.md. For sending, templates and delivery see messaging-delivery.md and communications.md. For add-on offers see ai-upsell-offers.md; for quality monitoring see ai-quality-and-eval.md.
Design rules the code follows:
- Every price, time, stylist, offer and policy in a reply must trace to a tool result (or the owner's own text). Otherwise the reply is retried, trimmed or handed to staff.
- A booking, cancellation or reschedule needs a matching proposal plus a plain "yes" from the client, checked in code.
- Failures are never silent: each failure path raises a staff bell notification or a monitoring event.
- The AI trusts only the phone number WhatsApp verified (see Identity rule).
Turn lifecycle at a glance
| Step | What happens | Code |
|---|---|---|
| 1 | Meta POSTs the message; signature checked; brand found from the receiving number | app/api/webhooks/whatsapp/route.ts |
| 2 | Non-chat handling: taps on offers, store picker, media, STOP, spam, lead capture | same file, processInboundMessage |
| 3 | Store resolved or picker sent (message parked) | lib/messaging/resolve-location.ts |
| 4 | Inbound row stored (this is the dedupe claim); 200 returned to Meta | webhook |
| 5 | After the 200: debounce, per-sender lock, merge quick messages, take a lease | lib/ai/whatsapp-turn-queue.ts |
| 6 | Brand AI on/off, handoff pause, per-sender and brand rate limits | lib/ai/whatsapp-agent-runner.ts |
| 7 | Conversation row, resume-or-start-over gate, history load, LLM loop with guards | lib/ai/gateway.ts |
| 8 | Reply jury, handoff alerts, outbound row, send (interactive with text fallback) | gateway + runner |
1. Inbound webhook
POST /api/webhooks/whatsapp (GET is Meta's verify challenge, checked against WHATSAPP_WEBHOOK_VERIFY_TOKEN).
- Signature: HMAC-SHA256 of the raw body against
META_APP_SECRET, compared in constant time. If the secret is unset the route fails closed with 403 (every webhook triggers paid AI turns). Rejections log which WABA sent the payload so a stale Meta app can be told apart from a wrong secret. - Always acks 200 once the signature is valid. Each status, template event and message is isolated in its own try/catch and reported with
captureError; one bad item never causes a Meta retry storm. - Brand lookup:
messaging_settings.wa_phone_number_id-> org and brand. Dropped if the brand is not found oris_whatsapp_enabledis false. A per-location toggle (location_messaging_settings.is_whatsapp_enabled, absent row = on) is checked after routing. - In-process ordering:
serializeTurns(lib/ai/turn-queue.ts) chains messages for the same brand and sender inside one Node process. It is only a first line of defence; the database lock below is what works across processes. - The agent turn runs in
after()(10-20 s), so Meta never times out and redelivers. The inbound row insert (inbound_messages, unique onprovider_message_id) is the claim: a redelivery finds the row and exits without replying twice.
Message types handled before the agent
| Input | Behaviour |
|---|---|
Tap on a choice message (choice: id) |
Treated as a text turn; the AI gets the option id as well as the title |
Pre-arrival upsell tap / text ADD / MORE INFO |
Applies the add-on to the sender's own upcoming appointment, or hands the offer to the AI (see ai-upsell-offers.md) |
Flash-promo, cancelled-slot (CLAIM) and NPS rating (1-5, 3-day look-back) replies |
Answered by code, no AI turn |
| Template quick-reply button | Its label is treated as typed text |
| Store picker tap (raw location id) | Saves the store and replays parked messages (section 3) |
| Voice note, photo, video, document, location, contact, sticker | Stored as a marker row. Voice note / photo / video / document also raise a "Customer sent a ..." bell. Photo, video and document go to a scripted handoff (the AI never "sees" them). Voice notes get a "please type" reply; no speech-to-text |
Opt-out, spam and lead capture
- STOP (
lib/ai/whatsapp-opt-out.ts): whole-message keywords (stop,unsubscribe,opt out) plus phrases in English, Tamil and Hinglish ("don't message me", "stop chatting", "band karo"). The sender gets one confirmation and no agent turn. Stored inwhatsapp_opt_outs(per brand and wa_id); known clients also get aclient_consentsmarketing refusal. Follow-ups and campaigns skip opted-out senders and the check fails closed on a lookup error. Only an explicitSTART/SUBSCRIBE/UNSTOPopts back in; a greeting still reaches the agent but leaves the opt-out in place. Opt-out does not stop the AI answering later booking questions. - Spam (
lib/ai/inbound-spam.ts): only for senders who are not client records. A message is dropped with no reply when it has a link AND money/prize wording AND no salon words. Keyword-based, English and Hinglish. - Lead capture (
lib/ai/whatsapp-lead.ts): an unknown sender becomes aclientsrow (name from the WhatsApp profile, else "WhatsApp +number") taggedLead, so owners can target them. Failure to create it never blocks the reply.
2. Queue, debounce and lease
lib/ai/whatsapp-turn-queue.ts makes sure a burst of messages ("hi" / "haircut tmrw?" / "around 5") gets one answer.
| Constant | Value | Meaning |
|---|---|---|
DEBOUNCE_MS |
2,500 ms | Every turn waits this long before it tries to run |
LOCK_TTL_S |
120 s | Per-sender lock (RPC ai_turn_lock / ai_turn_unlock, key per brand and sender) |
LEASE_TTL_S |
120 s | A claimed turn must finish (or be marked complete) inside this window |
| Pending window | 10 min | Older unanswered rows are stale and never folded in |
MAX_TURN_ATTEMPTS |
3 | Used by the sweep (below) |
Flow of claimInboundTurn:
- Sleep the debounce, take the lock (polls up to 125 s; fails open if the RPC errors).
- If a newer pending message from the same sender exists, this turn exits (
newer_message): the newer turn answers everything. - Otherwise it claims all pending rows for the sender (
ai_turn_claimed_at,lease_expires_at) and joins their text, oldest first, as one message. - After the turn:
completeInboundTurnclears the lease; if the turn failed,unclaimInboundTurnputs the rows back to pending so the client's next message answers them.
Only rows with a location are claimable. Rows parked behind the store picker, and rows the webhook marks as handled (picker taps, media markers, replayed text), are stamped with ai_turn_claimed_at so they never join a later turn.
Stranded-turn sweep
GET/POST /api/cron/ai-turn-lease-sweep (x-cron-secret; pg_cron job created in migration 0244, every minute, slowed to every 2 minutes in 0290) runs sweepExpiredTurnClaims (lib/ai/turn-lease-sweep.ts): rows claimed but with an expired lease, created in the last 10 minutes, grouped per sender.
- Chat handed off, or an outbound reply already exists after the claim: just clears the lease.
- Otherwise it retries the turn (up to 2 retries tracked in
inbound_messages.attempts). - When attempts reach
MAX_TURN_ATTEMPTS - 1it alerts staff ("WhatsApp AI turn failed after 3 attempts", keyai_agent_turn_failed), marks the conversationhanded_offwith reasonturn_crash_max_attempts, and stops retrying.
3. Store picker, routing and resume
Store resolution (resolveLocation). First match wins:
- Saved store preference used within the last 24 h
- A single branch named in the message ("book at Adyar") - treated exactly like a picker tap
- Recent appointment-linked outbound message (7-day window)
- Campaign context (
message_context, 7-day TTL) - Older saved preference
- Client's appointment in a 7-day window around now
- Brand with exactly one active location
If nothing matches: the webhook tries a typed store name (matchLocationByName). A website lead form ("I filled in your form ... City: ...") with no branch is answered at the brand's first active store and the agent asks which branch (lead_default). Anything else sends the store picker (reply buttons for up to 3 stores, a list for more, max 10 rows) at most once per 5 minutes per sender, and the message is parked unanswered.
applyStorePick saves client_store_preference, records the pick, and replays parked messages (up to 24 h old; text older than 30 min is prefixed "[sent Nh ago]"). If nothing was parked, the AI is told the client picked a store and has not asked anything yet, so a bare tap still gets a reply.
Mid-chat branch changes: the switch_store tool, or code in the gateway when a message names exactly one other branch, moves the conversation (ai_conversations.location_id) and re-runs the same message at the new branch. One switch per message. A question about a branch ("is it in Porur?") does not switch.
Resume or start over (lib/ai/resume.ts): when a client returns after 12 h or more:
- A message with real content (a service, a branch, "yes", a form) is simply answered, with a prompt note quoting our last open question.
- A bare greeting or emoji gets "Welcome back! ... pick up where we left off, or start over?" as buttons.
- "Pick up" keeps a safe summary of the previous 24 h (the client's own messages, kinds of reply sent, saved booking state, never our reply text) in
ai_resume_cachefor 48 h. "Start over" (or free text instead of a choice) cuts all earlier history. A choice is only a button tap or a bare 1/2; free text is never read as a choice.
4. Rate limits, caps and budgets
All in lib/ai/whatsapp-turn-queue.ts (checkSenderRateLimit) via the rate_limit_hit RPC. They run after the pause check, once per merged turn, and fail open on error.
| Limit | Window | Max |
|---|---|---|
| Per sender | 60 s | 6 |
| Per sender | 1 h | 40 |
| Per sender | 24 h | 80 |
| Per brand (all senders) | 24 h | 1,500 |
Over a sender cap the message stays in the inbox unanswered; the client gets one "taking a short pause" notice per hour, then silence. Over the brand cap the turn is dropped with a monitoring event only (no client notice, no staff bell).
Separate cost controls inside runAgentTurn:
- Monthly token budget:
ai_token_budgetsper org, summed fromai_usage_log. Only blocks whenhard_stopis true and the limit is reached; no budget row = unlimited. The client then gets "temporarily unavailable" and the chat is flagged as a handoff. - Widget budget: the public widget may use only
AI_WIDGET_BUDGET_FRACTION(default 0.3) of the monthly budget, so widget abuse cannot starve WhatsApp. - Per-turn cost log:
ai_action_logs(provider:model, tokens, cost, tool calls) andai_usage_log.
5. LLM chain and failover
lib/ai/llm.ts speaks the OpenAI-compatible /chat/completions format to every provider and translates to and from the Anthropic block format the loop uses. Temperature 0.2, 25 s timeout per call, 2,048 max output tokens. Any error (network, timeout, 4xx/5xx, bad body) moves to the next provider; if all fail the error lists each failure.
Default order (providers without a key are skipped):
| # | Provider | Model (env override) | Notes |
|---|---|---|---|
| 1 | OpenRouter | deepseek/deepseek-v4-flash-0731 (OPENROUTER_MODEL) |
Reasoning disabled. Key: OPENROUTER_API_KEY |
| 2 | OpenRouter pinned to Groq | openai/gpt-oss-20b (OPENROUTER_GROQ_MODEL) |
Only if OPENROUTER_GROQ_BYOK=1 |
| 3 | Groq direct | openai/gpt-oss-20b (GROQ_MODEL) |
Key: GROQ_API_KEY |
| 4 | Anthropic | claude-sonnet-4-6 or the brand's claude-* model |
Only if ANTHROPIC_API_KEY is set; last resort |
The brand's "AI model" setting (Settings > AI Agent) is ignored unless AI_HONOR_BRAND_MODEL=1. With the flag on, a Claude model moves Anthropic first, a Groq model moves Groq first, and any other id replaces the OpenRouter model. Per-token prices for cost logging come from OPENROUTER_COST_* / GROQ_COST_* env vars.
The Claude Haiku / Sonnet / Opus routing described in ai.md does not describe this agent. Which providers are configured in production is not visible in the repo (env only); /api/health reports ai_no_provider when none is set.
6. Tools
The model gets the tools in BOOKING_TOOLS (lib/ai/tools.ts) plus the workflows in lib/ai/workflows/*. The loop allows 5 tool rounds per turn, then forces a text answer.
Read tools (no writes to client data)
| Tool | Returns |
|---|---|
list_services |
Online-bookable services, filtered by query / category / gender, at the chat's branch |
check_availability |
Slots (IST label + HH:MM) for a service, stylist or "any", and date |
get_staff_for_service |
Stylists for a service, with gender only if the data has it |
get_salon_info |
Brand FAQ answers (whatsapp_faq, edited under Settings > WhatsApp FAQ). found: false means the AI must say the team will confirm |
get_promotional_offers |
Active offers with per-service service_check.qualifies computed by code |
get_service_combos |
Bundles with bundle pricing |
get_upsell_recommendations |
One add-on offer, once per chat; logs an ai_upsell_events row |
get_client_appointments |
The sender's own upcoming appointments (verified number only) |
check_wallet_balance |
The sender's own prepaid wallet balance and nearest expiry |
Control tools
| Tool | Effect |
|---|---|
present_choices |
WhatsApp buttons / list (2-10 options); ends the turn. Service menus are built from the database, not typed by the model |
switch_store |
Moves the chat to another branch and saves the preference. Refused for a question about a branch |
handoff_to_human |
Marks the chat for staff. The client's reply and the staff summary are written by code, never by the model |
Write tools
| Tool | Writes | Code gate |
|---|---|---|
propose_booking / propose_cancel / propose_reschedule |
Nothing; returns a summary_text and a proposal stored in the tool log |
Validates live: service, stylist, free slot, ownership, offer pricing |
create_booking |
New appointment (or a booking request when no stylist) | Confirmation gate (section 7) |
cancel_appointment |
Cancels the sender's own upcoming appointment | Confirmation gate |
reschedule_appointment |
Moves it if the stylist is free for the whole visit | Confirmation gate |
add_services_to_appointment |
Adds services / add-ons after the existing visit | No code confirmation gate; relies on the tool description and prompt |
Workflow rules (lib/ai/workflows/appointments.ts): every workflow returns {success, error_code, message} and never throws (a throw becomes internal_error plus an ai_workflow_failed bell). Cancel and reschedule only apply to appointments that belong to the verified client, in this brand, and have not started. Negotiated discounts must be 0, 10, 15 or 20 percent, only after the client objected to price (or after we offered that percent), and never on top of a published offer (the offer is priced in by code). Free-text notes with price or discount wording are removed. The booking name must come from the client, the lead form or the record, never invented.
7. Write confirmation gating
lib/ai/confirmation.ts. A create_booking / cancel_appointment / reschedule_appointment runs only if all of these hold:
- A pending
propose_*result of the same kind exists, newer than the last successful write. - The write's details exactly match the proposal (service, stylist, date, time, discount, add-ons, extra services; appointment id for cancel / reschedule).
- The client's latest message is a plain yes (English, Tamil, Hindi and Tanglish / Hinglish words, thumbs-up, a tapped "Yes" button), 6 words or fewer, no question mark, no "no/wait/change" word.
- The message they said yes to shows the proposal's day and time, and, for bookings, every service name and the total.
If the model wrote its own summary and the client said yes, the gateway proposes those exact details itself and runs the write only if that earlier message passes check 4. On a confirmed yes, code overwrites the write's details with the proposal's; the model only adds client name, gender and notes. A repeated identical write returns the first result (no double insert). After a successful write the client gets the code-written closing_text, and the turn ends with no further model text.
A reply that claims a booking happened (English, Tanglish, Hinglish, Tamil, Hindi patterns) with no successful write is retried twice, then replaced by the "let our team confirm" line and handed off as ungrounded_write_claim.
8. Grounding and reply guards
The gateway runs these on every drafted reply before it is sent. Most retry the model once with a [system check] message the client never sees, then fall back.
| Guard | File | What it catches | Fallback |
|---|---|---|---|
| Price / slot time / stylist / service / percent / offer-day / outcome claims | grounding.ts |
A number or name no tool, earlier reply or owner text supports. Client-typed amounts never ground a price | One retry (an extra one for stale times). Then: prices and times -> hand off as ungrounded_price / ungrounded_time and keep the draft for staff; softer claims -> the offending sentences are cut |
| Menu / option menus | choice-guard.ts |
Priced options without a real service id, ungrounded prices, a discount not offered or earned. Also resolves a typed "3" to the option shown | Tool returns an error, model retries |
| Promise with no action | promise-reply.ts |
"Let me check..." with no tool run; offers to "check another variant"; "not on our menu" with no lookup this turn; "I've got the details" listing nothing | Retry once; an empty announcement is not sent |
| Repeat | reply-repeat.ts |
Same text as our last reply within 2 minutes; repetition loops; cap of 3,800 characters | Retry once, then recovery |
| Dodged direct question | reply-direct.ts |
Price or address asked, draft has neither | Retry once |
| Internal leak | reply-leak.ts, markup.ts |
Tool names, narration ("let me re-check carefully"), claims to have seen a photo, raw tool-call markup | Rewrite once; remaining sentences cut |
| Unstated hygiene / product claims | reply-leak.ts |
Process claims no FAQ, tool or owner text states | Sentence removed |
| Retry apology | retry-apology.ts |
"You're right, sorry" for a check the client never saw | Stripped |
| Structure | reply-sentences.ts |
Bare list markers and dangling lead-ins after a cut | Repaired |
| Branch line, intro | branch-line.ts, gateway.ts |
Branch name dropped from a summary; AI disclosure line | Added by code: Hi! I'm <name>, <brand>'s virtual assistant. on the first reply only |
Other code-side behaviour: a first reply to a website lead form shows at most 3 priced options; discount percents, gender, once-per-chat add-on offers and membership mentions are tracked in code; scripted replies skip the model entirely ("On my way" -> "See you soon!" plus a staff notice, photo / "call me" / failed web booking -> handoff).
Empty-reply recovery: if the loop ends with nothing to send, the model is asked once more with tools off, then once more with an instruction to name no price, time or stylist. If that also fails, the chat is handed off with reason empty_reply ... plus a trace.
9. Reply jury and held replies
lib/ai/reply-jury.ts, enabled only when AI_REPLY_JURY=on. Up to 3 judges (distinct models on the one OpenRouter key; default Gemini 2.5 Flash, Claude Haiku 4.5 and the receptionist model; override with AI_REPLY_JURY_MODELS) score the draft against the facts the AI had. Mean confidence under 0.8, or fewer than 2 judges answering, holds the reply (fails closed). Handoff, canned and code-written replies are not judged.
A held reply:
- is not sent; the chat is set to
handed_offwith reasonlow_confidenceorjury_unavailable; - creates an
ai_reply_holdsrow with the draft, shown in the Inbox held-replies list (staff can Acknowledge to stop paging, or Mark handled); - pages staff on a ladder (
lib/ai/reply-alerts.ts, escalated byGET/POST /api/cron/ai-reply-escalation, a pg_cron job created in migration0240every minute and slowed to every 2 minutes in0290).
| Level | Who is paged | Held reply: next page after | Handoff: next page after |
|---|---|---|---|
| 1 | Front desk, location manager | 5 min | 5 min |
| 2 | Location manager, brand manager | 5 min | 25 min (owner at about 30 min after the handoff) |
| 3 | Org owner (handoff: also emailed once) | every 10 min | every 10 min |
Paging stops after 8 pages, or when staff acknowledge, reply from the Inbox, or the AI answers the chat again. A staff reply to a held (not handoff) chat is saved as a lesson in ai_reply_lessons and the newest 15 are injected into the prompt and the jury as approved answers.
The same ladder is used for ordinary handoffs (kind handoff): once the AI has told the client a person will reply (WhatsApp only, client phone known), one open alert per chat is raised until someone replies. Who is paged and by which channel can be changed in Settings > Alerts (keys ai_reply_held, ai_handoff_unanswered).
10. Human handoff and the pause
A chat is set to handed_off when the model calls handoff_to_human, or code does it as a backstop for: complaint / refund / legal / allergy words, a client arriving with no booking found, photos, call requests, failed web bookings, hard ungrounded claims, empty replies, or a jury hold. The client sees a fixed line that says what happens next ("I've passed this to our team"), never the model's text; the brand's custom handoff message is only used for the general kind. Staff get an ai_agent_handoff bell with a one-line summary (needs, service and price, store, slot, customer, reason, last message) built from the chat's tool log (lib/ai/handoff-summary.ts).
While paused (lib/ai/handoff-pause.ts) the AI does not reply, runs no follow-ups, and staff get an ai_agent_paused_message bell on each new customer message:
| Pause | Length | Notes |
|---|---|---|
| Handoff | 12 h | Runs from the later of the handoff and the last staff reply from this brand, so a person still replying keeps the AI out |
| Staff typed in the Inbox | 2 h | handoff_reason = staff_replied; set by pauseAiForStaffReply |
After an ungrounded_* handoff |
15 min grace | If staff have not replied in 15 min the AI answers again (SALO-2536); the open alert is resolved when it does |
| Unreadable conversation | indefinite | Fails closed: a silent bot beats a bot in a human's chat |
Staff can use "Take over" / "Resume AI" on a thread in the Inbox (setThreadAiHandoffAction) to pause or resume at once. When the brand's AI is switched off in Settings > AI Agent, the first message of each pause raises an ai_agent_disabled_message bell, the chat is marked handed_off (reason ai_disabled) and the owner's offline message is sent if one is set. With no settings row at all the agent stays silent.
11. Identity rule
The only phone number the AI trusts is from on the WhatsApp webhook, which Meta has verified. It becomes the conversation's channel_ref and clientPhone and is passed by the server into every tool; the model never supplies it.
get_client_appointments,check_wallet_balance, cancel, reschedule and add-services resolve the client from that number only, within the brand. Appointment ids are checked to belong to that client. A phone number typed in chat, or put in a tool argument, is ignored; on WhatsAppcreate_bookinguses the channel's number over anyclient_phoneargument.- One number can match several client records (family numbers, imports). Then the tool answers
ambiguous_clientand the AI must ask for the full name on the booking, which has to match exactly one record. - The widget and Meta DM channels are not verified: they cannot look up appointments or wallets (
not_verified) and never use a client name from a record. - The client name put in the prompt is capped at 60 characters, whitespace-collapsed, and placeholders or reference codes are dropped, so stored names cannot inject instructions. All client messages, tool output and owner text are marked as data in the system prompt.
- Bookings made by phone or in Zylu may not exist in Kagami, so an empty appointment list is never presented as "you have no booking".
12. Follow-ups and other jobs that touch the AI
| Job | Route | What it does |
|---|---|---|
| Cold follow-ups | /api/cron/ai-chat-recovery |
After the AI's last reply goes unanswered: up to 3 nudges at 5 min, 30 min and about 23.5 h, only 08:00-21:00 IST, only for active chats, never for opted-out or silent-declined clients (lib/ai/cart-recovery.ts) |
| Turn lease sweep | /api/cron/ai-turn-lease-sweep |
Section 2 |
| Reply escalation | /api/cron/ai-reply-escalation |
Section 9 |
| Pre-arrival nudges, whitespace analyser, NPS | /api/cron/ai-pre-arrival-nudge, ai-whitespace-analyzer, ai-nps-surveys |
See ai-upsell-offers.md and reputation.md |
| Chat anomaly check | /api/cron/ai-chat-anomalies |
Nightly: non-UUID option ids, price disputes, "no thanks" after a correction (see ai-quality-and-eval.md) |
All cron routes require the x-cron-secret header matching CRON_SECRET. Schedules: the lease sweep and reply escalation run every 2 minutes (pg_cron, 0244 and 0240, slowed from every minute by 0290_disk_io_cron_churn.sql); ai-chat-recovery every 5 minutes (0232); ai-nps-surveys every 15 minutes (0287). The pre-arrival nudge and whitespace analyser schedules are in ai-upsell-offers; the anomaly check runs from the VM crontab (see ai-quality-and-eval).
Where owners configure things
| Setting | Location |
|---|---|
| Agent on/off, name, custom instructions, handoff and offline messages | Dashboard > Settings > AI Agent |
| FAQ answers the AI quotes (parking, payments, cancellation, ...) | Settings > WhatsApp FAQ |
| Who is bell-notified and paged | Settings > Alerts |
| Brand-level WhatsApp on/off | Settings > Messaging |
| Per-store WhatsApp on/off | Settings > Locations (per-location WhatsApp toggle) |
| Held replies, Take over / Resume AI | Dashboard > Inbox |
Custom instructions are appended after the fixed rules and never override the Facts and Safety rules. Their text also counts as a source for price grounding, so an owner-written price in the instructions may be quoted.
Troubleshooting / where to look
| Symptom | Check |
|---|---|
| No replies at all | /api/health warnings (ai_no_enabled_brand, ai_no_provider, ai_silent); brand is_whatsapp_enabled; AI enabled in Settings > AI Agent; webhook 403s mean META_APP_SECRET is wrong or unset |
| Client says "no reply" in a quiet chat | Is the conversation handed_off and inside its pause (section 10)? Rate-limit hit (section 4)? Check the bell for ai_agent_paused_message |
| Reply delayed ~3 s | Normal: 2.5 s debounce to merge quick messages |
| Reply sent twice | Look for two web instances; the DB lock should prevent it. Check inbound_messages for the same provider_message_id |
| "AI assistant could not reply" bell | captureError tags whatsapp_webhook.agent_turn, ai_gateway.provider_failover; usually all LLM providers failed |
| Reply stuck mid-turn | inbound_messages.ai_turn_claimed_at set with lease_expires_at in the past and attempts; the sweep retries then alerts |
Reply held or handed off with ungrounded_* |
ai_conversations.handoff_reason, ai_action_logs.tool_calls (look for grounding_check entries); the blocked draft is in the held-replies list |
| WhatsApp reply failed to deliver | whatsapp_delivery_failed bell; outbound_messages.status and failed_at |
| Booking not made after a yes | Tool log rows in ai_messages (direction = tool_result), error_code confirmation_required, slot_unavailable or invalid_input |
| Customer messaged a store but landed at the wrong branch | inbound_messages.routing_type, client_store_preference (24 h preference beats older signals) |
Tables most useful for debugging: ai_conversations, ai_messages (includes tool rows), ai_action_logs, ai_reply_holds, inbound_messages, outbound_messages, whatsapp_opt_outs, ai_resume_cache. Tests live beside the code as lib/ai/*.test.ts; gateway.*.test.ts cover the loop and replay.*.test.ts replay real chats.