feat(channels): add WhatsApp Agent Platform channel

Adds `whatsapp_agent`, an additive channel that connects nanobot to the
official WhatsApp Agent Platform API (https://api.whatsapp.com/agent/v1).
It authenticates with a per-agent API token and long-polls `GET /updates`
instead of linking a device, so it is the officially supported interface
rather than the Neonize linked-device protocol used by the existing
`whatsapp` channel.

The existing `whatsapp` channel is unchanged; both can run at once under
different names.

Design notes:
- The poll cursor, dedup window, and creator identifier live in one
  atomically replaced state file. A message id is recorded before it is
  handled, so a crash re-reads the batch without answering twice, and the
  cursor is only accepted after the batch is processed.
- The first poll omits `offset`, which resolves the head and never replays
  up to 30 days of history into an auto-replying agent.
- A changed token resets the cursor, because `next_offset` is only valid
  for the agent that issued it.
- Each API method is paced below its own rolling 60-second limit, and
  progress/tool-hint messages default to off because they spend the shared
  12-per-minute send budget.
- Retries are limited to confirmed non-delivery (`429`, `503`/`131016`).
  A `500` or read timeout is ambiguous, so it is not retried unless
  `retryAmbiguousSends` is set; a duplicate is worse than a missed reply.
- Inbound media is downloaded through the shared SSRF guard, size-capped,
  and verified against the reported digest. Outbound media is validated
  before upload.
- Reactions are receive-only, matching the API. The token is never logged
  or persisted; state stores only a SHA-256 fingerprint.

Docs compare both WhatsApp channels, including the lack of end-to-end
encryption, country availability, and rate limits.
This commit is contained in:
Carmelo Campos authored and Xubin Ren committed 2026-10-18 14:49:49 +08:00
1 parent 74942bd190
commit b7cb5da4b5
30 files changed
+3962 -1

No files matched your search

+1
View File
@@ -130,6 +130,7 @@ File operations have path traversal protection, but:
**WhatsApp:**
- Keep the neonize session database under `~/.nanobot/whatsapp-auth` secure (mode 0700).
- Use `nanobot channels login whatsapp --force` to remove and recreate the local session database when rotating linked devices.
- The separate `whatsapp_agent` channel authenticates with a per-agent API token. Treat it as a secret, prefer `${WA_AGENT_TOKEN}` over a literal value in `config.json`, and regenerate it in WhatsApp when it may have leaked. Its poll cursor holds no token material.
### 6. Dependency Security
+44 -1
View File
@@ -9,6 +9,7 @@ Connect nanobot to Telegram, Discord, Slack, WeChat, Email, Mattermost, Linear,
| Slack | [Build a Slack AI Agent with nanobot](./guides/slack-ai-agent.md) |
| Feishu | [Build a Feishu AI Agent with nanobot](./guides/feishu-ai-agent.md) |
| WhatsApp | [Build a WhatsApp AI Agent with nanobot](./guides/whatsapp-ai-agent.md) |
| WhatsApp Agent Platform | [Build an official WhatsApp agent with nanobot](./guides/whatsapp-agent-platform.md) |
| WeChat | [Build a WeChat AI Agent with nanobot](./guides/wechat-ai-agent.md) |
| QQ | [Build a QQ AI Agent with nanobot](./guides/qq-ai-agent.md) |
| Email | [Build an Email AI Agent with nanobot](./guides/email-ai-agent.md) |
@@ -50,7 +51,7 @@ The sections below explain what each chat platform requires and provide manual c
> nanobot plugins enable <channel>
> ```
>
> Replace `<channel>` with names such as `telegram`, `slack`, `feishu`, `dingtalk`, `matrix`, `qq`, `napcat`, `weixin`, `wecom`, or `msteams`. To turn a channel off later, run `nanobot plugins disable <channel>`. nanobot keeps the saved settings, but stops loading that channel after the next restart.
> Replace `<channel>` with names such as `telegram`, `slack`, `feishu`, `dingtalk`, `matrix`, `qq`, `napcat`, `weixin`, `wecom`, `msteams`, or `whatsapp_agent`. To turn a channel off later, run `nanobot plugins disable <channel>`. nanobot keeps the saved settings, but stops loading that channel after the next restart.
## Manual Setup Pattern
@@ -89,6 +90,7 @@ If `nanobot channels status` does not show the channel as enabled, the config sn
| **Telegram** | Bot token from @BotFather |
| **Discord** | Bot token + Message Content intent |
| **WhatsApp** | QR code scan (`nanobot channels login whatsapp`) |
| **WhatsApp Agent Platform** | Agent API token from WhatsApp → Settings → Agents |
| **WeChat (Weixin)** | QR code scan (`nanobot channels login weixin`) |
| **Feishu** | QR code scan (`nanobot channels login feishu`) or App ID + App Secret |
| **DingTalk** | App Key + App Secret |
@@ -474,6 +476,47 @@ Modern WhatsApp can deliver a sender's LID instead of their phone number. nanobo
</details>
<details>
<summary><b>WhatsApp Agent Platform</b></summary>
Connects nanobot through the **official** WhatsApp Agent Platform API. The agent appears as its own chat in WhatsApp and can only talk to you, its creator. No QR pairing, no linked device, and no optional Python dependencies.
This is a different channel from `whatsapp`. See the [official WhatsApp agent guide](./guides/whatsapp-agent-platform.md) for the full comparison and walkthrough.
**1. Create the agent in WhatsApp**
Open WhatsApp → **Settings → Agents → Create an agent**, then copy the key from the agent's chat → **Chat info → API key**. This feature is available only in limited countries and might not be in your account yet.
**2. Configure**
```json
{
"channels": {
"whatsapp_agent": {
"enabled": true,
"token": "${WA_AGENT_TOKEN}"
}
}
}
```
`allowFrom` is optional. The platform already restricts the chat to the agent's creator; leave `allowFrom` empty to require pairing approval instead of a static list.
**3. Run**
```bash
nanobot gateway
```
**Notes**
- At most one gateway may poll a given agent token. A second one causes `409` and is logged as a duplicate-poller error.
- Agent conversations are not end-to-end encrypted: Meta processes them on the agent's behalf. Your other chats are unaffected.
- Replies are split at 4096 characters. Progress and tool-hint messages are off by default because every send spends the same 12-per-minute budget.
- Ambiguous send outcomes (HTTP `500`, read timeouts) are not retried by default, because a duplicate is worse than a miss. Set `retryAmbiguousSends: true` to opt in.
</details>
<details>
<summary><b>Feishu</b></summary>
+1
View File
@@ -26,6 +26,7 @@ Use **Channels** in the WebUI for guided setup. These guides explain the account
| Connect Slack | [Slack AI agent](./slack-ai-agent.md) |
| Connect Feishu | [Feishu AI agent](./feishu-ai-agent.md) |
| Connect WhatsApp | [WhatsApp AI agent](./whatsapp-ai-agent.md) |
| Connect an official WhatsApp agent | [Official WhatsApp agent](./whatsapp-agent-platform.md) |
| Connect WeChat | [WeChat AI agent](./wechat-ai-agent.md) |
| Connect QQ | [QQ AI agent](./qq-ai-agent.md) |
| Connect Email | [Email AI agent](./email-ai-agent.md) |
+173
View File
@@ -0,0 +1,173 @@
# Build an official WhatsApp agent with nanobot
This guide connects nanobot to WhatsApp through the `whatsapp_agent` channel, which uses the **official WhatsApp Agent Platform** API. The agent appears as its own chat inside WhatsApp and talks only to you.
This is a different product from the [`whatsapp`](./whatsapp-ai-agent.md) channel.
## Which WhatsApp channel should I use?
| | `whatsapp_agent` (this guide) | `whatsapp` |
|---|---|---|
| How it connects | An official agent API token | A linked WhatsApp device (QR) |
| API | `https://api.whatsapp.com/agent/v1` | Neonize device session |
| Who it can talk to | Only you, the agent's creator | Chats and groups the linked device can see |
| Groups | Not supported | Supported |
| Message transport | Long-polling `GET /updates` | Device connection |
| End-to-end encryption | **No** — Meta manages agent chats | Yes, like a linked device |
| Availability | Limited countries, per account | Wherever WhatsApp can link a device |
| Account risk | Officially supported interface | Uses an unofficial linked-device protocol |
Choose `whatsapp_agent` when you want an official, sandboxed personal assistant that WhatsApp itself provides, and you do not need group access. Keep `whatsapp` when you need groups, media breadth, or availability in a country where the Agent Platform has not rolled out.
Both channels can be enabled at once with different names and different access rules.
## What this guide builds
- the `whatsapp_agent` channel enabled in `config.json`
- a WhatsApp agent created from WhatsApp Settings
- the agent's API token stored in nanobot
- one approved sender
## Prerequisites
- A working local nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- A WhatsApp account with **Settings → Agents** available. This experience is available only in limited countries and might not appear in your account yet.
- A machine that can keep `nanobot gateway` running. Outbound connections are enough; no inbound webhook or public URL is required.
## Step 1: Create the agent in WhatsApp
1. Open WhatsApp and go to **Settings → Agents → Create an agent**.
2. Set a display name and avatar.
3. Open the agent's chat, then **Chat info → API key**.
4. Copy the key. This is the agent's API token.
You can connect up to five agents to one WhatsApp account. The token is shown again only if you regenerate it, and rotating it invalidates the previous value immediately. If you uninstall WhatsApp, regenerate the token.
## Step 2: Enable the channel
The channel uses only nanobot core dependencies, so no optional install is required:
```bash
nanobot plugins enable whatsapp_agent
```
Or edit `~/.nanobot/config.json` directly:
```json
{
"channels": {
"whatsapp_agent": {
"enabled": true,
"token": "<AGENT_API_TOKEN>"
}
}
}
```
Keep the token in an environment variable instead of the file when you can, and reference it:
```json
{
"channels": {
"whatsapp_agent": {
"enabled": true,
"token": "${WA_AGENT_TOKEN}"
}
}
}
```
## Step 3: Run and test
```bash
nanobot gateway
```
Open the agent's chat in WhatsApp and send a message. The agent replies in the same chat using the same model, workspace, memory, and tools as the CLI and WebUI.
## Access control
The Agent Platform already restricts the conversation to you, the agent's creator. `allowFrom` is a second, local check and is optional.
When `allowFrom` is empty, an unapproved sender receives a pairing code. Approve it from a trusted local surface:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
The sender identifier has the form `user:<id>`. Treat it as opaque, never share it, and prefer pairing over hardcoding it, because the identifier can change if you change your phone number or re-register your account. nanobot stores the most recent identifier and uses it for replies.
## Configuration reference
| Key | Default | Meaning |
|---|---|---|
| `enabled` | `false` | Load the channel at gateway start. |
| `token` | — | The agent's API token. Required. |
| `allowFrom` | `[]` | Extra local allowlist of `user:<id>` values, or `["*"]`. Empty means pairing-only. |
| `stateDir` | `~/.nanobot/whatsapp-agent` | Where the durable poll cursor and dedup state are stored. |
| `pollTimeout` | `25` | Long-poll hold time in seconds (0–25). |
| `markRead` | `true` | Send read receipts for inbound messages. |
| `typingIndicator` | `true` | Show "typing…" while the agent works. |
| `downloadMedia` | `true` | Download inbound image, audio, video, document, and sticker media. |
| `deleteMediaAfterDownload` | `false` | Delete the server copy once downloaded. |
| `maxMediaMb` | `16` | Local cap on inbound and outbound media, in MB. |
| `retryAmbiguousSends` | `false` | Retry sends whose outcome is unknown (HTTP 500, read timeouts). See "Delivery semantics". |
| `sendProgress` | `false` | Send agent progress messages. Off because each one spends the send budget. |
| `sendToolHints` | `false` | Send tool-call hints. Off for the same reason. |
## Media
Inbound media is downloaded, verified against the digest WhatsApp reports, then stored under the channel's media directory and passed to the agent like media from any other channel.
- Images: JPEG, PNG — 5 MB.
- Stickers: WebP — 500 KB.
- Video, audio, documents, generic files — 16 MB.
- Voice notes are transcribed when a transcription provider is configured; the audio file stays attached.
Outbound media is uploaded first, then sent as the matching message type. Files over the limit for their type, or with an MIME type the platform does not accept, are skipped with an error in the log instead of failing the whole reply.
Note that audio the agent sends arrives as a normal file attachment, not as a WhatsApp voice-note bubble.
Reactions are receive-only on this platform: the API rejects sending them. nanobot reads an inbound reaction (including an empty emoji, which means the reaction was removed) but does not forward it as a turn, so a reaction never triggers a reply. Media on both sides expires 30 days after it is stored; nanobot holds downloaded files locally and can delete the server copy with `deleteMediaAfterDownload`.
## Delivery semantics
The platform's send result determines whether a retry is safe:
- **Rate limit or "not accepted for delivery"** (`429`, `503`): the message was not sent, so nanobot retries with backoff.
- **A plain `500`, a dropped connection, or a read timeout**: WhatsApp cannot say whether the message was delivered. nanobot does **not** retry by default, because a duplicate is more disruptive than a missed reply. Set `retryAmbiguousSends` to `true` if you prefer a chance of duplicates over a chance of loss.
Replies longer than 4096 characters are split into multiple messages and sent in order. The first chunk quotes the message being answered.
At most one poller may run per agent token. If you start a second gateway against the same token, the older poll fails with `409`; nanobot logs this clearly and backs off. Run one gateway instance per agent.
## Operational notes
- **Rate limits.** WhatsApp allows 12 sends, 12 read receipts, 15 polls, and 12 media requests per minute per agent. nanobot paces each method below its own limit and counts retries against the same budget, which is why progress messages are off by default.
- **Durable cursor.** The poll cursor is written to disk after each handled message, so a restart resumes exactly where it stopped and a replayed batch is deduplicated by message id.
- **Retention.** WhatsApp keeps updates for 30 days. nanobot starts from the current head on first run, so it does not answer old history.
- **Invalid token.** If WhatsApp rejects the token, the channel stops and logs an actionable message instead of retrying forever.
- **Privacy.** Agent conversations are not end-to-end encrypted: Meta processes them on the agent's behalf. Your other WhatsApp chats are unaffected. Do not use this channel for data that requires end-to-end encryption.
## Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| `Settings → Agents` is missing | The feature is not available in your country or account | Use the `whatsapp` channel instead |
| "API token was rejected" | Token rotated, revoked, or mistyped | Regenerate it in the agent's chat info and update the config |
| `409` in the logs | Two gateways share one agent token | Run a single gateway per agent |
| Agent never replies | No inbound message has arrived yet, so no recipient is known | Send the agent a message first |
| Media messages show a placeholder | Download failed, digest mismatch, or the file exceeded the limit | Check the log; re-send the file |
| Replies arrive late | The turn is longer than the 25-second typing window | This is expected; the reply still arrives |
## Next steps
- [Chat Apps reference](../chat-apps.md)
- [Pairing](../configuration.md#pairing)
- [Official WhatsApp agent help](https://faq.whatsapp.com/1050934623978152)
- [Secure local AI agent](./secure-local-ai-agent.md)
+3
View File
@@ -2,6 +2,9 @@
This guide connects nanobot to WhatsApp through the `whatsapp` channel. The channel links as a WhatsApp device and uses the same nanobot agent runtime, tools, memory, and workspace as the CLI and WebUI.
> [!NOTE]
> WhatsApp also offers an official Agent Platform where the agent appears as its own chat and talks only to you. That is a separate channel with different tradeoffs — no group support, no end-to-end encryption, and limited country availability, but an officially supported interface that does not rely on a linked device. See [Build an official WhatsApp agent with nanobot](./whatsapp-agent-platform.md) to compare them.
## What this guide builds
- WhatsApp optional dependencies installed
@@ -0,0 +1 @@
"""WhatsApp Agent Platform channel package."""
@@ -0,0 +1,36 @@
"""WhatsApp Agent Platform management contract."""
from nanobot.channels._manifest import field, required
from nanobot.channels.contracts import ChannelSetupSpec
from nanobot.channels.plugin import ChannelPlugin
from nanobot.channels.whatsapp_agent.validation import validate
SETUP_SPEC = ChannelSetupSpec(
fields={
"token": field("secret"),
"allowFrom": field("list"),
"stateDir": field(),
"pollTimeout": field("int", default=25),
"markRead": field("bool", default=True),
"typingIndicator": field("bool", default=True),
"downloadMedia": field("bool", default=True),
"deleteMediaAfterDownload": field("bool", default=False),
"maxMediaMb": field("int", default=16),
"retryAmbiguousSends": field("bool", default=False),
"sendProgress": field("bool", default=False),
"sendToolHints": field("bool", default=False),
},
required=(required("token"),),
official_url="https://faq.whatsapp.com/1050934623978152",
validator=validate,
verifies_connection=True,
)
PLUGIN = ChannelPlugin(
name="whatsapp_agent",
display_name="WhatsApp Agent Platform",
runtime=f"{__package__}.runtime:WhatsAppAgentChannel",
setup=SETUP_SPEC,
dependencies=(),
webui="webui/index.ts",
)
+491
View File
@@ -0,0 +1,491 @@
"""Wire parsing and error classification for the WhatsApp Agent Platform.
Everything in this module is a pure function over untrusted response data. The
runtime calls it at the boundary so the rest of the channel works with concrete
types, matching nanobot's "type dynamic boundaries at the edge" constraint.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal, cast
from nanobot.security.network import validate_url_target
API_BASE = "https://api.whatsapp.com/agent/v1"
# Bump only alongside a deliberate protocol change; sent as a header on polls.
USER_AGENT = "nanobot-whatsapp-agent"
TEXT_MAX_CHARS = 4096
CAPTION_MAX_CHARS = 1024
# Per-method rolling-window limits from the Developer Manual, section 6.
RATE_LIMITS = {
"messages": 12,
"statuses": 12,
"updates": 15,
"media": 12,
}
_RATE_WINDOW_SECONDS = 60.0
# error.code values that carry a specific recovery contract.
CODE_INVALID_TOKEN = 100
CODE_MISSING_AUTH = 190
CODE_RATE_LIMITED = 130429
CODE_NOT_CREATOR = 131005
CODE_BAD_REQUEST = 131009
CODE_NOT_ACCEPTED = 131016
CODE_MEDIA_REJECTED = 131053
CODE_POLL_REPLACED = 1752041
MEDIA_LIMITS = {
"image": 5 * 1024 * 1024,
"sticker": 500 * 1024,
"video": 16 * 1024 * 1024,
"audio": 16 * 1024 * 1024,
"document": 16 * 1024 * 1024,
"application/octet-stream": 16 * 1024 * 1024,
}
ACCEPTED_UPLOAD_MIME = {
# image
"image/jpeg",
"image/png",
# video
"video/mp4",
"video/3gpp",
# audio
"audio/aac",
"audio/mp4",
"audio/mpeg",
"audio/amr",
"audio/ogg",
"audio/opus",
# document
"application/pdf",
"text/plain",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
# sticker
"image/webp",
# generic
"application/octet-stream",
}
# MIME aliases the platform normalizes to a canonical accepted type.
_MIME_ALIASES = {
"audio/x-m4a": "audio/mp4",
"audio/x-hx-aac-adts": "audio/aac",
"image/jpg": "image/jpeg",
}
MessageKind = Literal[
"text",
"image",
"audio",
"video",
"document",
"sticker",
"reaction",
"unknown",
]
@dataclass(frozen=True)
class InboundMedia:
"""Media handle attached to an inbound message."""
media_id: str
mime_type: str
sha256_base64: str = ""
caption: str = ""
filename: str = ""
voice: bool = False
animated: bool = False
@dataclass(frozen=True)
class InboundMessage:
"""One inbound WhatsApp message, normalized for the agent pipeline."""
wamid: str
sender: str
timestamp: int | None
kind: MessageKind
text: str = ""
media: InboundMedia | None = None
# Reply context: the quoted wamid and its author (``user:`` or ``agent:``).
context_id: str = ""
context_from: str = ""
# Reaction payload (receive-only).
reaction_to: str = ""
reaction_emoji: str = ""
raw: dict[str, Any] = field(default_factory=dict)
@property
def is_user_authored(self) -> bool:
"""Whether the creator, rather than the agent, sent this message."""
return self.sender.startswith("user:")
@dataclass(frozen=True)
class InboundStatus:
"""A delivery or read receipt for a previously sent message."""
wamid: str
status: str
recipient: str
timestamp: int | None
@dataclass(frozen=True)
class PollBatch:
"""One parsed ``GET /updates`` response."""
messages: list[InboundMessage]
statuses: list[InboundStatus]
next_offset: int | None
@dataclass(frozen=True)
class APIError:
"""Classified failure from any Agent Platform endpoint."""
status_code: int
code: int
message: str
details: str
fbtrace_id: str
@property
def invalid_token(self) -> bool:
"""Whether the response means the token was rotated or revoked.
A malformed or missing ``Authorization`` header yields 401/190. A token
that is present but not valid yields 400/100 — the API deliberately does
not use 401 for that case.
"""
return self.status_code == 401 or (
self.status_code == 400
and self.code == CODE_INVALID_TOKEN
and not self._is_length_rejection
)
@property
def _is_length_rejection(self) -> bool:
"""400/100 is also used for over-length text, captions, and bad media ids."""
if self.status_code not in (400, 404):
return False
# The manual sets ``message`` to the bare field name for a length cap.
return self.message.strip() in {"text.body", "text", "caption", "body"}
@property
def poll_replaced(self) -> bool:
"""Another process opened a newer poll for this agent."""
return self.status_code == 409 or self.code == CODE_POLL_REPLACED
@property
def rate_limited(self) -> bool:
return self.status_code == 429 or self.code == CODE_RATE_LIMITED
@property
def retryable(self) -> bool:
"""Whether an unchanged retry can succeed.
``503``/``131016`` means the message was not accepted for delivery, so
resending is safe. A plain ``500`` may or may not have been delivered,
so it is deliberately excluded from automatic retries.
"""
return self.rate_limited or self.code == CODE_NOT_ACCEPTED
@property
def ambiguous(self) -> bool:
"""Whether the outcome cannot be determined and a retry may duplicate."""
return self.status_code >= 500 and not self.retryable
def __str__(self) -> str:
parts = [f"HTTP {self.status_code}", f"code={self.code}"]
if self.fbtrace_id:
parts.append(f"fbtrace_id={self.fbtrace_id}")
if self.message:
parts.append(self.message)
return " ".join(parts)
class WhatsAppAgentError(Exception):
"""Base class for channel-owned failures."""
class WhatsAppAgentAuthError(WhatsAppAgentError):
"""The API token was rejected; retrying cannot succeed."""
class WhatsAppAgentAPIError(WhatsAppAgentError):
"""A classified non-auth API failure."""
def __init__(self, error: APIError) -> None:
super().__init__(str(error))
self.error = error
def classify_error(status_code: int, payload: Any) -> APIError:
"""Extract the structured error from a non-2xx response body."""
body = _as_dict(payload) or {}
error = _as_dict(body.get("error")) or {}
raw_code = error.get("code")
try:
code = int(raw_code) # type: ignore[arg-type]
except (TypeError, ValueError):
code = 0
details = ""
error_data = _as_dict(error.get("error_data"))
if error_data is not None:
details = _text(error_data.get("details"))
return APIError(
status_code=status_code,
code=code,
message=_text(error.get("message")),
details=details,
fbtrace_id=_text(error.get("fbtrace_id")),
)
def parse_poll_batch(payload: Any) -> PollBatch:
"""Parse a 200 ``GET /updates`` body.
The API guarantees exactly one entry and one change, but the parser still
reads defensively: a shape change must degrade to "no messages" rather than
crash the poll loop.
"""
if not isinstance(payload, dict):
return PollBatch([], [], None)
messages: list[InboundMessage] = []
statuses: list[InboundStatus] = []
for value in _change_values(cast(dict[str, Any], payload)):
for raw in _as_list(value.get("messages")):
message = parse_message(raw)
if message is not None:
messages.append(message)
for raw in _as_list(value.get("statuses")):
status = parse_status(raw)
if status is not None:
statuses.append(status)
return PollBatch(
messages, statuses, _optional_int(cast(dict[str, Any], payload).get("next_offset"))
)
def _change_values(payload: dict[str, Any]) -> list[dict[str, Any]]:
values: list[dict[str, Any]] = []
for entry in _as_list(payload["entry"] if "entry" in payload else None):
entry_map = _as_dict(entry)
if entry_map is None:
continue
for change in _as_list(entry_map.get("changes")):
change_map = _as_dict(change)
if change_map is None:
continue
value = _as_dict(change_map.get("value"))
if value is not None:
values.append(value)
return values
def parse_message(raw: Any) -> InboundMessage | None:
"""Parse one inbound message object."""
message = _as_dict(raw)
if message is None:
return None
wamid = _text(message.get("id"))
sender = _text(message.get("from"))
if not wamid or not sender:
return None
kind = _normalize_kind(raw.get("type"))
text = ""
media: InboundMedia | None = None
reaction_to = ""
reaction_emoji = ""
if kind == "text":
body = _as_dict(message.get("text"))
text = _text(body.get("body")) if body is not None else ""
elif kind == "reaction":
reaction = _as_dict(message.get("reaction"))
if reaction is not None:
reaction_to = _text(reaction.get("message_id"))
# An empty emoji means the reaction was removed.
reaction_emoji = _text(reaction.get("emoji"))
elif kind in {"image", "audio", "video", "document", "sticker"}:
media = _parse_media(kind, message.get(kind))
context_id = ""
context_from = ""
context = _as_dict(message.get("context"))
if context is not None:
# Inbound uses ``id``; outbound quoting uses ``message_id``.
context_id = _text(context.get("id"))
context_from = _text(context.get("from"))
return InboundMessage(
wamid=wamid,
sender=sender,
timestamp=_optional_int(message.get("timestamp")),
kind=kind,
text=text,
media=media,
context_id=context_id,
context_from=context_from,
reaction_to=reaction_to,
reaction_emoji=reaction_emoji,
raw=message,
)
def _parse_media(kind: str, payload: Any) -> InboundMedia | None:
media = _as_dict(payload)
if media is None:
return None
media_id = _text(media.get("id"))
if not media_id:
return None
return InboundMedia(
media_id=media_id,
mime_type=normalize_mime(_text(media.get("mime_type"))),
sha256_base64=_text(media.get("sha256")),
caption=_text(media.get("caption")),
filename=_text(media.get("filename")),
# ``voice`` and ``animated`` appear only for the matching variant.
voice=kind == "audio" and bool(media.get("voice")),
animated=bool(media.get("animated")),
)
def parse_status(raw: Any) -> InboundStatus | None:
"""Parse one delivery or read receipt."""
receipt = _as_dict(raw)
if receipt is None:
return None
wamid = _text(receipt.get("id"))
status = _text(receipt.get("status"))
if not wamid or status not in {"delivered", "read"}:
return None
return InboundStatus(
wamid=wamid,
status=status,
recipient=_text(receipt.get("recipient_id")),
timestamp=_optional_int(receipt.get("timestamp")),
)
def normalize_mime(mime_type: str) -> str:
"""Strip parameters and apply platform aliases."""
base = mime_type.partition(";")[0].strip().lower()
return _MIME_ALIASES.get(base, base)
def media_limit_for(mime_type: str, kind: str) -> int:
"""Return the upload size cap for a kind/MIME pair."""
if kind == "sticker":
return MEDIA_LIMITS["sticker"]
if kind == "image":
return MEDIA_LIMITS["image"]
return MEDIA_LIMITS.get(kind, MEDIA_LIMITS["application/octet-stream"])
def outbound_kind_for_mime(mime_type: str) -> MessageKind:
"""Map a detected MIME type to the sendable message kind."""
mime = normalize_mime(mime_type)
if mime == "image/webp":
return "sticker"
if mime.startswith("image/"):
return "image"
if mime.startswith("video/"):
return "video"
if mime.startswith("audio/"):
return "audio"
return "document"
def quote_safe_url(url: str) -> tuple[bool, str]:
"""Validate an API-returned media URL before fetching it.
The URL arrives from the platform, but it is still an untrusted redirect
target, so it passes through the shared SSRF guard before any request.
"""
if not url:
return False, "empty URL"
return validate_url_target(url)
def _normalize_kind(value: Any) -> MessageKind:
kind = _text(value).lower()
if kind in {"text", "image", "audio", "video", "document", "sticker", "reaction"}:
return kind # type: ignore[return-value]
return "unknown"
def _as_dict(value: Any) -> dict[str, Any] | None:
"""Narrow an untrusted JSON value to an object at the boundary."""
if not isinstance(value, dict):
return None
return cast(dict[str, Any], value)
def _as_list(value: Any) -> list[Any]:
return cast(list[Any], value) if isinstance(value, list) else []
def _text(value: Any) -> str:
if value is None or isinstance(value, bool):
return ""
return str(value).strip()
def _optional_int(value: Any) -> int | None:
if value is None or isinstance(value, bool):
return None
try:
return int(str(value))
except (TypeError, ValueError):
return None
__all__ = [
"ACCEPTED_UPLOAD_MIME",
"API_BASE",
"APIError",
"CAPTION_MAX_CHARS",
"CODE_BAD_REQUEST",
"CODE_MEDIA_REJECTED",
"CODE_NOT_ACCEPTED",
"CODE_NOT_CREATOR",
"CODE_POLL_REPLACED",
"InboundMedia",
"InboundMessage",
"InboundStatus",
"MEDIA_LIMITS",
"MessageKind",
"PollBatch",
"RATE_LIMITS",
"TEXT_MAX_CHARS",
"USER_AGENT",
"WhatsAppAgentAPIError",
"WhatsAppAgentAuthError",
"WhatsAppAgentError",
"classify_error",
"media_limit_for",
"normalize_mime",
"outbound_kind_for_mime",
"parse_message",
"parse_poll_batch",
"parse_status",
"quote_safe_url",
]
+857
View File
@@ -0,0 +1,857 @@
"""WhatsApp Agent Platform channel.
Connects a personal agent to its creator's WhatsApp account through the
official Agent Platform REST API (``https://api.whatsapp.com/agent/v1``).
This is a different product from the ``whatsapp`` channel, which links a
WhatsApp device with Neonize:
* Authentication is an opaque per-agent API token, not a device session.
* Updates arrive by long-polling ``GET /updates``, not by a client connection.
* The agent can only ever talk to its creator, and cannot join groups.
* Conversations are not end-to-end encrypted.
Because the API exposes a single long-poll stream and a small per-method rate
budget, delivery is deliberately serial: one poll at a time, one reply at a
time, and progress/typing traffic is kept off by default.
"""
from __future__ import annotations
import asyncio
import hashlib
import mimetypes
import time
from collections import deque
from contextlib import suppress
from pathlib import Path
from typing import Any, cast
import httpx
from pydantic import Field
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.channels.whatsapp_agent.protocol import (
ACCEPTED_UPLOAD_MIME,
API_BASE,
RATE_LIMITS,
TEXT_MAX_CHARS,
USER_AGENT,
APIError,
InboundMedia,
PollBatch,
WhatsAppAgentAPIError,
WhatsAppAgentAuthError,
classify_error,
media_limit_for,
normalize_mime,
outbound_kind_for_mime,
parse_poll_batch,
quote_safe_url,
)
from nanobot.channels.whatsapp_agent.protocol import (
InboundMessage as PlatformMessage,
)
from nanobot.channels.whatsapp_agent.state import (
WhatsAppAgentState,
default_state_dir,
token_fingerprint,
)
from nanobot.config.schema import Base
from nanobot.events import ContextCompactionEvent
from nanobot.utils.helpers import safe_filename, split_message
# The API allows at most one in-flight poll per agent and counts every request
# over a rolling 60-second window, so the channel paces itself below each cap.
_RATE_LIMIT_MARGIN = 1
_RATE_WINDOW_SECONDS = 60.0
# 15 polls/minute is one per 4s even when traffic is continuous.
_MIN_POLL_GAP_SECONDS = 4.1
_MAX_POLL_LIMIT = 100
_DEFAULT_POLL_LIMIT = 50
# The typing indicator expires after 25s, so refresh inside that window.
_TYPING_REFRESH_SECONDS = 20.0
_BACKOFF_MAX_SECONDS = 60.0
_POLL_REPLACED_SLEEP_SECONDS = 10.0
# After a non-retryable 4xx the request will never succeed unchanged.
_BAD_REQUEST_SLEEP_SECONDS = 60.0
# Local conversation key. The platform allows exactly one counterparty — the
# agent's creator — so a stable key survives the identifier changing.
CREATOR_CHAT_ID = "creator"
AUTH_FAILURE_MESSAGE = (
"WhatsApp Agent API token was rejected. Regenerate it in WhatsApp → "
"Settings → Agents → the agent's chat → Chat info → API key, then update "
"channels.whatsapp_agent.token."
)
# Placeholders for media-only messages, matching other nanobot channels.
_MEDIA_PLACEHOLDERS = {
"image": "[image]",
"video": "[video]",
"sticker": "[sticker]",
"audio": "[voice note]",
"document": "[document]",
}
class WhatsAppAgentConfig(Base):
"""WhatsApp Agent Platform channel configuration."""
enabled: bool = False
token: str = ""
allow_from: list[str] = Field(default_factory=list)
state_dir: str = ""
poll_timeout: int = Field(default=25, ge=0, le=25)
mark_read: bool = True
typing_indicator: bool = True
download_media: bool = True
delete_media_after_download: bool = False
max_media_mb: int = Field(default=16, ge=1, le=16)
retry_ambiguous_sends: bool = False
# Progress/tool-hint chatter spends the 12 sends/minute budget, so it stays
# off unless an operator opts in.
send_progress: bool = False
send_tool_hints: bool = False
class _RollingWindowLimiter:
"""Pace requests per method over a rolling 60-second window.
The API counts each method separately, so a burst of sends cannot borrow
budget from the poll counter. Waiting here keeps the channel under the cap
without depending on the server to reject it.
"""
def __init__(self, limits: dict[str, int], margin: int) -> None:
self._limits = {
method: max(limit - margin, 1) for method, limit in limits.items()
}
self._events: dict[str, deque[float]] = {}
async def acquire(self, method: str) -> None:
limit = self._limits.get(method, 1)
while True:
now = time.monotonic()
events = self._events.setdefault(method, deque())
while events and now - events[0] >= _RATE_WINDOW_SECONDS:
events.popleft()
if len(events) < limit:
events.append(now)
return
await asyncio.sleep(_RATE_WINDOW_SECONDS - (now - events[0]) + 0.05)
class WhatsAppAgentChannel(BaseChannel):
"""WhatsApp Agent Platform channel using the official agent API."""
name = "whatsapp_agent"
display_name = "WhatsApp Agent Platform"
@classmethod
def default_config(cls) -> dict[str, Any]:
return WhatsAppAgentConfig().model_dump(by_alias=True)
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WhatsAppAgentConfig.model_validate(config)
super().__init__(config, bus)
self._client: httpx.AsyncClient | None = None
self._limiter = _RollingWindowLimiter(RATE_LIMITS, _RATE_LIMIT_MARGIN)
self._state = WhatsAppAgentState()
self._typing_task: asyncio.Task[None] | None = None
# ------------------------------------------------------------------
# Transport helpers
# ------------------------------------------------------------------
def progress_transport_defaults(self) -> tuple[bool, bool]:
"""Keep progress traffic opt-in; each hint spends the send budget."""
return self.config.send_progress, self.config.send_tool_hints
def should_retry_send_error(self, error: Exception) -> bool:
"""Return whether the channel manager may retry a failed delivery.
A retry is only safe when the first attempt provably did not deliver:
rate limits and ``503``/``131016`` are confirmed non-delivery. A ``500``
or a read timeout leaves the outcome unknown, so it is not retried
unless the operator explicitly accepts possible duplicates.
"""
if isinstance(error, WhatsAppAgentAuthError):
return False
if isinstance(error, WhatsAppAgentAPIError):
api_error = error.error
if api_error.retryable:
return True
if api_error.ambiguous:
return bool(self.config.retry_ambiguous_sends)
# Any other 4xx fails identically until the request or token changes.
return False
if isinstance(error, (httpx.ConnectError, httpx.ConnectTimeout)):
# The request never reached the API, so resending cannot duplicate.
return True
if isinstance(error, httpx.HTTPError):
# Read timeout or protocol failure after the request was written.
return bool(self.config.retry_ambiguous_sends)
return True
def start_error_message(self, error: Exception) -> str | None:
if isinstance(error, WhatsAppAgentAuthError):
return AUTH_FAILURE_MESSAGE
return None
def _new_http_client(self) -> httpx.AsyncClient:
"""Create the client shared by polling, statuses, and media calls.
The read timeout is deliberately well above the long-poll window so an
ordinary send delay never turns into an unresolved delivery state.
"""
read_timeout = max(self.config.poll_timeout + 15.0, 40.0)
return httpx.AsyncClient(
timeout=httpx.Timeout(read_timeout, connect=15.0),
follow_redirects=False,
trust_env=False,
headers={"User-Agent": USER_AGENT},
)
def _auth_headers(self) -> dict[str, str]:
return {"Authorization": f"Bearer {self.config.token}"}
async def _request(
self,
method: str,
path: str,
*,
method_key: str,
params: dict[str, Any] | None = None,
json_body: dict[str, Any] | None = None,
files: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
) -> tuple[int, Any]:
"""Perform one paced API request and decode a JSON body when present."""
client = self._client
if client is None:
raise RuntimeError("WhatsApp Agent Platform channel is not connected")
await self._limiter.acquire(method_key)
response = await client.request(
method,
f"{API_BASE}{path}",
params=params,
json=json_body,
files=files,
data=data,
headers=self._auth_headers(),
)
if response.status_code == 204:
return 204, None
payload: Any = None
if response.content:
with suppress(ValueError):
payload = response.json()
return response.status_code, payload
async def _request_ok(
self,
method: str,
path: str,
*,
method_key: str,
params: dict[str, Any] | None = None,
json_body: dict[str, Any] | None = None,
files: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
) -> Any:
"""Perform a request that must succeed, raising a classified error."""
status_code, payload = await self._request(
method,
path,
method_key=method_key,
params=params,
json_body=json_body,
files=files,
data=data,
)
if 200 <= status_code < 300:
return payload
error = classify_error(status_code, payload)
if error.invalid_token:
raise WhatsAppAgentAuthError(str(error))
raise WhatsAppAgentAPIError(error)
# ------------------------------------------------------------------
# Durable state
# ------------------------------------------------------------------
def _state_path(self) -> Path:
configured = self.config.state_dir.strip()
base = Path(configured).expanduser() if configured else default_state_dir()
return base / "state.json"
def _load_state(self) -> None:
"""Load the cursor, resetting it when the token identifies a new agent."""
path = self._state_path()
self._state = WhatsAppAgentState.load(path)
if self._state.reset_for_token(self.config.token):
self.logger.info("WhatsApp Agent token changed; restarting the poll cursor")
def _persist(self) -> None:
"""Persist the cursor before it is trusted.
A lost cursor replays a batch (deduplicated by wamid); a cursor written
before the batch is handled would drop messages. The write is therefore
ordered after each message is recorded and fsynced by ``state.save``.
"""
try:
self._state.save(self._state_path())
except OSError:
self.logger.exception("Failed to persist WhatsApp Agent poll state")
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
async def start(self) -> None:
if not self.config.token.strip():
raise WhatsAppAgentAuthError(
"WhatsApp Agent Platform requires a token. Create an agent in "
"WhatsApp → Settings → Agents, then copy its API key."
)
self._load_state()
self._client = self._new_http_client()
self._running = True
backoff = 1.0
loop = asyncio.get_running_loop()
self.logger.info(
"Starting WhatsApp Agent Platform channel (long-poll, timeout={}s)",
self.config.poll_timeout,
)
try:
last_poll = 0.0
while self._running:
gap = loop.time() - last_poll
if gap < _MIN_POLL_GAP_SECONDS:
await asyncio.sleep(_MIN_POLL_GAP_SECONDS - gap)
last_poll = loop.time()
try:
batch = await self._poll_once()
backoff = 1.0
if batch is not None:
await self._process_batch(batch)
except asyncio.CancelledError:
raise
except WhatsAppAgentAuthError:
# An invalid token cannot recover by retrying; surface it.
self._running = False
raise
except WhatsAppAgentAPIError as exc:
backoff, last_poll = await self._handle_api_error(
exc.error, backoff, last_poll
)
except httpx.HTTPError as exc:
self.logger.warning("WhatsApp Agent poll transport error: {}", exc)
await asyncio.sleep(backoff)
backoff = min(backoff * 2, _BACKOFF_MAX_SECONDS)
except asyncio.CancelledError:
raise
finally:
self._running = False
await self._stop_typing()
await self._close_client()
async def _handle_api_error(
self,
error: APIError,
backoff: float,
last_poll: float,
) -> tuple[float, float]:
"""Apply the documented recovery for a failed poll."""
if error.poll_replaced:
self.logger.error(
"Another poller replaced this WhatsApp Agent poll (409). "
"Run a single gateway instance per agent token. {}",
error,
)
await asyncio.sleep(_POLL_REPLACED_SLEEP_SECONDS)
return backoff, last_poll
if error.rate_limited or error.status_code >= 500:
self.logger.warning("WhatsApp Agent poll failed; backing off: {}", error)
await asyncio.sleep(backoff)
return min(backoff * 2, _BACKOFF_MAX_SECONDS), last_poll
self.logger.error("WhatsApp Agent poll rejected: {}", error)
await asyncio.sleep(_BAD_REQUEST_SLEEP_SECONDS)
return backoff, last_poll
async def stop(self) -> None:
self._running = False
await self._stop_typing()
await self._close_client()
self._persist()
async def _close_client(self) -> None:
client = self._client
self._client = None
if client is not None:
await client.aclose()
# ------------------------------------------------------------------
# Polling
# ------------------------------------------------------------------
async def _poll_once(self) -> PollBatch | None:
"""Run one long poll. Returns None when the timeout elapsed empty."""
params: dict[str, Any] = {
"limit": _DEFAULT_POLL_LIMIT,
"timeout": self.config.poll_timeout,
}
if self._state.initialized and self._state.offset is not None:
# next_offset is a signed 64-bit integer passed back unchanged.
params["offset"] = self._state.offset
status_code, payload = await self._request(
"GET", "/updates", method_key="updates", params=params
)
if status_code == 204:
# No body and no next_offset: the next poll reuses the same cursor.
return None
if status_code != 200:
error = classify_error(status_code, payload)
if error.invalid_token:
raise WhatsAppAgentAuthError(str(error))
raise WhatsAppAgentAPIError(error)
return parse_poll_batch(payload)
async def _process_batch(self, batch: PollBatch) -> None:
"""Handle one batch in order, persisting progress as it goes."""
for receipt in batch.statuses:
self._state.note_status(receipt.wamid, receipt.status)
for message in batch.messages:
if self._state.has_message(message.wamid):
continue
# Record before handling: a crash after this point re-reads the
# batch but never answers the same message twice.
self._state.note_message(message.wamid)
self._persist()
try:
await self._dispatch(message)
except asyncio.CancelledError:
raise
except Exception:
self.logger.exception(
"Failed to handle WhatsApp Agent message {}", message.wamid
)
if batch.next_offset is not None:
self._state.accept_offset(batch.next_offset)
self._persist()
# ------------------------------------------------------------------
# Inbound handling
# ------------------------------------------------------------------
async def _dispatch(self, message: PlatformMessage) -> None:
"""Route one inbound message into the agent pipeline."""
if message.kind == "reaction":
# Reactions are receive-only on this platform and carry no reply.
self.logger.debug(
"Ignoring reaction from {} to {}", message.sender, message.reaction_to
)
return
if not message.is_user_authored:
# A quoted agent message or an echo of our own send.
return
if message.kind == "unknown":
self.logger.warning("Ignoring unsupported WhatsApp Agent message type")
return
# Prefer the freshest inbound identifier: it is the only value the API
# accepts in ``to``, and it may change if the creator re-registers.
self._state.note_creator(message.sender)
if self.config.mark_read or self.config.typing_indicator:
await self._acknowledge(message.wamid)
media_paths, content = await self._materialize(message)
await self._handle_message(
sender_id=message.sender,
chat_id=CREATOR_CHAT_ID,
content=content,
media=media_paths,
metadata={
"message_id": message.wamid,
"origin_message_id": message.wamid,
"wa_id": message.sender,
},
is_dm=True,
)
async def _acknowledge(self, wamid: str) -> None:
"""Mark read and start the typing indicator, best effort."""
body: dict[str, Any] = {
"messaging_product": "whatsapp",
"status": "read",
"message_id": wamid,
}
if self.config.typing_indicator:
# ``type`` is required inside the object and only accepts "text".
body["typing_indicator"] = {"type": "text"}
try:
await self._request_ok(
"POST", "/statuses", method_key="statuses", json_body=body
)
except WhatsAppAgentAuthError:
raise
except Exception as exc:
# A read receipt is an affordance, never a processing gate.
self.logger.debug("Read/typing receipt failed for {}: {}", wamid, exc)
return
if self.config.typing_indicator:
self._start_typing(wamid)
def _start_typing(self, wamid: str) -> None:
"""Refresh the typing indicator while the turn is running."""
self._cancel_typing_task()
async def _refresh() -> None:
try:
while True:
await asyncio.sleep(_TYPING_REFRESH_SECONDS)
await self._request(
"POST",
"/statuses",
method_key="statuses",
json_body={
"messaging_product": "whatsapp",
"status": "read",
"message_id": wamid,
"typing_indicator": {"type": "text"},
},
)
except asyncio.CancelledError:
raise
except Exception as exc:
self.logger.debug("Typing refresh stopped for {}: {}", wamid, exc)
self._typing_task = asyncio.create_task(_refresh(), name="whatsapp-agent-typing")
def _cancel_typing_task(self) -> None:
task = self._typing_task
self._typing_task = None
if task is not None and not task.done():
task.cancel()
async def _stop_typing(self) -> None:
task = self._typing_task
self._typing_task = None
if task is None or task.done():
return
task.cancel()
with suppress(asyncio.CancelledError):
await task
async def _materialize(self, message: PlatformMessage) -> tuple[list[str], str]:
"""Download attached media and build the agent-visible content."""
caption = message.text or (message.media.caption if message.media else "")
if message.media is None or not self.config.download_media:
return [], caption
path = await self._download_media(message)
if path is None:
placeholder = _MEDIA_PLACEHOLDERS.get(message.kind, "[attachment]")
return [], caption or placeholder
if message.kind == "audio" and message.media.voice:
# Voice notes are transcribed when a provider is configured; the
# file stays attached so the agent can still inspect it.
transcription = (await self.transcribe_audio(path)).strip()
if transcription:
return [str(path)], transcription
return [str(path)], caption or "[voice note]"
content = caption
if not content:
label = _MEDIA_PLACEHOLDERS.get(message.kind, "[attachment]")
if message.media.filename:
content = f"{label} {message.media.filename}"
else:
content = label
return [str(path)], content
# ------------------------------------------------------------------
# Media download
# ------------------------------------------------------------------
async def _download_media(self, message: PlatformMessage) -> Path | None:
"""Fetch inbound media bytes and store them under the media directory."""
media = message.media
if media is None:
return None
limit = min(
media_limit_for(media.mime_type, message.kind),
self.config.max_media_mb * 1024 * 1024,
)
try:
metadata = await self._request_ok(
"GET", f"/media/{media.media_id}", method_key="media"
)
except WhatsAppAgentAuthError:
raise
except Exception as exc:
self.logger.warning(
"Could not fetch metadata for media {}: {}", media.media_id, exc
)
return None
metadata_map = cast(dict[str, Any], metadata) if isinstance(metadata, dict) else {}
url = str(metadata_map.get("url") or "")
safe, reason = quote_safe_url(url)
if not safe:
self.logger.error("Refusing unsafe WhatsApp Agent media URL: {}", reason)
return None
try:
content = await self._fetch_media_bytes(url, limit)
except Exception as exc:
self.logger.warning("Media download failed for {}: {}", media.media_id, exc)
return None
if not self._digest_matches(media, content):
self.logger.error(
"Discarding WhatsApp Agent media {}: sha256 mismatch", media.media_id
)
return None
path = self._media_target(message)
try:
path.write_bytes(content)
except OSError:
self.logger.exception("Failed to store WhatsApp Agent media")
return None
if self.config.delete_media_after_download:
with suppress(Exception):
await self._request(
"DELETE", f"/media/{media.media_id}", method_key="media"
)
return path
async def _fetch_media_bytes(self, url: str, limit: int) -> bytes:
"""Download media bytes with the bearer token and a hard size cap."""
client = self._client
if client is None:
raise RuntimeError("WhatsApp Agent Platform channel is not connected")
await self._limiter.acquire("media")
async with client.stream(
"GET", url, headers=self._auth_headers(), follow_redirects=False
) as response:
response.raise_for_status()
declared = response.headers.get("content-length")
if declared and declared.isdigit() and int(declared) > limit:
raise ValueError(f"declared media size exceeds the {limit}-byte limit")
chunks: list[bytes] = []
total = 0
async for chunk in response.aiter_bytes():
total += len(chunk)
if total > limit:
raise ValueError(f"media exceeds the {limit}-byte limit")
chunks.append(chunk)
return b"".join(chunks)
@staticmethod
def _digest_matches(media: InboundMedia, content: bytes) -> bool:
"""Verify the platform digest, which is Base64 inbound and hex in metadata."""
if not media.sha256_base64:
return True
import base64
try:
# Inbound payloads carry the digest Base64-encoded; the media
# metadata endpoint returns the same digest as hex.
expected = base64.b64decode(media.sha256_base64, validate=True)
except Exception:
try:
expected = bytes.fromhex(media.sha256_base64)
except ValueError:
return True
return hashlib.sha256(content).digest() == expected
def _media_target(self, message: PlatformMessage) -> Path:
from nanobot.config.paths import get_media_dir
media = message.media
assert media is not None
suffix = Path(media.filename).suffix if media.filename else ""
if not suffix:
suffix = mimetypes.guess_extension(media.mime_type or "") or ".bin"
name = safe_filename(Path(media.filename).stem) if media.filename else message.wamid
digest = hashlib.sha256(message.wamid.encode("utf-8")).hexdigest()[:12]
return get_media_dir(self.name) / f"{name}-{digest}{suffix}"
# ------------------------------------------------------------------
# Outbound
# ------------------------------------------------------------------
def _recipient(self) -> str:
"""Return the creator identifier the API accepts in ``to``."""
if self._state.creator_id:
return self._state.creator_id
return ""
async def send(self, msg: OutboundMessage) -> None:
"""Deliver one outbound message, chunked to the API text limit."""
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
if isinstance(msg.event, ProgressEvent):
# Progress is disabled by default; never spend send budget on it.
return
to = self._recipient()
if not to:
raise WhatsAppAgentAPIError(
APIError(
status_code=0,
code=0,
message="No creator identifier is known yet; wait for an inbound message.",
details="",
fbtrace_id="",
)
)
# The reply implicitly clears the typing indicator.
await self._stop_typing()
quote = msg.metadata.get("message_id") or msg.metadata.get("origin_message_id")
reply_to = quote if isinstance(quote, str) and quote else None
chunks = split_message(msg.content, TEXT_MAX_CHARS)
for index, chunk in enumerate(chunks):
await self._send_text(to, chunk, reply_to if index == 0 else None)
for media_path in msg.media or []:
await self._send_media(to, media_path)
async def _send_text(self, to: str, body: str, reply_to: str | None) -> None:
payload: dict[str, Any] = {
"messaging_product": "whatsapp",
"to": to,
"type": "text",
"text": {"body": body},
}
if reply_to:
# Inbound quotes use ``id``; outbound quoting uses ``message_id``.
payload["context"] = {"message_id": reply_to}
response = await self._request_ok(
"POST", "/messages", method_key="messages", json_body=payload
)
self._remember_sent(response)
def _remember_sent(self, response: Any) -> None:
"""Record the outbound wamid that later receipts refer to."""
if not isinstance(response, dict):
return
body = cast(dict[str, Any], response)
raw_messages = body.get("messages")
if not isinstance(raw_messages, list) or not raw_messages:
return
first = cast(list[object], raw_messages)[0]
if not isinstance(first, dict):
return
wamid = str(cast(dict[str, Any], first).get("id") or "")
if wamid:
self._state.note_status(wamid, "sent")
async def _send_media(self, to: str, media_path: str) -> None:
"""Upload a local file and send it as the matching message type."""
path = Path(media_path).expanduser()
if not path.is_file():
self.logger.warning("Skipping missing WhatsApp Agent media: {}", media_path)
return
size = path.stat().st_size
mime_type = self._detect_mime(path)
kind = outbound_kind_for_mime(mime_type)
limit = media_limit_for(mime_type, kind)
if size > limit:
self.logger.error(
"Skipping {} ({} bytes) for {}: exceeds the {}-byte limit",
path.name,
size,
kind,
limit,
)
return
if mime_type not in ACCEPTED_UPLOAD_MIME:
# The generic binary type is accepted for any file up to 16 MB.
mime_type = "application/octet-stream"
media_id = await self._upload_media(path, mime_type)
if kind == "sticker":
# Stickers reject captions and extra payload objects.
media_object: dict[str, Any] = {"id": media_id}
elif kind == "document":
media_object = {"id": media_id, "filename": path.name}
elif kind == "audio":
media_object = {"id": media_id}
else:
media_object = {"id": media_id}
payload = {
"messaging_product": "whatsapp",
"to": to,
"type": kind,
# Only the object matching ``type`` is sent, but the others are
# still validated, so no extra payload objects are included.
kind: media_object,
}
response = await self._request_ok(
"POST", "/messages", method_key="messages", json_body=payload
)
self._remember_sent(response)
async def _upload_media(self, path: Path, mime_type: str) -> str:
with path.open("rb") as handle:
payload = await self._request_ok(
"POST",
"/media",
method_key="media",
data={"messaging_product": "whatsapp", "type": mime_type},
files={"file": (path.name, handle, mime_type)},
)
payload_map = cast(dict[str, Any], payload) if isinstance(payload, dict) else {}
media_id = str(payload_map.get("id") or "")
if not media_id:
raise WhatsAppAgentAPIError(
APIError(
status_code=0,
code=0,
message="Media upload returned no id",
details="",
fbtrace_id="",
)
)
return media_id
@staticmethod
def _detect_mime(path: Path) -> str:
guessed, _ = mimetypes.guess_type(path.name)
return normalize_mime(guessed or "application/octet-stream")
__all__ = [
"AUTH_FAILURE_MESSAGE",
"CREATOR_CHAT_ID",
"WhatsAppAgentChannel",
"WhatsAppAgentConfig",
"token_fingerprint",
]
+203
View File
@@ -0,0 +1,203 @@
"""Durable poll cursor and dedup state for the WhatsApp Agent Platform channel.
The Agent Platform long-poll contract has three properties that force an
explicit, crash-safe store on the channel side:
* ``next_offset`` must be stored as a 64-bit signed integer and replayed
unchanged; the server never accepts a client-computed cursor.
* Polling does not consume updates, so a re-read replays the same messages
until the retention window (30 days) expires.
* Marking a message read may delete it server-side, so a message must be
recorded before its receipt is acknowledged.
The store keeps the cursor, the recently handled wamids, and accumulated
contact display names in one atomically replaced JSON file.
"""
from __future__ import annotations
import hashlib
import json
from collections import OrderedDict
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, cast
from nanobot.utils.helpers import atomic_write_lines
# Dedup window. One creator talks to the agent, so a few hundred ids cover any
# realistic replay after a reconnect or a failed batch.
_SEEN_MAX = 2000
def token_fingerprint(token: str) -> str:
"""Return an opaque, non-reversible identifier for a token value."""
return hashlib.sha256(token.encode("utf-8")).hexdigest() if token else ""
def local_state_present(section: Any) -> bool:
"""Return whether the channel already has a durable poll cursor on disk."""
from nanobot.channels.contracts import channel_field_value
configured_dir = channel_field_value(section, "stateDir")
state_dir = (
Path(str(configured_dir)).expanduser()
if configured_dir
else default_state_dir()
)
try:
decoded = json.loads((state_dir / "state.json").read_text(encoding="utf-8"))
except (OSError, ValueError, TypeError):
return False
payload = _json_object(decoded)
if payload is None:
return False
return bool(str(payload.get("token_fingerprint") or "").strip())
def default_state_dir() -> Path:
"""Return the default runtime directory owned by this channel."""
from nanobot.config.paths import get_runtime_subdir
return get_runtime_subdir("whatsapp-agent")
@dataclass
class WhatsAppAgentState:
"""Crash-safe cursor, dedup window, and contact-name cache."""
offset: int | None = None
initialized: bool = False
token_fingerprint: str = ""
# Most recent inbound identifier, kept so a restart can reply before the
# next message arrives. The API only accepts this value in ``to``.
creator_id: str = ""
# Ordered oldest-first so trimming drops the least recently seen wamid.
seen: OrderedDict[str, None] = field(default_factory=OrderedDict)
last_status: dict[str, str] = field(default_factory=dict)
@classmethod
def load(cls, path: Path) -> WhatsAppAgentState:
"""Load persisted state, returning a fresh store when unreadable."""
try:
decoded = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError, TypeError):
return cls()
payload = _json_object(decoded)
if payload is None:
return cls()
raw_seen = payload.get("seen")
seen_items = cast(list[object], raw_seen) if isinstance(raw_seen, list) else []
seen_entries = [
str(item) for item in seen_items if isinstance(item, str | int)
]
statuses = _string_map(payload.get("last_status"))
return cls(
offset=_optional_int(payload.get("offset")),
initialized=bool(payload.get("initialized")),
token_fingerprint=str(payload.get("token_fingerprint") or ""),
creator_id=str(payload.get("creator_id") or ""),
seen=OrderedDict.fromkeys(seen_entries[-_SEEN_MAX:]),
last_status=statuses,
)
def save(self, path: Path) -> None:
"""Atomically replace the persisted snapshot."""
payload = {
"offset": self.offset,
"initialized": self.initialized,
"token_fingerprint": self.token_fingerprint,
"creator_id": self.creator_id,
"seen": list(self.seen),
"last_status": self.last_status,
}
path.parent.mkdir(parents=True, exist_ok=True)
# fsync keeps the cursor durable across a crash: a lost cursor means a
# replayed batch, and a cursor written before the batch is committed
# would drop messages.
atomic_write_lines(path, [json.dumps(payload, ensure_ascii=False)])
def reset_for_token(self, token: str) -> bool:
"""Discard cursor state when the configured token identifies a new agent.
``next_offset`` is only meaningful for the agent that issued it, so a
rotated or replaced token starts a fresh stream. Returns True when the
caller must re-resolve the head on the next poll.
"""
fingerprint = token_fingerprint(token)
if fingerprint and fingerprint == self.token_fingerprint:
return False
self.offset = None
self.initialized = False
self.creator_id = ""
self.seen.clear()
self.last_status.clear()
self.token_fingerprint = fingerprint
return True
def note_creator(self, sender: str) -> None:
"""Remember the creator identifier from the freshest inbound message."""
if sender:
self.creator_id = sender
def accept_offset(self, next_offset: int) -> None:
"""Store the server cursor exactly as issued."""
self.offset = next_offset
self.initialized = True
def note_message(self, wamid: str) -> None:
"""Record a handled wamid so a replayed batch does not repeat it."""
if not wamid:
return
self.seen[wamid] = None
self.seen.move_to_end(wamid)
while len(self.seen) > _SEEN_MAX:
self.seen.popitem(last=False)
def has_message(self, wamid: str) -> bool:
return bool(wamid) and wamid in self.seen
def note_status(self, wamid: str, status: str) -> None:
"""Remember the latest delivery receipt for an outbound message."""
if not wamid or not status:
return
self.last_status[wamid] = status
while len(self.last_status) > _SEEN_MAX:
self.last_status.pop(next(iter(self.last_status)))
def _json_object(value: object) -> dict[str, Any] | None:
"""Narrow decoded JSON to a string-keyed object."""
if not isinstance(value, dict):
return None
return cast(dict[str, Any], value)
def _string_map(value: object) -> dict[str, str]:
"""Narrow a persisted JSON value to a flat string map."""
if not isinstance(value, dict):
return {}
mapping = cast(dict[object, object], value)
return {
str(key): str(item)
for key, item in mapping.items()
if item is not None and not isinstance(item, bool)
}
def _optional_int(value: object) -> int | None:
if value is None or isinstance(value, bool):
return None
try:
return int(str(value))
except (TypeError, ValueError):
return None
__all__ = [
"WhatsAppAgentState",
"default_state_dir",
"local_state_present",
"token_fingerprint",
]
@@ -0,0 +1 @@
"""Package marker for WhatsApp Agent Platform tests."""
@@ -0,0 +1,269 @@
"""Wire parsing and error-classification contracts for the Agent Platform.
These tests pin the documented protocol facts that the runtime depends on but
cannot verify against the live API in CI.
"""
from __future__ import annotations
import pytest
from nanobot.channels.whatsapp_agent.protocol import (
classify_error,
media_limit_for,
normalize_mime,
outbound_kind_for_mime,
parse_message,
parse_poll_batch,
parse_status,
quote_safe_url,
)
def _poll_body(messages=None, statuses=None, next_offset=1287):
return {
"object": "whatsapp_agent_platform",
"entry": [
{
"id": "123456789",
"changes": [
{
"field": "messages",
"value": {
"messaging_product": "whatsapp",
"contacts": [{"wa_id": "user:55", "profile": {"name": "Alex"}}],
"messages": messages or [],
"statuses": statuses or [],
},
}
],
}
],
"next_offset": next_offset,
}
def test_parses_text_message_with_quote_context():
batch = parse_poll_batch(
_poll_body(
messages=[
{
"from": "user:55",
"id": "wamid.1",
"timestamp": "1736844652",
"type": "text",
"text": {"body": "Hello agent"},
"context": {"id": "wamid.q", "from": "agent:9"},
}
]
)
)
assert batch.next_offset == 1287
message = batch.messages[0]
assert message.wamid == "wamid.1"
assert message.sender == "user:55"
assert message.timestamp == 1736844652
assert message.text == "Hello agent"
# Inbound quoting names the field ``id``; outbound uses ``message_id``.
assert message.context_id == "wamid.q"
assert message.context_from == "agent:9"
assert message.is_user_authored is True
@pytest.mark.parametrize(
("kind", "payload", "attribute"),
[
("image", {"id": "m1", "mime_type": "image/jpeg", "caption": "look"}, "caption"),
("video", {"id": "m2", "mime_type": "video/mp4"}, None),
("document", {"id": "m3", "mime_type": "application/pdf", "filename": "r.pdf"}, "filename"),
("sticker", {"id": "m4", "mime_type": "image/webp", "animated": False}, None),
],
)
def test_parses_media_kinds(kind, payload, attribute):
message = parse_message(
{"from": "user:55", "id": "w", "timestamp": "1", "type": kind, kind: payload}
)
assert message is not None
assert message.kind == kind
assert message.media is not None
assert message.media.media_id == payload["id"]
if attribute:
assert getattr(message.media, attribute) == payload[attribute]
def test_voice_key_marks_only_audio_notes():
voice_note = parse_message(
{
"from": "user:55",
"id": "w1",
"timestamp": "1",
"type": "audio",
"audio": {"id": "m1", "mime_type": "audio/ogg", "voice": True},
}
)
audio_file = parse_message(
{
"from": "user:55",
"id": "w2",
"timestamp": "1",
"type": "audio",
"audio": {"id": "m2", "mime_type": "audio/mpeg"},
}
)
assert voice_note is not None and voice_note.media is not None
assert voice_note.media.voice is True
assert audio_file is not None and audio_file.media is not None
assert audio_file.media.voice is False
def test_empty_reaction_emoji_means_removed():
message = parse_message(
{
"from": "user:55",
"id": "w1",
"timestamp": "1",
"type": "reaction",
"reaction": {"message_id": "wamid.x", "emoji": ""},
}
)
assert message is not None
assert message.kind == "reaction"
assert message.reaction_to == "wamid.x"
assert message.reaction_emoji == ""
def test_poll_can_return_statuses_without_messages():
batch = parse_poll_batch(
_poll_body(
statuses=[
{
"id": "wamid.s",
"status": "delivered",
"recipient_id": "user:55",
"timestamp": "1736844655",
}
]
)
)
assert batch.messages == []
assert [status.status for status in batch.statuses] == ["delivered"]
assert batch.next_offset == 1287
def test_missing_profile_name_is_not_treated_as_empty_string():
body = _poll_body()
body["entry"][0]["changes"][0]["value"]["contacts"] = [{"wa_id": "user:55"}]
# The absent ``profile`` key must not raise; names are optional per poll.
assert parse_poll_batch(body).messages == []
def test_next_offset_beyond_float_precision_is_preserved():
offset = 9007199254740993
assert parse_poll_batch(_poll_body(next_offset=offset)).next_offset == offset
def test_malformed_payloads_degrade_to_empty_batch():
assert parse_poll_batch(None).messages == []
assert parse_poll_batch({"entry": "nope"}).next_offset is None
assert parse_message({"type": "text"}) is None
assert parse_status({"id": "w", "status": "unknown"}) is None
@pytest.mark.parametrize(
("mime_type", "expected"),
[
("audio/ogg; codecs=opus", "audio/ogg"),
("audio/x-m4a", "audio/mp4"),
("IMAGE/JPEG", "image/jpeg"),
],
)
def test_mime_normalization(mime_type, expected):
assert normalize_mime(mime_type) == expected
@pytest.mark.parametrize(
("mime_type", "kind"),
[
("image/jpeg", "image"),
("image/webp", "sticker"),
("video/mp4", "video"),
("audio/ogg", "audio"),
("application/pdf", "document"),
("application/octet-stream", "document"),
],
)
def test_outbound_kind_mapping(mime_type, kind):
assert outbound_kind_for_mime(mime_type) == kind
def test_media_limits_match_the_documented_caps():
assert media_limit_for("image/jpeg", "image") == 5 * 1024 * 1024
assert media_limit_for("image/webp", "sticker") == 500 * 1024
assert media_limit_for("video/mp4", "video") == 16 * 1024 * 1024
# An undeclared type still receives the generic 16 MB cap.
assert media_limit_for("audio/ogg", "unknown") == 16 * 1024 * 1024
def test_media_url_must_pass_the_ssrf_guard():
# A malformed or internal target must be refused before any request is made.
assert quote_safe_url("http://127.0.0.1/media")[0] is False
assert quote_safe_url("file:///etc/passwd")[0] is False
assert quote_safe_url("")[0] is False
assert quote_safe_url("https://lookaside.fbsbx.com/x")[0] is True
def test_missing_authorization_header_is_auth_failure():
error = classify_error(401, {"error": {"code": 190}})
assert error.invalid_token is True
def test_invalid_token_uses_400_not_401():
error = classify_error(400, {"error": {"code": 100, "message": "(#100) Invalid token"}})
assert error.invalid_token is True
def test_length_rejection_on_400_is_not_an_auth_failure():
# 400/100 is shared between an invalid token and an over-length field; the
# over-length case sets ``message`` to the bare field name.
error = classify_error(400, {"error": {"code": 100, "message": "text.body"}})
assert error.invalid_token is False
def test_only_confirmed_non_delivery_is_retryable():
assert classify_error(429, {"error": {"code": 130429}}).retryable is True
assert classify_error(503, {"error": {"code": 131016}}).retryable is True
# A 500 may have been delivered, so it is ambiguous rather than retryable.
ambiguous = classify_error(500, {"error": {"code": 2}})
assert ambiguous.retryable is False
assert ambiguous.ambiguous is True
# A plain 4xx fails identically until the request changes.
fatal = classify_error(400, {"error": {"code": 131009}})
assert fatal.retryable is False
assert fatal.ambiguous is False
def test_duplicate_poller_is_reported_as_poll_replaced():
error = classify_error(409, {"error": {"code": 1752041}})
assert error.poll_replaced is True
assert error.retryable is False
def test_error_string_carries_code_and_trace_id():
error = classify_error(
500,
{"error": {"code": 2, "message": "oops", "fbtrace_id": "AW7bqWj4"}},
)
text = str(error)
assert "code=2" in text
assert "fbtrace_id=AW7bqWj4" in text
@@ -0,0 +1,706 @@
"""Runtime contracts for the WhatsApp Agent Platform channel.
These exercise the paths that protect real invariants: ordered chunked sends,
cursor durability, dedup across a replayed batch, pacing, and retry safety.
"""
from __future__ import annotations
import asyncio
import base64
import hashlib
import json
from pathlib import Path
from typing import Any
import httpx
import pytest
from loguru import logger
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.whatsapp_agent import runtime as runtime_module
from nanobot.channels.whatsapp_agent.protocol import (
APIError,
WhatsAppAgentAPIError,
WhatsAppAgentAuthError,
)
from nanobot.channels.whatsapp_agent.runtime import (
CREATOR_CHAT_ID,
WhatsAppAgentChannel,
WhatsAppAgentConfig,
)
class _Bus(MessageBus):
def __init__(self) -> None:
super().__init__()
self.inbound_messages: list[Any] = []
async def publish_inbound(self, msg: Any) -> None:
self.inbound_messages.append(msg)
def _channel(tmp_path: Path, **overrides: Any) -> WhatsAppAgentChannel:
config = WhatsAppAgentConfig(
enabled=True,
token=overrides.pop("token", "test-token"),
allow_from=["*"],
state_dir=str(tmp_path),
**overrides,
)
return WhatsAppAgentChannel(config, _Bus())
def _poll_body(messages: list[dict[str, Any]], next_offset: int = 10) -> dict[str, Any]:
return {
"object": "whatsapp_agent_platform",
"entry": [
{
"id": "1",
"changes": [
{
"field": "messages",
"value": {
"messaging_product": "whatsapp",
"messages": messages,
"statuses": [],
},
}
],
}
],
"next_offset": next_offset,
}
def _text_message(wamid: str, body: str = "hi", sender: str = "user:55") -> dict[str, Any]:
return {
"from": sender,
"id": wamid,
"timestamp": "1736844652",
"type": "text",
"text": {"body": body},
}
def _json_response(status: int, payload: Any) -> httpx.Response:
return httpx.Response(status, json=payload)
# ----------------------------------------------------------------------
# Retry policy
# ----------------------------------------------------------------------
def test_confirmed_non_delivery_is_retried(tmp_path: Path):
channel = _channel(tmp_path)
assert channel.should_retry_send_error(
WhatsAppAgentAPIError(APIError(429, 130429, "", "", ""))
)
assert channel.should_retry_send_error(
WhatsAppAgentAPIError(APIError(503, 131016, "", "", ""))
)
def test_ambiguous_and_fatal_outcomes_are_not_retried_by_default(tmp_path: Path):
channel = _channel(tmp_path)
# A 500 may already have delivered; a duplicate annoys more than a loss.
assert channel.should_retry_send_error(
WhatsAppAgentAPIError(APIError(500, 2, "", "", ""))
) is False
# A plain 4xx fails identically until the request or token changes.
assert channel.should_retry_send_error(
WhatsAppAgentAPIError(APIError(400, 131009, "", "", ""))
) is False
assert channel.should_retry_send_error(WhatsAppAgentAuthError("bad token")) is False
def test_ambiguous_retry_can_be_opted_in(tmp_path: Path):
channel = _channel(tmp_path, retryAmbiguousSends=True)
assert channel.should_retry_send_error(
WhatsAppAgentAPIError(APIError(500, 2, "", "", ""))
) is True
def test_connection_failure_is_retried_because_nothing_was_written(tmp_path: Path):
channel = _channel(tmp_path)
assert channel.should_retry_send_error(httpx.ConnectError("refused")) is True
def test_progress_traffic_is_off_by_default(tmp_path: Path):
channel = _channel(tmp_path)
assert channel.progress_transport_defaults() == (False, False)
assert channel.config.send_progress is False
# ----------------------------------------------------------------------
# Polling and durable cursor
# ----------------------------------------------------------------------
def test_empty_204_reuses_the_same_offset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._load_state()
channel._state.accept_offset(77)
seen_params: list[dict[str, Any]] = []
async def fake_request(method, path, *, method_key, params=None, **kwargs):
seen_params.append(dict(params or {}))
return 204, None
monkeypatch.setattr(channel, "_request", fake_request)
channel._client = object() # type: ignore[assignment]
assert asyncio.run(channel._poll_once()) is None
assert seen_params[0]["offset"] == 77
def test_first_poll_omits_offset_to_skip_the_backlog(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._load_state()
seen_params: list[dict[str, Any]] = []
async def fake_request(method, path, *, method_key, params=None, **kwargs):
seen_params.append(dict(params or {}))
return 204, None
monkeypatch.setattr(channel, "_request", fake_request)
channel._client = object() # type: ignore[assignment]
asyncio.run(channel._poll_once())
# Omitting ``offset`` resolves the head, so a first run never replays
# up to 30 days of history into an auto-replying agent.
assert "offset" not in seen_params[0]
def test_batch_advances_and_persists_the_cursor(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._load_state()
dispatched: list[Any] = []
async def fake_dispatch(message):
dispatched.append(message)
monkeypatch.setattr(channel, "_dispatch", fake_dispatch)
channel._client = object() # type: ignore[assignment]
asyncio.run(channel._process_batch(_parse(_poll_body([_text_message("wamid.1")], 4242))))
assert [m.wamid for m in dispatched] == ["wamid.1"]
assert channel._state.offset == 4242
persisted = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
assert persisted["offset"] == 4242
def test_replayed_batch_does_not_dispatch_twice(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._load_state()
dispatched: list[Any] = []
async def fake_dispatch(message):
dispatched.append(message.wamid)
monkeypatch.setattr(channel, "_dispatch", fake_dispatch)
channel._client = object() # type: ignore[assignment]
batch = _parse(_poll_body([_text_message("wamid.1")], 5))
# Polling does not consume entries, so the same offset returns them again.
asyncio.run(channel._process_batch(batch))
channel._state.offset = 0
asyncio.run(channel._process_batch(batch))
assert dispatched == ["wamid.1"]
def test_failed_message_is_not_retried_as_a_duplicate_on_replay(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._load_state()
calls: list[str] = []
async def fake_dispatch(message):
calls.append(message.wamid)
raise RuntimeError("boom")
monkeypatch.setattr(channel, "_dispatch", fake_dispatch)
channel._client = object() # type: ignore[assignment]
batch = _parse(_poll_body([_text_message("wamid.1")], 1))
asyncio.run(channel._process_batch(batch))
asyncio.run(channel._process_batch(batch))
# The wamid is recorded before handling, so a crash cannot double-answer.
assert calls == ["wamid.1"]
def _parse(body: dict[str, Any]):
from nanobot.channels.whatsapp_agent.protocol import parse_poll_batch
return parse_poll_batch(body)
# ----------------------------------------------------------------------
# Inbound routing
# ----------------------------------------------------------------------
def test_inbound_text_reaches_the_bus_with_quote_metadata(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
bus = _Bus()
channel = WhatsAppAgentChannel(
WhatsAppAgentConfig(enabled=True, token="t", allow_from=["*"], state_dir=str(tmp_path)),
bus,
)
channel._load_state()
async def no_ack(wamid: str) -> None:
return None
monkeypatch.setattr(channel, "_acknowledge", no_ack)
asyncio.run(channel._dispatch(_message(_text_message("wamid.1", "hello"))))
assert len(bus.inbound_messages) == 1
inbound = bus.inbound_messages[0]
assert inbound.channel == "whatsapp_agent"
assert inbound.chat_id == CREATOR_CHAT_ID
assert inbound.content == "hello"
assert inbound.metadata["message_id"] == "wamid.1"
assert channel._state.creator_id == "user:55"
@pytest.mark.parametrize("kind", ["reaction", "unknown"])
def test_non_replyable_messages_are_not_forwarded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str):
bus = _Bus()
channel = WhatsAppAgentChannel(
WhatsAppAgentConfig(enabled=True, token="t", allow_from=["*"], state_dir=str(tmp_path)),
bus,
)
channel._load_state()
raw = {"from": "user:55", "id": "w1", "timestamp": "1", "type": kind}
if kind == "reaction":
raw["reaction"] = {"message_id": "x", "emoji": "👍"}
asyncio.run(channel._dispatch(_message(raw)))
assert bus.inbound_messages == []
def _message(raw: dict[str, Any]):
from nanobot.channels.whatsapp_agent.protocol import parse_message
parsed = parse_message(raw)
assert parsed is not None
return parsed
# ----------------------------------------------------------------------
# Outbound
# ----------------------------------------------------------------------
def test_text_is_chunked_to_the_api_limit_and_sent_in_order(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._state.note_creator("user:55")
sent: list[dict[str, Any]] = []
async def fake_request_ok(method, path, *, method_key, json_body=None, **kwargs):
sent.append(json_body)
return {"messages": [{"id": f"wamid.out{len(sent)}"}]}
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
body = "x" * 5000
asyncio.run(
channel.send(OutboundMessage(channel="whatsapp_agent", chat_id=CREATOR_CHAT_ID, content=body))
)
assert [len(chunk["text"]["body"]) for chunk in sent] == [4096, 904]
# No inbound message id was supplied, so no quote is attached.
assert all("context" not in chunk for chunk in sent)
assert all(chunk["to"] == "user:55" for chunk in sent)
def test_reply_quotes_the_originating_message_once(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._state.note_creator("user:55")
sent: list[dict[str, Any]] = []
async def fake_request_ok(method, path, *, method_key, json_body=None, **kwargs):
sent.append(json_body)
return {"messages": [{"id": "wamid.out"}]}
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
asyncio.run(
channel.send(
OutboundMessage(
channel="whatsapp_agent",
chat_id=CREATOR_CHAT_ID,
content="y" * 5000,
metadata={"message_id": "wamid.in"},
)
)
)
assert sent[0]["context"] == {"message_id": "wamid.in"}
assert "context" not in sent[1]
def test_send_without_a_known_creator_fails_loudly(tmp_path: Path):
channel = _channel(tmp_path)
with pytest.raises(WhatsAppAgentAPIError):
asyncio.run(
channel.send(OutboundMessage(channel="whatsapp_agent", chat_id=CREATOR_CHAT_ID, content="hi"))
)
def test_outbound_wamid_is_remembered_for_receipts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._state.note_creator("user:55")
async def fake_request_ok(method, path, *, method_key, json_body=None, **kwargs):
return {"messages": [{"id": "wamid.sent"}]}
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
asyncio.run(
channel.send(OutboundMessage(channel="whatsapp_agent", chat_id=CREATOR_CHAT_ID, content="hi"))
)
assert channel._state.last_status["wamid.sent"] == "sent"
def test_media_uses_the_matching_payload_object_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
channel._state.note_creator("user:55")
image = tmp_path / "chart.png"
image.write_bytes(b"\x89PNG\r\n\x1a\n" + b"0" * 32)
sent: list[dict[str, Any]] = []
async def fake_request_ok(method, path, *, method_key, json_body=None, data=None, files=None, **kwargs):
if path == "/media":
return {"id": "MEDIA1"}
sent.append(json_body)
return {"messages": [{"id": "wamid.out"}]}
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
asyncio.run(
channel.send(
OutboundMessage(
channel="whatsapp_agent",
chat_id=CREATOR_CHAT_ID,
content="",
media=[str(image)],
)
)
)
assert sent[0]["type"] == "image"
assert sent[0]["image"] == {"id": "MEDIA1"}
# Extra payload objects are validated by the API, so none are included.
assert set(sent[0]) == {"messaging_product", "to", "type", "image"}
def test_oversized_media_is_skipped_before_upload(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path, maxMediaMb=1)
channel._state.note_creator("user:55")
big = tmp_path / "big.png"
big.write_bytes(b"\x89PNG\r\n\x1a\n" + b"0" * (6 * 1024 * 1024))
calls: list[str] = []
async def fake_request_ok(method, path, *, method_key, **kwargs):
calls.append(path)
return {}
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
asyncio.run(
channel.send(
OutboundMessage(
channel="whatsapp_agent",
chat_id=CREATOR_CHAT_ID,
content="",
media=[str(big)],
)
)
)
assert calls == []
# ----------------------------------------------------------------------
# Inbound media
# ----------------------------------------------------------------------
def test_inbound_media_is_downloaded_and_verified(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
content = b"pdf-bytes"
digest = base64.b64encode(hashlib.sha256(content).digest()).decode()
raw = {
"from": "user:55",
"id": "wamid.m",
"timestamp": "1",
"type": "document",
"document": {
"id": "MEDIA1",
"mime_type": "application/pdf",
"sha256": digest,
"filename": "report.pdf",
},
}
async def fake_request_ok(method, path, *, method_key, **kwargs):
return {"url": "https://lookaside.fbsbx.com/x/content"}
async def fake_fetch(url, limit):
return content
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
monkeypatch.setattr(channel, "_fetch_media_bytes", fake_fetch)
paths, text = asyncio.run(channel._materialize(_message(raw)))
assert len(paths) == 1
assert Path(paths[0]).read_bytes() == content
assert "report.pdf" in text
def test_media_with_a_mismatched_digest_is_discarded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
raw = {
"from": "user:55",
"id": "wamid.m",
"timestamp": "1",
"type": "image",
"image": {"id": "MEDIA1", "mime_type": "image/jpeg", "sha256": "AAAA"},
}
async def fake_request_ok(method, path, *, method_key, **kwargs):
return {"url": "https://lookaside.fbsbx.com/x/content"}
async def fake_fetch(url, limit):
return b"tampered"
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
monkeypatch.setattr(channel, "_fetch_media_bytes", fake_fetch)
paths, text = asyncio.run(channel._materialize(_message(raw)))
# The bytes never reach the agent and no file is written.
assert paths == []
assert text == "[image]"
def test_internal_media_urls_are_refused(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
raw = {
"from": "user:55",
"id": "wamid.m",
"timestamp": "1",
"type": "image",
"image": {"id": "MEDIA1", "mime_type": "image/jpeg"},
}
async def fake_request_ok(method, path, *, method_key, **kwargs):
return {"url": "http://169.254.169.254/latest/meta-data"}
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
paths, _ = asyncio.run(channel._materialize(_message(raw)))
assert paths == []
def test_voice_note_is_transcribed_when_a_provider_is_available(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
raw = {
"from": "user:55",
"id": "wamid.v",
"timestamp": "1",
"type": "audio",
"audio": {"id": "MEDIA1", "mime_type": "audio/ogg", "voice": True},
}
async def fake_request_ok(method, path, *, method_key, **kwargs):
return {"url": "https://lookaside.fbsbx.com/x/content"}
async def fake_fetch(url, limit):
return b"ogg"
async def fake_transcribe(path):
return "remember to buy milk"
monkeypatch.setattr(channel, "_request_ok", fake_request_ok)
monkeypatch.setattr(channel, "_fetch_media_bytes", fake_fetch)
monkeypatch.setattr(channel, "transcribe_audio", fake_transcribe)
paths, text = asyncio.run(channel._materialize(_message(raw)))
assert text == "remember to buy milk"
assert len(paths) == 1
# ----------------------------------------------------------------------
# Lifecycle and pacing
# ----------------------------------------------------------------------
def test_start_requires_a_token(tmp_path: Path):
channel = _channel(tmp_path, token="")
with pytest.raises(WhatsAppAgentAuthError):
asyncio.run(channel.start())
def test_start_error_message_is_actionable(tmp_path: Path):
channel = _channel(tmp_path)
message = channel.start_error_message(WhatsAppAgentAuthError("nope"))
assert message is not None
assert "API key" in message
def test_invalid_token_during_poll_stops_the_loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
channel = _channel(tmp_path)
entered = asyncio.Event()
async def fake_poll_once():
entered.set()
raise WhatsAppAgentAuthError("bad")
monkeypatch.setattr(channel, "_poll_once", fake_poll_once)
monkeypatch.setattr(channel, "_new_http_client", lambda: _FakeClient())
async def run() -> None:
with pytest.raises(WhatsAppAgentAuthError):
await channel.start()
asyncio.run(run())
assert entered.is_set()
# An invalid token cannot recover by retrying, so the channel is not running.
assert channel._running is False
def test_rolling_window_limiter_paces_a_method(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(runtime_module, "_RATE_WINDOW_SECONDS", 0.25)
limiter = runtime_module._RollingWindowLimiter({"messages": 2}, margin=0)
async def run() -> float:
loop = asyncio.get_running_loop()
start = loop.time()
for _ in range(3):
await limiter.acquire("messages")
return loop.time() - start
# The third call must wait for the window rather than exceed the cap.
assert asyncio.run(run()) >= 0.24
def test_rolling_window_limiter_counts_each_method_separately(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(runtime_module, "_RATE_WINDOW_SECONDS", 0.25)
limiter = runtime_module._RollingWindowLimiter({"messages": 1, "updates": 1}, margin=0)
async def run() -> None:
# A send must not consume the poll budget; both complete immediately.
await asyncio.wait_for(limiter.acquire("messages"), timeout=0.2)
await asyncio.wait_for(limiter.acquire("updates"), timeout=0.2)
asyncio.run(run())
def test_restart_resumes_from_the_persisted_offset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
# First process handles one message and advances the cursor.
first = _channel(tmp_path)
first._load_state()
async def ok_dispatch(message):
return None
monkeypatch.setattr(first, "_dispatch", ok_dispatch)
first._client = object() # type: ignore[assignment]
asyncio.run(first._process_batch(_parse(_poll_body([_text_message("wamid.1")], 500))))
# A new process with the same token must resume, not restart the stream.
second = _channel(tmp_path)
second._load_state()
seen: list[dict[str, Any]] = []
async def fake_request(method, path, *, method_key, params=None, **kwargs):
seen.append(dict(params or {}))
return 204, None
monkeypatch.setattr(second, "_request", fake_request)
second._client = object() # type: ignore[assignment]
asyncio.run(second._poll_once())
assert seen[0]["offset"] == 500
# The dedup window also survives the restart.
assert second._state.has_message("wamid.1") is True
def test_restart_with_a_new_token_does_not_reuse_the_old_cursor(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
first = _channel(tmp_path)
first._load_state()
first._state.accept_offset(500)
first._persist()
replacement = _channel(tmp_path, token="a-different-agent-token")
replacement._load_state()
seen: list[dict[str, Any]] = []
async def fake_request(method, path, *, method_key, params=None, **kwargs):
seen.append(dict(params or {}))
return 204, None
monkeypatch.setattr(replacement, "_request", fake_request)
replacement._client = object() # type: ignore[assignment]
asyncio.run(replacement._poll_once())
# next_offset belongs to the agent that issued it, so it is not replayed.
assert "offset" not in seen[0]
def test_the_token_never_appears_in_logs_or_persisted_state(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
secret = "EAAG-super-secret-agent-token"
channel = _channel(tmp_path, token=secret)
channel._load_state()
channel._state.accept_offset(9)
channel._persist()
records: list[str] = []
logger_id = logger.add(lambda message: records.append(message), level="DEBUG")
try:
# A failing poll exercises the error-logging path with a live token.
async def failing_request(method, path, *, method_key, params=None, **kwargs):
return 400, {"error": {"code": 100, "message": "(100) invalid"}}
monkeypatch.setattr(channel, "_request", failing_request)
channel._client = object() # type: ignore[assignment]
with pytest.raises(WhatsAppAgentAuthError):
asyncio.run(channel._poll_once())
finally:
logger.remove(logger_id)
assert secret not in "".join(records)
assert secret not in (tmp_path / "state.json").read_text(encoding="utf-8")
def test_channel_does_not_regress_the_neonize_whatsapp_channel(tmp_path: Path):
from nanobot.channels.registry import discover_plugins
plugins = discover_plugins()
assert "whatsapp" in plugins
assert "whatsapp_agent" in plugins
assert plugins["whatsapp"].runtime != plugins["whatsapp_agent"].runtime
class _FakeClient:
async def aclose(self) -> None:
return None
@@ -0,0 +1,121 @@
"""Setup contract and validation ownership for the Agent Platform channel."""
from __future__ import annotations
import httpx
import pytest
from nanobot.channels._setup import channel_setup_spec
from nanobot.channels.contracts import ChannelValidationContext
from nanobot.channels.plugin import load_channel_package
from nanobot.channels.whatsapp_agent.validation import validate
_CONTEXT = ChannelValidationContext(allow_local_service_access=False)
def test_manifest_and_setup_contract_match_the_runtime_fields():
plugin = load_channel_package("whatsapp_agent")
assert plugin is not None
assert plugin.name == "whatsapp_agent"
assert plugin.display_name == "WhatsApp Agent Platform"
assert plugin.runtime == "nanobot.channels.whatsapp_agent.runtime:WhatsAppAgentChannel"
# No optional platform SDK: the API is plain HTTPS.
assert plugin.dependencies == ()
assert plugin.default_enabled is False
assert plugin.setup is not None
assert plugin.setup.simple_required_fields == ("token",)
def test_token_is_a_secret_and_setup_does_not_require_a_second_step():
spec = channel_setup_spec("whatsapp_agent")
assert spec is not None
assert spec.secrets == {"token"}
assert spec.route_field_types["token"] == "secret"
# There is no QR or terminal login step; the token alone completes setup.
assert spec.is_configured({"token": "abc"}) is True
assert spec.is_configured({"token": ""}) is False
def test_public_contract_exposes_every_writable_field_only_once():
spec = channel_setup_spec("whatsapp_agent")
assert spec is not None
public = spec.to_public_dict("whatsapp_agent")
fields = [field["field"] for field in public["fields"]]
assert fields == list(spec.fields)
assert "token" in fields
assert public["verifies_connection"] is True
assert public["official_url"].startswith("https://faq.whatsapp.com/")
def test_progress_defaults_are_off_in_the_setup_contract():
spec = channel_setup_spec("whatsapp_agent")
assert spec is not None
# Progress traffic spends the shared 12-per-minute send budget.
assert spec.fields["sendProgress"].default is False
assert spec.fields["sendToolHints"].default is False
assert spec.fields["retryAmbiguousSends"].default is False
def test_missing_token_reports_needs_setup():
payload = validate({}, _CONTEXT)
assert payload["status"] == "needs_setup"
assert payload["can_enable"] is False
assert "token" in payload["missing_fields"]
def test_valid_token_is_reported_as_connected(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(httpx, "get", lambda *a, **k: httpx.Response(204))
payload = validate({"token": "abc"}, _CONTEXT)
assert payload["status"] == "connected"
assert payload["can_enable"] is True
def test_invalid_token_uses_the_400_code_100_contract(monkeypatch: pytest.MonkeyPatch):
response = httpx.Response(400, json={"error": {"code": 100}})
monkeypatch.setattr(httpx, "get", lambda *a, **k: response)
payload = validate({"token": "abc"}, _CONTEXT)
assert payload["status"] == "invalid"
assert payload["can_enable"] is False
def test_missing_authorization_header_is_reported(monkeypatch: pytest.MonkeyPatch):
response = httpx.Response(401, json={"error": {"code": 190}})
monkeypatch.setattr(httpx, "get", lambda *a, **k: response)
payload = validate({"token": "abc"}, _CONTEXT)
assert payload["status"] == "invalid"
def test_duplicate_poller_is_valid_but_warned(monkeypatch: pytest.MonkeyPatch):
response = httpx.Response(409, json={"error": {"code": 1752041}})
monkeypatch.setattr(httpx, "get", lambda *a, **k: response)
payload = validate({"token": "abc"}, _CONTEXT)
assert payload["status"] == "connected"
assert payload["can_enable"] is True
def test_network_failure_warns_without_invalidating_the_token(
monkeypatch: pytest.MonkeyPatch,
):
def fail(*args, **kwargs):
raise httpx.ConnectError("offline")
monkeypatch.setattr(httpx, "get", fail)
payload = validate({"token": "abc"}, _CONTEXT)
assert payload["status"] == "configured"
assert payload["can_enable"] is True
@@ -0,0 +1,129 @@
"""Durable cursor, dedup, and token-rotation contracts for the channel store."""
from __future__ import annotations
import json
from pathlib import Path
from nanobot.channels.whatsapp_agent.state import (
WhatsAppAgentState,
local_state_present,
token_fingerprint,
)
def test_cursor_round_trips_through_disk(tmp_path: Path):
path = tmp_path / "state.json"
state = WhatsAppAgentState()
state.reset_for_token("token-a")
state.accept_offset(9007199254740993)
state.note_message("wamid.1")
state.note_status("wamid.out", "read")
state.note_creator("user:55")
state.save(path)
reloaded = WhatsAppAgentState.load(path)
# next_offset is a signed 64-bit value replayed unchanged.
assert reloaded.offset == 9007199254740993
assert reloaded.initialized is True
assert reloaded.has_message("wamid.1") is True
assert reloaded.last_status["wamid.out"] == "read"
assert reloaded.creator_id == "user:55"
def test_corrupt_or_missing_state_starts_a_fresh_cursor(tmp_path: Path):
path = tmp_path / "state.json"
assert WhatsAppAgentState.load(path).initialized is False
path.write_text("{not json", encoding="utf-8")
recovered = WhatsAppAgentState.load(path)
assert recovered.initialized is False
assert recovered.offset is None
def test_state_file_contains_no_raw_token(tmp_path: Path):
path = tmp_path / "state.json"
state = WhatsAppAgentState()
state.reset_for_token("super-secret-token")
state.save(path)
assert "super-secret-token" not in path.read_text(encoding="utf-8")
assert state.token_fingerprint == token_fingerprint("super-secret-token")
def test_rotating_the_token_discards_a_foreign_cursor():
state = WhatsAppAgentState()
state.reset_for_token("token-a")
state.accept_offset(42)
state.note_message("wamid.1")
# next_offset is only meaningful for the agent that issued it.
assert state.reset_for_token("token-b") is True
assert state.offset is None
assert state.initialized is False
assert state.has_message("wamid.1") is False
def test_restarting_with_the_same_token_keeps_the_cursor():
state = WhatsAppAgentState()
state.reset_for_token("token-a")
state.accept_offset(42)
assert state.reset_for_token("token-a") is False
assert state.offset == 42
assert state.initialized is True
def test_dedup_window_is_bounded_and_drops_the_oldest():
state = WhatsAppAgentState()
for index in range(2500):
state.note_message(f"wamid.{index}")
assert len(state.seen) == 2000
assert state.has_message("wamid.2499") is True
assert state.has_message("wamid.0") is False
def test_persisted_seen_order_survives_a_reload(tmp_path: Path):
path = tmp_path / "state.json"
state = WhatsAppAgentState()
state.note_message("wamid.a")
state.note_message("wamid.b")
state.save(path)
assert list(WhatsAppAgentState.load(path).seen) == ["wamid.a", "wamid.b"]
def test_local_state_present_requires_a_saved_token_fingerprint(tmp_path: Path):
section = {"stateDir": str(tmp_path)}
assert local_state_present(section) is False
state = WhatsAppAgentState()
state.reset_for_token("token-a")
state.save(tmp_path / "state.json")
assert local_state_present(section) is True
def test_unreadable_state_file_reports_no_local_state(tmp_path: Path):
(tmp_path / "state.json").write_text("[]", encoding="utf-8")
assert local_state_present({"stateDir": str(tmp_path)}) is False
def test_legacy_state_without_creator_id_loads():
# A state file written before creator ids were persisted must still load.
payload = json.dumps({"offset": 5, "initialized": True, "token_fingerprint": "abc"})
import tempfile
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "state.json"
path.write_text(payload, encoding="utf-8")
state = WhatsAppAgentState.load(path)
assert state.offset == 5
assert state.creator_id == ""
@@ -0,0 +1,103 @@
"""WhatsApp Agent Platform setup validation owned by the channel package."""
from typing import Any, cast
import httpx
from nanobot.channels.contracts import ChannelValidationContext
from nanobot.channels.validation import (
check,
required_checks,
status_from_checks,
string_value,
)
from nanobot.channels.whatsapp_agent.protocol import API_BASE
_PROBE_TIMEOUT_SECONDS = 6.0
# A poll probe with timeout=0 returns immediately instead of holding a slot.
_PROBE_URL = f"{API_BASE}/updates?limit=1&timeout=0"
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
checks, missing = required_checks("whatsapp_agent", values)
token = string_value(values.get("token"))
if not token:
return status_from_checks("whatsapp_agent", checks, missing)
try:
response = httpx.get(
_PROBE_URL,
headers={"Authorization": f"Bearer {token}"},
timeout=_PROBE_TIMEOUT_SECONDS,
follow_redirects=False,
)
except httpx.HTTPError as exc:
checks.append(
check(
"agent_token",
"API token",
"warn",
f"Could not reach the WhatsApp Agent API now: {exc}",
)
)
return status_from_checks("whatsapp_agent", checks, missing)
code = _error_code(response)
if response.status_code == 401 or code == 190:
checks.append(
check(
"agent_token",
"API token",
"fail",
"The Authorization header was rejected. Re-copy the API key from the agent's chat.",
)
)
elif response.status_code == 400 and code == 100:
checks.append(
check(
"agent_token",
"API token",
"fail",
"WhatsApp rejected this token. Regenerate it from the agent's chat info.",
)
)
elif response.status_code in {200, 204} or response.status_code == 409:
# 409 means the token is valid but another poller is already running.
detail = (
"The token is accepted. A poller is already active for this agent; "
"keep one gateway instance per agent."
if response.status_code == 409
else "The token is accepted by the WhatsApp Agent API."
)
checks.append(check("agent_token", "API token", "pass", detail))
else:
checks.append(
check(
"agent_token",
"API token",
"warn",
f"WhatsApp returned HTTP {response.status_code} while checking the token.",
)
)
return status_from_checks("whatsapp_agent", checks, missing)
def _error_code(response: httpx.Response) -> int:
try:
payload_data: object = response.json()
except ValueError:
return 0
if not isinstance(payload_data, dict):
return 0
body = cast(dict[str, Any], payload_data)
error = body.get("error")
if not isinstance(error, dict):
return 0
raw_code = cast(dict[str, Any], error).get("code")
try:
return int(cast(Any, raw_code))
except (TypeError, ValueError):
return 0
__all__ = ["validate"]
@@ -0,0 +1,30 @@
import { Bot } from "lucide-react";
import type { ChannelUiContribution } from "@/channel-plugins/types";
import { chatAppGuideUrl } from "@/components/settings/channels/catalog";
export default {
presentation: {
logoUrl: "https://static.whatsapp.net/rsrc.php/y1/r/FJbTMJqMap7.svg",
displayName: "WhatsApp Agent Platform",
initials: "WA",
color: "#25D366",
icon: Bot,
setup: {
mode: "credentials",
docsUrl: chatAppGuideUrl("whatsapp-agent-platform"),
fields: [
{ key: "channels.whatsapp_agent.token", section: "credentials" },
{ key: "channels.whatsapp_agent.allowFrom", section: "access" },
{ key: "channels.whatsapp_agent.markRead", section: "behavior" },
{ key: "channels.whatsapp_agent.typingIndicator", section: "behavior" },
{ key: "channels.whatsapp_agent.downloadMedia", section: "behavior" },
{ key: "channels.whatsapp_agent.deleteMediaAfterDownload", section: "behavior" },
{ key: "channels.whatsapp_agent.retryAmbiguousSends", section: "behavior" },
{ key: "channels.whatsapp_agent.pollTimeout", section: "advanced" },
{ key: "channels.whatsapp_agent.maxMediaMb", section: "advanced" },
{ key: "channels.whatsapp_agent.stateDir", section: "advanced" },
],
},
},
} satisfies ChannelUiContribution;
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "Open agent setup guide",
"officialLabel": "Open WhatsApp agent help",
"summary": "Connect nanobot as an official third-party agent in your own WhatsApp account. Only you can chat with it, and it cannot access your other chats.",
"fields": {
"token": {
"label": "API token",
"placeholder": "In WhatsApp, open Settings → Agents, create the agent, then copy the key from the agent chat → Chat info → API key.",
"help": "In WhatsApp, open Settings → Agents, create the agent, then copy the key from the agent chat → Chat info → API key."
},
"allowFrom": {
"label": "Allowed senders",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "State directory",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "Poll timeout (seconds)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "Max media size (MB)",
"placeholder": "16"
},
"markRead": {
"label": "Send read receipts",
"choices": {
"true": "On",
"false": "Off"
}
},
"typingIndicator": {
"label": "Show typing indicator",
"choices": {
"true": "On",
"false": "Off"
}
},
"downloadMedia": {
"label": "Download incoming media",
"choices": {
"true": "On",
"false": "Off"
}
},
"deleteMediaAfterDownload": {
"label": "Delete media after download",
"choices": {
"true": "On",
"false": "Off"
}
},
"retryAmbiguousSends": {
"label": "Retry unknown send outcomes",
"choices": {
"true": "On",
"false": "Off"
}
},
"sendProgress": {
"label": "Send progress messages",
"choices": {
"true": "On",
"false": "Off"
}
},
"sendToolHints": {
"label": "Send tool hints",
"choices": {
"true": "On",
"false": "Off"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "Abrir la guía de configuración del agente",
"officialLabel": "Abrir la ayuda de agentes de WhatsApp",
"summary": "Conecta nanobot como agente oficial de terceros en tu propia cuenta de WhatsApp. Solo tú puedes chatear con él y no accede a tus otros chats.",
"fields": {
"token": {
"label": "Token de API",
"placeholder": "En WhatsApp, abre Ajustes → Agentes, crea el agente y copia la clave desde el chat del agente → Info del chat → Clave de API.",
"help": "En WhatsApp, abre Ajustes → Agentes, crea el agente y copia la clave desde el chat del agente → Info del chat → Clave de API."
},
"allowFrom": {
"label": "Remitentes permitidos",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "Directorio de estado",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "Tiempo de sondeo (segundos)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "Tamaño máximo de multimedia (MB)",
"placeholder": "16"
},
"markRead": {
"label": "Enviar confirmaciones de lectura",
"choices": {
"true": "Activado",
"false": "Desactivado"
}
},
"typingIndicator": {
"label": "Mostrar indicador de escritura",
"choices": {
"true": "Activado",
"false": "Desactivado"
}
},
"downloadMedia": {
"label": "Descargar multimedia entrante",
"choices": {
"true": "Activado",
"false": "Desactivado"
}
},
"deleteMediaAfterDownload": {
"label": "Eliminar multimedia tras descargar",
"choices": {
"true": "Activado",
"false": "Desactivado"
}
},
"retryAmbiguousSends": {
"label": "Reintentar envíos de resultado desconocido",
"choices": {
"true": "Activado",
"false": "Desactivado"
}
},
"sendProgress": {
"label": "Enviar mensajes de progreso",
"choices": {
"true": "Activado",
"false": "Desactivado"
}
},
"sendToolHints": {
"label": "Enviar sugerencias de herramientas",
"choices": {
"true": "Activado",
"false": "Desactivado"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "Ouvrir le guide de configuration de l'agent",
"officialLabel": "Ouvrir l'aide des agents WhatsApp",
"summary": "Connectez nanobot comme agent tiers officiel dans votre propre compte WhatsApp. Vous seul pouvez lui écrire, et il n'accède pas à vos autres conversations.",
"fields": {
"token": {
"label": "Jeton d'API",
"placeholder": "Dans WhatsApp, ouvrez Réglages → Agents, créez l'agent, puis copiez la clé depuis la conversation de l'agent → Infos de la discussion → Clé API.",
"help": "Dans WhatsApp, ouvrez Réglages → Agents, créez l'agent, puis copiez la clé depuis la conversation de l'agent → Infos de la discussion → Clé API."
},
"allowFrom": {
"label": "Expéditeurs autorisés",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "Répertoire d'état",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "Délai d'interrogation (secondes)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "Taille max. des médias (Mo)",
"placeholder": "16"
},
"markRead": {
"label": "Envoyer les accusés de lecture",
"choices": {
"true": "Activé",
"false": "Désactivé"
}
},
"typingIndicator": {
"label": "Afficher l'indicateur de saisie",
"choices": {
"true": "Activé",
"false": "Désactivé"
}
},
"downloadMedia": {
"label": "Télécharger les médias entrants",
"choices": {
"true": "Activé",
"false": "Désactivé"
}
},
"deleteMediaAfterDownload": {
"label": "Supprimer les médias après téléchargement",
"choices": {
"true": "Activé",
"false": "Désactivé"
}
},
"retryAmbiguousSends": {
"label": "Réessayer les envois au résultat inconnu",
"choices": {
"true": "Activé",
"false": "Désactivé"
}
},
"sendProgress": {
"label": "Envoyer les messages de progression",
"choices": {
"true": "Activé",
"false": "Désactivé"
}
},
"sendToolHints": {
"label": "Envoyer les indications d'outil",
"choices": {
"true": "Activé",
"false": "Désactivé"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "Buka panduan penyiapan agen",
"officialLabel": "Buka bantuan agen WhatsApp",
"summary": "Hubungkan nanobot sebagai agen pihak ketiga resmi di akun WhatsApp Anda sendiri. Hanya Anda yang dapat mengobrol dengannya, dan ia tidak mengakses obrolan lain Anda.",
"fields": {
"token": {
"label": "Token API",
"placeholder": "Di WhatsApp, buka Setelan → Agen, buat agen, lalu salin kunci dari obrolan agen → Info obrolan → Kunci API.",
"help": "Di WhatsApp, buka Setelan → Agen, buat agen, lalu salin kunci dari obrolan agen → Info obrolan → Kunci API."
},
"allowFrom": {
"label": "Pengirim yang diizinkan",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "Direktori status",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "Batas waktu polling (detik)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "Ukuran media maksimum (MB)",
"placeholder": "16"
},
"markRead": {
"label": "Kirim tanda dibaca",
"choices": {
"true": "Aktif",
"false": "Nonaktif"
}
},
"typingIndicator": {
"label": "Tampilkan indikator mengetik",
"choices": {
"true": "Aktif",
"false": "Nonaktif"
}
},
"downloadMedia": {
"label": "Unduh media masuk",
"choices": {
"true": "Aktif",
"false": "Nonaktif"
}
},
"deleteMediaAfterDownload": {
"label": "Hapus media setelah unduh",
"choices": {
"true": "Aktif",
"false": "Nonaktif"
}
},
"retryAmbiguousSends": {
"label": "Coba ulang kirim yang tidak pasti",
"choices": {
"true": "Aktif",
"false": "Nonaktif"
}
},
"sendProgress": {
"label": "Kirim pesan kemajuan",
"choices": {
"true": "Aktif",
"false": "Nonaktif"
}
},
"sendToolHints": {
"label": "Kirim petunjuk alat",
"choices": {
"true": "Aktif",
"false": "Nonaktif"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "エージェント設定ガイドを開く",
"officialLabel": "WhatsApp エージェントのヘルプを開く",
"summary": "nanobot を公式のサードパーティエージェントとして自分の WhatsApp アカウントに接続します。会話できるのは本人だけで、他のチャットにはアクセスできません。",
"fields": {
"token": {
"label": "API トークン",
"placeholder": "WhatsApp で 設定 → エージェント を開き、エージェントを作成して、エージェントのチャット → チャット情報 → API キー からキーをコピーします。",
"help": "WhatsApp で 設定 → エージェント を開き、エージェントを作成して、エージェントのチャット → チャット情報 → API キー からキーをコピーします。"
},
"allowFrom": {
"label": "許可する送信者",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "状態ディレクトリ",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "ポーリング タイムアウト(秒)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "メディア最大サイズ(MB)",
"placeholder": "16"
},
"markRead": {
"label": "既読通知を送信",
"choices": {
"true": "オン",
"false": "オフ"
}
},
"typingIndicator": {
"label": "入力中表示を表示",
"choices": {
"true": "オン",
"false": "オフ"
}
},
"downloadMedia": {
"label": "受信メディアをダウンロード",
"choices": {
"true": "オン",
"false": "オフ"
}
},
"deleteMediaAfterDownload": {
"label": "ダウンロード後にメディアを削除",
"choices": {
"true": "オン",
"false": "オフ"
}
},
"retryAmbiguousSends": {
"label": "結果不明な送信を再試行",
"choices": {
"true": "オン",
"false": "オフ"
}
},
"sendProgress": {
"label": "進捗メッセージを送信",
"choices": {
"true": "オン",
"false": "オフ"
}
},
"sendToolHints": {
"label": "ツールのヒントを送信",
"choices": {
"true": "オン",
"false": "オフ"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "에이전트 설정 가이드 열기",
"officialLabel": "WhatsApp 에이전트 도움말 열기",
"summary": "nanobot을 공식 서드파티 에이전트로 내 WhatsApp 계정에 연결합니다. 나만 대화할 수 있으며 다른 채팅에는 접근할 수 없습니다.",
"fields": {
"token": {
"label": "API 토큰",
"placeholder": "WhatsApp에서 설정 → 에이전트를 열고 에이전트를 만든 뒤 에이전트 채팅 → 채팅 정보 → API 키에서 키를 복사하세요.",
"help": "WhatsApp에서 설정 → 에이전트를 열고 에이전트를 만든 뒤 에이전트 채팅 → 채팅 정보 → API 키에서 키를 복사하세요."
},
"allowFrom": {
"label": "허용된 발신자",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "상태 디렉터리",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "폴링 제한 시간(초)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "최대 미디어 크기(MB)",
"placeholder": "16"
},
"markRead": {
"label": "읽음 표시 보내기",
"choices": {
"true": "켜기",
"false": "끄기"
}
},
"typingIndicator": {
"label": "입력 중 표시 보기",
"choices": {
"true": "켜기",
"false": "끄기"
}
},
"downloadMedia": {
"label": "수신 미디어 다운로드",
"choices": {
"true": "켜기",
"false": "끄기"
}
},
"deleteMediaAfterDownload": {
"label": "다운로드 후 미디어 삭제",
"choices": {
"true": "켜기",
"false": "끄기"
}
},
"retryAmbiguousSends": {
"label": "결과를 알 수 없는 전송 재시도",
"choices": {
"true": "켜기",
"false": "끄기"
}
},
"sendProgress": {
"label": "진행 메시지 보내기",
"choices": {
"true": "켜기",
"false": "끄기"
}
},
"sendToolHints": {
"label": "도구 힌트 보내기",
"choices": {
"true": "켜기",
"false": "끄기"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "Abrir o guia de configuração do agente",
"officialLabel": "Abrir a ajuda de agentes do WhatsApp",
"summary": "Conecte o nanobot como agente oficial de terceiros na sua própria conta do WhatsApp. Só você pode conversar com ele, e ele não acessa suas outras conversas.",
"fields": {
"token": {
"label": "Token de API",
"placeholder": "No WhatsApp, abra Configurações → Agentes, crie o agente e copie a chave em conversa do agente → Informações da conversa → Chave de API.",
"help": "No WhatsApp, abra Configurações → Agentes, crie o agente e copie a chave em conversa do agente → Informações da conversa → Chave de API."
},
"allowFrom": {
"label": "Remetentes permitidos",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "Diretório de estado",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "Tempo limite de sondagem (segundos)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "Tamanho máximo de mídia (MB)",
"placeholder": "16"
},
"markRead": {
"label": "Enviar confirmações de leitura",
"choices": {
"true": "Ativado",
"false": "Desativado"
}
},
"typingIndicator": {
"label": "Mostrar indicador de digitação",
"choices": {
"true": "Ativado",
"false": "Desativado"
}
},
"downloadMedia": {
"label": "Baixar mídia recebida",
"choices": {
"true": "Ativado",
"false": "Desativado"
}
},
"deleteMediaAfterDownload": {
"label": "Excluir mídia após baixar",
"choices": {
"true": "Ativado",
"false": "Desativado"
}
},
"retryAmbiguousSends": {
"label": "Repetir envios de resultado desconhecido",
"choices": {
"true": "Ativado",
"false": "Desativado"
}
},
"sendProgress": {
"label": "Enviar mensagens de progresso",
"choices": {
"true": "Ativado",
"false": "Desativado"
}
},
"sendToolHints": {
"label": "Enviar dicas de ferramentas",
"choices": {
"true": "Ativado",
"false": "Desativado"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "Mở hướng dẫn thiết lập tác nhân",
"officialLabel": "Mở trợ giúp tác nhân WhatsApp",
"summary": "Kết nối nanobot như một tác nhân bên thứ ba chính thức trong tài khoản WhatsApp của bạn. Chỉ bạn có thể trò chuyện với nó và nó không truy cập các cuộc trò chuyện khác.",
"fields": {
"token": {
"label": "Mã thông báo API",
"placeholder": "Trong WhatsApp, mở Cài đặt → Tác nhân, tạo tác nhân, rồi sao chép khóa từ trò chuyện của tác nhân → Thông tin trò chuyện → Khóa API.",
"help": "Trong WhatsApp, mở Cài đặt → Tác nhân, tạo tác nhân, rồi sao chép khóa từ trò chuyện của tác nhân → Thông tin trò chuyện → Khóa API."
},
"allowFrom": {
"label": "Người gửi được phép",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "Thư mục trạng thái",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "Thời gian chờ thăm dò (giây)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "Kích thước phương tiện tối đa (MB)",
"placeholder": "16"
},
"markRead": {
"label": "Gửi biên nhận đã đọc",
"choices": {
"true": "Bật",
"false": "Tắt"
}
},
"typingIndicator": {
"label": "Hiện chỉ báo đang nhập",
"choices": {
"true": "Bật",
"false": "Tắt"
}
},
"downloadMedia": {
"label": "Tải phương tiện đến",
"choices": {
"true": "Bật",
"false": "Tắt"
}
},
"deleteMediaAfterDownload": {
"label": "Xóa phương tiện sau khi tải",
"choices": {
"true": "Bật",
"false": "Tắt"
}
},
"retryAmbiguousSends": {
"label": "Thử lại gửi không rõ kết quả",
"choices": {
"true": "Bật",
"false": "Tắt"
}
},
"sendProgress": {
"label": "Gửi tin nhắn tiến trình",
"choices": {
"true": "Bật",
"false": "Tắt"
}
},
"sendToolHints": {
"label": "Gửi gợi ý công cụ",
"choices": {
"true": "Bật",
"false": "Tắt"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "打开智能体设置指南",
"officialLabel": "打开 WhatsApp 智能体帮助",
"summary": "将 nanobot 作为官方第三方智能体接入你自己的 WhatsApp 账号。只有你可以与它对话,它无法访问你的其他聊天。",
"fields": {
"token": {
"label": "API 令牌",
"placeholder": "在 WhatsApp 中打开 设置 → 智能体,创建智能体,然后从智能体聊天 → 聊天信息 → API 密钥 复制密钥。",
"help": "在 WhatsApp 中打开 设置 → 智能体,创建智能体,然后从智能体聊天 → 聊天信息 → API 密钥 复制密钥。"
},
"allowFrom": {
"label": "允许的发送者",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "状态目录",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "轮询超时(秒)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "媒体大小上限(MB)",
"placeholder": "16"
},
"markRead": {
"label": "发送已读回执",
"choices": {
"true": "开启",
"false": "关闭"
}
},
"typingIndicator": {
"label": "显示正在输入",
"choices": {
"true": "开启",
"false": "关闭"
}
},
"downloadMedia": {
"label": "下载传入媒体",
"choices": {
"true": "开启",
"false": "关闭"
}
},
"deleteMediaAfterDownload": {
"label": "下载后删除媒体",
"choices": {
"true": "开启",
"false": "关闭"
}
},
"retryAmbiguousSends": {
"label": "重试结果不明的发送",
"choices": {
"true": "开启",
"false": "关闭"
}
},
"sendProgress": {
"label": "发送进度消息",
"choices": {
"true": "开启",
"false": "关闭"
}
},
"sendToolHints": {
"label": "发送工具提示",
"choices": {
"true": "开启",
"false": "关闭"
}
}
}
}
}
@@ -0,0 +1,79 @@
{
"setup": {
"docsLabel": "開啟代理設定指南",
"officialLabel": "開啟 WhatsApp 代理說明",
"summary": "將 nanobot 作為官方第三方代理連結到你的 WhatsApp 帳號。只有你可以與它對話,它無法存取你的其他聊天。",
"fields": {
"token": {
"label": "API 權杖",
"placeholder": "在 WhatsApp 中開啟 設定 → 代理,建立代理,然後從代理聊天 → 聊天資訊 → API 金鑰 複製金鑰。",
"help": "在 WhatsApp 中開啟 設定 → 代理,建立代理,然後從代理聊天 → 聊天資訊 → API 金鑰 複製金鑰。"
},
"allowFrom": {
"label": "允許的寄件者",
"placeholder": "user:1234567890"
},
"stateDir": {
"label": "狀態目錄",
"placeholder": "~/.nanobot/whatsapp-agent"
},
"pollTimeout": {
"label": "輪詢逾時(秒)",
"placeholder": "25"
},
"maxMediaMb": {
"label": "媒體大小上限(MB)",
"placeholder": "16"
},
"markRead": {
"label": "傳送已讀回條",
"choices": {
"true": "開啟",
"false": "關閉"
}
},
"typingIndicator": {
"label": "顯示正在輸入",
"choices": {
"true": "開啟",
"false": "關閉"
}
},
"downloadMedia": {
"label": "下載傳入媒體",
"choices": {
"true": "開啟",
"false": "關閉"
}
},
"deleteMediaAfterDownload": {
"label": "下載後刪除媒體",
"choices": {
"true": "開啟",
"false": "關閉"
}
},
"retryAmbiguousSends": {
"label": "重試結果不明的傳送",
"choices": {
"true": "開啟",
"false": "關閉"
}
},
"sendProgress": {
"label": "傳送進度訊息",
"choices": {
"true": "開啟",
"false": "關閉"
}
},
"sendToolHints": {
"label": "傳送工具提示",
"choices": {
"true": "開啟",
"false": "關閉"
}
}
}
}
}
+1
View File
@@ -292,6 +292,7 @@ def test_channels_config_keeps_shared_delivery_defaults():
"matrix",
"weixin",
"whatsapp",
"whatsapp_agent",
],
)
def test_special_setup_validation_is_owned_by_channel_package(name: str):
+1
View File
@@ -32,6 +32,7 @@ EXPECTED_CHANNELS = {
"wecom",
"weixin",
"whatsapp",
"whatsapp_agent",
}
INTERNAL_CHANNEL_FIELDS = {
@@ -24,6 +24,7 @@ const expectedChannels = [
"wecom",
"weixin",
"whatsapp",
"whatsapp_agent",
];
function flatten(value: unknown, prefix = ""): Map<string, string> {