docs(voice): freeze OpenAI Realtime Phase 0 contracts

Align voice specifications and the MVP plan with OpenAI Realtime.
Document audio admission, bounded playback, cancellation ownership,
turn correlation, cleanup barriers and calibration prerequisites.
Preserve historical checkpoints and record unrun acceptance gates.
This commit is contained in:
amirhosein mazaheri
2026-10-08 18:07:38 +03:30
parent 9dac244590
commit 6f0561c490
10 changed files with 834 additions and 48 deletions
+20 -20
View File
@@ -13,7 +13,7 @@ Document lifecycle decision (revision 1.1): every upload is an independent immut
## 1. Purpose and Scope
The current milestone is the conditional four-day Live document MVP governed by delivery plan revision 1.3. Known users in one organization upload new supported documents through the browser, activate ready knowledge and ask Persian spoken questions. LangChain exposes the shared scoped retrieval/tool boundary; Gemini Live owns native audio conversation. Full text chat, durable messages and settings editing are deferred. Historical/broader sections below do not expand this active scope.
The current milestone follows the delivery plan's scoped Phase 0 amendment and the Realtime MVP backend plan; its conditional 3-5 day estimate supersedes the earlier four-day integration sequence. Known users in one organization upload new supported documents through the browser, activate ready knowledge and ask Persian spoken questions. LangChain exposes the shared scoped retrieval/tool boundary; OpenAI Realtime owns native audio conversation. Full text chat, durable messages and settings editing are deferred. Historical/broader sections below do not expand this active scope.
The four supplied PDFs/DOCX/image examples are mandatory initial tests, not an upload allowlist or a known final corpus. New files within declared structure/resource limits require no developer code changes.
@@ -23,7 +23,7 @@ The initial business use case is a reliable demonstration and subsequent organiz
- PostgreSQL with pgvector stores application data and document embeddings.
- Preserve the implemented hosted embedding adapter, validation and staging from ingestion Phases 1-4, including compatible profiles/vectors; funded deployment identity and Persian quality still need proof. Provider comparison is optional, not required delivery work.
- Initial voice uses direct Gemini Live API access managed by the backend over WSS. There is no mandatory separate ASR, TTS or answer-generation call for each voice turn.
- Initial voice uses direct OpenAI Realtime API access managed by the backend over WSS. There is no mandatory separate ASR, TTS or answer-generation call for each voice turn.
- The agent decides whether to call the knowledge search tool and can repeat a search when necessary.
- Documents are dynamically uploaded, updated and selected by the organization.
- The only initial knowledge tool is `search_knowledge`. A separate read-document tool is excluded.
@@ -46,7 +46,7 @@ The current MVP includes document ingestion/review, organization-scoped retrieva
1. **Agentic interaction:** the model chooses a registered tool; the backend validates and executes the call. Models never receive database credentials or generate executable SQL for direct execution.
2. **Organization-controlled knowledge:** retrieval is restricted to authorized, selected and ready documents.
3. **Shared retrieval:** both conversation modes use one search implementation and evidence contract.
4. **Backend-managed live audio:** the backend relays client audio to direct Gemini Live and executes authorized tools on the same controlled session.
4. **Backend-managed live audio:** the backend relays client audio to direct OpenAI Realtime and executes authorized tools on the same controlled session.
5. **Persistent application state:** provider session state and local process memory are not authoritative conversation history.
6. **Explicit lifecycle:** uploading a file does not immediately make it searchable. Ingestion must complete before publication.
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
@@ -64,7 +64,7 @@ The current MVP includes document ingestion/review, organization-scoped retrieva
| Embedding/extraction providers | Existing compatible vector generation and direct/vision extraction | Fixed funded profiles; preserve embedding identity |
| Live provider | Direct audio understanding and speech generation | External live model service |
A provider adapter is backend code. It is not the provider service. The browser uses an authenticated application WSS stream to the backend. The backend owns the Gemini Live connection, credentials, policy and tool execution; the provider service remains external.
A provider adapter is backend code. It is not the provider service. The browser uses an authenticated application WSS stream to the backend. The backend owns the OpenAI Realtime connection, credentials, policy and tool execution; the provider service remains external.
The two presentation diagrams are retained in Appendix A. They show logical responsibilities; they do not imply that the live model runs inside the backend deployment.
@@ -295,17 +295,17 @@ The worker claims jobs with a lease and claim token, updates progress and publis
Store job attempts, next retry time, stage, error category and processing profile. Retry temporary network/rate-limit failures with bounded backoff; unsupported formats and invalid input require correction. File storage and PostgreSQL do not share a transaction: use staged storage and reconciliation to clean abandoned uploads or recover incomplete metadata transitions.
## 8. Live Voice with direct Gemini API access
## 8. Live Voice with backend-managed OpenAI Realtime
### 8.1 Connection responsibilities
Use direct Gemini Live for the initial voice MVP. The provider connection is stateful WSS; the backend relays client audio and controls private tools. Browser-to-provider SDP/WebRTC from revision 1.1 is superseded for this MVP, not assumed compatible with Gemini. See [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api).
Use backend-managed OpenAI Realtime for voice, as authorized in the [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md). The provider connection is stateful WSS; the backend relays client audio and controls private tools. The browser uses the application stream, not provider SDP or credentials. See [Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations).
OpenRouter is for bounded comparisons of two or three text/vision candidates. Its [audio interface](https://openrouter.ai/docs/guides/overview/multimodal/audio) supports request audio and streamed response audio; that does not establish a compatible bidirectional Gemini Live session.
OpenRouter is for bounded comparisons of two or three text/vision candidates. Its [audio interface](https://openrouter.ai/docs/guides/overview/multimodal/audio) supports request audio and streamed response audio; that does not establish a compatible bidirectional OpenAI Realtime session.
### 8.2 Session establishment
Authenticate the HTTP creation request; persist the owned reservation and idempotency hash before provider setup. Validate session/auth/access epoch again at the application WSS handshake using cookie and trusted Origin. The backend connects to Gemini with its server credential, installs Persian instructions and `search_knowledge`, and enables available input/output transcription. Mark connected only after trusted adapter confirmation. The application WSS transport/event fields are proposed in [API catalog Section 7](RAG-Phase1-API-Catalog.md).
Authenticate the HTTP creation request; persist the owned reservation and idempotency hash before provider setup. Validate session/auth/access epoch again at the application WSS handshake using cookie and trusted Origin. The backend connects to OpenAI Realtime with its server credential, installs Persian instructions and `search_knowledge`, and enables available input/output transcription. Mark connected only after trusted adapter confirmation. The application WSS audio/event fields are frozen in [API catalog Section 7](RAG-Phase1-API-Catalog.md).
### 8.3 Voice tool cycle
@@ -313,7 +313,7 @@ Authenticate the HTTP creation request; persist the owned reservation and idempo
sequenceDiagram
participant U as Browser or approved audio bridge
participant B as Backend Live controller
participant L as Gemini Live
participant L as OpenAI Realtime
participant K as Shared knowledge service
participant D as PostgreSQL and pgvector
U->>B: Authenticated audio stream
@@ -331,7 +331,7 @@ sequenceDiagram
The Live model may answer directly from returned evidence. A separate text-generation call on every voice turn is not mandatory. The existing prototype text agent is not a prerequisite for this milestone. The trusted dispatcher invokes the shared LangChain knowledge tool; adding a separate answer model would require a measured purpose and re-estimated latency/cost.
Backend dispatch correlates session/call IDs, validates complete arguments, deduplicates same-ID calls and rejects changed arguments. Recheck current document eligibility and epoch before releasing evidence, including cached duplicates. [Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools) require application handling of function responses; validate the chosen model's blocking/asynchronous capabilities rather than combining incompatible examples.
Backend dispatch correlates session/call IDs, validates complete arguments, deduplicates same-ID calls and rejects changed arguments. Recheck current document eligibility and epoch before releasing evidence, including cached duplicates. [Realtime function calling](https://developers.openai.com/api/docs/guides/realtime-conversations) requires application handling of function results and authorized response continuation through private provider call IDs.
### 8.4 Conversation, interruption and failure behavior
@@ -351,7 +351,7 @@ Seamless reconnect and provider context restoration are deferred. A new session
### 8.5 Audio, transcripts and telephony boundaries
The proposed application stream uses mono raw PCM matching Gemini: 16-bit little-endian input at 16 kHz and output at 24 kHz. Capture/resample browser audio and convert output for playback; do not forward compressed browser blobs as PCM. The provider accepts explicitly declared input rates, but standardizing the bridge simplifies the MVP. Interruption clears playback buffers. Verify these behaviors against the configured model using [Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities).
The frozen application stream uses raw mono signed PCM16LE at 24 kHz in both directions, governed by API Section 7.1. Capture/resample browser audio and convert output for playback; do not forward compressed blobs as PCM. user_speech_started, audio_started and validated playback_progress correlate turns and reported playback. One audio_ref covers one provider item/audio content part; audio_ended seals generation, not playback. API 7.1.1-7.1.4 governs integer sample coordinates, retained references, final reports after interruption, acknowledged private cleanup before continuation, transport bounds and sixteen walkthroughs. API 7.1.5 separately bounds generated audio and paces delivery using validated progress credits; 7.1.6 preserves delayed user ASR and gates response release on current committed input, valid authority/epoch and all cleanup barriers. Both VAD flags are false with backend-owned response-specific cancellation and narrow completion-race handling; normal exchanges are not relabeled interrupted. Interruption clears playback; cleanup failure closes the session instead of continuing with unheard context. See [Realtime audio and interruption](https://developers.openai.com/api/docs/guides/realtime-conversations).
Keep available answer transcription and source references visible for the current session. Missing transcription is labeled unavailable, never reconstructed as if spoken; partial generated text does not prove what was heard. Durable full voice history and raw recording remain deferred. The chosen demo model must prove output-transcription delivery; API/storage details must not imply voice messages already exist in the current text-only schema.
@@ -454,7 +454,7 @@ Final application statuses include `answered`, `needs_clarification`, `insuffici
### 10.3 Live session application contract
For Phase 1, the request carries `conversation_id` and `client_request_id`; the response contains session ID, state and an owned application WSS path. The backend connects to direct Gemini Live. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.
For Phase 1, the request carries `conversation_id` and `client_request_id`; the response contains session ID, state and an owned application WSS path. The backend connects to direct OpenAI Realtime. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.
### 10.4 Error envelope
@@ -565,7 +565,7 @@ Remove indexing side effects from module imports. Re-embed the source documents
## 18. Implementation Sequence
1. Prove actual funded Gemini Persian audio/transcripts/tools and target-network access early.
1. Prove actual funded OpenAI Realtime Persian audio/transcripts/tools and target-network access early.
2. Reuse ingestion Phases 1-4; implement Phase 5 worker, exact-output review/resume and complete publication.
3. Add minimal cookie identity and new-document HTTP upload/status/review/selection.
4. Implement one scoped pgvector search service using compatible existing embeddings.
@@ -584,7 +584,7 @@ and capacity/quality targets require confirmation. Documentation is not runtime
| --- | --- | --- |
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
| Organization-wide selection | Confirmed MVP direction | Preserve selected-set revision and backend eligibility |
| Exact Gemini Live model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
| Configured OpenAI Realtime model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
| Funded embedding/extraction/Live profiles | AI team | Preserve current embedding compatibility; prove real quality/access |
| Cookie session TTL/account operation | IT / backend | Pre-created local accounts now; SSO deferred |
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
@@ -601,9 +601,9 @@ These items must be resolved by their owners rather than silently converted into
External references establish platform capabilities. Module boundaries, contracts and lifecycle rules in this document are project design proposals. Model/API availability must be checked when implementing the selected adapter.
- **[R1]** [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api): initial direct provider/session access.
- **[R2]** [Gemini Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities): audio, transcription and interruption.
- **[R3]** [Gemini Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools): correlated function calls/results.
- **[R1]** [OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime): initial direct provider/session access.
- **[R2]** [OpenAI Realtime capabilities](https://developers.openai.com/api/docs/guides/realtime-conversations): audio, transcription and interruption.
- **[R3]** [OpenAI Realtime tools](https://developers.openai.com/api/docs/guides/realtime-conversations): correlated function calls/results.
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
## Appendix A. Presentation Diagrams
@@ -684,7 +684,7 @@ flowchart TD
CHAT <--> TEXT
SESSION -->|"Initialize and Control"| LIVE
UI <-->|"Authenticated audio WSS"| SESSION
SESSION <-->|"Direct Gemini Live WSS"| LIVE
SESSION <-->|"Direct OpenAI Realtime WSS"| LIVE
TOOL <--> SEARCH
SEARCH <--> DB
@@ -704,7 +704,7 @@ No standalone ADR directory or separate requirements specification was found. Th
| --- | --- |
| Confirmed product direction | Complete upload → extraction/QC → chunk/index → Persian voice → retrieval → grounded spoken answer; text-only or voice without retrieval is insufficient |
| Confirmed existing lifecycle | Independent immutable uploads; direct document/chunk references; manual replacement; same eligible failed document/job retry; existing scope/revision/epoch/fencing rules |
| Confirmed provider direction | Direct Gemini Live; Flash vision extraction candidate; OpenRouter comparisons; USD 20 initial allocation and USD 30 planned budget |
| Confirmed provider direction | Direct Gemini Live (historical; superseded for voice by Phase 0); Flash vision extraction candidate; OpenRouter comparisons; historical USD 20 initial allocation and USD 30 planned budget |
| Proposed details | Application WSS event schema, optional tool context, derived extraction artifact, manual quality gate, identifier matching alongside semantic retrieval |
| Verified by static inspection | Markdown folder loader and character splitter; Chroma/FastEmbed `BAAI/bge-small-en-v1.5`; LangGraph `MemorySaver`; configurable OpenAI-compatible text client; prototype chat route without the planned auth/turn contracts |
| Verified by static inspection | Seven-table ingestion foundation and trusted intake CLI/local immutable originals; settings allow only PDF/Markdown; `ExtractedBlock` has text/page/section; no extraction worker, hosted embedding adapter, pgvector chat search, Live adapter or frontend |
@@ -719,7 +719,7 @@ See the [Persian sample scenarios](RAG-Phase1-Scenario-Report-FA.md) for local i
| Category | Current baseline |
| --- | --- |
| Confirmed product | Limited demo for known users; new browser uploads; all four examples; unknown future document count |
| Confirmed framework | LangChain RAG/tools; direct Gemini Live audio loop |
| Confirmed framework | LangChain RAG/tools; direct OpenAI Realtime audio loop |
| Confirmed reuse | Implemented ingestion/embedding Phases 1-4 and repaired validation/staging; no wholesale embedding refactor |
| Required next implementation | Fenced worker/review/resume/publication, scoped pgvector search, HTTP identity/upload, owned Live and minimal workspace |
| Deferred milestone | Full text/history/citations, rich settings/delete UI, raw recording, seamless reconnect and CTI |
@@ -9,6 +9,8 @@
| Milestone | Four implementation days as a conditional demo target; three days is optimistic |
| Scope authority | This plan governs the current MVP; it supersedes the previous 7-10 day text-and-voice milestone |
Phase 0 amendment (2026-10-08): OpenAI Realtime replaces Gemini Live for voice only. The [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md) supplies the current backend phase sequence and conditional 3-5 day estimate; prior four-day schedule is historical. See [Phase 0 prerequisites and results](../guides/realtime-agent-phase0.md). Extraction/embeddings and HTTP/search contracts are unchanged.
## 1. Release Objective
Deliver an authenticated Persian document assistant with this actual workflow:
@@ -31,7 +33,7 @@ Full text chat and durable message history move to the follow-up milestone.
Confirmed user direction: browser upload, all four supplied examples, new
documents beyond those examples, LangChain, reuse of the implemented embedding
pipeline, and backend-managed direct Gemini Live speech-to-speech.
pipeline, and backend-managed direct OpenAI Realtime speech-to-speech.
| Existing component | Evidence and reuse boundary |
| --- | --- |
@@ -49,7 +51,7 @@ dimension, preprocessing or rebuilding compatible vectors. Recorded tests
establish component behavior only; real hosted-provider quality, Persian
speech and the complete workflow remain unverified.
In the first Day 1 work block, prove real Gemini audio, Persian output,
In the first Day 1 work block, prove real OpenAI Realtime audio, Persian output,
transcription and a backend-executed function call on the intended network.
Confirm funded embedding/extraction profiles and actual HTTPS hosting in the
same day. Failed provider access changes the dependent estimate; it does not
@@ -65,7 +67,7 @@ justify quietly replacing Live with text.
| Processing | Existing extraction/chunking/embedding components, separate durable worker, fenced recovery and complete publication | Distributed fleet, broker, batch checkpoint orchestration |
| QC | Evidence-bound review of retained output and explicit factual FAQ approval; clear failures | Elaborate review editor and automatic quality classifier |
| Search/framework | LangChain tool/retriever integration over one scoped pgvector search service; compatible query embedding and exact identifiers | Retrieval tuning UI; reranker/ANN only if measured failures justify them |
| Voice | Direct Gemini Live through backend WSS, Persian speech, follow-ups, topic changes, interruption and visible failure | Seamless reconnect, raw recording, telephony/CTI |
| Voice | Direct OpenAI Realtime through backend WSS, Persian speech, follow-ups, topic changes, interruption and visible failure | Seamless reconnect, raw recording, telephony/CTI |
| Visible evidence | Current-session provider transcripts when delivered, retrieved sources with real locators | Guaranteed durable transcript, complete message history and exact spoken-claim attribution |
| Persistence | Original files, jobs/chunks, review decisions, identity, owned voice/session/tool metadata | Durable text turns/messages/citations and cross-mode continuation |
| Configuration | Fixed server profiles and seeded assistant name/instruction; read-only capabilities | Settings editor, model/voice selector and provider comparisons as required delivery work |
@@ -97,7 +99,7 @@ attribution has been proved. Refreshing the page need not recover a full transcr
Use one modular FastAPI application, a separate ingestion worker from the
same codebase, PostgreSQL/pgvector and durable file storage. LangChain is the
RAG/tool framework; Gemini Live owns the native audio conversation loop.
RAG/tool framework; OpenAI Realtime owns the native audio conversation loop.
```mermaid
flowchart TB
@@ -109,7 +111,7 @@ flowchart TB
API --> SEARCH["Shared search service / LangChain tool"]
SEARCH --> DB
UI <-->|"Authenticated audio/events WSS"| API
API <-->|"Direct audio + correlated function calls/results"| LIVE["Gemini Live"]
API <-->|"Direct audio + correlated function calls/results"| LIVE["OpenAI Realtime"]
```
### 5.1 Existing embedding pipeline and LangChain boundary
+135 -8
View File
@@ -50,7 +50,7 @@ Proposed field limits: deferred text message 8000 characters; assistant name 120
Delivery labels define the current MVP. Deferred sections preserve future contracts, not routes required to ship now. F01 is read-only settings/capabilities; C01 only accepts mode=voice in this milestone. The old prototype POST /chat is not a scoped MVP consumer and must not be exposed as an authenticated replacement.
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider Gemini WSS connection. Internal model tools have no public REST route.
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider OpenAI Realtime WSS connection. Internal model tools have no public REST route.
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_knowledge` is internal and has no public HTTP route.
@@ -265,9 +265,9 @@ Scope key `(conversation_id,client_request_id)`. Changed message under same key:
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
## 7. Voice contract — direct Gemini Live; proposed application WSS
## 7. Voice contract — OpenAI Realtime; frozen application audio/events
The initial provider is direct Gemini Live managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Audio/event field names below are proposed application names, not provider-native event names.
The initial provider is direct OpenAI Realtime managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Phase 0 freezes the application audio/event fields below; implementation remains pending. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID.
### V01 — Create session (HTTP)
@@ -303,12 +303,12 @@ No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Alrea
Proposed WSS upgrade on the V01 `stream_path`: authenticate cookie, trusted Origin, owner, auth session, current epoch and unexpired reservation before accepting. HTTP creation requires normal CSRF; the browser WebSocket handshake uses cookie/Origin validation, not an assumed arbitrary CSRF header. Reject extra caller/model scope. One media connection per session; an additional connection is refused and does not open another provider session.
Proposed binary client frames carry mono PCM16 little-endian at 16 kHz; server audio frames carry PCM16 at 24 kHz. These rates and bounded frame/buffer limits are agreed at stream setup. JSON control/events are distinguished from binary audio. Bridge/transcoding is backend/client work, not a public provider key flow.
Binary frames in both directions carry raw mono signed PCM16LE at 24 kHz (pcm_s16le, one channel, 48,000 bytes/second), without WAV headers or compressed audio. Rates are fixed, not negotiated by callers. Client capture must resample to 24 kHz. JSON controls/events are separate from binary audio. Engineering defaults and deterministic transport admission/close behavior are specified in 7.1.3; all remain runtime implementation obligations.
Illustrative proposed control/event shapes:
Frozen application control/event shapes (illustrative IDs):
```json
{"type":"session_ready","session_id":"a0000000-0000-4000-8000-000000000001","input_audio":{"encoding":"pcm_s16le","sample_rate":16000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}
{"type":"session_ready","session_id":"a0000000-0000-4000-8000-000000000001","input_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}
```
```json
@@ -327,9 +327,136 @@ Illustrative proposed control/event shapes:
{"type":"error","turn_ref":"live-turn-2","error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
```
Transcript status is partial, completed or interrupted. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
Additional server events and the client playback control:
On interruption, flush audio buffers, mark partial output, cancel outstanding calls when possible and suppress late results. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
```json
{"type":"user_speech_started","turn_ref":"live-turn-2"}
{"type":"audio_started","turn_ref":"live-turn-1","audio_ref":"live-audio-1"}
{"type":"playback_progress","audio_ref":"live-audio-1","played_ms":120}
```
#### 7.1.1 Audio coordinates and reference lifecycle
An output segment is exactly one provider assistant output item/audio content part, from its first sample to provider generation completion or cancellation. Allocate one backend-generated audio_ref per such part, unique and never reused in a session. Provider item/response IDs and content indices stay private. Do not split a part into multiple audio_ref values in this MVP: splitting would require a separately reviewed private sample-offset mapping. Splitting a segment into transport messages does not create a new reference. The adapter must support the documented truncatable audio content index (currently 0); unexpected layouts fail safely, never guess a mapping.
Emit audio_started before the first binary message for that reference. Binary messages belong to the last audio_started; serialize output parts without interleaving their bytes. Seal the prior part with audio_ended before the next audio_started, unless turn_interrupted has sealed it. Duplicate audio_started with identical turn_ref/audio_ref is a no-op and must not reset playback; a conflicting reuse is a protocol error. Generation completion does not mean playback completion. Add this end delimiter, since neither transcript completion nor another audio_started reliably seals the last part:
```json
{"type":"audio_ended","turn_ref":"live-turn-1","audio_ref":"live-audio-1","sent_bytes":48000}
```
audio_ended is server-only and occurs after all successfully sent messages of a normally completed segment. sent_bytes is a nonnegative even integer counting only raw PCM payload bytes whose application WebSocket send completed successfully. It excludes provider-generated bytes still queued, discarded on cancellation, JSON and framing overhead. It is not a claim that the browser received or heard those bytes. Exact duplicate audio_ended is a no-op; changed totals are a protocol error. No audio_ended is required for an interrupted segment: turn_interrupted seals all its audio references. Send uncertainty makes the session unusable; do not continue with ambiguous accounting.
Reference states are open (may send), sealed (no further bytes, browser may still play), finalizing (cleanup owns the reference; interrupted refs accept bounded final progress), and retired (no progress can alter provider context). Finalizing also covers normal submillisecond-tail cleanup without relabeling the exchange interrupted. Only open/sealed refs can be playback-stall eligible under 7.1.5; finalizing/interrupted/retired refs cannot. Retain sealed mappings and last valid progress even after provider response completion and while newer segments play. At most 64 unretired references per session is an engineering default; exceeding it fails the session rather than evicting an unresolved reference. After interruption cleanup acknowledgement, retire all affected references, retaining their frozen last progress as tombstones until session close. At most 256 references including tombstones per session is an engineering default; fail safely on exhaustion. Session close retires everything. A normally completed reference may retire without truncation only after provider terminal generation, audio_ended, all sends completed, generated_bytes == sent_bytes == 48 * last_valid_played_ms and a whole-millisecond total: every sample is then confirmed by the report. A normal submillisecond-tail cleanup follows 7.1.6 without relabeling an otherwise complete exchange interrupted. Otherwise retain it for interruption cleanup. Do not retire on transcript completion or a rounded progress value alone.
played_ms is a JSON integer token (not boolean, fractional/exponent-form number, string, NaN or infinity), cumulative duration actually played from the start of that reference, excluding queued audio. The browser computes floor(played_samples / 24) at 24 kHz; the backend computes max_sent_ms = floor(sent_bytes / 48). Accept only 0 <= played_ms <= max_sent_ms and monotonic values within that session/reference; equal duplicates are no-ops. For example, 50 sent bytes = 25 samples: max_sent_ms is 1, never rounded to 2. Provider audio_end_ms is the accepted integer played_ms, equivalent to 24 * played_ms sample positions from the part's start. No public/provider offset conversion is needed. Round down; submillisecond uncertainty is discarded from provider context, not claimed heard. Never silently clamp excessive input to a believable value.
Send progress once every 100 ms during playback (engineering cadence default) and once at segment completion and immediately after stop/flush. Repeated equal values are allowed. FIFO browser playback spans multiple references; every queued-but-unplayed segment has confirmed progress zero. Progress is a playback assertion subject to validation, never authority or proof of human comprehension.
#### 7.1.2 Interruption, final reporting and provider continuation
On genuine trusted user speech detection, first classify prior work using normal-completion versus actual-interruption rules in 7.1.6. For actually unfinished old output, atomically transfer affected refs to finalizing and invalidate their playback-stall timer identities before emitting interruption/stop controls; stop admission/delivery of its audio/tool results, cancel under the ownership rule below, seal sent-byte counters and start the final reporting window. Cleanup now owns those refs: the final-progress, cancellation/terminal and cleanup-ack deadlines below remain enforceable, but stopped/flushed playback has no stall obligation. Final reports never rearm it. Emit turn_interrupted only for affected unfinished old output, before user_speech_started for the new turn. A normally completed exchange retains its completed state; pending input with no assistant output can be superseded internally without inventing an interrupted answer. Duplicate interruption of an already finalizing/retired turn neither restarts timers nor sends cancellation/cleanup twice. A serialized send already completed before interruption is counted; queued unsent bytes are removed and never counted. Suppress all late old-turn audio, audio_started/audio_ended, completed tool results/continuations and assistant transcript completion updates. Delayed user-input transcripts follow 7.1.6 and are not suppressed merely because a newer turn exists. Retain already delivered sources/transcripts only as interrupted display evidence, never claim an exact spoken transcript.
On turn_interrupted (or user_speech_started while old playback remains), the browser immediately stops currently playing old-turn audio, samples the played position at stop, cancels scheduled playback and flushes every old-turn queued segment. It sends final playback_progress for every retained affected reference, including zero for never-played segments and the last completed position for earlier segments. It stops even if provider generation was already completed. Identical interruption notifications must not resume audio or reset progress. Socket close/error uses the same stop/flush behavior without assuming final reports will arrive.
The server accepts valid old-reference progress arriving after turn_interrupted while the window is open. Proposed engineering default LIVE_FINAL_PROGRESS_WINDOW_MS is 1000, measured by backend monotonic time from interruption detection, not receipt by the browser. Validate/process fully admitted messages strictly before the deadline in connection order; messages still queued at expiry cannot extend the window. At or after the deadline freeze all last valid values. No extra final flag or acknowledgement is added to playback_progress, so wait the bounded window rather than guessing the last report. Auth expiry/revocation bypasses this wait and closes; progress never renews access. Reports after freezing cannot amend truncation: an equal duplicate against a known frozen/retired value is ignored, changed late/retired or unknown-reference progress is rejected by the error policy below.
At window expiry use the last valid progress for each part; missing progress means zero, not all sent audio. Coalesce the old response's cancellation request sent at interruption; cancellation alone does not remove unheard context. Privately count all received provider-generated samples, including unsent/cancelled deltas, without delivering late output. Wait for provider terminal generation/cancellation before deciding the final generated total and dispatching cleanup; final played values remain frozen. Privately truncate every affected part with unconfirmed playback, including earlier/later generated parts and parts with zero application sends. Only a terminal part with generated_bytes == sent_bytes == 48 * confirmed_played_ms is fully confirmed and needs no truncation; unsent generated audio and any remaining fraction of a millisecond require cleanup. If the provider cannot truncate a mapped part or remove wholly unheard later output with confirmed cleanup, fail/close the session; do not continue with that context. No invented shortened transcript is returned.
Require provider-confirmed cancellation/terminal generation within 5 seconds of the one cancellation dispatch, then matching cleanup acknowledgements (item/content/audio_end_ms), with all cleanup acknowledgements received within LIVE_TRUNCATION_ACK_TIMEOUT_SECONDS = 5 after cleanup dispatch (engineering default). Cancellation timeout uses that same configured 5-second bound. Thus the final-report/cancellation barriers have finite deadlines even if the provider never terminates generation. An already-completed response needs no cancel acknowledgement; its unplayed audio still needs cleanup. Coalesce identical pending cleanup and acknowledgements. A conflicting cleanup acknowledgement, truncation/provider failure (apart from the narrowly correlated no-active-response cancellation race below), lost connection or timeout yields normalized LIVE_CONTEXT_SYNC_FAILED, retires the session and requires reconciliation/fresh session. Never infer success from sending truncate or receiving response completion.
The backend is the sole cancellation and response-creation owner. Configure private VAD create_response=false AND interrupt_response=false and require provider configuration acknowledgement; VAD still reports speech/commit events. The proof's defaults are not evidence of this configuration. For a known active old response, send at most one response.cancel with that specific private response_id and a unique private event_id mapped to the cancellation intent; never issue a bare cancel that could hit a newer response. Record terminal response.done state by response identity. If completion or provider cancellation was already observed for that response, skip cancellation and proceed to required playback/context cleanup.
A completion/cancellation racing after the backend's active-state check can produce a no-active-response cancellation error. Only an adapter-verified no-active-response classification tied by error event_id to that one cancellation intent/response is benign by itself: it does not fail the session, retry cancellation or satisfy the terminal/cleanup barrier. Independently require a correlated terminal response.done (completed/cancelled; failed/incomplete handled as technical failure) within the bounded cancellation deadline, then complete all required context cleanup. A terminal event already recorded satisfies this test; missing terminal confirmation times out and fails. A response identity mismatch, generic/unrelated error, bad arguments, authentication failure or truncation error is not this exception and remains fatal under its normal policy. Official docs establish the benign behavior but not a stable named error code; an exact structured classifier must be proved with the selected provider profile before race acceptance, never infer it from a free-text substring or swallow all cancellation errors.
Keep both VAD flags disabled throughout the session. Unexpected automatic generation/cancellation is an observable configuration/protocol deviation; correlate any actual terminal event for cleanup, suppress unintended output and fail if the controlled state cannot be established. The independent response-release gate in 7.1.6 applies even after all cleanup acknowledgements arrive. This is a future runtime obligation, not proof-script behavior.
#### 7.1.3 Transport admission, queues and terminal errors
These finite engineering defaults are frozen for initial integration and configurable by trusted deployment only. Product owners still need to approve capacity/latency targets; missing runtime enforcement blocks runtime acceptance, not this documentation checkpoint.
| Boundary | Limit / accounting |
| --- | --- |
| Application binary message, either direction | 9600 raw bytes (200 ms), nonempty and even-length; each message ends on a complete PCM16 sample |
| Client JSON control message | 4096 UTF-8 bytes before parsing; one object, only playback_progress with exact documented fields; ref strings 1-128 ASCII characters |
| Server JSON event message | 65536 UTF-8 bytes; build within a bounded serialization budget; preserve whole evidence/source fields or fail, never truncate them silently |
| Application transport audio queues | 96000 raw bytes (2 seconds) AND 100 queued messages per direction; count queues/in-flight sends until completion. Output scheduling also obeys the smaller 72000-byte T+R credit window in 7.1.5 |
| Provider-generated reservoir / aggregate undrained output | 1440000 bytes (30 seconds) across G+T+R, 512 packed slabs, bounded descriptors/scratch/metadata; 7.1.5 distinguishes storage from delivery/playback |
| Browser output backlog | 96000 bytes AND 100 messages across all refs, including currently playing remainder and scheduled buffers; independently enforced by browser |
| Input since last commit | 480000 bytes (10 seconds), including forwarded provider-buffered PCM; fail if not committed within this bound |
| Control/event queues | 64 messages and 262144 encoded bytes per direction; ordered relative to audio markers |
| Send completion deadline | 5 seconds per message; uncertain/failed send fails session, does not increment confirmed sent_bytes |
Application message limits apply to reassembled WebSocket messages as well as individual wire fragments: fragmentation cannot bypass the bound. Reject oversized headers before payload allocation; configure transport maximum reassembled size and bounded receive queues, disable compression and reject RSV/compressed frames. Before UTF-8 decoding, JSON parsing, PCM conversion or queue append reserve size/count capacity. Browser code checks byteLength before copying/decoding. Provider receive messages require an independent 262144-byte cap, checked before JSON/base64 decode; decoded audio must be sample-aligned and fit the generated-reservoir/scratch admission in 7.1.5 before allocation/enqueue; it need not fit immediately into the much smaller transport queue. Divide admitted PCM into <=9600-byte even messages. Do not allocate an unbounded delta and then check it.
Before session_ready, browser capture/send is disabled; backend accepts no application audio/control payload, buffers none, and forwards none to provider. Setup acknowledgement precedes session_ready and any output audio. Early audio/control is LIVE_NOT_READY and closes with 1008. Ping/pong/close protocol frames remain transport concerns. Server emits no binary output without a preceding audio_started. Schema errors, unknown controls, malformed UTF-8/JSON, empty/odd PCM, invalid progress and conflicting reference reuse fail with LIVE_PROTOCOL_ERROR and close 1008. A reference tombstone's equal duplicate is the only accepted post-retirement progress.
Oversized messages use LIVE_FRAME_TOO_LARGE and close 1009. Capacity exhaustion uses LIVE_BUFFER_OVERFLOW and close 1013. Provider malformed output, send uncertainty, or context synchronization failure uses the corresponding normalized error (LIVE_PROVIDER_PROTOCOL_ERROR, LIVE_TRANSPORT_FAILED, LIVE_CONTEXT_SYNC_FAILED) and close 1011. Stop admissions, cancel work, flush queues and mark the session failed/unusable. Use the existing error envelope with the affected application turn_ref (null before any turn), safe request_id and retryable=false for this unusable session; recovery requires reconciliation and a fresh session. Attempt one bounded error send only if reserved control capacity and a writable socket exist; otherwise close directly. Overflow must not block on enqueueing its own error. Browser detects close even when no JSON error can be delivered and immediately stops/flushes.
Use queue accounting across references, not a fresh allowance per segment. Unsent canceled bytes may be discarded only while sealing/interruption/terminal failure; never silently drop output and keep generating/counting it as delivered. A genuinely stalled client or exhausted generated backlog fails explicitly under 7.1.5; a healthy generation burst is admitted and paced, not mistaken for transport overflow. Progress acknowledgements do not free server memory for an uncompleted send or expand any limit. Server queue bounds and client playback bounds are separate; neither proves the other.
#### 7.1.4 Contract walkthroughs (documentation acceptance only)
| Case | Required sequence / result |
| --- | --- |
| Final progress after interruption | Ref A last reported 300 ms, 1000 ms sent; interrupt at t=0, browser stops at 420 ms and reports at t=0.2 s. Accept 420 within the 1 s window, truncate privately to 420, wait matching ack, then retire A/allow new response. A later 430 is a protocol error; equal 420 duplicate is ignored. |
| Generation done, playback queued | audio_ended seals A at 48000 bytes, but browser has played 200 ms and queued 800 ms. Keep mapping; interruption stops/flushes and final progress governs cleanup. Generation/transcript completion never means 1000 ms heard. |
| Later segment interrupted | A and B map to distinct private items/content parts; A sent/played 1000 ms, B sent 800 ms/played 250 ms, later C generated but unheard. Keep A, truncate B to 250 in B's own coordinates, remove/truncate C to zero and wait all required acknowledgements. No A offset is added to B. Unsupported multi-part cleanup closes, rather than retaining C as heard context. |
| Duplicates and bad progress | Identical A=250 while open/finalizing or against retired frozen A=250 is a no-op. Unknown A, retired A=251, fractional 250.5, regression 249, boolean, exponent token or value beyond floor(sent_bytes/48) is LIVE_PROTOCOL_ERROR/1008. Timers/calls never restart on duplicates. |
| Missing progress | At deadline no valid A report: use zero. Invalid reports never become a default or no_evidence; protocol violations close. Disconnected client prevents continuation, regardless of last progress. |
| Oversized/overflowing frames | 9602-byte PCM is LIVE_FRAME_TOO_LARGE/1009; 3-byte PCM is LIVE_PROTOCOL_ERROR/1008. A would-be 96002-byte aligned queue exceeds budget: fail LIVE_BUFFER_OVERFLOW/1013 before append, cancel/flush; unsent bytes are not counted. Before readiness even valid PCM fails LIVE_NOT_READY/1008. |
| Six seconds generated in one second | 288000 PCM bytes arrive in multiple provider messages within the per-message cap. Admit into G under the 1440000-byte aggregate limit; T+R never exceeds 72000 bytes. After 1 s of valid real-time playback, 48000 bytes are confirmed and B is about 240000 bytes (plus <1 ms rounding uncertainty). Pace remaining delivery using progress; six-second generation completion neither overflows a healthy browser nor emits audio_ended before the last send. |
| Stalled browser reaches the bound | With no increasing progress, only 72000 bytes can enter T/R. G grows until aggregate B reaches 1440000 bytes; the next aligned delta fails LIVE_BUFFER_OVERFLOW/1013 before allocation. If generation stops below that cap, the 5 s no-progress deadline still terminates the stalled session. Cancel/flush, never count unsent audio as delivered. |
| Cancel versus terminal response | Backend reserves cancel for old response R1; R1 completes or is cancelled before request reaches provider. A correlated verified no-active-response error is benign only by itself. Record R1's terminal response.done, finish required final-progress/truncation cleanup, then evaluate current-turn release; no cancel retry or blanket provider-error suppression. |
| Delayed user transcription | T1 input committed, T2 begins, then ASR completion for T1's private input item arrives. If current authorization/epoch is valid, emit transcript(role=user, turn_ref=T1, status=completed); do not label T2 or release T1. A late assistant completion for interrupted T1 remains suppressed. |
| Cleanup while T2 still speaks | T1 truncation ack clears T1 barrier while T2 is speaking. No response.create: T2 still needs its own speech-stop and committed input confirmation. Duplicate T1 ack cannot bypass these conditions. |
| T3 before earlier cleanup completes | T2 is pending behind T1 cleanup. A new input item/start for T3 advances the private generation token and supersedes T2; replay of T2 start does not. T1 ack clears only T1's barrier; it cannot release T2, and T3 waits for its own commitment, valid authority and every applicable cleanup. |
| Cleanup outlasts former stall deadline | Interrupt A at t=0: atomically finalizing, stall identity invalidated, browser stops/flushes. Final progress at 0.2 s is accepted; freeze at 1.0 s. Cancellation dispatched at 0; correlated terminal confirmation at 4.8 s satisfies its 5 s deadline. Dispatch cleanup at 4.8 s; matching ack at 9.6 s is within 5 s of dispatch (deadline 9.8). Retire/release remaining credit once without claiming discarded audio heard. No playback timeout at 5 s; response release still requires every 7.1.6 gate. |
| Stall callback races finalization | A's deadline callback is queued while interruption acquires the serialized state decision. Finalization invalidates A's timer identity first; the callback rechecks state/identity and does nothing. If the callback instead wins with A eligible and its deadline actually expired, stall failure is terminal. Neither ordering permits double failure/retirement or reviving the session. |
| Fresh output after cleanup | A retires after acknowledged cleanup with its frozen evidence retained and remaining credit released once. Once current input/authority/all barriers permit B, B's first reportable successful send at t=10 s starts B's own deadline at 15 s; no A timestamp or callback applies. B's increasing progress renews only B's eligible timer. |
| Genuine active-playback stall | A remains open/sealed with 48000 sent bytes, zero valid played_ms and no interruption/cleanup ownership. First reportable send at t=0 starts deadline 5 s. Equal zero reports do not renew it. At t=5 s the matching callback confirms A is still eligible and expires it: LIVE_BUFFER_OVERFLOW/1013, terminal failure/stop/flush. Cleanup exclusion does not excuse a genuinely stalled browser. |
#### 7.1.5 Generated backlog and paced delivery
The provider can generate audio faster than real-time playback. The two-second application transport/browser buffers are not a limit on an entire generated response. Keep three distinct counters across all output refs: G = admitted provider-generated PCM not yet scheduled for delivery; T = PCM reserved in the application output queue/in-flight send; R = the outstanding delivery-credit balance for successfully sent PCM not yet confirmed played or explicitly released at retirement/terminal teardown. R is not the retained sent-minus-played evidence counter. A sample moves G -> T -> R without double counting; generated_bytes, sent_bytes and confirmed played bytes remain separate per-reference counters. Never count generated or queued bytes as sent. R is a delivery-credit ledger and need not retain PCM after successful send.
Initial trusted engineering defaults: maximum aggregate undrained backlog B = G + T + R is 1440000 bytes (30 seconds); at most 512 packed PCM slabs and 64 unretired ref descriptors. Pack provider deltas into bounded <=9600-byte even slabs, preserving ref/order; coalescing tiny deltas prevents provider event count alone exhausting the slab budget. Empty/slab metadata is bounded to 65536 bytes, not a per-delta history. Audio storage G+T cannot exceed B; transport copies are separately limited to 96000 bytes; one provider encoded-message scratch buffer is capped at 262144 bytes and one decoded scratch at 196608 bytes, reserved before decoding. Thus maximum raw/scratch/copy/metadata payload memory is 2060288 bytes per session (object/allocator overhead must also be bounded and measured in later runtime acceptance). Count caps apply before allocation, not after a burst. This supports at most 30 seconds of outstanding generated-but-unconfirmed audio, not arbitrary response duration or unlimited API-process concurrency. Global session admission/memory capacity remains a deployment decision.
Output scheduler reserves a 72000-byte (1500 ms) sliding delivery window: T + R + next_message_bytes <= 72000, plus transport byte/count capacity. It transfers admitted PCM from G only when credits permit; it never dumps a generation burst into the browser. The remaining margin to the browser's 96000-byte limit covers scheduling/report cadence. Browser backlog retains its independent 96000-byte AND 100-message limit. A progress increase releases only 48 * delta_played_ms bytes from that ref's R after validating it against sent_bytes; rounded fractions remain conservatively outstanding. Identical reports release no credits. Transfer reservations to sent accounting atomically on send completion and release failed/cancelled reservations exactly once. At acknowledged retirement (or terminal session teardown), release that ref's remaining R exactly once through a private retirement-credit marker; atomically mark it released and subtract only its then-outstanding ledger balance. Valid final progress may first reduce R; retirement releases only the remainder. Duplicate progress, cleanup acknowledgements, retirement or teardown cannot release it again. This credit release is capacity bookkeeping, not playback evidence: retain frozen generated_bytes, sent_bytes and last_valid_played_ms in the bounded tombstone, including discarded/unconfirmed amounts. Never set played equal to sent/generated or zero evidence counters to manufacture confirmation. Discard cancelled G/T once under their reservation ownership without changing sent/played counters. Normal fully confirmed retirement has zero remaining R and needs no cleanup acknowledgement under 7.1.1; any retirement with unconfirmed audio while continuing a usable session requires acknowledged cleanup; terminal teardown may release resources but never permits continuation. Do not release R merely on interruption, window expiry, terminal generation or cleanup dispatch. Credit release cannot satisfy any missing cleanup/authorization/commitment barrier or itself trigger response.create; 7.1.6 must independently pass. Reported progress cannot free an uncompleted send, widen any cap or grant authority.
Delivery messages normally pack up to 9600 bytes; cap queued/in-flight output messages at 100 and scheduler reservations at 64 descriptors. Per-connection ingress/egress/control count limits remain as in 7.1.3. Scheduler waits off the provider receive loop for credit; provider control, speech-start, commitment, cancellation and cleanup events continue to be processed while audio waits. Retain a bounded control lane with interruption/terminal controls ahead of unsent audio, preserving ordering for already sent bytes and audio markers. Socket sends have deadlines and must not block the provider receiver. Do not stop reading provider events as flow control: there is no assumed provider-side generation pause command. Decode/admit each delta only within reservoir/scratch limits; fail safely on exhaustion while still attempting bounded cancellation/close.
Playback-stall detection is per reference, only while its state is open or sealed, playback has not been interrupted/stopped for cleanup, and successfully sent bytes contain at least one reportable unplayed whole millisecond (floor(sent_bytes / 48) > last_valid_played_ms). Finalizing, interrupted and retired refs are ineligible even if their retained sent/played evidence differs. On entering eligibility, initialize a fresh backend monotonic 5-second deadline and unique private timer identity for that ref; do not inherit another ref's send time, progress time or deadline. A first send with only a submillisecond remainder is not eligible; a later successful send that makes a whole millisecond outstanding starts the deadline then. Strictly increasing valid progress for that eligible ref renews its own deadline with a new timer identity if it remains eligible; reaching no reportable remainder invalidates the timer. Newly reportable output after that point starts a new identity/deadline. Another ref's progress, provider generation and equal reports cannot renew it; pause/mute cannot extend it indefinitely. A genuinely eligible ref with no increasing progress for 5 seconds fails LIVE_BUFFER_OVERFLOW/1013.
Interruption ownership and the state transition to finalizing must atomically invalidate the timer identity with stopping admission/delivery, before browser stop/flush controls. Normal-tail cleanup also invalidates it when cleanup takes ownership. Do not carry a playback-stall deadline into final reporting or cancellation/context cleanup, and do not rearm it on final progress or a duplicate interruption. Each queued timer callback must reenter the same serialized state decision and verify session usability, matching ref/timer identity, current eligibility and actual monotonic deadline expiry before failing. If finalization wins that decision, an already queued callback is a no-op; if a genuine eligible stall failure wins first, the session stays failed and later interruption cannot revive it. Stale callbacks from retirement, a progress renewal or a previous eligibility interval are no-ops. These timer identities remain private.
An unreportable <1 ms tail consumes credit/backlog until conservative cleanup/retirement, but cannot trigger stalled-playback failure. Finalizing refs retain their R ledger pending acknowledged retirement and the independent final-progress/cancellation/cleanup deadlines in 7.1.2; a cleanup timeout still fails LIVE_CONTEXT_SYNC_FAILED. In-flight T remains subject to its separate 5 s send deadline; interruption does not excuse send uncertainty or relax transport limits. A healthy 100 ms reporter playing at real time frees credits even if generation finishes early. At B's 30-second/slab/descriptor limit, refuse the next delta before allocation, cancel the correlated response, stop admissions/delivery and fail LIVE_BUFFER_OVERFLOW/1013. Unsupported output beyond the bounded backlog is a terminal capacity failure; do not misreport it as browser slowness. Provider-message, input and control caps retain their independent errors. Never silently drop audio while the session continues. On interruption, discard unsent G/T as cancelled, preserve exact sent/played/generated counters for acknowledged context cleanup, and suppress late old output.
#### 7.1.6 Transcript classes, turn eligibility and response release
User transcription is independent ASR of committed input, not assistant response completion. Map private input item identity to its original application turn at speech-start/commit. A delayed authorized user transcript emits the existing transcript shape with role=user, original turn_ref and the provider's partial/completed state even when a newer turn is active or the older request was superseded. It must not change current-turn eligibility, resurrect old work, trigger response creation or be displayed under the newest turn. Revalidate session/actor/access epoch before delivery; revoked/closed-session transcripts are suppressed. Retain input mappings/tombstones until session close with at most 256 input turns per session (engineering default); fail rather than guess an expired mapping or evict a pending transcript. Unknown input correlation is an observable protocol failure. Identical transcription events are no-ops; do not synthesize text on ASR failure.
Assistant transcripts/audio/tool output use private response/item/call-to-turn correlation. An assistant transcript done event is not proof of successful generation or audible completion: it may occur on cancellation. After actual interruption/supersession, suppress late assistant partial/done/completed events and tool outputs; they cannot restore completed display state or output audio. Already visible interrupted assistant text stays marked interrupted, without invented precise truncation. Delayed user transcripts are expressly exempt from that assistant-only suppression rule.
Normal exchange completion requires a terminal successful response, no pending tool/continuation or unsent G/T, and valid progress confirming all whole-millisecond output. An unconfirmed submillisecond tail receives conservative private cleanup before subsequent response release without automatically relabeling an otherwise completed exchange interrupted. For that normal tail, no active response needs cancellation and no interruption/final-report window is restarted; freeze its existing maximum reportable progress, transition the ref to finalizing with its stall timer invalidated, acknowledge private truncation, then retire the ref before subsequent response release. A new user turn after normal completion emits user_speech_started only; completed transcripts/sources retain their state. Actual interruption means unfinished generation/tool work, unsent audio or meaningful unplayed audio existed when genuine new speech started. Emit turn_interrupted only for that affected old turn. A pending request superseded before any assistant output is cancelled internally; do not fabricate an interrupted answer/transcript. Completed generation with queued playback is still interruptible.
Use a private monotonic current-turn generation token independent of access_epoch. A genuine speech start advances it, establishes a speaking input turn, makes older unfinished/pending work ineligible and adds every affected older response to the session cleanup set. Duplicate provider event IDs, or repeated speech-start for the same mapped input item/start position, do not advance it or restart cleanup. Distinct authenticated provider input item/start identities in forward media order are genuine subsequent speech; a known older item or delayed older start is not a new turn. Contradictory identities/ordering fail safely. Replays do not become genuine simply because their event_id differs. None of these private IDs/tokens is sent to the browser.
For every initial response.create, one serialized backend release decision must establish: (1) session_ready and usable session; (2) current input turn is the unsuperseded token holder; (3) correlated speech-stop and provider input_audio_buffer.committed confirmation identify its input item, not a commit for an earlier utterance; (4) actor/session/ownership/expiry/current authorization and pinned access epoch still match; (5) all older generation-terminal, final-progress, cancellation and context-cleanup barriers in the session cleanup set are satisfied; and (6) no conflicting active response or previously consumed initial-create intent exists. Input transcription completion is not a release prerequisite. The operator-only diagnostic text harness instead requires a provider-confirmed created input item; this exemption neither relaxes audio commitment nor adds a public text route. Cleanup finishing while input is still speaking or uncommitted clears only that barrier; it does not create a response.
Reserve/consume one initial-create intent per current turn before sending, privately correlate response.created to it (serialized single outstanding creation and backend-only metadata), and never blindly retry an uncertain send/acknowledgement. Uncertain creation closes the session; it cannot generate a second response. This is application exactly-once admission within the session, not a claim of provider network idempotency. Duplicate commit, stop, terminal, tool or cleanup events only reevaluate the gate.
A tool continuation is distinct from initial creation: authorize the existing canonical result once for its owning current-turn token and completed private call ID/hash, wait for the originating response's terminal tool-call state, send its matching function result once, then consume one continuation intent for that completed authorized call set. All input/authorization/cleanup/current-turn gates still apply. Multiple calls in one response produce one continuation after that authorized call set completes; duplicates never produce parallel responses or repeat results. The intent/result ledger is bounded to 256 entries per session; exhaustion fails explicitly. Late results from superseded turns are suppressed, not fed into new context. No public event shape or canonical tool output changes.
If T3 genuinely starts while T1 cleanup is pending and T2 has not been released, supersede T2, cancel its admitted retrieval/creation intents, and make T3 current. Continue existing T1 cleanup with unchanged deadlines and add any T2-generated output requiring cleanup; never restart old windows on the new turn. Bound the pending cleanup set by existing response/ref/intent limits. Cleanup callbacks record only their own response/barrier identity and cannot capture a turn to release later. Reevaluate the shared gate against the latest token and all outstanding barriers; T1's acknowledgement cannot release T2. If T3 is speaking, wait; if only T2 is committed, wait for T3's commitment. Retain superseded user input for authorized display/context as mapped user speech, without executing a response to it. Provider commitment ordering/correlation and late-event behavior are assumptions to prove in later authorized runtime acceptance.
Transcript status is partial, completed or interrupted. The backend assigns turn_ref at trusted user speech start and retains original-turn correlation for delayed events. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
Interruption, final progress, acknowledged context cleanup and late-output suppression follow 7.1.2; generation completion is not playback completion. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
### 7.2 Internal model tool — `search_knowledge`
@@ -372,9 +372,9 @@ Keep source identity rows as tombstones if allowed. `available` in API is comput
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
| close_reason, error_code | text nullable | Normalized reason |
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. No SDP replay field is required for the proposed Gemini WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential.
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. No SDP replay field is required for the OpenAI Realtime WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential.
API instance owns the direct Gemini Live WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
API instance owns the direct OpenAI Realtime WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
### 6.2 audit_events
@@ -2,6 +2,8 @@
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
Phase 0 amendment (2026-10-08): OpenAI Realtime replaces Gemini Live for voice only. The [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md) supplies the current backend phase sequence and conditional 3-5 day estimate; prior four-day schedule is historical. See [Phase 0 prerequisites and results](../guides/realtime-agent-phase0.md). Extraction/embeddings and HTTP/search contracts are unchanged.
## 1. Purpose and authority
Implement the conditional four-day Live document MVP in
@@ -31,7 +33,7 @@ declared format/structure/resource limits must run without developer changes.
| Upload | New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count |
| QC | Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state |
| Retrieval | Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need |
| Voice | Direct Gemini Live audio over backend WSS; shared LangChain knowledge tool |
| Voice | Direct OpenAI Realtime audio over backend WSS; shared LangChain knowledge tool |
| Evidence | Current-session provider transcripts/sources; durable owned session/tool diagnostics |
| Deferred | Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI |
| Settings | Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities |
@@ -214,13 +216,15 @@ If the browser times out, it queries the turn by client request ID. Retrying the
## 9. Live lifecycle
Create a fresh owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to direct Gemini Live WSS, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
Create a fresh owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to direct OpenAI Realtime WSS, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations.
States: `creating → connecting → connected → closed`; any nonterminal state may fail/close. Adapter-confirmed setup defines connected, not client assertions. Use deadlines, bounded audio buffers and TTL; provider calls occur outside database transactions. Restart marks previous nonterminal sessions failed and attempts cleanup.
Follow-up questions resolve the last unambiguous document/article, but retrieve fresh evidence. New topics clear old anchors; ambiguous references prompt clarification. Missing/conflicting support is disclosed; tool/provider failure is a technical error. On interruption flush playback, mark output partial/interrupted, cancel outstanding work where possible and discard late results. Logout/expiry/removal close sessions. Reconnect requires reconciliation and a new session; provider context recovery is not promised.
Follow-up questions resolve the last unambiguous document/article, but retrieve fresh evidence. New topics clear old anchors; ambiguous references prompt clarification. Missing/conflicting support is disclosed; tool/provider failure is a technical error. On actual interruption flush playback, mark affected unfinished assistant output partial/interrupted, cancel response-specific work and discard late assistant/tool results. A normally completed exchange stays completed; delayed authorized user transcripts retain their original turn. Logout/expiry/removal close sessions. Reconnect requires reconciliation and a new session; provider context recovery is not promised.
Apply the frozen [API Section 7.1](RAG-Phase1-API-Catalog.md) lifecycle/bounds before runtime acceptance: retain refs through queued playback, accept final reports within the bounded interruption window, await private cleanup acknowledgement before continuation, and close on synchronization/overflow failures. The [Phase 0 report](../guides/realtime-agent-phase0.md) records actual whisper-1/fa configuration, retirement dates and read-only calibration preflight; no automatic provider migration. Use both VAD flags false and backend-only targeted cancellation; a narrowly correlated no-active-response race is benign by itself but still requires terminal confirmation and cleanup. Separate the 30 s generated/undrained backlog from paced 1500 ms delivery credits and two-second transport/browser buffers; keep provider controls responsive. Only eligible open/sealed refs have playback-stall timers; finalization atomically invalidates their identities, queued callbacks recheck current state/identity, and each new eligible interval starts fresh. Acknowledged retirement releases remaining credit exactly once while preserving generated/sent/played evidence; final-progress/cancellation/cleanup deadlines and all release barriers remain independent. API 7.1.6 gates exactly-once response/continuation admission on correlated current input commitment, valid authority/epoch and every cleanup barrier. Genuine later speech advances a private current-turn token; old cleanup callbacks cannot release superseded work. These are documentation obligations, not implemented runtime evidence.
Capture/resample client audio and convert returned PCM for playback as specified in architecture Section 8.5. Test real Persian names, dates, percentages and amounts. CTI/Asterisk is outside this web MVP and would need an explicitly commissioned audio bridge.
@@ -272,7 +276,7 @@ and reviewer availability; fixed funded extraction/embedding/Live identities and
vector dimension; account/quotas/Persian capability proof; hosting/connectivity;
session TTL, retention/purge, quantitative quality/latency targets and actual
presentation date. General browser upload, all four example structures,
LangChain, existing embedding reuse and direct Gemini Live are confirmed direction.
LangChain, existing embedding reuse and direct OpenAI Realtime are confirmed direction.
Exact-output retention/review, FAQ inclusion decisions and their forward schema/
HTTP mechanisms in this revision are implementation proposals made concrete for
@@ -15,7 +15,7 @@ from the browser, inspects uncertain extraction, activates ready documents and
starts a Persian voice conversation. Users hear supported document answers and
see retrieved sources plus available provider transcripts.
LangChain supplies the RAG/tool integration boundary. Gemini Live manages
LangChain supplies the RAG/tool integration boundary. OpenAI Realtime manages
native audio; the backend owns secrets, identity, tools and scope. Existing
ingestion/embedding Phases 1-4 remain the processing foundation.
@@ -117,7 +117,7 @@ Request clarification rather than choose an arbitrary similarity match.
Interrupt with the Persian equivalent of "Wait, only tell me the exceptions."
Stop/clear queued playback, mark partial output interrupted and suppress cancelled
tool results. A late result cannot restart the prior answer.
tool results. A late result cannot restart the prior answer. The sixteen contract walkthroughs in [API 7.1.4](RAG-Phase1-API-Catalog.md) cover final progress after interruption, completed generation with queued playback, later output segments, duplicate/invalid progress, missing reports and frame/queue overflow, plus fast generation versus stalled playback, cancellation races, delayed user transcription, speaking/uncommitted input and third-turn supersession; these are expected behaviors, not executed browser acceptance.
For no supporting evidence, state the limitation. For conflicting evidence,
disclose conflict or ask clarification. For query embedding/search/provider