Skip to content

Self-improving AI Employees for everyone

refactor(whatsapp)!: one Send node for the whole /messages endpoint

trohitg62ee2c3e75aa
diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.json
index a8afa03c..47e97b56 100644
--- a/server/config/node_allowlist.json
+++ b/server/config/node_allowlist.json
@@ -36,8 +36,6 @@
"whatsappBusinessReceive",
"whatsappBusinessStatus",
"whatsappBusinessMedia",
- "whatsappBusinessTemplate",
- "whatsappBusinessInteractive",
"airplaneModeControl",
"appLauncher",
diff --git a/server/nodes/whatsapp_business/__init__.py b/server/nodes/whatsapp_business/__init__.py
index 10ae99df..3be0429e 100644
--- a/server/nodes/whatsapp_business/__init__.py
+++ b/server/nodes/whatsapp_business/__init__.py
@@ -21,10 +21,6 @@ from ._credentials import WhatsAppBusinessCredential
from ._events import MESSAGE_RECEIVED_TYPE, STATUS_UPDATED_TYPE
from ._option_loaders import load_templates
from ._source import get_webhook_source
-from .whatsapp_business_interactive import (
- WhatsAppBusinessInteractiveNode,
- WhatsAppBusinessInteractiveOutput,
-)
from .whatsapp_business_media import WhatsAppBusinessMediaNode, WhatsAppBusinessMediaOutput
from .whatsapp_business_receive import (
WhatsAppBusinessReceiveNode,
@@ -33,10 +29,6 @@ from .whatsapp_business_receive import (
WhatsAppBusinessStatusOutput,
)
from .whatsapp_business_send import WhatsAppBusinessSendNode, WhatsAppBusinessSendOutput
-from .whatsapp_business_template import (
- WhatsAppBusinessTemplateNode,
- WhatsAppBusinessTemplateOutput,
-)
# Claims POST/GET /webhook/whatsapp-business. Takes an instance, not the class.
# Without this the path falls through to the generic legacy handler, which
@@ -56,15 +48,11 @@ register_output_schema(WhatsAppBusinessSendNode.type, WhatsAppBusinessSendOutput
register_output_schema(WhatsAppBusinessReceiveNode.type, WhatsAppBusinessReceiveOutput)
register_output_schema(WhatsAppBusinessStatusNode.type, WhatsAppBusinessStatusOutput)
register_output_schema(WhatsAppBusinessMediaNode.type, WhatsAppBusinessMediaOutput)
-register_output_schema(WhatsAppBusinessTemplateNode.type, WhatsAppBusinessTemplateOutput)
-register_output_schema(WhatsAppBusinessInteractiveNode.type, WhatsAppBusinessInteractiveOutput)
__all__ = [
"WhatsAppBusinessCredential",
- "WhatsAppBusinessInteractiveNode",
"WhatsAppBusinessMediaNode",
"WhatsAppBusinessReceiveNode",
"WhatsAppBusinessSendNode",
"WhatsAppBusinessStatusNode",
- "WhatsAppBusinessTemplateNode",
]
diff --git a/server/nodes/whatsapp_business/whatsapp_business_interactive.py b/server/nodes/whatsapp_business/whatsapp_business_interactive.py
deleted file mode 100644
index 1321c5f7..00000000
--- a/server/nodes/whatsapp_business/whatsapp_business_interactive.py
+++ /dev/null
@@ -1,306 +0,0 @@
-"""whatsappBusinessInteractive — reply buttons, list menus and CTA-URL.
-
-Replies arrive back on ``whatsappBusinessReceive`` as ``interactive_reply``,
-with the ``id`` you set here, so the id is the join between what was offered
-and what was chosen.
-"""
-
-from __future__ import annotations
-
-from typing import Any, Dict, List, Literal, Optional
-
-from pydantic import BaseModel, ConfigDict, Field, field_validator
-
-from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue
-
-from ._base import graph_post, normalize_recipient, resolve_phone_number_id
-from ._credentials import WhatsAppBusinessCredential
-
-# Meta's documented ceilings. Enforced locally because the API rejects the
-# whole message rather than trimming, and a 400 mid-conversation is worse
-# than a clear error before sending.
-_MAX_BUTTONS = 3
-_MAX_BUTTON_TITLE = 20
-_MAX_ROWS_TOTAL = 10
-_MAX_ROW_TITLE = 24
-_MAX_ROW_DESCRIPTION = 72
-_MAX_LIST_BUTTON = 20
-# The OpenAPI spec says 1024 and the interactive-list docs page says 4096.
-# Using the smaller of Meta's two numbers: too-short fails loudly at authoring
-# time, too-long fails at send time in front of a customer.
-_MAX_BODY = 1024
-_MAX_FOOTER = 60
-_MAX_HEADER = 60
-
-
-class WhatsAppBusinessInteractiveParams(BaseModel):
- operation: Literal["send_buttons", "send_list", "send_cta_url"] = Field(
- default="send_buttons",
- description="Which interactive message to send.",
- )
- to: str = Field(default="", description="Recipient phone number in international format.")
- body: str = Field(
- default="",
- description="Main message text.",
- json_schema_extra={"rows": 3},
- )
- header: str = Field(default="", description="Optional bold header text.")
- footer: str = Field(default="", description="Optional small footer text.")
-
- buttons: List[Dict[str, str]] = Field(
- default_factory=list,
- description='Up to 3 reply buttons: [{"id": "yes", "title": "Yes"}]',
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_buttons"]}}},
- )
-
- list_button_text: str = Field(
- default="Choose",
- description="Label on the button that opens the list.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_list"]}}},
- )
- sections: List[Dict[str, Any]] = Field(
- default_factory=list,
- description=(
- 'Sections of rows: [{"title": "Plans", "rows": '
- '[{"id": "p1", "title": "Basic", "description": "..."}]}]. '
- "10 rows maximum across all sections."
- ),
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_list"]}}},
- )
-
- cta_display_text: str = Field(
- default="",
- description="Button label for the CTA URL.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_cta_url"]}}},
- )
- cta_url: str = Field(
- default="",
- description="URL the button opens.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_cta_url"]}}},
- )
-
- model_config = ConfigDict(extra="ignore")
-
- @field_validator("buttons", "sections", mode="before")
- @classmethod
- def _coerce_json(cls, value: Any) -> Any:
- """LLM tool arguments routinely arrive as stringified JSON."""
- if isinstance(value, str):
- text = value.strip()
- if not text:
- return []
- import json
-
- try:
- parsed = json.loads(text)
- except ValueError:
- return []
- return parsed if isinstance(parsed, list) else [parsed]
- return value
-
-
-class WhatsAppBusinessInteractiveOutput(BaseModel):
- message_id: Optional[str] = None
- to: Optional[str] = None
- wa_id: Optional[str] = None
- phone_number_id: Optional[str] = None
- message_status: Optional[str] = None
-
- model_config = ConfigDict(extra="allow")
-
-
-class WhatsAppBusinessInteractiveNode(ActionNode):
- type = "whatsappBusinessInteractive"
- display_name = "WhatsApp Business Interactive"
- subtitle = "Buttons / list / CTA"
- group = ("whatsapp_business", "tool")
- description = "Send reply buttons, a list menu, or a call-to-action URL button"
- component_kind = "square"
- tool_name = "whatsapp_business_interactive"
- tool_description = (
- "Send an interactive WhatsApp message: up to 3 reply buttons, a list menu "
- "of up to 10 rows, or a single call-to-action URL button. The user's "
- "choice comes back on the WhatsApp Business Receive trigger carrying the "
- "id you set here."
- )
- handles = (
- {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
- {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
- )
- credentials = (WhatsAppBusinessCredential,)
- annotations = {"destructive": False, "readonly": False, "open_world": True}
- task_queue = TaskQueue.MESSAGING
- usable_as_tool = True
-
- Params = WhatsAppBusinessInteractiveParams
- Output = WhatsAppBusinessInteractiveOutput
-
- @Operation("send_buttons", cost={"service": "whatsapp_business", "action": "send_interactive", "count": 1})
- async def send_buttons(
- self, ctx: NodeContext, params: WhatsAppBusinessInteractiveParams
- ) -> WhatsAppBusinessInteractiveOutput:
- if not params.buttons:
- raise NodeUserError('Add at least one button, e.g. [{"id": "yes", "title": "Yes"}].')
- if len(params.buttons) > _MAX_BUTTONS:
- raise NodeUserError(
- f"WhatsApp allows at most {_MAX_BUTTONS} reply buttons; got {len(params.buttons)}. "
- "Use a list message for more options."
- )
-
- buttons = []
- for index, button in enumerate(params.buttons):
- title = str(button.get("title") or "").strip()
- if not title:
- raise NodeUserError(f"Button {index + 1} has no title.")
- if len(title) > _MAX_BUTTON_TITLE:
- raise NodeUserError(
- f"Button title {title!r} is {len(title)} characters; the limit is {_MAX_BUTTON_TITLE}."
- )
- buttons.append(
- {
- "type": "reply",
- "reply": {"id": str(button.get("id") or f"btn_{index + 1}"), "title": title},
- }
- )
-
- return await self._send(ctx, params, {"type": "button", "action": {"buttons": buttons}})
-
- @Operation("send_list", cost={"service": "whatsapp_business", "action": "send_interactive", "count": 1})
- async def send_list(
- self, ctx: NodeContext, params: WhatsAppBusinessInteractiveParams
- ) -> WhatsAppBusinessInteractiveOutput:
- if not params.sections:
- raise NodeUserError("Add at least one section with rows.")
-
- total_rows = sum(len(section.get("rows") or []) for section in params.sections)
- if total_rows == 0:
- raise NodeUserError("The list has no rows.")
- if total_rows > _MAX_ROWS_TOTAL:
- # The cap is across ALL sections, not per section -- a common
- # misreading, so the message says so.
- raise NodeUserError(
- f"A list allows {_MAX_ROWS_TOTAL} rows in total across every section; got {total_rows}."
- )
-
- button_text = params.list_button_text.strip() or "Choose"
- if len(button_text) > _MAX_LIST_BUTTON:
- raise NodeUserError(
- f"List button text is {len(button_text)} characters; the limit is {_MAX_LIST_BUTTON}."
- )
-
- sections = []
- for section in params.sections:
- rows = []
- for index, row in enumerate(section.get("rows") or []):
- title = str(row.get("title") or "").strip()
- if not title:
- raise NodeUserError(f"Row {index + 1} has no title.")
- if len(title) > _MAX_ROW_TITLE:
- raise NodeUserError(
- f"Row title {title!r} is {len(title)} characters; the limit is {_MAX_ROW_TITLE}."
- )
- entry = {"id": str(row.get("id") or f"row_{index + 1}"), "title": title}
- description = str(row.get("description") or "").strip()
- if description:
- if len(description) > _MAX_ROW_DESCRIPTION:
- raise NodeUserError(
- f"Row description for {title!r} is {len(description)} characters; "
- f"the limit is {_MAX_ROW_DESCRIPTION}."
- )
- entry["description"] = description
- rows.append(entry)
- sections.append({"title": str(section.get("title") or "")[:24], "rows": rows})
-
- return await self._send(
- ctx,
- params,
- {"type": "list", "action": {"button": button_text, "sections": sections}},
- # A list header is text-only; media there is rejected.
- header_text_only=True,
- )
-
- @Operation("send_cta_url", cost={"service": "whatsapp_business", "action": "send_interactive", "count": 1})
- async def send_cta_url(
- self, ctx: NodeContext, params: WhatsAppBusinessInteractiveParams
- ) -> WhatsAppBusinessInteractiveOutput:
- display_text = params.cta_display_text.strip()
- url = params.cta_url.strip()
- if not display_text or not url:
- raise NodeUserError("A CTA button needs both display text and a URL.")
-
- return await self._send(
- ctx,
- params,
- {
- "type": "cta_url",
- "action": {
- "name": "cta_url",
- "parameters": {"display_text": display_text, "url": url},
- },
- },
- )
-
- async def _send(
- self,
- ctx: NodeContext,
- params: WhatsAppBusinessInteractiveParams,
- interactive: Dict[str, Any],
- *,
- header_text_only: bool = False,
- ) -> WhatsAppBusinessInteractiveOutput:
- body = params.body.strip()
- if not body:
- raise NodeUserError("An interactive message needs body text.")
- if len(body) > _MAX_BODY:
- raise NodeUserError(
- f"Body is {len(body)} characters; the limit is {_MAX_BODY}."
- )
-
- interactive = dict(interactive)
- interactive["body"] = {"text": body}
-
- header = params.header.strip()
- if header:
- if len(header) > _MAX_HEADER:
- raise NodeUserError(f"Header is {len(header)} characters; the limit is {_MAX_HEADER}.")
- interactive["header"] = {"type": "text", "text": header}
- elif header_text_only:
- pass
-
- footer = params.footer.strip()
- if footer:
- if len(footer) > _MAX_FOOTER:
- raise NodeUserError(f"Footer is {len(footer)} characters; the limit is {_MAX_FOOTER}.")
- interactive["footer"] = {"text": footer}
-
- recipient = normalize_recipient(params.to)
- phone_number_id = await resolve_phone_number_id(ctx)
- result = await graph_post(
- ctx,
- f"{phone_number_id}/messages",
- {
- "messaging_product": "whatsapp",
- "recipient_type": "individual",
- "to": recipient,
- "type": "interactive",
- "interactive": interactive,
- },
- )
-
- messages = result.get("messages") or []
- contacts = result.get("contacts") or []
- first = messages[0] if messages else {}
- return WhatsAppBusinessInteractiveOutput(
- message_id=first.get("id"),
- message_status=first.get("message_status"),
- to=recipient,
- wa_id=(contacts[0].get("wa_id") if contacts else None),
- phone_number_id=phone_number_id,
- )
-
-
-__all__ = [
- "WhatsAppBusinessInteractiveNode",
- "WhatsAppBusinessInteractiveOutput",
- "WhatsAppBusinessInteractiveParams",
-]
diff --git a/server/nodes/whatsapp_business/whatsapp_business_media.py b/server/nodes/whatsapp_business/whatsapp_business_media.py
index fdbf47bb..47aab080 100644
--- a/server/nodes/whatsapp_business/whatsapp_business_media.py
+++ b/server/nodes/whatsapp_business/whatsapp_business_media.py
@@ -102,6 +102,7 @@ class WhatsAppBusinessMediaNode(ActionNode):
credentials = (WhatsAppBusinessCredential,)
annotations = {"destructive": False, "readonly": False, "open_world": True}
task_queue = TaskQueue.MESSAGING
+ usable_as_tool = True
Params = WhatsAppBusinessMediaParams
Output = WhatsAppBusinessMediaOutput
diff --git a/server/nodes/whatsapp_business/whatsapp_business_send.py b/server/nodes/whatsapp_business/whatsapp_business_send.py
index ed9519a0..99c2e90f 100644
--- a/server/nodes/whatsapp_business/whatsapp_business_send.py
+++ b/server/nodes/whatsapp_business/whatsapp_business_send.py
@@ -1,52 +1,125 @@
-"""whatsappBusinessSend — send a message via Meta's WhatsApp Cloud API."""
+"""whatsappBusinessSend — every Cloud API outbound message type, one node.
+
+Meta models message type as a *field* on a single endpoint
+(``POST /{phone-number-id}/messages``), not as separate endpoints: text,
+image, video, audio, document, sticker, location, contacts, reaction,
+interactive and template all post the same URL and differ only in ``type``
+and one sibling object. Splitting them across nodes made the canvas imply
+an API shape that does not exist, so they are operations here.
+
+Media *management* is the one genuinely separate endpoint family
+(``POST /{phone-number-id}/media``, ``GET``/``DELETE /{media-id}``) and
+stays in ``whatsappBusinessMedia``. ``list_templates`` is the other
+outlier — it is WABA-scoped rather than phone-scoped — but it is kept
+here because it exists to answer "what can I send", which is a question
+about sending.
+"""
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue
-from ._base import graph_post, normalize_recipient, resolve_phone_number_id
+from ._base import (
+ graph_get,
+ graph_post,
+ normalize_recipient,
+ resolve_phone_number_id,
+)
from ._credentials import WhatsAppBusinessCredential
-# Meta's documented ceiling for a text body. Longer bodies are rejected
-# outright rather than truncated: silently dropping the tail of an outbound
-# business message is worse than a clear failure.
_MAX_TEXT_BODY = 4096
+# Interactive ceilings, enforced locally because Meta rejects the whole
+# message rather than trimming, and a 400 mid-conversation is worse than a
+# clear error at authoring time.
+_MAX_BUTTONS = 3
+_MAX_BUTTON_TITLE = 20
+_MAX_ROWS_TOTAL = 10
+_MAX_ROW_TITLE = 24
+_MAX_ROW_DESCRIPTION = 72
+_MAX_LIST_BUTTON = 20
+# The OpenAPI spec says 1024 and the interactive-list docs page says 4096.
+# Using the smaller of Meta's two numbers: too-short fails loudly at
+# authoring time, too-long fails at send time in front of a customer.
+_MAX_BODY = 1024
+_MAX_FOOTER = 60
+_MAX_HEADER = 60
+
+_INTERACTIVE_OPS = ["send_buttons", "send_list", "send_cta_url"]
+
+
+def _show(**conditions: Any) -> Dict[str, Any]:
+ """displayOptions helper. All conditions must hold (the frontend ANDs them)."""
+ return {"displayOptions": {"show": conditions}}
+
class WhatsAppBusinessSendParams(BaseModel):
"""Operator configuration, persisted on the node."""
- # Required once a node declares more than one @Operation: _pick_operation
- # reads this off the raw parameters, and an absent value resolves to no
- # operation at all rather than a default.
- operation: Literal["send_text", "send_media"] = Field(
- default="send_text",
- description="What to send.",
- )
+ # Load-bearing, not decorative: _pick_operation reads this off the raw
+ # parameter dict *before* Pydantic validation, so the default below never
+ # applies at dispatch time and an absent value resolves to no operation
+ # at all. Callers constructing raw dicts must pass it explicitly.
+ operation: Literal[
+ "send_text",
+ "send_media",
+ "send_template",
+ "send_buttons",
+ "send_list",
+ "send_cta_url",
+ "send_reaction",
+ "send_location",
+ "send_contacts",
+ "list_templates",
+ ] = Field(default="send_text", description="What to send.")
+
to: str = Field(
default="",
description="Recipient phone number in international format (e.g. +14155551234).",
+ json_schema_extra=_show(
+ operation=[
+ "send_text",
+ "send_media",
+ "send_template",
+ *_INTERACTIVE_OPS,
+ "send_reaction",
+ "send_location",
+ "send_contacts",
+ ]
+ ),
+ )
+ reply_to_message_id: str = Field(
+ default="",
+ description="Quote an inbound message by its wamid.",
+ json_schema_extra=_show(
+ operation=[
+ "send_text",
+ "send_media",
+ "send_location",
+ "send_contacts",
+ ]
+ ),
)
+
+ # --- send_text ----------------------------------------------------------
text: str = Field(
default="",
description="Message body.",
- json_schema_extra={"rows": 4},
+ json_schema_extra={"rows": 4, **_show(operation=["send_text"])},
)
preview_url: bool = Field(
default=False,
description="Render a link preview for the first URL in the body.",
- )
- reply_to_message_id: str = Field(
- default="",
- description="Optional message id to reply to, threading the message.",
+ json_schema_extra=_show(operation=["send_text"]),
)
format_markdown: bool = Field(
default=True,
description="Convert GFM markdown to WhatsApp's *bold* / _italic_ syntax.",
+ json_schema_extra=_show(operation=["send_text"]),
)
# --- send_media ---------------------------------------------------------
@@ -58,7 +131,7 @@ class WhatsAppBusinessSendParams(BaseModel):
media_type: Literal["image", "video", "audio", "document", "sticker"] = Field(
default="image",
description="Kind of media to send.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_media"]}}},
+ json_schema_extra=_show(operation=["send_media"]),
)
media_source: Literal["file", "id", "link"] = Field(
default="file",
@@ -66,7 +139,7 @@ class WhatsAppBusinessSendParams(BaseModel):
"file: upload from the workspace. id: a media ID already uploaded. "
"link: a public URL Meta fetches itself."
),
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_media"]}}},
+ json_schema_extra=_show(operation=["send_media"]),
)
media: Any = Field(
default=None,
@@ -74,28 +147,163 @@ class WhatsAppBusinessSendParams(BaseModel):
json_schema_extra={
"widget": "file",
"accept": "*/*",
- "displayOptions": {"show": {"media_source": ["file"]}},
+ # Gated on operation as well as source: media_source defaults to
+ # "file", so keying on it alone rendered the file picker during
+ # send_text.
+ **_show(operation=["send_media"], media_source=["file"]),
},
)
media_id: str = Field(
default="",
description="Existing Meta media ID.",
- json_schema_extra={"displayOptions": {"show": {"media_source": ["id"]}}},
+ json_schema_extra=_show(operation=["send_media"], media_source=["id"]),
)
media_url: str = Field(
default="",
description="Publicly reachable URL. Meta downloads it directly.",
- json_schema_extra={"displayOptions": {"show": {"media_source": ["link"]}}},
+ json_schema_extra=_show(operation=["send_media"], media_source=["link"]),
)
caption: str = Field(
default="",
description="Caption. Not supported for audio or sticker.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_media"]}}},
+ json_schema_extra=_show(operation=["send_media"]),
)
media_filename: str = Field(
default="",
description="Filename shown to the recipient. Documents only.",
- json_schema_extra={"displayOptions": {"show": {"media_type": ["document"]}}},
+ json_schema_extra=_show(operation=["send_media"], media_type=["document"]),
+ )
+
+ # --- send_template ------------------------------------------------------
+ template_name: str = Field(
+ default="",
+ description="Exact name of the approved template.",
+ json_schema_extra={
+ "loadOptionsMethod": "whatsappBusinessTemplates",
+ **_show(operation=["send_template"]),
+ },
+ )
+ language_code: str = Field(
+ default="en_US",
+ description="Template language, e.g. en_US, es_MX, hi. Meta does not translate.",
+ json_schema_extra=_show(operation=["send_template"]),
+ )
+ body_parameters: List[str] = Field(
+ default_factory=list,
+ description=(
+ "Values for the body placeholders, in order. For a named template "
+ "use the Named Parameters field instead."
+ ),
+ json_schema_extra=_show(operation=["send_template"]),
+ )
+ named_parameters: Dict[str, str] = Field(
+ default_factory=dict,
+ description=(
+ "Values keyed by placeholder name, for templates created with "
+ "parameter_format=named."
+ ),
+ json_schema_extra=_show(operation=["send_template"]),
+ )
+ header_media_id: str = Field(
+ default="",
+ description="Media ID for a template whose header is an image, video or document.",
+ json_schema_extra=_show(operation=["send_template"]),
+ )
+ header_media_type: Literal["image", "video", "document"] = Field(
+ default="image",
+ description="Which media kind the template header expects.",
+ json_schema_extra=_show(operation=["send_template"]),
+ )
+
+ # --- interactive --------------------------------------------------------
+ body: str = Field(
+ default="",
+ description="Main message text.",
+ json_schema_extra={"rows": 3, **_show(operation=_INTERACTIVE_OPS)},
+ )
+ header: str = Field(
+ default="",
+ description="Optional bold header text.",
+ json_schema_extra=_show(operation=_INTERACTIVE_OPS),
+ )
+ footer: str = Field(
+ default="",
+ description="Optional small footer text.",
+ json_schema_extra=_show(operation=_INTERACTIVE_OPS),
+ )
+ buttons: List[Dict[str, str]] = Field(
+ default_factory=list,
+ description='Up to 3 reply buttons: [{"id": "yes", "title": "Yes"}]',
+ json_schema_extra=_show(operation=["send_buttons"]),
+ )
+ list_button_text: str = Field(
+ default="Choose",
+ description="Label on the button that opens the list.",
+ json_schema_extra=_show(operation=["send_list"]),
+ )
+ sections: List[Dict[str, Any]] = Field(
+ default_factory=list,
+ description=(
+ 'Sections of rows: [{"title": "Plans", "rows": '
+ '[{"id": "p1", "title": "Basic", "description": "..."}]}]. '
+ "10 rows maximum across all sections."
+ ),
+ json_schema_extra=_show(operation=["send_list"]),
+ )
+ cta_display_text: str = Field(
+ default="",
+ description="Button label for the CTA URL.",
+ json_schema_extra=_show(operation=["send_cta_url"]),
+ )
+ cta_url: str = Field(
+ default="",
+ description="URL the button opens.",
+ json_schema_extra=_show(operation=["send_cta_url"]),
+ )
+
+ # --- send_reaction ------------------------------------------------------
+ reaction_message_id: str = Field(
+ default="",
+ description="wamid of the message to react to.",
+ json_schema_extra=_show(operation=["send_reaction"]),
+ )
+ emoji: str = Field(
+ default="",
+ description="Single emoji. Leave empty to remove an existing reaction.",
+ json_schema_extra=_show(operation=["send_reaction"]),
+ )
+
+ # --- send_location ------------------------------------------------------
+ latitude: Optional[float] = Field(
+ default=None,
+ description="Latitude in decimal degrees.",
+ json_schema_extra=_show(operation=["send_location"]),
+ )
+ longitude: Optional[float] = Field(
+ default=None,
+ description="Longitude in decimal degrees.",
+ json_schema_extra=_show(operation=["send_location"]),
+ )
+ location_name: str = Field(
+ default="",
+ description="Optional place name.",
+ json_schema_extra=_show(operation=["send_location"]),
+ )
+ location_address: str = Field(
+ default="",
+ description="Optional street address. Only shown when a name is set.",
+ json_schema_extra=_show(operation=["send_location"]),
+ )
+
+ # --- send_contacts ------------------------------------------------------
+ contacts: List[Dict[str, Any]] = Field(
+ default_factory=list,
+ description=(
+ 'Contact cards: [{"name": {"formatted_name": "Ada Lovelace", '
+ '"first_name": "Ada"}, "phones": [{"phone": "+14155551234", '
+ '"type": "CELL"}]}]'
+ ),
+ json_schema_extra=_show(operation=["send_contacts"]),
)
# There is deliberately NO phone_number_id parameter.
@@ -111,10 +319,48 @@ class WhatsAppBusinessSendParams(BaseModel):
#
# The sending number therefore comes only from the credential, where the
# model cannot reach it. A per-node override belongs with multi-number
- # support, which is deferred (see the plan's 6.4).
+ # support, which is deferred.
model_config = ConfigDict(extra="ignore")
+ @field_validator("buttons", "sections", "body_parameters", "contacts", mode="before")
+ @classmethod
+ def _coerce_json_list(cls, value: Any) -> Any:
+ """LLM tool arguments routinely arrive as stringified JSON.
+
+ A ValidationError here reads as a node bug rather than a retryable
+ argument mistake, so a string is parsed before Pydantic sees it.
+ Malformed input still falls through.
+ """
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return []
+ import json
+
+ try:
+ parsed = json.loads(text)
+ except ValueError:
+ return []
+ return parsed if isinstance(parsed, list) else [parsed]
+ return value
+
+ @field_validator("named_parameters", mode="before")
+ @classmethod
+ def _coerce_json_dict(cls, value: Any) -> Any:
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return {}
+ import json
+
+ try:
+ parsed = json.loads(text)
+ except ValueError:
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+ return value
+
class WhatsAppBusinessSendOutput(BaseModel):
message_id: Optional[str] = None
@@ -124,6 +370,9 @@ class WhatsAppBusinessSendOutput(BaseModel):
# Meta's reference schema always documents this, but no per-type example
# includes it, so it is parsed as optional rather than assumed.
message_status: Optional[str] = None
+ # list_templates only.
+ templates: List[dict] = Field(default_factory=list)
+ count: Optional[int] = None
model_config = ConfigDict(extra="allow")
@@ -133,14 +382,18 @@ class WhatsAppBusinessSendNode(ActionNode):
display_name = "WhatsApp Business Send"
subtitle = "Cloud API"
group = ("whatsapp_business", "tool")
- description = "Send a WhatsApp message through Meta's official Cloud API"
+ description = "Send any WhatsApp message type through Meta's official Cloud API"
component_kind = "square"
tool_name = "whatsapp_business_send"
tool_description = (
- "Send a WhatsApp text message to a phone number using the official "
- "WhatsApp Business Cloud API. Only works if the recipient messaged the "
- "business within the last 24 hours; outside that window an approved "
- "template is required instead."
+ "Send a WhatsApp message through the official Business Cloud API. Set "
+ "`operation` to choose the kind: send_text, send_media, send_template, "
+ "send_buttons, send_list, send_cta_url, send_reaction, send_location, "
+ "send_contacts, or list_templates. Everything except send_template and "
+ "list_templates only works if the recipient messaged the business within "
+ "the last 24 hours; outside that window an approved template is the only "
+ "way through. Use list_templates to see what is approved and how many "
+ "placeholders each one takes."
)
handles = (
{"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
@@ -159,13 +412,12 @@ class WhatsAppBusinessSendNode(ActionNode):
Params = WhatsAppBusinessSendParams
Output = WhatsAppBusinessSendOutput
+ # --- text ---------------------------------------------------------------
+
@Operation("send_text", cost={"service": "whatsapp_business", "action": "send_text", "count": 1})
async def send_text(
- self,
- ctx: NodeContext,
- params: WhatsAppBusinessSendParams,
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
) -> WhatsAppBusinessSendOutput:
- recipient = normalize_recipient(params.to)
body = params.text or ""
if not body.strip():
raise NodeUserError("Cannot send an empty WhatsApp message.")
@@ -181,30 +433,21 @@ class WhatsAppBusinessSendNode(ActionNode):
f"{_MAX_TEXT_BODY}. Split it before sending."
)
- preview_url = params.preview_url
- reply_to = (params.reply_to_message_id or "").strip()
- phone_number_id = await resolve_phone_number_id(ctx)
-
- payload: Dict[str, Any] = {
- "messaging_product": "whatsapp",
- "recipient_type": "individual",
- "to": recipient,
- "type": "text",
- "text": {"preview_url": preview_url, "body": body},
- }
- if reply_to:
- payload["context"] = {"message_id": reply_to}
+ return await self._post_message(
+ ctx,
+ params,
+ "text",
+ {"preview_url": params.preview_url, "body": body},
+ )
- result = await graph_post(ctx, f"{phone_number_id}/messages", payload)
- return _shape_send_result(result, recipient, phone_number_id)
+ # --- media --------------------------------------------------------------
@Operation("send_media", cost={"service": "whatsapp_business", "action": "send_media", "count": 1})
async def send_media(
self, ctx: NodeContext, params: WhatsAppBusinessSendParams
) -> WhatsAppBusinessSendOutput:
- recipient = normalize_recipient(params.to)
- phone_number_id = await resolve_phone_number_id(ctx)
media_type = params.media_type
+ phone_number_id = await resolve_phone_number_id(ctx)
# `id` and `link` are a strict oneOf in Meta's schema -- sending both
# is rejected, so exactly one is built here.
@@ -226,32 +469,354 @@ class WhatsAppBusinessSendNode(ActionNode):
if media_type == "document" and params.media_filename.strip():
media_object["filename"] = params.media_filename.strip()
+ return await self._post_message(
+ ctx, params, media_type, media_object, phone_number_id=phone_number_id
+ )
+
+ # --- template -----------------------------------------------------------
+
+ @Operation("send_template", cost={"service": "whatsapp_business", "action": "send_template", "count": 1})
+ async def send_template(
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
+ ) -> WhatsAppBusinessSendOutput:
+ if not params.template_name.strip():
+ raise NodeUserError("Choose a template name. Use list_templates to see approved ones.")
+
+ components: List[Dict[str, Any]] = []
+ if params.header_media_id.strip():
+ components.append(
+ {
+ "type": "header",
+ "parameters": [
+ {
+ "type": params.header_media_type,
+ params.header_media_type: {"id": params.header_media_id.strip()},
+ }
+ ],
+ }
+ )
+
+ body_params = _build_body_parameters(params)
+ if body_params:
+ components.append({"type": "body", "parameters": body_params})
+
+ template: Dict[str, Any] = {
+ "name": params.template_name.strip(),
+ # An object at send time, a bare string at creation time. The
+ # asymmetry is Meta's, not ours.
+ "language": {"code": params.language_code.strip() or "en_US"},
+ }
+ if components:
+ template["components"] = components
+
+ return await self._post_message(ctx, params, "template", template, quotable=False)
+
+ @Operation("list_templates")
+ async def list_templates(
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
+ ) -> WhatsAppBusinessSendOutput:
+ from services.plugin.deps import get_auth_service
+
+ waba_id = await get_auth_service().get_api_key("whatsapp_business_waba_id")
+ if not waba_id:
+ raise NodeUserError(
+ "Add your WhatsApp Business Account ID to the credential to list templates."
+ )
+
+ result = await graph_get(
+ ctx,
+ f"{waba_id}/message_templates",
+ {"fields": "name,status,category,language,components", "limit": 100},
+ )
+ rows = [
+ {
+ "name": item.get("name"),
+ "status": item.get("status"),
+ "category": item.get("category"),
+ "language": item.get("language"),
+ "placeholders": _count_placeholders(item),
+ }
+ for item in (result.get("data") or [])
+ ]
+ return WhatsAppBusinessSendOutput(templates=rows, count=len(rows))
+
+ # --- interactive --------------------------------------------------------
+
+ @Operation("send_buttons", cost={"service": "whatsapp_business", "action": "send_interactive", "count": 1})
+ async def send_buttons(
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
+ ) -> WhatsAppBusinessSendOutput:
+ if not params.buttons:
+ raise NodeUserError('Add at least one button, e.g. [{"id": "yes", "title": "Yes"}].')
+ if len(params.buttons) > _MAX_BUTTONS:
+ raise NodeUserError(
+ f"WhatsApp allows at most {_MAX_BUTTONS} reply buttons; got {len(params.buttons)}. "
+ "Use a list message for more options."
+ )
+
+ buttons = []
+ for index, button in enumerate(params.buttons):
+ title = str(button.get("title") or "").strip()
+ if not title:
+ raise NodeUserError(f"Button {index + 1} has no title.")
+ if len(title) > _MAX_BUTTON_TITLE:
+ raise NodeUserError(
+ f"Button title {title!r} is {len(title)} characters; the limit is {_MAX_BUTTON_TITLE}."
+ )
+ buttons.append(
+ {
+ "type": "reply",
+ "reply": {"id": str(button.get("id") or f"btn_{index + 1}"), "title": title},
+ }
+ )
+
+ return await self._send_interactive(
+ ctx, params, {"type": "button", "action": {"buttons": buttons}}
+ )
+
+ @Operation("send_list", cost={"service": "whatsapp_business", "action": "send_interactive", "count": 1})
+ async def send_list(
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
+ ) -> WhatsAppBusinessSendOutput:
+ if not params.sections:
+ raise NodeUserError("Add at least one section with rows.")
+
+ total_rows = sum(len(section.get("rows") or []) for section in params.sections)
+ if total_rows == 0:
+ raise NodeUserError("The list has no rows.")
+ if total_rows > _MAX_ROWS_TOTAL:
+ # The cap is across ALL sections, not per section -- a common
+ # misreading, so the message says so.
+ raise NodeUserError(
+ f"A list allows {_MAX_ROWS_TOTAL} rows in total across every section; got {total_rows}."
+ )
+
+ button_text = params.list_button_text.strip() or "Choose"
+ if len(button_text) > _MAX_LIST_BUTTON:
+ raise NodeUserError(
+ f"List button text is {len(button_text)} characters; the limit is {_MAX_LIST_BUTTON}."
+ )
+
+ sections = []
+ for section in params.sections:
+ rows = []
+ for index, row in enumerate(section.get("rows") or []):
+ title = str(row.get("title") or "").strip()
+ if not title:
+ raise NodeUserError(f"Row {index + 1} has no title.")
+ if len(title) > _MAX_ROW_TITLE:
+ raise NodeUserError(
+ f"Row title {title!r} is {len(title)} characters; the limit is {_MAX_ROW_TITLE}."
+ )
+ entry = {"id": str(row.get("id") or f"row_{index + 1}"), "title": title}
+ description = str(row.get("description") or "").strip()
+ if description:
+ if len(description) > _MAX_ROW_DESCRIPTION:
+ raise NodeUserError(
+ f"Row description for {title!r} is {len(description)} characters; "
+ f"the limit is {_MAX_ROW_DESCRIPTION}."
+ )
+ entry["description"] = description
+ rows.append(entry)
+ sections.append({"title": str(section.get("title") or "")[:24], "rows": rows})
+
+ return await self._send_interactive(
+ ctx,
+ params,
+ {"type": "list", "action": {"button": button_text, "sections": sections}},
+ )
+
+ @Operation("send_cta_url", cost={"service": "whatsapp_business", "action": "send_interactive", "count": 1})
+ async def send_cta_url(
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
+ ) -> WhatsAppBusinessSendOutput:
+ display_text = params.cta_display_text.strip()
+ url = params.cta_url.strip()
+ if not display_text or not url:
+ raise NodeUserError("A CTA button needs both display text and a URL.")
+
+ return await self._send_interactive(
+ ctx,
+ params,
+ {
+ "type": "cta_url",
+ "action": {
+ "name": "cta_url",
+ "parameters": {"display_text": display_text, "url": url},
+ },
+ },
+ )
+
+ # --- reaction / location / contacts -------------------------------------
+
+ @Operation("send_reaction", cost={"service": "whatsapp_business", "action": "send_reaction", "count": 1})
+ async def send_reaction(
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
+ ) -> WhatsAppBusinessSendOutput:
+ """React to an inbound message.
+
+ An empty emoji is not an error: Meta documents the empty string as the
+ way to *remove* a previously sent reaction, so it is passed through
+ rather than rejected.
+ """
+ target = params.reaction_message_id.strip()
+ if not target:
+ raise NodeUserError(
+ "A reaction needs the wamid of the message to react to. Inbound "
+ "messages carry it on message_id."
+ )
+ # A reaction addresses its target through reaction.message_id, so it
+ # never carries a `context` block of its own.
+ return await self._post_message(
+ ctx,
+ params,
+ "reaction",
+ {"message_id": target, "emoji": params.emoji.strip()},
+ quotable=False,
+ )
+
+ @Operation("send_location", cost={"service": "whatsapp_business", "action": "send_location", "count": 1})
+ async def send_location(
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
+ ) -> WhatsAppBusinessSendOutput:
+ if params.latitude is None or params.longitude is None:
+ raise NodeUserError("A location needs both a latitude and a longitude.")
+ if not -90 <= params.latitude <= 90:
+ raise NodeUserError(f"Latitude {params.latitude} is outside -90..90.")
+ if not -180 <= params.longitude <= 180:
+ raise NodeUserError(f"Longitude {params.longitude} is outside -180..180.")
+
+ location: Dict[str, Any] = {
+ "latitude": params.latitude,
+ "longitude": params.longitude,
+ }
+ name = params.location_name.strip()
+ address = params.location_address.strip()
+ if name:
+ location["name"] = name
+ # Meta only renders address alongside a name; sending it alone is
+ # accepted and then silently dropped, so it is nested here to keep
+ # the payload honest about what will actually show.
+ if address:
+ location["address"] = address
+
+ return await self._post_message(ctx, params, "location", location)
+
+ @Operation("send_contacts", cost={"service": "whatsapp_business", "action": "send_contacts", "count": 1})
+ async def send_contacts(
+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams
+ ) -> WhatsAppBusinessSendOutput:
+ if not params.contacts:
+ raise NodeUserError("Add at least one contact card.")
+
+ for index, contact in enumerate(params.contacts):
+ name = contact.get("name")
+ if not isinstance(name, dict) or not str(name.get("formatted_name") or "").strip():
+ raise NodeUserError(
+ f"Contact {index + 1} needs name.formatted_name; Meta rejects "
+ "a contact card without it."
+ )
+
+ # `contacts` is the one message type whose sibling is a list, so it
+ # bypasses the dict-shaped helper.
+ recipient = normalize_recipient(params.to)
+ phone_number_id = await resolve_phone_number_id(ctx)
payload: Dict[str, Any] = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": recipient,
- "type": media_type,
- media_type: media_object,
+ "type": "contacts",
+ "contacts": params.contacts,
}
- reply_to = (params.reply_to_message_id or "").strip()
+ reply_to = params.reply_to_message_id.strip()
if reply_to:
payload["context"] = {"message_id": reply_to}
result = await graph_post(ctx, f"{phone_number_id}/messages", payload)
return _shape_send_result(result, recipient, phone_number_id)
+ # --- shared senders -----------------------------------------------------
+
+ async def _post_message(
+ self,
+ ctx: NodeContext,
+ params: WhatsAppBusinessSendParams,
+ message_type: str,
+ sibling: Dict[str, Any],
+ *,
+ phone_number_id: Optional[str] = None,
+ quotable: bool = True,
+ ) -> WhatsAppBusinessSendOutput:
+ """POST one message. Every type differs only in `type` and one sibling."""
+ recipient = normalize_recipient(params.to)
+ if phone_number_id is None:
+ phone_number_id = await resolve_phone_number_id(ctx)
+
+ payload: Dict[str, Any] = {
+ "messaging_product": "whatsapp",
+ "recipient_type": "individual",
+ "to": recipient,
+ "type": message_type,
+ message_type: sibling,
+ }
+ reply_to = params.reply_to_message_id.strip()
+ if quotable and reply_to:
+ payload["context"] = {"message_id": reply_to}
+
+ result = await graph_post(ctx, f"{phone_number_id}/messages", payload)
+ return _shape_send_result(result, recipient, phone_number_id)
+
+ async def _send_interactive(
+ self,
+ ctx: NodeContext,
+ params: WhatsAppBusinessSendParams,
+ interactive: Dict[str, Any],
+ ) -> WhatsAppBusinessSendOutput:
+ body = params.body.strip()
+ if not body:
+ raise NodeUserError("An interactive message needs body text.")
+ if len(body) > _MAX_BODY:
+ raise NodeUserError(f"Body is {len(body)} characters; the limit is {_MAX_BODY}.")
+
+ interactive = dict(interactive)
+ interactive["body"] = {"text": body}
+
+ header = params.header.strip()
+ if header:
+ if len(header) > _MAX_HEADER:
+ raise NodeUserError(
+ f"Header is {len(header)} characters; the limit is {_MAX_HEADER}."
+ )
+ # Text-only by construction. A list header must be text, and the
+ # other two subtypes are only given text headers here, so there is
+ # no media-header branch to guard.
+ interactive["header"] = {"type": "text", "text": header}
+
+ footer = params.footer.strip()
+ if footer:
+ if len(footer) > _MAX_FOOTER:
+ raise NodeUserError(
+ f"Footer is {len(footer)} characters; the limit is {_MAX_FOOTER}."
+ )
+ interactive["footer"] = {"text": footer}
+
+ return await self._post_message(
+ ctx, params, "interactive", interactive, quotable=False
+ )
+
async def _upload_for_send(
ctx: NodeContext, params: WhatsAppBusinessSendParams, phone_number_id: str
) -> str:
"""Upload a workspace file and return the media id Meta assigns."""
+ import mimetypes
+
from services.media import coerce_file_param
if params.media in (None, ""):
raise NodeUserError("Select a file to send, or switch the media source to id/link.")
filename, blob = coerce_file_param(params.media, ctx=ctx)
- import mimetypes
mime_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
result = await graph_post(
@@ -268,6 +833,40 @@ async def _upload_for_send(
return str(media_id)
+def _build_body_parameters(params: WhatsAppBusinessSendParams) -> List[Dict[str, Any]]:
+ """Named and positional are mutually exclusive, fixed at template creation.
+
+ Named wins when both are supplied, because a named template rejects
+ positional values outright with error 132000 rather than ignoring them.
+ """
+ if params.named_parameters:
+ return [
+ {"type": "text", "parameter_name": key, "text": str(value)}
+ for key, value in params.named_parameters.items()
+ ]
+ return [{"type": "text", "text": str(value)} for value in params.body_parameters]
+
+
+def _count_placeholders(template: Dict[str, Any]) -> Optional[int]:
+ """How many body values the template expects.
+
+ Surfaced because a count mismatch is error 132000, the single most common
+ template failure, and the number is otherwise invisible until a send fails.
+ """
+ for component in template.get("components") or []:
+ if str(component.get("type", "")).upper() != "BODY":
+ continue
+ text = component.get("text") or ""
+ example = component.get("example") or {}
+ named = example.get("body_text_named_params")
+ if isinstance(named, list):
+ return len(named)
+ import re
+
+ return len(set(re.findall(r"\{\{\s*([^}]+?)\s*\}\}", text)))
+ return None
+
+
def _shape_send_result(
result: Dict[str, Any], recipient: str, phone_number_id: str
) -> WhatsAppBusinessSendOutput:
diff --git a/server/nodes/whatsapp_business/whatsapp_business_template.py b/server/nodes/whatsapp_business/whatsapp_business_template.py
deleted file mode 100644
index b0a8152c..00000000
--- a/server/nodes/whatsapp_business/whatsapp_business_template.py
+++ /dev/null
@@ -1,272 +0,0 @@
-"""whatsappBusinessTemplate — send an approved template, or list templates.
-
-Templates are the only way to message a user outside the 24-hour customer
-service window, so this is the node error 131047 points at.
-"""
-
-from __future__ import annotations
-
-from typing import Any, Dict, List, Literal, Optional
-
-from pydantic import BaseModel, ConfigDict, Field, field_validator
-
-from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue
-
-from ._base import graph_get, graph_post, normalize_recipient, resolve_phone_number_id
-from ._credentials import WhatsAppBusinessCredential
-
-
-class WhatsAppBusinessTemplateParams(BaseModel):
- operation: Literal["send_template", "list_templates"] = Field(
- default="send_template",
- description="Send an approved template, or list what is available.",
- )
- to: str = Field(
- default="",
- description="Recipient phone number in international format.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_template"]}}},
- )
- template_name: str = Field(
- default="",
- description="Exact name of the approved template.",
- json_schema_extra={
- "displayOptions": {"show": {"operation": ["send_template"]}},
- "loadOptionsMethod": "whatsappBusinessTemplates",
- },
- )
- language_code: str = Field(
- default="en_US",
- description="Template language, e.g. en_US, es_MX, hi. Meta does not translate.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_template"]}}},
- )
- body_parameters: List[str] = Field(
- default_factory=list,
- description=(
- "Values for the body placeholders, in order. For a named template "
- "use the Named Parameters field instead."
- ),
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_template"]}}},
- )
- named_parameters: Dict[str, str] = Field(
- default_factory=dict,
- description=(
- "Values keyed by placeholder name, for templates created with "
- "parameter_format=named."
- ),
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_template"]}}},
- )
- header_media_id: str = Field(
- default="",
- description="Media ID for a template whose header is an image, video or document.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_template"]}}},
- )
- header_media_type: Literal["image", "video", "document"] = Field(
- default="image",
- description="Which media kind the template header expects.",
- json_schema_extra={"displayOptions": {"show": {"operation": ["send_template"]}}},
- )
-
- model_config = ConfigDict(extra="ignore")
-
- @field_validator("body_parameters", mode="before")
- @classmethod
- def _coerce_body_parameters(cls, value: Any) -> Any:
- """Accept a JSON string as well as a list.
-
- An LLM supplying tool arguments frequently stringifies arrays, and a
- ValidationError there reads as a node bug rather than a retryable
- argument mistake. Malformed input still falls through to Pydantic.
- """
- if isinstance(value, str):
- text = value.strip()
- if not text:
- return []
- import json
-
- try:
- parsed = json.loads(text)
- except ValueError:
- return [text]
- return parsed if isinstance(parsed, list) else [parsed]
- return value
-
- @field_validator("named_parameters", mode="before")
- @classmethod
- def _coerce_named_parameters(cls, value: Any) -> Any:
- if isinstance(value, str):
- text = value.strip()
- if not text:
- return {}
- import json
-
- try:
- parsed = json.loads(text)
- except ValueError:
- return {}
- return parsed if isinstance(parsed, dict) else {}
- return value
-
-
-class WhatsAppBusinessTemplateOutput(BaseModel):
- message_id: Optional[str] = None
- to: Optional[str] = None
- wa_id: Optional[str] = None
- phone_number_id: Optional[str] = None
- message_status: Optional[str] = None
- templates: List[dict] = Field(default_factory=list)
- count: Optional[int] = None
-
- model_config = ConfigDict(extra="allow")
-
-
-class WhatsAppBusinessTemplateNode(ActionNode):
- type = "whatsappBusinessTemplate"
- display_name = "WhatsApp Business Template"
- subtitle = "Approved template"
- group = ("whatsapp_business", "tool")
- description = "Send an approved WhatsApp template message, or list available templates"
- component_kind = "square"
- tool_name = "whatsapp_business_template"
- tool_description = (
- "Send a pre-approved WhatsApp template message. This is the ONLY way to "
- "message someone who has not written to the business in the last 24 hours. "
- "Use list_templates first to see what is approved and how many "
- "placeholders each one takes."
- )
- handles = (
- {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
- {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
- )
- credentials = (WhatsAppBusinessCredential,)
- annotations = {"destructive": False, "readonly": False, "open_world": True}
- task_queue = TaskQueue.MESSAGING
- usable_as_tool = True
-
- Params = WhatsAppBusinessTemplateParams
- Output = WhatsAppBusinessTemplateOutput
-
- @Operation("send_template", cost={"service": "whatsapp_business", "action": "send_template", "count": 1})
- async def send_template(
- self, ctx: NodeContext, params: WhatsAppBusinessTemplateParams
- ) -> WhatsAppBusinessTemplateOutput:
- if not params.template_name.strip():
- raise NodeUserError("Choose a template name. Use list_templates to see approved ones.")
-
- recipient = normalize_recipient(params.to)
- phone_number_id = await resolve_phone_number_id(ctx)
-
- components: List[Dict[str, Any]] = []
-
- if params.header_media_id.strip():
- components.append(
- {
- "type": "header",
- "parameters": [
- {
- "type": params.header_media_type,
- params.header_media_type: {"id": params.header_media_id.strip()},
- }
- ],
- }
- )
-
- body_params = _build_body_parameters(params)
- if body_params:
- components.append({"type": "body", "parameters": body_params})
-
- payload: Dict[str, Any] = {
- "messaging_product": "whatsapp",
- "recipient_type": "individual",
- "to": recipient,
- "type": "template",
- "template": {
- "name": params.template_name.strip(),
- # An object at send time, a bare string at creation time. The
- # asymmetry is Meta's, not ours.
- "language": {"code": params.language_code.strip() or "en_US"},
- },
- }
- if components:
- payload["template"]["components"] = components
-
- result = await graph_post(ctx, f"{phone_number_id}/messages", payload)
- messages = result.get("messages") or []
- contacts = result.get("contacts") or []
- first = messages[0] if messages else {}
- return WhatsAppBusinessTemplateOutput(
- message_id=first.get("id"),
- message_status=first.get("message_status"),
- to=recipient,
- wa_id=(contacts[0].get("wa_id") if contacts else None),
- phone_number_id=phone_number_id,
- )
-
- @Operation("list_templates")
- async def list_templates(
- self, ctx: NodeContext, params: WhatsAppBusinessTemplateParams
- ) -> WhatsAppBusinessTemplateOutput:
- from services.plugin.deps import get_auth_service
-
- waba_id = await get_auth_service().get_api_key("whatsapp_business_waba_id")
- if not waba_id:
- raise NodeUserError(
- "Add your WhatsApp Business Account ID to the credential to list templates."
- )
-
- result = await graph_get(
- ctx,
- f"{waba_id}/message_templates",
- {"fields": "name,status,category,language,components", "limit": 100},
- )
- rows = [
- {
- "name": item.get("name"),
- "status": item.get("status"),
- "category": item.get("category"),
- "language": item.get("language"),
- "placeholders": _count_placeholders(item),
- }
- for item in (result.get("data") or [])
- ]
- return WhatsAppBusinessTemplateOutput(templates=rows, count=len(rows))
-
-
-def _build_body_parameters(params: WhatsAppBusinessTemplateParams) -> List[Dict[str, Any]]:
- """Named and positional are mutually exclusive, fixed at template creation.
-
- Named wins when both are supplied, because a named template rejects
- positional values outright with error 132000 rather than ignoring them.
- """
- if params.named_parameters:
- return [
- {"type": "text", "parameter_name": key, "text": str(value)}
- for key, value in params.named_parameters.items()
- ]
- return [{"type": "text", "text": str(value)} for value in params.body_parameters]
-
-
-def _count_placeholders(template: Dict[str, Any]) -> Optional[int]:
- """How many body values the template expects.
-
- Surfaced because a count mismatch is error 132000, the single most common
- template failure, and the number is otherwise invisible until a send fails.
- """
- for component in template.get("components") or []:
- if str(component.get("type", "")).upper() != "BODY":
- continue
- text = component.get("text") or ""
- example = component.get("example") or {}
- named = example.get("body_text_named_params")
- if isinstance(named, list):
- return len(named)
- import re
-
- return len(set(re.findall(r"\{\{\s*([^}]+?)\s*\}\}", text)))
- return None
-
-
-__all__ = [
- "WhatsAppBusinessTemplateNode",
- "WhatsAppBusinessTemplateOutput",
- "WhatsAppBusinessTemplateParams",
-]
diff --git a/server/tests/nodes/test_whatsapp_business.py b/server/tests/nodes/test_whatsapp_business.py
index d912046e..e5992683 100644
--- a/server/tests/nodes/test_whatsapp_business.py
+++ b/server/tests/nodes/test_whatsapp_business.py
@@ -45,6 +45,349 @@ def _ctx(**raw):
)
+def _capture(params, *, number="PN1", result=None):
+ """Run one operation and return the outgoing Graph request."""
+ node = WhatsAppBusinessSendNode()
+ captured = {}
+
+ async def _fake_post(ctx, path, body=None, **kwargs):
+ captured["path"] = path
+ captured["body"] = body
+ captured["kwargs"] = kwargs
+ return result or {"messages": [{"id": "wamid.X"}], "contacts": [{"wa_id": "1"}]}
+
+ async def _fake_get(ctx, path, params=None):
+ captured["path"] = path
+ captured["params"] = params
+ return result or {"data": []}
+
+ with (
+ patch("nodes.whatsapp_business.whatsapp_business_send.graph_post", new=_fake_post),
+ patch("nodes.whatsapp_business.whatsapp_business_send.graph_get", new=_fake_get),
+ patch(
+ "services.plugin.deps.get_auth_service",
+ return_value=SimpleNamespace(get_api_key=AsyncMock(return_value=number)),
+ ),
+ ):
+ captured["envelope"] = _run(node.execute("wac-1", params, _ctx()))
+ return captured
+
+
+class TestOneNodeCoversTheMessagesEndpoint:
+ """Meta models message type as a field on one endpoint, not as endpoints.
+
+ The node mirrors that: every send operation posts
+ ``{phone_number_id}/messages`` and differs only in ``type``. If someone
+ splits these back into separate nodes, or routes one at a different URL,
+ these fail.
+ """
+
+ SEND_OPS = [
+ "send_text",
+ "send_media",
+ "send_template",
+ "send_buttons",
+ "send_list",
+ "send_cta_url",
+ "send_reaction",
+ "send_location",
+ "send_contacts",
+ ]
+
+ def test_every_message_type_is_an_operation_on_this_node(self):
+ declared = WhatsAppBusinessSendParams.model_fields["operation"].annotation
+ import typing
+
+ values = set(typing.get_args(declared))
+ assert values == set(self.SEND_OPS) | {"list_templates"}
+
+ def test_the_absorbed_node_types_are_gone(self):
+ """whatsappBusinessTemplate / ...Interactive were merged into send.
+
+ They are unreleased, so they are deleted rather than aliased. A
+ re-import would mean the split crept back.
+ """
+ import importlib
+
+ for name in ("whatsapp_business_template", "whatsapp_business_interactive"):
+ with pytest.raises(ModuleNotFoundError):
+ importlib.import_module(f"nodes.whatsapp_business.{name}")
+
+ def test_absorbed_types_are_not_registered(self):
+ import nodes # noqa: F401 -- triggers discovery
+ from models.node_metadata import NODE_METADATA
+
+ assert "whatsappBusinessTemplate" not in NODE_METADATA
+ assert "whatsappBusinessInteractive" not in NODE_METADATA
+ assert "whatsappBusinessSend" in NODE_METADATA
+
+
+class TestNewMessageTypes:
+ def test_reaction_addresses_its_target_and_never_quotes(self):
+ """A reaction points at its target through reaction.message_id.
+
+ Adding a `context` block as well is a different thing (a quoted
+ reply), so reply_to_message_id must be ignored here.
+ """
+ captured = _capture(
+ {
+ "operation": "send_reaction",
+ "to": "+14155551234",
+ "reaction_message_id": "wamid.TARGET",
+ "emoji": "\N{THUMBS UP SIGN}",
+ "reply_to_message_id": "wamid.SOMETHINGELSE",
+ }
+ )
+ assert captured["body"]["type"] == "reaction"
+ assert captured["body"]["reaction"] == {
+ "message_id": "wamid.TARGET",
+ "emoji": "\N{THUMBS UP SIGN}",
+ }
+ assert "context" not in captured["body"]
+
+ def test_empty_emoji_is_allowed_because_it_removes_a_reaction(self):
+ """Meta documents "" as the removal signal, so it is not an error."""
+ captured = _capture(
+ {
+ "operation": "send_reaction",
+ "to": "+14155551234",
+ "reaction_message_id": "wamid.TARGET",
+ "emoji": "",
+ }
+ )
+ assert captured["body"]["reaction"]["emoji"] == ""
+
+ def test_reaction_without_a_target_is_refused(self):
+ captured = _capture(
+ {"operation": "send_reaction", "to": "+14155551234", "emoji": "x"}
+ )
+ assert captured["envelope"]["success"] is False
+ assert captured["envelope"]["error_type"] == "NodeUserError"
+
+ def test_location_sends_coordinates(self):
+ captured = _capture(
+ {
+ "operation": "send_location",
+ "to": "+14155551234",
+ "latitude": 12.9716,
+ "longitude": 77.5946,
+ }
+ )
+ assert captured["body"]["type"] == "location"
+ assert captured["body"]["location"] == {"latitude": 12.9716, "longitude": 77.5946}
+
+ def test_location_address_is_nested_under_a_name(self):
+ """Meta only renders an address alongside a name; alone it is dropped."""
+ captured = _capture(
+ {
+ "operation": "send_location",
+ "to": "+14155551234",
+ "latitude": 1.0,
+ "longitude": 2.0,
+ "location_address": "221B Baker Street",
+ }
+ )
+ assert "address" not in captured["body"]["location"]
+
+ captured = _capture(
+ {
+ "operation": "send_location",
+ "to": "+14155551234",
+ "latitude": 1.0,
+ "longitude": 2.0,
+ "location_name": "Home",
+ "location_address": "221B Baker Street",
+ }
+ )
+ assert captured["body"]["location"]["address"] == "221B Baker Street"
+
+ @pytest.mark.parametrize(
+ "lat,lon",
+ [(91.0, 0.0), (-91.0, 0.0), (0.0, 181.0), (0.0, -181.0)],
+ )
+ def test_out_of_range_coordinates_fail_locally(self, lat, lon):
+ captured = _capture(
+ {"operation": "send_location", "to": "+14155551234", "latitude": lat, "longitude": lon}
+ )
+ assert captured["envelope"]["success"] is False
+
+ def test_missing_coordinate_is_refused(self):
+ captured = _capture(
+ {"operation": "send_location", "to": "+14155551234", "latitude": 1.0}
+ )
+ assert captured["envelope"]["success"] is False
+
+ def test_contacts_sends_the_list_verbatim(self):
+ card = {
+ "name": {"formatted_name": "Ada Lovelace", "first_name": "Ada"},
+ "phones": [{"phone": "+14155551234", "type": "CELL"}],
+ }
+ captured = _capture(
+ {"operation": "send_contacts", "to": "+14155551234", "contacts": [card]}
+ )
+ assert captured["body"]["type"] == "contacts"
+ assert captured["body"]["contacts"] == [card]
+
+ def test_contact_without_formatted_name_is_refused(self):
+ """Meta rejects the card outright; failing locally names the field."""
+ captured = _capture(
+ {
+ "operation": "send_contacts",
+ "to": "+14155551234",
+ "contacts": [{"phones": [{"phone": "+1"}]}],
+ }
+ )
+ assert captured["envelope"]["success"] is False
+ assert "formatted_name" in captured["envelope"]["error"]
+
+ def test_contacts_accepts_a_stringified_list(self):
+ """LLM tool arguments routinely arrive as JSON strings."""
+ captured = _capture(
+ {
+ "operation": "send_contacts",
+ "to": "+14155551234",
+ "contacts": '[{"name": {"formatted_name": "Ada"}}]',
+ }
+ )
+ assert captured["body"]["contacts"] == [{"name": {"formatted_name": "Ada"}}]
+
+
+class TestAbsorbedTemplateAndInteractive:
+ """The merged operations keep the payloads their old nodes produced."""
+
+ def test_template_envelope_survives_the_merge(self):
+ captured = _capture(
+ {
+ "operation": "send_template",
+ "to": "+14155551234",
+ "template_name": "order_update",
+ "language_code": "en_US",
+ "body_parameters": ["A", "B"],
+ }
+ )
+ assert captured["body"]["type"] == "template"
+ assert captured["body"]["template"]["name"] == "order_update"
+ assert captured["body"]["template"]["language"] == {"code": "en_US"}
+ assert captured["body"]["template"]["components"] == [
+ {"type": "body", "parameters": [{"type": "text", "text": "A"}, {"type": "text", "text": "B"}]}
+ ]
+
+ def test_named_parameters_win_over_positional(self):
+ """A named template rejects positional values with 132000."""
+ captured = _capture(
+ {
+ "operation": "send_template",
+ "to": "+14155551234",
+ "template_name": "t",
+ "body_parameters": ["positional"],
+ "named_parameters": {"customer": "Ada"},
+ }
+ )
+ params = captured["body"]["template"]["components"][0]["parameters"]
+ assert params == [{"type": "text", "parameter_name": "customer", "text": "Ada"}]
+
+ def test_list_templates_hits_the_waba_endpoint_not_messages(self):
+ """The one WABA-scoped call in the node. A phone-scoped path 404s."""
+ captured = _capture(
+ {"operation": "list_templates"},
+ number="WABA123",
+ result={"data": [{"name": "t", "status": "APPROVED"}]},
+ )
+ assert captured["path"] == "WABA123/message_templates"
+
+ def test_buttons_envelope_survives_the_merge(self):
+ captured = _capture(
+ {
+ "operation": "send_buttons",
+ "to": "+14155551234",
+ "body": "Confirm?",
+ "buttons": [{"id": "yes", "title": "Yes"}],
+ }
+ )
+ assert captured["body"]["type"] == "interactive"
+ assert captured["body"]["interactive"]["type"] == "button"
+ assert captured["body"]["interactive"]["action"]["buttons"] == [
+ {"type": "reply", "reply": {"id": "yes", "title": "Yes"}}
+ ]
+ assert captured["body"]["interactive"]["body"] == {"text": "Confirm?"}
+
+ def test_more_than_three_buttons_is_refused(self):
+ captured = _capture(
+ {
+ "operation": "send_buttons",
+ "to": "+14155551234",
+ "body": "Pick",
+ "buttons": [{"id": str(i), "title": str(i)} for i in range(4)],
+ }
+ )
+ assert captured["envelope"]["success"] is False
+
+ def test_list_row_cap_is_across_all_sections(self):
+ sections = [
+ {"title": "A", "rows": [{"id": f"a{i}", "title": f"a{i}"} for i in range(6)]},
+ {"title": "B", "rows": [{"id": f"b{i}", "title": f"b{i}"} for i in range(6)]},
+ ]
+ captured = _capture(
+ {"operation": "send_list", "to": "+14155551234", "body": "Pick", "sections": sections}
+ )
+ assert captured["envelope"]["success"] is False
+ assert "across every section" in captured["envelope"]["error"]
+
+ def test_cta_url_payload_shape(self):
+ captured = _capture(
+ {
+ "operation": "send_cta_url",
+ "to": "+14155551234",
+ "body": "Open it",
+ "cta_display_text": "Open",
+ "cta_url": "https://example.com",
+ }
+ )
+ assert captured["body"]["interactive"] == {
+ "type": "cta_url",
+ "action": {
+ "name": "cta_url",
+ "parameters": {"display_text": "Open", "url": "https://example.com"},
+ },
+ "body": {"text": "Open it"},
+ }
+
+ def test_interactive_header_is_text_typed(self):
+ captured = _capture(
+ {
+ "operation": "send_cta_url",
+ "to": "+14155551234",
+ "body": "b",
+ "header": "Title",
+ "cta_display_text": "Open",
+ "cta_url": "https://example.com",
+ }
+ )
+ assert captured["body"]["interactive"]["header"] == {"type": "text", "text": "Title"}
+
+ def test_interactive_never_quotes(self):
+ """Meta rejects `context` alongside an interactive payload."""
+ captured = _capture(
+ {
+ "operation": "send_buttons",
+ "to": "+14155551234",
+ "body": "b",
+ "buttons": [{"id": "y", "title": "Y"}],
+ "reply_to_message_id": "wamid.P",
+ }
+ )
+ assert "context" not in captured["body"]
+
+
+class TestFileWidgetVisibility:
+ def test_media_picker_is_gated_on_operation_as_well_as_source(self):
+ """media_source defaults to "file", so keying on it alone rendered the
+ file picker while the operation was send_text."""
+ show = WhatsAppBusinessSendParams.model_fields["media"].json_schema_extra["displayOptions"]["show"]
+ assert show["operation"] == ["send_media"]
+ assert show["media_source"] == ["file"]
+
+
class TestParamsShape:
def test_phone_number_id_is_not_a_parameter(self):
"""It selects the business identity a message is sent FROM.