Files
rag-technical-docs-assistant/app/modules/voice/durable_tools.py
T
11linear11 996435d2ae 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.
2026-10-09 07:59:02 -04:00

77 lines
3.4 KiB
Python

"""Durable admission wraps actual StructuredTool work, never browser event inference."""
import asyncio
import time
from app.infrastructure.blocking import blocking
from sqlalchemy.exc import SQLAlchemyError
class DurableFailure(ValueError):
def __init__(self, code):
self.live_code = code
super().__init__(code)
class DurableTools:
def __init__(self, lifecycle, user, session_id):
self.lifecycle, self.user, self.session_id = lifecycle, user, session_id
async def execute(self, external_id, call, ctx, args, invoke):
row = await blocking(self.lifecycle.admit_tool, self.user, self.session_id,
external_id, call['ref'], args, ctx.execution)
call['ref'], call['durable_id'], call['inserted'] = str(row['public_ref']), row['id'], row['inserted']
if row['inserted']:
result = await invoke()
if ctx.cancelled.is_set():
await blocking(self.lifecycle.cancel_tools, self.user, self.session_id, [call['ref']])
raise ValueError('CANCELLED')
if not await blocking(self.lifecycle.complete_tool, self.user, self.session_id,
row['id'], result, ctx.execution):
raise ValueError('LIVE_SESSION_UNUSABLE')
return result
# Independent callers coalesce through the durable row; no second retrieval.
while True:
if time.monotonic() >= ctx.deadline:
raise TimeoutError("Tool duplicate wait expired")
if ctx.cancelled.is_set():
raise ValueError('CANCELLED')
result = await blocking(self.lifecycle.tool_result, self.user, self.session_id, row['id'], ctx.execution)
if result is not None:
return result
await asyncio.sleep(.025)
async def delivery(self, call, execution):
if 'durable_id' not in call:
return
try:
result = await blocking(self.lifecycle.tool_result, self.user, self.session_id, call['durable_id'], execution, allow_technical_failure=True)
if result != call['result']:
raise ValueError('LIVE_CONTEXT_SYNC_FAILED')
except Exception as exc:
raise DurableFailure(failure_code(exc)) from None
def failure_code(exc):
"""A persistence failure is terminal: no unverified result may continue.
Diagnostics distinguish technical failure from verified authority loss.
"""
if isinstance(exc, DurableFailure):
return exc.live_code
if isinstance(exc, SQLAlchemyError):
return 'DEPENDENCY_UNAVAILABLE'
if isinstance(exc, TimeoutError):
return 'SEARCH_TIMEOUT'
code = str(exc) if isinstance(exc, ValueError) else getattr(exc, 'code', '')
if code in ('AUTH_REQUIRED','ACCOUNT_DISABLED','SESSION_REVOKED','SESSION_EXPIRED',
'CONTEXT_REVOKED','CONVERSATION_STALE','CONVERSATION_CLOSED',
'LIVE_SESSION_EXPIRED','LIVE_SESSION_UNUSABLE'):
return 'CONTEXT_REVOKED'
if code == 'LIVE_CONTEXT_SYNC_FAILED':
return code
if code in ('CANCELLED','TOOL_CANCELLED','SEARCH_CANCELLED'):
return 'SEARCH_CANCELLED'
if code == 'IDEMPOTENCY_CONFLICT':
return 'LIVE_PROVIDER_PROTOCOL_ERROR'
if code in ('SERVICE_BUSY','SEARCH_SATURATED'):
return 'SEARCH_SATURATED'
# Database/connectivity/provider availability never masquerades as revocation.
return 'LIVE_PROVIDER_UNAVAILABLE'