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
+65
View File
@@ -0,0 +1,65 @@
"""Deployment configuration, independent of runtime limits and embedding profiles."""
from pathlib import Path
from typing import Literal
from urllib.parse import urlsplit
from pydantic import Field, SecretStr, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class VoiceSettings(BaseSettings):
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True)
provider: Literal['gemini'] = 'gemini'
gemini_api_key: SecretStr = SecretStr('')
gemini_model: str = Field(default='gemini-2.0-flash-exp', min_length=1, max_length=200)
gemini_voice: str = Field(default='Aoede', min_length=1, max_length=80)
gemini_proxy: str | None = None
trusted_origins: tuple[str, ...] = ('http://localhost:8000', 'http://127.0.0.1:8000')
trusted_hosts: tuple[str, ...] = ('localhost:8000', '127.0.0.1:8000')
cookie_secure: bool = True
auth_session_seconds: int = Field(default=28800, ge=60, le=604800)
live_session_seconds: int = Field(default=600, ge=10, le=3600)
search_calibration_report: Path | None = None
max_provider_sessions: int = Field(default=4, ge=1, le=32)
login_attempts_per_minute: int = Field(default=12, ge=1, le=120)
@field_validator('gemini_model', 'gemini_voice')
@classmethod
def identifier(cls, value):
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
raise ValueError('Invalid voice profile identifier')
return value
@field_validator('trusted_origins', 'trusted_hosts', 'gemini_proxy')
@classmethod
def urls(cls, value, info):
if info.field_name == 'gemini_proxy' and value is None:
return value
values = (value,) if info.field_name == 'gemini_proxy' else value
if not values or len(values) > 20:
raise ValueError('Explicit bounded trusted endpoints required')
for entry in values:
try:
p = urlsplit('http://' + entry if info.field_name == 'trusted_hosts' else entry)
port = p.port
except ValueError:
raise ValueError('Invalid endpoint configuration') from None
schemes = ('http', 'https', 'socks5', 'socks5h') if info.field_name == 'gemini_proxy' else ('http', 'https')
if (len(entry) > 512 or p.scheme not in schemes or not p.hostname or p.username
or p.password or p.path or p.query or p.fragment or '*' in entry):
raise ValueError('Invalid endpoint configuration')
return value
@model_validator(mode='after')
def cookie_policy(self):
if not self.cookie_secure and any(urlsplit(o).hostname not in ('localhost', '127.0.0.1', '::1') for o in self.trusted_origins):
raise ValueError('Insecure cookies require loopback-only development origins')
return self
def require_voice(self):
key = self.gemini_api_key.get_secret_value()
if not key or len(key) > 512 or not key.isascii() or any(c.isspace() for c in key):
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
def profile(self):
return dict(provider=self.provider, model=self.gemini_model, voice=self.gemini_voice,
input_sample_rate=16000, output_sample_rate=24000)
+76
View File
@@ -0,0 +1,76 @@
"""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'
+327
View File
@@ -0,0 +1,327 @@
"""Settings-first durable Live transactions. Remote work runs after commit."""
from datetime import datetime, timezone, timedelta
import hashlib
import json
from uuid import UUID, uuid4
from sqlalchemy import text
from app.modules.knowledge.service import SearchInput, authority, transaction, KnowledgeError
ACTIVE = ('creating', 'connecting', 'connected')
TECHNICAL_ERRORS = frozenset(('SEARCH_TIMEOUT','SEARCH_FAILED','SEARCH_SATURATED',
'PROVIDER_TIMEOUT','PROVIDER_UNAVAILABLE','DEPENDENCY_UNAVAILABLE',
'SERVICE_UNAVAILABLE','DATABASE_UNAVAILABLE','SEARCH_UNAVAILABLE',
'CALIBRATION_REQUIRED','PROFILE_MISMATCH','INVALID_CONFIGURATION','INVALID_VECTOR'))
def replayable_error(row):
result = row['result_json']
return (row['status'] == 'failed' and isinstance(result, dict)
and result.get('status') == 'error'
and row['error_code'] in TECHNICAL_ERRORS
and (result.get('error') or {}).get('code') == row['error_code'])
def canonical_hash(data):
return hashlib.sha256(json.dumps(data, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')).hexdigest()
def now():
return datetime.now(timezone.utc)
class LiveLifecycleService:
def __init__(self, engine, session_ttl=timedelta(minutes=10)):
self.engine, self.session_ttl = engine, session_ttl
def _actor(self, conn, user):
try:
current, settings = authority(conn, user.id, exclusive=True)
except KnowledgeError as exc:
raise ValueError("ACCOUNT_DISABLED" if exc.code == "ACTOR_UNAVAILABLE" else "AUTH_REQUIRED") from None
if current['organization_id'] != user.organization_id:
raise ValueError('AUTH_REQUIRED')
auth = conn.execute(text('''SELECT * FROM auth_sessions WHERE id=:auth
AND organization_id=:org AND user_id=:owner FOR SHARE'''),
dict(auth=user.auth_session_id, org=user.organization_id, owner=user.id)).mappings().first()
if auth is None:
raise ValueError('AUTH_REQUIRED')
if auth['revoked_at'] is not None:
raise ValueError('SESSION_REVOKED')
if auth['expires_at'] <= now():
raise ValueError('SESSION_EXPIRED')
return current, settings
def _conversation(self, conn, user, cid, settings):
row = conn.execute(text('''SELECT * FROM conversations WHERE id=:id
AND organization_id=:org AND owner_user_id=:owner FOR UPDATE'''),
dict(id=cid, org=user.organization_id, owner=user.id)).mappings().first()
if row is None:
raise ValueError('CONVERSATION_NOT_FOUND')
if row['mode'] != 'voice':
raise ValueError('MODE_MISMATCH')
if row['status'] == 'closed':
raise ValueError('CONVERSATION_CLOSED')
if row['status'] != 'active' or row['access_epoch'] != settings['access_epoch']:
raise ValueError('CONVERSATION_STALE')
return row
def _session(self, conn, user, sid, settings, *, connected=False):
initial = conn.execute(text('''SELECT conversation_id FROM live_sessions WHERE id=:id
AND organization_id=:org AND owner_user_id=:owner'''),
dict(id=sid, org=user.organization_id, owner=user.id)).mappings().first()
if initial is None:
raise ValueError('SESSION_NOT_FOUND')
self._conversation(conn, user, initial['conversation_id'], settings)
row = conn.execute(text('SELECT * FROM live_sessions WHERE id=:id FOR UPDATE'), {'id': sid}).mappings().one()
if row['expires_at'] <= now():
raise ValueError('LIVE_SESSION_EXPIRED')
if (row['auth_session_id'] != user.auth_session_id or row['status'] not in ACTIVE
or row['expires_at'] <= now() or row['access_epoch'] != settings['access_epoch']
or (connected and row['status'] != 'connected')):
raise ValueError('LIVE_SESSION_UNUSABLE')
return row
@staticmethod
def _shape(row, *, replayed=False, eligible=True):
sid = str(row['id'])
return dict(session_id=sid, conversation_id=str(row['conversation_id']), status=row['status'],
stream_path=f'/api/v1/voice/sessions/{sid}/stream' if eligible else None,
expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed)
@staticmethod
def _terminal(conn, sid, reason, *, failed=False):
stamp = now()
conn.execute(text('''UPDATE live_sessions SET status=:status, closed_at=:now,
close_reason=:reason,error_code=:error,updated_at=:now
WHERE id=:id AND status IN ('creating','connecting','connected')'''),
dict(id=sid, status='failed' if failed else 'closed', now=stamp, reason=reason, error=reason if failed else None))
conn.execute(text('''UPDATE tool_calls SET status='failed',completed_at=:now,error_code=:reason
WHERE live_session_id=:id AND status='running' '''), dict(id=sid, now=stamp, reason=reason))
def expire_reservations(self, user):
# Cleanup commits independently so a later creation conflict cannot undo it.
with transaction(self.engine) as conn:
self._actor(conn, user)
rows = conn.execute(text('''SELECT id FROM live_sessions WHERE organization_id=:org
AND owner_user_id=:owner AND status IN ('creating','connecting','connected') AND expires_at<=:now
ORDER BY conversation_id,id'''), dict(org=user.organization_id, owner=user.id, now=now())).scalars().all()
for sid in rows:
self._terminal(conn, sid, 'LIVE_SESSION_EXPIRED')
def create_conversation(self, user, client_request_id, mode='voice', title=None):
if mode != 'voice':
raise ValueError('MODE_MISMATCH')
legacy_title = title
title = title.strip() if title is not None else None
digest = canonical_hash(dict(mode=mode, title=title))
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
row = conn.execute(text('''SELECT * FROM conversations WHERE owner_user_id=:owner
AND organization_id=:org AND client_request_id=:req'''),
dict(owner=user.id, org=user.organization_id, req=client_request_id)).mappings().first()
replayed = row is not None
if row is not None and row['request_hash'] != digest:
legacy = canonical_hash(dict(user=str(user.id), request=str(client_request_id),
mode=mode, title=legacy_title or ''))
if row['request_hash'] != legacy or row['mode'] != mode or row['title'] != legacy_title:
raise ValueError('IDEMPOTENCY_CONFLICT')
conn.execute(text('UPDATE conversations SET request_hash=:hash WHERE id=:id'),
dict(hash=digest, id=row['id']))
if row is None:
row = conn.execute(text('''INSERT INTO conversations
(id,organization_id,owner_user_id,client_request_id,request_hash,mode,title,access_epoch)
VALUES (:id,:org,:owner,:req,:hash,'voice',:title,:epoch) RETURNING *'''),
dict(id=uuid4(), org=user.organization_id, owner=user.id, req=client_request_id,
hash=digest, title=title, epoch=settings['access_epoch'])).mappings().one()
return dict(id=str(row['id']), mode=row['mode'], title=row['title'], status=row['status'],
access_epoch=row['access_epoch'], created_at=row['created_at'].isoformat(), replayed=replayed)
def create_live_session(self, user, conversation_id, client_request_id, provider='gemini',
model='gemini-2.0-flash-exp', execution_profile=None):
self.expire_reservations(user)
digest = canonical_hash(dict(conversation_id=str(conversation_id)))
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
row = conn.execute(text('''SELECT * FROM live_sessions WHERE organization_id=:org
AND owner_user_id=:owner AND client_request_id=:req'''),
dict(org=user.organization_id, owner=user.id, req=client_request_id)).mappings().first()
if row is not None:
if row['request_hash'] != digest:
# Original Phase 2 included server configuration in V01's hash.
# Verify against the original pinned row, never today's config.
legacy = canonical_hash(dict(owner=str(user.id), conversation_id=str(conversation_id),
client_request_id=str(client_request_id), provider=row['provider'], model=row['model']))
if row['request_hash'] != legacy or row['conversation_id'] != conversation_id:
raise ValueError('IDEMPOTENCY_CONFLICT')
conn.execute(text('UPDATE live_sessions SET request_hash=:hash WHERE id=:id'),
dict(hash=digest, id=row['id']))
self._session(conn, user, row['id'], settings)
return self._shape(row, replayed=True)
self._conversation(conn, user, conversation_id, settings)
if conn.execute(text('''SELECT id FROM live_sessions WHERE conversation_id=:id
AND status IN ('creating','connecting','connected')'''), {'id': conversation_id}).first():
raise ValueError('LIVE_SESSION_BUSY')
row = conn.execute(text('''INSERT INTO live_sessions
(id,organization_id,conversation_id,owner_user_id,auth_session_id,client_request_id,request_hash,
provider,model,status,settings_revision,knowledge_revision,access_epoch,execution_profile,expires_at)
VALUES (:id,:org,:conv,:owner,:auth,:req,:hash,:provider,:model,'connecting',
:revision,:knowledge,:epoch,CAST(:profile AS jsonb),:expires) RETURNING *'''),
dict(id=uuid4(), org=user.organization_id, conv=conversation_id, owner=user.id,
auth=user.auth_session_id, req=client_request_id, hash=digest, provider=provider, model=model,
revision=settings['revision'], knowledge=settings['knowledge_revision'], epoch=settings['access_epoch'],
profile=json.dumps(execution_profile or {}), expires=now()+self.session_ttl)).mappings().one()
return self._shape(row)
def recover_live_session(self, user, client_request_id):
self.expire_reservations(user)
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
row = conn.execute(text('''SELECT * FROM live_sessions WHERE organization_id=:org
AND owner_user_id=:owner AND client_request_id=:req'''),
dict(org=user.organization_id, owner=user.id, req=client_request_id)).mappings().first()
if row is None:
raise ValueError('SESSION_NOT_FOUND')
try:
self._session(conn, user, row['id'], settings)
eligible = row['status'] == 'connecting'
except ValueError:
eligible = False
return self._shape(row, eligible=eligible)
def validate_stream(self, user, session_id, execution=None, *, initial=False):
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
row = self._session(conn, user, session_id, settings)
if initial and row['status'] != 'connecting':
raise ValueError('LIVE_SESSION_UNUSABLE')
if execution is not None and not execution.capture(current, settings['access_epoch']):
raise ValueError('CONTEXT_REVOKED')
return dict(row)
def mark_connected(self, user, session_id):
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
self._session(conn, user, session_id, settings)
conn.execute(text('''UPDATE live_sessions SET status='connected',connected_at=COALESCE(connected_at,now()),
updated_at=now() WHERE id=:id'''), {'id': session_id})
def finish_session(self, user, session_id, reason='user_requested', *, failed=False):
with transaction(self.engine) as conn:
conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE'), {'org': user.organization_id})
row = conn.execute(text('''SELECT * FROM live_sessions WHERE id=:id
AND organization_id=:org AND owner_user_id=:owner'''),
dict(id=session_id, org=user.organization_id, owner=user.id)).mappings().first()
if row is None:
raise ValueError('SESSION_NOT_FOUND')
self._terminal(conn, session_id, reason, failed=failed)
row = conn.execute(text('SELECT * FROM live_sessions WHERE id=:id'), {'id': session_id}).mappings().one()
from app.modules.voice.registry import notify
notify(session_id=session_id)
return dict(session_id=str(session_id), status=row['status'], close_reason=row['close_reason'])
def close_live_session(self, user, session_id, reason='user_requested'):
return self.finish_session(user, session_id, reason)
def _sources(self, conn, org, sources):
result = []
for source in sources:
copied = dict(source)
row = conn.execute(text('''SELECT d.id FROM documents d JOIN document_chunks c
ON c.organization_id=d.organization_id AND c.document_id=d.id
WHERE d.organization_id=:org AND d.id=:doc AND c.id=:chunk
AND d.status='ready' AND d.is_active AND d.deleted_at IS NULL AND d.content_purged_at IS NULL'''),
dict(org=org, doc=UUID(source['document_id']), chunk=UUID(source['chunk_id']))).first()
copied['available'] = row is not None
copied['excerpt'] = copied.pop('text', copied.get('excerpt')) if row else None
if row is None:
copied.pop('text', None)
result.append(copied)
return result
def get_live_session(self, user, session_id):
self.expire_reservations(user)
with transaction(self.engine) as conn:
self._actor(conn, user)
row = conn.execute(text('''SELECT * FROM live_sessions WHERE id=:id AND organization_id=:org
AND owner_user_id=:owner'''), dict(id=session_id, org=user.organization_id, owner=user.id)).mappings().first()
if row is None:
raise ValueError('SESSION_NOT_FOUND')
calls = conn.execute(text('''SELECT * FROM tool_calls WHERE live_session_id=:id
AND organization_id=:org ORDER BY created_at DESC,id DESC LIMIT 20'''),
dict(id=session_id, org=user.organization_id)).mappings().all()
results = [dict(tool_call_id=str(c['public_ref']), status=c['status'], created_at=c['created_at'].isoformat(),
error_code=c['error_code'], sources=self._sources(conn, user.organization_id, (c['result_json'] or {}).get('sources', [])))
for c in reversed(calls)]
return dict(session_id=str(row['id']), status=row['status'], close_reason=row['close_reason'],
expires_at=row['expires_at'].isoformat(), error_code=row['error_code'], recent_tool_results=results)
def admit_tool(self, user, session_id, external_call_id, public_ref, arguments, execution):
arguments = SearchInput.model_validate(arguments).model_dump()
digest = canonical_hash(arguments)
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
self._session(conn, user, session_id, settings, connected=True)
if not execution.capture(current, settings['access_epoch']):
raise ValueError('CONTEXT_REVOKED')
row = conn.execute(text('''SELECT * FROM tool_calls WHERE live_session_id=:sid
AND external_call_id=:ext FOR UPDATE'''), dict(sid=session_id, ext=external_call_id)).mappings().first()
if row:
if row['request_hash'] != digest:
raise ValueError('IDEMPOTENCY_CONFLICT')
if (row['status'] == 'failed' and not replayable_error(row)) or row['access_epoch'] != settings['access_epoch']:
raise ValueError('LIVE_SESSION_UNUSABLE')
if row['result_json'] and any(not s['available'] for s in self._sources(conn, user.organization_id, row['result_json'].get('sources', []))):
raise ValueError('CONTEXT_REVOKED')
return dict(row, inserted=False)
row = conn.execute(text('''INSERT INTO tool_calls
(id,organization_id,live_session_id,external_call_id,public_ref,arguments,request_hash,knowledge_revision,access_epoch)
VALUES (:id,:org,:sid,:ext,:ref,CAST(:args AS jsonb),:hash,:knowledge,:epoch) RETURNING *'''),
dict(id=uuid4(), org=user.organization_id, sid=session_id, ext=external_call_id, ref=UUID(public_ref),
args=json.dumps(arguments), hash=digest, knowledge=settings['knowledge_revision'], epoch=settings['access_epoch'])).mappings().one()
return dict(row, inserted=True)
def tool_result(self, user, session_id, call_id, execution, *, allow_technical_failure=False):
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
self._session(conn, user, session_id, settings, connected=True)
if not execution.matches(current, settings['access_epoch']):
raise ValueError('CONTEXT_REVOKED')
row = conn.execute(text('SELECT * FROM tool_calls WHERE id=:id AND live_session_id=:sid'), dict(id=call_id, sid=session_id)).mappings().one()
if row['status'] == 'failed' and not replayable_error(row):
raise ValueError('LIVE_SESSION_UNUSABLE')
result = row['result_json']
if result and any(not s['available'] for s in self._sources(conn, user.organization_id, result.get('sources', []))):
raise ValueError('CONTEXT_REVOKED')
return result
def complete_tool(self, user, session_id, call_id, result, execution):
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
self._session(conn, user, session_id, settings, connected=True)
if not execution.matches(current, settings['access_epoch']):
raise ValueError('CONTEXT_REVOKED')
if any(not s['available'] for s in self._sources(conn, user.organization_id, result.get('sources', []))):
raise ValueError('CONTEXT_REVOKED')
code = (result.get('error') or {}).get('code') if result.get('status') == 'error' else None
return bool(conn.execute(text('''UPDATE tool_calls SET status=:status,result_json=CAST(:result AS jsonb),
error_code=:error,completed_at=now() WHERE id=:id AND live_session_id=:sid
AND status='running' AND access_epoch=:epoch RETURNING id'''),
dict(id=call_id, sid=session_id, epoch=settings['access_epoch'], status='failed' if code else 'succeeded',
result=json.dumps(result), error=code)).first())
def cancel_tools(self, user, session_id, refs=None, code='TOOL_CANCELLED'):
with transaction(self.engine) as conn:
conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE'), {'org': user.organization_id})
conn.execute(text('''UPDATE tool_calls SET status='failed',completed_at=now(),error_code=:code
WHERE live_session_id=:sid AND organization_id=:org AND status='running'
AND (:all OR public_ref=ANY(CAST(:refs AS uuid[])))'''),
dict(sid=session_id, org=user.organization_id, code=code, all=refs is None, refs=refs or []))
def reconcile_startup(self):
from app.infrastructure.database import LIVE_REVISION
with transaction(self.engine) as conn:
if conn.execute(text('SELECT version_num FROM alembic_version')).scalar_one() != LIVE_REVISION:
raise ValueError('SCHEMA_UNAVAILABLE')
conn.execute(text('SELECT organization_id FROM organization_settings ORDER BY organization_id FOR UPDATE'))
result = conn.execute(text('''UPDATE live_sessions SET status='failed',closed_at=now(),
close_reason='API_RESTARTED',error_code='API_RESTARTED',updated_at=now()
WHERE status IN ('creating','connecting','connected')'''))
conn.execute(text("UPDATE tool_calls SET status='failed',completed_at=now(),error_code='ABANDONED' WHERE status='running'"))
return result.rowcount
+49
View File
@@ -0,0 +1,49 @@
"""Post-commit notifications marshal mutations onto the owning event loop."""
import asyncio
from dataclasses import dataclass, field
from threading import RLock
@dataclass
class Entry:
organization_id: object
epoch: int
auth_session_id: object
runtime: object
loop: asyncio.AbstractEventLoop
finished: asyncio.Event = field(default_factory=asyncio.Event)
ENTRIES = {}
_LOCK = RLock()
def register(session_id, organization_id, epoch, auth_session_id, runtime):
with _LOCK:
ENTRIES[session_id] = Entry(organization_id, epoch, auth_session_id, runtime, asyncio.get_running_loop())
def unregister(session_id):
with _LOCK:
entry = ENTRIES.pop(session_id, None)
if entry:
entry.finished.set()
def notify(*, organization_id=None, new_epoch=None, auth_session_id=None, session_id=None, code='CONTEXT_REVOKED'):
with _LOCK:
selected = [e for sid, e in ENTRIES.items()
if (organization_id is None or e.organization_id == organization_id)
and (new_epoch is None or e.epoch < new_epoch)
and (auth_session_id is None or e.auth_session_id == auth_session_id)
and (session_id is None or sid == session_id)]
async def fail(entry):
async with entry.runtime.lock:
entry.runtime.fail(code)
for entry in selected:
if not entry.loop.is_closed():
entry.loop.call_soon_threadsafe(lambda e=entry: asyncio.create_task(fail(e)))
return len(selected)
async def shutdown():
with _LOCK:
entries = list(ENTRIES.values())
for entry in entries:
async with entry.runtime.lock:
entry.runtime.fail('LIVE_SERVER_SHUTDOWN')
await asyncio.gather(*(e.finished.wait() for e in entries), return_exceptions=True)
+64 -23
View File
@@ -51,7 +51,7 @@ def provider_event_digest(event, limit):
item = event.get("item")
if isinstance(item, dict) and item.get("type") == "function_call":
event = dict(event, item=arguments(item))
elif kind == "response.done":
elif kind in ("response.done", "provider.tools_requested"):
response = event.get("response")
if isinstance(response, dict) and isinstance(response.get("output"), list):
output = [arguments(item) if isinstance(item, dict) and item.get("type") == "function_call"
@@ -158,7 +158,7 @@ class VoiceRuntime:
"""
def __init__(self, adapter, service, runner, user_id, emit, *,
authority_check=None, clock=time.monotonic, tool_seconds=None,
session_id=None, max_calls=None, settings=None, close_client=None):
session_id=None, max_calls=None, settings=None, close_client=None, tool_store=None):
self.settings = settings or getattr(adapter, "settings", None) or RuntimeSettings()
if not isinstance(self.settings, RuntimeSettings):
raise ValueError("Validated runtime settings required")
@@ -168,6 +168,7 @@ class VoiceRuntime:
if (type(tool_seconds) not in (int, float) or not 0 < tool_seconds <= self.settings.tool_timeout_seconds
or type(max_calls) is not int or not 1 <= max_calls <= self.settings.max_tool_calls):
raise ValueError("Invalid backend tool deadline/call bound")
self.tool_store = tool_store
self.close_client = close_client
self.adapter, self.service, self.runner = adapter, service, runner
self.user_id, self.emit, self.clock = user_id, emit, clock
@@ -210,6 +211,7 @@ class VoiceRuntime:
self.intent_count = 0
self.provider_ready = False
self.ready = False
self.ready_signal = asyncio.Event()
self.usable = True
self.failure = None
self.setup_deadline = None
@@ -495,6 +497,8 @@ class VoiceRuntime:
audio.state, audio.timer, audio.stall_deadline = "retired", None, None
async def start(self):
if hasattr(self.adapter, "backlog"):
self.adapter.backlog = lambda: sum(len(a.data) + a.reserved + a.credit for a in self.audio.values())
async with self.lock:
if self._workers:
raise RuntimeError("Runtime already started")
@@ -522,9 +526,10 @@ class VoiceRuntime:
await self.handle(await self.adapter.receive())
except asyncio.CancelledError:
raise
except (ProviderProtocolError, ValueError, TypeError, RecursionError):
except (ProviderProtocolError, ValueError, TypeError, RecursionError) as exc:
async with self.lock:
self.fail("LIVE_PROVIDER_PROTOCOL_ERROR")
self.fail("LIVE_BUFFER_OVERFLOW" if getattr(exc, "overflow", False) else
"LIVE_CONTEXT_SYNC_FAILED" if getattr(exc, "context_sync", False) else "LIVE_PROVIDER_PROTOCOL_ERROR")
except Exception:
async with self.lock:
self.fail("LIVE_CONTEXT_SYNC_FAILED" if self.context_pending()
@@ -554,9 +559,22 @@ class VoiceRuntime:
continue
if kind in ("response.create", "conversation.item.create") and owner:
valid = await self.check_authority(owner)
failure = "CONTEXT_REVOKED"
if valid and self.tool_store:
try:
if kind == "conversation.item.create" and event["item"]["type"] == "function_call_output":
await self.tool_store.delivery(self.calls[event["item"]["call_id"]][1], owner.execution)
elif kind == "response.create":
origin = self.origin_intents.get(event["response"]["metadata"]["voice_intent"])
if origin:
for call in self.responses[origin].calls.values():
await self.tool_store.delivery(call, owner.execution)
except Exception as exc:
from app.modules.voice.durable_tools import failure_code
valid, failure = False, failure_code(exc)
async with self.lock:
if not valid:
self.fail("CONTEXT_REVOKED", turn=owner)
self.fail(failure, turn=owner)
continue
if not self.check_deadlines() or owner is not self.current or owner.superseded:
self.release_command(cmd)
@@ -593,9 +611,9 @@ class VoiceRuntime:
cmd = None
except asyncio.CancelledError:
raise
except Exception:
except Exception as exc:
async with self.lock:
self.fail("LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None)
self.fail("LIVE_CONTEXT_SYNC_FAILED" if getattr(exc, "context_sync", False) else "LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None)
finally:
if cmd:
async with self.lock:
@@ -690,7 +708,7 @@ class VoiceRuntime:
responses = [r for r in self.responses.values() if r.turn is turn]
return (turn.initial and responses and
not (self.pending_create and self.pending_create[1] is turn) and
all(r.terminal and r.status == "completed"
all(r.terminal and r.status in ("completed", "waiting_tools")
and (not r.calls or r.continued) for r in responses)
and all(a.state == "retired" or (
a.done and a.generated == a.sent == a.played == 0
@@ -787,7 +805,7 @@ class VoiceRuntime:
continue
if not response.terminal or any(c["result"] is None for c in response.calls.values()):
continue
if response.status != "completed":
if response.status not in ("completed", "waiting_tools"):
self.fail("LIVE_PROVIDER_UNAVAILABLE")
return
for call_id, call in response.calls.items():
@@ -1000,6 +1018,7 @@ class VoiceRuntime:
if entry:
if self.usable and event["type"] == "session_ready":
self.ready = True
self.ready_signal.set()
if self.usable and event["type"] == "audio_ended":
self.audio[event["audio_ref"]].ended = True
if (self.usable and entry.completed_transcript and entry.response and
@@ -1016,9 +1035,9 @@ class VoiceRuntime:
async with self.lock:
self.fail("LIVE_TRANSPORT_FAILED", turn=owner, writable=False)
raise
except Exception:
except Exception as exc:
async with self.lock:
self.fail("LIVE_TRANSPORT_FAILED", turn=owner, writable=False)
self.fail(getattr(exc, "live_code", "LIVE_TRANSPORT_FAILED"), turn=owner, writable=False)
finally:
async with self.lock:
if entry:
@@ -1104,6 +1123,8 @@ class VoiceRuntime:
async def handle(self, event):
async with self.lock:
if hasattr(self.adapter, "consumed"):
self.adapter.consumed()
if not self.check_deadlines():
return
affected = None
@@ -1134,6 +1155,8 @@ class VoiceRuntime:
kind = event["type"]
if not isinstance(kind, str):
raise ValueError("Event type required")
if kind.startswith("provider.") and not getattr(self.adapter, "native_input_consumption", False):
raise ValueError("Unsupported native adapter event")
if not self.provider_ready and kind not in ("session.created", "session.updated", "error"):
raise ValueError("Event before readiness")
if kind == "session.updated":
@@ -1171,9 +1194,9 @@ class VoiceRuntime:
turn.input_deadline = self.clock() + self.settings.input_commit_timeout_seconds
if turn.commit_ack:
self.acknowledge_input(turn)
elif kind == "input_audio_buffer.committed":
elif kind in ("input_audio_buffer.committed", "provider.input_consumed"):
self.acknowledge_input(self.inputs[event["item_id"]])
elif kind in ("conversation.item.added", "conversation.item.created"):
elif kind in ("conversation.item.added", "conversation.item.created", "provider.input_consumed_text"):
item = event["item"]
turn = self.inputs.get(item["id"])
if turn and turn.diagnostic is not None:
@@ -1224,8 +1247,10 @@ class VoiceRuntime:
or len(content) > 1 or
(content and content[0]["type"] != "audio")):
raise ValueError("Unsupported output layout")
elif kind == "response.done":
elif kind in ("response.done", "provider.tools_requested"):
wire = event["response"]
if wire["status"] == "waiting_tools" and kind != "provider.tools_requested":
raise ValueError("Invalid native tool phase")
response = self.responses[wire["id"]]
if response.terminal and response.status != wire["status"]:
raise ValueError("Conflicting terminal")
@@ -1262,7 +1287,7 @@ class VoiceRuntime:
raise ValueError("Terminal call-set mismatch")
response.terminal, response.status = True, wire["status"]
self.wake.set()
if wire["status"] not in ("completed", "cancelled"):
if wire["status"] not in ("completed", "cancelled", "waiting_tools"):
self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn)
elif wire["status"] == "cancelled" and not response.interrupted:
raise ValueError("Unexpected cancellation")
@@ -1287,7 +1312,7 @@ class VoiceRuntime:
if estimate < 0 or estimate % 2:
raise ValueError("PCM alignment")
backlog = sum(len(a.data) + a.reserved + a.credit for a in self.audio.values())
if audio.state != "finalizing" and backlog + estimate > self.settings.max_output_backlog_bytes:
if audio.state != "finalizing" and backlog + estimate + getattr(self.adapter, "_audio_bytes", 0) > self.settings.max_output_backlog_bytes:
self.fail("LIVE_BUFFER_OVERFLOW", turn=response.turn)
return
decoded = base64.b64decode(encoded, validate=True)
@@ -1349,7 +1374,8 @@ class VoiceRuntime:
response.transcript_parts[key] = fingerprint
elif key in response.transcript_parts:
raise ValueError("Transcript delta after completion")
if not response.interrupted and not response.turn.superseded:
if (not response.interrupted and not response.turn.superseded
and (response.turn is self.current or response.status == "completed")):
response.visible = True
entry = self.control(dict(type="transcript", turn_ref=response.turn.ref, role="assistant",
text=text, status="completed" if completed else "partial"),
@@ -1417,7 +1443,7 @@ class VoiceRuntime:
name=name, raw=raw, item=item_id, ref=str(uuid4()))
self.calls[call_id] = (response, call)
response.calls[call_id] = call
if response.interrupted or response.turn.superseded:
if response.interrupted or response.turn.superseded or response.turn is not self.current:
return
ctx = ToolContext(response.turn.execution, self.clock() + self.tool_seconds,
response.turn.cancelled)
@@ -1434,16 +1460,31 @@ class VoiceRuntime:
task.add_done_callback(self.tasks.discard)
async def _search(self, response, call, ctx, args):
async def invoke():
try:
tool = create_search_tool(self.service, ctx, self.runner)
return await tool.ainvoke(args)
except asyncio.CancelledError:
raise
except Exception:
return self.runner.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed")
try:
tool = create_search_tool(self.service, ctx, self.runner)
result = await tool.ainvoke(args)
if self.tool_store:
external_id = next(cid for cid, c in response.calls.items() if c is call)
result = await asyncio.wait_for(self.tool_store.execute(external_id, call, ctx, args, invoke),
self.tool_seconds + 2 * self.settings.authority_timeout_seconds)
else:
result = await invoke()
except asyncio.CancelledError:
return
except Exception:
result = self.runner.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed")
except Exception as exc:
from app.modules.voice.durable_tools import failure_code
async with self.lock:
self.fail(failure_code(exc), turn=response.turn)
return
async with self.lock:
if (self.usable and not response.interrupted and not response.turn.superseded
and not ctx.cancelled.is_set()):
and response.turn is self.current and not ctx.cancelled.is_set()):
call["result"] = result
await self.release()