meta-agent-bridge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,127 @@
1
+ """Agentic-first omnichannel Meta messaging SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from meta_agent_bridge.core import (
8
+ CAPABILITY_PROFILES,
9
+ ERROR_MAP,
10
+ VERIFIED_META_DATE,
11
+ ActionStep,
12
+ AgentEvent,
13
+ AgentEventAdapter,
14
+ AgentMessageEvent,
15
+ AgentResponse,
16
+ AgentStatusEvent,
17
+ AuthError,
18
+ ButtonsStep,
19
+ CapabilityProfile,
20
+ Channel,
21
+ Choice,
22
+ CompiledPlan,
23
+ CompiledStep,
24
+ Credentials,
25
+ DeliveryStatus,
26
+ DispatchResult,
27
+ ErrorCategory,
28
+ InboundMedia,
29
+ InstagramDirectCredentials,
30
+ InstagramFacebookCredentials,
31
+ InteractiveReply,
32
+ ListStep,
33
+ LocationData,
34
+ MediaStep,
35
+ MediaType,
36
+ MessengerCredentials,
37
+ MetaError,
38
+ OutboundMedia,
39
+ RateLimitError,
40
+ RequestSpec,
41
+ SenderAction,
42
+ SignatureVerificationError,
43
+ StepResult,
44
+ Surface,
45
+ TenantTarget,
46
+ TextStep,
47
+ UnknownEvent,
48
+ WhatsAppCredentials,
49
+ WindowExpiredError,
50
+ classify_error,
51
+ compile_response,
52
+ get_capability_profile,
53
+ make_deterministic_id,
54
+ require_valid_signature,
55
+ verify_hub_challenge,
56
+ verify_webhook_signature,
57
+ )
58
+
59
+ if TYPE_CHECKING:
60
+ from meta_agent_bridge.bridge import SocialBridge
61
+
62
+ __version__ = "0.1.0"
63
+
64
+
65
+ def __getattr__(name: str) -> Any:
66
+ """Lazily load `SocialBridge` so importing `core` remains strictly sans-I/O."""
67
+ if name == "SocialBridge":
68
+ from meta_agent_bridge.bridge import SocialBridge
69
+
70
+ return SocialBridge
71
+ msg = f"module {__name__!r} has no attribute {name!r}"
72
+ raise AttributeError(msg)
73
+
74
+
75
+ __all__ = [
76
+ "CAPABILITY_PROFILES",
77
+ "ERROR_MAP",
78
+ "VERIFIED_META_DATE",
79
+ "ActionStep",
80
+ "AgentEvent",
81
+ "AgentEventAdapter",
82
+ "AgentMessageEvent",
83
+ "AgentResponse",
84
+ "AgentStatusEvent",
85
+ "AuthError",
86
+ "ButtonsStep",
87
+ "CapabilityProfile",
88
+ "Channel",
89
+ "Choice",
90
+ "CompiledPlan",
91
+ "CompiledStep",
92
+ "Credentials",
93
+ "DeliveryStatus",
94
+ "DispatchResult",
95
+ "ErrorCategory",
96
+ "InboundMedia",
97
+ "InstagramDirectCredentials",
98
+ "InstagramFacebookCredentials",
99
+ "InteractiveReply",
100
+ "ListStep",
101
+ "LocationData",
102
+ "MediaStep",
103
+ "MediaType",
104
+ "MessengerCredentials",
105
+ "MetaError",
106
+ "OutboundMedia",
107
+ "RateLimitError",
108
+ "RequestSpec",
109
+ "SenderAction",
110
+ "SignatureVerificationError",
111
+ "SocialBridge",
112
+ "StepResult",
113
+ "Surface",
114
+ "TenantTarget",
115
+ "TextStep",
116
+ "UnknownEvent",
117
+ "WhatsAppCredentials",
118
+ "WindowExpiredError",
119
+ "__version__",
120
+ "classify_error",
121
+ "compile_response",
122
+ "get_capability_profile",
123
+ "make_deterministic_id",
124
+ "require_valid_signature",
125
+ "verify_hub_challenge",
126
+ "verify_webhook_signature",
127
+ ]
@@ -0,0 +1,297 @@
1
+ """Public async facade wiring parsing, compilation, and resumable dispatch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import Literal
8
+
9
+ import httpx
10
+
11
+ from meta_agent_bridge.core.capabilities import get_capability_profile
12
+ from meta_agent_bridge.core.compiler import compile_response
13
+ from meta_agent_bridge.core.credentials import Credentials
14
+ from meta_agent_bridge.core.crypto import require_valid_signature, verify_hub_challenge
15
+ from meta_agent_bridge.core.enums import Channel, Surface
16
+ from meta_agent_bridge.core.errors import (
17
+ ErrorCategory,
18
+ MetaError,
19
+ SignatureVerificationError,
20
+ )
21
+ from meta_agent_bridge.core.models import (
22
+ AgentEvent,
23
+ AgentResponse,
24
+ CompiledPlan,
25
+ DispatchResult,
26
+ StepResult,
27
+ TenantTarget,
28
+ UnknownEvent,
29
+ make_deterministic_id,
30
+ )
31
+ from meta_agent_bridge.drivers import get_driver
32
+ from meta_agent_bridge.transport.http import AsyncTransportProtocol, GraphTransport
33
+ from meta_agent_bridge.transport.media import MediaDownloader
34
+
35
+ _WEBHOOK_OBJECT_SURFACE_MAP: dict[str, Surface] = {
36
+ "whatsapp_business_account": Surface.WHATSAPP,
37
+ "page": Surface.MESSENGER,
38
+ "instagram": Surface.INSTAGRAM_FB,
39
+ }
40
+
41
+
42
+ class SocialBridge:
43
+ """Agentic-first omnichannel Meta messaging facade."""
44
+
45
+ def __init__(
46
+ self,
47
+ *,
48
+ client: httpx.AsyncClient | None = None,
49
+ transport: AsyncTransportProtocol | None = None,
50
+ ) -> None:
51
+ """Initialize the omnichannel `SocialBridge`.
52
+
53
+ Args:
54
+ client: Optional caller-managed `httpx.AsyncClient` passed to `GraphTransport`.
55
+ transport: Optional custom transport (such as `FakeMetaTransport` in tests).
56
+ """
57
+ self._transport: AsyncTransportProtocol = (
58
+ transport if transport is not None else GraphTransport(client=client)
59
+ )
60
+ self._media_downloader: MediaDownloader | None = (
61
+ MediaDownloader(self._transport)
62
+ if isinstance(self._transport, GraphTransport)
63
+ else None
64
+ )
65
+
66
+ @property
67
+ def transport(self) -> AsyncTransportProtocol:
68
+ """Return the underlying async transport instance."""
69
+ return self._transport
70
+
71
+ @property
72
+ def media(self) -> MediaDownloader:
73
+ """Return the SSRF-safe `MediaDownloader` backed by `GraphTransport`.
74
+
75
+ Raises:
76
+ RuntimeError: If initialized with a custom non-HTTP transport.
77
+ """
78
+ if self._media_downloader is None:
79
+ msg = "MediaDownloader is only available when using GraphTransport."
80
+ raise RuntimeError(msg)
81
+ return self._media_downloader
82
+
83
+ async def __aenter__(self) -> SocialBridge:
84
+ return self
85
+
86
+ async def __aexit__(self, *_exc: object) -> None:
87
+ await self.aclose()
88
+
89
+ async def aclose(self) -> None:
90
+ """Close transport resources owned by this bridge."""
91
+ await self._transport.aclose()
92
+
93
+ def verify_challenge(
94
+ self,
95
+ params: Mapping[str, str],
96
+ verify_token: str,
97
+ *,
98
+ channel: Channel = Channel.WHATSAPP,
99
+ ) -> str:
100
+ """Validate a Meta webhook GET handshake and return `hub.challenge`."""
101
+ return verify_hub_challenge(params, verify_token, channel=channel)
102
+
103
+ def parse_webhook(
104
+ self,
105
+ raw_body: bytes | str,
106
+ *,
107
+ signature: str | None = None,
108
+ app_secret: str | Sequence[str] | None = None,
109
+ surface: Surface | None = None,
110
+ verify_signature: bool = True,
111
+ ) -> list[AgentEvent]:
112
+ """Verify and parse a Meta webhook POST payload into canonical `AgentEvent`s.
113
+
114
+ Args:
115
+ raw_body: Exact raw HTTP body bytes (or UTF-8 string).
116
+ signature: Value of the `X-Hub-Signature-256` request header.
117
+ app_secret: Secret or candidate secrets (for example Meta + IG App Secrets).
118
+ surface: Optional explicit `Surface` override (useful to tag IG Direct webhooks
119
+ as `Surface.INSTAGRAM_DIRECT` instead of the default `INSTAGRAM_FB`).
120
+ verify_signature: Whether to enforce HMAC-SHA256 verification (default `True`).
121
+
122
+ Returns:
123
+ List of parsed `AgentEvent` objects (`UnknownEvent` on unrecognized shapes).
124
+
125
+ Raises:
126
+ SignatureVerificationError: If `verify_signature=True` and verification fails.
127
+ """
128
+ body_bytes = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body
129
+ error_channel = surface.channel if surface is not None else Channel.WHATSAPP
130
+
131
+ if verify_signature:
132
+ if app_secret is None:
133
+ raise SignatureVerificationError(
134
+ category=ErrorCategory.AUTH,
135
+ channel=error_channel,
136
+ message="app_secret is required when verify_signature=True.",
137
+ http_status=401,
138
+ retryable=False,
139
+ )
140
+ require_valid_signature(
141
+ body_bytes,
142
+ signature,
143
+ app_secret,
144
+ channel=error_channel,
145
+ )
146
+
147
+ try:
148
+ payload = json.loads(body_bytes)
149
+ except (UnicodeDecodeError, json.JSONDecodeError):
150
+ return [
151
+ UnknownEvent(
152
+ event_id=make_deterministic_id("evt", "invalid_json", len(body_bytes)),
153
+ channel=surface.channel if surface is not None else None,
154
+ surface=surface,
155
+ reason="invalid_json_payload",
156
+ raw={},
157
+ )
158
+ ]
159
+
160
+ if not isinstance(payload, dict):
161
+ return [
162
+ UnknownEvent(
163
+ event_id=make_deterministic_id(
164
+ "evt", "non_object_json", type(payload).__name__
165
+ ),
166
+ channel=surface.channel if surface is not None else None,
167
+ surface=surface,
168
+ reason="non_object_json_payload",
169
+ raw={},
170
+ )
171
+ ]
172
+
173
+ resolved_surface = surface
174
+ if resolved_surface is None:
175
+ raw_object = payload.get("object")
176
+ if isinstance(raw_object, str):
177
+ resolved_surface = _WEBHOOK_OBJECT_SURFACE_MAP.get(raw_object)
178
+
179
+ if resolved_surface is None:
180
+ return [
181
+ UnknownEvent(
182
+ event_id=make_deterministic_id("evt", "unknown_object", payload),
183
+ reason=f"unknown_webhook_object:{payload.get('object')}",
184
+ raw=payload,
185
+ )
186
+ ]
187
+
188
+ driver = get_driver(resolved_surface)
189
+ return driver.parse_webhook(payload)
190
+
191
+ def compile(
192
+ self,
193
+ response: AgentResponse,
194
+ target: TenantTarget,
195
+ credentials_or_surface: Credentials | Surface,
196
+ ) -> CompiledPlan:
197
+ """Compile an `AgentResponse` into a deterministic `CompiledPlan`."""
198
+ surface = (
199
+ credentials_or_surface
200
+ if isinstance(credentials_or_surface, Surface)
201
+ else credentials_or_surface.surface
202
+ )
203
+ profile = get_capability_profile(surface)
204
+ return compile_response(response, profile, target)
205
+
206
+ async def send_plan(
207
+ self,
208
+ plan: CompiledPlan,
209
+ credentials: Credentials,
210
+ *,
211
+ resume_from: str | None = None,
212
+ ) -> DispatchResult:
213
+ """Execute a `CompiledPlan` sequentially, optionally resuming from a failed step.
214
+
215
+ Args:
216
+ plan: Compiled execution plan produced by `compile()`.
217
+ credentials: Tenant credentials matching `plan.surface`.
218
+ resume_from: Optional `step_id` from a prior partial `DispatchResult` to resume from.
219
+
220
+ Returns:
221
+ `DispatchResult` containing per-step outcomes (`sent`, `failed`, or `unknown`).
222
+
223
+ Raises:
224
+ MetaError: If `credentials.surface` mismatches `plan.surface` or `resume_from`
225
+ is not found in `plan.steps`.
226
+ """
227
+ if credentials.surface is not plan.surface:
228
+ raise MetaError(
229
+ category=ErrorCategory.INVALID_PARAM,
230
+ channel=plan.channel,
231
+ message=(
232
+ f"Plan surface {plan.surface.value!r} does not match "
233
+ f"credentials surface {credentials.surface.value!r}."
234
+ ),
235
+ )
236
+
237
+ steps_to_run = plan.steps
238
+ if resume_from is not None:
239
+ match_index = next(
240
+ (idx for idx, step in enumerate(plan.steps) if step.step_id == resume_from),
241
+ None,
242
+ )
243
+ if match_index is None:
244
+ raise MetaError(
245
+ category=ErrorCategory.INVALID_PARAM,
246
+ channel=plan.channel,
247
+ message=f"Step {resume_from!r} was not found in CompiledPlan {plan.plan_id!r}.",
248
+ )
249
+ steps_to_run = plan.steps[match_index:]
250
+
251
+ driver = get_driver(plan.surface)
252
+ results: list[StepResult] = []
253
+
254
+ for step in steps_to_run:
255
+ spec = driver.render_step(step, plan.target, credentials)
256
+ try:
257
+ response_json = await self._transport.execute(spec, credentials)
258
+ except MetaError as exc:
259
+ status: Literal["unknown", "failed"] = (
260
+ "unknown"
261
+ if exc.category is ErrorCategory.NETWORK and exc.delivery_ambiguous
262
+ else "failed"
263
+ )
264
+ results.append(
265
+ StepResult(
266
+ step_id=step.step_id,
267
+ status=status,
268
+ error=exc,
269
+ )
270
+ )
271
+ break
272
+
273
+ external_id = driver.extract_message_id(response_json)
274
+ results.append(
275
+ StepResult(
276
+ step_id=step.step_id,
277
+ status="sent",
278
+ external_message_id=external_id,
279
+ )
280
+ )
281
+
282
+ return DispatchResult(
283
+ plan_id=plan.plan_id,
284
+ surface=plan.surface,
285
+ channel=plan.channel,
286
+ results=tuple(results),
287
+ )
288
+
289
+ async def send(
290
+ self,
291
+ response: AgentResponse,
292
+ target: TenantTarget,
293
+ credentials: Credentials,
294
+ ) -> DispatchResult:
295
+ """Compile an `AgentResponse` and dispatch it to Meta."""
296
+ plan = self.compile(response, target, credentials)
297
+ return await self.send_plan(plan, credentials)
@@ -0,0 +1,114 @@
1
+ """Pure sync sans-I/O core for meta-agent-bridge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from meta_agent_bridge.core.capabilities import (
6
+ CAPABILITY_PROFILES,
7
+ VERIFIED_META_DATE,
8
+ CapabilityProfile,
9
+ get_capability_profile,
10
+ )
11
+ from meta_agent_bridge.core.compiler import compile_response
12
+ from meta_agent_bridge.core.credentials import (
13
+ Credentials,
14
+ InstagramDirectCredentials,
15
+ InstagramFacebookCredentials,
16
+ MessengerCredentials,
17
+ WhatsAppCredentials,
18
+ )
19
+ from meta_agent_bridge.core.crypto import (
20
+ require_valid_signature,
21
+ verify_hub_challenge,
22
+ verify_webhook_signature,
23
+ )
24
+ from meta_agent_bridge.core.enums import Channel, Surface
25
+ from meta_agent_bridge.core.errors import (
26
+ ERROR_MAP,
27
+ AuthError,
28
+ ErrorCategory,
29
+ MetaError,
30
+ RateLimitError,
31
+ SignatureVerificationError,
32
+ WindowExpiredError,
33
+ classify_error,
34
+ )
35
+ from meta_agent_bridge.core.models import (
36
+ ActionStep,
37
+ AgentEvent,
38
+ AgentEventAdapter,
39
+ AgentMessageEvent,
40
+ AgentResponse,
41
+ AgentStatusEvent,
42
+ ButtonsStep,
43
+ Choice,
44
+ CompiledPlan,
45
+ CompiledStep,
46
+ DeliveryStatus,
47
+ DispatchResult,
48
+ InboundMedia,
49
+ InteractiveReply,
50
+ ListStep,
51
+ LocationData,
52
+ MediaStep,
53
+ MediaType,
54
+ OutboundMedia,
55
+ RequestSpec,
56
+ SenderAction,
57
+ StepResult,
58
+ TenantTarget,
59
+ TextStep,
60
+ UnknownEvent,
61
+ make_deterministic_id,
62
+ )
63
+
64
+ __all__ = [
65
+ "CAPABILITY_PROFILES",
66
+ "ERROR_MAP",
67
+ "VERIFIED_META_DATE",
68
+ "ActionStep",
69
+ "AgentEvent",
70
+ "AgentEventAdapter",
71
+ "AgentMessageEvent",
72
+ "AgentResponse",
73
+ "AgentStatusEvent",
74
+ "AuthError",
75
+ "ButtonsStep",
76
+ "CapabilityProfile",
77
+ "Channel",
78
+ "Choice",
79
+ "CompiledPlan",
80
+ "CompiledStep",
81
+ "Credentials",
82
+ "DeliveryStatus",
83
+ "DispatchResult",
84
+ "ErrorCategory",
85
+ "InboundMedia",
86
+ "InstagramDirectCredentials",
87
+ "InstagramFacebookCredentials",
88
+ "InteractiveReply",
89
+ "ListStep",
90
+ "LocationData",
91
+ "MediaStep",
92
+ "MediaType",
93
+ "MessengerCredentials",
94
+ "MetaError",
95
+ "OutboundMedia",
96
+ "RateLimitError",
97
+ "RequestSpec",
98
+ "SenderAction",
99
+ "SignatureVerificationError",
100
+ "StepResult",
101
+ "Surface",
102
+ "TenantTarget",
103
+ "TextStep",
104
+ "UnknownEvent",
105
+ "WhatsAppCredentials",
106
+ "WindowExpiredError",
107
+ "classify_error",
108
+ "compile_response",
109
+ "get_capability_profile",
110
+ "make_deterministic_id",
111
+ "require_valid_signature",
112
+ "verify_hub_challenge",
113
+ "verify_webhook_signature",
114
+ ]
@@ -0,0 +1,122 @@
1
+ """Declarative capability profiles for Meta messaging surfaces."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date
6
+
7
+ from pydantic import BaseModel, ConfigDict
8
+
9
+ from meta_agent_bridge.core.enums import Channel, Surface
10
+
11
+ VERIFIED_META_DATE = date(2026, 12, 1)
12
+
13
+
14
+ class CapabilityProfile(BaseModel):
15
+ """Declarative platform limits and constraints for a Meta surface."""
16
+
17
+ model_config = ConfigDict(frozen=True, extra="ignore")
18
+
19
+ surface: Surface
20
+ channel: Channel
21
+ verified_on: date
22
+ max_text_length: int
23
+ max_reply_buttons: int
24
+ max_quick_replies: int
25
+ max_button_title_length: int
26
+ max_button_id_length: int
27
+ max_list_sections: int
28
+ max_list_rows: int
29
+ max_list_row_title_length: int
30
+ max_list_row_description_length: int
31
+ max_list_row_id_length: int
32
+ allows_choices_with_media: bool
33
+ supports_separate_sender_actions: bool
34
+ requires_message_id_for_typing: bool
35
+
36
+
37
+ CAPABILITY_PROFILES: dict[Surface, CapabilityProfile] = {
38
+ Surface.WHATSAPP: CapabilityProfile(
39
+ surface=Surface.WHATSAPP,
40
+ channel=Channel.WHATSAPP,
41
+ verified_on=VERIFIED_META_DATE,
42
+ max_text_length=4096,
43
+ max_reply_buttons=3,
44
+ max_quick_replies=0,
45
+ max_button_title_length=20,
46
+ max_button_id_length=256,
47
+ max_list_sections=10,
48
+ max_list_rows=10,
49
+ max_list_row_title_length=24,
50
+ max_list_row_description_length=72,
51
+ max_list_row_id_length=200,
52
+ allows_choices_with_media=False,
53
+ supports_separate_sender_actions=False,
54
+ requires_message_id_for_typing=True,
55
+ ),
56
+ Surface.MESSENGER: CapabilityProfile(
57
+ surface=Surface.MESSENGER,
58
+ channel=Channel.MESSENGER,
59
+ verified_on=VERIFIED_META_DATE,
60
+ max_text_length=2000,
61
+ max_reply_buttons=0,
62
+ max_quick_replies=13,
63
+ max_button_title_length=20,
64
+ max_button_id_length=1000,
65
+ max_list_sections=0,
66
+ max_list_rows=0,
67
+ max_list_row_title_length=0,
68
+ max_list_row_description_length=0,
69
+ max_list_row_id_length=0,
70
+ allows_choices_with_media=True,
71
+ supports_separate_sender_actions=True,
72
+ requires_message_id_for_typing=False,
73
+ ),
74
+ Surface.INSTAGRAM_FB: CapabilityProfile(
75
+ surface=Surface.INSTAGRAM_FB,
76
+ channel=Channel.INSTAGRAM,
77
+ verified_on=VERIFIED_META_DATE,
78
+ max_text_length=1000,
79
+ max_reply_buttons=0,
80
+ max_quick_replies=13,
81
+ max_button_title_length=20,
82
+ max_button_id_length=1000,
83
+ max_list_sections=0,
84
+ max_list_rows=0,
85
+ max_list_row_title_length=0,
86
+ max_list_row_description_length=0,
87
+ max_list_row_id_length=0,
88
+ allows_choices_with_media=False,
89
+ supports_separate_sender_actions=True,
90
+ requires_message_id_for_typing=False,
91
+ ),
92
+ Surface.INSTAGRAM_DIRECT: CapabilityProfile(
93
+ surface=Surface.INSTAGRAM_DIRECT,
94
+ channel=Channel.INSTAGRAM,
95
+ verified_on=VERIFIED_META_DATE,
96
+ max_text_length=1000,
97
+ max_reply_buttons=0,
98
+ max_quick_replies=13,
99
+ max_button_title_length=20,
100
+ max_button_id_length=1000,
101
+ max_list_sections=0,
102
+ max_list_rows=0,
103
+ max_list_row_title_length=0,
104
+ max_list_row_description_length=0,
105
+ max_list_row_id_length=0,
106
+ allows_choices_with_media=False,
107
+ supports_separate_sender_actions=True,
108
+ requires_message_id_for_typing=False,
109
+ ),
110
+ }
111
+
112
+
113
+ def get_capability_profile(surface: Surface) -> CapabilityProfile:
114
+ """Return the verified `CapabilityProfile` for a Meta surface.
115
+
116
+ Args:
117
+ surface: The target Meta API surface.
118
+
119
+ Returns:
120
+ The frozen `CapabilityProfile` for that surface.
121
+ """
122
+ return CAPABILITY_PROFILES[surface]