Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(whatsapp): media, template and interactive Cloud API nodes
trohitgcdc31f323ab6
diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.jsonindex ccff0f68..a8afa03c 100644--- a/server/config/node_allowlist.json+++ b/server/config/node_allowlist.json@@ -35,6 +35,9 @@"whatsappBusinessSend","whatsappBusinessReceive","whatsappBusinessStatus",+ "whatsappBusinessMedia",+ "whatsappBusinessTemplate",+ "whatsappBusinessInteractive","airplaneModeControl","appLauncher",diff --git a/server/nodes/whatsapp_business/__init__.py b/server/nodes/whatsapp_business/__init__.pyindex d5e0b2d0..10ae99df 100644--- a/server/nodes/whatsapp_business/__init__.py+++ b/server/nodes/whatsapp_business/__init__.py@@ -15,9 +15,17 @@ from services.deployment.canary_registry import register_canary_trigger_typefrom services.events import register_webhook_sourcefrom services.node_output_schemas import register_output_schema+from services.ws_handler_registry import register_option_loader+from ._credentials import WhatsAppBusinessCredentialfrom ._events import MESSAGE_RECEIVED_TYPE, STATUS_UPDATED_TYPE+from ._option_loaders import load_templatesfrom ._source import get_webhook_source+from .whatsapp_business_interactive import (+ WhatsAppBusinessInteractiveNode,+ WhatsAppBusinessInteractiveOutput,+)+from .whatsapp_business_media import WhatsAppBusinessMediaNode, WhatsAppBusinessMediaOutputfrom .whatsapp_business_receive import (WhatsAppBusinessReceiveNode,WhatsAppBusinessReceiveOutput,@@ -25,6 +33,10 @@ 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@@ -38,13 +50,21 @@ register_webhook_source(get_webhook_source())register_canary_trigger_type(WhatsAppBusinessReceiveNode.type, MESSAGE_RECEIVED_TYPE)register_canary_trigger_type(WhatsAppBusinessStatusNode.type, STATUS_UPDATED_TYPE)+register_option_loader("whatsappBusinessTemplates", load_templates)+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/_option_loaders.py b/server/nodes/whatsapp_business/_option_loaders.pynew file mode 100644index 00000000..56671bec--- /dev/null+++ b/server/nodes/whatsapp_business/_option_loaders.py@@ -0,0 +1,68 @@+"""``loadOptionsMethod`` loaders for the WhatsApp Business plugin.++Registered from ``__init__.py``. These run outside node execution -- the+parameter panel calls them directly -- so they build their own HTTP request+rather than going through ``ctx.connection``.+"""++from __future__ import annotations++from typing import Any, Dict, List++import httpx++from core.logging import get_logger++from ._base import GRAPH_API_VERSION, GRAPH_BASE_URL++logger = get_logger(__name__)++# Approved is the only status that can actually be sent. The others are shown+# with a marker rather than hidden, because "my template is missing from the+# dropdown" is a worse debugging experience than seeing it listed as pending.+_SENDABLE = "APPROVED"+++async def load_templates(params: Dict[str, Any]) -> List[Dict[str, Any]]:+ """Message templates for the template-name selector."""+ from services.plugin.deps import get_auth_service++ auth = get_auth_service()+ token = await auth.get_api_key("whatsapp_business")+ waba_id = await auth.get_api_key("whatsapp_business_waba_id")+ if not token or not waba_id:+ return []++ url = f"{GRAPH_BASE_URL}/{GRAPH_API_VERSION}/{waba_id}/message_templates"+ try:+ async with httpx.AsyncClient(timeout=15.0) as client:+ response = await client.get(+ url,+ headers={"Authorization": f"Bearer {token}"},+ params={"fields": "name,status,language,category", "limit": 100},+ )+ response.raise_for_status()+ payload = response.json()+ except Exception as exc:+ # A dropdown that cannot load must not break the panel; an empty list+ # leaves the field free-text, which still sends.+ logger.warning("whatsapp business: template list unavailable", error=str(exc))+ return []++ options: List[Dict[str, Any]] = []+ for item in payload.get("data") or []:+ name = item.get("name")+ if not name:+ continue+ status = str(item.get("status") or "").upper()+ language = item.get("language") or ""+ suffix = f" ({language})" if language else ""+ if status != _SENDABLE:+ suffix += f" [{status.title()}]"+ options.append({"value": name, "label": f"{name}{suffix}"})++ options.sort(key=lambda option: option["label"].lower())+ return options+++__all__ = ["load_templates"]diff --git a/server/nodes/whatsapp_business/whatsapp_business_interactive.py b/server/nodes/whatsapp_business/whatsapp_business_interactive.pynew file mode 100644index 00000000..1321c5f7--- /dev/null+++ b/server/nodes/whatsapp_business/whatsapp_business_interactive.py@@ -0,0 +1,306 @@+"""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.pynew file mode 100644index 00000000..fdbf47bb--- /dev/null+++ b/server/nodes/whatsapp_business/whatsapp_business_media.py@@ -0,0 +1,266 @@+"""whatsappBusinessMedia — upload, resolve, download and delete Meta media.++Why this is a separate node rather than an ``auto_download`` flag on the+trigger: shaping happens inside the webhook request, where Meta expects a+prompt 200 and retries anything slower, and the deployed trigger path never+runs the node body at all. Downloading there would both delay the+acknowledgement and be unreachable once deployed. Wiring+``whatsappBusinessReceive -> whatsappBusinessMedia`` keeps the fetch on the+workflow's own time.+"""++from __future__ import annotations++from typing import Any, Dict, List, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue++from ._base import (+ CREDENTIAL_ID,+ GRAPH_API_VERSION,+ GRAPH_BASE_URL,+ graph_delete,+ graph_get,+ graph_post,+ resolve_phone_number_id,+)+from ._credentials import WhatsAppBusinessCredential++# Meta's own per-kind ceilings. Enforced before upload so an oversize file+# fails locally with a useful message instead of as a generic 131053.+_MAX_BYTES = {+ "audio": 16 * 1024 * 1024,+ "document": 100 * 1024 * 1024,+ "image": 5 * 1024 * 1024,+ "sticker": 500 * 1024,+ "video": 16 * 1024 * 1024,+}+++class WhatsAppBusinessMediaParams(BaseModel):+ operation: Literal["upload", "get_url", "download", "delete"] = Field(+ default="download",+ description="What to do with the media.",+ )+ media_id: str = Field(+ default="",+ description="Meta media ID. Inbound messages carry one on `media.id`.",+ json_schema_extra={"displayOptions": {"show": {"operation": ["get_url", "download", "delete"]}}},+ )+ file: Any = Field(+ default=None,+ description="File to upload.",+ json_schema_extra={+ "widget": "file",+ "accept": "*/*",+ "displayOptions": {"show": {"operation": ["upload"]}},+ },+ )+ mime_type: str = Field(+ default="",+ description="Override the detected MIME type. Meta rejects unsupported types.",+ json_schema_extra={"displayOptions": {"show": {"operation": ["upload"]}}},+ )++ model_config = ConfigDict(extra="ignore")+++class WhatsAppBusinessMediaOutput(BaseModel):+ media_id: Optional[str] = None+ url: Optional[str] = None+ mime_type: Optional[str] = None+ sha256: Optional[str] = None+ file_size: Optional[int] = None+ # Populated by `download`. A reference, never the bytes -- a payload here+ # would be persisted, broadcast and replayed into LLM context.+ file: Optional[dict] = None+ files: List[dict] = Field(default_factory=list)+ success: Optional[bool] = None++ model_config = ConfigDict(extra="allow")+++class WhatsAppBusinessMediaNode(ActionNode):+ type = "whatsappBusinessMedia"+ display_name = "WhatsApp Business Media"+ subtitle = "Upload / download"+ group = ("whatsapp_business", "tool")+ description = "Upload media to WhatsApp, or download media from an inbound message"+ component_kind = "square"+ tool_name = "whatsapp_business_media"+ tool_description = (+ "Download media from an inbound WhatsApp message into the workflow "+ "workspace, or upload a file to WhatsApp and get a media ID for sending. "+ "Inbound messages carry the media ID on media.id."+ )+ 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++ Params = WhatsAppBusinessMediaParams+ Output = WhatsAppBusinessMediaOutput++ @Operation("upload", cost={"service": "whatsapp_business", "action": "media_upload", "count": 1})+ async def upload(+ self, ctx: NodeContext, params: WhatsAppBusinessMediaParams+ ) -> WhatsAppBusinessMediaOutput:+ from services.media import coerce_file_param++ if params.file in (None, ""):+ raise NodeUserError("Select a file to upload.")++ # One call handles all three shapes the UI can produce (workspace ref,+ # legacy base64 envelope, bare path) and enforces containment.+ filename, blob = coerce_file_param(params.file, ctx=ctx)++ mime_type = params.mime_type.strip() or _guess_mime(filename)+ kind = _kind_for(mime_type)+ cap = _MAX_BYTES.get(kind)+ if cap and len(blob) > cap:+ raise NodeUserError(+ f"{filename} is {len(blob) // (1024 * 1024)} MB; WhatsApp accepts at "+ f"most {cap // (1024 * 1024)} MB for {kind}."+ )++ phone_number_id = await resolve_phone_number_id(ctx)+ result = await graph_post(+ ctx,+ f"{phone_number_id}/media",+ files={"file": (filename, blob, mime_type)},+ data={"messaging_product": "whatsapp", "type": mime_type},+ )+ return WhatsAppBusinessMediaOutput(+ media_id=result.get("id"), mime_type=mime_type, file_size=len(blob)+ )++ @Operation("get_url")+ async def get_url(+ self, ctx: NodeContext, params: WhatsAppBusinessMediaParams+ ) -> WhatsAppBusinessMediaOutput:+ media_id = _require_media_id(params)+ phone_number_id = await resolve_phone_number_id(ctx)+ result = await graph_get(ctx, media_id, {"phone_number_id": phone_number_id})+ return WhatsAppBusinessMediaOutput(+ media_id=result.get("id") or media_id,+ url=result.get("url"),+ mime_type=result.get("mime_type"),+ sha256=result.get("sha256"),+ file_size=_as_int(result.get("file_size")),+ )++ @Operation("download", cost={"service": "whatsapp_business", "action": "media_download", "count": 1})+ async def download(+ self, ctx: NodeContext, params: WhatsAppBusinessMediaParams+ ) -> WhatsAppBusinessMediaOutput:+ """Resolve then fetch, in that order and without caching the URL.++ Meta's media URLs expire after five minutes, so resolving here rather+ than trusting one carried from an earlier node is what makes this work+ on a retry. The URL is also authenticated despite being signed, so the+ bearer token still has to be sent.+ """+ from services.media import fetch_to_workspace+ from services.media.preview import preview_kind++ media_id = _require_media_id(params)+ phone_number_id = await resolve_phone_number_id(ctx)++ resolved = await graph_get(ctx, media_id, {"phone_number_id": phone_number_id})+ url = resolved.get("url")+ if not url:+ raise NodeUserError(+ f"WhatsApp returned no download URL for media {media_id}. "+ "Media older than 30 days is deleted by Meta."+ )++ mime_type = resolved.get("mime_type") or ""+ async with ctx.connection(CREDENTIAL_ID) as conn:+ secrets = await conn.credentials()+ token = secrets.get("api_key")++ ref = await fetch_to_workspace(+ url,+ ctx=ctx,+ stem=f"whatsapp-{media_id[:12]}",+ # preview_kind maps a MIME to the renderer the UI can actually+ # show; "audio" is never claimed here because that kind asserts a+ # real container probe, which no download performs.+ kind=_ref_kind(preview_kind(mime_type)),+ headers={"Authorization": f"Bearer {token}"},+ )+ payload = ref.model_dump(mode="json")+ return WhatsAppBusinessMediaOutput(+ media_id=media_id,+ mime_type=mime_type or ref.mime_type,+ sha256=resolved.get("sha256") or ref.sha256,+ file_size=ref.size_bytes,+ file=payload,+ files=[payload],+ )++ @Operation("delete")+ async def delete(+ self, ctx: NodeContext, params: WhatsAppBusinessMediaParams+ ) -> WhatsAppBusinessMediaOutput:+ media_id = _require_media_id(params)+ phone_number_id = await resolve_phone_number_id(ctx)+ result = await graph_delete(ctx, media_id, {"phone_number_id": phone_number_id})+ return WhatsAppBusinessMediaOutput(+ media_id=media_id, success=bool(result.get("success", True))+ )+++def _require_media_id(params: WhatsAppBusinessMediaParams) -> str:+ media_id = (params.media_id or "").strip()+ if not media_id:+ raise NodeUserError(+ "No media ID supplied. An inbound WhatsApp message carries one on "+ "media.id."+ )+ return media_id+++def _guess_mime(filename: str) -> str:+ import mimetypes++ return mimetypes.guess_type(filename)[0] or "application/octet-stream"+++def _kind_for(mime_type: str) -> str:+ base = (mime_type or "").split("/")[0].lower()+ if mime_type == "image/webp":+ return "sticker"+ if base in {"image", "audio", "video"}:+ return base+ return "document"+++def _ref_kind(preview: str) -> str:+ """Map a preview verdict onto a FileRef kind.++ Never returns "audio": that kind asserts the duration came from a real+ probe, and a download measures nothing.+ """+ return preview if preview in {"image", "video"} else "file"+++def _as_int(value: Any) -> Optional[int]:+ # Meta documents file_size as a number but serialises it as a string in+ # some responses.+ try:+ return int(value) if value is not None else None+ except (TypeError, ValueError):+ return None+++__all__ = [+ "WhatsAppBusinessMediaNode",+ "WhatsAppBusinessMediaOutput",+ "WhatsAppBusinessMediaParams",+]diff --git a/server/nodes/whatsapp_business/whatsapp_business_template.py b/server/nodes/whatsapp_business/whatsapp_business_template.pynew file mode 100644index 00000000..b0a8152c--- /dev/null+++ b/server/nodes/whatsapp_business/whatsapp_business_template.py@@ -0,0 +1,272 @@+"""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",+]