Spaces:
Running

File size: 4,376 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""Channel contract: how WorkPilot talks to customers (WhatsApp, email, web chat, SMS).



A ``Channel`` is a thin, stateless adapter over one provider API for one tenant account:



* ``send(to, content, template=None) -> SendResult``: deliver one message; returns the

  provider's message id (and thread key, where the provider has threads);

* ``parse_inbound(payload) -> list[NormalizedEvent]``: provider payload -> ``Event``s (plus

  their dedupe keys) for the event inbox. Customer text in them is always untrusted;

* ``parse_receipts(payload) -> list[DeliveryReceipt]``: delivery/read/failed receipts.



Channels never decide *whether* to send: the gateway did that when the message was queued

(see ``core.channels.outbox``). They never see the LLM, and the LLM never sees them: their

credentials are resolved from secret references at delivery time.



Errors: ``ChannelError(transient=True)`` means "try again later" (timeouts, 429, 5xx);

``transient=False`` means retrying cannot help (bad number, closed 24-hour window, rejected

template, bad credentials).

"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Literal, Protocol, runtime_checkable

from core.events.intake import NormalizedEvent

ChannelName = Literal["whatsapp", "email", "webchat", "sms"]
CHANNELS: tuple[str, ...] = ("whatsapp", "email", "webchat", "sms")
TemplateCategory = Literal["utility", "marketing", "authentication"]
TEMPLATE_CATEGORIES: tuple[str, ...] = ("utility", "marketing", "authentication")
ReceiptStatus = Literal["sent", "delivered", "read", "failed"]


class ChannelError(Exception):
    def __init__(self, message: str, *, transient: bool, code: str | None = None) -> None:
        super().__init__(message)
        self.transient = transient
        self.code = code


class ChannelNotConfigured(ChannelError):
    def __init__(self, message: str) -> None:
        super().__init__(message, transient=False, code="not_configured")


@dataclass(frozen=True)
class TemplateRef:
    """A provider-approved template (WhatsApp). ``params`` fill the body placeholders in

    order; ``buttons`` are quick-reply payloads, one per button index."""

    name: str
    language: str = "en"
    category: str = "utility"
    params: tuple[str, ...] = ()
    buttons: tuple[str, ...] = ()


@dataclass(frozen=True)
class MessageContent:
    body: str
    subject: str | None = None
    thread_key: str | None = None  # provider thread/conversation id to continue
    in_reply_to: str | None = None  # provider id of the message being answered
    # WhatsApp: is the 24-hour customer-service window open for this recipient? The outbox
    # computes it from stored inbound messages; ``None`` means unknown (treated as closed).
    session_window_open: bool | None = None
    reference: str | None = None  # our id (outbox row), for logs and provider metadata
    # Provider details of the message being answered, e.g. ``{"rfc_message_id": "<..>"}``
    # (Gmail threads replies by RFC 5322 Message-ID; Outlook by its Graph message id).
    reply_meta: dict[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class SendResult:
    provider_message_id: str
    thread_key: str | None = None
    meta: dict[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class DeliveryReceipt:
    channel: str
    provider_message_id: str
    status: ReceiptStatus
    timestamp: str | None = None  # provider timestamp (unix seconds as text, or ISO)
    error: str | None = None
    meta: dict[str, Any] = field(default_factory=dict)  # e.g. WhatsApp pricing category


@runtime_checkable
class Channel(Protocol):
    name: str

    async def send(

        self, to: str, content: MessageContent, template: TemplateRef | None = None

    ) -> SendResult: ...

    def parse_inbound(self, payload: Any) -> list[NormalizedEvent]: ...

    def parse_receipts(self, payload: Any) -> list[DeliveryReceipt]: ...


def http_error(status: int, detail: str, *, code: str | None = None) -> ChannelError:
    """Map an HTTP status to a channel error: 408/425/429/5xx are transient."""
    transient = status in (408, 425, 429) or status >= 500
    return ChannelError(f"HTTP {status}: {detail}"[:500], transient=transient, code=code)