feat(voice): add authenticated Phase 2 live lifecycle

Add cookie authentication, owned conversations, durable Live reservations,
tool completion/replay fencing, revocation, and startup reconciliation.
Introduce forward lifecycle/owner-chain migrations and the temporary Gemini
adapter while preserving the existing OpenAI Realtime adapter.

Include the executable audio client, regression coverage, configuration,
API/database documentation, and recorded acceptance evidence.

Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript
syntax, and whitespace checks passed. Full PostgreSQL/provider-free results
are recorded in the repair report; real-provider/browser acceptance is unrun.

Follow-up work remains for configurable OpenAI/Gemini selection, transport
admission, authority diagnostics, playback message bounds, and client replay
identity after ambiguous creation responses.
This commit is contained in:
11linear11
2026-10-09 07:59:02 -04:00
parent 07245cd5ca
commit 996435d2ae
42 changed files with 4551 additions and 88 deletions
+283
View File
@@ -0,0 +1,283 @@
"""V01-V04 and supervised, cookie-authenticated Gemini stream."""
import asyncio
from dataclasses import asdict
import json
import logging
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, Response, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, ConfigDict
from app.api.v1.dependencies import (get_auth_service, get_current_user, get_engine,
get_lifecycle_service, get_search_service, get_tool_runner, get_voice_settings, require_csrf, error)
from app.infrastructure.blocking import blocking
from app.modules.auth.service import COOKIE_NAME, UserContext, check_origin
from app.modules.voice.lifecycle import LiveLifecycleService
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.durable_tools import DurableTools
from app.modules.voice import registry
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.evidence import RETRIEVAL_POLICY
from app.modules.documents.settings import IngestionSettings
logger = logging.getLogger(__name__)
router = APIRouter(prefix='/voice/sessions', tags=['Voice Sessions'])
ACTIVE_MEDIA_SESSIONS = set()
# Event-loop-local guard mutation has no await between membership check and insertion.
def close_affected_runtimes(organization_id, new_epoch=0):
return registry.notify(organization_id=organization_id, new_epoch=new_epoch)
class CreateLiveSessionRequest(BaseModel):
model_config = ConfigDict(extra='forbid')
conversation_id: UUID
client_request_id: UUID
class LiveSessionResponse(BaseModel):
session_id: str
conversation_id: str
status: str
stream_path: str | None
expires_at: str
poll_url: str
class CloseLiveSessionResponse(BaseModel):
session_id: str
status: str
close_reason: str | None = None
def capability(config):
config.require_voice()
try:
if config.search_calibration_report is None:
raise ValueError('CALIBRATION_REQUIRED')
cutoff = load_cutoff(json.loads(config.search_calibration_report.read_text(encoding='utf-8')))
if (cutoff.profile != asdict(IngestionSettings().embedding_profile)
or cutoff.retrieval_policy != RETRIEVAL_POLICY):
raise ValueError('CALIBRATION_REQUIRED')
except (OSError, ValueError, KeyError, TypeError, AttributeError):
raise ValueError('CALIBRATION_REQUIRED') from None
return cutoff
@router.post('', response_model=LiveSessionResponse, status_code=201)
def create_voice_session(req: CreateLiveSessionRequest, response: Response,
user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)],
_csrf: Annotated[None, Depends(require_csrf)] = None):
try:
# Recover replay before capability checks: a configuration change cannot alter identity.
try:
result = lifecycle.recover_live_session(user, req.client_request_id)
except ValueError as exc:
if str(exc) != 'SESSION_NOT_FOUND':
raise
else:
if result['conversation_id'] != str(req.conversation_id):
raise ValueError('IDEMPOTENCY_CONFLICT')
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id)
response.status_code = 201 if result['status'] == 'connected' else 202
response.headers['Idempotency-Replayed'] = 'true'
return result
cutoff = capability(config)
profile = config.profile()
profile["search"] = {"embedding": cutoff.profile, "calibration_id": cutoff.calibration_id,
"retrieval_policy": cutoff.retrieval_policy, "distance": cutoff.distance}
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id,
provider=config.provider, model=config.gemini_model, execution_profile=profile)
except ValueError as exc:
raise error(str(exc)) from None
if result['replayed']:
response.status_code = 201 if result['status'] == 'connected' else 202
response.headers['Idempotency-Replayed'] = 'true'
return result
@router.get('/by-request/{client_request_id}', response_model=LiveSessionResponse)
def recover(client_request_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)]):
try:
return lifecycle.recover_live_session(user, client_request_id)
except ValueError as exc:
raise error(str(exc)) from None
@router.get('/{session_id}')
def poll(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)]):
try:
return lifecycle.get_live_session(user, session_id)
except ValueError as exc:
raise error(str(exc)) from None
@router.post('/{session_id}/close', response_model=CloseLiveSessionResponse)
def close(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
_csrf: Annotated[None, Depends(require_csrf)] = None):
try:
return lifecycle.close_live_session(user, session_id)
except ValueError as exc:
raise error(str(exc)) from None
async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle_service,
engine, search_service, tool_runner, config=None):
config = config or VoiceSettings()
if (websocket.query_params or not check_origin(websocket.headers.get('origin'), websocket.headers.get('host'),
config.trusted_origins, config.trusted_hosts, required=True)):
await websocket.close(code=1008, reason='Stream unavailable')
return
try:
user = await blocking(auth_service.get_current_user, websocket.cookies.get(COOKIE_NAME))
info = await blocking(lifecycle_service.validate_stream, user, session_id, initial=True)
config.require_voice()
if search_service.cutoff is None:
raise ValueError('CALIBRATION_REQUIRED')
if (info['provider'] != 'gemini' or info['model'] != config.gemini_model
or any(info['execution_profile'].get(k) != v for k,v in config.profile().items())
or info['execution_profile'].get('search') != {
'embedding': search_service.cutoff.profile, 'calibration_id': search_service.cutoff.calibration_id,
'retrieval_policy': search_service.cutoff.retrieval_policy, 'distance': search_service.cutoff.distance}):
raise ValueError('LIVE_SESSION_UNUSABLE')
except Exception as exc:
logger.info('Stream admission rejected: %s', type(exc).__name__)
await websocket.close(code=1008, reason='Stream unavailable')
return
if session_id in ACTIVE_MEDIA_SESSIONS or len(ACTIVE_MEDIA_SESSIONS) >= config.max_provider_sessions:
await websocket.close(code=1008, reason='Stream unavailable')
return
ACTIVE_MEDIA_SESSIONS.add(session_id)
runtime = adapter = None
children = []
outcome, failed = 'LIVE_TRANSPORT_FAILED', True
client_closed = False
ready_sent = asyncio.Event()
async def close_client(code=1000):
nonlocal client_closed
if not client_closed:
client_closed = True
try:
await websocket.close(code=code, reason='Voice session stopped')
except (RuntimeError, WebSocketDisconnect):
pass
try:
# Guard is released even if accept fails.
await websocket.accept()
limits = RuntimeSettings()
transport = await asyncio.wait_for(connect_gemini(config.gemini_api_key.get_secret_value(),
config.gemini_model, config.gemini_proxy, limits), limits.connect_timeout_seconds)
adapter = GeminiLiveAdapter(transport, model=config.gemini_model, voice=config.gemini_voice, settings=limits)
async def authority_check(execution):
nonlocal outcome
try:
await blocking(lifecycle_service.validate_stream, user, session_id, runtime.session_execution)
await blocking(lifecycle_service.validate_stream, user, session_id, execution)
except ValueError as exc:
outcome = str(exc)
raise
return True
store = DurableTools(lifecycle_service, user, session_id)
async def emit(event):
if isinstance(event,bytes):
await websocket.send_bytes(event)
else:
if event['type'] == 'sources':
for response, call in runtime.calls.values():
if call['ref'] == event['tool_call_id']:
await store.delivery(call, response.turn.execution)
if event['type'] == 'turn_interrupted':
await blocking(lifecycle_service.cancel_tools, user, session_id, event['cancelled_tool_call_ids'])
await websocket.send_text(json.dumps(event,ensure_ascii=False))
if event['type'] == 'session_ready':
ready_sent.set()
await blocking(lifecycle_service.mark_connected, user, session_id)
runtime = VoiceRuntime(adapter, search_service, tool_runner, user.id, emit,
authority_check=authority_check, session_id=str(session_id), settings=limits,
close_client=close_client, tool_store=store)
registry.register(session_id, user.organization_id, info['access_epoch'], user.auth_session_id, runtime)
await runtime.start()
async def browser():
while runtime.usable:
message = await websocket.receive()
if message['type'] == 'websocket.disconnect':
return
if not runtime.ready and ready_sent.is_set():
await asyncio.wait_for(runtime.ready_signal.wait(), limits.send_timeout_seconds)
if message.get('bytes') is not None:
await runtime.input_audio(message['bytes'])
elif message.get('text') is not None:
await runtime.client_control(message['text'].encode('utf-8'))
async def monitor():
nonlocal outcome
while runtime.usable:
await asyncio.sleep(.25)
try:
await blocking(lifecycle_service.validate_stream, user, session_id)
except ValueError as exc:
outcome = str(exc)
async with runtime.lock:
runtime.fail('CONTEXT_REVOKED')
return
children = [asyncio.create_task(browser()), asyncio.create_task(runtime.receive_loop()),
asyncio.create_task(monitor()), asyncio.create_task(runtime.failure_signal.wait())]
done, pending = await asyncio.wait(children, return_when=asyncio.FIRST_COMPLETED)
for task in done:
if not task.cancelled():
exc = task.exception()
if exc:
raise exc
if runtime.failure:
# Give its terminal-error delivery its bounded opportunity before cancellation.
try:
await asyncio.wait_for(runtime.error_delivered.wait(), limits.send_timeout_seconds)
except TimeoutError:
pass
outcome = outcome if outcome not in ('connection_closed', 'LIVE_TRANSPORT_FAILED') else runtime.failure
failed = outcome.startswith('LIVE_') or outcome in ('SEARCH_TIMEOUT','SEARCH_SATURATED','DEPENDENCY_UNAVAILABLE','SEARCH_CANCELLED')
except WebSocketDisconnect:
outcome = 'LIVE_TRANSPORT_FAILED'
failed = True
except Exception:
if runtime and runtime.failure:
outcome = runtime.failure
else:
outcome = 'LIVE_SETUP_FAILED' if runtime is None or not runtime.ready else 'LIVE_TRANSPORT_FAILED'
failed = True
finally:
async def cleanup():
try:
for task in children:
task.cancel()
await asyncio.gather(*children, return_exceptions=True)
try:
if runtime:
await asyncio.wait_for(runtime.close(), 6)
elif adapter:
await asyncio.wait_for(adapter.close(), 6)
except Exception:
logger.warning('Bounded provider cleanup incomplete')
try:
await blocking(lifecycle_service.finish_session, user, session_id, outcome, failed=failed)
except Exception:
logger.warning('Live terminal persistence unavailable')
await asyncio.wait_for(close_client(runtime.close_code or 1000 if runtime else 1011), 5)
finally:
registry.unregister(session_id)
ACTIVE_MEDIA_SESSIONS.discard(session_id)
# An ASGI disconnect can cancel its route after close was delivered. Cleanup
# owns a separate task so cancellation cannot strand the media guard.
cleaning = asyncio.create_task(cleanup())
try:
await asyncio.shield(cleaning)
except asyncio.CancelledError:
# Owning-loop registry/shutdown tracks this independent completion.
raise
@router.websocket('/{session_id}/stream')
async def stream(websocket: WebSocket, session_id: UUID,
engine=Depends(get_engine), auth_service=Depends(get_auth_service), lifecycle=Depends(get_lifecycle_service),
runner=Depends(get_tool_runner), search=Depends(get_search_service), config=Depends(get_voice_settings)):
if not websocket.app.state.ready:
await websocket.close(code=1013,reason='Service unavailable')
return
await handle_stream_websocket(websocket,session_id,auth_service,lifecycle,engine,search,runner,config)