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:
+59
-7
@@ -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"]
|
||||
|
||||
Reference in New Issue
Block a user