feat(voice): add authenticated Phase 2 live lifecycle
Add cookie authentication, owned conversations, durable Live reservations, tool completion/replay fencing, revocation, and startup reconciliation. Introduce forward lifecycle/owner-chain migrations and the temporary Gemini adapter while preserving the existing OpenAI Realtime adapter. Include the executable audio client, regression coverage, configuration, API/database documentation, and recorded acceptance evidence. Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript syntax, and whitespace checks passed. Full PostgreSQL/provider-free results are recorded in the repair report; real-provider/browser acceptance is unrun. Follow-up work remains for configurable OpenAI/Gemini selection, transport admission, authority diagnostics, playback message bounds, and client replay identity after ambiguous creation responses.
This commit is contained in:
@@ -51,7 +51,7 @@ def provider_event_digest(event, limit):
|
||||
item = event.get("item")
|
||||
if isinstance(item, dict) and item.get("type") == "function_call":
|
||||
event = dict(event, item=arguments(item))
|
||||
elif kind == "response.done":
|
||||
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"
|
||||
@@ -158,7 +158,7 @@ class VoiceRuntime:
|
||||
"""
|
||||
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):
|
||||
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")
|
||||
@@ -168,6 +168,7 @@ class VoiceRuntime:
|
||||
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
|
||||
@@ -210,6 +211,7 @@ class VoiceRuntime:
|
||||
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
|
||||
@@ -495,6 +497,8 @@ class VoiceRuntime:
|
||||
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")
|
||||
@@ -522,9 +526,10 @@ class VoiceRuntime:
|
||||
await self.handle(await self.adapter.receive())
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except (ProviderProtocolError, ValueError, TypeError, RecursionError):
|
||||
except (ProviderProtocolError, ValueError, TypeError, RecursionError) as exc:
|
||||
async with self.lock:
|
||||
self.fail("LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
self.fail("LIVE_BUFFER_OVERFLOW" if getattr(exc, "overflow", False) else
|
||||
"LIVE_CONTEXT_SYNC_FAILED" if getattr(exc, "context_sync", False) else "LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
except Exception:
|
||||
async with self.lock:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED" if self.context_pending()
|
||||
@@ -554,9 +559,22 @@ class VoiceRuntime:
|
||||
continue
|
||||
if kind in ("response.create", "conversation.item.create") and owner:
|
||||
valid = await self.check_authority(owner)
|
||||
failure = "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("CONTEXT_REVOKED", turn=owner)
|
||||
self.fail(failure, turn=owner)
|
||||
continue
|
||||
if not self.check_deadlines() or owner is not self.current or owner.superseded:
|
||||
self.release_command(cmd)
|
||||
@@ -593,9 +611,9 @@ class VoiceRuntime:
|
||||
cmd = None
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
async with self.lock:
|
||||
self.fail("LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None)
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED" if getattr(exc, "context_sync", False) else "LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None)
|
||||
finally:
|
||||
if cmd:
|
||||
async with self.lock:
|
||||
@@ -690,7 +708,7 @@ class VoiceRuntime:
|
||||
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 == "completed"
|
||||
all(r.terminal and r.status in ("completed", "waiting_tools")
|
||||
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
|
||||
@@ -787,7 +805,7 @@ class VoiceRuntime:
|
||||
continue
|
||||
if not response.terminal or any(c["result"] is None for c in response.calls.values()):
|
||||
continue
|
||||
if response.status != "completed":
|
||||
if response.status not in ("completed", "waiting_tools"):
|
||||
self.fail("LIVE_PROVIDER_UNAVAILABLE")
|
||||
return
|
||||
for call_id, call in response.calls.items():
|
||||
@@ -1000,6 +1018,7 @@ class VoiceRuntime:
|
||||
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
|
||||
@@ -1016,9 +1035,9 @@ class VoiceRuntime:
|
||||
async with self.lock:
|
||||
self.fail("LIVE_TRANSPORT_FAILED", turn=owner, writable=False)
|
||||
raise
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
async with self.lock:
|
||||
self.fail("LIVE_TRANSPORT_FAILED", turn=owner, writable=False)
|
||||
self.fail(getattr(exc, "live_code", "LIVE_TRANSPORT_FAILED"), turn=owner, writable=False)
|
||||
finally:
|
||||
async with self.lock:
|
||||
if entry:
|
||||
@@ -1104,6 +1123,8 @@ class VoiceRuntime:
|
||||
|
||||
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
|
||||
@@ -1134,6 +1155,8 @@ class VoiceRuntime:
|
||||
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":
|
||||
@@ -1171,9 +1194,9 @@ class VoiceRuntime:
|
||||
turn.input_deadline = self.clock() + self.settings.input_commit_timeout_seconds
|
||||
if turn.commit_ack:
|
||||
self.acknowledge_input(turn)
|
||||
elif kind == "input_audio_buffer.committed":
|
||||
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"):
|
||||
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:
|
||||
@@ -1224,8 +1247,10 @@ class VoiceRuntime:
|
||||
or len(content) > 1 or
|
||||
(content and content[0]["type"] != "audio")):
|
||||
raise ValueError("Unsupported output layout")
|
||||
elif kind == "response.done":
|
||||
elif kind in ("response.done", "provider.tools_requested"):
|
||||
wire = event["response"]
|
||||
if wire["status"] == "waiting_tools" and kind != "provider.tools_requested":
|
||||
raise ValueError("Invalid native tool phase")
|
||||
response = self.responses[wire["id"]]
|
||||
if response.terminal and response.status != wire["status"]:
|
||||
raise ValueError("Conflicting terminal")
|
||||
@@ -1262,7 +1287,7 @@ class VoiceRuntime:
|
||||
raise ValueError("Terminal call-set mismatch")
|
||||
response.terminal, response.status = True, wire["status"]
|
||||
self.wake.set()
|
||||
if wire["status"] not in ("completed", "cancelled"):
|
||||
if wire["status"] not in ("completed", "cancelled", "waiting_tools"):
|
||||
self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn)
|
||||
elif wire["status"] == "cancelled" and not response.interrupted:
|
||||
raise ValueError("Unexpected cancellation")
|
||||
@@ -1287,7 +1312,7 @@ class VoiceRuntime:
|
||||
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 > self.settings.max_output_backlog_bytes:
|
||||
if audio.state != "finalizing" and backlog + estimate + getattr(self.adapter, "_audio_bytes", 0) > self.settings.max_output_backlog_bytes:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW", turn=response.turn)
|
||||
return
|
||||
decoded = base64.b64decode(encoded, validate=True)
|
||||
@@ -1349,7 +1374,8 @@ class VoiceRuntime:
|
||||
response.transcript_parts[key] = fingerprint
|
||||
elif key in response.transcript_parts:
|
||||
raise ValueError("Transcript delta after completion")
|
||||
if not response.interrupted and not response.turn.superseded:
|
||||
if (not response.interrupted and not response.turn.superseded
|
||||
and (response.turn is self.current or response.status == "completed")):
|
||||
response.visible = True
|
||||
entry = self.control(dict(type="transcript", turn_ref=response.turn.ref, role="assistant",
|
||||
text=text, status="completed" if completed else "partial"),
|
||||
@@ -1417,7 +1443,7 @@ class VoiceRuntime:
|
||||
name=name, raw=raw, item=item_id, ref=str(uuid4()))
|
||||
self.calls[call_id] = (response, call)
|
||||
response.calls[call_id] = call
|
||||
if response.interrupted or response.turn.superseded:
|
||||
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)
|
||||
@@ -1434,16 +1460,31 @@ class VoiceRuntime:
|
||||
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:
|
||||
tool = create_search_tool(self.service, ctx, self.runner)
|
||||
result = await tool.ainvoke(args)
|
||||
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:
|
||||
result = self.runner.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed")
|
||||
except Exception as exc:
|
||||
from app.modules.voice.durable_tools import failure_code
|
||||
async with self.lock:
|
||||
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 not ctx.cancelled.is_set()):
|
||||
and response.turn is self.current and not ctx.cancelled.is_set()):
|
||||
call["result"] = result
|
||||
await self.release()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user