# RAG Assistant — Phase 1 API Catalog Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects one backend adapter. Gemini remains the temporary default because an OpenAI Realtime voice key is unavailable.** Reservation, authenticated stream and operator smoke share the selected model/voice/profile. Only the selected voice key is required; there is no fallback or frontend provider selector. Legacy PROVIDER and existing GEMINI_* settings remain supported; conflicting provider aliases fail configuration. Dedicated OPENAI_REALTIME_* settings do not change embedding credentials. Browser PCM16LE remains mono 24 kHz in both directions. Pinned reservations cannot switch providers on connection or replay. Gemini interruption requiring unverified context truncation closes safely; OpenAI keeps its existing native cancellation/truncation contract. Canonical search, original documents, frozen profiles and owner/replay/revocation rules remain unchanged. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md). Version 1.3 آ· 2026-10-07 آ· Current Live document MVP contract; planned endpoints are not claimed operational. Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1. ## 1. Transport and common conventions Base path `/api/v1`; UTF-8 JSON except multipart upload; same-origin HTTPS. UUIDs identify application records. Timestamps are UTC RFC3339. `null` means unavailable, not an invented source location. Unexpected request fields return 422. Example UUIDs are illustrative. Secure HttpOnly `rag_session` cookie authenticates requests. Login and all mutations enforce trusted Origin; authenticated mutations also require `X-CSRF-Token`. `/me` returns a CSRF token for refresh. No frontend persistent provider key, organization ID override or model override is accepted. Roles: `admin` and `user`. Both can create owned voice conversations and read/control their own Live state. Only admin manages uploads, review, retry and selection. Hidden resource access returns 404. Admin does not implicitly own all conversations. Full text chat/history, delete UI and settings mutation are deferred. Lists use `limit` (default 20, maximum 100) and opaque `cursor`. Stable ordering is `(created_at DESC,id DESC)` except messages, ordered by ascending `sequence_no`. Responses use `{items:[],next_cursor:null}`. Unknown/invalid cursor returns 422. No total count is promised. `X-Request-ID` response header and `error.request_id` correlate logs. Servers generate one if none is valid. `Idempotency-Key` is required on upload, manual ingestion retry and delete; UUID `client_request_id` is required in create-conversation, chat and create-live bodies. Keys are scoped to actor/organization and operation as specified below. Reuse with different normalized input returns 409. Proposed field limits: deferred text message 8000 characters; assistant name 120; instruction 8000; search query 2000; conversation title 120; document title 200; review note 2000. File limits/formats and audio frame caps come from deployment configuration and are exposed as capabilities where useful. These are implementation defaults to confirm, not provider guarantees. ## 2. Endpoint inventory | ID | Method and path | Access | Success | Delivery | | --- | --- | --- | --- | --- | | A01 | POST `/auth/login` | Public, trusted Origin | 200 + cookie | MVP | | A02 | POST `/auth/logout` | Authenticated; expired/missing session accepted | 204 | MVP | | A03 | GET `/me` | Authenticated | 200 | MVP | | D01 | POST `/documents` | Admin | 202 | MVP | | D02 | GET `/documents` | Admin | 200 | MVP | | D03 | GET `/documents/{document_id}` | Admin | 200 | MVP | | D04 | POST `/documents/{document_id}/retry` | Admin | 202 | MVP | | D05 | DELETE `/documents/{document_id}` | Admin | 202 | User-authorized server import (2026-10-18) | | D06 | GET `/documents/{document_id}/extraction-review` | Admin | 200 | MVP | | D07 | POST `/documents/{document_id}/extraction-review/decisions` | Admin | 200 | MVP | | K01 | GET `/knowledge-selection` | Admin | 200 | MVP | | K02 | PATCH `/knowledge-selection` | Admin | 200 | MVP | | F01 | GET `/configuration` | Authenticated | 200 | MVP | | F02 | PATCH `/configuration` | Admin | 200 | Deferred | | C01 | POST `/conversations` | Authenticated | 201 | MVP: voice only | | C02 | GET `/conversations` | Owner | 200 | Deferred | | C03 | GET `/conversations/{conversation_id}/messages` | Owner | 200 | Deferred | | T01 | POST `/chat` | Owner of text conversation | 200 or 202 | Deferred | | T02 | GET `/conversations/{conversation_id}/turns/{client_request_id}` | Owner | 200 | Deferred | | V01 | POST `/voice/sessions` | Owner of voice conversation | 201 or 202 | MVP | | V02 | GET `/voice/sessions/{session_id}` | Owner | 200 | MVP | | V03 | GET `/voice/sessions/by-request/{client_request_id}` | Owner | 200 | MVP | | V04 | POST `/voice/sessions/{session_id}/close` | Owner | 200 | MVP | | H01 | GET `/health/live` | Deployment health access | 200 | MVP | | H02 | GET `/health/ready` | Deployment health access | 200 or 503 | MVP | 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 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. ## 3. Authentication ### A01 — Login ```json {"username":"demo.admin","password":""} ``` ```json {"user":{"id":"01000000-0000-4000-8000-000000000001","username":"demo.admin","role":"admin","organization_id":"02000000-0000-4000-8000-000000000001"},"csrf_token":"","expires_at":"2026-10-05T18:00:00Z"} ``` Credentials invalid: 401 `INVALID_CREDENTIALS`; throttled: 429. Do not distinguish missing username from wrong password. Expiry above is illustrative. Set Secure/HttpOnly/SameSite=Lax cookie; rotate tokens after successful login. ### A02 — Logout No body. Revoke current session, clear cookie and close owned live sessions linked to it. Repeated logout returns 204. For a valid session require CSRF; missing/expired session may simply clear cookie after Origin validation. ### A03 — Current identity No body. Same identity/CSRF/expiry shape as login. Missing/expired session returns 401 `AUTH_REQUIRED`. ## 4. Documents and selected knowledge ### D01 — Upload `multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive. Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PNG with byte/signature/package/image bounds and correct MIME. D01 accepts new files without a repository filename/hash allowlist. The four examples are acceptance fixtures, not upload eligibility. Stream/spool within configured limits; do not buffer an unbounded request. These engineering defaults do not imply every layout is extractable or total corpus capacity is unlimited. D01 HTTP transport is implemented; see the Phase 3 handoff. ```json {"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false} ``` 202 acknowledges durable metadata/job creation, not completed processing. Replay same upload returns these stable identities with current processing state and header `Idempotency-Replayed: true`. Scope key to organization; hash bytes and normalized title. 413 `FILE_TOO_LARGE`, 415 `UNSUPPORTED_FILE_TYPE`, 422 `INVALID_FILE`, 409 `IDEMPOTENCY_CONFLICT`. A parser failure after acceptance is represented by document status, not a later HTTP response to upload. ### D02 — List Query: common pagination; optional `status=queued|processing|ready|failed`, `is_active=true|false`. Exclude deleted documents. Items use the D03 shape, except potentially omit verbose error detail. Return current `knowledge_revision` alongside the list. ### D03 — Detail / processing polling ```json {"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}} ``` `searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail includes `review_required`, `review_state`, frozen `ocr_review_required` and `extraction_quality_decision` (null before complete extraction). D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID. ### D04 — Retry failed processing No body; required `Idempotency-Key`. Eligible only for failed undeleted document and retained original. Requeue same job, reset attempt count, increment retry generation and audit. Same key replays without incrementing twice. ```json {"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","retry_generation":1} ``` 409 `DOCUMENT_NOT_RETRYABLE` for running/ready/unrecoverable failure; 404 hidden/deleted. Review-required retry becomes eligible only after all currently pending evidence-bound approvals exist; additional pages can require later review. An unapproved candidate returns 409 `EXTRACTION_REVIEW_PENDING`; rejection stays failed. Successful factual-corpus review is a separate precondition where required. No ready document is reindexed through retry. The retry-key record is retained in audit metadata with a database uniqueness constraint. ### D06 - Read retained extraction/factual review Admin-only, paginated bounded review candidates. No provider calls. Return 404 for hidden/deleted documents. A document with no pending candidates returns an empty items list. Example application shape: ```json {"document_id":"10000000-0000-4000-8000-000000000001","status":"failed","review_required":true,"items":[{"evidence_sha256":"","review_kind":"extraction","location":{"page":1,"section":"pdf/page/1"},"blocks":[{"block_id":"pdf/page/1/block/1","text":"","group_id":null}],"required_checks":["readability","order","completeness","numbers","dates","negation","exceptions"],"decision":null,"preview_path":"/api/v1/documents/10000000-0000-4000-8000-000000000001/extraction-review//preview"}],"next_cursor":null} ``` Serve the retained image on authenticated GET `/documents/{document_id}/extraction-review/{evidence_sha256}/preview`. This is a D06 subresource with the same admin/organization/candidate checks, configured byte/pixel limits, a validated image MIME and Cache-Control: no-store. It accepts no raw path or redirect and exposes no internal storage key. For factual_corpus candidates, preview_path may be null and blocks are grouped Q&A and their governing context with real source locators from the retained complete extraction. Context association is deterministic; ambiguous scope fails visibly. required_checks then includes factual authority, whole-pair association, behavioral separation and placeholders. Locators/digests are actual server values; illustrative strings are not API values. ### D07 - Decide on retained evidence Required Idempotency-Key; normal admin Origin/CSRF checks. Server derives actor. One candidate decision per request; UI may submit multiple requests. ```json {"evidence_sha256":"","decision":"approve","checked":["readability","order","completeness","numbers","dates","negation","exceptions"],"note":"Compared retained extraction against the original page.","excluded_group_ids":[]} ``` 200 returns document_id, evidence_sha256, decision and review_required indicating whether current pending decisions remain. It does not enqueue, activate or mark ready; D04 resumes the same failed job with its own key. Allow approve/reject only. Require a nonblank bounded note; approval checked must match the server-required check set. For extraction, excluded_group_ids must be empty. For factual_corpus, permit only whole existing Q&A group IDs to exclude unapproved facts, behavioral entries or live-data placeholders. Store the inclusion manifest separately; never edit original/faithful extraction. An empty eligible factual set cannot be indexed. Scope idempotency to organization/actor/document/extraction_review/key; hash the canonical decision, checks, note, evidence digest and excluded group IDs. Replay is resolved before new state checks but after authorization; it returns the saved decision without mutating current candidate state. Changed payload returns 409 IDEMPOTENCY_CONFLICT. A new conflicting decision for an already decided candidate returns 409 REVIEW_ALREADY_DECIDED. Removed/superseded evidence, wrong failed-job state or profile/source mismatch returns 409 REVIEW_STALE. Invalid digest/check/group shape returns 422 VALIDATION_ERROR. A valid digest alone grants no access. Recompute/validate trusted retained candidate identity under the document/job locks; don't trust client blocks, paths, models or reviewer fields. Rejecting keeps zero publication and a safe failure reason. Lost worker ownership cannot attach candidates; an admin cannot approve a fresh OCR response using an old digest. ### D05 — Delete (enabled HTTP/UI, 2026-10-18) JSON body: `{"expected_revision": N}` (positive strict integer; extra fields rejected). Required `expected_revision` is the current knowledge revision; required idempotency key. The authenticated administrator route requires Origin/CSRF validation and uses a bounded 1024-byte JSON body. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response. ```json {"document_id":"10000000-0000-4000-8000-000000000001","deleted":true,"knowledge_revision":3,"access_epoch":2,"cleanup_status":"pending_policy"} ``` 202; 409 `REVISION_CONFLICT` on stale initial request. Replay same delete/key returns recorded result before revision validation. A new delete request for an already-deleted owned document can return its tombstone result without changing revisions. No read or search route restores eligibility. ### K01 — Get selection ```json {"revision":1,"access_epoch":1,"document_ids":[]} ``` ### K02 — Replace selected set This replaces the entire set, not a delta. UI reads current selection before toggling a document. ```json {"expected_revision":1,"document_ids":["10000000-0000-4000-8000-000000000001"]} ``` ```json {"revision":2,"access_epoch":1,"document_ids":["10000000-0000-4000-8000-000000000001"],"conversations_invalidated":false} ``` Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected IDs in details; no partial update. Hidden ID: 404. Stale revision: 409 `REVISION_CONFLICT`. No-op preserves revision. Removing an active ID increments epoch and sets `conversations_invalidated=true`; all older organization conversations become unusable for new turns. After a timeout GET current state instead of blindly repeating with an old revision. ## 5. Configuration (read-only in MVP) ### F01 — Read ```json {"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":[""],"max_upload_bytes":20971520,"ocr_review_required":true}} ``` Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities. ### F02 — Update (deferred) ```json {"expected_revision":1,"assistant_name":"HR Assistant","instruction":"Use formal Persian and state when supporting evidence is missing."} ``` 200 returns F01 with incremented revision. Both fields are required; no-op preserves revision. Stale value: 409 `REVISION_CONFLICT`. Text applies on subsequent turns; existing live session keeps its snapshot until restarted. Settings cannot relax system authorization or grounding rules. ## 6. Conversations and deferred text ### C01 — Create ```json {"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"voice","title":"Working hours"} ``` ```json {"id":"60000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours","status":"active","access_epoch":1,"created_at":"2026-10-05T09:05:00Z"} ``` The current MVP accepts `mode=voice` only; text/mixed requests return 409 `MODE_MISMATCH`. Follow-up text support uses a separate mode and must not silently alter the voice contract. Title optional. Idempotency scope `(owner,client_request_id)`; same payload replays original 201. Different payload 409. New conversation snapshots current epoch. Voice history cannot be continued as text in Phase 1. ### C02 — List own conversations (deferred history UI) Common pagination, optional `mode`. Items use C01 response plus `updated_at`; derive `status=stale` when epoch differs. Status values: active, stale, closed. List excludes other users regardless of role. ### C03 — Read messages (deferred) Common pagination, ascending sequence. Voice can return no durable messages: current-session answer transcripts are delivered through Live events when available; durable full voice history is deferred. Old text history remains viewable even when stale. ```json {"conversation_id":"60000000-0000-4000-8000-000000000001","conversation_status":"active","items":[{"id":"70000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","sequence_no":1,"role":"user","content":"What are the Thursday opening hours?","created_at":"2026-10-05T09:06:00Z","sources":[]}],"next_cursor":null} ``` Assistant items also expose `turn_status` and source objects. Failed turns remain visible as state, not fabricated assistant answers. A user message may exist without an assistant reply; UI follows turn status. ### T01 — Submit text turn (deferred) ```json {"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"What are the Thursday opening hours?"} ``` ```json {"conversation_id":"60000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","status":"answered","message_id":"70000000-0000-4000-8000-000000000002","answer":"The illustrative working-hours document states Thursday closing is noon.","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"Illustrative Thursday hours: 08:00 to 12:00.","location":{"page":2,"section":null},"available":true}],"error":null} ``` 200 returns terminal execution: answered, needs_clarification, insufficient_information or failed. `answer`/`message_id` are null on failed, with normalized error. A successfully processed unsupported question uses insufficient_information, human-readable answer and usually empty sources. Failed generation is not reported as a successful answer. 202 returns a running turn shape with `answer:null`, `message_id:null`, empty sources, `error:null` and `Location` pointing to T02. This occurs on duplicate running request or when the initial response deadline expires while the owned task is still running. Do not start a second task. Client disconnection must not silently create duplicate execution. Scope key `(conversation_id,client_request_id)`. Changed message under same key: 409. Another different request while one runs: 409 `CONVERSATION_BUSY`. Wrong mode: 409 `MODE_MISMATCH`. Stale epoch: 409 `CONVERSATION_STALE`. Admission failures use the common HTTP error envelope; failures after a turn is persisted use its failed terminal result. Retry completed failures only with a new request ID. ### T02 — Recover/poll turn (deferred) 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 — backend-selected provider; frozen application audio/events The selected provider is backend-managed Gemini Live or OpenAI Realtime. The OpenAI-specific mechanisms below describe the preserved Realtime adapter; the Gemini adapter uses native setupComplete, voiceActivity, toolCall/toolResponse and transcription. Missing verified input boundaries fail safely. Interruption requiring unheard-audio context repair closes the session rather than inventing a cancellation/truncation acknowledgement. The browser still uses 24 kHz mono PCM16LE; Gemini input conversion to 16 kHz occurs inside the adapter. 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. Phase 0 freezes the application audio/event fields below. Technical implementation evidence and remaining live acceptance prerequisites are recorded in the Phase 2 repair report. 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. OpenAI Phase 1 speech configuration is server-only. New reservations freeze the exact requested transcription/language mode/prompt/vocabulary, server VAD parameters and optional noise reduction under execution_profile.audio_input. The same values must be acknowledged before readiness. Existing defaults remain; both automatic response/interrupt flags stay false. A missing or mismatched OpenAI audio snapshot is unusable at stream admission before provider opening. Replay retains the original identity and snapshot; never backfill it. Gemini profiles and all public fields/events remain unchanged. See the [Phase 1 handoff](../guides/openai-persian-speech-phase1.md) for settings and unrun real-speech/browser gates. OpenAI Phase 2 additionally freezes `style_revision` and `effective_instructions_digest` (SHA-256 of exact UTF-8 composed instructions). Missing/mismatched style fields reject stream admission before provider opening; replay never rewrites snapshots. Effective instructions require provider acknowledgment. Gemini instructions remain unchanged. Voice changes require fresh sessions; candidate voices remain unverified until listening/interruption acceptance. See [Phase 2 handoff](../guides/openai-persian-delivery-phase2.md). OpenAI playback-speed configuration is server-only: `OPENAI_REALTIME_SPEED` (default 1.0, finite range 0.25..1.5) is frozen as `execution_profile.audio_output_speed` and acknowledged as `audio.output.speed` before readiness. Changing it requires a new reservation; replay retains the original snapshot and old/mismatched snapshots fail stream admission. PCM remains 24 kHz and playback credit uses actual provider-generated sample duration. Gemini profiles and public events are unchanged. OpenAI Phase 3 freezes optional `execution_profile.reasoning`: null when omitted, or `{"effort":"low"}` / `{"effort":"medium"}` for the explicitly supported `gpt-realtime-2.1` and `gpt-realtime-2.1-mini` candidates. Unsupported explicit combinations reject configuration before connection. Enabled reasoning is sent as private session reasoning and must be acknowledged before readiness. Disabled reasoning is omitted on the wire; provider-enabled reasoning is rejected when unrequested. Missing enabled snapshots and changed effort/model reject admission; replay retains identity and never rewrites snapshots. Gemini/public contracts are unchanged. See [Phase 3 report](../guides/openai-persian-understanding-phase3.md). ### V01 — Create session (HTTP) ```json {"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001"} ``` ```json {"session_id":"a0000000-0000-4000-8000-000000000001","conversation_id":"61000000-0000-4000-8000-000000000001","status":"connecting","stream_path":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001/stream","expires_at":"2026-10-06T09:30:00Z","poll_url":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"} ``` Voice conversation must be owned and current-epoch. Reserve session before provider creation. Scope key `(owner,client_request_id)`; hash normalized conversation/create options, with no SDP. Changed payload is 409. One nonterminal session per conversation. Duplicate creation returns 202 and the existing ID/state; completed replay returns 201 with the same still-eligible session. Replay never creates another provider connection. Closed/failed/expired returns 409 `LIVE_SESSION_UNUSABLE`. No persistent provider secret or provider credential is returned. Backend adapter installs tools/Persian policy and enables available transcription before marking usable. Provider timeout leaves failed/uncertain reservation: inspect with V03, never blind recreation. 503 can represent a capability failure before reservation. `connecting` is not proof of working audio. ### V02 — Poll state, diagnostics and recent retrieved sources (HTTP) ```json {"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-06T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-06T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","excerpt":"","location":{"page":1,"section":""},"available":true}]}]} ``` Illustrative payload; not an extracted source quotation. At most 20 recent results, chronological, deduplicate by tool_call_id. Sources are retrieved evidence unless exact answer attribution is verified. Redact revoked excerpts and mark unavailable. States: creating, connecting, connected, closed, failed. Poll approximately every 2 seconds while active; stop at terminal state. Polling is not durable transcript recovery. A client cannot claim connected state or inject a trusted tool result. ### V03 — Recover creation by request ID (HTTP) 200 returns V01's session/path shape if reservation remains eligible, otherwise terminal state and `stream_path:null`. Owner-only, 404 if no reservation, never creates a session. Before starting a fresh request after media loss, reconcile/close the old session. The old path does not restore provider context. ### V04 — Close (HTTP) No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Already terminal returns its existing state. Close application stream/microphone/playback and attempt provider cleanup. Unresolved cleanup is logged and bounded by expiry; logout, auth expiry, epoch revocation and provider loss also close the session. ### 7.1 Application Live stream (WebSocket) 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. 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. 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":24000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}} ``` ```json {"type":"transcript","turn_ref":"live-turn-1","role":"assistant","text":"","status":"completed"} ``` ```json {"type":"sources","turn_ref":"live-turn-1","tool_call_id":"call-1","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","location":{"page":1,"section":null}}]} ``` ```json {"type":"turn_interrupted","turn_ref":"live-turn-1","cancelled_tool_call_ids":["call-1"]} ``` ```json {"type":"error","turn_ref":"live-turn-2","error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}} ``` Additional server events and the client playback control: ```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/other incomplete handled as technical failure; the validated audio-only output-token limit below is terminal but limited) 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; the exact captured OpenAI structured classifier is provider-protocol scoped, independent of model and voice, and must retain cancellation event-ID correlation plus terminal/cleanup confirmation, 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 | | Detected uncommitted speech | 3072000 bytes (64 seconds) across trusted speech intervals, allowing 60 seconds of user speech plus up to four seconds of VAD padding; silence outside those intervals is excluded. Active intervals have an independent 65-second wall deadline from receipt of speech-start; stopped intervals require commitment within 15 seconds. These are lifecycle bounds, not claims about provider-retained PCM | | 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 closure requires a terminal successful response or the validated limited-audio outcome below (which never means a complete answer), 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, interrupted, or limited (assistant only). 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` Model arguments, identical for the internal text-query harness, later text chat and Live. The LangChain tool uses this schema while trusted dispatcher context supplies authority: ```json {"query":"What are the conditions and exceptions of the circular?","context":"The circular identified as source S1 in the preceding exchange."} ``` `query` required, 1–2000 characters; optional `context` proposed maximum 2000 characters, a conversation-resolved textual reference. Reject unknown fields. Context does not grant permission or turn previous model prose into evidence. No model-supplied organization/user IDs or paths; supported document filters remain deferred. Backend derives identity, current selected ready/active/undeleted scope, profile, bounded top_k/evidence size and execution IDs. Illustrative successful result; text/location must be populated from actual retained chunks, never from these placeholders: ```json { "status":"ok", "knowledge_revision":2, "sources":[{ "source_ref":"S1", "document_id":"10000000-0000-4000-8000-000000000001", "chunk_id":"30000000-0000-4000-8000-000000000001", "title":"Illustrative administrative circular", "text":"", "location":{"page":1,"section":""} }], "warnings":[] } ``` ```json {"status":"no_evidence","knowledge_revision":2,"sources":[],"warnings":["insufficient_support"]} ``` ```json {"status":"error","sources":[],"error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}} ``` `no_evidence` is completed retrieval with insufficient support, not a provider failure. The shared core requires a measured profile-specific cutoff for canonical evidence admission; absent calibration returns `error` with `CALIBRATION_REQUIRED`, never an invented default threshold. Operator inspection may return explicitly labeled uncalibrated candidates without claiming evidence sufficiency. Contradictory passages may be returned with `warnings:["conflicting_evidence"]`; ask clarification or disclose conflict instead of silently resolving policy. `error` also covers provider unavailable/profile mismatch/revoked context, with normalized codes and safe retryability. Document claims require current supporting passages; greeting/clarification may omit search. Locators use existing `location.page/section`. DOCX and image use page null, with table/row/Q&A or visual-group location in section. Same search backend/profile serves all extracted text. Source refs are unique across a turn and validated against returned evidence. Deduplicate by parent session/turn plus provider call ID and normalized argument hash. Same running call waits; same completed call replays only after fresh eligibility/epoch checks; changed payload conflicts. Cancelled/closed/stale-parent results are not sent back to generate a new answer. No tool request becomes a public REST upload/search endpoint. The MVP persists voice tool_calls independently of deferred text turns/messages/citations. Cancelled work is terminal failed with a cancellation reason and cannot be replayed to resume speech. ### 7.3 Internal continuation tool — `reuse_last_evidence` The 2026-10-12 Live repair amendment permits an unambiguous same-topic continuation from the latest successful, delivered evidence bundle in the same connection. The model supplies exactly `{}`; identity, scope, session and source selection remain backend-owned. Prior assistant prose is never evidence. New topics or insufficient evidence require canonical `search_knowledge`; ambiguous references require clarification. Automatic response chaining remains excluded. Before reuse and again before delivery/continuation, revalidate the owner/auth session, active Live session, access epoch, knowledge revision, and each original document/chunk's ready/active/undeleted/unpurged eligibility. A selection addition can change knowledge revision without changing access epoch and still invalidates reuse. Revocation follows the invalid-session contract; it never triggers a hidden replacement search. Without a reusable bundle, return `no_evidence` with `warnings:["fresh_search_required"]`, allowing an explicit model search. Attach evidence to the new turn using real document/chunk identities and turn-local source labels. Its `sources.tool_call_id` identifies the original retrieval; reuse creates no `tool_calls` row or embedding/retrieval execution. Revalidate the original saved result before every delivery. Interrupted/cancelled tool results are excluded. Fresh search replaces the topic bundle; failure and session termination clear it. No durable conversation history or cross-session cache is introduced. New reservations pin `evidence_policy_revision` and the effective instruction profile; existing reservations are never rewritten. ## 8. Health H01: 200 `{"status":"ok"}` when the process is alive. H02: 200 `{"status":"ready","ingestion":"available"}` or degraded ingestion marker if worker heartbeat is stale; 503 `{"status":"not_ready"}` for required DB/schema/storage failure. Health responses never disclose connection strings or provider keys. Provider outages surface in relevant business operations, not liveness. ## 9. Error envelope and mapping ```json {"error":{"code":"REVISION_CONFLICT","message":"Selection changed; reload and try again.","request_id":"req-example","retryable":false,"details":{"current_revision":3}}} ``` | HTTP | Codes / use | Client action | | --- | --- | --- | | 401 | AUTH_REQUIRED, INVALID_CREDENTIALS | Login; do not retry provider work | | 403 | FORBIDDEN, CSRF_INVALID | Show denial or refresh session token | | 404 | NOT_FOUND | Stop; do not expose ownership details | | 409 | REVISION_CONFLICT | Read latest selection/configuration | | 409 | IDEMPOTENCY_CONFLICT | Correct client request/key handling | | 409 | CONVERSATION_BUSY, CONVERSATION_STALE, MODE_MISMATCH | Poll current turn, start fresh conversation, or correct mode | | 409 | DOCUMENT_NOT_READY, DOCUMENT_NOT_RETRYABLE, LIVE_SESSION_UNUSABLE | Follow returned state | | 409 | EXTRACTION_REVIEW_PENDING, REVIEW_STALE, REVIEW_ALREADY_DECIDED | Refresh exact review evidence or follow the recorded decision | | 413/415/422 | FILE_TOO_LARGE, UNSUPPORTED_FILE_TYPE, VALIDATION_ERROR | Correct input | | 429 | RATE_LIMITED | Honor Retry-After; reuse key when retrying same operation | | 503 | DEPENDENCY_UNAVAILABLE | Show service failure; reconcile state before retry | Inside persisted jobs/sessions/tool calls, normalized codes include PROVIDER_TIMEOUT, PROVIDER_UNAVAILABLE, SEARCH_FAILED, PROCESS_INTERRUPTED, CONVERSATION_STALE, TOOL_CANCELLED and EXTRACTION_REVIEW_REQUIRED. Review-required is a controlled human-action failure, not an automatic transient-provider retry. INVALID_CITATION and failed text-turn responses belong to the deferred text contract. An HTTP 200 failed-turn result still represents application failure. Technical retryability does not authorize automatic regeneration under a new key. ## 10. Frontend implementation order and exclusions Prove real native audio/tools early. Build A01/A03, bounded upload/polling, D06/D07 review and D04 resume, selection, C01 voice creation, V01-V04/WSS and read-only F01 capabilities. Full T01/T02/messages and settings editing are deferred. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context. Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses. Current temporary Gemini capability failures before reservation are 503 `LIVE_PROVIDER_UNAVAILABLE` for missing voice credentials/profile access and `CALIBRATION_REQUIRED` for a missing/invalid/incompatible measured report. A configured profile is a prerequisite, not proof of provider access. These safe codes never return keys or native provider errors. HTTP authentication failures normalize to `AUTH_REQUIRED`, CSRF to `CSRF_INVALID`, hidden resources to `NOT_FOUND`, admission throttling to `RATE_LIMITED` with Retry-After, and unexpected dependency failures to `DEPENDENCY_UNAVAILABLE`. ### OCR supervisor deployment policy (2026-10-09) `INGEST_OCR_REVIEW_REQUIRED` defaults to true and is backend-only. New ingestion jobs freeze the boolean in `processing_profile.extraction.ocr_review_required` (the existing immutable document-owned snapshot for its one job). Workers and retries use that snapshot; absent fields in legacy profiles mean true. Preserve existing profile bytes/digests; do not backfill applied records. False permits clean OCR/vision output that passes existing automatic validation without a human extraction decision. It never waives non-OCR review, warning/integrity/coverage checks, independent factual-corpus approval, or explicit knowledge selection. Automatic extraction remains quality_decision=passed; mixed inspected/automatic PDFs use partially_reviewed with annotations only for inspected locators. Neither automatic OCR nor its portions in mixed PDFs creates a human review annotation/audit record. Ready publication remains inactive. Retained pending or rejected candidates still block retry; deployment changes cannot waive them. F01 capabilities.ocr_review_required is current deployment policy; D03 reports frozen ocr_review_required, review_state and extraction_quality_decision. See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md). ### Phase 3/4 additive admission diagnostics (2026-10-09) V01, by-request recovery and V03 polling expose calibration_status with values calibrated, uncalibrated or unknown (legacy reservations without search metadata). It is derived from the frozen server execution profile, never supplied by clients. F01 capabilities additionally expose calibration_status and voice_transport_testing. With explicit server VOICE_TRANSPORT_TESTING=true, missing/pending calibration permits voice connectivity using configured embedding transport. This does not change Section 7.2 evidence admission: search returns error/CALIBRATION_REQUIRED without sources until measured calibration exists. Default false retains strict admission. Origin/CSRF, ownership, epochs, deduplication and provider pinning remain. Leading unstyled FAQ introductions appear in factual review and in each included pair's source context. Recognition warnings or complete=false with legible blocks produce extraction review candidates, including when frozen ocr_review_required is false. D06/D07 and same-job D04 approval/retry semantics remain unchanged; no chunks are published while review is pending. Approval attests to exact output, including completeness; reject missing/inaccurate content rather than approve guesses. Fatal format/provenance/readability failures still map to EXTRACTION_QUALITY_FAILED. ### OpenAI generation-limit amendment (2026-10-12) Server-only OPENAI_REALTIME_MAX_OUTPUT_TOKENS defaults to 256 (integer 1..4096). Session setup must acknowledge it; initial responses and tool continuations inherit it. New execution_profile snapshots freeze max_output_tokens and revised OpenAI instruction revision/digest. Missing/mismatched old snapshots fail existing stream admission without rewriting reservation identities or profiles. Gemini is unchanged. This budget includes tool calls and is not a measured PCM-duration guarantee. Credit, transport/browser and timeout bounds remain. The OpenAI reservoir is amended below. ### OpenAI output-capacity amendment (2026-10-12) For the selected OpenAI Live repair profile, aggregate undrained backlog defaults to **5760000 bytes / 120 seconds**, with a finite 664 packed-slab accounting cap (600 full slabs plus partial slabs across at most 64 unretired references). `LIVE_MAX_OUTPUT_BACKLOG_BYTES` may select a smaller aligned bound. Values above 5760000 fail configuration validation. Gemini retains its 1440000-byte / 512-slab baseline and rejects the OpenAI capacity profile before opening its provider. The earlier 30-second examples and memory total describe the baseline profile; this amendment supersedes only their OpenAI reservoir/slab values. New OpenAI reservation snapshots freeze `output_backlog_bytes` and `output_slab_limit`; replay never rewrites them and missing/mismatched profiles fail admission. Aggregate accounting includes runtime PCM, adapter PCM, reservations, delivery credit and all unresolved references. Both byte and slab admission checks run before decoding/extending PCM. Exhaustion remains `LIVE_BUFFER_OVERFLOW` with `OUTPUT_BACKLOG_CAPACITY` or `OUTPUT_SLAB_CAPACITY`; a genuine missing-playback deadline remains `PLAYBACK_PROGRESS_STALL`. Frame size 9600, transport/browser queues 96000, delivery credit 72000, deadlines and control reception remain unchanged. No provider receive throttling, silent audio discard, fabricated progress or automatic response chaining is added. Raw/scratch/copy/metadata payload allowance becomes 6380288 bytes per OpenAI session under the existing scratch/copy/metadata caps; Python/process overhead must be measured separately. This finite capacity amendment does not select an answer token budget or establish real-provider quality/memory acceptance. ### Validated limited-answer behavior A validated OpenAI response.done with status=incomplete, status_details.type=incomplete and reason=max_output_tokens, no error, and matching max_output_tokens if supplied is an intentional limited answer only when its audio-only output/identity set and audio-done events validate. Preserve valid audio and exact counters; drain and retire through 7.1.1/7.1.5. Failed, content-filtered, other incomplete, malformed and context synchronization errors remain failures. Incomplete tool phases fail safely, without executing cut-off calls or continuing. OpenAI argument-done stages calls; validated successful terminal output permits execution. No automatic retry or response chaining bypasses the budget. Emit server-only {"type":"answer_limited","turn_ref":"live-turn-1","reason":"output_token_limit"} once for a current uninterrupted limited answer. It does not seal or flush audio. Final assistant transcript text uses status=limited rather than completed. OpenAI transcript-done alone is held within the existing control reservation budget until successful/limited terminal validation, then released or suppressed on interruption/failure. Transcript completion never claims playback confirmation. A limited answer retains that display state after normal exchange closure; genuine interruption takes precedence. Missing transcripts stay unavailable. All 7.1.2/7.1.6 input-commitment, current-turn, authority, terminal, final-progress, cleanup-ack and intent gates still apply. Limited generation alone neither creates a new user turn nor releases a response. A later genuine user turn after fully drained/cleaned limited output emits no fabricated turn_interrupted. See docs/guides/openai-output-limit-repair.md for consumer and acceptance details. ## Live declared-source amendment ? 2026-10-13 `search_knowledge` and `reuse_last_evidence` still give the model the complete eligible evidence bundle. They no longer publish every retrieval candidate as an answer citation. Before a document answer, the model calls internal `report_used_sources` with exactly `{"source_refs":["S1","S3"]}` (or an empty list when no passage supports the answer). Labels must be unique, bounded and belong to successful evidence already delivered to the same turn. Backend-owned document/chunk identities and excerpts are resolved from those originals; forged labels, scope/identity fields and prior-turn labels without revalidated reuse are rejected. No source report creates a durable retrieval row. Only declared labels are emitted through the existing `sources` event, grouped by their real retrieval's `tool_call_id`. Revalidate original durable results before report output, source delivery and answer continuation; interrupted or revoked evidence must never become citations. Missing/invalid reports do not fall back to displaying every candidate. Multiple reports add to the set of sources declared during the turn; event/call replay remains idempotent. Polling `recent_tool_results` remains explicitly retrieval diagnostics, not declared answer citations. Declaration is model attribution, not independent proof of claim-level support or which spoken words were heard. No new public endpoint, database table or durable transcript is introduced. New reservations pin `evidence_policy_revision=same-session-evidence-selected-v2`; OpenAI delivery style is `iranian-persian-professional-v5`. An optional pre-tool acknowledgement is only «یه لحظه…», at most once per turn. No acknowledgement is needed when the answer can start directly. Suppression of longer preambles is an instruction, not a guarantee inferred from synthetic tests. Existing pinned reservations are never rewritten; use a new session after this deployment. ### Source-report recovery - 2026-10-13 Invalid `report_used_sources` arguments are recoverable provider-tool feedback, not browser `error` events. Unknown-label feedback includes server-derived `available_source_refs` for the current turn; an empty set requires revalidated reuse or a fresh search (or an empty report after no_evidence). Invalid reports still emit no citations, never fall back to all candidates and cannot widen scope. Other tool/runtime errors retain their browser error behavior. Current new reservations use evidence policy `same-session-evidence-selected-v3` and OpenAI delivery `iranian-persian-conversational-v6`. Existing pins are preserved. Numeric source-report traces record requested/available/rejected counts only. ### Abandoned OpenAI tool resolution - 2026-10-13 After interruption terminal confirmation and existing audio cleanup barriers, the OpenAI adapter supplies a private function_call_output with status cancelled and empty sources for each interrupted call whose output was never sent. These metadata-only outputs precede the next current-turn response.create and undergo current authority and supersession checks. They do not validate or disclose old evidence, create retrieval rows, resume the old response or rewrite durable tool status. Delivered tool outputs are not emitted again; late retrieval results remain suppressed. Gemini retains its existing native interruption behavior. Existing bounded send/correlation failures remain terminal; no blind send retry. New sessions use evidence policy `same-session-evidence-selected-v4`. Official wire reference: https://developers.openai.com/api/reference/resources/realtime/client-events (function_call_output accepts a string associated with the original call_id). ### Session provider-event replay capacity - 2026-10-13 Finite `LIVE_MAX_EVENTS` default and validated upper bound are now 32768, replacing 4096. This counts all unique provider event IDs over the session, including audio/transcript deltas; it is not an outstanding audio buffer. The full ID-to-digest ledger remains retained: identical replay is ignored, changed-payload replay fails, and cap exhaustion still closes with LIVE_BUFFER_OVERFLOW. No eviction or duplicate audio replay is introduced. Only this metadata capacity increases; other audio, message, identity and turn bounds remain independent. This increases maximum replay-ledger memory eightfold; it does not establish unlimited duration or deployment concurrency acceptance. ### Retain one same-topic search across speech interruption - 2026-10-13 This user-authorized amendment supersedes cancellation of the retained search on ordinary speech interruption. Playback/old response cancellation remains immediate under the existing terminal, audio cleanup and authority gates. The latest real search has a separate cancellation token and its original deadline; interruption of a turn or a reuse waiter does not cancel that search or reset its time budget. Keep its result private until explicitly reused/revalidated for a current turn. `turn_interrupted.cancelled_tool_call_ids` excludes the retained search; other cancelled operations retain their existing semantics. `reuse_last_evidence` still accepts only {}. For a repeated question or clear same-topic continuation, it awaits the retained search if necessary, then revalidates the original durable row against current identity/session, access epoch, knowledge revision and document eligibility. It retains document/chunk IDs and the actual public retrieval reference, and assigns source labels using the new turn's backend execution. It creates no retrieval row. Reporting sources still selects only current delivered labels. No old response resumes or emits its late evidence. Technical errors do not become fabricated no-evidence answers. A fresh search in a later turn for a different query discards/cancels the old retained search and starts a new topic. An exactly identical validated search argument object in a later turn can coalesce through the same revalidation path, even if the model chooses search rather than reuse. Semantic equivalence of differently phrased queries remains the model's explicit reuse decision; the backend performs no fuzzy scope or question matching. Session stop, failure or close cancels independent searches. Expiry/revocation still fails safely; this is not cross-session caching or reuse of assistant prose. At most the latest search is retained for continuation; existing tool/task/session bounds apply. The OpenAI interruption function output closes the old private response's call with empty metadata and directs same-topic continuation to reuse. Its cancelled status does not declare cancellation of the separately retained backend search. Gemini continues to use its native interruption transport. New reservations use `evidence_policy_revision=same-session-evidence-retained-v5`; existing pins are not rewritten. No schema/table migration or new public endpoint is introduced. ## Temporary best-effort ingestion admission (2026-10-13) User-authorized `INGEST_ALLOW_PARTIAL_EXTRACTION=true` is frozen in NEW upload profiles as `extraction.allow_partial_extraction`. Default false and missing legacy fields retain strict admission; existing profiles/digests are not rewritten. This temporary mode bypasses PDF visual, OCR and factual manual approval without fabricating reviewer identities or annotations. Usable recognition with incomplete regions, warnings or unknown glyphs proceeds to chunking/embedding. Warnings remain in the retained artifact; `extraction_quality_decision=accepted_with_warnings` identifies unreviewed admission. Artifact `complete=true` denotes completion of the extraction attempt, not a claim of perfect recognition. No measured 90% accuracy threshold is available. Empty/unusable output, malformed provider JSON, identity/checksum mismatch, invalid relationships and resource bounds remain errors. Publication remains atomic, ready and inactive until selection. F01 capabilities add `allow_partial_extraction` and report effective review gates. Failed existing documents require a new upload to use this new frozen policy. Regression source: `tests/unit/test_partial_extraction.py`. ### Verified Marin cancellation race (2026-10-13) Operational session 79421770-4615-4140-ae2f-fc590510787d pinned `gpt-realtime-2.1/marin`. Turn 7 cancellation was dispatched at elapsed 44499 ms; completed terminal confirmation arrived at 44677 ms. The correlated error then matched all three exact structured type/code/null-param guards but failed the Shimmer-only profile guard, closing with CANCELLATION_PROVIDER_ERROR. The verified profile set now additionally includes gpt-realtime-2.1/marin. It does not admit other model/voice pairs or relax event-ID correlation, terminal confirmation, final playback positions or truncation acknowledgement. Synthetic regressions reproduce the original rejection, cover both terminal orderings, and retain failure when terminal confirmation is absent. ### OpenAI model-independent cancellation classification (2026-10-14) User-authorized amendment superseding the selected-model/voice restriction: OpenAI's captured invalid_request_error / response_cancel_not_active / null-param signature is classified independently of model and voice. Model admission and session setup acknowledgement remain separate. Cancellation event-ID correlation, bounded terminal confirmation, final playback and truncation acknowledgement gates remain mandatory; unknown errors and failed/incomplete technical terminals remain fatal. This change does not establish live acceptance for every OpenAI model. ### Local S2S development candidate amendment (2026-10-15) The server may select `local_s2s` only with explicit development/transport-test opt-in. This does not add a client provider selector or change PCM24k/public events. Private setup requires the pinned engine/extension/contract revision, fixed component identities and effective post-application configuration proof; a session echo alone is insufficient. Interruption requiring history repair fails closed pending Phase 3. Preserve owner, Origin, cookie, CSRF, replay, profile and epoch checks. Candidate startup requires dedicated test DB/storage. Build and real Persian/browser acceptance remain open; see [Phase 2 evidence](../evaluation/local-s2s/phase-02.md). ## User-authorized provider selection amendment — 2026-10-16 The Phase 4 development UI may select an existing server-configured provider; it cannot choose model/voice, change audio policy, supply credentials or override identity/scope. This supersedes the earlier no-provider-selector UI restriction for this explicitly requested capability. It does not authorize promotion. - Authenticated `GET /api/v1/voice/sessions/providers` returns `default_provider`, `connection_checked=false` and `providers` rows `{id,label,can_start,reason}`. IDs are openai/local_s2s/gemini. Reasons are disabled, not_configured, isolated_environment_required or calibration_required. Eligibility is server configuration/capability evidence, not a remote health or quality check. - `GET /api/v1/configuration` accepts an optional provider enum and evaluates that allowed provider's existing capability gates; omission retains prior behavior. - V01 accepts optional `provider` from the same enum. Only the default plus `VOICE_SELECTABLE_PROVIDERS` may be newly admitted; missing credentials never fall back. Other provider/model/audio fields remain forbidden. - V01/V03 responses add the frozen `provider` field. An explicit different provider on the same client_request_id is IDEMPOTENCY_CONFLICT (409), including concurrent creation. Replay without an explicit choice recovers the original frozen row before current configuration checks. No old profile is rewritten. - Stream admission selects server settings for the row's pinned, currently allowed provider, then applies the existing model/profile/search/owner/Origin/cookie/epoch checks. Local requests still require disposable database/storage isolation. - Changing provider ends the old call and requires a fresh session/request identity. No seamless media switch or automatic cross-provider fallback is introduced. Provider secrets and tuned OpenAI speech settings stay server-side. Selection adds no tables/migrations or document-content versioning. ## Server source import amendment (2026-10-18) The user explicitly authorized importing deployed document deletion, S2S diagnostics and model settings. D05 HTTP/UI is enabled under its existing soft-deletion, revision/epoch, replay and retention rules. The deployed request sends the revision in the JSON body, not the historical query placeholder. This amendment records that intentional contract and its Angular consumer. F01 adds `models`, an array of `{id, label, model}` public identifiers. Roles are `embedding`, `ocr`, and, when enabled/selectable, `dialogue`, `stt`, `tts`, `openai` and `gemini`. It contains no credentials or service URLs and does not promise that provider readiness has passed. The settings UI displays deployed models; its Live card uses the existing permitted provider selector for the next conversation. This does not add F02 model/credential editing or a selectable arbitrary-model API. Existing model profile/revision pinning remains intact. See [import evidence](../guides/server-source-sync-20261018.md). ## User-authorized evidence admission amendment (2026-10-18) `search_knowledge` and shared search inspection now return up to ten whole eligible source chunks (previously five), within the unchanged 12,000-character text budget. Cutoff filtering may yield fewer. Schema and source identities are unchanged. Retrieval-policy fingerprint includes `whole-10-12000`; calibration reports must match. Current-turn source reporting remains mandatory; source order does not establish relevance. Local voice enables a bounded extractive output gate before TTS; unsupported text becomes a fixed insufficient-evidence response. See [grounding correction and validation](../guides/strict-grounding-20261018.md).