Metadata-Version: 2.5
Name: meta-agent-bridge
Version: 0.1.0
Summary: Agentic-first omnichannel Meta messaging SDK (WhatsApp Cloud API, Messenger, Instagram)
Project-URL: Homepage, https://github.com/Umar4880/meta-agent-bridge
Project-URL: Repository, https://github.com/Umar4880/meta-agent-bridge
Project-URL: Issues, https://github.com/Umar4880/meta-agent-bridge/issues
Author: Rana Muhammad Umar Javed
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,async,instagram,messenger,meta,whatsapp
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.0.0
Description-Content-Type: text/markdown

<div align="center">

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.svg" />
  <source media="(prefers-color-scheme: light)" srcset="assets/banner-light.svg" />
  <img alt="meta-agent-bridge" src="assets/banner-light.svg" width="100%" />
</picture>

# meta-agent-bridge

**Agentic-first omnichannel Meta messaging SDK — one canonical schema across WhatsApp Cloud API, Messenger, and Instagram.**

[![PyPI](https://img.shields.io/pypi/v/meta-agent-bridge?color=blue)](https://pypi.org/project/meta-agent-bridge/)
[![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-3776AB.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](#disclaimer--license)
[![mypy: strict](https://img.shields.io/badge/mypy-strict-blue.svg)](pyproject.toml)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](pyproject.toml)

[Architecture](#architecture) •
[Installation](#installation) •
[Quickstart](#quickstart) •
[Capabilities](#capabilities) •
[Resumable Sends](#resumable-sends) •
[Error Handling](#error-handling) •
[Testing](#testing) •
[Roadmap](#roadmap)

</div>

---

## Why `meta-agent-bridge`

Single-tenant bot wrappers couple your agent to one Meta surface, leak HTTP clients onto message objects, or force you through paid SaaS middlemen. `meta-agent-bridge` gives AI agents direct, zero-markup control over Meta's APIs:

- **One Canonical Schema (`AgentEvent` / `AgentResponse`):** Write your LangGraph, PydanticAI, or plain Python agent once against `AgentEvent` and `AgentResponse` — never branch on Meta payload dialects.
- **4 Official Meta Surfaces (`Graph API v27.0`):** Supports **WhatsApp Cloud API**, **Facebook Messenger**, **Instagram (Facebook Login)**, and **Instagram (Instagram Direct Login)** out of the box.
- **Pure Sync Sans-I/O `core/`:** `parse_webhook()` and `compile()` run synchronously with zero `httpx` or driver imports in `core/`, making them safe for FastAPI, Celery, or unit tests.
- **JSON-Serializable Events:** Every `AgentEvent` carries `schema_version: str = "1.0"`, a deterministic `event_id: str` for deduplication, and `raw: dict[str, Any]` — with zero bound HTTP clients or `.reply()` methods.
- **Multi-Tenant Connection Pooling:** Share one `httpx.AsyncClient` across thousands of tenants; `GraphTransport` binds `Authorization: Bearer ...` and `base_url` strictly per request.
- **`UnknownEvent` Resilience:** Unrecognized webhook payloads, echo events, or future Meta fields never raise `ValidationError` — they safely yield `UnknownEvent`.

---

## Architecture

```mermaid
flowchart LR
    Agent["AI Agent / Queue Worker"] --> Bridge["bridge.py (SocialBridge)"]
    Webhook["FastAPI / Webhook Route"] --> Bridge
    Bridge --> Drivers["drivers/ (whatsapp.py, meta_messaging.py)"]
    Bridge --> Transport["transport/ (GraphTransport, MediaDownloader)"]
    Drivers --> Core["core/ (Pure Sync Sans-I/O: models, compiler, crypto, capabilities, errors)"]
    Transport --> Core
    Transport --> WA["graph.facebook.com (WhatsApp Cloud API)"]
    Transport --> FB["graph.facebook.com (Messenger & IG FB Login)"]
    Transport --> IG["graph.instagram.com (IG Direct Login)"]
```

**Strict Dependency Direction:** `bridge.py` → `drivers/` & `transport/` → `core/`.
`core/` never imports from `drivers/`, `transport/`, or `httpx`. `SocialBridge` is lazily exported at the package root so importing `meta_agent_bridge.core` stays completely sans-I/O.

<details>
<summary>Package Layout</summary>

```text
src/meta_agent_bridge/
├── core/                  # Pure sync sans-I/O (zero httpx or driver imports)
│   ├── enums.py           # Channel, Surface
│   ├── models.py          # AgentEvent union, TenantTarget, AgentResponse, CompiledPlan, RequestSpec
│   ├── credentials.py     # Typed per-surface credentials with SecretStr redaction
│   ├── capabilities.py    # Declarative CapabilityProfile limits + verified_on date
│   ├── compiler.py        # Pure compile_response(response, profile, target) -> CompiledPlan
│   ├── crypto.py          # Constant-time X-Hub-Signature-256 & hub.challenge helpers
│   └── errors.py          # Flat MetaError, ErrorCategory, declarative ERROR_MAP
├── transport/             # Async httpx execution layer
│   ├── http.py            # GraphTransport (injected/managed AsyncClient, per-call Bearer auth)
│   └── media.py           # SSRF-safe MediaDownloader (WA 2-step media_id & CDN URLs)
├── drivers/               # Depends ONLY on core/
│   ├── base.py            # ChannelDriver protocol
│   ├── whatsapp.py        # WhatsApp Cloud API parser & RequestSpec renderer
│   └── meta_messaging.py  # Shared Messenger / IG-FB / IG-Direct parser & renderer
├── bridge.py              # SocialBridge public facade
└── testing/               # FakeMetaTransport & signed webhook payload factories
```

</details>

---

## Installation

```bash
uv add meta-agent-bridge
```

Or with `pip`:

```bash
pip install meta-agent-bridge
```

Requires **Python 3.12+**. Core runtime dependencies are strictly `httpx` and `pydantic>=2.0`.

---

## Quickstart

### Step 1: Webhook Ingestion (FastAPI)

Verify `X-Hub-Signature-256` (enabled by default), parse batched `entry[]` payloads synchronously, and push serialized JSON events to your background queue:

```python
from fastapi import FastAPI, Header, HTTPException, Request, Response

from meta_agent_bridge import SignatureVerificationError, SocialBridge

app = FastAPI()
bridge = SocialBridge()

APP_SECRETS = ["meta-app-secret", "instagram-app-secret"]  # single str or candidate sequence
VERIFY_TOKEN = "my-webhook-verify-token"


@app.get("/webhook")
def verify_webhook(request: Request) -> Response:
    try:
        challenge = bridge.verify_challenge(request.query_params, VERIFY_TOKEN)
        return Response(content=challenge, media_type="text/plain")
    except SignatureVerificationError as exc:
        raise HTTPException(status_code=403, detail=exc.message) from exc


@app.post("/webhook")
async def ingest_webhook(
    request: Request,
    x_hub_signature_256: str | None = Header(default=None),
) -> dict[str, int]:
    raw_body = await request.body()
    try:
        events = bridge.parse_webhook(
            raw_body,
            signature=x_hub_signature_256,
            app_secret=APP_SECRETS,
        )
    except SignatureVerificationError as exc:
        raise HTTPException(status_code=401, detail=exc.message) from exc

    for event in events:
        payload_json = event.model_dump_json()
        # Enqueue payload_json into Redis / Celery / SQS here
        _ = payload_json

    return {"accepted": len(events)}
```

### Step 2: Agent Worker Reply

Deserialize an `AgentEvent` in your worker, build a channel-neutral `AgentResponse`, and dispatch with `await bridge.send(...)`:

```python
from pydantic import SecretStr

from meta_agent_bridge import (
    AgentEventAdapter,
    AgentMessageEvent,
    AgentResponse,
    Choice,
    MediaType,
    OutboundMedia,
    SenderAction,
    SocialBridge,
    WhatsAppCredentials,
)


async def handle_queued_event(raw_event_json: str) -> None:
    event = AgentEventAdapter.validate_json(raw_event_json)
    if not isinstance(event, AgentMessageEvent):
        return

    creds = WhatsAppCredentials(
        access_token=SecretStr("EAAG..."),
        phone_number_id=event.target.tenant_id or "109876543210",
    )

    response = AgentResponse(
        text="Here is your invoice. Would you like to pay now?",
        media=(
            OutboundMedia(
                media_type=MediaType.IMAGE,
                url="https://lookaside.fbsbx.com/example/invoice.png",
            ),
        ),
        choices=(
            Choice(id="pay_now", title="Pay Now"),
            Choice(id="remind_later", title="Remind Later"),
        ),
        actions=(SenderAction.MARK_READ, SenderAction.TYPING_ON),
        reply_to_message_id=event.message_id,
    )

    async with SocialBridge() as bridge:
        result = await bridge.send(response, event.target, creds)
        if not result.succeeded:
            print("Failed step:", result.failed_step_id)
```

### Step 3: Multi-Tenant Credentials

Pass the credential model matching each tenant's channel and auth flavor — `GraphTransport` routes to the right Meta host and binds the token per call:

```python
from pydantic import SecretStr

from meta_agent_bridge import (
    InstagramDirectCredentials,
    InstagramFacebookCredentials,
    MessengerCredentials,
    WhatsAppCredentials,
)

wa_creds = WhatsAppCredentials(
    access_token=SecretStr("EAAG..."),
    phone_number_id="109876543210",
)
ms_creds = MessengerCredentials(
    access_token=SecretStr("EAAG..."),
    page_id="page_90001",
)
ig_fb_creds = InstagramFacebookCredentials(
    access_token=SecretStr("EAAG..."),
    page_id="page_90001",
    ig_account_id="ig_acct_777",
)
ig_direct_creds = InstagramDirectCredentials(
    access_token=SecretStr("IGA..."),
    ig_account_id="ig_acct_777",
)
```

---

## Capabilities

Verified against Meta Graph API `v27.0` (`CapabilityProfile.verified_on = 2026-12-01`) in `v0.1.0`:

| Capability | WhatsApp Cloud API | Messenger | Instagram (FB Login) | Instagram (IG Direct) |
| :--- | :--- | :--- | :--- | :--- |
| **Base Host** | `graph.facebook.com` | `graph.facebook.com` | `graph.facebook.com` | `graph.instagram.com` |
| **Max Text Length** | `4096` (auto-chunked) | `2000` (auto-chunked) | `1000` (auto-chunked) | `1000` (auto-chunked) |
| **Interactive Choices** | `1–3` reply buttons · `4–10` list rows | `1–13` quick replies | `1–13` quick replies | `1–13` quick replies |
| **Recipient Routing** | Phone (`to`) & BSUID (`recipient`) | PSID (`recipient.id`) | IGSID (`recipient.id`) | IGSID (`recipient.id`) |
| **Typing & Read Receipts** | Coupled `status="read"` + `typing_indicator` | Separate `sender_action` | Separate `sender_action` | Separate `sender_action` |
| **Media + Choices Split** | Emits `MediaStep` then interactive | Allowed together / sequential | Enforced split (`MediaStep` → `ButtonsStep`) | Enforced split (`MediaStep` → `ButtonsStep`) |
| **Media (URL / `media_id`)** | Supported (inbound & outbound) | Supported (inbound & outbound) | Supported (inbound & outbound) | Supported (inbound & outbound) |
| **Inbound Location (Maps)** | Supported (`LocationData`) | Supported (`LocationData`) | Supported (`LocationData`) | Supported (`LocationData`) |
| **Templates** | Planned `v0.2.0` | Planned `v0.2.0` | Planned `v0.2.0` | Planned `v0.2.0` |
| **Link / URL Buttons** | Planned `v0.2.0` | Planned `v0.2.0` | Planned `v0.2.0` | Planned `v0.2.0` |
| **Emoji Reactions** | Planned `v0.2.0` | Planned `v0.2.0` | Planned `v0.2.0` | Planned `v0.2.0` |
| **Multipart Binary Upload** | Planned `v0.2.0` | Planned `v0.2.0` | — (hosted URL) | — (hosted URL) |

---

## Resumable Sends

Meta's Send APIs do not support request idempotency keys. If a multi-step response (for example, `mark_read` → `MediaStep` → `ButtonsStep`) experiences a post-dispatch `ReadTimeout`, blindly retrying from step 1 can duplicate messages already delivered to the user.

`meta-agent-bridge` compiles every response into a deterministic `CompiledPlan` and returns a `DispatchResult` where each `StepResult` has a 3-state status: `"sent"`, `"failed"`, or `"unknown"` (ambiguous network failure after dispatch):

```python
from meta_agent_bridge import (
    AgentResponse,
    Choice,
    Credentials,
    MediaType,
    OutboundMedia,
    SenderAction,
    SocialBridge,
    TenantTarget,
)


async def send_resumable(
    bridge: SocialBridge,
    target: TenantTarget,
    creds: Credentials,
) -> None:
    response = AgentResponse(
        text="Confirm your booking?",
        media=(
            OutboundMedia(
                media_type=MediaType.IMAGE,
                url="https://scontent.cdninstagram.com/booking.png",
            ),
        ),
        choices=(Choice(id="yes", title="Confirm"), Choice(id="no", title="Cancel")),
        actions=(SenderAction.MARK_READ,),
    )

    # Compile once into deterministic, JSON-serializable steps
    plan = bridge.compile(response, target, creds)
    result = await bridge.send_plan(plan, creds)

    if not result.succeeded and result.failed_step_id is not None:
        failed = next(r for r in result.results if r.step_id == result.failed_step_id)
        if failed.status == "failed" and failed.error is not None and failed.error.retryable:
            # Resume strictly from the failed step without duplicating prior "sent" steps
            await bridge.send_plan(plan, creds, resume_from=result.failed_step_id)
        elif failed.status == "unknown":
            # Delivery is ambiguous (e.g., ReadTimeout); inspect or prompt before retrying
            print("Ambiguous delivery at step:", failed.step_id)
```

---

## Error Handling

All Graph API, transport, compilation, and verification failures raise or return a single flat `MetaError` carrying normalized metadata (`category`, `channel`, `code`, `subcode`, `http_status`, `fbtrace_id`, `retryable`, `retry_after`, `delivery_ambiguous`), plus four convenience subclasses for common `except` blocks:

```python
from meta_agent_bridge import (
    AgentResponse,
    AuthError,
    MetaError,
    RateLimitError,
    SignatureVerificationError,
    SocialBridge,
    TenantTarget,
    WhatsAppCredentials,
    WindowExpiredError,
)


async def dispatch_with_handling(
    bridge: SocialBridge,
    response: AgentResponse,
    target: TenantTarget,
    creds: WhatsAppCredentials,
) -> None:
    plan = bridge.compile(response, target, creds)
    result = await bridge.send_plan(plan, creds)
    if result.succeeded:
        return

    err = result.results[-1].error
    if err is None:
        return

    try:
        raise err
    except SignatureVerificationError:
        print("Webhook HMAC or hub.verify_token invalid")
    except AuthError as exc:
        print(f"Token invalid/expired (code={exc.code}, fbtrace_id={exc.fbtrace_id})")
    except RateLimitError as exc:
        print(f"Rate limited; retry after {exc.retry_after}s (retryable={exc.retryable})")
    except WindowExpiredError:
        print("24h customer service window closed")
    except MetaError as exc:
        print(f"[{exc.category.value}] code={exc.code} subcode={exc.subcode}: {exc.message}")
```

---

## Testing

Use `meta_agent_bridge.testing` (`FakeMetaTransport`, `make_whatsapp_text_webhook`, `make_messenger_text_webhook`, `make_instagram_text_webhook`, `sign_webhook_payload`) to test your agent end-to-end in `pytest` with zero live network calls or Meta App Review:

```python
import pytest
from pydantic import SecretStr

from meta_agent_bridge import AgentMessageEvent, AgentResponse, SocialBridge, WhatsAppCredentials
from meta_agent_bridge.testing import (
    FakeMetaTransport,
    make_whatsapp_text_webhook,
    sign_webhook_payload,
)


@pytest.mark.asyncio
async def test_agent_handles_bsuid_message() -> None:
    fake = FakeMetaTransport()
    bridge = SocialBridge(transport=fake)
    creds = WhatsAppCredentials(access_token=SecretStr("test-token"), phone_number_id="109876543210")

    raw_body, signature = sign_webhook_payload(
        make_whatsapp_text_webhook(
            sender_id="US.13491208655302741918",
            text="Where is my order?",
            use_bsuid=True,
        ),
        "test-app-secret",
    )

    events = bridge.parse_webhook(raw_body, signature=signature, app_secret="test-app-secret")
    assert len(events) == 1
    inbound = events[0]
    assert isinstance(inbound, AgentMessageEvent)

    result = await bridge.send(AgentResponse(text="On its way!"), inbound.target, creds)
    assert result.succeeded is True
    assert fake.calls[0].json_body is not None
    assert fake.calls[0].json_body["recipient"] == "US.13491208655302741918"
```

---

## Roadmap

### Coming in `v0.2.0`

- **WhatsApp Template Sending (`TemplateStep`):** Structured outbound template messages (`name`, `language_code`, `components`) for re-engaging users outside the 24-hour customer service window, with compile-time surface validation and BSUID support.
- **URL / CTA Buttons (`LinkButton` & `UrlButtonsStep`):** Native WhatsApp `cta_url` buttons (`max_url_buttons = 1`) and Messenger/Instagram Button Templates (`max_url_buttons = 3`), automatically degrading excess links into formatted `TextStep`s.
- **Multipart Media Upload (`upload_media`):** Upload in-memory `bytes` directly to WhatsApp (`/{phone_number_id}/media`) and Messenger (`/{page_id}/message_attachments`), returning `UploadedMedia(media_id, channel)` while guarding Instagram (`INVALID_PARAM`) where hosted URLs are required.
- **Instagram Story Mentions, Story Replies & Post/Reel Shares (`StoryContext`):** Normalize `story_mention`, `reply_to.story`, and `share` attachments into `AgentMessageEvent` with `cacheable=False` policy compliance (never auto-downloading ephemeral story media).
- **Explicit Quoted Replies on Messenger & Instagram (`quote_message_id`):** Decouple WhatsApp's coupled typing/read `target_message_id` from explicit message quoting (`reply_to.mid` on Messenger/IG, `context.message_id` on WhatsApp).
- **Emoji Reactions (`AgentReactionEvent` & `ReactionStep`):** Bidirectional react and unreact support across WhatsApp, Messenger, and Instagram.
- **Quick Wins:** WhatsApp `preview_url: bool` toggle on `TextStep` and Messenger/Instagram `sticker_id` detection mapped to `MediaType.STICKER`.

### Planned for `v0.3.0`

- Outbound Maps / Location (`LocationStep`) and WhatsApp `location_request_message`
- WhatsApp Contacts (`vCard`) inbound and outbound support
- Exponential backoff / retry helper and optional `[redis]` / `[auth]` extras

---

## Support the Project

If `meta-agent-bridge` saves you time building omnichannel Meta agents, consider supporting its development:

[![Buy Me A Coffee](https://img.shields.io/badge/Buy%20Me%20A%20Coffee-FFDD00?style=for-the-badge&logo=buy-me-a-coffee&logoColor=black)](https://www.buymeacoffee.com/Umar4880)

---

## Disclaimer & License

> **Disclaimer:** `meta-agent-bridge` is an unofficial, independent open-source library and is **not** affiliated with, endorsed by, or sponsored by Meta Platforms, Inc. "WhatsApp", "Facebook", "Messenger", and "Instagram" are trademarks of Meta Platforms, Inc.

Licensed under the **MIT License**.
