diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 85a26fe..3a63110 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -210,7 +210,27 @@ another `chat.send` receives `run_active`. Never infer state from text. Cancellation uses Hermes's supported interrupt mechanism (agent interrupt + run-generation invalidation) — the conversation stays consistent and resumable. A stale `run_id`, missing run, or run that Hermes can no longer -interrupt returns `not_found`; success emits exactly one cancelled event. +interrupt returns `not_found`. If the request carries a `request_id`, the caller +gets a correlated `run.finished` reply. Every authenticated client also gets the +same terminal event without the request ID. + +### GPT-Live setup + +Both HTTP routes accept `Authorization: Bearer `. + +- `GET /voice-live/status` returns `available`, `reason`, `model`, and `voice` + when supported. Availability describes whether Hermes can resolve a key. +- `POST /voice-live/session` accepts `{"sdp":""}` and returns + `{"session_id":"","sdp":""}`. Keep SDP line + endings intact. The connector supplies the Hermes voice prompt and uses + client delegation. + +Submit a delegated voice turn through `chat.send` with the existing +`conversation_id`. `voice_context` marks a spoken turn and can include the +superseded request for a correction (up to 6000 characters, or an empty string +for the initial request). Hermes receives the context as a turn note. The +`run_id` in `run.accepted` correlates the primary +`message.complete` and `run.finished` with that turn. --- diff --git a/docs/README.md b/docs/README.md index 4b1891c..7b27ef3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -144,6 +144,7 @@ pheby.example.com { # WebSocket + API reverse_proxy /ws 127.0.0.1:8620 reverse_proxy /attachments/* 127.0.0.1:8620 + reverse_proxy /voice-live/* 127.0.0.1:8620 reverse_proxy /health 127.0.0.1:8620 # Optionally restrict by source when on a public VPS: @@ -210,6 +211,15 @@ Notes: --- +## GPT-Live Voice Mode + +Voice Mode uses the installed Hermes `tools.voice_live` helper for the same +gateway profile that owns Pheby. Configure an OpenAI key for that profile +(`OPENAI_API_KEY` or `voice.gpt_live.api_key`). The connector authenticates +call setup with the Pheby secret and gives the app an SDP answer. Android +exchanges audio with OpenAI over WebRTC and submits delegated turns through +the existing chat connection. + ## Debugging & logging Set `PHEBY_DEBUG=true` (env) or `extra.debug: true` (YAML) for verbose diff --git a/plugin/pheby/adapter.py b/plugin/pheby/adapter.py index 1b2936b..81df6a4 100644 --- a/plugin/pheby/adapter.py +++ b/plugin/pheby/adapter.py @@ -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 ───────────────────────────────────────── diff --git a/plugin/pheby/hermes_bridge.py b/plugin/pheby/hermes_bridge.py index ba0e988..c1918fc 100644 --- a/plugin/pheby/hermes_bridge.py +++ b/plugin/pheby/hermes_bridge.py @@ -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) # ═══════════════════════════════════════════════════════════════════════════ diff --git a/plugin/pheby/server.py b/plugin/pheby/server.py index bd79712..a1d2d6b 100644 --- a/plugin/pheby/server.py +++ b/plugin/pheby/server.py @@ -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"] diff --git a/plugin/pheby/voice_live.py b/plugin/pheby/voice_live.py new file mode 100644 index 0000000..7a60d42 --- /dev/null +++ b/plugin/pheby/voice_live.py @@ -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} diff --git a/tests/test_pheby.py b/tests/test_pheby.py index 29fe562..3d4f715 100644 --- a/tests/test_pheby.py +++ b/tests/test_pheby.py @@ -1155,6 +1155,24 @@ class TestBridge: ok = await hb.cancel_run("convY", "wrong-run") assert ok is False + @pytest.mark.asyncio + async def test_cancel_ack_is_private_and_terminal_event_is_broadcast(self, tmp_path): + server = make_server(tmp_path) + caller, other = FakeClientConnection(), FakeClientConnection() + caller.authenticated = other.authenticated = True + server._clients.update(caller=caller, other=other) + server.adapter.gateway_runner = runner = FakeRunner() + runner._running_agents["agent:main:pheby:dm:voice-chat"] = FakeAgent() + from pheby import hermes_bridge as hb + hb._ACTIVE_RUNS["voice-chat"] = {"run_id": "voice-run", "started": 0} + + await server._handle_run_cancel(caller, {"conversation_id": "voice-chat", "run_id": "voice-run"}, "r1") + + event = {"type": "run.finished", "conversation_id": "voice-chat", "run_id": "voice-run", "status": "cancelled"} + assert caller.ws.events() == [{**event, "request_id": "r1"}, event] + assert other.ws.events() == [event] + assert hb.active_run_id("voice-chat") is None + @pytest.mark.asyncio async def test_reasoning_set_validation(self, tmp_path): from pheby import hermes_bridge as hb @@ -1404,6 +1422,34 @@ class TestAdapterUnits: assert [e["type"] for e in client.ws.events()][-2:] == [ proto.S_MESSAGE_COMPLETE, proto.S_RUN_FINISHED] + @pytest.mark.asyncio + async def test_cancelled_task_delivery_does_not_finish_successor(self, tmp_path, monkeypatch): + from gateway.config import PlatformConfig + from gateway.platforms.base import BasePlatformAdapter + from pheby import hermes_bridge as hb + + server = make_server(tmp_path) + listener = FakeClientConnection() + listener.authenticated = True + server._clients["listener"] = listener + adapter = PhebyAdapter(PlatformConfig(enabled=True)) + adapter._server = server + conv = "voice-replacement" + adapter._drafts[conv] = {"run_id": "new", "message_id": "draft-new", "text": ""} + monkeypatch.setitem(hb._ACTIVE_RUNS, conv, {"run_id": "new", "started": 0}) + + async def late_delivery(self, event, key): + await self.send(conv, "old final") + await self.edit_message(conv, "draft-old", "old edit", finalize=True) + + monkeypatch.setattr(BasePlatformAdapter, "_process_message_background", late_delivery) + event = SimpleNamespace(metadata={"pheby_run_id": "old"}, source=SimpleNamespace(chat_id=conv)) + await adapter._process_message_background(event, "session-key") + + assert hb.active_run_id(conv) == "new" + assert adapter._drafts[conv]["message_id"] == "draft-new" + assert listener.ws.events() == [] + def test_transport_auth_is_gateway_authorization(self): from pheby.adapter import PhebyAdapter from gateway.config import PlatformConfig diff --git a/tests/test_voice_live.py b/tests/test_voice_live.py new file mode 100644 index 0000000..1e31070 --- /dev/null +++ b/tests/test_voice_live.py @@ -0,0 +1,117 @@ +import aiohttp +import pytest + +from pheby import voice_live +from test_pheby import FakeClientConnection, make_server + + +@pytest.mark.asyncio +async def test_session_uses_hermes_client_delegation_and_owning_profile(tmp_path, monkeypatch): + import io + import json + from types import SimpleNamespace + + from tools import voice_live as upstream + + home = tmp_path / "voice-profile" + home.mkdir() + (home / ".env").write_text("OPENAI_API_KEY=profile-test-key\n") + adapter = SimpleNamespace(hermes_home=home) + + def exchange(request, timeout): + assert request.full_url == "https://api.openai.com/v1/live/sessions" + assert request.get_header("Authorization") == "Bearer profile-test-key" + body = json.loads(request.data) + assert body["session"]["delegation"] == {"type": "client"} + assert body["session"]["instructions"] == upstream.LIVE_PERSONA + assert body["transport"] == {"type": "webrtc", "sdp": "offer\r\n"} + return io.BytesIO(b'{"session":{"id":"live-test"},"transport":{"sdp":"answer"}}') + + monkeypatch.setattr(upstream.urllib.request, "urlopen", exchange) + assert (await voice_live.status(adapter))["available"] is True + assert await voice_live.create_session(adapter, "offer\r\n") == {"session_id": "live-test", "sdp": "answer"} + + +@pytest.mark.asyncio +async def test_voice_routes_authenticate_and_preserve_the_sdp_offer(tmp_path, monkeypatch): + server = make_server(tmp_path) + server.config.port = 0 + offers = [] + + async def status(adapter): + return {"available": True, "model": "gpt-live-1"} + + async def create_session(adapter, offer): + offers.append(offer) + return {"session_id": "live-id", "sdp": "answer\r\n"} + + monkeypatch.setattr(voice_live, "status", status) + monkeypatch.setattr(voice_live, "create_session", create_session) + assert await server.start() + try: + port = server._site._server.sockets[0].getsockname()[1] + root = f"http://127.0.0.1:{port}/voice-live" + auth = {"Authorization": f"Bearer {server.config.secret}"} + async with aiohttp.ClientSession() as http: + async with http.get(root + "/status") as response: + assert response.status == 401 + async with http.get(root + "/status", headers=auth) as response: + assert (await response.json())["available"] is True + async with http.post(root + "/session", json={"sdp": "offer"}) as response: + assert response.status == 401 + async with http.post(root + "/session", headers=auth, json={"sdp": " "}) as response: + assert response.status == 400 + async with http.post(root + "/session", headers=auth, json={"sdp": "x" * 65_536}) as response: + assert response.status == 413 + async with http.post(root + "/session", headers=auth, json={"sdp": "offer\r\n"}) as response: + assert response.status == 200 + assert response.headers["Cache-Control"] == "no-store" + assert await response.json() == {"session_id": "live-id", "sdp": "answer\r\n"} + assert offers == ["offer\r\n"] + finally: + await server.stop() + + +@pytest.mark.asyncio +async def test_voice_turn_history_uses_the_current_hermes_store(tmp_path): + from types import SimpleNamespace + + from persistence.conversation.messages import NewMessage + from persistence.conversation.sessions import NewSession + from persistence_assembly import open_persistence, profile_scope + from pheby import hermes_bridge as bridge + + server = make_server(tmp_path) + conversation = "shared-thread" + key = bridge._session_key_for(conversation) + with open_persistence(profile_scope()) as db: + server.adapter.gateway_runner = SimpleNamespace(_session_db=db) + await server.router.ensure_conversation(conversation) + for sid, text in [("prior", "Typed first"), ("current", "Spoken next")]: + db.sessions.create(NewSession(session_id=sid, source="pheby", session_key=key, chat_id=conversation)) + db.messages.append(sid, NewMessage(role="user", content=text)) + await bridge.persist_cron_delivery(conversation, "Scheduled note", {"job_id": "test"}) + + messages, found, more = await bridge.conversation_history(conversation, 10) + assert found and not more + assert [item["text"] for item in messages] == ["Typed first", "Spoken next", "Scheduled note"] + + +@pytest.mark.asyncio +async def test_voice_correction_uses_the_existing_chat_and_displays_only_the_utterance(tmp_path, monkeypatch): + from pheby import hermes_bridge as bridge + + server = make_server(tmp_path) + client = FakeClientConnection() + conversation = "correction-thread" + monkeypatch.setattr(bridge, "_ACTIVE_RUNS", {}) + await server._handle_chat_send(client, { + "conversation_id": conversation, "text": "Thursday instead.", + "voice_context": "Find a train for Friday.", + }, "correction") + + event = server.adapter.handled[-1] + assert event.source.chat_id == conversation + assert bridge._display_user_text(event.text) == "Thursday instead." + assert "Earlier spoken request that was interrupted: Find a train for Friday." in event.text + assert client.ws.events()[0]["type"] == "run.accepted"