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:
Chris Mendoza
2026-11-20 12:36:28 -05:00
parent 3bfb300a2f
commit 49b180922d
8 changed files with 462 additions and 72 deletions
+62 -6
View File
@@ -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 ─────────────────────────────────────────
+86 -58
View File
@@ -269,7 +269,7 @@ def _iso(value: Any) -> Optional[str]:
def _display_user_text(text: str) -> str:
"""Hide agent-only inline file context from the user-facing transcript."""
"""Hide inline attachments and voice context from the display transcript."""
start = "[Pheby user message]\n"
end = "\n[/Pheby user message]"
if start not in text:
@@ -540,7 +540,8 @@ async def delete_conversation(conversation_id: str) -> bool:
# ═══════════════════════════════════════════════════════════════════════════
async def send_chat(server: Any, conversation_id: str, text: str,
client: Any, request_id: Optional[str],
attachment_ids: Optional[List[str]] = None) -> None:
attachment_ids: Optional[List[str]] = None,
voice_context: Optional[str] = None) -> None:
"""Deliver a user message into the Hermes gateway for this conversation.
The gateway's full pipeline (auth, sessions, tools, approvals, clarify,
@@ -607,10 +608,15 @@ async def send_chat(server: Any, conversation_id: str, text: str,
media_text_inlined.append(inlined)
effective_text = text
if attachment_descs:
if attachment_descs or voice_context is not None:
effective_text = f"[Pheby user message]\n{text}\n[/Pheby user message]"
if inline_blocks:
effective_text += "\n\n" + "\n\n".join(inline_blocks)
if voice_context is not None:
from tools.voice_live import voice_live_turn_note
previous = f"Earlier spoken request that was interrupted: {voice_context}" if voice_context else ""
effective_text += "\n\n" + voice_live_turn_note(previous)
from gateway.platforms.base import MessageEvent, MessageType
event = MessageEvent(
@@ -632,6 +638,8 @@ async def send_chat(server: Any, conversation_id: str, text: str,
if not already_active:
_ACTIVE_RUNS[conversation_id] = {
"run_id": run_id,
"message_id": message_id,
"dispatch_started": False,
"started": asyncio.get_running_loop().time(),
}
_TOOL_EVENTS[conversation_id] = {}
@@ -654,11 +662,16 @@ async def send_chat(server: Any, conversation_id: str, text: str,
"run_id": run_id,
"message_id": draft_message_id,
})
with _RUN_LOCK:
run = _ACTIVE_RUNS.get(conversation_id)
if not run or run["run_id"] != run_id or run.get("cancelling"):
return
run["dispatch_started"] = True
# Track the draft in the adapter so send()/edit_message() associate the
# final text with the announced draft message id.
if getattr(adapter, "_drafts", None) is not None:
adapter._drafts.setdefault(conversation_id, {
"message_id": draft_message_id, "text": ""})
adapter._drafts[conversation_id] = {
"message_id": draft_message_id, "run_id": run_id, "text": ""}
# The base adapter's handle_message() spawns background tasks and
# returns quickly; the eventual reply arrives through adapter.send().
@@ -675,17 +688,19 @@ async def send_chat(server: Any, conversation_id: str, text: str,
except Exception:
with _RUN_LOCK:
current = _ACTIVE_RUNS.get(conversation_id)
if current and current.get("run_id") == run_id:
_ACTIVE_RUNS.pop(conversation_id, None)
if getattr(adapter, "_drafts", None) is not None:
adapter._drafts.pop(conversation_id, None)
await server.broadcast({
"type": proto.S_RUN_FINISHED,
"conversation_id": conversation_id,
"run_id": run_id,
"status": "failed",
"error": "Gateway rejected the message",
})
failed = bool(current and current["run_id"] == run_id and not current.get("cancelling"))
if failed:
del _ACTIVE_RUNS[conversation_id]
if getattr(adapter, "_drafts", None) is not None:
adapter._drafts.pop(conversation_id, None)
if failed:
await server.broadcast({
"type": proto.S_RUN_FINISHED,
"conversation_id": conversation_id,
"run_id": run_id,
"status": "failed",
"error": "Gateway rejected the message",
})
raise
@@ -697,7 +712,7 @@ def active_run(conversation_id: str) -> Optional[Dict[str, Any]]:
def active_run_id(conversation_id: str) -> Optional[str]:
run = active_run(conversation_id)
return str(run["run_id"]) if run else None
return str(run["run_id"]) if run and not run.get("cancelling") else None
def record_tool_event(conversation_id: str, event: Dict[str, Any]) -> None:
@@ -729,14 +744,14 @@ def runtime_snapshot(conversation_id: str) -> Dict[str, Any]:
}
def note_run_finished(conversation_id: str, status: str = "completed",
def note_run_finished(conversation_id: str, run_id: Optional[str], status: str = "completed",
error: Optional[str] = None) -> None:
"""Called by the adapter when a turn completes/fails."""
with _RUN_LOCK:
run = _ACTIVE_RUNS.pop(conversation_id, None)
if run is None:
return
run_id = run["run_id"]
run = _ACTIVE_RUNS.get(conversation_id)
if not run or run["run_id"] != run_id or run.get("cancelling"):
return
del _ACTIVE_RUNS[conversation_id]
server = _current_server()
if server is None:
return
@@ -758,45 +773,58 @@ def note_run_finished(conversation_id: str, status: str = "completed",
async def cancel_run(conversation_id: str, run_id: Optional[str]) -> bool:
"""Cancel an active run via Hermes's supported interrupt path."""
"""Hold the conversation slot until Hermes has released the interrupted turn."""
adapter = _current_adapter()
run = active_run(conversation_id)
if run is None:
return False
if run_id and run["run_id"] != run_id:
return False # stale run id — nothing to cancel
session_key = _session_key_for(conversation_id)
runner = _runner()
with _RUN_LOCK:
run = _ACTIVE_RUNS.get(conversation_id)
if not run or run.get("cancelling") or (run_id and run["run_id"] != run_id):
return False
run["cancelling"] = True
interrupted = False
if runner is not None:
# Preferred: gateway's own /stop dispatch (cancels task + drains).
running = getattr(runner, "_running_agents", {}).get(session_key)
agent = running if running is not None else None
interrupt = getattr(agent, "interrupt", None)
if callable(interrupt):
try:
interrupt("Cancelled by Pheby client")
invalidate = getattr(
runner, "_invalidate_session_run_generation", None)
if callable(invalidate):
invalidate(session_key, reason="pheby_cancel")
interrupted = True
except Exception:
logger.debug("[pheby] agent interrupt failed", exc_info=True)
if not interrupted and adapter is not None:
try:
event = getattr(adapter, "_active_sessions", {}).get(session_key)
if event is not None:
await adapter.interrupt_session_activity(
session_key, conversation_id)
interrupted = True
except Exception:
logger.debug("[pheby] adapter interrupt failed", exc_info=True)
if interrupted:
try:
if not run.get("dispatch_started", True):
interrupted = True
return True
runner = _runner()
session_key = _session_key_for(conversation_id)
agent = getattr(runner, "_running_agents", {}).get(session_key)
active = getattr(adapter, "_active_sessions", {}).get(session_key)
stop = getattr(runner, "_handle_stop_command", None)
if callable(stop) and (agent is not None or active is not None):
from gateway.platforms.base import MessageEvent, MessageType
# Reuse /stop's runtime cancellation and cache cleanup without
# admitting a synthetic user message or sending its notice.
await stop(MessageEvent(text="/stop", message_type=MessageType.TEXT,
source=_source_for(conversation_id)))
elif callable(getattr(agent, "interrupt", None)):
agent.interrupt("Cancelled by Pheby client")
invalidate = getattr(runner, "_invalidate_session_run_generation", None)
if callable(invalidate):
invalidate(session_key, reason="pheby_cancel")
elif active is not None:
await adapter.interrupt_session_activity(session_key, conversation_id)
else:
return False
cancel_processing = getattr(adapter, "cancel_session_processing", None)
if active is not None and callable(cancel_processing):
await cancel_processing(session_key, discard_pending=False)
interrupted = True
return True
except Exception:
logger.exception("[pheby] run interruption failed")
return False
finally:
with _RUN_LOCK:
_ACTIVE_RUNS.pop(conversation_id, None)
return interrupted
if _ACTIVE_RUNS.get(conversation_id) is run:
if interrupted:
drafts = getattr(adapter, "_drafts", None)
if drafts is not None:
drafts.pop(conversation_id, None)
del _ACTIVE_RUNS[conversation_id]
else:
run.pop("cancelling", None)
# ═══════════════════════════════════════════════════════════════════════════
+59 -7
View File
@@ -5,6 +5,7 @@ Listens on localhost/plain HTTP behind Caddy. Routes:
* ``GET /health`` — unauthenticated liveness (minimal info).
* ``GET /ws`` — WebSocket; first frame must be ``hello``.
* ``GET /attachments/{id}`` — authenticated attachment download (streamed).
* ``GET /voice-live/status`` and ``POST /voice-live/session`` — authenticated WebRTC setup.
All message routing lives in :meth:`PhebyServer.handle_client_message`;
Hermes integration (runs, approvals, clarifications, models) lives in
@@ -15,6 +16,7 @@ from __future__ import annotations
import asyncio
import ipaddress
import json
import logging
import time
from urllib.parse import quote
@@ -23,7 +25,7 @@ from typing import Any, Dict, List, Optional
from aiohttp import web
from . import protocol as proto
from . import protocol as proto, voice_live
from .attachments import AttachmentStore, constant_time_equals
from .config import PhebyConfig
from .conversations import ConversationRouter
@@ -68,6 +70,8 @@ class PhebyServer:
app.router.add_get("/attachments/{attachment_id}",
self._handle_attachment_download)
app.router.add_post("/attachments", self._handle_attachment_upload)
app.router.add_get("/voice-live/status", self._handle_voice_status)
app.router.add_post("/voice-live/session", self._handle_voice_session)
self._app = app
self._runner = web.AppRunner(app, access_log=None)
await self._runner.setup()
@@ -140,6 +144,39 @@ class PhebyServer:
return False
return constant_time_equals(token, self.config.secret)
async def _handle_voice_status(self, request: web.Request) -> web.Response:
if not self._check_http_secret(request):
return _voice_error(401, proto.ERR_UNAUTHORIZED, "Authentication required")
try:
status = await voice_live.status(self.adapter)
except voice_live.Unavailable as exc:
status = {"available": False, "reason": str(exc)}
return web.json_response(status, headers={"Cache-Control": "no-store"})
async def _handle_voice_session(self, request: web.Request) -> web.Response:
if not self._check_http_secret(request):
return _voice_error(401, proto.ERR_UNAUTHORIZED, "Authentication required")
try:
body = bytearray()
async with asyncio.timeout(10):
async for chunk in request.content.iter_chunked(8192):
body.extend(chunk)
if len(body) > 64 * 1024:
return _voice_error(413, proto.ERR_TOO_LARGE, "Voice offer is too large")
payload = json.loads(body)
except (ValueError, TimeoutError, RecursionError):
return _voice_error(400, proto.ERR_BAD_REQUEST, "A JSON voice offer is required")
sdp = payload.get("sdp") if isinstance(payload, dict) else None
if not isinstance(sdp, str) or not sdp.strip():
return _voice_error(400, proto.ERR_BAD_REQUEST, "An SDP offer is required")
try:
result = await voice_live.create_session(self.adapter, sdp)
except voice_live.Unavailable as exc:
return _voice_error(503, "voice_unavailable", str(exc))
except voice_live.ExchangeFailed:
return _voice_error(502, "voice_setup_failed", "Hermes could not start the GPT-Live session")
return web.json_response(result, headers={"Cache-Control": "no-store"})
async def _handle_attachment_download(
self, request: web.Request) -> web.StreamResponse:
attachment_id = request.match_info.get("attachment_id", "")
@@ -384,6 +421,7 @@ class PhebyServer:
if not self.config.log_chat_content and mtype == proto.C_CHAT_SEND:
safe = dict(safe)
safe["text"] = f"<{len(str(message.get('text', '')))} chars>"
safe.pop("voice_context", None)
logger.info("[pheby] << %s", proto.safe_str(safe, 400))
try:
@@ -531,6 +569,11 @@ class PhebyServer:
proto.ERR_TOO_LARGE,
f"text exceeds {proto.MAX_TEXT_CHARS} chars", request_id))
return
voice_context = message.get("voice_context")
if voice_context is not None and (not isinstance(voice_context, str) or len(voice_context) > 6000):
await client.send_json(proto.error_event(
proto.ERR_BAD_REQUEST, "voice_context must contain at most 6000 characters", request_id))
return
raw_ids = message.get("attachment_ids")
attachment_ids: List[str] = []
if raw_ids is not None:
@@ -559,7 +602,7 @@ class PhebyServer:
attachment_ids.append(aid)
await self.bridge.send_chat(
self, conversation_id, text, client, request_id,
attachment_ids=attachment_ids)
attachment_ids=attachment_ids, voice_context=voice_context)
async def _handle_run_cancel(self, client, message, request_id):
conversation_id = str(message.get("conversation_id", ""))
@@ -568,6 +611,10 @@ class PhebyServer:
proto.ERR_BAD_REQUEST, "Invalid conversation_id", request_id))
return
requested_run_id = message.get("run_id")
if requested_run_id is not None and (not isinstance(requested_run_id, str) or not requested_run_id):
await client.send_json(proto.error_event(
proto.ERR_BAD_REQUEST, "Invalid run_id", request_id))
return
active = self.bridge.active_run(conversation_id)
run_id = active.get("run_id") if active else requested_run_id
ok = await self.bridge.cancel_run(conversation_id, requested_run_id)
@@ -575,15 +622,15 @@ class PhebyServer:
await client.send_json(proto.error_event(
proto.ERR_NOT_FOUND, "No matching active run", request_id))
return
if self.adapter is not None:
self.adapter._drafts.pop(conversation_id, None)
await self.broadcast({
event = {
"type": proto.S_RUN_FINISHED,
"conversation_id": conversation_id,
"run_id": run_id,
"status": "cancelled",
**({"request_id": request_id} if request_id else {}),
})
}
if request_id:
await client.send_json({**event, "request_id": request_id})
await self.broadcast(event)
async def _handle_approval_respond(self, client, message, request_id):
approval_id = str(message.get("approval_id", ""))
@@ -758,4 +805,9 @@ class PhebyServer:
}
def _voice_error(status: int, code: str, message: str) -> web.Response:
return web.json_response({"error": {"code": code, "message": message}},
status=status, headers={"Cache-Control": "no-store"})
__all__ = ["PhebyServer"]
+61
View File
@@ -0,0 +1,61 @@
"""Use Hermes's GPT-Live helper in the profile that owns this connector."""
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import Any
class Unavailable(Exception):
pass
class ExchangeFailed(Exception):
pass
def _run(adapter: Any, operation: str, *args: str) -> dict:
try:
from tools import voice_live
except ImportError as exc:
raise Unavailable("This Hermes build does not support GPT-Live") from exc
from agent.secret_scope import (
build_profile_secret_scope, reset_secret_scope, set_secret_scope,
)
from hermes_constants import (
get_hermes_home, reset_hermes_home_override, set_hermes_home_override,
)
home = Path(getattr(adapter, "hermes_home", None) or get_hermes_home())
home_token = set_hermes_home_override(str(home))
try:
secret_token = set_secret_scope(build_profile_secret_scope(home))
try:
return getattr(voice_live, operation)(*args)
finally:
reset_secret_scope(secret_token)
finally:
reset_hermes_home_override(home_token)
async def status(adapter: Any) -> dict:
result = await asyncio.to_thread(_run, adapter, "resolve_gpt_live_status")
return {key: result.get(key) for key in ("available", "reason", "model", "voice")}
async def create_session(adapter: Any, offer: str) -> dict:
try:
result = await asyncio.to_thread(_run, adapter, "create_webrtc_session", offer)
session_id = result["session"]["id"]
answer = result["transport"]["sdp"]
except ValueError as exc:
if str(exc).startswith("GPT-Live needs an OpenAI API key"):
raise Unavailable("Hermes needs an OpenAI API key for GPT-Live") from exc
raise ExchangeFailed from exc
except (OSError, RuntimeError, KeyError, TypeError) as exc:
raise ExchangeFailed from exc
if not isinstance(session_id, str) or not session_id or not isinstance(answer, str) or not answer.strip():
raise ExchangeFailed
return {"session_id": session_id, "sdp": answer}