Spaces:
Running

WorkPilot-AI / core /channels /webchat.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
2.76 kB
"""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 []