feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add an opt-in isolated Local S2S adapter, pinned engine extension, bounded component gateway and frozen effective configuration profiles. Enforce request token limits, zero retries, local asset validation, connection deadlines, disconnect ownership, bounded cleanup and signals. Include regression coverage, pinned source fixtures, operator guidance, asset fingerprints and guarded disposable PostgreSQL acceptance tooling. Preserve immutable fixture bytes across Git line-ending conversion. Validation recorded in the reports: - 74 repair, 107 combined and 242 preservation checks passed. - Fresh PostgreSQL local checks: 2 passed. - Expanded PostgreSQL: 57 passed, 6 documented baseline failures. - Compose configurations, staged whitespace and fixture hashes passed. Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component audio and Persian browser acceptance remain pending. No operational switch, paid call, model download or Phase 3 implementation is included.
This commit is contained in:
@@ -15,7 +15,8 @@ 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
|
||||
from app.infrastructure.realtime import POLICY
|
||||
from app.modules.voice.provider import strict_json, ProviderProtocolError
|
||||
|
||||
class GeminiContextError(ProviderProtocolError):
|
||||
context_sync = True
|
||||
@@ -102,6 +103,21 @@ class GeminiLiveAdapter:
|
||||
self._sent_samples = 0
|
||||
self._resampler = PCM24To16()
|
||||
|
||||
def cancellation_request(self, response_id, operation_id=None):
|
||||
event = dict(type="response.cancel", response_id=response_id)
|
||||
if operation_id is not None:
|
||||
event["event_id"] = operation_id
|
||||
return event
|
||||
|
||||
def history_repair_request(self, repair):
|
||||
# Preserve the existing send-path failure and its bounded cleanup.
|
||||
return dict(type="conversation.item.truncate", event_id=repair.operation_id,
|
||||
item_id=repair.item_id, content_index=repair.content_index,
|
||||
audio_end_ms=repair.played_ms)
|
||||
|
||||
def confirm_history_repair(self, repair, event):
|
||||
raise GeminiContextError('Gemini context cannot be safely truncated')
|
||||
|
||||
def setup(self):
|
||||
return dict(type='session.update', session={'provider':'gemini'})
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""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
|
||||
|
||||
def setup(self):
|
||||
from copy import deepcopy
|
||||
return dict(type='session.update', session=deepcopy(self._setup))
|
||||
|
||||
def acknowledged(self, session):
|
||||
# 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)
|
||||
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):
|
||||
return False
|
||||
|
||||
def confirm_history_repair(self, repair, event):
|
||||
raise LocalS2SContextError('Local history repair is not available in Phase 2')
|
||||
|
||||
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'):
|
||||
raise LocalS2SContextError('Local interruption requires Phase 3 history repair')
|
||||
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)
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Private OpenAI Realtime wire adapter; no application/provider IDs cross to clients."""
|
||||
import json
|
||||
from urllib.parse import quote
|
||||
|
||||
from app.modules.knowledge.service import SearchInput
|
||||
@@ -8,8 +7,9 @@ from app.modules.voice.configuration import OpenAIInputSettings
|
||||
from app.modules.voice.serialization import bounded_json
|
||||
from app.modules.voice.openai_style import effective_instructions
|
||||
|
||||
class ProviderProtocolError(ValueError):
|
||||
pass
|
||||
from app.modules.voice.provider import (
|
||||
ProviderProtocolError, canonical_json, strict_json, HistoryRepair, HistoryRepairReceipt,
|
||||
)
|
||||
|
||||
POLICY = """You are the official voice assistant for «شرکت شهرکهای صنعتی اصفهان».
|
||||
Your scope is strictly limited to answering questions regarding «شرکت شهرکهای صنعتی اصفهان», including its regulations, industrial parks in Isfahan province, land allocations, contracts, permits, circulars, and official procedures.
|
||||
@@ -52,21 +52,6 @@ When calling search_knowledge:
|
||||
- Preserve the user's explicitly stated place names, person names, document titles and identifiers in query. Shortening the question must not replace them with different entities. If a name is unclear, ask for clarification rather than guessing.
|
||||
- Set 'context' to null. Never write explanations or user intent in 'context'."""
|
||||
|
||||
def canonical_json(value):
|
||||
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
||||
separators=(",", ":"), sort_keys=True)
|
||||
|
||||
def strict_json(raw):
|
||||
def pairs(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
if key in value:
|
||||
raise ValueError("Duplicate JSON key")
|
||||
value[key] = item
|
||||
return value
|
||||
return json.loads(raw, object_pairs_hook=pairs,
|
||||
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")))
|
||||
|
||||
class RealtimeAdapter:
|
||||
# Argument-done can precede a cut-off tool call: wait for terminal success.
|
||||
defer_tool_execution = True
|
||||
@@ -146,6 +131,30 @@ class RealtimeAdapter:
|
||||
for key in empty_defaults
|
||||
if key not in expected['audio']['input']['transcription'])
|
||||
|
||||
def cancellation_request(self, response_id, operation_id=None):
|
||||
event = dict(type="response.cancel", response_id=response_id)
|
||||
if operation_id is not None:
|
||||
event["event_id"] = operation_id
|
||||
return event
|
||||
|
||||
def history_repair_request(self, repair: HistoryRepair):
|
||||
return dict(type="conversation.item.truncate", event_id=repair.operation_id,
|
||||
item_id=repair.item_id, content_index=repair.content_index,
|
||||
audio_end_ms=repair.played_ms)
|
||||
|
||||
def confirm_history_repair(self, repair: HistoryRepair, event):
|
||||
# Native OpenAI ack has no request event_id/response_id. Runtime first
|
||||
# matches exactly one dispatched item/part in this session; never invent
|
||||
# additional upstream confirmation or infer a heard transcript prefix.
|
||||
if (event.get("type") != "conversation.item.truncated"
|
||||
or event.get("item_id") != repair.item_id
|
||||
or type(event.get("content_index")) is not int
|
||||
or event["content_index"] != repair.content_index
|
||||
or type(event.get("audio_end_ms")) is not int
|
||||
or event["audio_end_ms"] != repair.played_ms):
|
||||
raise ProviderProtocolError("History repair acknowledgement mismatch")
|
||||
return HistoryRepairReceipt(repair, event.get("event_id"), "openai.item_truncated")
|
||||
|
||||
def interrupted_tool_output(self, call_id):
|
||||
# Resolve abandoned private tool calls without publishing stale evidence.
|
||||
return dict(type="conversation.item.create", item=dict(
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
"""Selected voice transport construction shared by the API and operator smoke."""
|
||||
import asyncio
|
||||
from app.modules.voice.provider import VoiceProvider
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
|
||||
from app.infrastructure.realtime import RealtimeAdapter, connect as connect_openai
|
||||
|
||||
|
||||
async def create_adapter(config, limits):
|
||||
async def create_adapter(config, limits) -> VoiceProvider:
|
||||
config.require_voice()
|
||||
if config.provider == 'local_s2s':
|
||||
from app.infrastructure.local_s2s import LocalS2SAdapter, connect_local
|
||||
if limits.output_capacity_profile != 'standard':
|
||||
raise ValueError('OpenAI output capacity cannot be used for local S2S')
|
||||
transport = await asyncio.wait_for(connect_local(config, limits), limits.connect_timeout_seconds)
|
||||
try:
|
||||
return LocalS2SAdapter(transport, config=config, settings=limits)
|
||||
except BaseException:
|
||||
await asyncio.wait_for(transport.close(), limits.send_timeout_seconds)
|
||||
raise
|
||||
if config.provider == 'gemini' and limits.output_capacity_profile != 'standard':
|
||||
raise ValueError('OpenAI output capacity cannot be used for Gemini')
|
||||
input_settings = None
|
||||
|
||||
Reference in New Issue
Block a user