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:
@@ -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)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
Reference in New Issue
Block a user