"""Pinned local engine GA transport; no invented native input/history receipts.""" from app.infrastructure.realtime import RealtimeAdapter from app.modules.voice.provider import ProviderProtocolError from app.modules.voice.local_s2s import setup_session, effective_identity class LocalS2SContextError(ProviderProtocolError): context_sync = True class LocalS2SAdapter(RealtimeAdapter): def __init__(self, transport, *, config, settings): # The local text model is not an OpenAI Realtime model. Keep its config # independent of OpenAI reasoning/transcription settings. self.transport, self.config, self.settings = transport, config, settings self.model, self.voice = config.selected_model, config.selected_voice self._setup = setup_session(config) self._identity = effective_identity(config.components(), self._setup) self._confirmed = False self._engine_session = None self._history_revision = 0 self._repair_receipts = {} def setup(self): from copy import deepcopy return dict(type='session.update', session=deepcopy(self._setup)) def acknowledged(self, session): self._confirmed = False self._engine_session = None # A session echo cannot certify a fixed global engine's real components. # The versioned engine extension derives this from initialized handlers. if not isinstance(session, dict) or session.get('s2s_effective') != self._identity: return False def matches(actual, expected): if isinstance(expected, dict): return isinstance(actual, dict) and all(k in actual and matches(actual[k], v) for k, v in expected.items()) if isinstance(expected, list): return isinstance(actual, list) and len(actual) == len(expected) and all(matches(a, b) for a, b in zip(actual, expected)) return type(actual) is type(expected) and actual == expected self._confirmed = matches(session, self._setup) if self._confirmed and self.config.local_s2s_retain_interrupted_answers: self._engine_session = session.get('id') self._confirmed = isinstance(self._engine_session, str) and bool(self._engine_session) return self._confirmed def token_limited(self, response): # No unverified local terminal signature is accepted as a successful answer. return False def is_no_active(self, error): try: return (isinstance(error, dict) and ( (error.get("type") == "invalid_request_error" and error.get("code") == "response_cancel_not_active" and error.get("param") is None) or (error.get("type") == "s2s_history_failed" and error.get("message") == "Cancellation identity mismatch" and error.get("param") is None) )) except Exception: return False def history_repair_request(self, repair): if not self.config.local_s2s_retain_interrupted_answers or not self._confirmed: raise LocalS2SContextError('Local retained history is not enabled/confirmed') return dict(type='conversation.item.truncate', event_id=repair.operation_id, session_id=repair.session_id, engine_session_id=self._engine_session, generation=repair.generation, response_id=repair.response_id, item_id=repair.item_id, content_index=repair.content_index, audio_end_ms=repair.played_ms) def confirm_history_repair(self, repair, event): from app.modules.voice.provider import HistoryRepairReceipt from app.modules.voice.local_s2s import RETENTION_POLICY as POLICY if repair is None: raise LocalS2SContextError('Missing frozen history repair') expected=self.history_repair_request(repair) fields={k:v for k,v in expected.items() if k not in ('type','event_id')} revision=event.get('history_revision') if (event.get('s2s_native_type')!='s2s.history.retained' or event.get('type')!='conversation.item.truncated' or event.get('operation_id')!=repair.operation_id or event.get('applied') is not True or event.get('policy')!=POLICY or any(type(event.get(k)) is not type(v) or event.get(k)!=v for k,v in fields.items()) or not isinstance(event.get('event_id'),str) or not event['event_id'] or len(event['event_id'])>200 or type(revision) is not int or revision<=0): raise LocalS2SContextError('Retained history receipt mismatch') proof={k:v for k,v in event.items() if k!='event_id'} prior=self._repair_receipts.get(repair.operation_id) if prior is not None: if prior!=proof: raise LocalS2SContextError('Conflicting retained history receipt') else: if revision!=self._history_revision+1: raise LocalS2SContextError('Stale retained history revision') self._history_revision=revision self._repair_receipts[repair.operation_id]=proof return HistoryRepairReceipt(repair,event.get('event_id'),'local_s2s.retained_unheard_draft') async def receive(self): event=await super().receive() if event.get('type')=='s2s.history.retained': # Private normalization only: provenance and native type are retained. # This receipt attests annotation, never OpenAI truncation/heard text. event=dict(event,type='conversation.item.truncated',s2s_native_type=event['type']) return event async def send_serialized(self, wire): from app.modules.voice.provider import strict_json event=strict_json(wire) if event.get('type') in ('response.cancel','conversation.item.truncate','s2s.history.retain'): if not self.config.local_s2s_retain_interrupted_answers or not self._confirmed: raise LocalS2SContextError('Local retained history requires confirmed opt-in') if event.get('type')=='conversation.item.truncate': # Keep the shared runtime's cleanup command/deadline accounting; # only the local adapter changes its private native wire operation. wire=self.serialize(dict(event,type='s2s.history.retain')) await self.transport.send(wire) async def connect_local(config, limits): from websockets.asyncio.client import connect token = config.local_s2s_token.get_secret_value() return await connect(config.local_s2s_endpoint, additional_headers={'Authorization': 'Bearer ' + token} if token else {}, proxy=None, compression=None, max_size=limits.max_provider_message_bytes, max_queue=16, open_timeout=limits.connect_timeout_seconds, close_timeout=limits.send_timeout_seconds, ping_interval=20, ping_timeout=20)