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
+81
View File
@@ -0,0 +1,81 @@
"""A01-A03: opaque sessions, bounded login admission, and synchronizer CSRF."""
from collections import deque
import time
from threading import Lock, BoundedSemaphore
from typing import Annotated
from fastapi import APIRouter, Depends, Request, Response
from pydantic import BaseModel, ConfigDict, Field
from app.api.v1.dependencies import get_auth_service, get_current_user, get_voice_settings, require_origin, error
from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, generate_csrf_token, verify_csrf_token
from app.modules.voice.configuration import VoiceSettings
router = APIRouter(prefix='/auth', tags=['Authentication'])
identity_router = APIRouter(tags=['Authentication'])
_ATTEMPTS = deque(maxlen=120)
_LOCK = Lock()
_LOGINS = BoundedSemaphore(2)
class LoginRequest(BaseModel):
model_config = ConfigDict(extra='forbid', strict=True)
username: str = Field(min_length=1, max_length=120)
password: str = Field(min_length=1, max_length=1024)
class UserDTO(BaseModel):
id: str
username: str
role: str
organization_id: str
class AuthResponse(BaseModel):
user: UserDTO
csrf_token: str
expires_at: str
@router.post('/login', response_model=AuthResponse)
def login(req: LoginRequest, request: Request, response: Response,
auth_service: Annotated[AuthService, Depends(get_auth_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
require_origin(request, config)
stamp = time.monotonic()
with _LOCK:
while _ATTEMPTS and stamp - _ATTEMPTS[0] >= 60:
_ATTEMPTS.popleft()
if len(_ATTEMPTS) >= config.login_attempts_per_minute:
raise error('SERVICE_BUSY')
_ATTEMPTS.append(stamp)
if not _LOGINS.acquire(blocking=False):
raise error('SERVICE_BUSY')
try:
user, token, csrf, expiry = auth_service.login(req.username, req.password)
except ValueError as exc:
raise error(str(exc)) from None
finally:
_LOGINS.release()
response.set_cookie(COOKIE_NAME, token, httponly=True, secure=config.cookie_secure,
samesite='lax', expires=expiry, path='/')
return AuthResponse(user=UserDTO(**user), csrf_token=csrf, expires_at=expiry.isoformat())
@router.post('/logout', status_code=204)
def logout(request: Request, response: Response,
auth_service: Annotated[AuthService, Depends(get_auth_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
require_origin(request, config)
token = request.cookies.get(COOKIE_NAME)
try:
auth_service.get_current_user(token)
except ValueError:
pass
else:
if not verify_csrf_token(token, request.headers.get('x-csrf-token')):
raise error('CSRF_TOKEN_INVALID')
auth_service.logout(token)
response.delete_cookie(COOKIE_NAME, path='/', secure=config.cookie_secure, httponly=True, samesite='lax')
response.status_code = 204
return response
@identity_router.get('/me', response_model=AuthResponse)
@router.get('/me', response_model=AuthResponse, include_in_schema=False)
def get_me(request: Request, user: Annotated[UserContext, Depends(get_current_user)]):
return AuthResponse(user=UserDTO(id=str(user.id), organization_id=str(user.organization_id),
username=user.username, role=user.role), csrf_token=generate_csrf_token(request.cookies.get(COOKIE_NAME)),
expires_at=user.expires_at.isoformat())
+71
View File
@@ -0,0 +1,71 @@
"""Conversation management endpoints (C01)."""
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Response, status
from pydantic import BaseModel, ConfigDict, Field
from app.api.v1.dependencies import (
get_current_user,
get_lifecycle_service,
require_csrf,
)
from app.modules.auth.service import UserContext
from app.modules.voice.lifecycle import LiveLifecycleService
router = APIRouter(prefix="/conversations", tags=["Conversations"])
class CreateConversationRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
client_request_id: UUID
mode: str = Field(default="voice", description="Must be 'voice' in MVP")
title: str | None = Field(default=None, max_length=120)
class ConversationResponse(BaseModel):
id: str
mode: str
title: str | None = None
status: str
access_epoch: int
created_at: str
@router.post(
"",
response_model=ConversationResponse,
status_code=status.HTTP_201_CREATED,
summary="C01: Create Conversation",
description="Creates an owned voice conversation container with idempotency protection.",
)
def create_conversation(
req: CreateConversationRequest,
response: Response,
user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
_csrf: Annotated[None, Depends(require_csrf)] = None,
) -> ConversationResponse:
try:
result = lifecycle.create_conversation(
user=user,
client_request_id=req.client_request_id,
mode=req.mode,
title=req.title,
)
except ValueError as exc:
from app.api.v1.dependencies import error
raise error(str(exc)) from None
if result.get("replayed"):
response.headers["Idempotency-Replayed"] = "true"
return ConversationResponse(
id=result["id"],
mode=result["mode"],
title=result["title"],
status=result["status"],
access_epoch=result["access_epoch"],
created_at=result["created_at"],
)
+104
View File
@@ -0,0 +1,104 @@
"""Cookie-only identity and shared backend services, lazily constructed."""
from datetime import timedelta
import json
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Request
from sqlalchemy.engine import Engine
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, check_origin, verify_csrf_token
from app.modules.voice.lifecycle import LiveLifecycleService
from app.modules.voice.configuration import VoiceSettings
from app.modules.knowledge.service import SearchService
from app.modules.knowledge.langchain_tool import SearchToolRunner
from app.modules.knowledge.calibration import load_cutoff
_ENGINE = _AUTH_SERVICE = _LIFECYCLE_SERVICE = _TOOL_RUNNER = _SEARCH_SERVICE = None
def get_voice_settings():
return VoiceSettings()
def error(code):
code = {'SESSION_NOT_FOUND':'NOT_FOUND','CONVERSATION_NOT_FOUND':'NOT_FOUND',
'SESSION_REVOKED':'AUTH_REQUIRED','SESSION_EXPIRED':'AUTH_REQUIRED','ACCOUNT_DISABLED':'AUTH_REQUIRED',
'CSRF_TOKEN_INVALID':'CSRF_INVALID','FORBIDDEN_ORIGIN':'FORBIDDEN','SERVICE_BUSY':'RATE_LIMITED',
'SERVICE_UNAVAILABLE':'DEPENDENCY_UNAVAILABLE'}.get(code,code)
codes = {
'AUTH_REQUIRED': 401, 'INVALID_CREDENTIALS': 401, 'ACCOUNT_DISABLED': 401,
'SESSION_REVOKED': 401, 'SESSION_EXPIRED': 401, 'CSRF_TOKEN_INVALID': 403,
'FORBIDDEN_ORIGIN': 403, 'CONVERSATION_NOT_FOUND': 404, 'SESSION_NOT_FOUND': 404,
'CALIBRATION_REQUIRED': 503, 'LIVE_PROVIDER_UNAVAILABLE': 503, 'SERVICE_BUSY': 429,
'MODE_MISMATCH': 409, 'CONVERSATION_CLOSED': 409, 'CONVERSATION_STALE': 409,
'LIVE_SESSION_BUSY': 409, 'LIVE_SESSION_UNUSABLE': 409, 'IDEMPOTENCY_CONFLICT': 409,
'CONTEXT_REVOKED': 409, 'LIVE_SESSION_EXPIRED':409, 'NOT_FOUND':404,'CSRF_INVALID':403,'FORBIDDEN':403,'RATE_LIMITED':429,'DEPENDENCY_UNAVAILABLE':503,
}
if code not in codes:
code = 'DEPENDENCY_UNAVAILABLE'
return HTTPException(codes.get(code, 503), detail={'code': code, 'message': 'Request could not be completed.'})
def get_engine():
global _ENGINE
if _ENGINE is None:
_ENGINE = create_database(IngestionSettings().database_url.get_secret_value())
return _ENGINE
def get_auth_service(engine: Annotated[Engine, Depends(get_engine)]):
global _AUTH_SERVICE
if _AUTH_SERVICE is None or _AUTH_SERVICE.engine is not engine:
_AUTH_SERVICE = AuthService(engine, session_lifetime=timedelta(seconds=VoiceSettings().auth_session_seconds))
return _AUTH_SERVICE
def get_lifecycle_service(engine: Annotated[Engine, Depends(get_engine)]):
global _LIFECYCLE_SERVICE
if _LIFECYCLE_SERVICE is None or _LIFECYCLE_SERVICE.engine is not engine:
_LIFECYCLE_SERVICE = LiveLifecycleService(engine, session_ttl=timedelta(seconds=VoiceSettings().live_session_seconds))
return _LIFECYCLE_SERVICE
def get_tool_runner():
global _TOOL_RUNNER
if _TOOL_RUNNER is None:
_TOOL_RUNNER = SearchToolRunner()
return _TOOL_RUNNER
def get_search_service(engine: Annotated[Engine, Depends(get_engine)]):
global _SEARCH_SERVICE
if _SEARCH_SERVICE is None or _SEARCH_SERVICE.engine is not engine:
settings = IngestionSettings()
path = VoiceSettings().search_calibration_report
cutoff = None
if path is not None:
try:
cutoff = load_cutoff(json.loads(path.read_text(encoding='utf-8')))
except (ValueError, OSError, KeyError, TypeError, AttributeError):
raise error('CALIBRATION_REQUIRED') from None
from app.worker import factories
_, provider_factory = factories(settings)
provider, counter = provider_factory(settings.processing_profile())
_SEARCH_SERVICE = SearchService(engine, settings, provider, counter, cutoff=cutoff)
return _SEARCH_SERVICE
def get_current_user(request: Request, auth_service: Annotated[AuthService, Depends(get_auth_service)]) -> UserContext:
try:
return auth_service.get_current_user(request.cookies.get(COOKIE_NAME))
except ValueError:
raise error('AUTH_REQUIRED') from None
def require_origin(request: Request, config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
if not check_origin(request.headers.get('origin'), request.headers.get('host'), config.trusted_origins, config.trusted_hosts, required=True):
raise error('FORBIDDEN_ORIGIN')
def require_csrf(request: Request, config: Annotated[VoiceSettings, Depends(get_voice_settings)],
x_csrf_token: Annotated[str | None, Header()] = None):
require_origin(request, config)
if not verify_csrf_token(request.cookies.get(COOKIE_NAME), x_csrf_token):
raise error('CSRF_TOKEN_INVALID')
+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)
+24
View File
@@ -0,0 +1,24 @@
"""Bounded blocking work; timed-out workers retain admission until actual completion."""
import asyncio
from concurrent.futures import ThreadPoolExecutor
from threading import BoundedSemaphore
_POOL = None
_SLOTS = BoundedSemaphore(8)
async def blocking(function, *args, **kwargs):
global _POOL
if _POOL is None:
_POOL = ThreadPoolExecutor(max_workers=8, thread_name_prefix="live-db")
if not _SLOTS.acquire(blocking=False):
raise ValueError('SERVICE_BUSY')
loop = asyncio.get_running_loop()
future = _POOL.submit(function, *args, **kwargs)
future.add_done_callback(lambda _: _SLOTS.release())
return await asyncio.wait_for(asyncio.shield(asyncio.wrap_future(future, loop=loop)), 6)
def shutdown_pool():
global _POOL
if _POOL is not None:
_POOL.shutdown(wait=False, cancel_futures=True)
_POOL = None
+7 -3
View File
@@ -9,6 +9,8 @@ from sqlalchemy.orm import sessionmaker
from app.modules.documents.types import EmbeddingProfile
LIVE_REVISION = "0005_live_owner_chain"
PREVIOUS_LIVE_REVISION = "0004_live_lifecycle"
SCHEMA_REVISION = "0003_extraction_review"
WORKER_REVISION = "0002_worker_artifact"
FOUNDATION_REVISION = "0001_ingestion_foundation"
@@ -63,17 +65,19 @@ def check_compatibility(connection: Connection, profile: EmbeddingProfile, *, re
schema = connection.execute(text("SELECT current_schema()")).scalar_one()
assert_foundation_scope(connection, schema)
revision = connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one()
allowed = (SCHEMA_REVISION,) if require_worker else (FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION)
allowed = (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION) if require_worker else (
FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION
)
if revision not in allowed:
raise CompatibilityError("Unexpected ingestion schema revision")
if revision in (WORKER_REVISION, SCHEMA_REVISION):
if revision in (WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION):
artifact_type = connection.execute(text("""
SELECT format_type(atttypid,atttypmod) FROM pg_attribute
WHERE attrelid=to_regclass('documents') AND attname='extraction_state' AND NOT attisdropped
""")).scalar_one_or_none()
if artifact_type != "jsonb":
raise CompatibilityError("Missing worker artifact attachment column")
if revision == SCHEMA_REVISION:
if revision in (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION):
definitions = connection.execute(text("""
SELECT pg_get_constraintdef(oid) FROM pg_constraint
WHERE conrelid=to_regclass(\'audit_events\')
+450
View File
@@ -0,0 +1,450 @@
"""Gemini native wire translation; synthetic provider acknowledgements are forbidden.
Native voiceActivity must provide usable input boundaries. First model/tool output
proves input consumption, independently of an OpenAI input-commit acknowledgement.
No verified sample-level context truncation exists: interruption closes safely.
"""
import asyncio
import base64
from collections import deque
import json
import math
import struct
from urllib.parse import quote
from uuid import uuid4
from app.modules.knowledge.service import SearchInput
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.serialization import bounded_json
from app.infrastructure.realtime import POLICY, strict_json, ProviderProtocolError
class GeminiContextError(ProviderProtocolError):
context_sync = True
class GeminiOverflow(ProviderProtocolError):
overflow = True
class PCM24To16:
"""Streaming rational 2/3 FIR resampler with bounded history and antialias filtering."""
def __init__(self):
# Filter the 48kHz zero-stuffed stream below the 16kHz output Nyquist.
count, cutoff = 31, 1/6
weights = []
for k in range(count):
x = k - (count-1)/2
sinc = 2*cutoff if x == 0 else math.sin(2*math.pi*cutoff*x)/(math.pi*x)
weights.append(sinc * (.54-.46*math.cos(2*math.pi*k/(count-1))))
self.weights = [2*w/sum(weights) for w in weights]
self.history = deque([0.0]*count, maxlen=count)
self.position = 0
def convert(self, pcm):
if not isinstance(pcm, bytes) or len(pcm) % 2:
raise ProviderProtocolError('Invalid PCM input')
out = []
for sample in struct.unpack('<' + 'h'*(len(pcm)//2), pcm):
for value in (sample, 0):
self.history.appendleft(value)
if self.position % 3 == 0:
filtered = round(sum(v*w for v,w in zip(self.history, self.weights)))
out.append(max(-32768,min(32767,filtered)))
self.position += 1
return struct.pack('<'+'h'*len(out), *out)
def _schema(value):
if isinstance(value, dict):
return {k:_schema(v) for k,v in value.items() if k not in ('title','$defs','additionalProperties')}
if isinstance(value, list):
return [_schema(v) for v in value]
return value
class GeminiLiveAdapter:
native_input_consumption = True
def __init__(self, transport, *, model='gemini-2.0-flash-exp', voice='Aoede', settings=None, no_active_classifier=None):
self.transport, self.model, self.voice = transport, model, voice
self.settings = settings or RuntimeSettings()
self.no_active_classifier = None
self._inbound_events = asyncio.Queue()
self._queued_bytes = 0
self._control_count = 0
self._audio_bytes = self._audio_slabs = self._leased_audio = self._audio_metadata = 0
self.backlog = lambda: 0
self._pump_task = self._close_task = None
self._failure = None
self._confirmed = False
self._setup_sent = False
self._intent = None
self._gate = asyncio.Event()
self._inputs = []
self._input = None
self._input_end = None
self._input_consumed = False
self._generation_complete = False
self._response = None
self._calls = {}
self._completed_calls = {}
self._diagnostic = None
self._outputs = {}
self._seen_intents = set()
self._input_text = self._output_text = ''
self._sent_samples = 0
self._resampler = PCM24To16()
def setup(self):
return dict(type='session.update', session={'provider':'gemini'})
def acknowledged(self, session):
return self._confirmed and session == {'provider':'gemini', 'setup_complete':True}
def serialize(self, event):
return bounded_json(event, self.settings.max_provider_message_bytes, ensure_ascii=False)
async def send_serialized(self, wire):
await self.send(strict_json(wire))
def _put(self, event):
# Controls and decoded PCM have independent reservations. Adjacent tiny
# deltas pack into PCM slabs while the single FIFO retains native order.
if event['type'] == 'response.output_audio.delta':
encoded = event['delta']
if not isinstance(encoded,str) or len(encoded) > self.settings.max_provider_message_bytes:
raise ProviderProtocolError('Gemini audio scratch bound')
estimate = len(encoded)//4*3 - (len(encoded)-len(encoded.rstrip('=')))
if estimate < 0 or estimate > 196608 or estimate % 2:
raise ProviderProtocolError('Gemini PCM alignment')
if self._audio_bytes + self._leased_audio + self.backlog() + estimate > self.settings.max_output_backlog_bytes:
raise GeminiOverflow('Gemini generated backlog overflow')
pcm = base64.b64decode(encoded, validate=True)
if len(pcm) != estimate or len(pcm) % 2:
raise ProviderProtocolError('Gemini PCM alignment')
if self._audio_bytes + self._leased_audio + self.backlog() + len(pcm) > self.settings.max_output_backlog_bytes:
raise GeminiOverflow('Gemini generated backlog overflow')
key = {k:v for k,v in event.items() if k != 'delta'}
queue = self._inbound_events._queue
tail = queue[-1] if queue else None
capacity = 0
if tail and tail[2] and tail[0] == key:
capacity = 9600 - len(tail[1])
slabs = (max(0, len(pcm)-capacity) + 9599)//9600
metadata = len(self.serialize(key).encode('utf-8'))
if self._audio_slabs + slabs > 512 or self._audio_metadata + slabs * metadata > 65536:
raise GeminiOverflow('Gemini audio slab overflow')
self._audio_bytes += len(pcm)
self._audio_metadata += slabs * metadata
if capacity:
take = min(capacity, len(pcm)); tail[1].extend(pcm[:take]); pcm = pcm[take:]
for offset in range(0, len(pcm), 9600):
self._inbound_events.put_nowait((key, bytearray(pcm[offset:offset+9600]), True))
self._audio_slabs += 1
return
size = len(self.serialize(event).encode('utf-8'))
if self._control_count >= self.settings.max_control_messages or self._queued_bytes + size > self.settings.max_control_bytes:
raise GeminiOverflow('Gemini control overflow')
self._queued_bytes += size
self._control_count += 1
self._inbound_events.put_nowait((event,size,False))
def consumed(self):
self._leased_audio = 0
async def _wire(self, event):
await self.transport.send(self.serialize(event))
async def send(self, event):
kind = event['type']
if kind in ('response.cancel','conversation.item.truncate'):
self._failure = GeminiContextError('Gemini context cannot be safely truncated')
await self.close()
raise self._failure
if kind == 'session.update':
if self._setup_sent:
raise ProviderProtocolError('Repeated setup')
self._setup_sent = True
await self._wire({'setup': {
'model': self.model if self.model.startswith('models/') else 'models/'+self.model,
'generationConfig': {'responseModalities':['AUDIO'], 'speechConfig': {'voiceConfig': {'prebuiltVoiceConfig': {'voiceName':self.voice}}}},
'systemInstruction': {'parts':[{'text':POLICY}]},
'realtimeInputConfig': {'activityHandling':'NO_INTERRUPTION'},
'inputAudioTranscription': {}, 'outputAudioTranscription': {},
'tools':[{'functionDeclarations':[{'name':'search_knowledge',
'description':'Retrieve authorized evidence.', 'parameters':_schema(SearchInput.model_json_schema())}]}]}})
self._pump_task = asyncio.create_task(self._read_provider_loop())
return
if not self._confirmed:
raise ProviderProtocolError('Input before Gemini readiness')
if kind == 'input_audio_buffer.append':
pcm = base64.b64decode(event['audio'], validate=True)
if len(pcm) > self.settings.max_binary_message_bytes or len(pcm) % 2:
raise ProviderProtocolError('Invalid PCM frame')
converted = self._resampler.convert(pcm)
self._sent_samples += len(pcm)//2
if converted:
await self._wire({'realtimeInput': {'audio': {'mimeType':'audio/pcm;rate=16000', 'data':base64.b64encode(converted).decode('ascii')}}})
elif kind == 'conversation.item.create':
item = event['item']
if item['type'] == 'message' and item.get('role') == 'user':
if self._input or self._diagnostic:
raise ProviderProtocolError('Diagnostic input must start fresh')
content = item.get('content')
if not isinstance(content, list) or len(content) != 1 or content[0].get('type') != 'input_text':
raise ProviderProtocolError('Invalid diagnostic input')
self._diagnostic = item
await self._wire({'clientContent': {'turns': [{'role': 'user', 'parts': [{'text': content[0]['text']}]}], 'turnComplete': True}})
return
if item['type'] != 'function_call_output':
raise ProviderProtocolError('Unsupported Gemini item')
cid = item['call_id']
if cid not in self._calls:
raise ProviderProtocolError('Unknown Gemini tool identity')
output = strict_json(item['output'])
if cid in self._outputs and self._outputs[cid] != output:
raise ProviderProtocolError('Conflicting Gemini result')
self._outputs[cid] = output
elif kind == 'response.create':
intent = event['response']['metadata']['voice_intent']
if intent in self._seen_intents:
return
if len(self._seen_intents) >= self.settings.max_intents:
raise ProviderProtocolError('Intent bound')
self._seen_intents.add(intent)
self._intent = intent
if self._calls:
if set(self._outputs) != set(self._calls):
raise ProviderProtocolError('Incomplete Gemini tool results')
outputs = [{'id':cid,'name':self._calls[cid]['name'],'response':self._outputs[cid]} for cid in self._calls]
for cid, function in self._calls.items():
self._completed_calls[cid] = function
self._calls, self._outputs, self._response = {}, {}, None
await self._wire({'toolResponse': {'functionResponses': outputs}})
self._gate.set()
else:
raise ProviderProtocolError('Unsupported Gemini command')
async def _read_provider_loop(self):
try:
while True:
raw = await self.transport.recv()
if not isinstance(raw, (str,bytes)) or len(raw.encode('utf-8') if isinstance(raw,str) else raw) > self.settings.max_provider_message_bytes:
raise ProviderProtocolError('Gemini frame limit')
msg = strict_json(raw.decode('utf-8') if isinstance(raw,bytes) else raw)
await self._translate_google_message(msg)
except asyncio.CancelledError:
raise
except Exception as exc:
self._failure = exc if isinstance(exc, ProviderProtocolError) else ConnectionError('Gemini transport lost')
# Failure supersedes queued late content and wakes the runtime immediately.
while not self._inbound_events.empty():
self._inbound_events.get_nowait()
self._queued_bytes = self._control_count = self._audio_bytes = self._audio_slabs = self._leased_audio = self._audio_metadata = 0
self._inbound_events.put_nowait((None,0,False))
async def _begin(self):
if self._response:
return
if self._diagnostic is None and (self._input is None or self._input_end is None):
raise ProviderProtocolError('Gemini input boundaries unavailable')
if not self._input_consumed:
self._input_consumed = True
if self._diagnostic:
self._put({'type':'provider.input_consumed_text','item':self._diagnostic})
else:
self._put({'type':'provider.input_consumed','item_id':self._input})
await asyncio.wait_for(self._gate.wait(), self.settings.response_ack_timeout_seconds)
self._gate.clear()
self._response = 'gemini-response-'+uuid4().hex
self._item = 'gemini-item-'+uuid4().hex
self._output_text = ''
self._message_announced = False
self._put({'type':'response.created','response':{'id':self._response,'metadata':{'voice_intent':self._intent}}})
def _audio_event(self, kind, **payload):
self._put(dict(type=kind, response_id=self._response, item_id=self._item, output_index=0, content_index=0, **payload))
def _announce(self):
if not self._message_announced:
self._message_announced = True
self._put(dict(type='response.output_item.added',response_id=self._response,output_index=0,
item=dict(id=self._item,type='message',role='assistant',content=[{'type':'audio','transcript':''}])))
async def _translate_google_message(self, msg):
if 'setupComplete' in msg:
if not self._setup_sent or not isinstance(msg['setupComplete'], dict):
raise ProviderProtocolError('Invalid Gemini setup confirmation')
if not self._confirmed:
self._confirmed = True
self._put({'type':'session.updated','session':{'provider':'gemini','setup_complete':True}})
return
if not self._confirmed:
raise ProviderProtocolError('Gemini output before setup')
if 'goAway' in msg or 'toolCallCancellation' in msg:
raise GeminiContextError('Gemini session no longer eligible')
activity = msg.get('voiceActivity')
if activity:
offset = activity.get('audioOffset')
if not isinstance(offset,str) or not offset.endswith('s'):
raise ProviderProtocolError('Gemini activity coordinates unavailable')
milliseconds = int(float(offset[:-1])*1000)
if not 0 <= milliseconds <= self._sent_samples//24:
raise ProviderProtocolError('Gemini activity coordinates invalid')
if activity.get('type') == 'ACTIVITY_START':
duplicate = any(entry['start'] == milliseconds for entry in self._inputs)
if not duplicate:
if self._input and (self._input_end is None or not self._generation_complete):
raise GeminiContextError('Gemini pending generation cannot be rebound')
if self._response or self._calls:
raise GeminiContextError('Gemini interruption requires fresh context')
if self._inputs and milliseconds < self._inputs[-1]['end']:
raise GeminiContextError('Conflicting Gemini activity start')
self._input, self._input_end = 'gemini-input-'+uuid4().hex, None
self._input_consumed = self._generation_complete = False
if len(self._inputs) >= self.settings.max_input_turns:
raise GeminiOverflow('Gemini input mapping bound')
self._inputs.append({'id':self._input, 'start':milliseconds, 'end':None})
self._input_text = ''
self._put(dict(type='input_audio_buffer.speech_started',item_id=self._input,audio_start_ms=milliseconds))
elif activity.get('type') == 'ACTIVITY_END':
duplicate = any(entry['end'] == milliseconds for entry in self._inputs)
if not duplicate:
if self._input is None or self._input_end is not None or milliseconds <= self._inputs[-1]['start']:
raise GeminiContextError('Conflicting Gemini activity end')
self._input_end = milliseconds
self._inputs[-1]['end'] = milliseconds
self._put(dict(type='input_audio_buffer.speech_stopped',item_id=self._input,audio_end_ms=milliseconds))
else:
raise ProviderProtocolError('Unknown Gemini activity')
if 'toolCall' in msg:
functions = msg['toolCall']['functionCalls']
if not isinstance(functions,list) or not 1 <= len(functions) <= 16:
raise ProviderProtocolError('Gemini tool bound')
if all(fn.get('id') in self._completed_calls for fn in functions):
if any(self._completed_calls[fn['id']] != fn for fn in functions):
raise ProviderProtocolError('Conflicting completed Gemini tool replay')
return
if len(self._completed_calls) + len(self._calls) + len(functions) > self.settings.max_tool_calls:
raise ProviderProtocolError('Gemini call bound')
if self._calls:
if functions != list(self._calls.values()):
raise ProviderProtocolError('Conflicting Gemini tool replay')
return
await self._begin()
if self._message_announced:
raise GeminiContextError('Gemini mixed audio/tool phase unsupported')
output = []
for position, fn in enumerate(functions):
cid = fn.get('id')
if not isinstance(cid,str) or not cid or len(cid)>256 or cid in self._calls:
raise ProviderProtocolError('Gemini tool identity required')
item = dict(id='gemini-call-item-'+uuid4().hex,type='function_call',call_id=cid,
name=fn['name'],arguments=bounded_json(fn['args'],self.settings.max_provider_message_bytes,ensure_ascii=False))
self._calls[cid] = fn
output.append(item)
self._put(dict(type='response.output_item.added',response_id=self._response,output_index=position,item=item))
self._put(dict(type='response.function_call_arguments.done',response_id=self._response,item_id=item['id'],
call_id=cid,name=fn['name'],arguments=item['arguments']))
# Native tool request is a suspended generation phase, not a terminal acknowledgement.
self._put(dict(type='provider.tools_requested',response=dict(id=self._response,status='waiting_tools',output=output)))
content = msg.get('serverContent')
if content:
if content.get('interrupted'):
raise GeminiContextError('Gemini unheard audio cannot be truncated')
transcription = content.get('inputTranscription')
if transcription:
if not self._input or not isinstance(transcription.get('text'),str):
raise ProviderProtocolError('Uncorrelated Gemini input transcription')
offset = transcription.get('startOffset')
if offset is None:
if len(self._inputs) != 1:
raise ProviderProtocolError('Gemini delayed transcription is ambiguous')
input_item = self._inputs[0]['id']
else:
if not isinstance(offset, str) or not offset.endswith('s'):
raise ProviderProtocolError('Invalid Gemini transcript coordinates')
position = float(offset[:-1])*1000
matches = [entry for entry in self._inputs if entry['start'] <= position
and (entry['end'] is None or position <= entry['end'])]
if len(matches) != 1:
raise ProviderProtocolError('Uncorrelated Gemini transcript coordinates')
input_item = matches[0]['id']
self._input_text += transcription['text']
if len(self._input_text.encode('utf-8')) > self.settings.max_server_event_bytes//2:
raise ProviderProtocolError('Gemini transcript bound')
self._put(dict(type='conversation.item.input_audio_transcription.delta',item_id=input_item,
content_index=0,delta=transcription['text']))
parts = content.get('modelTurn', {}).get('parts', [])
out_text = content.get('outputTranscription', {}).get('text')
if parts or out_text is not None:
if self._calls:
raise GeminiContextError('Gemini output before authorized continuation')
await self._begin()
self._announce()
for part in parts:
if 'inlineData' in part:
blob = part['inlineData']
if blob.get('mimeType') != 'audio/pcm;rate=24000':
raise ProviderProtocolError('Unexpected Gemini output format')
self._audio_event('response.output_audio.delta',delta=blob['data'])
elif part.get('text') and not part.get('thought'):
# modelTurn text is not an audio transcript; outputTranscription is.
raise ProviderProtocolError('Unexpected Gemini text modality')
if out_text is not None:
if not isinstance(out_text,str):
raise ProviderProtocolError('Invalid Gemini transcript')
self._output_text += out_text
if len(self._output_text.encode('utf-8')) > self.settings.max_server_event_bytes//2:
raise ProviderProtocolError('Gemini transcript bound')
self._audio_event('response.output_audio_transcript.delta',delta=out_text)
if content.get('turnComplete') and self._response and not self._calls:
self._announce()
self._audio_event('response.output_audio_transcript.done',transcript=self._output_text)
self._audio_event('response.output_audio.done')
item=dict(id=self._item,type='message',role='assistant',content=[{'type':'audio','transcript':self._output_text}])
self._put(dict(type='response.output_item.done',response_id=self._response,output_index=0,item=item))
self._put(dict(type='response.done',response=dict(id=self._response,status='completed',output=[item])))
self._response = None
self._generation_complete = True
async def receive(self):
if self._failure:
raise self._failure
item,size,audio = await self._inbound_events.get()
if audio:
self._audio_bytes -= len(size)
self._audio_slabs -= 1
self._audio_metadata -= len(self.serialize(item).encode('utf-8'))
self._leased_audio = len(size)
item = dict(item, delta=base64.b64encode(size).decode('ascii'))
else:
self._queued_bytes -= size
self._control_count -= 1
if self._failure:
raise self._failure
return item
def is_no_active(self, error):
return False
async def close(self):
if self._close_task is None:
async def cleanup():
if self._pump_task and self._pump_task is not asyncio.current_task():
self._pump_task.cancel()
await asyncio.gather(self._pump_task, return_exceptions=True)
try:
await asyncio.wait_for(self.transport.close(), self.settings.send_timeout_seconds)
finally:
while not self._inbound_events.empty():
self._inbound_events.get_nowait()
self._queued_bytes = self._control_count = 0
self._audio_bytes = self._audio_slabs = self._leased_audio = self._audio_metadata = 0
self._close_task = asyncio.create_task(cleanup())
await asyncio.shield(self._close_task)
async def connect_gemini(api_key, model='gemini-2.0-flash-exp', proxy=None, settings=None):
if not api_key:
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
settings = settings or RuntimeSettings()
from websockets.asyncio.client import connect
endpoint = 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent'
return await connect(endpoint+'?key='+quote(api_key,safe=''), proxy=proxy,compression=None,
max_size=settings.max_provider_message_bytes,max_queue=16,open_timeout=settings.connect_timeout_seconds,
close_timeout=settings.send_timeout_seconds,ping_interval=20,ping_timeout=20)
+110 -36
View File
@@ -1,43 +1,117 @@
"""Main FastAPI Application Entrypoint.
Initializes the FastAPI application, sets up CORS middleware, registers API routes,
and provides system health check endpoints.
"""
from fastapi import FastAPI
"""Modular API: startup reconciliation gates admission; no prototype imports."""
import asyncio
from contextlib import asynccontextmanager
from uuid import UUID, uuid4
from fastapi import FastAPI, Request, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.auth import router as auth_router, identity_router
from app.api.v1.conversations import router as conversations_router
from app.api.v1.live import router as voice_router
from app.api.v1 import dependencies
from app.infrastructure.blocking import blocking, shutdown_pool
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.registry import shutdown
from app.api.v1.chat import router as chat_router
from app.core.config import settings
@asynccontextmanager
async def lifespan(app):
app.state.ready = False
engine = None
startup_error = None
try:
engine = dependencies.get_engine()
lifecycle = dependencies.get_lifecycle_service(engine)
await blocking(lifecycle.reconcile_startup)
app.state.ready = True
yield
except BaseException as exc:
startup_error = exc
raise
finally:
app.state.ready = False
async def cleanup():
try:
await asyncio.wait_for(shutdown(), 6)
finally:
try:
runner = dependencies._TOOL_RUNNER
if runner is not None:
await asyncio.wait_for(asyncio.to_thread(runner.close), 6)
finally:
try:
if engine is not None:
engine.dispose()
finally:
dependencies._TOOL_RUNNER = None
dependencies._ENGINE = dependencies._AUTH_SERVICE = dependencies._LIFECYCLE_SERVICE = dependencies._SEARCH_SERVICE = None
shutdown_pool()
task = asyncio.create_task(cleanup())
try:
await asyncio.shield(task)
except asyncio.CancelledError:
# Cleanup retains ownership after cancellation, including startup.
try:
await asyncio.shield(task)
except Exception:
if startup_error is None:
raise
if startup_error is None:
raise
except Exception:
if startup_error is None:
raise
# Initialize FastAPI application instance
app = FastAPI(
title=settings.app_name,
version=settings.app_version,
description=settings.app_description,
docs_url="/docs",
redoc_url="/redoc",
)
app = FastAPI(title='Technical Documentation Assistant API', lifespan=lifespan)
app.state.ready = False
config = VoiceSettings()
app.add_middleware(CORSMiddleware, allow_origins=list(config.trusted_origins), allow_credentials=True,
allow_methods=['GET','POST'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID'])
# Configure Cross-Origin Resource Sharing (CORS) middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware('http')
async def transport(request, call_next):
try:
request_id = str(UUID(request.headers.get('x-request-id', '')))
except (ValueError, TypeError):
request_id = str(uuid4())
request.state.request_id = request_id
if request.headers.get('host') not in config.trusted_hosts:
result = envelope(request, 'FORBIDDEN', 403)
elif not app.state.ready and request.url.path not in ('/health/live','/health/ready'):
result = envelope(request, 'DEPENDENCY_UNAVAILABLE', 503)
else:
result = await call_next(request)
result.headers['X-Request-ID'] = request_id
return result
# Register API v1 routers
app.include_router(chat_router, prefix="/api/v1")
def envelope(request, code, status):
return JSONResponse(status_code=status, headers={'Retry-After':'60'} if status == 429 else {}, content={'error': {'code': code,
'message': 'Request could not be completed.', 'request_id': getattr(request.state, 'request_id', str(uuid4())),
'retryable': status in (429,503)}})
@app.exception_handler(StarletteHTTPException)
@app.exception_handler(HTTPException)
async def http_error(request, exc):
detail = exc.detail if isinstance(exc.detail, dict) else {}
return envelope(request, detail.get('code', 'NOT_FOUND' if exc.status_code == 404 else 'REQUEST_FAILED'), exc.status_code)
@app.get(
"/api/v1/health",
tags=["Health"],
summary="Health Check",
description="Check the operational health and readiness of the service.",
)
async def health_check() -> dict[str, str]:
"""Return the service health status."""
return {"status": "healthy"}
@app.exception_handler(RequestValidationError)
async def dto_error(request, exc):
return envelope(request, 'VALIDATION_ERROR', 422)
@app.exception_handler(Exception)
async def unexpected_error(request, exc):
return envelope(request, 'DEPENDENCY_UNAVAILABLE', 503)
for router in (auth_router, identity_router, conversations_router, voice_router):
app.include_router(router, prefix='/api/v1')
@app.get('/health/live')
def live():
return {'status': 'ok'}
@app.get('/health/ready')
def ready():
return JSONResponse(status_code=200 if app.state.ready else 503,
content={'status': 'ready', 'ingestion': 'available'} if app.state.ready else {'status': 'not_ready'})
+1
View File
@@ -0,0 +1 @@
"""Auth and session management module."""
+245
View File
@@ -0,0 +1,245 @@
"""Authentication, session lifecycle, CSRF tokens and access validation."""
from datetime import datetime, timezone, timedelta
import hashlib
import hmac
import os
import secrets
from uuid import UUID, uuid4
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError
from pydantic import BaseModel, Field
from sqlalchemy import text
COOKIE_NAME = "rag_session"
DEFAULT_SESSION_LIFETIME = timedelta(hours=8)
class UserContext(BaseModel):
id: UUID
organization_id: UUID
username: str
role: str
is_enabled: bool
auth_session_id: UUID
access_epoch: int
expires_at: datetime | None = None
def hash_token(raw_token: str) -> str:
"""Computes SHA-256 hex digest of raw session token."""
if not valid_token(raw_token):
raise ValueError("AUTH_REQUIRED")
return hashlib.sha256(raw_token.encode("ascii")).hexdigest()
def valid_token(value):
return isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value)
def generate_csrf_token(raw_token: str) -> str:
if not valid_token(raw_token):
raise ValueError('AUTH_REQUIRED')
return hmac.new(raw_token.encode('ascii'), b'rag-session-csrf-v1', hashlib.sha256).hexdigest()
def verify_csrf_token(raw_token: str, client_csrf: str) -> bool:
return (valid_token(raw_token) and valid_token(client_csrf)
and hmac.compare_digest(generate_csrf_token(raw_token), client_csrf))
def check_origin(origin_header, host_header, allowed_origins=None, allowed_hosts=None, *, required=False):
from app.modules.voice.configuration import VoiceSettings
config = VoiceSettings()
origins = allowed_origins if allowed_origins is not None else config.trusted_origins
hosts = allowed_hosts if allowed_hosts is not None else config.trusted_hosts
if not isinstance(host_header, str) or len(host_header) > 255 or host_header not in hosts:
return False
if origin_header is None:
return not required
return isinstance(origin_header, str) and len(origin_header) <= 512 and origin_header in origins
class AuthService:
def __init__(self, engine, session_lifetime: timedelta | None = None, session_ttl: timedelta | None = None):
self.engine = engine
self.lifetime = session_ttl or session_lifetime or DEFAULT_SESSION_LIFETIME
self._hasher = PasswordHasher()
self._dummy_hash = self._hasher.hash(secrets.token_hex(32))
def login(self, username: str, password: str) -> tuple[dict, str, str, datetime]:
"""Authenticates user and issues a new opaque cookie session.
Returns: (user_dict, raw_token, csrf_token, expires_at)
Raises: ValueError("INVALID_CREDENTIALS") or ValueError("ACCOUNT_DISABLED")
"""
if (not isinstance(username, str) or not isinstance(password, str)
or not 1 <= len(username) <= 120 or not 1 <= len(password) <= 1024
or '\x00' in username or '\x00' in password):
raise ValueError('INVALID_CREDENTIALS')
clean_user = username.strip().lower()
now = datetime.now(timezone.utc)
expires_at = now + self.lifetime
from app.modules.knowledge.service import transaction
with transaction(self.engine) as conn:
row = conn.execute(
text("""
SELECT u.id, u.organization_id, u.username, u.password_hash, u.role, u.is_enabled,
s.access_epoch
FROM users u
JOIN organization_settings s ON s.organization_id = u.organization_id
WHERE u.username = :username
"""),
{"username": clean_user}
).mappings().first()
if not row:
try:
self._hasher.verify(self._dummy_hash, password)
except VerificationError:
pass
raise ValueError("INVALID_CREDENTIALS")
conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR SHARE'), {'org': row['organization_id']})
row = conn.execute(text('''SELECT u.id,u.organization_id,u.username,u.password_hash,u.role,u.is_enabled,s.access_epoch
FROM users u JOIN organization_settings s ON s.organization_id=u.organization_id
WHERE u.id=:id FOR SHARE OF u'''), {'id':row['id']}).mappings().first()
if row is None:
raise ValueError('INVALID_CREDENTIALS')
try:
self._hasher.verify(row["password_hash"], password)
except (VerifyMismatchError, VerificationError):
raise ValueError("INVALID_CREDENTIALS")
if not row["is_enabled"]:
raise ValueError("ACCOUNT_DISABLED")
session_id = uuid4()
raw_token = secrets.token_hex(32)
token_h = hash_token(raw_token)
csrf_token = generate_csrf_token(raw_token)
conn.execute(
text("""
INSERT INTO auth_sessions (id, organization_id, user_id, token_hash, created_at, expires_at, last_seen_at)
VALUES (:id, :org, :user, :token_hash, :created_at, :expires_at, :last_seen_at)
"""),
{
"id": session_id,
"org": row["organization_id"],
"user": row["id"],
"token_hash": token_h,
"created_at": now,
"expires_at": expires_at,
"last_seen_at": now,
}
)
user_dict = {
"id": str(row["id"]),
"username": row["username"],
"role": row["role"],
"organization_id": str(row["organization_id"]),
}
return user_dict, raw_token, csrf_token, expires_at
def get_current_user(self, raw_token: str) -> UserContext:
"""Validates session token and returns active UserContext."""
if not raw_token:
raise ValueError("AUTH_REQUIRED")
token_h = hash_token(raw_token)
now = datetime.now(timezone.utc)
from app.modules.knowledge.service import transaction
with transaction(self.engine) as conn:
row = conn.execute(
text("""
SELECT a.id AS auth_session_id, a.expires_at, a.revoked_at,
u.id AS user_id, u.organization_id, u.username, u.role, u.is_enabled,
s.access_epoch
FROM auth_sessions a
JOIN users u ON u.id = a.user_id AND u.organization_id = a.organization_id
JOIN organization_settings s ON s.organization_id = a.organization_id
WHERE a.token_hash = :token_hash
"""),
{"token_hash": token_h}
).mappings().first()
if not row:
raise ValueError("AUTH_REQUIRED")
if row["revoked_at"] is not None:
raise ValueError("SESSION_REVOKED")
if row["expires_at"] <= now:
raise ValueError("SESSION_EXPIRED")
if not row["is_enabled"]:
raise ValueError("ACCOUNT_DISABLED")
sess_id = row.get("auth_session_id") or row.get("id")
# Update last_seen_at
conn.execute(
text("UPDATE auth_sessions SET last_seen_at = :now WHERE id = :id"),
{"now": now, "id": sess_id}
)
return UserContext(
id=row["user_id"],
organization_id=row["organization_id"],
username=row["username"],
role=row["role"],
is_enabled=row["is_enabled"],
auth_session_id=sess_id,
access_epoch=row["access_epoch"],
expires_at=row["expires_at"],
)
def logout(self, raw_token: str | None) -> None:
"""Revokes the current auth session and closes owned live sessions."""
if not valid_token(raw_token):
return
token_h = hash_token(raw_token)
now = datetime.now(timezone.utc)
from app.modules.knowledge.service import transaction
with transaction(self.engine) as conn:
initial = conn.execute(text("SELECT organization_id FROM auth_sessions WHERE token_hash=:hash"), {"hash": token_h}).mappings().first()
if initial is None:
return
conn.execute(text("SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE"), {"org": initial["organization_id"]})
session = conn.execute(
text("SELECT id, user_id, organization_id FROM auth_sessions WHERE token_hash = :hash AND revoked_at IS NULL"),
{"hash": token_h}
).mappings().first()
if not session:
return
conn.execute(
text("UPDATE auth_sessions SET revoked_at = :now WHERE id = :id"),
{"now": now, "id": session["id"]}
)
# Close linked active live sessions
conn.execute(
text("""
UPDATE live_sessions
SET status = 'closed', closed_at = :now, close_reason = 'user_logout', updated_at = :now
WHERE auth_session_id = :session_id AND status IN ('creating', 'connecting', 'connected')
"""),
{"now": now, "session_id": session["id"]}
)
conn.execute(text("""
UPDATE tool_calls SET status='failed', completed_at=:now, error_code='SESSION_REVOKED'
WHERE status='running' AND live_session_id IN
(SELECT id FROM live_sessions WHERE auth_session_id=:auth)
"""), {'now': now, 'auth': session['id']})
from app.modules.voice.registry import notify
notify(auth_session_id=session['id'])
+13 -1
View File
@@ -158,6 +158,15 @@ def selection_replace(engine, administrator_id, expected_revision, document_ids)
UPDATE organization_settings SET knowledge_revision=:revision,access_epoch=:epoch,
updated_by=:actor,updated_at=now() WHERE organization_id=:org
"""), dict(org=org, actor=current["id"], revision=revision, epoch=epoch))
if removed:
conn.execute(text("""UPDATE conversations SET status='stale',updated_at=now() WHERE organization_id=:org AND access_epoch<:epoch AND status='active'"""), {'org': org, 'epoch': epoch})
conn.execute(text("""
UPDATE live_sessions
SET status = 'closed', closed_at = now(), close_reason = 'epoch_invalidated', updated_at = now()
WHERE organization_id = :org AND access_epoch < :epoch AND status IN ('creating', 'connecting', 'connected')
"""), {"org": org, "epoch": epoch})
conn.execute(text("""UPDATE tool_calls SET status='failed',completed_at=now(),error_code='CONTEXT_REVOKED'
WHERE organization_id=:org AND access_epoch<:epoch AND status='running'"""), {'org': org, 'epoch': epoch})
conn.execute(text("""
INSERT INTO audit_events(id,organization_id,actor_user_id,action,metadata)
VALUES (:id,:org,:actor,'selection_changed',CAST(:metadata AS jsonb))
@@ -165,7 +174,10 @@ def selection_replace(engine, administrator_id, expected_revision, document_ids)
metadata=json.dumps(dict(knowledge_revision=revision, access_epoch=epoch,
added_document_ids=[str(v) for v in sorted(wanted - old)],
removed_document_ids=[str(v) for v in sorted(old - wanted)]))))
return result
if changed and removed:
from app.modules.voice.registry import notify
notify(organization_id=org, new_epoch=epoch)
return result
class SearchService:
+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()
+147
View File
@@ -0,0 +1,147 @@
"""Trusted maintenance tool for provisioning demo and operator accounts.
No public signup or user management UI is exposed; only trusted maintenance
commands or scripts provision accounts.
"""
import argparse
from getpass import getpass
import json
import sys
from uuid import UUID, uuid4
from argon2 import PasswordHasher
from sqlalchemy import text
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
def provision_user(
connection,
*,
username: str,
password: str,
role: str = "user",
organization_id: UUID | str | None = None,
is_enabled: bool = True,
) -> dict:
username = username.strip().lower()
if not username or len(username) > 120:
raise ValueError("Username must contain 1-120 characters")
if role not in ("admin", "user"):
raise ValueError("Role must be 'admin' or 'user'")
if not password:
raise ValueError("Password cannot be empty")
# If organization_id not provided, look up existing organization
if organization_id is None:
org_row = connection.execute(
text("SELECT id FROM organizations ORDER BY created_at ASC LIMIT 1")
).mappings().first()
if not org_row:
raise ValueError("No organization exists. Run bootstrap first.")
org_id = org_row["id"]
else:
org_id = UUID(str(organization_id))
org_row = connection.execute(
text("SELECT id FROM organizations WHERE id = :org_id"),
{"org_id": org_id}
).mappings().first()
if not org_row:
raise ValueError(f"Organization {organization_id} not found.")
password_hash = PasswordHasher().hash(password)
# Check if user already exists
existing = connection.execute(
text("SELECT id, organization_id, role, is_enabled FROM users WHERE username = :username"),
{"username": username}
).mappings().first()
if existing:
if existing["organization_id"] != org_id:
raise ValueError("Username belongs to another organization")
user_id = existing["id"]
connection.execute(
text("""
UPDATE users
SET password_hash = :hash, role = :role, is_enabled = :enabled, updated_at = now()
WHERE id = :id AND organization_id = :org_id
"""),
{"id": user_id, "org_id": org_id, "hash": password_hash, "role": role, "enabled": is_enabled}
)
return {
"status": "updated",
"user_id": str(user_id),
"organization_id": str(existing["organization_id"]),
"username": username,
"role": role,
"is_enabled": is_enabled,
}
else:
user_id = uuid4()
connection.execute(
text("""
INSERT INTO users (id, organization_id, username, password_hash, role, is_enabled)
VALUES (:id, :org_id, :username, :hash, :role, :enabled)
"""),
{
"id": user_id,
"org_id": org_id,
"username": username,
"hash": password_hash,
"role": role,
"enabled": is_enabled,
}
)
return {
"status": "created",
"user_id": str(user_id),
"organization_id": str(org_id),
"username": username,
"role": role,
"is_enabled": is_enabled,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--username", required=True, help="Username (1-120 characters)")
parser.add_argument("--role", default="user", choices=["admin", "user"], help="User role")
parser.add_argument("--organization-id", help="Organization UUID (defaults to first org)")
parser.add_argument("--disabled", action="store_true", help="Provision user as disabled")
parser.add_argument("--password-stdin", action="store_true", help="Read password from stdin")
args = parser.parse_args()
if args.password_stdin:
password = sys.stdin.readline().rstrip("\r\n")
else:
if not sys.stdin.isatty():
parser.error("Use an interactive terminal or explicitly select --password-stdin")
password = getpass("Account password: ")
if password != getpass("Confirm password: "):
parser.error("Passwords do not match")
engine = None
try:
settings = IngestionSettings()
engine = create_database(settings.database_url.get_secret_value())
with engine.begin() as connection:
result = provision_user(
connection,
username=args.username,
password=password,
role=args.role,
organization_id=args.organization_id,
is_enabled=not args.disabled,
)
print(json.dumps(result))
except Exception as exc:
parser.exit(1, f"Account provisioning failed: {exc}\n")
finally:
if engine is not None:
engine.dispose()
if __name__ == "__main__":
main()
+16 -17
View File
@@ -1,4 +1,4 @@
"""Operator-only diagnostic Realtime/search smoke; no HTTP/text-chat route."""
"""Operator-only diagnostic Gemini/search smoke; no HTTP/text-chat route."""
import argparse
import asyncio
from dataclasses import asdict
@@ -7,12 +7,9 @@ from pathlib import Path
import sys
from uuid import UUID
from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import text
from app.infrastructure.database import create_database, check_compatibility
from app.infrastructure.realtime import RealtimeAdapter, connect
from app.modules.documents.settings import IngestionSettings
from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.langchain_tool import SearchToolRunner
@@ -21,13 +18,7 @@ from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.serialization import bounded_json
class VoiceSettings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore", hide_input_in_errors=True)
openai_api_key: SecretStr
openai_realtime_model: str = Field(default="gpt-realtime-mini", min_length=1)
openai_proxy: str | None = None
runtime_settings: RuntimeSettings = Field(default_factory=RuntimeSettings)
search_calibration_report: Path
from app.modules.voice.configuration import VoiceSettings
def preflight(engine, settings, actor, cutoff):
if cutoff.profile != asdict(settings.embedding_profile):
@@ -59,15 +50,20 @@ async def run(service, runner, actor, config, query, seconds, max_calls):
print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr)
return 1
async def create_adapter(config, limits):
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
config.require_voice()
transport = await connect_gemini(config.gemini_api_key.get_secret_value(), config.gemini_model, config.gemini_proxy, limits)
adapter = GeminiLiveAdapter(transport, model=config.gemini_model, voice=config.gemini_voice, settings=limits)
return adapter
async def _run(service, runner, actor, config, query, max_calls, limits):
transport = await connect(config.openai_api_key.get_secret_value(),
config.openai_realtime_model, config.openai_proxy,
limits)
adapter = await create_adapter(config, limits)
async def emit(event):
if isinstance(event, bytes):
return # No playback assertion: diagnostic smoke never claims heard audio.
print(bounded_json(event, limits.max_server_event_bytes), flush=True)
runtime = VoiceRuntime(RealtimeAdapter(transport, model=config.openai_realtime_model, settings=limits),
runtime = VoiceRuntime(adapter,
service, runner, actor, emit, max_calls=max_calls,
settings=limits)
receiver = None
@@ -98,7 +94,7 @@ async def _run(service, runner, actor, config, query, max_calls, limits):
actual = [(cid, r, c) for cid, (r, c) in runtime.calls.items()
if r.turn is current]
if (not actual or any(not c["sent"] or c["result"] is None or
not r.terminal or r.status != "completed" or r.interrupted
not r.terminal or r.status not in ("completed", "waiting_tools") or r.interrupted
for _, r, c in actual)):
continue
chain, cursor = set(), answer
@@ -133,7 +129,7 @@ def main(argv=None):
parser.add_argument("--user-id", type=UUID, required=True)
parser.add_argument("--query", required=True)
parser.add_argument("--allow-provider-calls", action="store_true", required=True,
help="Authorize Realtime plus up to --max-tool-calls query embeddings")
help="Authorize Gemini Live plus up to --max-tool-calls query embeddings")
parser.add_argument("--seconds", type=int, choices=range(1, 601), default=90, metavar="1..600")
parser.add_argument("--max-tool-calls", type=int, choices=range(1, 11), default=4, metavar="1..10")
args = parser.parse_args(argv)
@@ -143,6 +139,9 @@ def main(argv=None):
if not args.query.strip() or len(args.query) > 2000:
raise ValueError("Bounded query required")
settings, config = IngestionSettings(), VoiceSettings()
config.require_voice()
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 settings.embedding_timeout_seconds > 75:
raise ValueError("Smoke embedding timeout must not exceed 75 seconds")