Spaces:
Running

File size: 2,758 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
"""Minimal web chat channel: an in-process hub of per-session queues.



The storefront widget posts customer messages (``parse_inbound`` -> ``webchat.message``

events, untrusted) and listens on a session stream (SSE in a later phase). ``send`` puts the

reply on the session's queue. Single-process only: a multi-worker deployment replaces the

hub with Postgres ``LISTEN/NOTIFY`` or Redis pub/sub behind the same two methods.

"""

from __future__ import annotations

import asyncio
import hashlib
import uuid
from typing import Any

from core.agent.state import Event
from core.channels.base import (
    ChannelError,
    DeliveryReceipt,
    MessageContent,
    SendResult,
    TemplateRef,
)
from core.events.intake import NormalizedEvent

MAX_QUEUE = 100


class WebChatHub:
    def __init__(self) -> None:
        self._queues: dict[str, asyncio.Queue[dict[str, Any]]] = {}

    def queue(self, session_id: str) -> asyncio.Queue[dict[str, Any]]:
        return self._queues.setdefault(session_id, asyncio.Queue(MAX_QUEUE))

    def publish(self, session_id: str, message: dict[str, Any]) -> None:
        q = self.queue(session_id)
        if q.full():  # drop the oldest: a chat widget only needs the latest replies
            q.get_nowait()
        q.put_nowait(message)


HUB = WebChatHub()


class WebChatChannel:
    name = "webchat"

    def __init__(self, hub: WebChatHub | None = None) -> None:
        self.hub = hub or HUB

    async def send(

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

    ) -> SendResult:
        if not to:
            raise ChannelError("web chat needs a session id", transient=False)
        mid = f"webchat:{uuid.uuid4()}"
        self.hub.publish(to, {"id": mid, "text": content.body})
        return SendResult(provider_message_id=mid, thread_key=to)

    def parse_inbound(self, payload: Any) -> list[NormalizedEvent]:
        if not isinstance(payload, dict):
            return []
        session, text = payload.get("session_id"), payload.get("text")
        if not session or not isinstance(text, str) or not text.strip():
            return []
        mid = (
            payload.get("message_id")
            or hashlib.sha256(f"{session}:{text}:{payload.get('sent_at')}".encode()).hexdigest()
        )
        event = Event(
            type="webchat.message",
            source="webchat",
            text=text[:4000],
            payload={"message_id": str(mid), "from": str(session), "session_id": str(session)},
        )
        return [NormalizedEvent(event, f"webchat:{session}:{mid}"[:300])]

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