# WAHA OpenClaw Plugin — Product Requirements Document

## Vision
A production-grade WhatsApp channel plugin for OpenClaw that enables AI agents to fully interact with WhatsApp — messaging, group management, contact resolution, media handling, and more. The plugin should be reliable, durable, and handle edge cases gracefully.

**Future**: Port core WAHA client library to work with Claude Code, Cursor, and other AI platforms.

## Current State (v1.10.4)
- **API Coverage**: ~87% of WAHA endpoints implemented
- **Message Types**: Text, images, video, audio, documents, polls, locations, contacts, lists, link previews, buttons, reactions, stickers — all working
- **Name Resolution**: Fuzzy name-to-JID resolution with auto-resolve on standard actions (30s cache)
- **Search/Listing**: `search` action for finding groups/contacts/channels by name
- **Deployed**: Production on hpg6, Sammie responding in groups and DMs with text+voice

### Full Working Features

**Standard Actions** (gateway-recognized, support targets):
send, poll, react, edit, unsend, pin, unpin, read, delete, reply

**Auto Name-to-JID Resolution**:
Fuzzy matching via `autoResolveTarget`, 30-second TTL cache, works on all standard actions automatically.

**Rich Message Types**:
Polls, locations, contact cards (vCards), lists, link previews, button replies, events.

**Media**:
Images, videos, files, voice messages (proper voice bubbles), stickers (send and receive). Direct WAHA API calls via `sendWahaImage`/`sendWahaVideo`/`sendWahaFile`.

**Message Management**:
Edit, delete/unsend, pin, unpin, star, forward.

**Chat Management**:
Archive, unarchive, mark read/unread, delete, clear.

**Group Management**:
Create, delete, leave, join, rename, description, picture, participants (add/remove), admin promote/demote, invite codes, info/messages admin-only settings.

**Contact Management**:
List, details, exists check, about, picture, block/unblock.

**Channel/Newsletter**:
List, create, delete, follow, unfollow, mute, unmute, search, preview.

**Labels**:
CRUD, assign to chats, filter chats by label.

**Status/Stories**:
Text, image, voice, video, delete.

**Presence**:
Online/offline, subscribe to contact presence.

**Profile**:
Get/set name, status, picture.

**LID Resolution**:
Phone-to-LID and LID-to-phone lookups.

**Calls**:
Reject incoming calls.

**Search/Listing**:
`search` action for finding groups, contacts, channels by name.

### Admin Panel (Web UI)
Embedded single-page web UI served by the webhook HTTP server in `monitor.ts`.

**Directory Tab**:
- Paginated listing of contacts, groups, and newsletters
- Search and filter by type (contact/group/newsletter)
- Lazy-loaded group participants with admin indicators
- Per-contact DM settings (mode: active/listen_only, mention-only, custom keywords, can-initiate)
- Allow/block toggles for DMs and group participants
- Bulk allow/block all participants in a group
- Refresh directory from WAHA API

**Config Tab**:
- Group filter settings (enable/disable, keyword patterns)
- DM filter settings (enable/disable)
- Editable keyword patterns for message filtering
- Config persisted to `~/.openclaw/openclaw.json`

**Filter Stats Tab**:
- Message filter statistics (processed, filtered, passed)
- Duplicate webhook tracking (message vs message.any dedup)
- Per-filter breakdown of filtered messages

**Status Tab**:
- WAHA session status and connection health
- Gateway restart button
- Session details from WAHA API

**Data Store**: SQLite via `DirectoryDb` class (directory.ts) with tables: `contacts`, `dm_settings`, `allow_list`, `group_participants`. WAL mode, foreign keys enabled.

## Requirements — Reliability & Durability

### R1: No Silent Errors
- All WAHA API call failures must be logged with context (action, chatId, error message)
- Outbound failures must return actionable error messages to the LLM
- Presence calls (typing, seen) currently silently swallow errors — add warning logs
- Media preprocessing failures must be surfaced, not silently dropped

### R2: Rate Limiting & Backoff
- Implement exponential backoff on WAHA API 429 responses
- Add token bucket for outbound messages (configurable rate limit)
- Prevent message flood from large groups overwhelming the handler

### R3: Session Health Monitoring
- Periodic health check ping to WAHA API (every 60s)
- Detect silent session disconnection (no webhooks for >5 minutes when expected)
- Log warnings on session health degradation
- Auto-alert on session loss

### R4: Memory Leak Prevention
- Audit all caches (resolveTarget cache, config cache) for unbounded growth
- Add cache size limits and LRU eviction
- Ensure webhook handler doesn't accumulate state across requests
- Profile memory usage under sustained load

### R5: Webhook Robustness
- Message deduplication by messageId (not just event type filtering)
- Handle out-of-order webhook delivery
- Graceful handling of malformed webhook payloads
- Request timeout on WAHA API calls (30s default)

## Requirements — Missing Features

### F1: Mute/Unmute Chat (MEDIUM)
- Add muteChat/unmuteChat actions to send.ts and channel.ts
- Expose in UTILITY_ACTIONS
- Document in SKILL.md

### F2: Inbound Group Events (MEDIUM)
- Handle group.join, group.leave, group.promote, group.demote system messages
- Parse participant info from system message payloads
- Surface as context to the LLM

### F3: Mentions Detection (MEDIUM)
- Extract @mentioned users from inbound messages
- Provide mention context to the LLM (who was mentioned, their JID)

### F4: Multi-Recipient Send (MEDIUM)
- Add batch send capability (send same message to multiple chats)
- Rate-limited sequential send (not parallel, to avoid WAHA overload)
- Return per-recipient success/failure results

### F5: Message Queue / Flood Protection (HIGH)
- Async message preprocessing with bounded queue
- Drop oldest messages if queue exceeds threshold
- Priority lane for DMs over group messages
- Configurable queue size and timeout

### F6: HTTP Request Timeouts (HIGH)
- Add configurable timeout to all WAHA API calls (default 30s)
- AbortController-based cancellation
- Retry with backoff on timeout

### F7: Better Error Messages (LOW)
- Wrap all WAHA API errors with context (what action, what target, what failed)
- Suggest fixes in error messages (e.g., "JID not found — did you mean X?")

## Non-Goals (For Now)
- Claude Code / Cursor adapter (future milestone)
- Scheduled messages (WAHA doesn't support)
- WhatsApp Business templates (not applicable for personal assistant)
- Broadcast lists (WAHA limitation)
- Call initiation (WAHA limitation)
- Disappearing messages (low priority)

## Success Criteria
1. Zero silent errors — all failures logged and surfaced
2. Graceful degradation under load (message queue, rate limiting)
3. Session loss detected within 2 minutes
4. No memory leaks after 24h sustained operation
5. All WAHA API calls have timeouts
6. Comprehensive SKILL.md with error scenarios documented
