Files
rag-technical-docs-assistant/app/modules/voice/runtime.py
T
amirhosein mazaheri 9e6864ae2a fix(voice): expand speech buffer to 60s, handle 2.1 cancellation race, and bound cleanup
- Expand max_input_buffer_bytes to 3,072,000 (64s at 24kHz PCM16) with 65s fixed deadline
- Broaden response_cancel_not_active race classifier to include gpt-realtime-2.1/shimmer
- Add transport abort method and bound cleanup waits during websocket close
- Record repair progress in docs/plans/live-conversation-repair-progress.md
2026-10-12 18:51:06 +03:30

1791 lines
95 KiB
Python

"""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
from dataclasses import dataclass, field
import hashlib
import time
from threading import Event
from uuid import uuid4
from pydantic import ValidationError
from app.modules.knowledge.evidence import SearchExecution
from app.modules.knowledge.langchain_tool import ToolContext, create_search_tool
from app.modules.knowledge.service import SearchInput, authority, transaction
from app.infrastructure.realtime import canonical_json, strict_json, ProviderProtocolError
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.diagnostics import diagnostic, protocol_reason
from app.modules.voice.serialization import bounded_json, json_size, bounded_json_digest
def identity():
return uuid4().hex
def provider_identifier(value):
if not isinstance(value, str) or not 1 <= len(value) <= 128 or not value.isascii():
raise ValueError("Provider identity bound")
def argument_digest(raw):
if not isinstance(raw, str) or len(raw) > 8192:
raise ValueError("Tool argument bound")
encoded = raw.encode("utf-8", errors="surrogatepass")
if len(encoded) > 8192:
raise ValueError("Tool argument bound")
return hashlib.sha256(encoded).digest()
def provider_event_digest(event, limit):
# Only model argument strings may contain rejected Unicode. All framing,
# correlation and other provider fields still use strict scalar validation.
fingerprints = []
def arguments(item):
if not isinstance(item, dict) or "arguments" not in item:
return item
raw = item["arguments"]
fingerprints.append(argument_digest(raw))
safe = "".join(chr(0xFFFD) if 0xD800 <= ord(ch) <= 0xDFFF else ch for ch in raw)
return dict(item, arguments=safe)
kind = event.get("type")
if kind == "response.function_call_arguments.done":
event = arguments(event)
elif kind in ("response.output_item.added", "response.output_item.done"):
item = event.get("item")
if isinstance(item, dict) and item.get("type") == "function_call":
event = dict(event, item=arguments(item))
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"
else item for item in response["output"]]
event = dict(event, response=dict(response, output=output))
# Scalar replacement stays within admitted UTF-8 work (surrogates were
# escaped on the wire). Original fixed-size argument digests distinguish
# replacement/literal and changed arguments without logging unsafe data.
digest = bounded_json_digest(event, limit)
for fingerprint in fingerprints:
digest.update(fingerprint)
return digest.digest()
@dataclass
class Turn:
ref: str
token: int
input_id: str
execution: SearchExecution
stopped: bool = False
committed: bool = False
superseded: bool = False
initial: bool = False
intent: str | None = None
cancelled: Event = field(default_factory=Event)
diagnostic: str | None = None
speech_deadline: float | None = None
start_position: int | None = None
input_deadline: float | None = None
commit_ack: bool = False
stop_boundary: int | None = None
diagnostic_dispatched: bool = False
transcript_parts: dict = field(default_factory=dict)
@dataclass
class Response:
id: str
turn: Turn
terminal: bool = False
status: str | None = None
interrupted: bool = False
calls: dict = field(default_factory=dict)
continued: bool = False
creation_intent: str | None = None
visible: bool = False
transcript_completed: bool = False
transcript_delivered: bool = False
parent_response: str | None = None
transcript_parts: dict = field(default_factory=dict)
pending_transcript: "Control | None" = None
limited: bool = False
terminal_digest: bytes | None = None
cancel_event: str | None = None
cancel_deadline: float | None = None
final_deadline: float | None = None
@dataclass
class Audio:
ref: str
response: Response
item: str
index: int
state: str = "open"
data: bytearray = field(default_factory=bytearray)
generated: int = 0
sent: int = 0
played: int = 0
credit: int = 0
reserved: int = 0
started: bool = False
ended: bool = False
done: bool = False
frozen: bool = False
retired_credit: bool = False
timer: str | None = None
stall_deadline: float | None = None
cleanup: str | None = None
cleanup_deadline: float | None = None
cleanup_dispatched: bool = False
@dataclass
class Command:
event: dict
size: int
owner: Turn | None
queue_deadline: float
pcm: bytes | None = None
input_end: int | None = None
dispatched: bool = False
send_deadline: float | None = None
accounted: bool = True
wire: str | None = None
@dataclass
class Control:
event: dict
size: int
response: Response | None = None
completed_transcript: bool = False
accounted: bool = True
send_deadline: float | None = None
class VoiceRuntime:
"""All decisions serialize under lock; retrieval and socket sends run separately.
authority_check is a trusted async backend callback that captures/revalidates
the session's persisted actor/epoch. It is never model input.
"""
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, 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")
adapter.settings = self.settings
tool_seconds = self.settings.tool_timeout_seconds if tool_seconds is None else tool_seconds
max_calls = self.settings.max_tool_calls if max_calls is None else max_calls
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
self.authority_check = authority_check or self._persisted_authority
self.session_execution = SearchExecution(user_id)
self.tool_seconds, self.max_calls = tool_seconds, max_calls
self.session_id = session_id or str(uuid4())
self.lock = asyncio.Lock()
self.wake = asyncio.Event()
self.commands = asyncio.Queue(maxsize=self.settings.max_control_messages +
self.settings.max_queued_audio_messages)
self.pending_commands = {}
self.command_bytes = self.command_count = 0
self.control_bytes = self.control_count = 0
self.active_control = None
self.input_transport_bytes = self.input_transport_count = 0
self.input_admitted_total = self.input_dispatched_total = self.input_forwarded_total = 0
self.input_committed_total = 0
self.input_released = False
self.origin_intents = {}
self.intent_dispatched = False
self.error_delivered = asyncio.Event()
self.failure_signal = asyncio.Event()
self.close_code = None
self._provider_closed = False
self._provider_close_task = None
self._close_task = None
self.failure_error_pending = False
self.controls = deque()
self.tasks = set()
self.inputs, self.responses, self.audio, self.parts, self.calls = {}, {}, {}, {}, {}
self.output_items = {}
self.output_positions = {}
self.item_types = {}
self.function_items = {}
self.events = {}
self.current = None
self.token = 0
self.last_start = -1
self.pending_create = None
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
self.intent_deadline = None
self._workers = []
self._release_check = None
self.audio_send_deadline = None
self.audio_send_owner = None
async def _persisted_authority(self, execution):
def check():
with transaction(self.service.engine) as conn:
actor, settings = authority(conn, self.user_id)
epoch = settings["access_epoch"]
if not self.session_execution.capture(actor, epoch):
return False
return execution.capture(actor, epoch)
return await asyncio.to_thread(check)
async def check_authority(self, turn=None):
try:
valid = await asyncio.wait_for(self.authority_check(
turn.execution if turn else self.session_execution), self.settings.authority_timeout_seconds)
except Exception as exc:
code = authority_failure_code(exc)
diagnostic(self.session_id, "authority", "AUTHORITY_CHECK_FAILED", exc=exc, code=code)
self.fail(code, turn=turn)
return False
if not valid:
diagnostic(self.session_id, "authority", "AUTHORITY_INVALIDATED", code="CONTEXT_REVOKED")
self.fail("CONTEXT_REVOKED", turn=turn)
return valid
async def authorized(self, turn=None):
# Used only from startup; provider reception has not begun.
valid = await self.check_authority(turn)
return valid
def command(self, event, *, pcm=None, input_end=None):
if not self.usable and event["type"] != "response.cancel":
return None
event = dict(event)
event.setdefault("event_id", identity())
owner = self.current
kind = event["type"]
if kind == "response.cancel":
owner = self.responses.get(event.get("response_id"), None)
owner = owner.turn if owner else self.current
elif kind == "conversation.item.truncate":
part = next((a for a in self.audio.values() if a.cleanup == event["event_id"]), None)
owner = part.response.turn if part else self.current
try:
wire = None if pcm is not None else self.adapter.serialize(event)
size = 0 if wire is None else len(wire.encode("utf-8"))
if wire is not None:
event = strict_json(wire)
except (ValueError, TypeError, RecursionError):
self.fail("LIVE_FRAME_TOO_LARGE", turn=owner)
return None
if pcm is None and (self.command_count >= self.settings.max_control_messages or
self.command_bytes + size > self.settings.max_control_bytes):
self.overflow("PROVIDER_CONTROL_CAPACITY", turn=owner)
return None
if self.commands.full():
self.overflow("PROVIDER_COMMAND_CAPACITY", turn=owner)
return None
cmd = Command(event, size, owner,
self.clock() + self.settings.dispatch_wait_timeout_seconds, pcm, input_end,
wire=wire)
self.pending_commands[event["event_id"]] = cmd
if pcm is None:
self.command_count += 1
self.command_bytes += size
self.commands.put_nowait(cmd)
return cmd
def release_command(self, cmd):
if not cmd.accounted:
return
cmd.accounted = False
self.pending_commands.pop(cmd.event["event_id"], None)
if cmd.pcm is None:
self.command_count -= 1
self.command_bytes -= cmd.size
else:
self.input_transport_bytes -= len(cmd.pcm)
self.input_transport_count -= 1
def release_control(self, control):
if control.accounted:
control.accounted = False
self.control_count -= 1
self.control_bytes -= control.size
def control(self, event, *, response=None, completed_transcript=False, terminal=False):
try:
wire = bounded_json(event, self.settings.max_server_event_bytes)
except (ValueError, TypeError, RecursionError):
if not terminal:
self.fail("LIVE_FRAME_TOO_LARGE", turn=response.turn if response else None)
return None
size = len(wire.encode("utf-8"))
reserve_count, reserve_bytes = (0, 0) if terminal else (1, 1024)
if (self.control_count + 1 > self.settings.max_control_messages - reserve_count or
self.control_bytes + size > self.settings.max_control_bytes - reserve_bytes):
if not terminal:
self.overflow("CLIENT_CONTROL_CAPACITY", turn=response.turn if response else None)
return None
# Freeze a bounded event so later producer mutation cannot widen its reservation.
entry = Control(strict_json(wire), size, response, completed_transcript)
self.controls.append(entry)
self.control_count += 1
self.control_bytes += size
self.wake.set()
return entry
def stop_requested(self):
# HTTP close has already committed its terminal state. It is a normal
# stop, not evidence that authority was revoked.
if self.usable:
self.usable = False
self.close_code = 1000
for turn in self.inputs.values():
turn.cancelled.set()
self.failure_signal.set()
self.wake.set()
def fail(self, code, *, turn=None, writable=True):
if not self.usable:
return
self.usable, self.failure = False, code
self.close_code = (1008 if code in ("LIVE_NOT_READY", "LIVE_PROTOCOL_ERROR") else
1009 if code == "LIVE_FRAME_TOO_LARGE" else
1013 if code == "LIVE_BUFFER_OVERFLOW" else 1011)
affected = turn or self.current
pending_cancels = [cmd.event for cmd in self.pending_commands.values()
if cmd.event["type"] == "response.cancel" and not cmd.dispatched]
self.failure_signal.set()
for input_turn in self.inputs.values():
input_turn.cancelled.set()
for cmd in list(self.pending_commands.values()):
self.release_command(cmd)
while not self.commands.empty():
self.commands.get_nowait()
self.input_released = True
for audio in self.audio.values():
audio.data.clear()
audio.timer = None
self.retire(audio)
while self.controls:
self.release_control(self.controls.popleft())
if writable:
self.failure_error_pending = self.control(dict(type="error", turn_ref=affected.ref if affected else None,
error=dict(code=code, message="Voice session stopped; start a fresh session.",
request_id=self.session_id, retryable=False)), terminal=True) is not None
for cancel in pending_cancels:
self.command(cancel)
for response in self.responses.values():
self.discard_pending_transcript(response)
if not response.terminal and not response.cancel_event:
response.cancel_event = identity()
self.command(dict(type="response.cancel", response_id=response.id,
event_id=response.cancel_event))
task = asyncio.create_task(self._finish_failure(writable))
self.tasks.add(task)
task.add_done_callback(self._failure_finished)
self.wake.set()
def _ensure_provider_close(self):
# Event-loop-local creation is atomic; the close task outlives its waiters.
if self._provider_close_task is None:
self._provider_close_task = asyncio.create_task(self._bounded_provider_close())
self._provider_close_task.add_done_callback(self._provider_close_finished)
return self._provider_close_task
async def _bounded_provider_close(self):
closing = asyncio.create_task(self.adapter.close())
done, _ = await asyncio.wait({closing}, timeout=self.settings.send_timeout_seconds)
if done:
if closing.cancelled():
return TimeoutError("Provider close cancelled")
return closing.exception()
closing.cancel()
closing.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)
try:
aborted = self.adapter.abort()
except Exception:
aborted = False
diagnostic(self.session_id, "provider_close", "CLEANUP_ABORT",
code=self.failure, abort_succeeded=int(aborted))
return TimeoutError("Provider close deadline")
def _provider_close_finished(self, task):
if not task.cancelled():
exc = task.result()
self._provider_closed = exc is None
if exc is not None:
diagnostic(self.session_id, "provider_close",
"CLEANUP_TIMEOUT" if isinstance(exc, TimeoutError) else "CLEANUP_FAILED",
exc=exc, code=self.failure)
def _failure_finished(self, task):
self.tasks.discard(task)
# Cancellation before the coroutine's first step cannot enter its finally.
self._ensure_provider_close()
async def _close_provider(self):
result = await asyncio.shield(self._ensure_provider_close())
if isinstance(result, Exception):
raise result
async def _finish_failure(self, writable):
try:
if writable and self.failure_error_pending:
try:
await asyncio.wait_for(self.error_delivered.wait(), self.settings.send_timeout_seconds)
except TimeoutError:
pass
if self.close_client:
await asyncio.wait_for(self.close_client(self.close_code), self.settings.send_timeout_seconds)
except Exception:
pass
finally:
# Client failure/timeout/cancellation cannot skip independent provider cleanup.
try:
await self._close_provider()
except Exception:
pass
def context_pending(self):
return any(r.interrupted and not r.terminal for r in self.responses.values()) or any(
a.state == "finalizing" for a in self.audio.values())
def cleanup_owner(self):
audio = next((a for a in self.audio.values() if a.state == "finalizing"), None)
if audio:
return audio.response.turn
response = next((r for r in self.responses.values() if r.interrupted and not r.terminal), None)
return response.turn if response else None
def sync_failed(self, reason, *, turn=None, phase="context_sync",
event_type=None, exc=None, audio=None, deadline=None):
if not self.usable:
return
state = dict(pending_commands=len(self.pending_commands),
pending_responses=sum(not r.terminal for r in self.responses.values()),
pending_audio=sum(a.state == "finalizing" for a in self.audio.values()),
input_bytes=self.input_forwarded_total - self.input_committed_total)
if audio is not None:
state.update(sent_bytes=audio.sent, played_ms=audio.played)
if deadline is not None:
state["deadline_remaining_ms"] = int((deadline - self.clock()) * 1000)
diagnostic(self.session_id, phase, reason, event_type=event_type,
exc=exc, code="LIVE_CONTEXT_SYNC_FAILED", **state)
self.fail("LIVE_CONTEXT_SYNC_FAILED", turn=turn)
def overflow(self, reason, *, turn=None, occupancy=0, limit=0, audio=None):
counts = {
"PROVIDER_CONTROL_CAPACITY": (self.command_count, self.settings.max_control_messages),
"PROVIDER_COMMAND_CAPACITY": (self.commands.qsize(), self.commands.maxsize),
"CLIENT_CONTROL_CAPACITY": (self.control_count, self.settings.max_control_messages),
"INPUT_TURN_CAPACITY": (len(self.inputs), self.settings.max_input_turns),
"RESPONSE_INTENT_CAPACITY": (self.intent_count, self.settings.max_intents),
"OUTPUT_IDENTITY_CAPACITY": (len(self.output_items), self.settings.max_refs),
"OUTPUT_REFERENCE_CAPACITY": (len(self.audio), self.settings.max_refs),
"PROVIDER_EVENT_CAPACITY": (len(self.events), self.settings.max_events),
"OUTPUT_SLAB_CAPACITY": (sum((len(a.data) + 9599) // 9600 for a in self.audio.values()), 512),
"TOOL_CALL_CAPACITY": (len(self.calls), self.max_calls),
}
occupancy_count, limit_count = counts.get(reason, (0, 0))
if reason in ("GEMINI_OUTPUT_SLAB_CAPACITY", "GEMINI_INPUT_MAPPING_CAPACITY",
"GEMINI_CONTROL_MESSAGE_CAPACITY"):
occupancy_count, limit_count = occupancy, limit
occupancy = limit = 0
if reason == "PROVIDER_CONTROL_CAPACITY":
occupancy, limit = self.command_bytes, self.settings.max_control_bytes
elif reason == "CLIENT_CONTROL_CAPACITY":
occupancy, limit = self.control_bytes, self.settings.max_control_bytes
phase = ("playback" if audio else "capture_transport" if reason == "CAPTURE_TRANSPORT_CAPACITY"
else "speaking" if any(t.start_position is not None and not t.stopped
for t in self.inputs.values())
else "awaiting_commit" if self.uncommitted_speech_bytes else "idle")
state = dict(occupancy_count=occupancy_count, limit_count=limit_count,
transport_limit_bytes=self.settings.max_queued_audio_bytes,
transport_limit_messages=self.settings.max_queued_audio_messages,
occupancy_bytes=occupancy, limit_bytes=limit,
transport_bytes=self.input_transport_bytes,
transport_messages=self.input_transport_count,
speech_bytes=self.uncommitted_speech_bytes)
if reason == "SPEECH_STOP_DEADLINE" and turn is not None:
state["elapsed_ms"] = int((self.clock() - turn.speech_deadline +
self.settings.speech_stop_timeout_seconds) * 1000)
if audio is not None:
state.update(sent_bytes=audio.sent, played_ms=audio.played,
elapsed_ms=int((self.clock() - audio.stall_deadline +
self.settings.playback_stall_timeout_seconds) * 1000))
diagnostic(self.session_id, phase, reason,
code='LIVE_BUFFER_OVERFLOW', **state)
self.fail('LIVE_BUFFER_OVERFLOW', turn=turn)
@property
def uncommitted_speech_bytes(self):
# A speech interval is lifecycle metadata, not retained provider PCM.
return sum(max(0, (t.stop_boundary if t.stopped else self.input_admitted_total)
- t.start_position * 48)
for t in self.inputs.values()
if t.start_position is not None and not t.committed)
def check_deadlines(self):
if not self.usable:
return False
now = self.clock()
if self.setup_deadline is not None and not self.provider_ready and now >= self.setup_deadline:
self.fail("LIVE_PROVIDER_UNAVAILABLE")
return False
if self.intent_deadline is not None and now >= self.intent_deadline:
self.sync_failed("RESPONSE_ACK_DEADLINE",
turn=self.pending_create[1] if self.pending_create else None,
deadline=self.intent_deadline)
return False
if self.uncommitted_speech_bytes > self.settings.max_input_buffer_bytes:
self.overflow('UNCOMMITTED_SPEECH_BYTES',
occupancy=self.uncommitted_speech_bytes, limit=self.settings.max_input_buffer_bytes)
return False
for turn in self.inputs.values():
if not turn.stopped and turn.speech_deadline is not None and now >= turn.speech_deadline:
self.overflow('SPEECH_STOP_DEADLINE', turn=turn,
occupancy=self.uncommitted_speech_bytes, limit=self.settings.max_input_buffer_bytes)
return False
if turn.input_deadline is not None and not turn.committed and now >= turn.input_deadline:
self.sync_failed("INPUT_COMMIT_DEADLINE", turn=turn, deadline=turn.input_deadline)
return False
for response in self.responses.values():
if response.cancel_deadline is not None and not response.terminal and now >= response.cancel_deadline:
self.sync_failed("CANCELLATION_ACK_DEADLINE", turn=response.turn, deadline=response.cancel_deadline)
return False
for audio in self.audio.values():
if audio.cleanup_deadline is not None and now >= audio.cleanup_deadline:
self.sync_failed("TRUNCATION_ACK_DEADLINE", turn=audio.response.turn, audio=audio, deadline=audio.cleanup_deadline)
return False
if self.eligible(audio) and audio.timer and now >= audio.stall_deadline:
self.overflow("PLAYBACK_PROGRESS_STALL", turn=audio.response.turn, audio=audio, occupancy=audio.sent - audio.played * 48, limit=self.settings.output_credit_window_bytes)
return False
for cmd in list(self.pending_commands.values()):
deadline = cmd.send_deadline if cmd.dispatched else cmd.queue_deadline
if deadline is not None and now >= deadline:
diagnostic(self.session_id, "provider_send",
"PROVIDER_COMMAND_SEND_DEADLINE" if cmd.dispatched else "PROVIDER_COMMAND_QUEUE_DEADLINE",
event_type=cmd.event["type"], code="LIVE_TRANSPORT_FAILED",
deadline_remaining_ms=int((deadline - now) * 1000),
pending_commands=len(self.pending_commands))
self.fail("LIVE_TRANSPORT_FAILED", turn=cmd.owner)
return False
if self.audio_send_deadline is not None and now >= self.audio_send_deadline:
diagnostic(self.session_id, "client_send", "CLIENT_AUDIO_SEND_DEADLINE",
code="LIVE_TRANSPORT_FAILED",
deadline_remaining_ms=int((self.audio_send_deadline - now) * 1000))
self.fail("LIVE_TRANSPORT_FAILED", turn=self.audio_send_owner, writable=False)
return False
if self.active_control and self.active_control.send_deadline is not None and now >= self.active_control.send_deadline:
diagnostic(self.session_id, "client_send", "CLIENT_CONTROL_SEND_DEADLINE",
event_type=self.active_control.event["type"], code="LIVE_TRANSPORT_FAILED",
deadline_remaining_ms=int((self.active_control.send_deadline - now) * 1000))
self.fail("LIVE_TRANSPORT_FAILED", writable=False)
return False
return True
def begin_dispatch(self, cmd):
if not cmd.accounted:
return False
if self.usable and not self.check_deadlines():
return False
cmd.dispatched = True
cmd.send_deadline = self.clock() + self.settings.send_timeout_seconds
event, now = cmd.event, self.clock()
kind = event["type"]
if kind == "session.update":
self.setup_deadline = now + self.settings.setup_timeout_seconds
elif kind == "response.create":
if not self.pending_create or event["response"]["metadata"]["voice_intent"] != self.pending_create[0]:
return False
self.intent_dispatched = True
self.intent_deadline = now + self.settings.response_ack_timeout_seconds
elif kind == "response.cancel":
response = self.responses.get(event["response_id"])
if response and response.terminal:
return False
if response:
response.cancel_deadline = now + self.settings.cancellation_timeout_seconds
elif kind == "conversation.item.truncate":
audio = next(a for a in self.audio.values() if a.cleanup == event["event_id"])
if audio.state == "retired":
return False
audio.cleanup_dispatched = True
audio.cleanup_deadline = now + self.settings.truncation_ack_timeout_seconds
elif kind == "conversation.item.create" and event["item"]["type"] == "message":
turn = self.inputs[event["item"]["id"]]
if turn is not self.current or turn.superseded:
return False
turn.diagnostic_dispatched = True
turn.input_deadline = now + self.settings.input_commit_timeout_seconds
if cmd.pcm is not None:
self.input_dispatched_total = max(self.input_dispatched_total, cmd.input_end)
return True
def retire(self, audio):
if not audio.retired_credit:
audio.retired_credit = True
audio.credit = 0
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")
if not await self.authorized():
return
self.command(self.adapter.setup())
delivery = asyncio.create_task(self._delivery())
delivery.add_done_callback(self._delivery_finished)
self._workers = [asyncio.create_task(self._sender()), delivery,
asyncio.create_task(self._ticker())]
def _delivery_finished(self, task):
if task.cancelled() and self.usable:
cleanup = asyncio.create_task(self._delivery_cancelled())
self.tasks.add(cleanup)
cleanup.add_done_callback(self.tasks.discard)
async def _delivery_cancelled(self):
async with self.lock:
self.fail("LIVE_TRANSPORT_FAILED", writable=False)
async def receive_loop(self):
try:
while self.usable:
await self.handle(await self.adapter.receive())
except asyncio.CancelledError:
raise
except (ProviderProtocolError, ValueError, TypeError, RecursionError) as exc:
diagnostic(self.session_id, "provider_receive", protocol_reason(exc), exc=exc)
async with self.lock:
if getattr(exc, "overflow", False):
self.overflow(getattr(exc, "reason", "PROVIDER_ADAPTER_CAPACITY"),
occupancy=getattr(exc, "occupancy", 0), limit=getattr(exc, "limit", 0))
elif getattr(exc, "context_sync", False):
self.sync_failed("ADAPTER_CONTEXT_UNSUPPORTED",
phase="provider_receive", exc=exc)
else:
self.fail("LIVE_PROVIDER_PROTOCOL_ERROR")
except Exception as exc:
async with self.lock:
if self.context_pending():
self.sync_failed("PROVIDER_TRANSPORT_LOST_DURING_SYNC",
phase="provider_receive", exc=exc, turn=self.cleanup_owner())
else:
self.fail("LIVE_PROVIDER_UNAVAILABLE")
async def _sender(self):
cmd = None
try:
while True:
cmd = await self.commands.get()
async with self.lock:
if not cmd.accounted:
continue
event, owner = cmd.event, cmd.owner
kind = event["type"]
if self.usable and not self.check_deadlines():
continue
if not self.usable and kind != "response.cancel":
self.release_command(cmd)
continue
if kind in ("response.create", "conversation.item.create") and owner:
if owner is not self.current or owner.superseded:
self.release_command(cmd)
if kind == "response.create":
self.pending_create, self.intent_deadline = None, None
await self.release()
continue
if kind in ("response.create", "conversation.item.create") and owner:
valid = await self.check_authority(owner)
failure = self.failure or "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(failure, turn=owner)
continue
if not self.check_deadlines() or owner is not self.current or owner.superseded:
self.release_command(cmd)
if self.usable and kind == "response.create":
self.pending_create, self.intent_deadline = None, None
await self.release()
continue
if kind == "response.create":
origin = self.origin_intents.get(event["response"]["metadata"]["voice_intent"])
if origin and not all(c["sent"] for c in self.responses[origin].calls.values()):
self.sync_failed("TOOL_CONTINUATION_OUTPUT_UNSENT", turn=owner, phase="provider_send", event_type=kind)
continue
async with self.lock:
if not self.begin_dispatch(cmd):
self.release_command(cmd)
continue
if cmd.pcm is None:
sending = self.adapter.send_serialized(cmd.wire)
else:
wire_event = dict(event)
wire_event["audio"] = base64.b64encode(cmd.pcm).decode("ascii")
sending = self.adapter.send(wire_event)
await asyncio.wait_for(sending, self.settings.send_timeout_seconds)
async with self.lock:
# A delayed send completion cannot convert an expired send into success.
timely = not self.usable or self.check_deadlines()
self.release_command(cmd)
if not timely or not self.usable:
continue
if cmd.pcm is not None:
self.input_forwarded_total = max(self.input_forwarded_total, cmd.input_end)
elif kind == "conversation.item.create" and event["item"]["type"] == "function_call_output":
self.calls[event["item"]["call_id"]][1]["sent"] = True
cmd = None
except asyncio.CancelledError:
raise
except Exception as exc:
async with self.lock:
if getattr(exc, "context_sync", False):
self.sync_failed("ADAPTER_CONTEXT_COMMAND_UNSUPPORTED",
phase="provider_send", event_type=cmd.event["type"] if cmd else None,
exc=exc, turn=cmd.owner if cmd else None)
else:
diagnostic(self.session_id, "provider_send", "PROVIDER_SEND_FAILED",
event_type=cmd.event["type"] if cmd else None, exc=exc,
code="LIVE_TRANSPORT_FAILED")
self.fail("LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None)
finally:
if cmd:
async with self.lock:
self.release_command(cmd)
def eligible(self, audio):
return (self.usable and audio.state in ("open", "sealed") and
audio.sent // 48 > audio.played)
def timer_update(self, audio, *, progress=False):
if not self.eligible(audio):
audio.timer, audio.stall_deadline = None, None
elif audio.timer is None or progress:
audio.timer, audio.stall_deadline = identity(), self.clock() + self.settings.playback_stall_timeout_seconds
async def stall_callback(self, ref, timer):
async with self.lock:
audio = self.audio[ref]
if (self.eligible(audio) and audio.timer == timer and
self.clock() >= audio.stall_deadline):
self.overflow("PLAYBACK_PROGRESS_STALL", turn=audio.response.turn, audio=audio, occupancy=audio.sent - audio.played * 48, limit=self.settings.output_credit_window_bytes)
async def _ticker(self):
while True:
await asyncio.sleep(.02)
await self.tick()
async def tick(self):
async with self.lock:
if not self.check_deadlines():
return
await self.maintain()
await self.release()
async def diagnostic_text(self, text):
if not isinstance(text, str) or not text.strip() or len(text) > 2000:
raise ValueError("Bounded diagnostic text required")
async with self.lock:
if not self.ready or not self.usable:
raise RuntimeError("Session not ready")
if not self.check_deadlines():
raise RuntimeError("Session expired")
item = "operator_" + identity()
await self.new_turn(item)
self.current.stopped = True
self.current.diagnostic = text
self.command(dict(type="conversation.item.create", item=dict(
id=item, type="message", role="user",
content=[dict(type="input_text", text=text)])))
return self.current.ref
@property
def input_buffer_bytes(self):
# Absolute uncommitted stream prefix; not memory occupancy or speech.
return 0 if self.input_released else self.input_admitted_total - self.input_committed_total
@property
def forwarded_buffer_bytes(self):
return 0 if self.input_released else max(0, self.input_forwarded_total - self.input_committed_total)
async def input_audio(self, pcm):
async with self.lock:
if not self.usable:
return
if not self.ready:
self.fail("LIVE_NOT_READY")
elif not isinstance(pcm, bytes) or not pcm or len(pcm) % 2:
self.fail("LIVE_PROTOCOL_ERROR")
elif len(pcm) > self.settings.max_binary_message_bytes:
self.fail("LIVE_FRAME_TOO_LARGE")
elif not self.check_deadlines():
return
elif (self.input_transport_bytes + len(pcm) > self.settings.max_queued_audio_bytes or
self.input_transport_count + 1 > self.settings.max_queued_audio_messages):
self.overflow("CAPTURE_TRANSPORT_CAPACITY",
occupancy=self.input_transport_bytes + len(pcm),
limit=self.settings.max_queued_audio_bytes)
elif (self.uncommitted_speech_bytes + len(pcm) * sum(
t.start_position is not None and not t.stopped and not t.committed
for t in self.inputs.values()) > self.settings.max_input_buffer_bytes):
self.overflow("UNCOMMITTED_SPEECH_BYTES",
occupancy=self.uncommitted_speech_bytes + len(pcm),
limit=self.settings.max_input_buffer_bytes)
else:
self.input_transport_bytes += len(pcm)
self.input_transport_count += 1
self.input_admitted_total += len(pcm)
self.command(dict(type="input_audio_buffer.append"), pcm=pcm,
input_end=self.input_admitted_total)
def acknowledge_input(self, turn):
turn.commit_ack = True
if turn.stop_boundary is not None:
turn.committed = True
turn.input_deadline = None
# Old/duplicate commitment only releases its own known stream prefix.
self.input_committed_total = max(self.input_committed_total, turn.stop_boundary)
def normal(self, turn):
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 in ("completed", "waiting_tools") or r.limited)
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
and not a.data and not a.reserved) or (
a.state == "finalizing" and not a.response.interrupted and a.frozen and
a.generated == a.sent and a.played == a.sent // 48 and
not a.data and not a.reserved)
for a in self.audio.values() if a.response.turn is turn))
async def new_turn(self, item):
if item in self.inputs:
return self.inputs[item]
if len(self.inputs) >= self.settings.max_input_turns:
self.overflow("INPUT_TURN_CAPACITY")
return
old = self.current
if old and not self.normal(old):
old.superseded = True
old.cancelled.set()
affected = [r for r in self.responses.values() if r.turn is old]
for response in affected:
response.interrupted = True
self.discard_pending_transcript(response)
if response.final_deadline is None:
has_audio = any(a.response is response and a.state != "retired"
for a in self.audio.values())
response.final_deadline = self.clock() + (self.settings.final_progress_window_ms / 1000 if has_audio else 0)
for audio in self.audio.values():
if audio.response is response and audio.state != "retired":
audio.state, audio.timer, audio.stall_deadline = "finalizing", None, None
audio.data.clear()
if not response.terminal and not response.cancel_event:
response.cancel_event = identity()
self.command(dict(type="response.cancel", response_id=response.id,
event_id=response.cancel_event))
if any(r.visible for r in affected):
self.control(dict(type="turn_interrupted", turn_ref=old.ref,
cancelled_tool_call_ids=[
r.calls[c]["ref"] for r in affected for c in r.calls]))
self.token += 1
turn = Turn("live-turn-" + str(self.token), self.token, item,
SearchExecution(self.user_id))
self.inputs[item] = self.current = turn
self.control(dict(type="user_speech_started", turn_ref=turn.ref))
return turn
def barrier(self):
return (self.pending_create is not None or
any(not r.terminal for r in self.responses.values()) or
any(a.state == "finalizing" or a.reserved for a in self.audio.values()) or
any(r.interrupted and (not r.terminal or
self.clock() < r.final_deadline) for r in self.responses.values()))
async def release(self):
turn = self.current
if not self.check_deadlines():
return
if (not self.usable or not self.ready or turn is None or turn.superseded
or not turn.stopped or not turn.committed or self.barrier()):
return
needed = not turn.initial or any(
response.turn is turn and response.calls and not response.continued and
response.terminal and all(c["result"] is not None for c in response.calls.values())
for response in self.responses.values())
if needed and self._release_check is None:
task = asyncio.create_task(self._authorize_release(turn))
self._release_check = task
self.tasks.add(task)
task.add_done_callback(self.tasks.discard)
async def _authorize_release(self, turn):
valid = await self.check_authority(turn)
async with self.lock:
self._release_check = None
if not self.check_deadlines():
return
if not valid:
return
if turn is not self.current or turn.token != self.token:
await self.release()
return
if (not self.ready or turn.superseded or not turn.stopped or
not turn.committed or self.barrier()):
return
await self._release_authorized(turn)
async def _release_authorized(self, turn):
if not turn.initial:
turn.initial = True
await self.create_response(turn)
return
for response in self.responses.values():
if response.turn is not turn or response.continued or not response.calls:
continue
if not response.terminal or any(c["result"] is None for c in response.calls.values()):
continue
if response.status not in ("completed", "waiting_tools"):
self.fail("LIVE_PROVIDER_UNAVAILABLE")
return
for call_id, call in response.calls.items():
if not call["output_queued"]:
call["output_queued"] = True
self.command(dict(type="conversation.item.create",
item=dict(type="function_call_output", call_id=call_id,
output=canonical_json(call["result"]))))
raw_sources = call["result"].get("sources", [])
sources = []
for index, s in enumerate(raw_sources):
item = {k: v for k, v in s.items() if k != "text"}
full_text = s.get("text", "")
item["excerpt"] = full_text[:2000] if len(full_text) > 2000 else full_text
item["is_primary"] = (index == 0)
sources.append(item)
primary_source = sources[0] if sources else None
response.visible = True
self.control(dict(type="sources", turn_ref=turn.ref,
tool_call_id=call["ref"], sources=sources,
primary_source=primary_source))
if call["result"]["status"] == "error":
self.control(dict(type="error", turn_ref=turn.ref,
error=call["result"]["error"]))
response.continued = True
await self.create_response(turn, origin=response)
return
async def create_response(self, turn, *, origin=None):
if self.intent_count >= self.settings.max_intents:
self.overflow("RESPONSE_INTENT_CAPACITY")
return
self.intent_count += 1
intent = identity()
turn.intent = intent
self.pending_create = (intent, turn)
self.intent_dispatched = False
self.origin_intents[intent] = origin.id if origin else None
self.command(dict(type="response.create",
response=dict(metadata=dict(voice_intent=intent))))
async def maintain(self):
for audio in self.audio.values():
response = audio.response
if audio.state == "retired":
continue
if response.interrupted:
if self.clock() < response.final_deadline:
continue
audio.frozen = True
if not response.terminal or audio.reserved:
continue
elif (response.terminal and audio.done and audio.ended and
not audio.data and not audio.reserved and audio.played == audio.sent // 48):
if audio.generated == audio.sent == 48 * audio.played:
self.retire(audio)
continue
audio.state, audio.timer, audio.stall_deadline = "finalizing", None, None
audio.frozen = True
else:
continue
if audio.cleanup is None:
if audio.generated == audio.sent == 48 * audio.played:
self.retire(audio)
continue
audio.cleanup = identity()
self.command(dict(type="conversation.item.truncate", event_id=audio.cleanup,
item_id=audio.item, content_index=audio.index, audio_end_ms=audio.played))
async def client_control(self, raw):
async with self.lock:
if not self.usable:
return
if not self.ready:
self.fail("LIVE_NOT_READY")
return
if isinstance(raw, bytes) and len(raw) > self.settings.max_client_control_bytes:
self.fail("LIVE_FRAME_TOO_LARGE")
return
if not self.check_deadlines():
return
try:
if not isinstance(raw, bytes):
raise ValueError("Raw control bytes required")
control = strict_json(raw.decode("utf-8"))
if (not isinstance(control, dict) or set(control) != {"type", "audio_ref", "played_ms"}
or control["type"] != "playback_progress"
or not isinstance(control["audio_ref"], str)
or not 1 <= len(control["audio_ref"]) <= 128
or not control["audio_ref"].isascii()):
raise ValueError("Control schema")
except (ValueError, UnicodeError, RecursionError):
self.fail("LIVE_PROTOCOL_ERROR")
return
await self.playback_progress(control["audio_ref"], control["played_ms"])
async def playback_progress(self, ref, played):
async with self.lock:
if not self.check_deadlines():
return
audio = self.audio.get(ref)
if (audio is None or type(played) is not int or played < audio.played
or played > audio.sent // 48):
self.fail("LIVE_PROTOCOL_ERROR")
return
if audio.frozen or audio.state == "retired" or (
audio.state == "finalizing" and
self.clock() >= audio.response.final_deadline):
if played != audio.played:
self.fail("LIVE_PROTOCOL_ERROR")
return
delta = played - audio.played
audio.played = played
audio.credit -= 48 * delta
self.timer_update(audio, progress=delta > 0)
await self.maintain()
await self.release()
self.wake.set()
async def _delivery(self):
entry, audio, chunk, owner = None, None, None, None
try:
while True:
await self.wake.wait()
self.wake.clear()
while True:
audio, chunk, entry = None, None, None
async with self.lock:
if self.usable and not self.check_deadlines():
continue
if self.controls:
entry = self.controls.popleft()
self.active_control = entry
elif self.usable:
total = sum(a.credit + a.reserved for a in self.audio.values())
for a in self.audio.values():
if a.state != "open":
continue
if not a.started and (a.data or (
a.done and a.response.terminal and (a.response.status == "completed" or a.response.limited))):
a.started = True
self.control(dict(type="audio_started", turn_ref=a.response.turn.ref,
audio_ref=a.ref), response=a.response)
break
if a.data and total < self.settings.output_credit_window_bytes:
size = min(len(a.data), self.settings.max_binary_message_bytes,
self.settings.output_credit_window_bytes - total)
size -= size % 2
if size:
audio, chunk = a, bytes(a.data[:size])
del a.data[:size]
a.reserved += size
break
if a.done and not a.data and not a.reserved and a.started:
a.state = "sealed"
self.control(dict(type="audio_ended", turn_ref=a.response.turn.ref,
audio_ref=a.ref, sent_bytes=a.sent), response=a.response)
break
if not a.done or a.data or a.reserved:
break
if entry is None and chunk is None:
if self.controls:
continue
break
event = entry.event if entry else None
owner = audio.response.turn if audio else next(
(t for t in self.inputs.values() if event and t.ref == event.get("turn_ref")), None)
if owner and (audio or event["type"] in ("sources", "transcript", "audio_started", "audio_ended")):
valid = await self.check_authority(owner)
async with self.lock:
if self.usable:
self.check_deadlines()
suppressed = (not self.usable or
(owner.superseded and (audio or event.get("role") != "user")) or
(audio and audio.state != "open"))
if suppressed:
if audio:
audio.reserved -= len(chunk)
audio, chunk = None, None
if entry:
self.release_control(entry)
self.active_control = None
entry = None
await self.maintain()
await self.release()
continue
async with self.lock:
if entry:
entry.send_deadline = self.clock() + self.settings.send_timeout_seconds
elif audio:
# Send reservation has an independent timeout from playback timers.
self.audio_send_deadline = self.clock() + self.settings.send_timeout_seconds
self.audio_send_owner = audio.response.turn
try:
await asyncio.wait_for(self.emit(event if entry else chunk),
self.settings.send_timeout_seconds)
except BaseException:
if audio:
async with self.lock:
audio.reserved -= len(chunk)
self.audio_send_deadline = None
audio, chunk = None, None
raise
async with self.lock:
if self.usable:
self.check_deadlines()
if audio:
audio.reserved -= len(chunk)
self.audio_send_deadline = None
# Uncertain/expired completion is never counted as a successful send.
if self.usable:
audio.sent += len(chunk)
if not audio.retired_credit:
audio.credit += len(chunk)
self.timer_update(audio)
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
not entry.response.interrupted and not entry.response.turn.superseded):
entry.response.transcript_delivered = True
if event["type"] == "error" and not self.usable:
self.error_delivered.set()
self.release_control(entry)
self.active_control = None
entry, audio, chunk = None, None, None
await self.maintain()
await self.release()
except asyncio.CancelledError:
async with self.lock:
self.fail("LIVE_TRANSPORT_FAILED", turn=owner, writable=False)
raise
except Exception as exc:
async with self.lock:
self.fail(getattr(exc, "live_code", "LIVE_TRANSPORT_FAILED"), turn=owner, writable=False)
finally:
async with self.lock:
if entry:
self.release_control(entry)
self.active_control = None
if audio:
audio.reserved -= len(chunk)
self.audio_send_deadline = None
def correlated_response(self, event):
response = self.responses.get(event.get("response_id"))
if response is None:
raise ValueError("Unknown response")
return response
def bind_output_item(self, item, response):
provider_identifier(item)
previous = self.output_items.get(item)
if previous is not None and previous is not response:
raise ValueError("Output item rebound")
if previous is None:
if len(self.output_items) >= self.settings.max_refs:
self.overflow("OUTPUT_IDENTITY_CAPACITY")
raise ValueError("Output identity capacity")
self.output_items[item] = response
def bind_function_item(self, item_id, call_id, response):
provider_identifier(call_id)
provider_identifier(item_id)
previous = self.function_items.get(item_id)
if previous is not None and previous != call_id:
raise ValueError("Function item rebound to another call")
if any(item != item_id and bound == call_id for item, bound in self.function_items.items()):
raise ValueError("Call rebound to another function item")
self.bind_output_item(item_id, response)
if self.item_types.get(item_id, "function_call") != "function_call":
raise ValueError("Function item type rebound")
self.item_types[item_id] = "function_call"
self.function_items[item_id] = call_id
def part(self, event):
response = self.correlated_response(event)
item, index = event["item_id"], event["content_index"]
self.output_position(event, response)
if self.item_types.get(item, "message") != "message":
raise ValueError("Audio item type")
self.item_types[item] = "message"
if type(index) is not int or index != 0:
raise ValueError("Unsupported audio layout")
key = (response.id, item, index)
if key not in self.parts:
if len(self.audio) >= self.settings.max_refs or sum(a.state != "retired" for a in self.audio.values()) >= self.settings.max_unretired_refs:
self.overflow("OUTPUT_REFERENCE_CAPACITY")
raise ValueError("Reference capacity")
audio = Audio("live-audio-" + identity(), response, item, index)
if response.interrupted:
audio.state = "finalizing"
self.parts[key] = audio
self.audio[audio.ref] = audio
return self.parts[key]
def output_position(self, event, response, *, terminal=False):
item, position = event["item_id"], event["output_index"]
if type(position) is not int or not 0 <= position < self.settings.max_refs:
raise ValueError("Output position")
if terminal and item not in self.output_items:
raise ValueError("Unknown terminal output item")
self.bind_output_item(item, response)
key = (response.id, position)
if key in self.output_positions and self.output_positions[key] != item:
raise ValueError("Output position rebound")
if any(rid == response.id and old_item == item and old_pos != position
for (rid, old_pos), old_item in self.output_positions.items()):
raise ValueError("Output item position rebound")
self.output_positions[key] = item
def text_payload(self, event, field):
text = event[field]
if not isinstance(text, str):
raise ValueError("Transcript string required")
json_size(text, self.settings.max_provider_message_bytes)
return text
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
try:
if not isinstance(event, dict):
raise ValueError("Provider object required")
item_turn = self.inputs.get(event.get("item_id")) if isinstance(event.get("item_id"), str) else None
rid = event.get("response_id")
if isinstance(event.get("response"), dict):
rid = event["response"].get("id")
owning_response = self.responses.get(rid) if isinstance(rid, str) else None
affected = item_turn or (owning_response.turn if owning_response else None)
digest = provider_event_digest(event, self.settings.max_provider_message_bytes)
for field_name in ("event_id", "item_id", "response_id", "call_id"):
value = event.get(field_name)
if value is not None:
provider_identifier(value)
event_id = event.get("event_id")
if event_id:
if event_id in self.events:
if self.events[event_id] != digest:
raise ValueError("Conflicting event replay")
return
if len(self.events) >= self.settings.max_events:
self.overflow("PROVIDER_EVENT_CAPACITY")
return
self.events[event_id] = digest
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":
if self.setup_deadline is None or not self.adapter.acknowledged(event["session"]):
if not self.provider_ready or not self.adapter.acknowledged(event["session"]):
raise ValueError("Unacknowledged setup")
if not self.provider_ready:
self.provider_ready = True
self.setup_deadline = None
self.control(dict(type="session_ready", session_id=self.session_id,
input_audio=dict(encoding="pcm_s16le", sample_rate=24000, channels=1),
output_audio=dict(encoding="pcm_s16le", sample_rate=24000, channels=1)))
elif kind == "input_audio_buffer.speech_started":
item, start = event["item_id"], event["audio_start_ms"]
if item not in self.inputs:
if type(start) is not int or start < 0 or start <= self.last_start or start * 48 > self.input_dispatched_total:
raise ValueError("Input ordering")
self.last_start = start
await self.new_turn(item)
if not self.usable:
return
self.current.start_position = start
self.current.speech_deadline = self.clock() + self.settings.speech_stop_timeout_seconds
if not self.check_deadlines():
return
elif self.inputs[item].start_position != start:
raise ValueError("Conflicting input start")
elif kind == "input_audio_buffer.speech_stopped":
turn, end = self.inputs[event["item_id"]], event["audio_end_ms"]
if (type(end) is not int or end <= turn.start_position or
end * 48 > self.input_dispatched_total):
raise ValueError("Input stop boundary")
if turn.stop_boundary is not None and turn.stop_boundary != end * 48:
raise ValueError("Conflicting input stop")
if not turn.stopped:
turn.stopped = True
turn.speech_deadline = None
turn.stop_boundary = end * 48
turn.input_deadline = self.clock() + self.settings.input_commit_timeout_seconds
if turn.commit_ack:
self.acknowledge_input(turn)
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", "provider.input_consumed_text"):
item = event["item"]
turn = self.inputs.get(item["id"])
if turn and turn.diagnostic is not None:
if (not turn.diagnostic_dispatched or item.get("role") != "user" or
item.get("type") != "message" or
item.get("content") != [dict(type="input_text", text=turn.diagnostic)]):
raise ValueError("Diagnostic item confirmation mismatch")
turn.committed = True
turn.input_deadline = None
elif kind == "response.created":
wire = event["response"]
provider_identifier(wire["id"])
if wire["id"] not in self.responses:
intent = wire.get("metadata", {}).get("voice_intent")
if (self.pending_create is None or not self.intent_dispatched
or intent != self.pending_create[0]):
self.command(dict(type="response.cancel", response_id=wire["id"]))
raise ValueError("Unsolicited response")
_, turn = self.pending_create
response = Response(wire["id"], turn, creation_intent=intent,
parent_response=self.origin_intents[intent])
self.responses[response.id] = response
self.pending_create, self.intent_deadline = None, None
self.intent_dispatched = False
if turn.superseded:
response.interrupted = True
response.final_deadline = self.clock() + self.settings.final_progress_window_ms / 1000
response.cancel_event = identity()
self.command(dict(type="response.cancel", response_id=response.id,
event_id=response.cancel_event))
elif self.responses[wire["id"]].creation_intent != wire.get("metadata", {}).get("voice_intent"):
raise ValueError("Response creation identity conflict")
elif kind in ("response.output_item.added", "response.output_item.done"):
response, item = self.correlated_response(event), event["item"]
if hasattr(self.adapter, "normalize_output_item"):
item = self.adapter.normalize_output_item(item)
item_type = item["type"]
if item_type not in ("message", "function_call"):
raise ValueError("Unsupported output item")
self.output_position(dict(item_id=item["id"], output_index=event["output_index"]),
response, terminal=response.terminal)
if self.item_types.get(item["id"], item_type) != item_type:
raise ValueError("Output type rebound")
self.item_types[item["id"]] = item_type
if item_type == "function_call":
self.bind_function_item(item["id"], item["call_id"], response)
if item_type == "message":
content = item["content"]
if (item.get("role") != "assistant" or not isinstance(content, list)
or len(content) > 1 or
(content and content[0]["type"] != "audio")):
raise ValueError("Unsupported output layout")
elif kind in ("response.done", "provider.tools_requested"):
wire = event["response"]
if (not isinstance(wire, dict) or not isinstance(wire.get("output"), list)
or any(not isinstance(item, dict) for item in wire["output"])):
raise ValueError("Malformed terminal output")
if wire["status"] == "waiting_tools" and kind != "provider.tools_requested":
raise ValueError("Invalid native tool phase")
response = self.responses[wire["id"]]
# Semantic terminal replay ignores only the outer event ID.
terminal_digest = provider_event_digest(dict(type=kind, response=wire), self.settings.max_provider_message_bytes)
if response.terminal:
if response.terminal_digest != terminal_digest:
raise ValueError("Conflicting terminal")
return
limited = bool(getattr(self.adapter, "token_limited", lambda _: False)(wire))
if wire["status"] not in ("completed", "cancelled", "waiting_tools") and not limited:
self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn)
return
# Unfinished tool context cannot safely be reused; fail before execution.
if limited and (response.calls or any(
item.get("type") != "message" for item in wire["output"])):
self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn)
return
terminal_calls = set()
terminal_items = {item["id"] for item in wire["output"]}
if len(terminal_items) != len(wire["output"]):
raise ValueError("Repeated terminal item")
if not {item for item, owner in self.output_items.items() if owner is response} <= terminal_items:
raise ValueError("Terminal output-item set mismatch")
# Validate the complete identity set before scheduling any terminal-discovered call.
for item in wire["output"]:
if item["type"] == "function_call":
if (wire["status"] in ("completed", "waiting_tools")
and item.get("status", "completed") != "completed"):
raise ValueError("Incomplete terminal tool")
self.bind_function_item(item["id"], item["call_id"], response)
if item["call_id"] in terminal_calls:
raise ValueError("Repeated terminal call")
terminal_calls.add(item["call_id"])
for position, item in enumerate(wire["output"]):
if hasattr(self.adapter, "normalize_output_item"):
item = self.adapter.normalize_output_item(item)
self.output_position(dict(item_id=item["id"], output_index=position), response)
item_type = item["type"]
old_type = self.item_types.get(item["id"])
if old_type is not None and old_type != item_type:
raise ValueError("Output type rebound")
self.item_types[item["id"]] = item_type
if item_type == "message":
content = item["content"]
if (item.get("role") != "assistant" or not isinstance(content, list)
or len(content) != 1 or content[0]["type"] != "audio"):
raise ValueError("Unsupported output layout")
elif item_type == "function_call":
await self.dispatch(response, item["call_id"], item["name"], item["arguments"], item["id"], execute=False)
else:
raise ValueError("Unsupported output type")
if terminal_calls != set(response.calls):
raise ValueError("Terminal call-set mismatch")
if limited and any(not a.done for a in self.audio.values() if a.response is response):
raise ValueError("Limited response before audio completion")
if wire["status"] in ("completed", "waiting_tools"):
for item in wire["output"]:
if item["type"] == "function_call":
await self.dispatch(response, item["call_id"], item["name"], item["arguments"], item["id"], execute=True)
response.terminal, response.status = True, wire["status"]
response.limited, response.terminal_digest = limited, terminal_digest
if limited and not response.interrupted and not response.turn.superseded:
self.control(dict(type="answer_limited", turn_ref=response.turn.ref,
reason="output_token_limit"), response=response)
if response.pending_transcript is not None:
pending = response.pending_transcript
self.discard_pending_transcript(response)
self.assistant_transcript(response, pending.event, completed=True)
self.wake.set()
if wire["status"] == "cancelled" and not response.interrupted:
raise ValueError("Unexpected cancellation")
elif kind == "response.function_call_arguments.done":
response = self.correlated_response(event)
await self.dispatch(response, event["call_id"], event["name"], event["arguments"], event["item_id"],
execute=not getattr(self.adapter, "defer_tool_execution", False))
elif kind in ("response.output_audio.delta", "response.output_audio.done"):
response = self.correlated_response(event)
if response.terminal:
known = self.parts.get((response.id, event["item_id"], event["content_index"]))
if (kind.endswith(".done") and known and known.done
and type(event["content_index"]) is int):
self.output_position(event, response, terminal=True)
return
raise ValueError("Audio after terminal generation")
audio = self.part(event)
if kind.endswith(".delta"):
encoded = event["delta"]
if not isinstance(encoded, str) or len(encoded) > self.settings.max_provider_message_bytes:
raise ValueError("Audio scratch bound")
estimate = len(encoded) // 4 * 3 - (len(encoded) - len(encoded.rstrip("=")))
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 + getattr(self.adapter, "_audio_bytes", 0) > self.settings.max_output_backlog_bytes:
self.overflow("OUTPUT_BACKLOG_CAPACITY", turn=response.turn, occupancy=backlog + estimate + getattr(self.adapter, "_audio_bytes", 0), limit=self.settings.max_output_backlog_bytes)
return
decoded = base64.b64decode(encoded, validate=True)
if len(decoded) != estimate:
raise ValueError("Base64 size")
audio.generated += len(decoded)
if decoded:
audio.response.visible = True
if not audio.response.interrupted:
if audio.done or audio.state != "open":
raise ValueError("Late audio")
audio.data.extend(decoded)
if sum((len(a.data) + 9599) // 9600 for a in self.audio.values()) > 512:
self.overflow("OUTPUT_SLAB_CAPACITY", turn=response.turn)
else:
audio.done = True
self.wake.set()
elif kind.startswith("conversation.item.input_audio_transcription."):
if kind not in ("conversation.item.input_audio_transcription.delta",
"conversation.item.input_audio_transcription.completed",
"conversation.item.input_audio_transcription.failed"):
raise ValueError("Unknown input transcription event")
turn = self.inputs[event["item_id"]]
if type(event["content_index"]) is not int or event["content_index"] != 0:
raise ValueError("Input transcript layout")
if kind.endswith(("completed", "delta")):
field = "transcript" if kind.endswith("completed") else "delta"
text = self.text_payload(event, field)
if kind.endswith("completed"):
index = event["content_index"]
fingerprint = hashlib.sha256(text.encode("utf-8")).digest()
if index in turn.transcript_parts:
if turn.transcript_parts[index] != fingerprint:
raise ValueError("Conflicting completed input transcript")
return
# Only index zero is supported: one fixed-size completion
# per retained input mapping, bounded by max_input_turns.
turn.transcript_parts[index] = fingerprint
elif event['content_index'] in turn.transcript_parts:
raise ValueError('Input transcript delta after completion')
self.control(dict(type="transcript", turn_ref=turn.ref, role="user",
text=text, status="completed" if kind.endswith("completed") else "partial"))
elif kind.endswith("failed"):
self.control(dict(type="error", turn_ref=turn.ref, error=dict(
code="LIVE_TRANSCRIPTION_FAILED", message="Input transcription unavailable.",
request_id=self.session_id, retryable=False)))
elif kind in ("response.output_audio_transcript.delta",
"response.output_audio_transcript.done"):
response = self.correlated_response(event)
self.output_position(event, response, terminal=response.terminal)
item = event["item_id"]
if (type(event["content_index"]) is not int or event["content_index"] != 0
or self.item_types.get(item, "message") != "message"):
raise ValueError("Assistant transcript layout")
self.item_types[item] = "message"
completed = kind.endswith("done")
text = self.text_payload(event, "transcript" if completed else "delta")
key = (item, event["content_index"])
if completed:
fingerprint = hashlib.sha256(text.encode()).digest()
if key in response.transcript_parts:
if response.transcript_parts[key] != fingerprint:
raise ValueError("Conflicting completed transcript")
return
response.transcript_parts[key] = fingerprint
elif key in response.transcript_parts:
raise ValueError("Transcript delta after completion")
transcript = dict(type="transcript", turn_ref=response.turn.ref, role="assistant", text=text)
if completed and not response.terminal and getattr(self.adapter, "defer_tool_execution", False):
if not response.interrupted and not response.turn.superseded:
entry = self.control(dict(transcript, status="completed"), response=response)
if entry is not None:
self.controls.pop()
response.pending_transcript = entry
else:
self.assistant_transcript(response, transcript, completed=completed)
elif kind == "conversation.item.truncated":
matches = [a for a in self.audio.values() if a.cleanup_dispatched
and a.item == event["item_id"] and a.index == event["content_index"]]
if (len(matches) != 1 or type(event["content_index"]) is not int
or type(event["audio_end_ms"]) is not int
or event["audio_end_ms"] != matches[0].played):
self.sync_failed("TRUNCATION_ACK_IDENTITY_MISMATCH" if len(matches) != 1
or type(event["content_index"]) is not int
else "TRUNCATION_ACK_POSITION_MISMATCH", phase="provider_handle",
event_type=kind, audio=matches[0] if len(matches) == 1 else None)
return
audio = matches[0]
audio.cleanup_deadline = None
self.retire(audio)
self.wake.set()
elif kind == "error":
error = event["error"]
if not isinstance(error, dict):
raise ValueError("Provider error object required")
matches = [r for r in self.responses.values()
if r.cancel_deadline is not None and r.cancel_event == error.get("event_id")]
cleanup = next((a for a in self.audio.values()
if a.cleanup_dispatched and a.cleanup == error.get("event_id")), None)
if len(matches) == 1:
if not self.adapter.is_no_active(error):
diagnostic(self.session_id, "provider_handle", "CANCELLATION_ERROR_SIGNATURE",
event_type=kind,
cancellation_type_match=int(error.get("type") == "invalid_request_error"),
cancellation_code_match=int(error.get("code") == "response_cancel_not_active"),
cancellation_param_match=int(error.get("param") is None),
cancellation_profile_2_1_shimmer=int(
getattr(self.adapter, "model", None) == "gpt-realtime-2.1"
and getattr(self.adapter, "voice", None) == "shimmer"))
self.sync_failed("CANCELLATION_PROVIDER_ERROR", turn=matches[0].turn, phase="provider_handle", event_type=kind)
elif cleanup:
self.sync_failed("TRUNCATION_PROVIDER_ERROR", turn=cleanup.response.turn, phase="provider_handle", event_type=kind, audio=cleanup)
else:
if self.context_pending():
self.sync_failed("UNRELATED_PROVIDER_ERROR_DURING_SYNC",
phase="provider_handle", event_type=kind, turn=self.cleanup_owner())
else:
self.fail("LIVE_PROVIDER_UNAVAILABLE")
await self.maintain()
await self.release()
except (KeyError, TypeError, ValueError, UnicodeError, RecursionError) as exc:
diagnostic(self.session_id, "provider_handle", protocol_reason(exc),
event_type=event.get("type") if isinstance(event, dict) else None,
exc=exc, code="LIVE_PROVIDER_PROTOCOL_ERROR")
self.fail("LIVE_PROVIDER_PROTOCOL_ERROR", turn=affected)
def discard_pending_transcript(self, response):
if response.pending_transcript is not None:
self.release_control(response.pending_transcript)
response.pending_transcript = None
def assistant_transcript(self, response, event, *, completed):
if (response.interrupted or response.turn.superseded or
(response.turn is not self.current and not (response.status == "completed" or response.limited))):
return
response.visible = True
status = ("limited" if response.limited else "completed") if completed else "partial"
entry = self.control(dict(event, status=status), response=response, completed_transcript=completed)
if entry and completed:
response.transcript_completed = True
async def dispatch(self, response, call_id, name, raw, item_id, *, execute=True):
self.bind_function_item(item_id, call_id, response)
rejected_digest = argument_digest(raw)
try:
parsed = strict_json(raw)
# Check every key/value, including extra fields rejected by the schema.
json_size(parsed, self.settings.max_provider_message_bytes)
parsed = SearchInput.model_validate(parsed).model_dump()
encoded_args = canonical_json(parsed)
fingerprint = hashlib.sha256((name + "\0" + encoded_args).encode("utf-8")).hexdigest()
except (ValueError, UnicodeError):
parsed = None
fingerprint = hashlib.sha256(
name.encode("utf-8") + b"\0rejected\0" + rejected_digest).hexdigest()
if call_id in self.calls:
old_response, old = self.calls[call_id]
if old_response is not response or old["hash"] != fingerprint or old["item"] != item_id:
raise ValueError("Forged/rebound call")
call = old
if not execute or call["scheduled"] or call["result"] is not None:
return
else:
if response.continued or response.terminal:
raise ValueError("Late unknown tool")
if len(self.calls) >= self.max_calls:
self.overflow("TOOL_CALL_CAPACITY")
return
call = dict(hash=fingerprint, result=None, sent=False, output_queued=False,
scheduled=False, name=name, raw=raw, item=item_id, ref=str(uuid4()))
self.calls[call_id] = (response, call)
response.calls[call_id] = call
if not execute and parsed is not None and name == "search_knowledge":
return
call["scheduled"] = True
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)
try:
if name != "search_knowledge":
raise ValueError("Unknown function")
args = SearchInput.model_validate(parsed).model_dump()
except (ValueError, ValidationError):
call["result"] = self.runner.error(ctx, "INVALID_TOOL_ARGUMENTS",
"Only query and optional context are accepted")
return
task = asyncio.create_task(self._search(response, call, ctx, args))
self.tasks.add(task)
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:
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 as exc:
from app.modules.voice.durable_tools import failure_code
async with self.lock:
# DurableTools has already persisted TOOL_CANCELLED. Only trusted
# supersession of this search's old turn makes it nonterminal.
if (type(exc) is ValueError and str(exc) == "CANCELLED"
and self.responses.get(response.id) is response
and ctx.execution is response.turn.execution
and ctx.cancelled is response.turn.cancelled
and ctx.cancelled.is_set() and response.interrupted
and response.turn.superseded and response.turn is not self.current):
return
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 response.turn is self.current and not ctx.cancelled.is_set()):
call["result"] = result
await self.release()
async def close(self):
# All concurrent waiters share worker cancellation and provider ownership.
# Route cancellation must not cancel the shared shutdown.
if self._close_task is None:
self._close_task = asyncio.create_task(self._close())
result = await asyncio.shield(self._close_task)
if isinstance(result, Exception):
raise result
async def _close(self):
async with self.lock:
self.usable = False
for turn in self.inputs.values():
turn.cancelled.set()
for cmd in list(self.pending_commands.values()):
self.release_command(cmd)
while not self.commands.empty():
self.commands.get_nowait()
while self.controls:
self.release_control(self.controls.popleft())
self.input_released = True
for response in self.responses.values():
self.discard_pending_transcript(response)
for audio in self.audio.values():
audio.data.clear()
self.retire(audio)
tasks = [*self._workers, *self.tasks]
for task in tasks:
task.cancel()
pending = set()
if tasks:
_, pending = await asyncio.wait(tasks, timeout=self.settings.send_timeout_seconds)
if pending:
diagnostic(self.session_id, "runtime_close", "CLEANUP_TIMEOUT",
code=self.failure, pending_tasks=len(pending))
try:
await self._close_provider()
except Exception as exc:
return exc
if pending:
return TimeoutError("Runtime task termination deadline")