feat(pheby): add authenticated GPT-Live voice setup
Use Hermes to exchange WebRTC offers for the connector profile. Keep cancellation acknowledgments private and guard replacement runs against stale delivery.
This commit is contained in:
+62
-6
@@ -20,6 +20,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import logging
|
||||
from contextvars import ContextVar
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
AIOHTTP_AVAILABLE = importlib.util.find_spec("aiohttp") is not None
|
||||
@@ -27,6 +28,7 @@ AIOHTTP_AVAILABLE = importlib.util.find_spec("aiohttp") is not None
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms.base import (
|
||||
BasePlatformAdapter,
|
||||
ProcessingOutcome,
|
||||
SendResult,
|
||||
)
|
||||
from hermes_constants import get_hermes_home
|
||||
@@ -36,6 +38,8 @@ from . import hermes_bridge
|
||||
from .config import PhebyConfig, load_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_processing_run: ContextVar[Optional[tuple[str, str]]] = ContextVar(
|
||||
"pheby_processing_run", default=None)
|
||||
|
||||
class PhebyAdapter(BasePlatformAdapter):
|
||||
"""Serve the Pheby WebSocket/HTTP protocol and map it onto the gateway."""
|
||||
@@ -118,6 +122,44 @@ class PhebyAdapter(BasePlatformAdapter):
|
||||
def _conv_from_chat_id(self, chat_id: str) -> str:
|
||||
return str(chat_id)
|
||||
|
||||
async def _process_message_background(self, event, session_key: str) -> None:
|
||||
# Final delivery and the stream consumer's asyncio task inherit this
|
||||
# turn's ID, even if another run takes over the chat while they unwind.
|
||||
run_id = (event.metadata or {}).get("pheby_run_id")
|
||||
cid = self._conv_from_chat_id(event.source.chat_id)
|
||||
token = _processing_run.set((cid, run_id) if run_id else None)
|
||||
try:
|
||||
await super()._process_message_background(event, session_key)
|
||||
finally:
|
||||
_processing_run.reset(token)
|
||||
|
||||
def _delivery_run(self, conversation_id: str) -> tuple[Optional[str], bool]:
|
||||
active = hermes_bridge.active_run(conversation_id)
|
||||
scoped = _processing_run.get()
|
||||
if scoped and scoped[0] == conversation_id:
|
||||
return scoped[1], bool(active and active["run_id"] == scoped[1]
|
||||
and not active.get("cancelling"))
|
||||
if active and active.get("cancelling"):
|
||||
return None, False
|
||||
return active["run_id"] if active else None, True
|
||||
|
||||
async def on_processing_complete(self, event, outcome: ProcessingOutcome) -> None:
|
||||
await super().on_processing_complete(event, outcome)
|
||||
run_id = (event.metadata or {}).get("pheby_run_id")
|
||||
if not run_id:
|
||||
return
|
||||
cid = self._conv_from_chat_id(event.source.chat_id)
|
||||
if hermes_bridge.active_run_id(cid) != run_id:
|
||||
return
|
||||
pending = self._pending_messages.get(self._event_session_key(event))
|
||||
if pending is not None and (pending.metadata or {}).get("pheby_run_id") == run_id:
|
||||
return
|
||||
# Attachment-only and failed deliveries can finish without send() or a final edit.
|
||||
statuses = {ProcessingOutcome.SUCCESS: "completed", ProcessingOutcome.FAILURE: "failed",
|
||||
ProcessingOutcome.CANCELLED: "cancelled"}
|
||||
self._drafts.pop(cid, None)
|
||||
hermes_bridge.note_run_finished(cid, run_id, statuses[outcome])
|
||||
|
||||
async def send(
|
||||
self,
|
||||
chat_id: str,
|
||||
@@ -149,6 +191,10 @@ class PhebyAdapter(BasePlatformAdapter):
|
||||
await self._server.broadcast(event)
|
||||
return SendResult(success=True, message_id=event["message_id"])
|
||||
|
||||
run_id, current = self._delivery_run(conversation_id)
|
||||
if not current:
|
||||
return SendResult(success=True, message_id=f"draft-{run_id}")
|
||||
|
||||
# Commentary and gateway notices are complete standalone timeline
|
||||
# items. They must not close the primary assistant draft/run.
|
||||
if metadata.get("_interim_send") or metadata.get("non_conversational"):
|
||||
@@ -165,6 +211,11 @@ class PhebyAdapter(BasePlatformAdapter):
|
||||
await self._server.broadcast(event)
|
||||
return SendResult(success=True, message_id=message_id)
|
||||
|
||||
active = hermes_bridge.active_run(conversation_id)
|
||||
if (_processing_run.get() != (conversation_id, run_id) and reply_to and active
|
||||
and active.get("message_id") not in (None, reply_to)):
|
||||
return SendResult(success=True, message_id=f"draft-{run_id}")
|
||||
|
||||
draft = self._drafts.setdefault(conversation_id, {
|
||||
"message_id": f"draft-{proto.new_id()[:12]}", "text": ""})
|
||||
draft["text"] = content
|
||||
@@ -175,7 +226,7 @@ class PhebyAdapter(BasePlatformAdapter):
|
||||
await self._server.broadcast({
|
||||
"type": proto.S_MESSAGE_DELTA,
|
||||
"conversation_id": conversation_id,
|
||||
"run_id": hermes_bridge.active_run_id(conversation_id),
|
||||
"run_id": run_id,
|
||||
"message_id": draft["message_id"],
|
||||
"text": content,
|
||||
"ts": proto.now_iso(),
|
||||
@@ -190,13 +241,13 @@ class PhebyAdapter(BasePlatformAdapter):
|
||||
event = {
|
||||
"type": proto.S_MESSAGE_COMPLETE,
|
||||
"conversation_id": conversation_id,
|
||||
"run_id": hermes_bridge.active_run_id(conversation_id),
|
||||
"run_id": run_id,
|
||||
"message_id": message_id,
|
||||
"text": content,
|
||||
"ts": proto.now_iso(),
|
||||
}
|
||||
await self._server.broadcast(event)
|
||||
hermes_bridge.note_run_finished(conversation_id, "completed")
|
||||
hermes_bridge.note_run_finished(conversation_id, run_id)
|
||||
return SendResult(success=True, message_id=message_id)
|
||||
|
||||
async def edit_message(
|
||||
@@ -217,6 +268,10 @@ class PhebyAdapter(BasePlatformAdapter):
|
||||
if self._server is None:
|
||||
return SendResult(success=False, error="server not running")
|
||||
conversation_id = self._conv_from_chat_id(chat_id)
|
||||
run_id, current = self._delivery_run(conversation_id)
|
||||
existing = self._drafts.get(conversation_id)
|
||||
if not current or (run_id and existing and message_id != existing["message_id"]):
|
||||
return SendResult(success=True, message_id=message_id)
|
||||
draft = self._drafts.setdefault(conversation_id, {
|
||||
"message_id": message_id or f"draft-{proto.new_id()[:12]}",
|
||||
"text": "",
|
||||
@@ -226,15 +281,16 @@ class PhebyAdapter(BasePlatformAdapter):
|
||||
"type": (proto.S_MESSAGE_COMPLETE if finalize
|
||||
else proto.S_MESSAGE_DELTA),
|
||||
"conversation_id": conversation_id,
|
||||
"run_id": hermes_bridge.active_run_id(conversation_id),
|
||||
"run_id": run_id,
|
||||
"message_id": draft["message_id"],
|
||||
"text": content,
|
||||
"ts": proto.now_iso(),
|
||||
}
|
||||
await self._server.broadcast(event)
|
||||
if finalize:
|
||||
self._drafts.pop(conversation_id, None)
|
||||
hermes_bridge.note_run_finished(conversation_id, "completed")
|
||||
if self._drafts.get(conversation_id) is draft:
|
||||
self._drafts.pop(conversation_id, None)
|
||||
hermes_bridge.note_run_finished(conversation_id, run_id)
|
||||
return SendResult(success=True, message_id=draft["message_id"])
|
||||
|
||||
# ── structured stream events ─────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user