Add pinned CPU engine dependencies, retained interrupted-response history, provider admission, offline evaluation and isolated browser tooling. Record Phase 2 acceptance and Phase 3/4 preparation, bounded paid-test accounting and interruption incident findings. Human interruption acceptance, paired OpenAI evaluation and rollback remain pending.
92 lines
4.8 KiB
Python
92 lines
4.8 KiB
Python
"""Versioned extension for the pinned engine; no history-repair capability."""
|
|
from copy import deepcopy
|
|
from queue import Queue, Full
|
|
from app.modules.voice.local_s2s import effective_identity
|
|
|
|
|
|
class FailClosedQueue(Queue):
|
|
"""Saturation stops the candidate rather than blocking a teardown producer."""
|
|
def __init__(self, stop_event, maxsize=256):
|
|
super().__init__(maxsize=maxsize)
|
|
self.stop_event = stop_event
|
|
|
|
def put(self, item, block=True, timeout=None):
|
|
try:
|
|
return super().put(item, block=False)
|
|
except Full:
|
|
self.stop_event.set()
|
|
raise RuntimeError('LOCAL_ENGINE_QUEUE_CAPACITY') from None
|
|
|
|
|
|
def active_components(unit, expected):
|
|
"""Read initialized handlers, not session.update model/voice echoes."""
|
|
handlers = unit.handlers
|
|
stt = next(h for h in handlers if type(h).__module__.endswith('.STT.openai_compatible_handler'))
|
|
tts = next(h for h in handlers if type(h).__module__.endswith('.TTS.openai_compatible_handler'))
|
|
llm = next(h for h in handlers if hasattr(h, 'model_name') and hasattr(h, 'client'))
|
|
actual = dict(stt=dict(backend='openai', model=stt.model, language=stt.language,
|
|
response_format=stt.response_format, final_only=True),
|
|
llm=dict(backend='chat-completions', model=llm.model_name,
|
|
max_output_tokens=getattr(llm.client, 'token_limit', None)),
|
|
tts=dict(backend='openai', model=tts.model, voice=tts.voice,
|
|
response_format=tts.response_format, sample_rate=tts.sample_rate),
|
|
request_timeout_seconds=stt.timeout)
|
|
if (actual != expected or tts.timeout != stt.timeout or llm.request_timeout_s != stt.timeout
|
|
or stt.base_url != 'http://127.0.0.1:8766/v1' or tts.base_url != stt.base_url
|
|
or str(llm.client.base_url).rstrip('/') != stt.base_url
|
|
or stt.api_key != 'local-components' or tts.api_key != stt.api_key
|
|
or llm.client.api_key != stt.api_key):
|
|
raise ValueError('LOCAL_ENGINE_COMPONENT_MISMATCH')
|
|
# Startup configuration fixes these values; refuse any unsupported handler layout.
|
|
vad = handlers[0]
|
|
if getattr(vad, 'enable_realtime_transcription', None) is not False:
|
|
raise ValueError('LOCAL_ENGINE_FINAL_ONLY_REQUIRED')
|
|
if llm.client.max_retries != 0:
|
|
raise ValueError('LOCAL_ENGINE_RETRY_POLICY_MISMATCH')
|
|
return actual
|
|
|
|
|
|
def install_session_proof(handler_class, service_components, session_template):
|
|
original = handler_class.build_session_updated
|
|
def build_session_updated(self, conn_id):
|
|
result = original(self, conn_id)
|
|
cfg = self._state(conn_id).runtime_config
|
|
# Project the actual post-update state onto the requested contract shape.
|
|
# Extra SDK defaults do not change the effective contract fingerprint.
|
|
actual = cfg.session.model_dump(mode='json')
|
|
def project(value, shape):
|
|
if isinstance(shape, dict):
|
|
return {k: project(value[k], v) for k, v in shape.items()}
|
|
if isinstance(shape, list):
|
|
if not isinstance(value, list) or len(value) != len(shape):
|
|
raise ValueError('LOCAL_ENGINE_SESSION_LAYOUT')
|
|
return [project(a, b) for a, b in zip(value, shape)]
|
|
return value
|
|
session = project(actual, session_template)
|
|
from app.modules.voice.local_s2s import RETENTION_INSTRUCTIONS as INSTRUCTIONS
|
|
if (session.get('instructions', '').endswith(INSTRUCTIONS)
|
|
and not getattr(self._service, '_rag_retention_enabled', False)):
|
|
raise ValueError('LOCAL_ENGINE_RETENTION_EXTENSION_MISSING')
|
|
components = service_components[id(self._service)]
|
|
identity = effective_identity(components, session)
|
|
return result.model_copy(update={'session': result.session.model_copy(update={'s2s_effective': identity})})
|
|
handler_class.build_session_updated = build_session_updated
|
|
return original
|
|
|
|
class EngineTokenGuard:
|
|
def __init__(self, app, token):
|
|
self.app, self.token = app, token
|
|
|
|
async def __call__(self, scope, receive, send):
|
|
import hmac
|
|
if scope['type'] in ('http', 'websocket') and self.token:
|
|
header = dict(scope.get('headers', [])).get(b'authorization', b'')
|
|
if not hmac.compare_digest(header, ('Bearer ' + self.token).encode('ascii')):
|
|
if scope['type'] == 'websocket':
|
|
await send({'type': 'websocket.close', 'code': 1008})
|
|
else:
|
|
await send({'type': 'http.response.start', 'status': 401, 'headers': []})
|
|
await send({'type': 'http.response.body', 'body': b''})
|
|
return
|
|
await self.app(scope, receive, send)
|