feat(backend): deliver Phase 3 document and voice integration

Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
This commit is contained in:
11linear11
2026-10-09 17:43:52 -04:00
parent 9be47191d6
commit a73a496c54
67 changed files with 5988 additions and 234 deletions
+21
View File
@@ -0,0 +1,21 @@
"""Fail closed without labelling unavailable authority as verified revocation."""
from sqlalchemy.exc import SQLAlchemyError
from app.modules.knowledge.service import KnowledgeError
def authority_failure_code(exc):
if isinstance(exc, KnowledgeError) and exc.code in {'ACTOR_UNAVAILABLE', 'CONTEXT_REVOKED'}:
return 'CONTEXT_REVOKED'
if isinstance(exc, TimeoutError):
return 'SEARCH_TIMEOUT'
if isinstance(exc, SQLAlchemyError):
return 'DEPENDENCY_UNAVAILABLE'
if isinstance(exc, ValueError):
if str(exc) == 'SERVICE_BUSY':
return 'SEARCH_SATURATED'
if str(exc) in {'AUTH_REQUIRED', 'USER_DISABLED', 'ACCOUNT_DISABLED', 'SESSION_REVOKED', 'SESSION_EXPIRED',
'CONTEXT_REVOKED', 'CONVERSATION_STALE', 'CONVERSATION_CLOSED',
'CONVERSATION_NOT_FOUND', 'SESSION_NOT_FOUND', 'LIVE_SESSION_EXPIRED',
'LIVE_SESSION_UNUSABLE'}:
return 'CONTEXT_REVOKED'
return 'DEPENDENCY_UNAVAILABLE'
+61 -11
View File
@@ -2,39 +2,51 @@
from pathlib import Path
from typing import Literal
from urllib.parse import urlsplit
from pydantic import Field, SecretStr, field_validator, model_validator
from pydantic import AliasChoices, 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'
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
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
openai_realtime_api_key: SecretStr = SecretStr('')
openai_realtime_model: str = Field(default='gpt-realtime-mini', min_length=1, max_length=200)
openai_realtime_voice: str = Field(default='shimmer', min_length=1, max_length=80)
openai_realtime_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
voice_transport_testing: bool = False
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')
def __init__(self, **values):
# Settings sources normalize aliases and would otherwise discard conflicting init keys.
aliases = [key for key in values if key.lower() in ('voice_provider', 'provider')]
if len({values[key] for key in aliases}) > 1:
raise ValueError('Conflicting voice provider aliases')
super().__init__(**values)
@field_validator('gemini_model', 'gemini_voice', 'openai_realtime_model', 'openai_realtime_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')
@field_validator('trusted_origins', 'trusted_hosts', 'gemini_proxy', 'openai_realtime_proxy')
@classmethod
def urls(cls, value, info):
if info.field_name == 'gemini_proxy' and value is None:
if info.field_name.endswith('_proxy') and value is None:
return value
values = (value,) if info.field_name == 'gemini_proxy' else value
values = (value,) if info.field_name.endswith('_proxy') else value
if not values or len(values) > 20:
raise ValueError('Explicit bounded trusted endpoints required')
for entry in values:
@@ -43,7 +55,7 @@ class VoiceSettings(BaseSettings):
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')
schemes = ('http', 'https', 'socks5', 'socks5h') if info.field_name.endswith('_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')
@@ -55,11 +67,49 @@ class VoiceSettings(BaseSettings):
raise ValueError('Insecure cookies require loopback-only development origins')
return self
@classmethod
def settings_customise_sources(cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings):
# Normalize aliases before source merging; ordinary init > env > dotenv priority remains.
deployed = {**dotenv_settings.env_vars, **env_settings.env_vars}
if ('voice_provider' in deployed and 'provider' in deployed
and deployed['voice_provider'] != deployed['provider']):
raise ValueError('Conflicting VOICE_PROVIDER and PROVIDER')
def normalized(source):
def read():
values = source()
aliases = [key for key in ('VOICE_PROVIDER', 'PROVIDER', 'provider') if key in values]
if len({values[key] for key in aliases}) > 1:
raise ValueError('Conflicting voice provider aliases')
if aliases:
selected = values[aliases[0]]
for key in aliases:
del values[key]
values['VOICE_PROVIDER'] = selected
return values
return read
return tuple(normalized(source) for source in (init_settings, env_settings, dotenv_settings, file_secret_settings))
@property
def selected_model(self):
return self.gemini_model if self.provider == 'gemini' else self.openai_realtime_model
@property
def selected_voice(self):
return self.gemini_voice if self.provider == 'gemini' else self.openai_realtime_voice
@property
def selected_proxy(self):
return self.gemini_proxy if self.provider == 'gemini' else self.openai_realtime_proxy
@property
def selected_key(self):
return self.gemini_api_key if self.provider == 'gemini' else self.openai_realtime_api_key
def require_voice(self):
key = self.gemini_api_key.get_secret_value()
key = self.selected_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)
return dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000)
+9 -2
View File
@@ -78,12 +78,18 @@ class LiveLifecycleService:
raise ValueError('LIVE_SESSION_UNUSABLE')
return row
@staticmethod
def _calibration_status(row):
search = (row["execution_profile"] or {}).get("search", {})
return "calibrated" if search.get("calibration_id") else search.get("calibration_status", "unknown")
@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)
expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed,
calibration_status=LiveLifecycleService._calibration_status(row))
@staticmethod
def _terminal(conn, sid, reason, *, failed=False):
@@ -250,7 +256,8 @@ class LiveLifecycleService:
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)
expires_at=row['expires_at'].isoformat(), error_code=row['error_code'], recent_tool_results=results,
calibration_status=self._calibration_status(row))
def admit_tool(self, user, session_id, external_call_id, public_ref, arguments, execution):
arguments = SearchInput.model_validate(arguments).model_dump()
+3 -1
View File
@@ -1,4 +1,5 @@
"""Bounded, session-local voice state machine. HTTP identity/persistence is Phase 2."""
from app.modules.voice.authority import authority_failure_code
import asyncio
import base64
from collections import deque
@@ -235,7 +236,8 @@ class VoiceRuntime:
try:
valid = await asyncio.wait_for(self.authority_check(
turn.execution if turn else self.session_execution), self.settings.authority_timeout_seconds)
except Exception:
except Exception as exc:
self.fail(authority_failure_code(exc))
valid = False
return valid