Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs: WhatsApp Business reference, trigger-filter contract, icon refs
trohitgacce6581f862
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8e293d10..32592f1a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -27,6 +27,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Proxy Service](./docs-internal/proxy_service.md)** | Residential proxy provider management with template-based URL formatting, health scoring, and transparent HTTP node injection || **[Email Service](./docs-internal/email_service.md)** | IMAP/SMTP integration via Himalaya CLI with EmailService orchestrator, provider presets, custom credential fallback, and polling triggers || **[Browser Harness](./docs-internal/browser_harness.md)** | Wave 19 — `browserHarness` node integrating browser-use/browser-harness (alpha, raw CDP against the user's REAL Chrome; no Playwright). Primary op `run_python` pipes agent-authored Python to the CLI stdin against ~25 pre-imported helpers (see→act→verify loop: `capture_screenshot` → `click_at_xy` → `wait_for_load` → `js`). uv-tool install under `packages/browser-harness/`; daemon state pinned to `daemons/browser-harness/` via `BH_RUNTIME_DIR`/`BH_TMP_DIR`; Windows OK (token-auth TCP loopback IPC). Sibling of the stable `browser` node (agent-browser `@eN` refs) — NOT a replacement. Chrome must be CDP-reachable (`BU_CDP_URL` / chrome://inspect / `--remote-debugging-port`); `doctor` op diagnoses. Skill: `skills/web_agent/browser-harness-skill/`. |+| **[WhatsApp Business Service](./docs-internal/whatsapp_business_service.md)** | Official Meta Cloud API plugin in [`server/nodes/whatsapp_business/`](./server/nodes/whatsapp_business/) — **distinct from `nodes/whatsapp/`**, which is a personal account over an unofficial Go bridge; they share no node type, credential or palette group. Four nodes: `whatsappBusinessSend` (10 ops — Meta models message type as a *field* on one `/messages` endpoint, so text / media / template / interactive are operations, not nodes), `whatsappBusinessMedia` (the one genuinely separate endpoint family), and the `Receive` / `Status` triggers (kept separate because a canary trigger registers exactly one CloudEvents type). `phone_number_id` is deliberately **absent from Params** — on a dual-purpose ActionNode `execute_as_tool` merges `{**node_params, **tool_args}`, so a declared field is model-settable and a prompt injection could choose the sending identity; it comes from the credential only. Webhook via `register_webhook_source` on the shared catch-all, `X-Hub-Signature-256` HMAC failing closed, composite `wamid:status` dedup ids so `sent→delivered→read` don't collapse. || **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. || **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). npm install into the shared packages tree (pinned version). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. || **[GitHub Service](./docs-internal/github_service.md)** | GitHub CLI integration — `githubAction` (repo_clone / pr_create / pr_list / pr_merge / issue_create / issue_list + `custom` passthrough; AI tool `github`). **Strict Stripe pattern: the gh CLI owns its own auth** — no token stored/injected by OpenCompany, no auth pre-flight (gh's own error surfaces), marker OAuth row for the modal badge, fieldless catalogue entry. Login = spawned `gh auth login --hostname github.com --git-protocol https --web` — source-verified: headless takes the `isInteractive=false` branch (no Press-Enter), prints one-time code + `github.com/login/device` URL on stderr; the modal shows the code via the generic `verificationCode` plumbing (`useCredentialPanel` → `OAuthConnect`). `login_env()` strips `GH_TOKEN`/`GITHUB_TOKEN` (login aborts otherwise). Success gate = `gh auth status` exit 0, then best-effort **`gh auth setup-git`** (official bridge — the future git node needs zero auth code). gh binary: **project-local, pooch-driven** (temporal `_install.py` idiom) — pinned release under `package_dir("gh")`, system gh never consulted (auth state still shared: gh config paths are user-level). Palette group `vcs`. |@@ -568,11 +569,13 @@ The frontend uses a layered cache + slice-subscription model so cold refreshes a### Icon + color — per-plugin folder + visuals.json fallback-Plugin icons and colors live co-located in the plugin folder; `visuals.json` is the fallback registry for emoji / library icons and the skill reverse-map. Full resolution chain (per-node-type → shared → fallback) is documented in [server/nodes/README.md → Icon + color](./server/nodes/README.md) and [docs-internal/plugin_system.md](./docs-internal/plugin_system.md).+Plugin icons and colors live co-located in the plugin folder; `visuals.json` is the legacy central registry for plugins that predate it. Resolution chain: **co-located SVG (`icon_<nodeType>.svg` → `icon.svg`) → the plugin's own `meta.json` → `visuals.json`**, documented in [server/nodes/README.md → Icon + color](./server/nodes/README.md) and [docs-internal/plugin_system.md](./docs-internal/plugin_system.md).++**Prefer a library reference over vendored artwork.** `meta.json` carries icons as well as colour — `"icons": {"<nodeType>": "lucide:Send"}` per node type, or `"icon"` for the whole folder (the same specificity pair as `icon_<nodeType>.svg` / `icon.svg`). Ship an SVG only for artwork no library has, typically a brand mark. Two traps: a **file always beats a meta.json ref**, so a folder shipping `icon.svg` shadows refs for every node type in it (this is why the four WhatsApp Business nodes once rendered one glyph); and `lucide:` names are matched against the package's **export** identifiers, so `lucide:CheckCheck` resolves and the kebab-case `lucide:check-check` silently renders nothing. Locked from both sides — `client/src/assets/icons/index.test.ts` walks every `meta.json` under `server/nodes` and asserts each ref resolves to a real component; `test_node_spec.py` asserts every `icons` key is a registered node type.Backend endpoints serve SVGs at `GET /api/schemas/nodes/<type>/icon` (plugin icons) and `GET /api/schemas/credentials/<provider>/icon` (credential brand icons). Frontend resolver at [client/src/assets/icons/index.ts](./client/src/assets/icons/index.ts) dispatches `lib:brand` / URL passthrough / emoji / `asset:<key>`. The `asset:` branch is currently inert at runtime (the frontend `ICON_REGISTRY` glob finds no SVGs so it resolves to null) but it is NOT dead code — the backend still emits `asset:google` / `asset:stripe` for palette groups (`server/nodes/groups.py`) and the format is invariant-tested on both sides (`test_node_spec.py` Wave 10.B, `icons/index.test.ts`).-**Do not** declare `icon` / `color` as class attributes on a node (the override path was removed in F1). Drop `icon.svg` (or `icon_<nodeType>.svg` for multi-node folders like whatsapp) and `meta.json` into the plugin folder. SKILL.md icon/color resolves from the first node in `allowed-tools` — only orphan skills keep inline `metadata.icon` / `metadata.color`.+**Do not** declare `icon` / `color` as class attributes on a node (the override path was removed in F1). Put `meta.json` in the plugin folder (colour, plus icon refs as above), and `icon.svg` / `icon_<nodeType>.svg` only when artwork is genuinely needed. SKILL.md icon/color resolves from the first node in `allowed-tools` — only orphan skills keep inline `metadata.icon` / `metadata.color`.## Key Files & Componentsdiff --git a/docs-internal/event_framework.md b/docs-internal/event_framework.mdindex 92c30e3f..edecc356 100644--- a/docs-internal/event_framework.md+++ b/docs-internal/event_framework.md@@ -274,7 +274,13 @@ Locked by `TestCloudEventTypeMatchesSearchAttribute` in [`test_canary_registry.p`event_waiter.dispatch` / `broadcaster.send_custom_event` calls inside canary-registered plugin `_events.py` files (chat / webhook / task / telegram / email) had zero consumers in canary-on mode — the deployment manager skips `setup_event_trigger` when `is_canary_trigger_type(...)` is True, so no legacy waiter ever registered. Removed.-- `dispatch.emit(envelope, wire_routing_key=...)` is the single delivery path. It signals legacy `EventType` consumers and running workflow controllers through one Temporal Visibility query, while broadcasting to the frontend on the same wire key. Each controller filters against its durable trigger registry.+- `dispatch.emit(envelope, wire_routing_key=...)` is the single delivery path. It signals legacy `EventType` consumers and running workflow controllers through one Temporal Visibility query, while broadcasting to the frontend on the same wire key. Each controller filters against its durable trigger registry — note this is a match on the **CloudEvents type**, not on the trigger node's own parameters.++- **The trigger node's own filter is applied in `TriggerListenerWorkflow._spawn_child_run`**, gated on the `machina-trigger-listener-node-filter` patch. That method is the single choke point: `WorkflowControlWorkflow._spawn_push_run` constructs a `TriggerListenerWorkflow` purely to call it, so both the controller path and the legacy listener path go through one branch. The predicate runs in `evaluate_trigger_filter_activity` rather than inline, because filter builders live in plugin folders and reach imports the workflow sandbox forbids; the recorded boolean keeps replay deterministic. It receives the CloudEvents **`data` member, not the envelope** (`event_waiter.dispatch` unpacks to `(event_type, data)` and hands filters the inner payload), and fails **open** — an unknown node type, malformed payload or raising builder all admit the event, because over-firing is recoverable while a dropped trigger event looks like a broken product.++ Before this, `filter_params` was carried in `listener_data` and never read, so the `EventType` Search Attribute was the only narrowing and every event of the right type spawned a run: a `webhookTrigger` bound to `/a` fired on a POST to `/b` (all webhooks share one CloudEvents type and are unscoped), a `taskTrigger` watching one agent fired on every task, and a `whatsappReceive` scoped to one group fired on every message. The canvas-Run path applied these filters, so Run and deploy disagreed about what the same node does.++ `listener_data["filter_params"]` is the only possible source: the graph snapshot carries no parameters (`node.data` holds just the label, and `load_persisted_workflow_graph_activity` returns nodes and edges only), so the hot graph re-read cannot supply them. Editing a deployed trigger's filter therefore takes effect on **re-deploy** — consistent with the trigger node itself, which is pre-executed with the event as its output and never re-reads its parameters at run time.- For workflow-control generations, trigger definitions, push-event signals,and polling activities live directly in the generation's`WorkflowControlWorkflow`. There are no separate listener workflow runs;diff --git a/docs-internal/node-logic-flows/README.md b/docs-internal/node-logic-flows/README.mdindex 77e22c91..93a2b54b 100644--- a/docs-internal/node-logic-flows/README.md+++ b/docs-internal/node-logic-flows/README.md@@ -12,8 +12,10 @@ match its doc here, and each doc must still describe what the code does.- **Refactoring a node**: update the matching contract test in`server/tests/nodes/test_<category>.py` *first*, then change the handler,then update this doc.-- **The index below is maintained by hand** (there is no generator script- currently). When you add, rename, or remove a card, update its entry below.+- **The index below is generated.** Run `company docs nodes` after adding,+ renaming or removing a card; `company docs nodes --check` fails when a+ registered node has no card. Do not hand-edit between the+ `AUTO-GENERATED-INDEX` markers.## Conventions@@ -26,7 +28,7 @@ match its doc here, and each doc must still describe what the code does.## Index-<!-- INDEX-START (manually maintained; filenames are camelCase of the plugin `type`) -->+<!-- AUTO-GENERATED-INDEX-START -->### ai_agents@@ -82,8 +84,8 @@ match its doc here, and each doc must still describe what the code does.- [Chat History (`chatHistory`)](./chat_utility/chatHistory.md)- [Chat Send (`chatSend`)](./chat_utility/chatSend.md)- [Console (`console`)](./chat_utility/console.md)-- [Create Map (`gmaps_create`)](./chat_utility/gmaps_create.md)- [File Handler (`fileHandler`)](./chat_utility/fileHandler.md)+- [Create Map (`gmaps_create`)](./chat_utility/gmaps_create.md)- [Team Monitor (`teamMonitor`)](./chat_utility/teamMonitor.md)- [Text Generator (`textGenerator`)](./chat_utility/textGenerator.md)@@ -134,9 +136,6 @@ match its doc here, and each doc must still describe what the code does.### language-Sarvam AI's non-chat REST APIs. The chat models live under `ai_chat_models`-and share the same credential.-- [Detect Language (`detectLanguage`)](./language/detectLanguage.md)- [Speech to Text (`speechToText`)](./language/speechToText.md)- [Text to Speech (`textToSpeech`)](./language/textToSpeech.md)@@ -194,6 +193,13 @@ and share the same credential.- [WhatsApp Receive (`whatsappReceive`)](./whatsapp/whatsappReceive.md)- [WhatsApp Send (`whatsappSend`)](./whatsapp/whatsappSend.md)+### whatsapp_business++- [WhatsApp Business Media (`whatsappBusinessMedia`)](./whatsapp_business/whatsappBusinessMedia.md)+- [WhatsApp Business Receive (`whatsappBusinessReceive`)](./whatsapp_business/whatsappBusinessReceive.md)+- [WhatsApp Business Send (`whatsappBusinessSend`)](./whatsapp_business/whatsappBusinessSend.md)+- [WhatsApp Business Status (`whatsappBusinessStatus`)](./whatsapp_business/whatsappBusinessStatus.md)+### workflow_triggers- [Chat Trigger (`chatTrigger`)](./workflow_triggers/chatTrigger.md)@@ -204,4 +210,4 @@ and share the same credential.- [Webhook Response (`webhookResponse`)](./workflow_triggers/webhookResponse.md)- [Webhook Trigger (`webhookTrigger`)](./workflow_triggers/webhookTrigger.md)-<!-- INDEX-END -->+<!-- AUTO-GENERATED-INDEX-END -->diff --git a/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessMedia.md b/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessMedia.mdnew file mode 100644index 00000000..92c3f183--- /dev/null+++ b/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessMedia.md@@ -0,0 +1,119 @@+# WhatsApp Business Media (`whatsappBusinessMedia`)++| Field | Value |+|------|-------|+| **Category** | whatsapp_business / tool (dual-purpose) |+| **Backend handler** | [`server/nodes/whatsapp_business/whatsapp_business_media.py`](../../../server/nodes/whatsapp_business/whatsapp_business_media.py) (`WhatsAppBusinessMediaNode`) |+| **Tests** | [`server/tests/nodes/test_whatsapp_business.py`](../../../server/tests/nodes/test_whatsapp_business.py) |+| **Skill (if any)** | none |+| **Dual-purpose tool** | yes - tool name `whatsapp_business_media` |++## Purpose++Upload media to WhatsApp, resolve or download media from an inbound message,+and delete it. This is the one part of the Cloud API surface that is a+**genuinely separate endpoint family** (`POST /{phone-number-id}/media`,+`GET`/`DELETE /{media-id}`), which is why it stays its own node while every+message type collapsed into `whatsappBusinessSend`.++It exists as a node rather than an `auto_download` flag on the trigger for two+reasons: shaping runs inside the webhook request, where Meta expects a prompt+200 and retries anything slower; and the deployed trigger path never runs the+node body, so a download there would be unreachable once deployed. Wiring+`whatsappBusinessReceive -> whatsappBusinessMedia` keeps the fetch on the+workflow's own time.++## Inputs (handles)++| Handle | Connection type | Required | Purpose |+|--------|-----------------|----------|---------|+| `input-main` | main | no | Typically the trigger output, carrying `media.id` |++## Parameters++| Name | Type | Default | Shown when | Description |+|------|------|---------|-----------|-------------|+| `operation` | options | `download` | always | `upload` / `get_url` / `download` / `delete` |+| `media_id` | string | `""` | get_url, download, delete | Inbound messages carry one on `media.id` |+| `file` | file | `null` | upload | Workspace file to upload |+| `mime_type` | string | `""` | upload | Overrides the detected type |++## Outputs (handles)++| Handle | Shape | Description |+|--------|-------|-------------|+| `output-main` | object | Media metadata; `download` adds a workspace `FileRef` |++### Output payload (TypeScript shape)++```ts+{+ media_id?: string;+ url?: string; // get_url+ mime_type?: string;+ sha256?: string;+ file_size?: number;+ file?: FileRef; // download - a reference, never bytes+ files?: FileRef[];+ success?: boolean; // delete+}+```++## Logic Flow++```mermaid+flowchart TD+ A{operation}+ A -- upload --> B[coerce_file_param] --> C{size <= per-kind cap?}+ C -- no --> X[NodeUserError naming the cap]+ C -- yes --> D[POST phone_number_id/media] --> R[media_id]+ A -- get_url --> E[GET media_id] --> R2[url + metadata]+ A -- download --> F[GET media_id to resolve a FRESH url]+ F -- no url --> X2[NodeUserError: media older than 30 days is deleted]+ F -- ok --> G[fetch_to_workspace with bearer header] --> R3[FileRef]+ A -- delete --> H[DELETE media_id] --> R4[success]+```++## Decision Logic++- **`download` resolves the URL immediately before fetching**, never trusting+ one carried from an earlier node: Meta's media URLs expire after five+ minutes, so resolving here is what makes the operation survive a retry.+- The media URL is **authenticated despite being signed**, so the bearer token+ is still sent on the fetch.+- Per-kind size caps are enforced **before** upload so an oversize file fails+ locally with a useful message instead of as a generic `131053`.+- `_kind_for` maps `image/webp` to `sticker`; other `image`/`audio`/`video`+ map by MIME prefix; everything else is `document`.++## Side Effects++- **External API calls**: Graph media endpoints, bearer auth.+- **File I/O**: `download` writes into the workflow workspace via+ `fetch_to_workspace`; `upload` reads a workspace file via+ `coerce_file_param` (containment enforced).+- **Cost tracking**: `upload` and `download` declare `cost={...}`.++## External Dependencies++- **Credentials**: `WhatsAppBusinessCredential`.+- **Services**: `services.media` (`coerce_file_param`, `fetch_to_workspace`,+ `preview.preview_kind`).++## Edge cases & known limits++- **Results carry a `FileRef`, never bytes.** A node result is persisted,+ broadcast, retained in status, copied into downstream activity inputs and —+ because this node is agent-callable — serialized into LLM context. A base64+ payload would blow Temporal's blob limit and re-bill the provider on retry.+- **`download` never claims `kind="audio"`.** That kind asserts a real+ container probe (`inspect_audio`), which a download does not perform; a+ fabricated duration would mis-bill per-second providers downstream. It+ returns `image` / `video` / `file` only.+- Meta deletes media after 30 days; `get_url` / `download` then return no URL.+- Size caps: audio/video 16 MB, image 5 MB, sticker 500 KB, document 100 MB.++## Related++- **Architecture docs**: [WhatsApp Business Service](../../whatsapp_business_service.md), [Media Transport](../../media_transport.md)+- **Upstream node**: [`whatsappBusinessReceive`](./whatsappBusinessReceive.md)diff --git a/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessReceive.md b/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessReceive.mdnew file mode 100644index 00000000..4d3cbc84--- /dev/null+++ b/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessReceive.md@@ -0,0 +1,109 @@+# WhatsApp Business Receive (`whatsappBusinessReceive`)++| Field | Value |+|------|-------|+| **Category** | whatsapp_business / trigger |+| **Backend handler** | [`server/nodes/whatsapp_business/whatsapp_business_receive.py`](../../../server/nodes/whatsapp_business/whatsapp_business_receive.py) (`WhatsAppBusinessReceiveNode`, on the shared `_WhatsAppBusinessTrigger` base); webhook plumbing in [`_source.py`](../../../server/nodes/whatsapp_business/_source.py) |+| **Tests** | [`server/tests/nodes/test_whatsapp_business.py`](../../../server/tests/nodes/test_whatsapp_business.py) |+| **Skill (if any)** | none |+| **Dual-purpose tool** | no (trigger) |++## Purpose++Fire when a WhatsApp user messages the business number. Inbound deliveries+arrive on the shared webhook `POST /webhook/whatsapp-business`, are+signature-verified, fanned out per event, and emitted as CloudEvents of type+`com.opencompany.whatsapp_business.message.received`.++## Inputs (handles)++None — this is a trigger; it is the head of a run.++## Parameters++`BaseTriggerParams` only, whose `event_type_filter` is prefixed with+`com.opencompany.whatsapp_business.message.` by `WebhookTriggerNode`.++## Outputs (handles)++| Handle | Shape | Description |+|--------|-------|-------------|+| `output-main` | object | The flat shaped message (`WhatsAppBusinessReceiveOutput`) |++### Output payload (TypeScript shape)++```ts+{+ message_id: string; // wamid - the dedup key+ from: string; // sender wa_id (field is `from_` in Python)+ timestamp: string;+ type: string; // text | image | interactive | ...+ text?: string;+ contact_name?: string;+ phone_number_id?: string;+ media?: { id, mime_type, sha256, filename, caption, voice };+ interactive_reply?: { id, title, type };+ context_message_id?: string; // set when the user replied to a message+}+```++## Logic Flow++```mermaid+flowchart TD+ A[POST /webhook/whatsapp-business] --> B[MetaHubVerifier: X-Hub-Signature-256]+ B -- mismatch --> R400[400]+ B -- secret unavailable --> R503[503 + Retry-After]+ B -- ok --> C[iter_events: entry[] -> changes[] -> value.messages[]]+ C --> D[shape_message] --> E[emit_message_received via dispatch.emit]+ E --> F[Temporal listener signalled by EventType SA]+ F --> G[node filter gates the spawn] --> H[child MachinaWorkflow run]+ C --> I[event_waiter.dispatch] --> J[canvas Run path]+```++## Decision Logic++- **Signature verification fails closed**: no secret configured → `503` with+ `Retry-After`, mismatch → `400`.+- **`_check_precondition`** fails fast on the canvas when the credential is+ missing or `whatsapp_business_app_secret` is unset, instead of waiting out+ the 24-hour trigger timeout.+- **`shape_output` returns `event.data` flat**, matching what the deployed+ path hands downstream. The base default would dump the whole CloudEvents+ envelope, which made `{{trigger.text}}` resolve when deployed and break on+ Run.+- **Account-level `value.errors[]` are logged only**, never emitted.++## Side Effects++- **Broadcasts**: CloudEvents on wire key `whatsapp_business_message_received`.+- **Spawns**: one child `MachinaWorkflow` per admitted event when deployed.++## External Dependencies++- **Credentials**: `WhatsAppBusinessCredential` — `whatsapp_business_app_secret`+ is required for inbound (HMAC key), `whatsapp_business_verify_token` for the+ GET subscription handshake.++## Edge cases & known limits++- **The trigger never downloads media.** It carries a `media.id`; wire+ [`whatsappBusinessMedia`](./whatsappBusinessMedia.md) downstream to fetch.+ Downloading inside the webhook would delay Meta's expected prompt 200 and is+ unreachable on the deployed path anyway.+- **Dedup ids**: messages use the bare `wamid`, so Meta's 7-day retries+ collapse to one run.+- **Two nodes, not one with a mode switch.** A canary trigger registers exactly+ one CloudEvents type (`canary_registry` is a `str -> str` map and the listener+ carries a single `EventType` keyword Search Attribute), and the message and+ status payloads share almost no fields.+- The GET handshake returns a **bare `text/plain` body** — Meta rejects the+ router's JSON envelope.+- Meta's Messenger docs claim the signature is computed over an escaped-unicode+ rendering; this implementation uses raw bytes and logs a diagnostic when a+ failure coincides with non-ASCII input.++## Related++- **Architecture docs**: [WhatsApp Business Service](../../whatsapp_business_service.md), [Event Framework](../../event_framework.md)+- **Sibling**: [`whatsappBusinessStatus`](./whatsappBusinessStatus.md)diff --git a/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessSend.md b/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessSend.mdnew file mode 100644index 00000000..7c5875fb--- /dev/null+++ b/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessSend.md@@ -0,0 +1,165 @@+# WhatsApp Business Send (`whatsappBusinessSend`)++| Field | Value |+|------|-------|+| **Category** | whatsapp_business / tool (dual-purpose) |+| **Backend handler** | [`server/nodes/whatsapp_business/whatsapp_business_send.py`](../../../server/nodes/whatsapp_business/whatsapp_business_send.py) (`WhatsAppBusinessSendNode`); one `@Operation` per message type, all through [`_base.graph_post`](../../../server/nodes/whatsapp_business/_base.py) |+| **Tests** | [`server/tests/nodes/test_whatsapp_business.py`](../../../server/tests/nodes/test_whatsapp_business.py) |+| **Skill (if any)** | none |+| **Dual-purpose tool** | yes - tool name `whatsapp_business_send` |++## Purpose++Send any Cloud API message type from the business phone number. Meta models+message type as a **field on a single endpoint**+(`POST /{phone-number-id}/messages`), not as separate endpoints, so text,+media, template and interactive are operations on this one node rather than+separate nodes. `whatsappBusinessTemplate` and `whatsappBusinessInteractive`+were folded in here for that reason.++Distinct from `whatsappSend`, which drives a *personal* account through an+unofficial Go bridge. They share no credential, no node type and no palette+group.++## Inputs (handles)++| Handle | Connection type | Required | Purpose |+|--------|-----------------|----------|---------|+| `input-main` | main | no | Upstream data for template substitution into `to`, `text`, etc. |++## Parameters++`operation` selects the message type; every other field is gated on it via+`displayOptions.show`.++| Name | Type | Default | Shown when | Notes |+|------|------|---------|-----------|-------|+| `operation` | options | `send_text` | always | See the operation table below |+| `to` | string | `""` | all send ops | International format; punctuation stripped by `normalize_recipient` |+| `reply_to_message_id` | string | `""` | text / media / location / contacts | Quotes an inbound message by wamid |+| `text`, `preview_url`, `format_markdown` | | | `send_text` | `format_markdown` converts GFM to WhatsApp syntax |+| `media_type`, `media_source`, `media`, `media_id`, `media_url`, `caption`, `media_filename` | | | `send_media` | `media` also requires `media_source == 'file'` |+| `template_name`, `language_code`, `body_parameters`, `named_parameters`, `header_media_id`, `header_media_type` | | | `send_template` | `template_name` uses `loadOptionsMethod: whatsappBusinessTemplates` |+| `body`, `header`, `footer` | | | the three interactive ops | Caps enforced locally |+| `buttons` | array | `[]` | `send_buttons` | Max 3, title max 20 |+| `list_button_text`, `sections` | | | `send_list` | Max 10 rows **across all sections** |+| `cta_display_text`, `cta_url` | | | `send_cta_url` | |+| `reaction_message_id`, `emoji` | | | `send_reaction` | Empty emoji **removes** a reaction |+| `latitude`, `longitude`, `location_name`, `location_address` | | | `send_location` | Address only rendered alongside a name |+| `contacts` | array | `[]` | `send_contacts` | Each card needs `name.formatted_name` |++There is deliberately **no `phone_number_id` parameter** — see Edge cases.++### Operations++| Operation | `type` sent | Endpoint |+|---|---|---|+| `send_text` | `text` | `{phone_number_id}/messages` |+| `send_media` | `image`/`video`/`audio`/`document`/`sticker` | `{phone_number_id}/messages` (+ `/media` upload when source is `file`) |+| `send_template` | `template` | `{phone_number_id}/messages` |+| `send_buttons` / `send_list` / `send_cta_url` | `interactive` | `{phone_number_id}/messages` |+| `send_reaction` | `reaction` | `{phone_number_id}/messages` |+| `send_location` | `location` | `{phone_number_id}/messages` |+| `send_contacts` | `contacts` | `{phone_number_id}/messages` |+| `list_templates` | — | `GET {waba_id}/message_templates` |++## Outputs (handles)++| Handle | Shape | Description |+|--------|-------|-------------|+| `output-main` | object | Send result, or the template list |++### Output payload (TypeScript shape)++```ts+{+ message_id?: string; // wamid+ to?: string; // normalized recipient+ wa_id?: string;+ phone_number_id?: string;+ message_status?: string;+ templates?: Array<{ // list_templates only+ name: string; status: string; category: string;+ language: string; placeholders: number | null;+ }>;+ count?: number; // list_templates only+}+```++## Logic Flow++```mermaid+flowchart TD+ A[_pick_operation reads raw `operation`] --> B{which op}+ B -- list_templates --> L[GET waba_id/message_templates]+ B -- send_* --> C[normalize_recipient]+ C --> D[resolve_phone_number_id from CREDENTIAL only]+ D --> E{media_source == file?}+ E -- yes --> F[_upload_for_send: POST /media with bytes] --> G+ E -- no --> G[Build type-specific sibling object]+ G --> H[_post_message: POST /messages]+ H -- non-2xx --> I[raise_for_graph_error -> classify_error]+ H -- ok --> J[_shape_send_result]+```++## Decision Logic++- **`operation` is load-bearing.** `_pick_operation` reads it from the *raw*+ parameter dict **before** Pydantic validation, so the model default never+ applies at dispatch. Callers building raw dicts must pass it explicitly.+- **Media source is a strict oneOf.** `id` and `link` cannot both be sent, so+ exactly one is built.+- **Caption is dropped for audio and sticker** — Meta rejects it rather than+ ignoring it.+- **Named template params win over positional** — a named template rejects+ positional values with error 132000.+- **Interactive and template never carry `context`**; reaction addresses its+ target via `reaction.message_id` instead.+- **Error paths**: auth (`0`, `190`) → annotated `PermissionError`; throttle /+ transient → `RuntimeError` (retryable); permission / policy / template /+ `131047` (24-hour window closed) → `NodeUserError`.++## Side Effects++- **External API calls**: `graph.facebook.com/v25.0/...`, bearer token from the+ credential.+- **Cost tracking**: each `@Operation` declares a `cost={...}` block.+- **File I/O**: `send_media` with `media_source == 'file'` reads a workspace+ file via `coerce_file_param` (containment enforced).++## External Dependencies++- **Credentials**: `WhatsAppBusinessCredential` — `apiKey` plus+ `whatsapp_business_phone_number_id` and `whatsapp_business_waba_id`.+- **Python packages**: `httpx` (via the plugin `Connection` facade).++## Edge cases & known limits++- **`phone_number_id` is intentionally absent from `Params`.** It selects which+ business identity a message is sent *from*. On a dual-purpose `ActionNode`+ there is no way to protect a declared field: `BaseNode.execute_as_tool` sends+ `{**node_params, **tool_args}`, so model arguments win, and+ `ctx.raw["_raw_parameters"]` is that same merged dict. Sourcing it from the+ credential is the only place the model cannot reach. Locked by+ `TestModelCannotChooseTheSendingNumber`, which drives the real tool path with+ a hostile value.+- The upload posts **bytes, not a file handle** — `Connection.request` replays+ the same kwargs on its one auth retry and a consumed handle would replay+ empty.+- The kind selector is named `media_type`, **not** `message_type`:+ `ParameterRenderer.getFileAcceptType` hardcodes a switch on a sibling named+ `message_type` and would override the backend's `accept`.+- Text body caps at 4096; interactive body at 1024 (Meta's own docs disagree,+ 1024 in the OpenAPI spec vs 4096 on the interactive-list page — the smaller is+ used so failures happen at authoring time, not in front of a customer).+- `cta_url` matches Meta's documented CTA payload, but the messages reference+ schema does not enumerate it as an `interactive.type`. Unverified against a+ live send.+- Multi-number sending is deferred.++## Related++- **Architecture docs**: [WhatsApp Business Service](../../whatsapp_business_service.md)+- **Sibling nodes**: [`whatsappBusinessMedia`](./whatsappBusinessMedia.md),+ [`whatsappBusinessReceive`](./whatsappBusinessReceive.md),+ [`whatsappBusinessStatus`](./whatsappBusinessStatus.md)diff --git a/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessStatus.md b/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessStatus.mdnew file mode 100644index 00000000..97dd8a9e--- /dev/null+++ b/docs-internal/node-logic-flows/whatsapp_business/whatsappBusinessStatus.md@@ -0,0 +1,99 @@+# WhatsApp Business Status (`whatsappBusinessStatus`)++| Field | Value |+|------|-------|+| **Category** | whatsapp_business / trigger |+| **Backend handler** | [`server/nodes/whatsapp_business/whatsapp_business_receive.py`](../../../server/nodes/whatsapp_business/whatsapp_business_receive.py) (`WhatsAppBusinessStatusNode`, on the shared `_WhatsAppBusinessTrigger` base); webhook plumbing in [`_source.py`](../../../server/nodes/whatsapp_business/_source.py) |+| **Tests** | [`server/tests/nodes/test_whatsapp_business.py`](../../../server/tests/nodes/test_whatsapp_business.py) |+| **Skill (if any)** | none |+| **Dual-purpose tool** | no (trigger) |++## Purpose++Fire on delivery receipts for messages the business **sent** — `sent`,+`delivered`, `read`, `failed`. Shares the webhook, credential and verification+path with [`whatsappBusinessReceive`](./whatsappBusinessReceive.md) but carries a+different CloudEvents type (`...whatsapp_business.status.updated`) and a+different payload.++> **Note on volume.** WhatsApp emits a status callback per outbound message for+> each state transition, so this trigger typically fires 2-4x per message you+> send. Deploy it only when you actually consume receipts.++## Inputs (handles)++None — this is a trigger.++## Parameters++`BaseTriggerParams` only, whose `event_type_filter` is prefixed with+`com.opencompany.whatsapp_business.status.` by `WebhookTriggerNode`.++## Outputs (handles)++| Handle | Shape | Description |+|--------|-------|-------------|+| `output-main` | object | The flat shaped status (`WhatsAppBusinessStatusOutput`) |++### Output payload (TypeScript shape)++```ts+{+ message_id: string; // wamid of the message you sent+ status: string; // sent | delivered | read | failed+ recipient_id?: string;+ timestamp?: string;+ conversation_id?: string;+ conversation_origin?: string;+ conversation_expires_at?: string; // when the 24-hour window closes+ billable?: boolean;+ pricing_model?: string;+ pricing_category?: string;+ error_code?: number; // failed only+ error_title?: string;+ error_detail?: string;+ biz_opaque_callback_data?: string;+}+```++## Logic Flow++Identical intake to `whatsappBusinessReceive` — same route, same+`MetaHubVerifier`, same three-level fan-out — diverging at `iter_events`, which+walks `value.statuses[]` instead of `value.messages[]` and calls+`shape_status` / `emit_status_updated`.++## Decision Logic++- **Dedup id is composite**: `f"{wamid}:{status}"`. A bare wamid would make+ `sent -> delivered -> read` collapse into a single event, since all three+ carry the same message id.+- **`shape_output` returns `event.data` flat**, inherited from the shared base+ so Run and deploy cannot disagree about the output shape.+- **`_check_precondition`** is the shared one: fails fast when the credential+ or `whatsapp_business_app_secret` is missing.++## Side Effects++- **Broadcasts**: CloudEvents on wire key `whatsapp_business_status_updated`.+- **Spawns**: one child `MachinaWorkflow` per admitted event when deployed.++## External Dependencies++Same as `whatsappBusinessReceive`.++## Edge cases & known limits++- `conversation_expires_at` is the practical signal for whether a free-form+ reply is still allowed; past it, only an approved template gets through+ (error `131047`).+- `error_code` is populated only on `failed`.+- Meta's own subscription settings control whether status callbacks are+ delivered at all. If the WABA is not subscribed to the `message_status`+ field, this trigger never fires and nothing in OpenCompany reports that.++## Related++- **Architecture docs**: [WhatsApp Business Service](../../whatsapp_business_service.md), [Event Framework](../../event_framework.md)+- **Sibling**: [`whatsappBusinessReceive`](./whatsappBusinessReceive.md)+- **Template sending** (for a closed window): [`whatsappBusinessSend`](./whatsappBusinessSend.md) `send_template`diff --git a/docs-internal/whatsapp_business_service.md b/docs-internal/whatsapp_business_service.mdnew file mode 100644index 00000000..dd74ef07--- /dev/null+++ b/docs-internal/whatsapp_business_service.md@@ -0,0 +1,162 @@+# WhatsApp Business (Meta Cloud API)++Official Meta WhatsApp Business Platform integration, living entirely in+[`server/nodes/whatsapp_business/`](../server/nodes/whatsapp_business/).++**This is not the same integration as `nodes/whatsapp/`.** That one drives a+*personal* account through an unofficial Go bridge (`edgymeow`) and QR pairing.+Both ship. They share no node type, no credential id, no WebSocket key and no+palette group, because the auth models, capabilities and failure modes have+nothing in common. The Cloud API group is visible in the default palette; the+personal one is `dev`-only.++## Node surface (4 nodes)++| Node | Kind | Operations |+|---|---|---|+| `whatsappBusinessSend` | action, agent tool | `send_text`, `send_media`, `send_template`, `send_buttons`, `send_list`, `send_cta_url`, `send_reaction`, `send_location`, `send_contacts`, `list_templates` |+| `whatsappBusinessMedia` | action, agent tool | `upload`, `get_url`, `download`, `delete` |+| `whatsappBusinessReceive` | trigger | inbound messages |+| `whatsappBusinessStatus` | trigger | delivery receipts |++### Why the node split is where it is++Meta models message type as a **field on one endpoint**+(`POST /{phone-number-id}/messages`; `type` ∈ text, image, video, audio,+document, sticker, location, contacts, reaction, interactive, template), not as+separate endpoints. Splitting by message type would make the canvas imply an API+shape that does not exist, so Send carries them all as operations. Earlier+`whatsappBusinessTemplate` and `whatsappBusinessInteractive` nodes were folded+in for exactly this reason.++Media stays separate because it genuinely is a different endpoint family+(`POST /{phone-number-id}/media`, `GET`/`DELETE /{media-id}`).++The two triggers stay separate for a structural reason: a canary trigger+registers exactly **one** CloudEvents type — `canary_registry` is a `str -> str`+map and the listener carries a single `EventType` keyword Search Attribute — so+one node cannot subscribe to both. Their payloads also share almost no fields,+so merging would mean a union output schema and weaker `{{trigger.field}}`+resolution.++`list_templates` is the one WABA-scoped call kept on Send, because it exists to+answer "what can I send".++## Credential++`WhatsAppBusinessCredential` (`ApiKeyCredential`, `id="whatsapp_business"`,+bearer). One secret plus four operator-metadata fields:++| Field | Required | Purpose |+|---|---|---|+| `apiKey` | yes | System User access token |+| `whatsapp_business_waba_id` | yes | WhatsApp Business Account id — template listing |+| `whatsapp_business_phone_number_id` | yes | The number messages are sent **from** |+| `whatsapp_business_app_secret` | no* | HMAC key for `X-Hub-Signature-256`; *required for inbound* |+| `whatsapp_business_verify_token` | no* | Echoed in the GET subscription handshake |++The probe calls `GET /{waba_id}/phone_numbers` — authenticated, free, and it+validates the WABA id at the same time, returning discovered numbers with their+`quality_rating`.++### The sending number is credential-only, by design++There is deliberately **no `phone_number_id` parameter** on any node. It selects+which business identity a message is sent *from*, which is exactly what a prompt+injection in an inbound message would want to set. On a dual-purpose+`ActionNode` a declared field cannot be protected: the split-schema machinery+(`ToolInput` / `server_controlled_fields`) is a `ToolNode` extension, and+`BaseNode.execute_as_tool` sends `{**node_params, **tool_args}` for everything+else — model arguments win, and `ctx.raw["_raw_parameters"]` is that same merged+dict. Sourcing it from the credential puts it somewhere model arguments cannot+reach. Locked by `TestModelCannotChooseTheSendingNumber`, which drives the real+tool path with a hostile `phone_number_id`.++## Webhook++Claimed via `register_webhook_source(get_webhook_source())` — an *instance*, not+the class. There is no plugin router; the shared catch-all in+[`routers/webhook.py`](../server/routers/webhook.py) dispatches by path, and a+claimed path never reaches the legacy generic handler (which would otherwise+fire every deployed `webhookTrigger`).++| Route | Purpose |+|---|---|+| `GET /webhook/whatsapp-business` | Subscription handshake — compares `hub.verify_token` with `hmac.compare_digest`, echoes `hub.challenge` as **bare `text/plain`** (Meta rejects the router's JSON envelope). 403 on mismatch or unconfigured token. |+| `POST /webhook/whatsapp-business` | Deliveries — `MetaHubVerifier` (SHA-256 HMAC over the **raw body**, `X-Hub-Signature-256`, `sha256=` prefix). Fails **closed**: 503 + `Retry-After` when the secret is unavailable, 400 on mismatch. |++`iter_events` walks all three nesting levels+(`entry[] -> changes[] -> value.messages[] / statuses[] / errors[]`) and emits+one CloudEvent per item. Account-level `errors[]` are logged only.++Both delivery paths are driven: `dispatch.emit` for deployed Temporal listeners,+and `event_waiter.dispatch` for the canvas-Run path.++**Replay dedup ids.** Meta retries for 7 days. Messages use the bare `wamid`;+statuses use a composite `f"{wamid}:{status}"`, because `sent -> delivered ->+read` all carry the same message id and a bare wamid would collapse them into+one event.++**Known risk, documented in code**: Meta's *Messenger* docs claim the signature+is computed over an escaped-unicode rendering rather than raw bytes. This+implementation uses raw bytes and logs a diagnostic when a verification failure+coincides with non-ASCII bytes in the body.++## Error classification++`classify_error` splits Meta's numeric codes by retryability, which matters+because `NodeUserError` is on the framework's non-retryable list:++| Codes | Mapped to | Effect |+|---|---|---|+| `0`, `190` | `PermissionError` with `.provider` / `.reason` / `.auth` | Reconnect chip in the UI + `credential.*.runtime_failed` event |+| throttle / transient | `RuntimeError` | Retryable — preserves backoff |+| permission / policy / template / account | `NodeUserError` | One WARN line, no traceback |+| `131047` | `NodeUserError` | Bespoke message pointing at `send_template` — the 24-hour window has closed |++## Icons++All four node icons are **library references declared in the plugin's own+`meta.json`**, not vendored SVGs:++```json+{"color": "#128C7E",+ "icons": {"whatsappBusinessSend": "lucide:Send",+ "whatsappBusinessMedia": "lucide:Paperclip",+ "whatsappBusinessReceive": "lucide:Inbox",+ "whatsappBusinessStatus": "lucide:CheckCheck"}}+```++`CheckCheck` is WhatsApp's own delivery tick. `whatsapp_business.svg` remains as+the *credential* brand mark — it resolves through `Credential.get_icon_path`,+a different chain, and no library has an equivalent. See+[plugin_system.md](./plugin_system.md) for the resolution order.++## Gotchas worth knowing before editing++- **`operation` is load-bearing on Send.** `_pick_operation` reads it off the+ raw parameter dict *before* Pydantic validation, so the model default never+ applies at dispatch; raw-dict callers must pass it explicitly.+- **The kind selector is `media_type`, not `message_type`.**+ `ParameterRenderer.getFileAcceptType` hardcodes a switch on a sibling named+ `message_type` and would override the backend's declared `accept`.+- **Uploads post bytes, not a file handle** — `Connection.request` replays the+ same kwargs on its one auth retry, and a consumed handle replays empty.+- **Media travels as a reference, never bytes** — see+ [media_transport.md](./media_transport.md).+- **`shape_output` is overridden on both triggers** to return `event.data` flat,+ matching the deployed path. The base default dumps the whole CloudEvents+ envelope, which made `{{trigger.text}}` resolve when deployed and break on+ Run.++## Unverified++`cta_url` matches Meta's documented CTA payload shape, but the messages+reference schema does not enumerate it among `interactive.type` values. Not yet+confirmed against a live send.++## Related++- Per-node contracts: [`node-logic-flows/whatsapp_business/`](./node-logic-flows/whatsapp_business/)+- [Event Framework](./event_framework.md) · [Media Transport](./media_transport.md) · [Plugin System](./plugin_system.md)+- Meta docs: <https://developers.facebook.com/docs/whatsapp/cloud-api>