docs(voice): freeze OpenAI Realtime Phase 0 contracts
Align voice specifications and the MVP plan with OpenAI Realtime. Document audio admission, bounded playback, cancellation ownership, turn correlation, cleanup barriers and calibration prerequisites. Preserve historical checkpoints and record unrun acceptance gates.
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
# Phase 1 agent reference map
|
# Phase 1 agent reference map
|
||||||
|
|
||||||
Use this index to select the governing contract and inspect the real implementation before changing, testing, or reviewing behavior. Paths are relative to this file. Current MVP mapping updated 2026-10-07 for English revision 1.3. Historical component evidence below is preserved; the English revision 1.3 documentation checkpoint reran no application/provider/database tests; current repair acceptance is recorded at the end. Use the latest applicable recorded acceptance, not earlier unavailable-database reports. Dated component records below describe their historical checkpoint; absence-of-worker statements there are superseded by the current Phase 5/6 inventory and repair evidence.
|
Use this index to select the governing contract and inspect the real implementation before changing, testing, or reviewing behavior. Paths are relative to this file. Current voice contract amended 2026-10-08 by Realtime Phase 0; English revision 1.3 remains the broader scope baseline. Historical component evidence below is preserved; the English revision 1.3 documentation checkpoint reran no application/provider/database tests; current repair acceptance is recorded at the end. Use the latest applicable recorded acceptance, not earlier unavailable-database reports. Dated component records below describe their historical checkpoint; absence-of-worker statements there are superseded by the current Phase 5/6 inventory and repair evidence.
|
||||||
|
|
||||||
## Authority and document resolution
|
## Authority and document resolution
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ delivery plan, implementation guide, API catalog, database design, architecture
|
|||||||
and `RAG-Phase1-MVP-Scenarios.md`. Revision 1.3 replaces the prior 7-10 day
|
and `RAG-Phase1-MVP-Scenarios.md`. Revision 1.3 replaces the prior 7-10 day
|
||||||
text-and-voice milestone with a conditional four-day Live document MVP:
|
text-and-voice milestone with a conditional four-day Live document MVP:
|
||||||
new browser uploads, the existing ingestion/embedding Phases 1-4, LangChain,
|
new browser uploads, the existing ingestion/embedding Phases 1-4, LangChain,
|
||||||
direct Gemini Live and mandatory example/unseen-file acceptance.
|
mandatory example/unseen-file acceptance. The scoped 2026-10-08 Phase 0 amendment selects OpenAI Realtime for voice and the conditional 3-5 day backend sequence in [Realtime MVP plan](plans/realtime-agent-mvp-plan.md); the earlier four-day sequence is historical.
|
||||||
Full text chat/history and settings editing are deferred.
|
Full text chat/history and settings editing are deferred.
|
||||||
|
|
||||||
The four supplied files are test examples, not upload eligibility or final
|
The four supplied files are test examples, not upload eligibility or final
|
||||||
@@ -28,7 +28,7 @@ Section numbers and heading names below are verified against these files; no inf
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script |
|
| `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script |
|
||||||
| `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation |
|
| `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation |
|
||||||
| `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract — direct Gemini Live; proposed application WSS; 9. Error envelope and mapping |
|
| `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract — OpenAI Realtime; frozen application audio/events; 9. Error envelope and mapping |
|
||||||
| `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation |
|
| `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation |
|
||||||
| `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation |
|
| `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation |
|
||||||
| `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions |
|
| `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions |
|
||||||
@@ -69,8 +69,8 @@ Prototype runtime prerequisites remain unverified: configured credentials, appro
|
|||||||
|
|
||||||
- Required document content is available under `specifications/`; no reference-dependent workflow is currently blocked by missing content. If a linked document later disappears, mark only dependent contract work blocked, report its exact path, and continue unrelated work without inventing it.
|
- Required document content is available under `specifications/`; no reference-dependent workflow is currently blocked by missing content. If a linked document later disappears, mark only dependent contract work blocked, report its exact path, and continue unrelated work without inventing it.
|
||||||
- Material implementation gap: prototype Chroma/local Markdown/in-memory chat does not search the uploaded-document pipeline. Worker/publication/retry are implemented; remaining work includes authenticated review transport, real-model search calibration, HTTP identity/upload, LangChain integration, native Live and UI. The Fast-Track Search Phase 1 core and operator selection/inspection CLIs now exist; see the checkpoint below. Full durable text turns/history are deferred; no component test certifies this integration.
|
- Material implementation gap: prototype Chroma/local Markdown/in-memory chat does not search the uploaded-document pipeline. Worker/publication/retry are implemented; remaining work includes authenticated review transport, real-model search calibration, HTTP identity/upload, LangChain integration, native Live and UI. The Fast-Track Search Phase 1 core and operator selection/inspection CLIs now exist; see the checkpoint below. Full durable text turns/history are deferred; no component test certifies this integration.
|
||||||
- Open validations: exact format/size caps, funded model profiles/vector dimension, Gemini Live WSS/tool/transcript and Persian speech proof, hosting/connectivity, account/session/retention policy, quality target and delivery date. Direct Gemini Live, LangChain, new browser uploads, existing embedding reuse and all supplied example structures are confirmed MVP direction. See guide 13 and plan 2. Do not turn proposals into recorded approvals.
|
- Open validations: exact format/size caps, funded model profiles/vector dimension, OpenAI Realtime WSS/tool/transcript and Persian speech proof, hosting/connectivity, account/session/retention policy, quality target and delivery date. Direct OpenAI Realtime, LangChain, new browser uploads, existing embedding reuse and all supplied example structures are confirmed MVP direction. See guide 13 and plan 2. Do not turn proposals into recorded approvals.
|
||||||
- The 2026-10-06 MVP supersedes provisional SDP/WebRTC with backend-managed direct Gemini Live WSS; see API Section 7. Current-session provider answer transcripts/sources are displayed when available; durable full voice history remains deferred. Broader features do not authorize model selectors or CTI.
|
- The 2026-10-06 MVP supersedes provisional SDP/WebRTC with backend-managed direct OpenAI Realtime WSS; see API Section 7. Current-session provider answer transcripts/sources are displayed when available; durable full voice history remains deferred. Broader features do not authorize model selectors or CTI.
|
||||||
- Project documentation now lives under `docs/`; sample corpus files remain under `data/documents/`. A future default corpus rebuild excludes the moved specifications and reference map. Existing vector indexes are not rebuilt or cleaned by this reorganization and may retain previously indexed project documentation. Use an approved corpus for real-provider evaluation.
|
- Project documentation now lives under `docs/`; sample corpus files remain under `data/documents/`. A future default corpus rebuild excludes the moved specifications and reference map. Existing vector indexes are not rebuilt or cleaned by this reorganization and may retain previously indexed project documentation. Use an approved corpus for real-provider evaluation.
|
||||||
|
|
||||||
## Skill discovery
|
## Skill discovery
|
||||||
@@ -1627,6 +1627,25 @@ were unchanged. All three applied migrations match HEAD byte-for-byte. Local
|
|||||||
documentation links and new-file inspection passed. Existing intentional Markdown
|
documentation links and new-file inspection passed. Existing intentional Markdown
|
||||||
hard breaks were preserved. Temporary original-image inspection files were removed.
|
hard breaks were preserved. Temporary original-image inspection files were removed.
|
||||||
|
|
||||||
|
## OpenAI Realtime Phase 0 (2026-10-08)
|
||||||
|
|
||||||
|
Voice provider selection now follows the [Realtime MVP plan](plans/realtime-agent-mvp-plan.md); the scoped [Phase 0 report](guides/realtime-agent-phase0.md) records the frozen application contract, configuration and calibration prerequisites. Historical component/provider records above remain historical. Proof is isolated/hardcoded; canonical search and LangChain adapter are reused, not rebuilt. Runtime, real calibration and voice acceptance remain pending.
|
||||||
|
|
||||||
|
Phase 0 executed: 162 targeted provider-free search/calibration/LangChain tests passed, zero skips; CLI help and tracked whitespace checks passed. Persisted-profile connection probe failed (OperationalError); real providers and PostgreSQL acceptance were not run. Concurrent untracked scripts/mock_stream_server.py was preserved. See the report for remaining calibration prerequisites.
|
||||||
|
|
||||||
|
Phase 0 documentation repair (2026-10-08) supersedes incomplete progress/bounds preparation: API 7.1.1-7.1.4 defines reference lifecycle, floor/sample coordinates, final reports, acknowledged cleanup barrier, frame/queue caps and six walkthroughs. Report includes official model/transcription retirement and executable read-only profile/binding preflight. Earlier 162-test results were not rerun; this repair makes no provider, runtime, quality or PostgreSQL acceptance claim. Verification results are recorded in the repair report.
|
||||||
|
|
||||||
|
Repair checks: six CLI help commands and six PowerShell example parses passed; local original hash, Python example AST, UTF-8/local links/whitespace and proof/migration/frozen-input preservation passed. Eight documentation files changed; 168 other baseline files unchanged, with a concurrent external mock-server edit observed and preserved separately. No pytest/database/provider/runtime checks run for this documentation repair. Exact commands/results are in the Phase 0 report.
|
||||||
|
|
||||||
|
Remaining-four-findings Phase 0 repair (2026-10-08): API 7.1.5 separates bounded generated backlog from paced transport/playback, and 7.1.6 governs delayed user ASR, normal completion and committed current-turn release/supersession. API 7.1.2 selects backend cancellation ownership with both VAD flags false and narrowly correlated no-active-response races. Plan Phase 1/2 prompts and current guide/report/progress align; twelve walkthroughs are documented. Official-source verification is separate from unrun provider/runtime/database acceptance; exact checks are recorded in the latest Phase 0 report checkpoint. CALIBRATION_REQUIRED remains closed.
|
||||||
|
|
||||||
|
Latest four-findings repair checks: Git whitespace, strict UTF-8/local links, two Python AST parses and six PowerShell syntax parses passed. Eight documents changed; 169 other repair-start files are byte-identical, including the proof, existing mock-server changes, migrations and frozen calibration records. Recorded original hash verified. No CLI help commands, database/provider workflows or runtime tests were run in this repair; embedded examples were parsed only. See the latest report checkpoint for exact boundaries.
|
||||||
|
|
||||||
|
Playback-stall/cleanup timeout repair (2026-10-08): API 7.1.1/7.1.2/7.1.5 excludes finalizing/interrupted/retired refs from stall detection, atomically invalidates timer identities at cleanup ownership, rechecks queued callbacks, and initializes each eligible interval independently. Retirement releases credit once without changing evidence or bypassing response gates. Four additional walkthroughs (sixteen total), plan/guide/config summaries align; documentation-only checks and unchanged external gates are recorded in the latest Phase 0 report. CALIBRATION_REQUIRED remains.
|
||||||
|
|
||||||
|
Timeout-repair checks passed: tracked whitespace, strict UTF-8/local links, two Python AST parses, 39 JSON examples, six PowerShell syntax parses and manual timer/credit/barrier consistency. Eight documents changed; 169 other baseline files unchanged, including proof/mock scripts, applied migrations and frozen calibration inputs. Original hash verified. No database/provider/runtime workflows or tests were run; exact outcomes are in the latest report checkpoint.
|
||||||
|
|
||||||
|
|
||||||
## OpenAI Realtime Phase 1 runtime checkpoint (2026-10-08)
|
## OpenAI Realtime Phase 1 runtime checkpoint (2026-10-08)
|
||||||
|
|
||||||
[Operator/runtime guide](guides/realtime-agent-phase1.md) documents the private
|
[Operator/runtime guide](guides/realtime-agent-phase1.md) documents the private
|
||||||
|
|||||||
@@ -0,0 +1,582 @@
|
|||||||
|
# Realtime MVP Phase 0 contract checkpoint
|
||||||
|
|
||||||
|
2026-10-08. Contract/configuration preparation repaired as documented in the final checkpoint below; runtime and quality
|
||||||
|
acceptance remain pending. This scoped amendment selects OpenAI Realtime for
|
||||||
|
voice in the current six English specifications. The historical Persian report,
|
||||||
|
extraction/embedding providers, HTTP DTOs, canonical search outputs and applied
|
||||||
|
migrations are preserved. The [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md)
|
||||||
|
governs the new backend phase sequence; its 3-5 focused days is a conditional
|
||||||
|
estimate, superseding the earlier four-day integration sequence.
|
||||||
|
|
||||||
|
The frozen frontend audio/events are in
|
||||||
|
[API Section 7.1](../specifications/RAG-Phase1-API-Catalog.md).
|
||||||
|
Both directions use raw mono signed PCM16LE at 24 kHz.
|
||||||
|
Existing session_ready/transcript/sources/turn_interrupted/error shapes remain;
|
||||||
|
user_speech_started, audio_started and audio_ended are server events, playback_progress is
|
||||||
|
a validated client control. Provider objects and correlation mappings stay private.
|
||||||
|
No production UI, public text chat, new retrieval or voice runtime is implemented.
|
||||||
|
|
||||||
|
## Backend-only configuration prerequisites
|
||||||
|
|
||||||
|
The following names define the configuration handoff. Only key/model/proxy
|
||||||
|
are currently read by the isolated proof; the other settings must be wired by
|
||||||
|
Phases 1/2. Blank prerequisites must fail closed, not enable a capability.
|
||||||
|
|
||||||
|
| Setting | Initial value or requirement |
|
||||||
|
| --- | --- |
|
||||||
|
| OPENAI_API_KEY | Server secret with funded Realtime model access; do not share the prototype API_KEY fallback with production voice |
|
||||||
|
| OPENAI_REALTIME_MODEL | gpt-realtime-mini, the observed proof configuration; no silent substitution |
|
||||||
|
| OPENAI_REALTIME_VOICE | shimmer, the proof default; fixed by backend, no browser selector/update_voice |
|
||||||
|
| OPENAI_PROXY | Optional operator-controlled proxy; proof falls back to HTTPS_PROXY/HTTP_PROXY; never caller supplied or logged with credentials |
|
||||||
|
| LIVE_TRUSTED_ORIGIN | Exact browser origin including scheme/host/port, e.g. http://localhost:3000 behind a same-origin development proxy; HTTPS in deployment; reject missing/untrusted Origin, no wildcard |
|
||||||
|
| LIVE_CONNECT_TIMEOUT_SECONDS | 15, proof connection timeout |
|
||||||
|
| LIVE_SETUP_TIMEOUT_SECONDS | 30, provider-confirmed setup required before session_ready |
|
||||||
|
| LIVE_TOOL_TIMEOUT_SECONDS | 75 maximum including queue time, earlier trusted monotonic deadline wins; shared four-running/eight-waiting SearchToolRunner |
|
||||||
|
| LIVE_IDLE_TIMEOUT_SECONDS | Explicit finite positive deployment choice required; not yet approved |
|
||||||
|
| LIVE_SESSION_TTL_SECONDS | 600 proposed engineering default; cleanup bounded by expiry |
|
||||||
|
| LIVE_SHUTDOWN_TIMEOUT_SECONDS | Explicit finite positive cleanup deadline required; not yet approved |
|
||||||
|
| LIVE_MAX_QUEUED_AUDIO_SECONDS | 2 per application transport/browser buffer; 96000 bytes / 100 messages, separate from generated backlog |
|
||||||
|
| LIVE_MAX_OUTPUT_BACKLOG_BYTES | 1440000 aggregate G+T+R (30 s); 512 packed slabs, API 7.1.5 |
|
||||||
|
| LIVE_OUTPUT_CREDIT_WINDOW_BYTES | 72000 (1500 ms) across delivery reservations and sent-unconfirmed audio |
|
||||||
|
| LIVE_PLAYBACK_STALL_TIMEOUT_SECONDS | 5 per eligible open/sealed ref with a reportable unplayed millisecond; finalizing/interrupted/retired refs excluded, fresh timer identity per eligibility interval/renewal, API 7.1.5 |
|
||||||
|
| Output memory caps | Raw/scratch/copy/metadata payload budget 2060288 bytes per session; object overhead/global admission require validation, API 7.1.5 |
|
||||||
|
| LIVE_MAX_BINARY_MESSAGE_BYTES | 9600, even nonempty PCM (200 ms) |
|
||||||
|
| LIVE_MAX_CLIENT_CONTROL_BYTES / LIVE_MAX_SERVER_EVENT_BYTES | 4096 / 65536 UTF-8 bytes |
|
||||||
|
| LIVE_FINAL_PROGRESS_WINDOW_MS | 1000 from interruption detection, engineering default |
|
||||||
|
| LIVE_TRUNCATION_ACK_TIMEOUT_SECONDS | 5 after dispatch, engineering default; fail context synchronization on timeout |
|
||||||
|
| LIVE_SEND_TIMEOUT_SECONDS | 5 per send, engineering default |
|
||||||
|
| Other transport caps | Input 10 s since commit; control queues 64 / 262144 bytes; provider message 262144 bytes; 64 unretired / 256 total refs, API 7.1.3 |
|
||||||
|
| SEARCH_CALIBRATION_REPORT | Operator-controlled path to a new measured report; initially absent, never the pending phase2-status.json |
|
||||||
|
| Auth session TTL | Eight hours proposed; identity integration remains Phase 2 |
|
||||||
|
|
||||||
|
Durations must be finite and positive; no automatic provider retries or
|
||||||
|
caller overrides. Secrets/proxy/report paths are not frontend capabilities.
|
||||||
|
Snapshot nonsecret execution settings when durable lifecycle is implemented.
|
||||||
|
|
||||||
|
Official documentation checked on 2026-10-08:
|
||||||
|
[gpt-realtime-mini model](https://developers.openai.com/api/docs/models/gpt-realtime-mini)
|
||||||
|
lists the configured model and function calling;
|
||||||
|
[Realtime client configuration](https://developers.openai.com/api/reference/resources/realtime/client-events)
|
||||||
|
lists shimmer and 24 kHz PCM input/output and forbids changing voice after audio
|
||||||
|
has been emitted. [Conversation guidance](https://developers.openai.com/api/docs/guides/realtime-conversations)
|
||||||
|
describes session configuration and WebSocket interruption/truncation.
|
||||||
|
Documentation support does not verify this account, Persian quality or runtime.
|
||||||
|
|
||||||
|
### Provider configuration lifecycle and replacement decision
|
||||||
|
|
||||||
|
Read the official sources on 2026-10-08; this is documentation verification,
|
||||||
|
not account/model access, Persian quality or live truncation acceptance.
|
||||||
|
|
||||||
|
| Selected configuration from the proof | Official lifecycle | Required action |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| gpt-realtime-mini | Deprecated 2026-07-20; API retirement 2027-01-20 | Preserve this alias initially; backend fails explicitly on unavailable access, never substitutes a model |
|
||||||
|
| shimmer | Listed Realtime built-in voice; no separate retirement date found in the consulted sources | Preserve fixed voice; no browser override or in-session switch |
|
||||||
|
| Input transcription whisper-1, language fa | Deprecated 2026-08-26; API retirement 2027-02-26 | Preserve the proof's actual Persian transcription setup initially; no automatic transcription-model replacement |
|
||||||
|
| Input/output audio/pcm, rate 24000 | Official Realtime input/output configuration supports 24 kHz PCM | Keep frozen application PCM16LE; configuration acknowledgement is still required |
|
||||||
|
|
||||||
|
Sources: [model](https://developers.openai.com/api/docs/models/gpt-realtime-mini),
|
||||||
|
[client configuration/truncation](https://developers.openai.com/api/reference/resources/realtime/client-events),
|
||||||
|
[WebSocket interruption](https://developers.openai.com/api/docs/guides/realtime-conversations),
|
||||||
|
and [official deprecations](https://developers.openai.com/api/docs/deprecations).
|
||||||
|
Successful truncation has a provider acknowledgement; a send alone is not
|
||||||
|
confirmation. API Section 7.1.2 adds application ordering/timeout policy rather
|
||||||
|
than assuming provider response cancellation fixes unheard context.
|
||||||
|
The proof also sets output speed 0.98; this repair changes none of its settings.
|
||||||
|
|
||||||
|
AI/backend owner must make and record a separate replacement decision before
|
||||||
|
the respective retirement dates, with explicit account/budget approval and
|
||||||
|
Persian/tool/truncation regression validation. Official recommendations currently
|
||||||
|
include gpt-realtime-2.1-mini for Realtime and gpt-live-transcribe or gpt-transcribe
|
||||||
|
for transcription; these are candidates, not selected profiles. Do not change
|
||||||
|
extraction/embedding profiles, migrate automatically, or treat a listed model
|
||||||
|
as proof of funded account access. Recheck lifecycle guidance at deployment.
|
||||||
|
|
||||||
|
|
||||||
|
## Search/calibration gate and exact next commands
|
||||||
|
|
||||||
|
Keep the current configured ollama / bge-m3 / 1024 / preprocessing v1 profile
|
||||||
|
and endpoint unchanged. A read-only compatibility probe using the existing
|
||||||
|
check_compatibility could not connect (OperationalError, secret-bearing raw
|
||||||
|
diagnostic suppressed), so the persisted vector dimension/identity and eligible
|
||||||
|
bindings are unverified. TEST_DATABASE_URL is absent. No approved bindings,
|
||||||
|
persisted enabled actor, measured successful report or real-call opt-in were
|
||||||
|
provided for this task.
|
||||||
|
|
||||||
|
[Current calibration status](../calibration/phase2-status.json) is pending with
|
||||||
|
null cutoff and zero recorded provider calls. The existing runner
|
||||||
|
app.calibrate_search uses the canonical candidate service for six answerable
|
||||||
|
and four unsupported questions and authorizes at most ten query embeddings.
|
||||||
|
It verifies original hash, ready/active/undeleted scoped document bindings,
|
||||||
|
embedding profile and stable selection/authorization. Reuse its report loader,
|
||||||
|
app.modules.knowledge.calibration.load_cutoff(report), then inject the returned
|
||||||
|
CalibratedCutoff into SearchService. Profile and retrieval policy must match.
|
||||||
|
Missing cutoff remains CALIBRATION_REQUIRED with empty sources; a diagnostic
|
||||||
|
candidate inspection or test-only cutoff cannot replace measurements.
|
||||||
|
|
||||||
|
Run these provider-free commands now/from the repository root:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m app.calibrate_search --help
|
||||||
|
.venv/Scripts/python -m app.ingest --help
|
||||||
|
.venv/Scripts/python -m app.knowledge --help
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_scoped_search.py tests/unit/test_search_phase2.py tests/unit/test_search_phase2_repairs.py tests/unit/test_search_phase2_remaining.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q --tb=short -p no:cacheprovider
|
||||||
|
git diff --check
|
||||||
|
~~~
|
||||||
|
|
||||||
|
### Read-only operator preflight
|
||||||
|
|
||||||
|
Run from the repository root with the existing virtual environment. The first
|
||||||
|
example uses only frozen local bytes; it writes nothing and opens no database or
|
||||||
|
provider. PowerShell's literal here-string avoids native -c quoting problems.
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
@'
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from app.modules.knowledge.calibration import validate_cases
|
||||||
|
|
||||||
|
p = Path("docs/calibration/phase2-cases.json")
|
||||||
|
annotations = json.loads(p.read_text(encoding="utf-8"))
|
||||||
|
validate_cases(annotations["cases"])
|
||||||
|
original = p.parent / annotations["original_file"]
|
||||||
|
digest = hashlib.sha256(original.read_bytes()).hexdigest()
|
||||||
|
if digest != annotations["original_sha256"]:
|
||||||
|
raise SystemExit("ORIGINAL_HASH_MISMATCH")
|
||||||
|
print(json.dumps({"original_sha256": digest, "annotations_sha256":
|
||||||
|
hashlib.sha256(p.read_bytes()).hexdigest()}))
|
||||||
|
'@ | .venv/Scripts/python -
|
||||||
|
~~~
|
||||||
|
|
||||||
|
The exact bindings file is a JSON object, not a document list or report:
|
||||||
|
|
||||||
|
~~~json
|
||||||
|
{
|
||||||
|
"<original_sha256 printed above: 64 lowercase hex characters>": "<actual ready selected document UUID>"
|
||||||
|
}
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Both angle-bracket strings are placeholders and must be replaced. For the
|
||||||
|
unchanged current original, the verified key is
|
||||||
|
7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f.
|
||||||
|
The value must come from real intake/status, not an illustrative UUID. Keep
|
||||||
|
bindings outside frozen annotations and retain operator approval separately.
|
||||||
|
No example below fabricates or writes a binding.
|
||||||
|
|
||||||
|
After publication/selection, set these approved preflight inputs (replace each
|
||||||
|
placeholder; they are identity/path inputs, not credentials):
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
$env:PREFLIGHT_ADMIN_ID = '<existing enabled admin UUID>'
|
||||||
|
$env:PREFLIGHT_USER_ID = '<existing enabled calibration-user UUID in the same organization>'
|
||||||
|
$env:PREFLIGHT_BINDINGS = '<absolute path to approved bindings.json>'
|
||||||
|
~~~
|
||||||
|
|
||||||
|
This executable read-only compatibility/eligibility example uses the existing
|
||||||
|
check_compatibility API. It requires the current worker revision, checks the
|
||||||
|
persisted vector dimension/full profile and document profiles, checks enabled
|
||||||
|
admin/user roles and same organization, then checks the bound original is ready,
|
||||||
|
active, undeleted, unpurged and profile-compatible. An initial profile-only
|
||||||
|
result followed by PREFLIGHT_FAILED is not full preflight acceptance. SET
|
||||||
|
TRANSACTION READ ONLY prevents mutations; timeouts bound queries and connection.
|
||||||
|
The example never uses authority's locking path in a read-only transaction.
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
@'
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from dataclasses import asdict
|
||||||
|
from pathlib import Path
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine, text
|
||||||
|
from app.infrastructure.database import check_compatibility
|
||||||
|
from app.modules.documents.settings import IngestionSettings
|
||||||
|
from app.modules.knowledge.service import actor
|
||||||
|
|
||||||
|
engine = None
|
||||||
|
try:
|
||||||
|
cases_path = Path("docs/calibration/phase2-cases.json")
|
||||||
|
annotations = json.loads(cases_path.read_text(encoding="utf-8"))
|
||||||
|
original = cases_path.parent / annotations["original_file"]
|
||||||
|
digest = hashlib.sha256(original.read_bytes()).hexdigest()
|
||||||
|
if digest != annotations["original_sha256"]:
|
||||||
|
raise ValueError("Original hash mismatch")
|
||||||
|
settings = IngestionSettings()
|
||||||
|
engine = create_engine(
|
||||||
|
settings.database_url.get_secret_value(),
|
||||||
|
connect_args={"connect_timeout": 3},
|
||||||
|
pool_pre_ping=False,
|
||||||
|
)
|
||||||
|
with engine.connect() as conn:
|
||||||
|
with conn.begin():
|
||||||
|
conn.execute(text("SET TRANSACTION READ ONLY"))
|
||||||
|
conn.execute(text("SET LOCAL statement_timeout = '5s'"))
|
||||||
|
conn.execute(text("SET LOCAL lock_timeout = '2s'"))
|
||||||
|
check_compatibility(conn, settings.embedding_profile, require_worker=True)
|
||||||
|
print("persisted_profile: compatible (including worker revision)")
|
||||||
|
# Set only to existing operator-approved identities and bindings.
|
||||||
|
admin_id = UUID(os.environ["PREFLIGHT_ADMIN_ID"])
|
||||||
|
user_id = UUID(os.environ["PREFLIGHT_USER_ID"])
|
||||||
|
bindings = json.loads(
|
||||||
|
Path(os.environ["PREFLIGHT_BINDINGS"]).read_text(encoding="utf-8")
|
||||||
|
)
|
||||||
|
document_id = UUID(bindings[digest])
|
||||||
|
admin = actor(conn, admin_id, administrator=True)
|
||||||
|
user = actor(conn, user_id)
|
||||||
|
if admin["organization_id"] != user["organization_id"]:
|
||||||
|
raise ValueError("Actors differ in scope")
|
||||||
|
snapshot = conn.execute(text("""
|
||||||
|
SELECT knowledge_revision, access_epoch
|
||||||
|
FROM organization_settings WHERE organization_id=:org
|
||||||
|
"""), {"org": user["organization_id"]}).mappings().one()
|
||||||
|
row = conn.execute(text("""
|
||||||
|
SELECT id FROM documents
|
||||||
|
WHERE id=:id AND organization_id=:org AND file_sha256=:digest
|
||||||
|
AND status='ready' AND is_active
|
||||||
|
AND deleted_at IS NULL AND content_purged_at IS NULL
|
||||||
|
AND processing_profile->'embedding'=CAST(:profile AS jsonb)
|
||||||
|
"""), {
|
||||||
|
"id": document_id, "org": user["organization_id"], "digest": digest,
|
||||||
|
"profile": json.dumps(asdict(settings.embedding_profile)),
|
||||||
|
}).one_or_none()
|
||||||
|
if row is None:
|
||||||
|
raise ValueError("Bound original not ready/selected/eligible")
|
||||||
|
print(json.dumps({
|
||||||
|
"preflight": "eligible_snapshot",
|
||||||
|
"knowledge_revision": snapshot["knowledge_revision"],
|
||||||
|
"access_epoch": snapshot["access_epoch"],
|
||||||
|
}))
|
||||||
|
print("Preflight only; no embeddings, calibration or voice calls made.")
|
||||||
|
except Exception as exc:
|
||||||
|
# Do not print exception text, URL, SQL parameters, settings or credentials.
|
||||||
|
print("PREFLIGHT_FAILED: " + type(exc).__name__ +
|
||||||
|
"; check approved identities/bindings, original hash and configured database/profile.")
|
||||||
|
raise SystemExit(1)
|
||||||
|
finally:
|
||||||
|
if engine is not None:
|
||||||
|
engine.dispose()
|
||||||
|
'@ | .venv/Scripts/python -
|
||||||
|
~~~
|
||||||
|
|
||||||
|
The persisted profile is a column metadata/comment check, not a query to an
|
||||||
|
invented embedding_profiles table. Configured profile identity alone is
|
||||||
|
insufficient. The preflight is a short-lived eligible snapshot, not a durable
|
||||||
|
approval or account-access proof: the calibration CLI revalidates binding,
|
||||||
|
actor, selection revision/epoch and final authorization. Freeze the entire
|
||||||
|
selected corpus for the run; all selected originals must be approved, not just
|
||||||
|
the fixture. Rerun this read-only preflight after selection/review changes.
|
||||||
|
|
||||||
|
### Verified CLI sequence and separate authorizations
|
||||||
|
|
||||||
|
After an operator restores the configured database, verifies its pinned profile
|
||||||
|
using check_compatibility, approves the calibration original and supplies enabled
|
||||||
|
admin/user UUIDs, use the existing intake/publication/selection workflow. Set
|
||||||
|
these PowerShell variables to actual approved values: $administratorId, $userId,
|
||||||
|
$uploadKey (new UUID), $documentId (intake result), $knowledgeRevision (selection
|
||||||
|
get result), $bindingsPath and $reportPath (new path in an existing directory).
|
||||||
|
Preserve the complete selected corpus on selection replacement.
|
||||||
|
|
||||||
|
**Ingestion opt-in:** independently approve the original and worker embedding
|
||||||
|
budget before these commands. worker --once can claim any eligible job in its database; it is not document-targeted and an exit code of zero does not prove this original was processed. Use an
|
||||||
|
approved queue/database and inspect it first. Neither intake nor worker has an
|
||||||
|
--allow-provider-calls flag; starting the worker is its explicit operator opt-in.
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m app.ingest import data/calibration/phase2-source.md --administrator-id $administratorId --idempotency-key $uploadKey
|
||||||
|
.venv/Scripts/python -m app.worker --once
|
||||||
|
.venv/Scripts/python -m app.ingest status $documentId --administrator-id $administratorId
|
||||||
|
.venv/Scripts/python -m app.knowledge selection get --administrator-id $administratorId
|
||||||
|
.venv/Scripts/python -m app.knowledge selection replace --administrator-id $administratorId --expected-revision $knowledgeRevision --document-id $documentId
|
||||||
|
~~~
|
||||||
|
|
||||||
|
If other documents are selected, repeat --document-id for each retained approved
|
||||||
|
UUID; do not remove them inadvertently. Ready publication alone is inactive.
|
||||||
|
Record the frozen original_sha256 from phase2-cases.json to the actual selected
|
||||||
|
document UUID in the external bindings JSON. Never fabricate IDs or set states
|
||||||
|
with SQL. Required review decisions remain independent.
|
||||||
|
|
||||||
|
**Calibration opt-in:** separately approve up to ten compatible query embeddings,
|
||||||
|
freeze actor/selection/profile, and only then run:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m app.calibrate_search --user-id $userId --bindings $bindingsPath --output $reportPath --allow-provider-calls
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Set SEARCH_CALIBRATION_REPORT to this successful measured report only after
|
||||||
|
review. Null-cutoff technical_error/measured_failure reports do not unlock search.
|
||||||
|
No voice smoke command exists for the actual runtime yet; Phase 1 must add it.
|
||||||
|
Do not start scripts/live_voice_server.py as grounded-search acceptance:
|
||||||
|
its tool result is hardcoded. Voice smoke requires a third independent opt-in,
|
||||||
|
approved actor/corpus/budget and a ten-minute cap. Ingestion/calibration approval
|
||||||
|
never authorizes Realtime calls.
|
||||||
|
|
||||||
|
## Initial preparation evidence (historical; not rerun by this repair)
|
||||||
|
|
||||||
|
Initial Git status was clean. Read the instructions, current contracts, proof,
|
||||||
|
canonical service, calibration runner/loader, actual LangChain adapter and
|
||||||
|
current calibration records. Read-only configuration inspection observed the
|
||||||
|
model above and a configured Realtime key (value never printed), no proxy and
|
||||||
|
the embedding profile above. Key presence is not access validation.
|
||||||
|
The read-only persisted-profile probe failed to connect; no database mutations
|
||||||
|
or providers were invoked. Exact targeted check outcomes are recorded below
|
||||||
|
after execution. PostgreSQL acceptance, real ingestion, calibration, held-out
|
||||||
|
quality and Realtime/browser smoke are not run. No runtime readiness is claimed.
|
||||||
|
|
||||||
|
Executed targeted provider-free regression command above: **162 passed**, zero skips, 5.49 seconds. CLI help for calibration/intake/selection and tracked git diff --check passed. The first configuration inspection command failed due to Windows quoting; its corrected read-only command passed. No provider or PostgreSQL acceptance was run. A concurrently created untracked scripts/mock_stream_server.py was observed during final inspection and preserved untouched.
|
||||||
|
|
||||||
|
Final preservation checks: proof and all three applied migration files match HEAD byte-for-byte; frozen calibration original hash, changed-document local links, UTF-8 and new-report whitespace passed.
|
||||||
|
|
||||||
|
## Earlier five-findings repair checkpoint (2026-10-08; historical)
|
||||||
|
|
||||||
|
This repair supersedes the earlier incomplete lifecycle/bounds preparation,
|
||||||
|
not the historical test evidence. All five findings are corrected in
|
||||||
|
documentation; runtime enforcement and acceptance remain unimplemented.
|
||||||
|
|
||||||
|
| Finding | Correction / current location |
|
||||||
|
| --- | --- |
|
||||||
|
| 1. Interruption/progress ordering | API 7.1.1-7.1.2: open/sealed/finalizing/retired refs, stop/flush, 1000 ms final window, equal duplicate tombstones, zero missing progress, 5 s acknowledged cleanup barrier before continuation, late-output suppression |
|
||||||
|
| 2. Progress coordinates | API 7.1.1: one ref per provider item/audio content part, no splitting; exact sent bytes, sample alignment, integer floor conversion; new audio_ended delimiter distinguishes generation from playback completion |
|
||||||
|
| 3. Transport bounds | API 7.1.3: byte/count/message/fragment admission, pre-ready rejection, queues and send deadlines, deterministic error/close policy; values explicitly engineering defaults |
|
||||||
|
| 4. Configuration lifecycle | Provider configuration lifecycle table above and plan Section 4: actual whisper-1/fa and model retirement dates, fixed shimmer, future replacement decision |
|
||||||
|
| 5. Reproducible preflight | Read-only operator preflight above: frozen hash, exact bindings object, check_compatibility, enabled actor/scope/ready-selection checks and verified CLI sequence |
|
||||||
|
|
||||||
|
API 7.1.4 contains all six requested contract walkthroughs. Existing event
|
||||||
|
shapes are preserved; audio_ended is the minimal additional delimiter for the
|
||||||
|
last segment, not playback acknowledgement. All mappings/provider IDs remain
|
||||||
|
private; HTTP DTOs and canonical search results are unchanged.
|
||||||
|
|
||||||
|
Unresolved product/deployment decisions: approve engineering frame/queue/ref
|
||||||
|
limits, final-report/cleanup/send windows, capacity/latency targets, idle and
|
||||||
|
shutdown deadlines, auth/session TTL, trusted Origin/hosting, account/funding
|
||||||
|
and replacement profiles before retirement. The defaults define initial
|
||||||
|
integration behavior without recording product approval. Provider multi-part
|
||||||
|
cleanup/cancellation acknowledgement must be proved; unsupported layouts or
|
||||||
|
failed synchronization terminate rather than continuing unsafe context.
|
||||||
|
|
||||||
|
External prerequisites remain verified database/persisted profile, approved
|
||||||
|
originals and ready bindings, enabled same-scope actors, stable full selection,
|
||||||
|
required human reviews, a valid measured calibration report, separate funded
|
||||||
|
ingestion/calibration/voice opt-ins, and later frontend/runtime availability.
|
||||||
|
Missing prerequisites block only their dependent acceptance; absent calibration
|
||||||
|
still returns CALIBRATION_REQUIRED. No cutoff, model access or factual-quality
|
||||||
|
result is invented.
|
||||||
|
|
||||||
|
Current repair validation is documentation-only. Historical 162-test results
|
||||||
|
above were not rerun and do not establish this contract's runtime behavior.
|
||||||
|
No database connection/preflight acceptance, PostgreSQL suite, ingestion,
|
||||||
|
calibration, embeddings, voice or other real-provider call is executed by this
|
||||||
|
repair. The persisted-profile failure above belongs to initial preparation.
|
||||||
|
|
||||||
|
### Earlier executed repair checks and results
|
||||||
|
|
||||||
|
Executed from the repository root, without provider calls:
|
||||||
|
|
||||||
|
~~~text
|
||||||
|
git status --short
|
||||||
|
git diff --stat
|
||||||
|
git diff -- <affected current documentation>
|
||||||
|
git diff --check
|
||||||
|
.venv/Scripts/python -m app.calibrate_search --help
|
||||||
|
.venv/Scripts/python -m app.worker --help
|
||||||
|
.venv/Scripts/python -m app.ingest import --help
|
||||||
|
.venv/Scripts/python -m app.ingest status --help
|
||||||
|
.venv/Scripts/python -m app.knowledge selection get --help
|
||||||
|
.venv/Scripts/python -m app.knowledge selection replace --help
|
||||||
|
~~~
|
||||||
|
|
||||||
|
All six CLI help commands exited 0 and matched the documented positional
|
||||||
|
arguments/flags. Tracked whitespace check exited 0; Git's expected LF/CRLF
|
||||||
|
conversion warnings are not whitespace failures. The local original-hash
|
||||||
|
here-string under Read-only operator preflight was executed verbatim and exited
|
||||||
|
0: original SHA-256
|
||||||
|
7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f,
|
||||||
|
annotation SHA-256
|
||||||
|
b6bd922a0f17a1425d2cf06a3ed801fe0e2a892ec7c069e1e540288b9b2cad8f.
|
||||||
|
|
||||||
|
Read-only inline validation used strict UTF-8 decoding, relative-link existence
|
||||||
|
checks, new-report trailing-whitespace checks, Python ast.parse on both
|
||||||
|
here-string bodies, SHA-256 comparisons against the 177-file repair-start
|
||||||
|
snapshot, and git show HEAD:<path> byte comparisons for the proof and all
|
||||||
|
three applied migrations: passed. PowerShell parsed all six report command
|
||||||
|
blocks with scriptblock.Create without executing their dependent commands:
|
||||||
|
passed. Manual contract consistency review covered all six API walkthroughs,
|
||||||
|
integer/sample/sent-versus-generated accounting, normal and interrupted
|
||||||
|
retirement, final-window/ack barriers, bounds/error/close mapping and
|
||||||
|
plan/report/current-spec alignment.
|
||||||
|
|
||||||
|
Exactly eight documentation files changed in this repair; 168 other baseline
|
||||||
|
files matched their repair-start bytes. A concurrent external edit to
|
||||||
|
scripts/mock_stream_server.py initially triggered the preservation check;
|
||||||
|
it was reported separately and left untouched. No command in this repair
|
||||||
|
writes that file. scripts/live_voice_server.py and all three migrations also
|
||||||
|
match HEAD byte-for-byte. Frozen calibration originals, annotations and
|
||||||
|
status records match the repair-start snapshot.
|
||||||
|
|
||||||
|
Not run: database-dependent read-only preflight (syntax validated only),
|
||||||
|
PostgreSQL acceptance, ingestion/worker processing, calibration/query embeddings,
|
||||||
|
held-out quality, voice/provider smoke, runtime/browser validation and pytest.
|
||||||
|
Historical test/probe results remain explicitly historical. Phase 0 is a
|
||||||
|
documentation checkpoint; no runtime/quality/database readiness is certified.
|
||||||
|
|
||||||
|
## Remaining-four-findings repair checkpoint (2026-10-08)
|
||||||
|
|
||||||
|
This checkpoint supersedes the previous preparation where generation bursts,
|
||||||
|
cancellation races, delayed user transcripts and overlapping turns were
|
||||||
|
underspecified. It is documentation only; no Phase 1-4 runtime is implemented.
|
||||||
|
API Section 7.1 is authoritative. Public event shapes are unchanged by this
|
||||||
|
repair; provider identifiers and release/cancellation tokens remain private.
|
||||||
|
|
||||||
|
| Finding | Correction / authoritative location |
|
||||||
|
| --- | --- |
|
||||||
|
| 1. Bounded output delivery | API 7.1.3/7.1.5: separate G generated reservoir, T transport reservation and R sent-unconfirmed credit ledger; 30 s aggregate backlog, 1500 ms paced window, byte/count/scratch/metadata caps, 5 s no-progress deadline and terminal overload |
|
||||||
|
| 2. Cancellation ownership | API 7.1.2: both VAD flags false, backend-only response-ID-targeted cancellation; coalesced intent, terminal-state race handling, narrow no-active-response exception that never substitutes for cleanup |
|
||||||
|
| 3. Delayed transcripts | API 7.1.6: authorized user-input ASR retains original turn even when delayed; assistant late output cannot restore interrupted work; normal completion is distinguished from actual interruption |
|
||||||
|
| 4. Response release / overlap | API 7.1.6: correlated stop/committed input, current generation token, valid authority/epoch and all cleanup barriers; one consumed initial-create/continuation intent, supersession by genuine new speech and callback-safe gate reevaluation |
|
||||||
|
|
||||||
|
API 7.1.4 now has twelve concrete walkthroughs: the six earlier scenarios plus
|
||||||
|
all six requested burst/stall/race/transcript/commitment/third-turn scenarios.
|
||||||
|
The plan's Phase 1/2 prompts, current implementation guide, architecture audio
|
||||||
|
summary, scenarios and progress records point to the same requirements.
|
||||||
|
Pacing does not equate provider generation completion with application delivery
|
||||||
|
or browser playback. A normally finished exchange is not automatically marked
|
||||||
|
interrupted when new speech begins.
|
||||||
|
|
||||||
|
### Official behavior and unverified assumptions
|
||||||
|
|
||||||
|
Official OpenAI documentation read on 2026-10-08:
|
||||||
|
[client events](https://developers.openai.com/api/reference/resources/realtime/client-events)
|
||||||
|
specifies VAD create_response/interrupt_response, response-ID-targeted
|
||||||
|
cancellation and a session-unaffected error when no response is active;
|
||||||
|
[Realtime reference](https://developers.openai.com/api/reference/python/resources/realtime)
|
||||||
|
describes input transcription as asynchronous to response events and audio
|
||||||
|
generation faster than real time;
|
||||||
|
[conversation guide](https://developers.openai.com/api/docs/guides/realtime-conversations)
|
||||||
|
describes manual response creation with VAD retained, function-result
|
||||||
|
continuation and application-managed WebSocket playback/truncation.
|
||||||
|
|
||||||
|
These sources establish provider capabilities, not the proof's compliance.
|
||||||
|
The selected engineering policy is backend cancellation ownership, both VAD
|
||||||
|
flags false, a 30-second aggregate backlog and 1500 ms delivery window, rather
|
||||||
|
than provider auto-cancellation or unlimited storage. Exact structured
|
||||||
|
no-active-response error classification, speech-start/commit identity ordering,
|
||||||
|
response-intent acknowledgement correlation, multi-item context cleanup,
|
||||||
|
and bounds under real Persian audio require later authorized provider/runtime
|
||||||
|
acceptance. The consulted reference does not publish a stable no-active error
|
||||||
|
code: none is invented, nor is arbitrary error text treated as benign.
|
||||||
|
|
||||||
|
Unresolved engineering/product decisions: approve the backlog/window/count,
|
||||||
|
memory/session admission and stall/cleanup latency budgets; measure allocator
|
||||||
|
overhead, real delta distribution and progress cadence; validate the selected
|
||||||
|
model/account/Origin/network and provider correlations; retain separate model
|
||||||
|
replacement decisions and retirement dates. Defaults define finite initial
|
||||||
|
integration behavior, not product approval or an unlimited-duration guarantee.
|
||||||
|
|
||||||
|
External prerequisites remain a compatible persisted database/profile,
|
||||||
|
approved frozen original/document bindings and enabled same-scope actor,
|
||||||
|
stable approved selection/human reviews, successful measured calibration, and
|
||||||
|
separate ingestion/calibration/voice authorization. CALIBRATION_REQUIRED remains
|
||||||
|
until a valid measured report exists. Missing prerequisites block their
|
||||||
|
dependent acceptance only.
|
||||||
|
|
||||||
|
### Executed / not run for this repair
|
||||||
|
|
||||||
|
Executed checks for this four-findings repair:
|
||||||
|
|
||||||
|
- Read AGENTS.md, the reference map, applicable skill/current contracts,
|
||||||
|
plan/report and actual Git status/diff; no nested instructions were found.
|
||||||
|
- Consulted the official OpenAI references linked above; no provider calls.
|
||||||
|
- `git diff --check` passed (exit 0); existing line-ending notices are
|
||||||
|
informational. Manual contract review checked counters, rounding, pacing,
|
||||||
|
cancellation races, all twelve walkthroughs and current implementation prompts.
|
||||||
|
- Read-only Python inline validation passed: strict UTF-8 and local Markdown
|
||||||
|
link targets in all eight affected documents; report whitespace; two embedded
|
||||||
|
Python examples parsed with `ast.parse` without execution.
|
||||||
|
- PowerShell `[scriptblock]::Create` parsed all six fenced PowerShell examples;
|
||||||
|
their commands were not executed. CLI help was not rerun in this repair.
|
||||||
|
- SHA-256 comparison against the repair-start snapshot: exactly eight
|
||||||
|
documentation files changed, all 169 other baseline files unchanged, no
|
||||||
|
concurrent external changes. Proof, existing mock-server changes and all
|
||||||
|
three applied migrations retain their repair-start bytes; proof/migrations
|
||||||
|
also match HEAD byte-for-byte.
|
||||||
|
- Frozen calibration originals/annotations/status records retain their
|
||||||
|
repair-start hashes. The phase2 original matches the recorded
|
||||||
|
`original_sha256` in `docs/calibration/phase2-cases.json`.
|
||||||
|
|
||||||
|
The inline Python validator used only pathlib/hashlib/json/re/ast and read-only
|
||||||
|
`git show HEAD:<path>`; it opened no database and executed no embedded example.
|
||||||
|
The PowerShell parser read the report and compiled each fenced example only. Earlier 162-test, CLI/preflight and database-probe results
|
||||||
|
remain historical; this repair does not rerun or adopt them as runtime evidence.
|
||||||
|
No database connection/workflow, providers, embeddings, ingestion, calibration,
|
||||||
|
voice, PostgreSQL acceptance, runtime tests or pytest are executed.
|
||||||
|
|
||||||
|
## Playback-stall / cleanup timeout repair (2026-10-08)
|
||||||
|
|
||||||
|
Documentation-only correction; API Section 7.1 remains authoritative. This
|
||||||
|
checkpoint supersedes the earlier unconditional playback-stall wording, not
|
||||||
|
historical check results. Public event shapes and all configured limits remain
|
||||||
|
unchanged; no runtime, transport redesign or provider replacement is implemented.
|
||||||
|
|
||||||
|
- API 7.1.1/7.1.2: only open/sealed refs may be stall-eligible. Interruption
|
||||||
|
atomically moves affected refs to finalizing and invalidates stall identities
|
||||||
|
before browser stop/flush controls. Finalizing includes normal-tail cleanup
|
||||||
|
without relabeling completed output interrupted. Final progress, cancellation
|
||||||
|
confirmation and cleanup acknowledgements retain their independent deadlines.
|
||||||
|
- API 7.1.5: an eligible ref has a successfully sent, reportable unplayed whole
|
||||||
|
millisecond. Each eligibility interval/progress renewal gets a fresh monotonic
|
||||||
|
deadline and private identity. Queued callbacks recheck current state, identity,
|
||||||
|
session usability and expiry under the serialized state decision. Finalization
|
||||||
|
wins make callbacks no-ops; a genuine active stall that wins remains terminal.
|
||||||
|
- Retirement releases only remaining delivery credit once, after acknowledged
|
||||||
|
cleanup when required (or terminal teardown). Frozen generated/sent/played
|
||||||
|
counters survive as bounded evidence; released capacity is not heard audio.
|
||||||
|
Credit release never bypasses current-input/authorization/all-cleanup gates.
|
||||||
|
- API 7.1.4 adds four walkthroughs (sixteen total): final progress 0.2 s, terminal
|
||||||
|
confirmation 4.8 s, cleanup dispatched 4.8 s/acknowledged 9.6 s; a queued stall
|
||||||
|
callback racing finalization; fresh post-cleanup output timing; and genuine
|
||||||
|
active-playback failure at five seconds. The 9.6 s acknowledgement is timely
|
||||||
|
against cleanup's 9.8 s deadline without a stopped-playback timeout at 5 s.
|
||||||
|
|
||||||
|
Plan Phase 1/2 prompts/defaults and implementation guide Section 9 align;
|
||||||
|
architecture/scenario/TODO walkthrough counts and this configuration summary
|
||||||
|
also align. Timer ownership is an engineering contract, not measured provider
|
||||||
|
or browser behavior. Existing capacity/latency approvals, allocator/global
|
||||||
|
admission validation, provider correlation/account/model/Origin access,
|
||||||
|
compatible persisted profile, approved bindings/selection/human reviews and
|
||||||
|
separate ingestion/calibration/voice authorizations remain external gates.
|
||||||
|
CALIBRATION_REQUIRED remains until a valid measured report exists. Missing
|
||||||
|
prerequisites block dependent acceptance only; no runtime, quality or
|
||||||
|
PostgreSQL acceptance is claimed.
|
||||||
|
|
||||||
|
### Checks for this timeout-only repair
|
||||||
|
|
||||||
|
- Executed `git status --short`, `git diff --stat`, affected-file
|
||||||
|
`git diff -- <paths>`, instruction discovery and targeted UTF-8 reads.
|
||||||
|
- Executed `git diff --check`: exit 0; only informational LF/CRLF notices.
|
||||||
|
- Executed `.venv/Scripts/python -c` with a read-only inline validator
|
||||||
|
(pathlib/hashlib/json/re/ast/subprocess; only `git show HEAD:<path>`
|
||||||
|
subprocess reads). Strict UTF-8, local link targets, report whitespace,
|
||||||
|
two Python AST parses, 39 JSON fenced-example parses and the sixteen-row
|
||||||
|
walkthrough count passed; embedded examples were not executed.
|
||||||
|
- Executed PowerShell syntax-only parsing: read the report with
|
||||||
|
`Get-Content -LiteralPath ... -Raw -Encoding UTF8`, extract its
|
||||||
|
`~~~powershell` fences with `[regex]::Matches`, and compile each using
|
||||||
|
`[scriptblock]::Create`: all six parsed, no example commands executed.
|
||||||
|
- Read-only SHA-256 baseline comparison passed: eight affected documents
|
||||||
|
changed; all 169 other baseline files unchanged; no external changes.
|
||||||
|
Proof/mock scripts and three applied migrations match repair-start bytes;
|
||||||
|
proof and migrations also match `git show HEAD:<path>` byte-for-byte.
|
||||||
|
Frozen originals/annotations/status hashes are unchanged and the phase2
|
||||||
|
original matches the recorded original_sha256. The first preservation
|
||||||
|
checker attempt stopped on a Windows-path key mismatch; normalizing
|
||||||
|
separators in the checker fixed it, and the full validation then passed.
|
||||||
|
- Manual contract consistency review covered eligibility/state transitions,
|
||||||
|
timer renewal identity, queued callback races, independent 1/5/5-second
|
||||||
|
barriers, once-only retirement credits, retained evidence, new-output
|
||||||
|
timing and all four walkthroughs against the unchanged response-release gate.
|
||||||
|
|
||||||
|
No database connection/workflow, provider call, ingestion, calibration, voice,
|
||||||
|
CLI help/workflow, runtime test or pytest was run. Earlier acceptance/check
|
||||||
|
results remain historical; these documentation checks establish none of
|
||||||
|
runtime enforcement, model quality or PostgreSQL acceptance.
|
||||||
@@ -10,6 +10,19 @@ This checklist tracks implementation; it does not replace the governing
|
|||||||
Checked baseline items mean existing component implementation, not end-to-end
|
Checked baseline items mean existing component implementation, not end-to-end
|
||||||
MVP acceptance. See the reference map for executed component checks; these do not certify the full MVP.
|
MVP acceptance. See the reference map for executed component checks; these do not certify the full MVP.
|
||||||
|
|
||||||
|
## Realtime Phase 0 checkpoint (2026-10-08)
|
||||||
|
|
||||||
|
- [x] Authorized voice-provider change and frozen 24 kHz PCM16LE/application events documented.
|
||||||
|
- [x] Phase 0 contract preparation repaired: reference/final-report lifecycle, integer coordinates, transport bounds, sixteen walkthroughs, official retirement dates and read-only preflight examples. All remain future runtime obligations.
|
||||||
|
- [x] Remaining four Phase 0 documentation findings corrected: paced generated backlog, backend cancellation/race ownership, delayed user ASR and current committed-turn release/supersession. Runtime remains unimplemented.
|
||||||
|
- [ ] Validate provider cancellation/truncation acknowledgement and enforce documented transport/playback bounds in later runtime work.
|
||||||
|
- [ ] Make separate model/transcription replacement decisions before 2027-01-20 / 2027-02-26 retirement; no automatic migration.
|
||||||
|
- [x] Backend configuration, independent real-call opt-ins and exact next commands recorded in the [Phase 0 report](../guides/realtime-agent-phase0.md).
|
||||||
|
- [ ] Persisted compatible profile, approved bindings and measured cutoff verified; CALIBRATION_REQUIRED remains closed.
|
||||||
|
- [ ] Actual Realtime runtime/tool smoke and browser acceptance (later phases).
|
||||||
|
|
||||||
|
Use the [Realtime MVP plan](realtime-agent-mvp-plan.md) for the current backend sequence; prior WP/day estimates below are historical.
|
||||||
|
|
||||||
## Existing baseline to reuse
|
## Existing baseline to reuse
|
||||||
|
|
||||||
- [x] Phase 1: PostgreSQL/pgvector foundation, frozen processing/embedding profiles and trusted bootstrap.
|
- [x] Phase 1: PostgreSQL/pgvector foundation, frozen processing/embedding profiles and trusted bootstrap.
|
||||||
@@ -78,7 +91,7 @@ or a four-document capacity limit.
|
|||||||
- [x] Expose the shared search through a strict sync/async LangChain tool with lazy imports, bounded admission/deadlines, cancellation and shutdown; see [Phase 3 handoff](../guides/scoped-search-phase3.md).
|
- [x] Expose the shared search through a strict sync/async LangChain tool with lazy imports, bounded admission/deadlines, cancellation and shutdown; see [Phase 3 handoff](../guides/scoped-search-phase3.md).
|
||||||
- [ ] Keep persistent secrets and provider-specific objects behind server adapters.
|
- [ ] Keep persistent secrets and provider-specific objects behind server adapters.
|
||||||
- [ ] Add minimal owned voice conversations, Live sessions and voice tool-call persistence through forward migrations.
|
- [ ] Add minimal owned voice conversations, Live sessions and voice tool-call persistence through forward migrations.
|
||||||
- [ ] Implement session reservation and authenticated backend WSS audio relay to Gemini Live.
|
- [ ] Implement session reservation and authenticated backend WSS audio relay to OpenAI Realtime.
|
||||||
- [ ] Dispatch tools with trusted backend context; model arguments cannot override identity or knowledge scope.
|
- [ ] Dispatch tools with trusted backend context; model arguments cannot override identity or knowledge scope.
|
||||||
- [ ] Correlate current-session transcripts, tool results and displayed sources.
|
- [ ] Correlate current-session transcripts, tool results and displayed sources.
|
||||||
- [ ] Handle follow-up context, interruption/cancellation, provider failure and session termination.
|
- [ ] Handle follow-up context, interruption/cancellation, provider failure and session termination.
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ Deferred: frontend implementation, durable transcript history, public text chat,
|
|||||||
- `audio_started` with `turn_ref` and backend-generated `audio_ref`.
|
- `audio_started` with `turn_ref` and backend-generated `audio_ref`.
|
||||||
- Client `playback_progress` with `audio_ref` and cumulative `played_ms`.
|
- Client `playback_progress` with `audio_ref` and cumulative `played_ms`.
|
||||||
- Retain the existing `session_ready`, `transcript`, `sources`, `turn_interrupted`, and `error` event contracts.
|
- Retain the existing `session_ready`, `transcript`, `sources`, `turn_interrupted`, and `error` event contracts.
|
||||||
|
- Freeze audio_ref lifecycle/coordinates, final progress after interruption, acknowledged truncation before continuation, and transport admission/overflow policy in API Section 7.1. Add audio_ended as a generation delimiter, not playback acknowledgement; one ref per provider output item/audio content part, no splitting. See its sixteen contract walkthroughs, including bounded burst delivery, cancellation races, delayed user ASR, overlapping-turn release and stall/cleanup timer ownership.
|
||||||
|
- Keep these future runtime requirements as documentation in Phase 0; implement none of Phases 1-4 here.
|
||||||
- Verify the persisted embedding profile and approved document bindings. Use the existing calibration command and report loader; never invent a cutoff.
|
- Verify the persisted embedding profile and approved document bindings. Use the existing calibration command and report loader; never invent a cutoff.
|
||||||
- Establish separate explicit opt-ins for ingestion, calibration, and voice smoke calls.
|
- Establish separate explicit opt-ins for ingestion, calibration, and voice smoke calls.
|
||||||
|
|
||||||
@@ -177,6 +179,23 @@ provider/input-item/response/call-to-turn correlation. Keep retrieval
|
|||||||
off the audio receive loop. Coalesce duplicate events within the
|
off the audio receive loop. Coalesce duplicate events within the
|
||||||
active runtime and prevent duplicate response continuation.
|
active runtime and prevent duplicate response continuation.
|
||||||
|
|
||||||
|
Follow authoritative API 7.1.2/7.1.5/7.1.6: acknowledge VAD
|
||||||
|
create_response=false and interrupt_response=false; the backend alone
|
||||||
|
cancels the specific old response. Correlate a narrowly identified
|
||||||
|
no-active-response race with terminal state and complete context cleanup.
|
||||||
|
Keep provider-generated audio in the bounded reservoir and pace browser
|
||||||
|
delivery with progress credits; keep provider control reception responsive.
|
||||||
|
Only eligible open/sealed refs have playback-stall deadlines; atomically
|
||||||
|
invalidate ref/timer identities on finalization, recheck queued callbacks,
|
||||||
|
and start each new eligible interval independently. Retire credit once while
|
||||||
|
retaining heard/sent/generated evidence; cleanup and release gates stay separate.
|
||||||
|
Preserve delayed authorized user transcripts under their original turn;
|
||||||
|
suppress late assistant output only for actually interrupted/superseded work.
|
||||||
|
Gate each response/create and tool continuation on committed current input,
|
||||||
|
valid authority/epoch and every cleanup barrier. Consume one intent, and
|
||||||
|
make cleanup callbacks reevaluate the latest turn token, never release a
|
||||||
|
superseded response. Diagnostic text uses confirmed input-item creation.
|
||||||
|
|
||||||
Use an English policy prompt that requires concise Persian speech,
|
Use an English policy prompt that requires concise Persian speech,
|
||||||
fresh retrieval for document claims and follow-ups, faithful material
|
fresh retrieval for document claims and follow-ups, faithful material
|
||||||
conditions, clarification for ambiguity, and safe handling of
|
conditions, clarification for ambiguity, and safe handling of
|
||||||
@@ -244,6 +263,21 @@ truncation, late-event suppression, bounded queues, and cleanup.
|
|||||||
Accept only documented application controls; never forward arbitrary
|
Accept only documented application controls; never forward arbitrary
|
||||||
browser JSON as provider events.
|
browser JSON as provider events.
|
||||||
|
|
||||||
|
Apply API 7.1.2/7.1.5/7.1.6 exactly: separate bounded generated backlog,
|
||||||
|
transport reservations and browser playback; use a paced progress-credit
|
||||||
|
window, not a two-second cap on a generation burst. Restrict playback-stall
|
||||||
|
timers to eligible open/sealed refs; finalization atomically invalidates them,
|
||||||
|
queued callbacks recheck state/identity, and new eligible output gets fresh
|
||||||
|
timing. Acknowledged retirement releases remaining credit once without
|
||||||
|
changing playback evidence or bypassing response-release barriers. Both VAD flags are
|
||||||
|
false, with backend-owned response-specific cancellation and the narrow
|
||||||
|
no-active cancellation race exception after terminal-state confirmation.
|
||||||
|
Preserve delayed user ASR, distinguish normal completion from interruption,
|
||||||
|
and suppress only ineligible assistant output. Response release requires
|
||||||
|
current correlated input commitment, authorization/epoch and all cleanup
|
||||||
|
barriers; a new genuine speech-start supersedes pending work without
|
||||||
|
restarting old cleanup or letting its callbacks release the old turn.
|
||||||
|
|
||||||
Integrate logical epoch invalidation with the existing selection
|
Integrate logical epoch invalidation with the existing selection
|
||||||
service and close affected runtimes after commit. Handle logout,
|
service and close affected runtimes after commit. Handle logout,
|
||||||
expiry, disablement, provider loss, and startup recovery.
|
expiry, disablement, provider loss, and startup recovery.
|
||||||
@@ -399,13 +433,18 @@ For each material failure, record the scenario, expected behavior, correlated ID
|
|||||||
|
|
||||||
- **Responsibility:** backend implementation and integration support; frontend implementation remains with its developer.
|
- **Responsibility:** backend implementation and integration support; frontend implementation remains with its developer.
|
||||||
- **Development:** local browser first, using a same-origin proxy; HTTPS/WSS remains a separate deployment checkpoint.
|
- **Development:** local browser first, using a same-origin proxy; HTTPS/WSS remains a separate deployment checkpoint.
|
||||||
- **Voice profile:** keep the proof's configured model, `shimmer` voice, and Persian transcription initially; validate provider acknowledgement. No runtime voice switching.
|
- **Voice profile:** preserve gpt-realtime-mini and fixed shimmer; proof input transcription is whisper-1 with language fa (output speed 0.98). Official retirement dates checked 2026-10-08: gpt-realtime-mini 2027-01-20; whisper-1 2027-02-26. No shimmer-specific retirement date found. See [official deprecations](https://developers.openai.com/api/docs/deprecations) and [Phase 0 configuration lifecycle](../guides/realtime-agent-phase0.md). Replacement needs a separate explicit decision/account/budget/validation before retirement; never silently migrate.
|
||||||
- **Search:** reuse the current compatible embedding profile, measured cutoff, evidence limits, and four-running/eight-waiting runner with its existing 75-second maximum.
|
- **Search:** reuse the current compatible embedding profile, measured cutoff, evidence limits, and four-running/eight-waiting runner with its existing 75-second maximum.
|
||||||
- **Proposed local defaults:** eight-hour auth sessions, ten-minute voice sessions, 15-second provider connection timeout, 30-second setup deadline, and at most two seconds of queued audio per direction. Make these configurable engineering defaults.
|
- **Proposed local defaults:** eight-hour auth sessions, ten-minute voice sessions, 15-second provider connection timeout, 30-second setup deadline, and at most two seconds of queued audio per direction. Make these configurable engineering defaults.
|
||||||
|
- **Transport/lifecycle defaults:** API Section 7.1 is canonical: 9600-byte aligned PCM messages; 4096-byte client controls / 65536-byte server events; 96000-byte and 100-message audio queues; 1000 ms final progress window; 5-second cleanup acknowledgement and send deadlines. A separate 1440000-byte (30 s) generated-plus-undrained backlog and 72000-byte (1500 ms) progress-credit delivery window prevent healthy generation bursts overflowing playback; 5 s stalled progress fails explicitly only for eligible open/sealed refs. Finalization invalidates their stall timer atomically; final-progress/cancellation/cleanup deadlines remain independent, callbacks recheck state/identity, and newly eligible output gets fresh timing. Retirement releases credit once while retaining evidence counters. Other reference/input/provider/control/memory caps and current-turn release gates are specified there. These are initial engineering defaults, not product capacity/latency approval.
|
||||||
- **Real-call limits:** retain the existing ten-call calibration and 26-query evaluation bounds. Use a separately opted-in voice smoke run capped at ten minutes total. Ingestion has its own explicit budget.
|
- **Real-call limits:** retain the existing ten-call calibration and 26-query evaluation bounds. Use a separately opted-in voice smoke run capped at ten minutes total. Ingestion has its own explicit budget.
|
||||||
- **External prerequisites:** approved originals/document bindings, required human review, compatible database/provider access, and frontend availability. Missing prerequisites block their dependent acceptance only.
|
- **External prerequisites:** approved originals/document bindings, required human review, compatible database/provider access, and frontend availability. Missing prerequisites block their dependent acceptance only.
|
||||||
- **Markdown artifact:** this plan is stored as `docs/plans/realtime-agent-mvp-plan.md`. Add links to phase completion reports as implementation progresses. This document records the proposed work; it does not claim implementation or runtime acceptance.
|
- **Markdown artifact:** this plan is stored as `docs/plans/realtime-agent-mvp-plan.md`. Add links to phase completion reports as implementation progresses. This document records the proposed work; it does not claim implementation or runtime acceptance.
|
||||||
|
|
||||||
|
## Phase 0 checkpoint (2026-10-08)
|
||||||
|
|
||||||
|
Contract/configuration preparation repaired for ordering, coordinates, transport bounds, provider retirement, preflight, paced output, cancellation races, delayed user transcripts and overlapping-turn release; see [prerequisites, next commands and actual results](../guides/realtime-agent-phase0.md). Measured calibration remains blocked by explicit opt-in, approved bindings and verified database/profile access. Later phases are not implemented by this checkpoint.
|
||||||
|
|
||||||
## Phase 1 repair checkpoint (2026-10-08)
|
## Phase 1 repair checkpoint (2026-10-08)
|
||||||
|
|
||||||
Implemented the scoped existing-runtime repairs; see
|
Implemented the scoped existing-runtime repairs; see
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ Document lifecycle decision (revision 1.1): every upload is an independent immut
|
|||||||
|
|
||||||
## 1. Purpose and Scope
|
## 1. Purpose and Scope
|
||||||
|
|
||||||
The current milestone is the conditional four-day Live document MVP governed by delivery plan revision 1.3. Known users in one organization upload new supported documents through the browser, activate ready knowledge and ask Persian spoken questions. LangChain exposes the shared scoped retrieval/tool boundary; Gemini Live owns native audio conversation. Full text chat, durable messages and settings editing are deferred. Historical/broader sections below do not expand this active scope.
|
The current milestone follows the delivery plan's scoped Phase 0 amendment and the Realtime MVP backend plan; its conditional 3-5 day estimate supersedes the earlier four-day integration sequence. Known users in one organization upload new supported documents through the browser, activate ready knowledge and ask Persian spoken questions. LangChain exposes the shared scoped retrieval/tool boundary; OpenAI Realtime owns native audio conversation. Full text chat, durable messages and settings editing are deferred. Historical/broader sections below do not expand this active scope.
|
||||||
|
|
||||||
The four supplied PDFs/DOCX/image examples are mandatory initial tests, not an upload allowlist or a known final corpus. New files within declared structure/resource limits require no developer code changes.
|
The four supplied PDFs/DOCX/image examples are mandatory initial tests, not an upload allowlist or a known final corpus. New files within declared structure/resource limits require no developer code changes.
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ The initial business use case is a reliable demonstration and subsequent organiz
|
|||||||
|
|
||||||
- PostgreSQL with pgvector stores application data and document embeddings.
|
- PostgreSQL with pgvector stores application data and document embeddings.
|
||||||
- Preserve the implemented hosted embedding adapter, validation and staging from ingestion Phases 1-4, including compatible profiles/vectors; funded deployment identity and Persian quality still need proof. Provider comparison is optional, not required delivery work.
|
- Preserve the implemented hosted embedding adapter, validation and staging from ingestion Phases 1-4, including compatible profiles/vectors; funded deployment identity and Persian quality still need proof. Provider comparison is optional, not required delivery work.
|
||||||
- Initial voice uses direct Gemini Live API access managed by the backend over WSS. There is no mandatory separate ASR, TTS or answer-generation call for each voice turn.
|
- Initial voice uses direct OpenAI Realtime API access managed by the backend over WSS. There is no mandatory separate ASR, TTS or answer-generation call for each voice turn.
|
||||||
- The agent decides whether to call the knowledge search tool and can repeat a search when necessary.
|
- The agent decides whether to call the knowledge search tool and can repeat a search when necessary.
|
||||||
- Documents are dynamically uploaded, updated and selected by the organization.
|
- Documents are dynamically uploaded, updated and selected by the organization.
|
||||||
- The only initial knowledge tool is `search_knowledge`. A separate read-document tool is excluded.
|
- The only initial knowledge tool is `search_knowledge`. A separate read-document tool is excluded.
|
||||||
@@ -46,7 +46,7 @@ The current MVP includes document ingestion/review, organization-scoped retrieva
|
|||||||
1. **Agentic interaction:** the model chooses a registered tool; the backend validates and executes the call. Models never receive database credentials or generate executable SQL for direct execution.
|
1. **Agentic interaction:** the model chooses a registered tool; the backend validates and executes the call. Models never receive database credentials or generate executable SQL for direct execution.
|
||||||
2. **Organization-controlled knowledge:** retrieval is restricted to authorized, selected and ready documents.
|
2. **Organization-controlled knowledge:** retrieval is restricted to authorized, selected and ready documents.
|
||||||
3. **Shared retrieval:** both conversation modes use one search implementation and evidence contract.
|
3. **Shared retrieval:** both conversation modes use one search implementation and evidence contract.
|
||||||
4. **Backend-managed live audio:** the backend relays client audio to direct Gemini Live and executes authorized tools on the same controlled session.
|
4. **Backend-managed live audio:** the backend relays client audio to direct OpenAI Realtime and executes authorized tools on the same controlled session.
|
||||||
5. **Persistent application state:** provider session state and local process memory are not authoritative conversation history.
|
5. **Persistent application state:** provider session state and local process memory are not authoritative conversation history.
|
||||||
6. **Explicit lifecycle:** uploading a file does not immediately make it searchable. Ingestion must complete before publication.
|
6. **Explicit lifecycle:** uploading a file does not immediately make it searchable. Ingestion must complete before publication.
|
||||||
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
|
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
|
||||||
@@ -64,7 +64,7 @@ The current MVP includes document ingestion/review, organization-scoped retrieva
|
|||||||
| Embedding/extraction providers | Existing compatible vector generation and direct/vision extraction | Fixed funded profiles; preserve embedding identity |
|
| Embedding/extraction providers | Existing compatible vector generation and direct/vision extraction | Fixed funded profiles; preserve embedding identity |
|
||||||
| Live provider | Direct audio understanding and speech generation | External live model service |
|
| Live provider | Direct audio understanding and speech generation | External live model service |
|
||||||
|
|
||||||
A provider adapter is backend code. It is not the provider service. The browser uses an authenticated application WSS stream to the backend. The backend owns the Gemini Live connection, credentials, policy and tool execution; the provider service remains external.
|
A provider adapter is backend code. It is not the provider service. The browser uses an authenticated application WSS stream to the backend. The backend owns the OpenAI Realtime connection, credentials, policy and tool execution; the provider service remains external.
|
||||||
|
|
||||||
The two presentation diagrams are retained in Appendix A. They show logical responsibilities; they do not imply that the live model runs inside the backend deployment.
|
The two presentation diagrams are retained in Appendix A. They show logical responsibilities; they do not imply that the live model runs inside the backend deployment.
|
||||||
|
|
||||||
@@ -295,17 +295,17 @@ The worker claims jobs with a lease and claim token, updates progress and publis
|
|||||||
|
|
||||||
Store job attempts, next retry time, stage, error category and processing profile. Retry temporary network/rate-limit failures with bounded backoff; unsupported formats and invalid input require correction. File storage and PostgreSQL do not share a transaction: use staged storage and reconciliation to clean abandoned uploads or recover incomplete metadata transitions.
|
Store job attempts, next retry time, stage, error category and processing profile. Retry temporary network/rate-limit failures with bounded backoff; unsupported formats and invalid input require correction. File storage and PostgreSQL do not share a transaction: use staged storage and reconciliation to clean abandoned uploads or recover incomplete metadata transitions.
|
||||||
|
|
||||||
## 8. Live Voice with direct Gemini API access
|
## 8. Live Voice with backend-managed OpenAI Realtime
|
||||||
|
|
||||||
### 8.1 Connection responsibilities
|
### 8.1 Connection responsibilities
|
||||||
|
|
||||||
Use direct Gemini Live for the initial voice MVP. The provider connection is stateful WSS; the backend relays client audio and controls private tools. Browser-to-provider SDP/WebRTC from revision 1.1 is superseded for this MVP, not assumed compatible with Gemini. See [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api).
|
Use backend-managed OpenAI Realtime for voice, as authorized in the [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md). The provider connection is stateful WSS; the backend relays client audio and controls private tools. The browser uses the application stream, not provider SDP or credentials. See [Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations).
|
||||||
|
|
||||||
OpenRouter is for bounded comparisons of two or three text/vision candidates. Its [audio interface](https://openrouter.ai/docs/guides/overview/multimodal/audio) supports request audio and streamed response audio; that does not establish a compatible bidirectional Gemini Live session.
|
OpenRouter is for bounded comparisons of two or three text/vision candidates. Its [audio interface](https://openrouter.ai/docs/guides/overview/multimodal/audio) supports request audio and streamed response audio; that does not establish a compatible bidirectional OpenAI Realtime session.
|
||||||
|
|
||||||
### 8.2 Session establishment
|
### 8.2 Session establishment
|
||||||
|
|
||||||
Authenticate the HTTP creation request; persist the owned reservation and idempotency hash before provider setup. Validate session/auth/access epoch again at the application WSS handshake using cookie and trusted Origin. The backend connects to Gemini with its server credential, installs Persian instructions and `search_knowledge`, and enables available input/output transcription. Mark connected only after trusted adapter confirmation. The application WSS transport/event fields are proposed in [API catalog Section 7](RAG-Phase1-API-Catalog.md).
|
Authenticate the HTTP creation request; persist the owned reservation and idempotency hash before provider setup. Validate session/auth/access epoch again at the application WSS handshake using cookie and trusted Origin. The backend connects to OpenAI Realtime with its server credential, installs Persian instructions and `search_knowledge`, and enables available input/output transcription. Mark connected only after trusted adapter confirmation. The application WSS audio/event fields are frozen in [API catalog Section 7](RAG-Phase1-API-Catalog.md).
|
||||||
|
|
||||||
### 8.3 Voice tool cycle
|
### 8.3 Voice tool cycle
|
||||||
|
|
||||||
@@ -313,7 +313,7 @@ Authenticate the HTTP creation request; persist the owned reservation and idempo
|
|||||||
sequenceDiagram
|
sequenceDiagram
|
||||||
participant U as Browser or approved audio bridge
|
participant U as Browser or approved audio bridge
|
||||||
participant B as Backend Live controller
|
participant B as Backend Live controller
|
||||||
participant L as Gemini Live
|
participant L as OpenAI Realtime
|
||||||
participant K as Shared knowledge service
|
participant K as Shared knowledge service
|
||||||
participant D as PostgreSQL and pgvector
|
participant D as PostgreSQL and pgvector
|
||||||
U->>B: Authenticated audio stream
|
U->>B: Authenticated audio stream
|
||||||
@@ -331,7 +331,7 @@ sequenceDiagram
|
|||||||
|
|
||||||
The Live model may answer directly from returned evidence. A separate text-generation call on every voice turn is not mandatory. The existing prototype text agent is not a prerequisite for this milestone. The trusted dispatcher invokes the shared LangChain knowledge tool; adding a separate answer model would require a measured purpose and re-estimated latency/cost.
|
The Live model may answer directly from returned evidence. A separate text-generation call on every voice turn is not mandatory. The existing prototype text agent is not a prerequisite for this milestone. The trusted dispatcher invokes the shared LangChain knowledge tool; adding a separate answer model would require a measured purpose and re-estimated latency/cost.
|
||||||
|
|
||||||
Backend dispatch correlates session/call IDs, validates complete arguments, deduplicates same-ID calls and rejects changed arguments. Recheck current document eligibility and epoch before releasing evidence, including cached duplicates. [Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools) require application handling of function responses; validate the chosen model's blocking/asynchronous capabilities rather than combining incompatible examples.
|
Backend dispatch correlates session/call IDs, validates complete arguments, deduplicates same-ID calls and rejects changed arguments. Recheck current document eligibility and epoch before releasing evidence, including cached duplicates. [Realtime function calling](https://developers.openai.com/api/docs/guides/realtime-conversations) requires application handling of function results and authorized response continuation through private provider call IDs.
|
||||||
|
|
||||||
### 8.4 Conversation, interruption and failure behavior
|
### 8.4 Conversation, interruption and failure behavior
|
||||||
|
|
||||||
@@ -351,7 +351,7 @@ Seamless reconnect and provider context restoration are deferred. A new session
|
|||||||
|
|
||||||
### 8.5 Audio, transcripts and telephony boundaries
|
### 8.5 Audio, transcripts and telephony boundaries
|
||||||
|
|
||||||
The proposed application stream uses mono raw PCM matching Gemini: 16-bit little-endian input at 16 kHz and output at 24 kHz. Capture/resample browser audio and convert output for playback; do not forward compressed browser blobs as PCM. The provider accepts explicitly declared input rates, but standardizing the bridge simplifies the MVP. Interruption clears playback buffers. Verify these behaviors against the configured model using [Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities).
|
The frozen application stream uses raw mono signed PCM16LE at 24 kHz in both directions, governed by API Section 7.1. Capture/resample browser audio and convert output for playback; do not forward compressed blobs as PCM. user_speech_started, audio_started and validated playback_progress correlate turns and reported playback. One audio_ref covers one provider item/audio content part; audio_ended seals generation, not playback. API 7.1.1-7.1.4 governs integer sample coordinates, retained references, final reports after interruption, acknowledged private cleanup before continuation, transport bounds and sixteen walkthroughs. API 7.1.5 separately bounds generated audio and paces delivery using validated progress credits; 7.1.6 preserves delayed user ASR and gates response release on current committed input, valid authority/epoch and all cleanup barriers. Both VAD flags are false with backend-owned response-specific cancellation and narrow completion-race handling; normal exchanges are not relabeled interrupted. Interruption clears playback; cleanup failure closes the session instead of continuing with unheard context. See [Realtime audio and interruption](https://developers.openai.com/api/docs/guides/realtime-conversations).
|
||||||
|
|
||||||
Keep available answer transcription and source references visible for the current session. Missing transcription is labeled unavailable, never reconstructed as if spoken; partial generated text does not prove what was heard. Durable full voice history and raw recording remain deferred. The chosen demo model must prove output-transcription delivery; API/storage details must not imply voice messages already exist in the current text-only schema.
|
Keep available answer transcription and source references visible for the current session. Missing transcription is labeled unavailable, never reconstructed as if spoken; partial generated text does not prove what was heard. Durable full voice history and raw recording remain deferred. The chosen demo model must prove output-transcription delivery; API/storage details must not imply voice messages already exist in the current text-only schema.
|
||||||
|
|
||||||
@@ -454,7 +454,7 @@ Final application statuses include `answered`, `needs_clarification`, `insuffici
|
|||||||
|
|
||||||
### 10.3 Live session application contract
|
### 10.3 Live session application contract
|
||||||
|
|
||||||
For Phase 1, the request carries `conversation_id` and `client_request_id`; the response contains session ID, state and an owned application WSS path. The backend connects to direct Gemini Live. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.
|
For Phase 1, the request carries `conversation_id` and `client_request_id`; the response contains session ID, state and an owned application WSS path. The backend connects to direct OpenAI Realtime. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.
|
||||||
|
|
||||||
### 10.4 Error envelope
|
### 10.4 Error envelope
|
||||||
|
|
||||||
@@ -565,7 +565,7 @@ Remove indexing side effects from module imports. Re-embed the source documents
|
|||||||
|
|
||||||
## 18. Implementation Sequence
|
## 18. Implementation Sequence
|
||||||
|
|
||||||
1. Prove actual funded Gemini Persian audio/transcripts/tools and target-network access early.
|
1. Prove actual funded OpenAI Realtime Persian audio/transcripts/tools and target-network access early.
|
||||||
2. Reuse ingestion Phases 1-4; implement Phase 5 worker, exact-output review/resume and complete publication.
|
2. Reuse ingestion Phases 1-4; implement Phase 5 worker, exact-output review/resume and complete publication.
|
||||||
3. Add minimal cookie identity and new-document HTTP upload/status/review/selection.
|
3. Add minimal cookie identity and new-document HTTP upload/status/review/selection.
|
||||||
4. Implement one scoped pgvector search service using compatible existing embeddings.
|
4. Implement one scoped pgvector search service using compatible existing embeddings.
|
||||||
@@ -584,7 +584,7 @@ and capacity/quality targets require confirmation. Documentation is not runtime
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
|
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
|
||||||
| Organization-wide selection | Confirmed MVP direction | Preserve selected-set revision and backend eligibility |
|
| Organization-wide selection | Confirmed MVP direction | Preserve selected-set revision and backend eligibility |
|
||||||
| Exact Gemini Live model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
|
| Configured OpenAI Realtime model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
|
||||||
| Funded embedding/extraction/Live profiles | AI team | Preserve current embedding compatibility; prove real quality/access |
|
| Funded embedding/extraction/Live profiles | AI team | Preserve current embedding compatibility; prove real quality/access |
|
||||||
| Cookie session TTL/account operation | IT / backend | Pre-created local accounts now; SSO deferred |
|
| Cookie session TTL/account operation | IT / backend | Pre-created local accounts now; SSO deferred |
|
||||||
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
|
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
|
||||||
@@ -601,9 +601,9 @@ These items must be resolved by their owners rather than silently converted into
|
|||||||
|
|
||||||
External references establish platform capabilities. Module boundaries, contracts and lifecycle rules in this document are project design proposals. Model/API availability must be checked when implementing the selected adapter.
|
External references establish platform capabilities. Module boundaries, contracts and lifecycle rules in this document are project design proposals. Model/API availability must be checked when implementing the selected adapter.
|
||||||
|
|
||||||
- **[R1]** [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api): initial direct provider/session access.
|
- **[R1]** [OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime): initial direct provider/session access.
|
||||||
- **[R2]** [Gemini Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities): audio, transcription and interruption.
|
- **[R2]** [OpenAI Realtime capabilities](https://developers.openai.com/api/docs/guides/realtime-conversations): audio, transcription and interruption.
|
||||||
- **[R3]** [Gemini Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools): correlated function calls/results.
|
- **[R3]** [OpenAI Realtime tools](https://developers.openai.com/api/docs/guides/realtime-conversations): correlated function calls/results.
|
||||||
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
|
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
|
||||||
|
|
||||||
## Appendix A. Presentation Diagrams
|
## Appendix A. Presentation Diagrams
|
||||||
@@ -684,7 +684,7 @@ flowchart TD
|
|||||||
CHAT <--> TEXT
|
CHAT <--> TEXT
|
||||||
SESSION -->|"Initialize and Control"| LIVE
|
SESSION -->|"Initialize and Control"| LIVE
|
||||||
UI <-->|"Authenticated audio WSS"| SESSION
|
UI <-->|"Authenticated audio WSS"| SESSION
|
||||||
SESSION <-->|"Direct Gemini Live WSS"| LIVE
|
SESSION <-->|"Direct OpenAI Realtime WSS"| LIVE
|
||||||
|
|
||||||
TOOL <--> SEARCH
|
TOOL <--> SEARCH
|
||||||
SEARCH <--> DB
|
SEARCH <--> DB
|
||||||
@@ -704,7 +704,7 @@ No standalone ADR directory or separate requirements specification was found. Th
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Confirmed product direction | Complete upload → extraction/QC → chunk/index → Persian voice → retrieval → grounded spoken answer; text-only or voice without retrieval is insufficient |
|
| Confirmed product direction | Complete upload → extraction/QC → chunk/index → Persian voice → retrieval → grounded spoken answer; text-only or voice without retrieval is insufficient |
|
||||||
| Confirmed existing lifecycle | Independent immutable uploads; direct document/chunk references; manual replacement; same eligible failed document/job retry; existing scope/revision/epoch/fencing rules |
|
| Confirmed existing lifecycle | Independent immutable uploads; direct document/chunk references; manual replacement; same eligible failed document/job retry; existing scope/revision/epoch/fencing rules |
|
||||||
| Confirmed provider direction | Direct Gemini Live; Flash vision extraction candidate; OpenRouter comparisons; USD 20 initial allocation and USD 30 planned budget |
|
| Confirmed provider direction | Direct Gemini Live (historical; superseded for voice by Phase 0); Flash vision extraction candidate; OpenRouter comparisons; historical USD 20 initial allocation and USD 30 planned budget |
|
||||||
| Proposed details | Application WSS event schema, optional tool context, derived extraction artifact, manual quality gate, identifier matching alongside semantic retrieval |
|
| Proposed details | Application WSS event schema, optional tool context, derived extraction artifact, manual quality gate, identifier matching alongside semantic retrieval |
|
||||||
| Verified by static inspection | Markdown folder loader and character splitter; Chroma/FastEmbed `BAAI/bge-small-en-v1.5`; LangGraph `MemorySaver`; configurable OpenAI-compatible text client; prototype chat route without the planned auth/turn contracts |
|
| Verified by static inspection | Markdown folder loader and character splitter; Chroma/FastEmbed `BAAI/bge-small-en-v1.5`; LangGraph `MemorySaver`; configurable OpenAI-compatible text client; prototype chat route without the planned auth/turn contracts |
|
||||||
| Verified by static inspection | Seven-table ingestion foundation and trusted intake CLI/local immutable originals; settings allow only PDF/Markdown; `ExtractedBlock` has text/page/section; no extraction worker, hosted embedding adapter, pgvector chat search, Live adapter or frontend |
|
| Verified by static inspection | Seven-table ingestion foundation and trusted intake CLI/local immutable originals; settings allow only PDF/Markdown; `ExtractedBlock` has text/page/section; no extraction worker, hosted embedding adapter, pgvector chat search, Live adapter or frontend |
|
||||||
@@ -719,7 +719,7 @@ See the [Persian sample scenarios](RAG-Phase1-Scenario-Report-FA.md) for local i
|
|||||||
| Category | Current baseline |
|
| Category | Current baseline |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Confirmed product | Limited demo for known users; new browser uploads; all four examples; unknown future document count |
|
| Confirmed product | Limited demo for known users; new browser uploads; all four examples; unknown future document count |
|
||||||
| Confirmed framework | LangChain RAG/tools; direct Gemini Live audio loop |
|
| Confirmed framework | LangChain RAG/tools; direct OpenAI Realtime audio loop |
|
||||||
| Confirmed reuse | Implemented ingestion/embedding Phases 1-4 and repaired validation/staging; no wholesale embedding refactor |
|
| Confirmed reuse | Implemented ingestion/embedding Phases 1-4 and repaired validation/staging; no wholesale embedding refactor |
|
||||||
| Required next implementation | Fenced worker/review/resume/publication, scoped pgvector search, HTTP identity/upload, owned Live and minimal workspace |
|
| Required next implementation | Fenced worker/review/resume/publication, scoped pgvector search, HTTP identity/upload, owned Live and minimal workspace |
|
||||||
| Deferred milestone | Full text/history/citations, rich settings/delete UI, raw recording, seamless reconnect and CTI |
|
| Deferred milestone | Full text/history/citations, rich settings/delete UI, raw recording, seamless reconnect and CTI |
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
| Milestone | Four implementation days as a conditional demo target; three days is optimistic |
|
| Milestone | Four implementation days as a conditional demo target; three days is optimistic |
|
||||||
| Scope authority | This plan governs the current MVP; it supersedes the previous 7-10 day text-and-voice milestone |
|
| Scope authority | This plan governs the current MVP; it supersedes the previous 7-10 day text-and-voice milestone |
|
||||||
|
|
||||||
|
Phase 0 amendment (2026-10-08): OpenAI Realtime replaces Gemini Live for voice only. The [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md) supplies the current backend phase sequence and conditional 3-5 day estimate; prior four-day schedule is historical. See [Phase 0 prerequisites and results](../guides/realtime-agent-phase0.md). Extraction/embeddings and HTTP/search contracts are unchanged.
|
||||||
|
|
||||||
## 1. Release Objective
|
## 1. Release Objective
|
||||||
|
|
||||||
Deliver an authenticated Persian document assistant with this actual workflow:
|
Deliver an authenticated Persian document assistant with this actual workflow:
|
||||||
@@ -31,7 +33,7 @@ Full text chat and durable message history move to the follow-up milestone.
|
|||||||
|
|
||||||
Confirmed user direction: browser upload, all four supplied examples, new
|
Confirmed user direction: browser upload, all four supplied examples, new
|
||||||
documents beyond those examples, LangChain, reuse of the implemented embedding
|
documents beyond those examples, LangChain, reuse of the implemented embedding
|
||||||
pipeline, and backend-managed direct Gemini Live speech-to-speech.
|
pipeline, and backend-managed direct OpenAI Realtime speech-to-speech.
|
||||||
|
|
||||||
| Existing component | Evidence and reuse boundary |
|
| Existing component | Evidence and reuse boundary |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -49,7 +51,7 @@ dimension, preprocessing or rebuilding compatible vectors. Recorded tests
|
|||||||
establish component behavior only; real hosted-provider quality, Persian
|
establish component behavior only; real hosted-provider quality, Persian
|
||||||
speech and the complete workflow remain unverified.
|
speech and the complete workflow remain unverified.
|
||||||
|
|
||||||
In the first Day 1 work block, prove real Gemini audio, Persian output,
|
In the first Day 1 work block, prove real OpenAI Realtime audio, Persian output,
|
||||||
transcription and a backend-executed function call on the intended network.
|
transcription and a backend-executed function call on the intended network.
|
||||||
Confirm funded embedding/extraction profiles and actual HTTPS hosting in the
|
Confirm funded embedding/extraction profiles and actual HTTPS hosting in the
|
||||||
same day. Failed provider access changes the dependent estimate; it does not
|
same day. Failed provider access changes the dependent estimate; it does not
|
||||||
@@ -65,7 +67,7 @@ justify quietly replacing Live with text.
|
|||||||
| Processing | Existing extraction/chunking/embedding components, separate durable worker, fenced recovery and complete publication | Distributed fleet, broker, batch checkpoint orchestration |
|
| Processing | Existing extraction/chunking/embedding components, separate durable worker, fenced recovery and complete publication | Distributed fleet, broker, batch checkpoint orchestration |
|
||||||
| QC | Evidence-bound review of retained output and explicit factual FAQ approval; clear failures | Elaborate review editor and automatic quality classifier |
|
| QC | Evidence-bound review of retained output and explicit factual FAQ approval; clear failures | Elaborate review editor and automatic quality classifier |
|
||||||
| Search/framework | LangChain tool/retriever integration over one scoped pgvector search service; compatible query embedding and exact identifiers | Retrieval tuning UI; reranker/ANN only if measured failures justify them |
|
| Search/framework | LangChain tool/retriever integration over one scoped pgvector search service; compatible query embedding and exact identifiers | Retrieval tuning UI; reranker/ANN only if measured failures justify them |
|
||||||
| Voice | Direct Gemini Live through backend WSS, Persian speech, follow-ups, topic changes, interruption and visible failure | Seamless reconnect, raw recording, telephony/CTI |
|
| Voice | Direct OpenAI Realtime through backend WSS, Persian speech, follow-ups, topic changes, interruption and visible failure | Seamless reconnect, raw recording, telephony/CTI |
|
||||||
| Visible evidence | Current-session provider transcripts when delivered, retrieved sources with real locators | Guaranteed durable transcript, complete message history and exact spoken-claim attribution |
|
| Visible evidence | Current-session provider transcripts when delivered, retrieved sources with real locators | Guaranteed durable transcript, complete message history and exact spoken-claim attribution |
|
||||||
| Persistence | Original files, jobs/chunks, review decisions, identity, owned voice/session/tool metadata | Durable text turns/messages/citations and cross-mode continuation |
|
| Persistence | Original files, jobs/chunks, review decisions, identity, owned voice/session/tool metadata | Durable text turns/messages/citations and cross-mode continuation |
|
||||||
| Configuration | Fixed server profiles and seeded assistant name/instruction; read-only capabilities | Settings editor, model/voice selector and provider comparisons as required delivery work |
|
| Configuration | Fixed server profiles and seeded assistant name/instruction; read-only capabilities | Settings editor, model/voice selector and provider comparisons as required delivery work |
|
||||||
@@ -97,7 +99,7 @@ attribution has been proved. Refreshing the page need not recover a full transcr
|
|||||||
|
|
||||||
Use one modular FastAPI application, a separate ingestion worker from the
|
Use one modular FastAPI application, a separate ingestion worker from the
|
||||||
same codebase, PostgreSQL/pgvector and durable file storage. LangChain is the
|
same codebase, PostgreSQL/pgvector and durable file storage. LangChain is the
|
||||||
RAG/tool framework; Gemini Live owns the native audio conversation loop.
|
RAG/tool framework; OpenAI Realtime owns the native audio conversation loop.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TB
|
flowchart TB
|
||||||
@@ -109,7 +111,7 @@ flowchart TB
|
|||||||
API --> SEARCH["Shared search service / LangChain tool"]
|
API --> SEARCH["Shared search service / LangChain tool"]
|
||||||
SEARCH --> DB
|
SEARCH --> DB
|
||||||
UI <-->|"Authenticated audio/events WSS"| API
|
UI <-->|"Authenticated audio/events WSS"| API
|
||||||
API <-->|"Direct audio + correlated function calls/results"| LIVE["Gemini Live"]
|
API <-->|"Direct audio + correlated function calls/results"| LIVE["OpenAI Realtime"]
|
||||||
```
|
```
|
||||||
|
|
||||||
### 5.1 Existing embedding pipeline and LangChain boundary
|
### 5.1 Existing embedding pipeline and LangChain boundary
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ Proposed field limits: deferred text message 8000 characters; assistant name 120
|
|||||||
|
|
||||||
Delivery labels define the current MVP. Deferred sections preserve future contracts, not routes required to ship now. F01 is read-only settings/capabilities; C01 only accepts mode=voice in this milestone. The old prototype POST /chat is not a scoped MVP consumer and must not be exposed as an authenticated replacement.
|
Delivery labels define the current MVP. Deferred sections preserve future contracts, not routes required to ship now. F01 is read-only settings/capabilities; C01 only accepts mode=voice in this milestone. The old prototype POST /chat is not a scoped MVP consumer and must not be exposed as an authenticated replacement.
|
||||||
|
|
||||||
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider Gemini WSS connection. Internal model tools have no public REST route.
|
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider OpenAI Realtime WSS connection. Internal model tools have no public REST route.
|
||||||
|
|
||||||
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_knowledge` is internal and has no public HTTP route.
|
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_knowledge` is internal and has no public HTTP route.
|
||||||
|
|
||||||
@@ -265,9 +265,9 @@ Scope key `(conversation_id,client_request_id)`. Changed message under same key:
|
|||||||
|
|
||||||
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
|
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
|
||||||
|
|
||||||
## 7. Voice contract — direct Gemini Live; proposed application WSS
|
## 7. Voice contract — OpenAI Realtime; frozen application audio/events
|
||||||
|
|
||||||
The initial provider is direct Gemini Live managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Audio/event field names below are proposed application names, not provider-native event names.
|
The initial provider is direct OpenAI Realtime managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Phase 0 freezes the application audio/event fields below; implementation remains pending. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID.
|
||||||
|
|
||||||
### V01 — Create session (HTTP)
|
### V01 — Create session (HTTP)
|
||||||
|
|
||||||
@@ -303,12 +303,12 @@ No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Alrea
|
|||||||
|
|
||||||
Proposed WSS upgrade on the V01 `stream_path`: authenticate cookie, trusted Origin, owner, auth session, current epoch and unexpired reservation before accepting. HTTP creation requires normal CSRF; the browser WebSocket handshake uses cookie/Origin validation, not an assumed arbitrary CSRF header. Reject extra caller/model scope. One media connection per session; an additional connection is refused and does not open another provider session.
|
Proposed WSS upgrade on the V01 `stream_path`: authenticate cookie, trusted Origin, owner, auth session, current epoch and unexpired reservation before accepting. HTTP creation requires normal CSRF; the browser WebSocket handshake uses cookie/Origin validation, not an assumed arbitrary CSRF header. Reject extra caller/model scope. One media connection per session; an additional connection is refused and does not open another provider session.
|
||||||
|
|
||||||
Proposed binary client frames carry mono PCM16 little-endian at 16 kHz; server audio frames carry PCM16 at 24 kHz. These rates and bounded frame/buffer limits are agreed at stream setup. JSON control/events are distinguished from binary audio. Bridge/transcoding is backend/client work, not a public provider key flow.
|
Binary frames in both directions carry raw mono signed PCM16LE at 24 kHz (pcm_s16le, one channel, 48,000 bytes/second), without WAV headers or compressed audio. Rates are fixed, not negotiated by callers. Client capture must resample to 24 kHz. JSON controls/events are separate from binary audio. Engineering defaults and deterministic transport admission/close behavior are specified in 7.1.3; all remain runtime implementation obligations.
|
||||||
|
|
||||||
Illustrative proposed control/event shapes:
|
Frozen application control/event shapes (illustrative IDs):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"type":"session_ready","session_id":"a0000000-0000-4000-8000-000000000001","input_audio":{"encoding":"pcm_s16le","sample_rate":16000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}
|
{"type":"session_ready","session_id":"a0000000-0000-4000-8000-000000000001","input_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}
|
||||||
```
|
```
|
||||||
|
|
||||||
```json
|
```json
|
||||||
@@ -327,9 +327,136 @@ Illustrative proposed control/event shapes:
|
|||||||
{"type":"error","turn_ref":"live-turn-2","error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
|
{"type":"error","turn_ref":"live-turn-2","error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
|
||||||
```
|
```
|
||||||
|
|
||||||
Transcript status is partial, completed or interrupted. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
|
Additional server events and the client playback control:
|
||||||
|
|
||||||
On interruption, flush audio buffers, mark partial output, cancel outstanding calls when possible and suppress late results. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
|
```json
|
||||||
|
{"type":"user_speech_started","turn_ref":"live-turn-2"}
|
||||||
|
{"type":"audio_started","turn_ref":"live-turn-1","audio_ref":"live-audio-1"}
|
||||||
|
{"type":"playback_progress","audio_ref":"live-audio-1","played_ms":120}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 7.1.1 Audio coordinates and reference lifecycle
|
||||||
|
|
||||||
|
An output segment is exactly one provider assistant output item/audio content part, from its first sample to provider generation completion or cancellation. Allocate one backend-generated audio_ref per such part, unique and never reused in a session. Provider item/response IDs and content indices stay private. Do not split a part into multiple audio_ref values in this MVP: splitting would require a separately reviewed private sample-offset mapping. Splitting a segment into transport messages does not create a new reference. The adapter must support the documented truncatable audio content index (currently 0); unexpected layouts fail safely, never guess a mapping.
|
||||||
|
|
||||||
|
Emit audio_started before the first binary message for that reference. Binary messages belong to the last audio_started; serialize output parts without interleaving their bytes. Seal the prior part with audio_ended before the next audio_started, unless turn_interrupted has sealed it. Duplicate audio_started with identical turn_ref/audio_ref is a no-op and must not reset playback; a conflicting reuse is a protocol error. Generation completion does not mean playback completion. Add this end delimiter, since neither transcript completion nor another audio_started reliably seals the last part:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"type":"audio_ended","turn_ref":"live-turn-1","audio_ref":"live-audio-1","sent_bytes":48000}
|
||||||
|
```
|
||||||
|
|
||||||
|
audio_ended is server-only and occurs after all successfully sent messages of a normally completed segment. sent_bytes is a nonnegative even integer counting only raw PCM payload bytes whose application WebSocket send completed successfully. It excludes provider-generated bytes still queued, discarded on cancellation, JSON and framing overhead. It is not a claim that the browser received or heard those bytes. Exact duplicate audio_ended is a no-op; changed totals are a protocol error. No audio_ended is required for an interrupted segment: turn_interrupted seals all its audio references. Send uncertainty makes the session unusable; do not continue with ambiguous accounting.
|
||||||
|
|
||||||
|
Reference states are open (may send), sealed (no further bytes, browser may still play), finalizing (cleanup owns the reference; interrupted refs accept bounded final progress), and retired (no progress can alter provider context). Finalizing also covers normal submillisecond-tail cleanup without relabeling the exchange interrupted. Only open/sealed refs can be playback-stall eligible under 7.1.5; finalizing/interrupted/retired refs cannot. Retain sealed mappings and last valid progress even after provider response completion and while newer segments play. At most 64 unretired references per session is an engineering default; exceeding it fails the session rather than evicting an unresolved reference. After interruption cleanup acknowledgement, retire all affected references, retaining their frozen last progress as tombstones until session close. At most 256 references including tombstones per session is an engineering default; fail safely on exhaustion. Session close retires everything. A normally completed reference may retire without truncation only after provider terminal generation, audio_ended, all sends completed, generated_bytes == sent_bytes == 48 * last_valid_played_ms and a whole-millisecond total: every sample is then confirmed by the report. A normal submillisecond-tail cleanup follows 7.1.6 without relabeling an otherwise complete exchange interrupted. Otherwise retain it for interruption cleanup. Do not retire on transcript completion or a rounded progress value alone.
|
||||||
|
|
||||||
|
played_ms is a JSON integer token (not boolean, fractional/exponent-form number, string, NaN or infinity), cumulative duration actually played from the start of that reference, excluding queued audio. The browser computes floor(played_samples / 24) at 24 kHz; the backend computes max_sent_ms = floor(sent_bytes / 48). Accept only 0 <= played_ms <= max_sent_ms and monotonic values within that session/reference; equal duplicates are no-ops. For example, 50 sent bytes = 25 samples: max_sent_ms is 1, never rounded to 2. Provider audio_end_ms is the accepted integer played_ms, equivalent to 24 * played_ms sample positions from the part's start. No public/provider offset conversion is needed. Round down; submillisecond uncertainty is discarded from provider context, not claimed heard. Never silently clamp excessive input to a believable value.
|
||||||
|
|
||||||
|
Send progress once every 100 ms during playback (engineering cadence default) and once at segment completion and immediately after stop/flush. Repeated equal values are allowed. FIFO browser playback spans multiple references; every queued-but-unplayed segment has confirmed progress zero. Progress is a playback assertion subject to validation, never authority or proof of human comprehension.
|
||||||
|
|
||||||
|
#### 7.1.2 Interruption, final reporting and provider continuation
|
||||||
|
|
||||||
|
On genuine trusted user speech detection, first classify prior work using normal-completion versus actual-interruption rules in 7.1.6. For actually unfinished old output, atomically transfer affected refs to finalizing and invalidate their playback-stall timer identities before emitting interruption/stop controls; stop admission/delivery of its audio/tool results, cancel under the ownership rule below, seal sent-byte counters and start the final reporting window. Cleanup now owns those refs: the final-progress, cancellation/terminal and cleanup-ack deadlines below remain enforceable, but stopped/flushed playback has no stall obligation. Final reports never rearm it. Emit turn_interrupted only for affected unfinished old output, before user_speech_started for the new turn. A normally completed exchange retains its completed state; pending input with no assistant output can be superseded internally without inventing an interrupted answer. Duplicate interruption of an already finalizing/retired turn neither restarts timers nor sends cancellation/cleanup twice. A serialized send already completed before interruption is counted; queued unsent bytes are removed and never counted. Suppress all late old-turn audio, audio_started/audio_ended, completed tool results/continuations and assistant transcript completion updates. Delayed user-input transcripts follow 7.1.6 and are not suppressed merely because a newer turn exists. Retain already delivered sources/transcripts only as interrupted display evidence, never claim an exact spoken transcript.
|
||||||
|
|
||||||
|
On turn_interrupted (or user_speech_started while old playback remains), the browser immediately stops currently playing old-turn audio, samples the played position at stop, cancels scheduled playback and flushes every old-turn queued segment. It sends final playback_progress for every retained affected reference, including zero for never-played segments and the last completed position for earlier segments. It stops even if provider generation was already completed. Identical interruption notifications must not resume audio or reset progress. Socket close/error uses the same stop/flush behavior without assuming final reports will arrive.
|
||||||
|
|
||||||
|
The server accepts valid old-reference progress arriving after turn_interrupted while the window is open. Proposed engineering default LIVE_FINAL_PROGRESS_WINDOW_MS is 1000, measured by backend monotonic time from interruption detection, not receipt by the browser. Validate/process fully admitted messages strictly before the deadline in connection order; messages still queued at expiry cannot extend the window. At or after the deadline freeze all last valid values. No extra final flag or acknowledgement is added to playback_progress, so wait the bounded window rather than guessing the last report. Auth expiry/revocation bypasses this wait and closes; progress never renews access. Reports after freezing cannot amend truncation: an equal duplicate against a known frozen/retired value is ignored, changed late/retired or unknown-reference progress is rejected by the error policy below.
|
||||||
|
|
||||||
|
At window expiry use the last valid progress for each part; missing progress means zero, not all sent audio. Coalesce the old response's cancellation request sent at interruption; cancellation alone does not remove unheard context. Privately count all received provider-generated samples, including unsent/cancelled deltas, without delivering late output. Wait for provider terminal generation/cancellation before deciding the final generated total and dispatching cleanup; final played values remain frozen. Privately truncate every affected part with unconfirmed playback, including earlier/later generated parts and parts with zero application sends. Only a terminal part with generated_bytes == sent_bytes == 48 * confirmed_played_ms is fully confirmed and needs no truncation; unsent generated audio and any remaining fraction of a millisecond require cleanup. If the provider cannot truncate a mapped part or remove wholly unheard later output with confirmed cleanup, fail/close the session; do not continue with that context. No invented shortened transcript is returned.
|
||||||
|
|
||||||
|
Require provider-confirmed cancellation/terminal generation within 5 seconds of the one cancellation dispatch, then matching cleanup acknowledgements (item/content/audio_end_ms), with all cleanup acknowledgements received within LIVE_TRUNCATION_ACK_TIMEOUT_SECONDS = 5 after cleanup dispatch (engineering default). Cancellation timeout uses that same configured 5-second bound. Thus the final-report/cancellation barriers have finite deadlines even if the provider never terminates generation. An already-completed response needs no cancel acknowledgement; its unplayed audio still needs cleanup. Coalesce identical pending cleanup and acknowledgements. A conflicting cleanup acknowledgement, truncation/provider failure (apart from the narrowly correlated no-active-response cancellation race below), lost connection or timeout yields normalized LIVE_CONTEXT_SYNC_FAILED, retires the session and requires reconciliation/fresh session. Never infer success from sending truncate or receiving response completion.
|
||||||
|
|
||||||
|
The backend is the sole cancellation and response-creation owner. Configure private VAD create_response=false AND interrupt_response=false and require provider configuration acknowledgement; VAD still reports speech/commit events. The proof's defaults are not evidence of this configuration. For a known active old response, send at most one response.cancel with that specific private response_id and a unique private event_id mapped to the cancellation intent; never issue a bare cancel that could hit a newer response. Record terminal response.done state by response identity. If completion or provider cancellation was already observed for that response, skip cancellation and proceed to required playback/context cleanup.
|
||||||
|
|
||||||
|
A completion/cancellation racing after the backend's active-state check can produce a no-active-response cancellation error. Only an adapter-verified no-active-response classification tied by error event_id to that one cancellation intent/response is benign by itself: it does not fail the session, retry cancellation or satisfy the terminal/cleanup barrier. Independently require a correlated terminal response.done (completed/cancelled; failed/incomplete handled as technical failure) within the bounded cancellation deadline, then complete all required context cleanup. A terminal event already recorded satisfies this test; missing terminal confirmation times out and fails. A response identity mismatch, generic/unrelated error, bad arguments, authentication failure or truncation error is not this exception and remains fatal under its normal policy. Official docs establish the benign behavior but not a stable named error code; an exact structured classifier must be proved with the selected provider profile before race acceptance, never infer it from a free-text substring or swallow all cancellation errors.
|
||||||
|
|
||||||
|
Keep both VAD flags disabled throughout the session. Unexpected automatic generation/cancellation is an observable configuration/protocol deviation; correlate any actual terminal event for cleanup, suppress unintended output and fail if the controlled state cannot be established. The independent response-release gate in 7.1.6 applies even after all cleanup acknowledgements arrive. This is a future runtime obligation, not proof-script behavior.
|
||||||
|
|
||||||
|
#### 7.1.3 Transport admission, queues and terminal errors
|
||||||
|
|
||||||
|
These finite engineering defaults are frozen for initial integration and configurable by trusted deployment only. Product owners still need to approve capacity/latency targets; missing runtime enforcement blocks runtime acceptance, not this documentation checkpoint.
|
||||||
|
|
||||||
|
| Boundary | Limit / accounting |
|
||||||
|
| --- | --- |
|
||||||
|
| Application binary message, either direction | 9600 raw bytes (200 ms), nonempty and even-length; each message ends on a complete PCM16 sample |
|
||||||
|
| Client JSON control message | 4096 UTF-8 bytes before parsing; one object, only playback_progress with exact documented fields; ref strings 1-128 ASCII characters |
|
||||||
|
| Server JSON event message | 65536 UTF-8 bytes; build within a bounded serialization budget; preserve whole evidence/source fields or fail, never truncate them silently |
|
||||||
|
| Application transport audio queues | 96000 raw bytes (2 seconds) AND 100 queued messages per direction; count queues/in-flight sends until completion. Output scheduling also obeys the smaller 72000-byte T+R credit window in 7.1.5 |
|
||||||
|
| Provider-generated reservoir / aggregate undrained output | 1440000 bytes (30 seconds) across G+T+R, 512 packed slabs, bounded descriptors/scratch/metadata; 7.1.5 distinguishes storage from delivery/playback |
|
||||||
|
| Browser output backlog | 96000 bytes AND 100 messages across all refs, including currently playing remainder and scheduled buffers; independently enforced by browser |
|
||||||
|
| Input since last commit | 480000 bytes (10 seconds), including forwarded provider-buffered PCM; fail if not committed within this bound |
|
||||||
|
| Control/event queues | 64 messages and 262144 encoded bytes per direction; ordered relative to audio markers |
|
||||||
|
| Send completion deadline | 5 seconds per message; uncertain/failed send fails session, does not increment confirmed sent_bytes |
|
||||||
|
|
||||||
|
Application message limits apply to reassembled WebSocket messages as well as individual wire fragments: fragmentation cannot bypass the bound. Reject oversized headers before payload allocation; configure transport maximum reassembled size and bounded receive queues, disable compression and reject RSV/compressed frames. Before UTF-8 decoding, JSON parsing, PCM conversion or queue append reserve size/count capacity. Browser code checks byteLength before copying/decoding. Provider receive messages require an independent 262144-byte cap, checked before JSON/base64 decode; decoded audio must be sample-aligned and fit the generated-reservoir/scratch admission in 7.1.5 before allocation/enqueue; it need not fit immediately into the much smaller transport queue. Divide admitted PCM into <=9600-byte even messages. Do not allocate an unbounded delta and then check it.
|
||||||
|
|
||||||
|
Before session_ready, browser capture/send is disabled; backend accepts no application audio/control payload, buffers none, and forwards none to provider. Setup acknowledgement precedes session_ready and any output audio. Early audio/control is LIVE_NOT_READY and closes with 1008. Ping/pong/close protocol frames remain transport concerns. Server emits no binary output without a preceding audio_started. Schema errors, unknown controls, malformed UTF-8/JSON, empty/odd PCM, invalid progress and conflicting reference reuse fail with LIVE_PROTOCOL_ERROR and close 1008. A reference tombstone's equal duplicate is the only accepted post-retirement progress.
|
||||||
|
|
||||||
|
Oversized messages use LIVE_FRAME_TOO_LARGE and close 1009. Capacity exhaustion uses LIVE_BUFFER_OVERFLOW and close 1013. Provider malformed output, send uncertainty, or context synchronization failure uses the corresponding normalized error (LIVE_PROVIDER_PROTOCOL_ERROR, LIVE_TRANSPORT_FAILED, LIVE_CONTEXT_SYNC_FAILED) and close 1011. Stop admissions, cancel work, flush queues and mark the session failed/unusable. Use the existing error envelope with the affected application turn_ref (null before any turn), safe request_id and retryable=false for this unusable session; recovery requires reconciliation and a fresh session. Attempt one bounded error send only if reserved control capacity and a writable socket exist; otherwise close directly. Overflow must not block on enqueueing its own error. Browser detects close even when no JSON error can be delivered and immediately stops/flushes.
|
||||||
|
|
||||||
|
Use queue accounting across references, not a fresh allowance per segment. Unsent canceled bytes may be discarded only while sealing/interruption/terminal failure; never silently drop output and keep generating/counting it as delivered. A genuinely stalled client or exhausted generated backlog fails explicitly under 7.1.5; a healthy generation burst is admitted and paced, not mistaken for transport overflow. Progress acknowledgements do not free server memory for an uncompleted send or expand any limit. Server queue bounds and client playback bounds are separate; neither proves the other.
|
||||||
|
|
||||||
|
#### 7.1.4 Contract walkthroughs (documentation acceptance only)
|
||||||
|
|
||||||
|
| Case | Required sequence / result |
|
||||||
|
| --- | --- |
|
||||||
|
| Final progress after interruption | Ref A last reported 300 ms, 1000 ms sent; interrupt at t=0, browser stops at 420 ms and reports at t=0.2 s. Accept 420 within the 1 s window, truncate privately to 420, wait matching ack, then retire A/allow new response. A later 430 is a protocol error; equal 420 duplicate is ignored. |
|
||||||
|
| Generation done, playback queued | audio_ended seals A at 48000 bytes, but browser has played 200 ms and queued 800 ms. Keep mapping; interruption stops/flushes and final progress governs cleanup. Generation/transcript completion never means 1000 ms heard. |
|
||||||
|
| Later segment interrupted | A and B map to distinct private items/content parts; A sent/played 1000 ms, B sent 800 ms/played 250 ms, later C generated but unheard. Keep A, truncate B to 250 in B's own coordinates, remove/truncate C to zero and wait all required acknowledgements. No A offset is added to B. Unsupported multi-part cleanup closes, rather than retaining C as heard context. |
|
||||||
|
| Duplicates and bad progress | Identical A=250 while open/finalizing or against retired frozen A=250 is a no-op. Unknown A, retired A=251, fractional 250.5, regression 249, boolean, exponent token or value beyond floor(sent_bytes/48) is LIVE_PROTOCOL_ERROR/1008. Timers/calls never restart on duplicates. |
|
||||||
|
| Missing progress | At deadline no valid A report: use zero. Invalid reports never become a default or no_evidence; protocol violations close. Disconnected client prevents continuation, regardless of last progress. |
|
||||||
|
| Oversized/overflowing frames | 9602-byte PCM is LIVE_FRAME_TOO_LARGE/1009; 3-byte PCM is LIVE_PROTOCOL_ERROR/1008. A would-be 96002-byte aligned queue exceeds budget: fail LIVE_BUFFER_OVERFLOW/1013 before append, cancel/flush; unsent bytes are not counted. Before readiness even valid PCM fails LIVE_NOT_READY/1008. |
|
||||||
|
| Six seconds generated in one second | 288000 PCM bytes arrive in multiple provider messages within the per-message cap. Admit into G under the 1440000-byte aggregate limit; T+R never exceeds 72000 bytes. After 1 s of valid real-time playback, 48000 bytes are confirmed and B is about 240000 bytes (plus <1 ms rounding uncertainty). Pace remaining delivery using progress; six-second generation completion neither overflows a healthy browser nor emits audio_ended before the last send. |
|
||||||
|
| Stalled browser reaches the bound | With no increasing progress, only 72000 bytes can enter T/R. G grows until aggregate B reaches 1440000 bytes; the next aligned delta fails LIVE_BUFFER_OVERFLOW/1013 before allocation. If generation stops below that cap, the 5 s no-progress deadline still terminates the stalled session. Cancel/flush, never count unsent audio as delivered. |
|
||||||
|
| Cancel versus terminal response | Backend reserves cancel for old response R1; R1 completes or is cancelled before request reaches provider. A correlated verified no-active-response error is benign only by itself. Record R1's terminal response.done, finish required final-progress/truncation cleanup, then evaluate current-turn release; no cancel retry or blanket provider-error suppression. |
|
||||||
|
| Delayed user transcription | T1 input committed, T2 begins, then ASR completion for T1's private input item arrives. If current authorization/epoch is valid, emit transcript(role=user, turn_ref=T1, status=completed); do not label T2 or release T1. A late assistant completion for interrupted T1 remains suppressed. |
|
||||||
|
| Cleanup while T2 still speaks | T1 truncation ack clears T1 barrier while T2 is speaking. No response.create: T2 still needs its own speech-stop and committed input confirmation. Duplicate T1 ack cannot bypass these conditions. |
|
||||||
|
| T3 before earlier cleanup completes | T2 is pending behind T1 cleanup. A new input item/start for T3 advances the private generation token and supersedes T2; replay of T2 start does not. T1 ack clears only T1's barrier; it cannot release T2, and T3 waits for its own commitment, valid authority and every applicable cleanup. |
|
||||||
|
|
||||||
|
|
||||||
|
| Cleanup outlasts former stall deadline | Interrupt A at t=0: atomically finalizing, stall identity invalidated, browser stops/flushes. Final progress at 0.2 s is accepted; freeze at 1.0 s. Cancellation dispatched at 0; correlated terminal confirmation at 4.8 s satisfies its 5 s deadline. Dispatch cleanup at 4.8 s; matching ack at 9.6 s is within 5 s of dispatch (deadline 9.8). Retire/release remaining credit once without claiming discarded audio heard. No playback timeout at 5 s; response release still requires every 7.1.6 gate. |
|
||||||
|
| Stall callback races finalization | A's deadline callback is queued while interruption acquires the serialized state decision. Finalization invalidates A's timer identity first; the callback rechecks state/identity and does nothing. If the callback instead wins with A eligible and its deadline actually expired, stall failure is terminal. Neither ordering permits double failure/retirement or reviving the session. |
|
||||||
|
| Fresh output after cleanup | A retires after acknowledged cleanup with its frozen evidence retained and remaining credit released once. Once current input/authority/all barriers permit B, B's first reportable successful send at t=10 s starts B's own deadline at 15 s; no A timestamp or callback applies. B's increasing progress renews only B's eligible timer. |
|
||||||
|
| Genuine active-playback stall | A remains open/sealed with 48000 sent bytes, zero valid played_ms and no interruption/cleanup ownership. First reportable send at t=0 starts deadline 5 s. Equal zero reports do not renew it. At t=5 s the matching callback confirms A is still eligible and expires it: LIVE_BUFFER_OVERFLOW/1013, terminal failure/stop/flush. Cleanup exclusion does not excuse a genuinely stalled browser. |
|
||||||
|
|
||||||
|
#### 7.1.5 Generated backlog and paced delivery
|
||||||
|
|
||||||
|
The provider can generate audio faster than real-time playback. The two-second application transport/browser buffers are not a limit on an entire generated response. Keep three distinct counters across all output refs: G = admitted provider-generated PCM not yet scheduled for delivery; T = PCM reserved in the application output queue/in-flight send; R = the outstanding delivery-credit balance for successfully sent PCM not yet confirmed played or explicitly released at retirement/terminal teardown. R is not the retained sent-minus-played evidence counter. A sample moves G -> T -> R without double counting; generated_bytes, sent_bytes and confirmed played bytes remain separate per-reference counters. Never count generated or queued bytes as sent. R is a delivery-credit ledger and need not retain PCM after successful send.
|
||||||
|
|
||||||
|
Initial trusted engineering defaults: maximum aggregate undrained backlog B = G + T + R is 1440000 bytes (30 seconds); at most 512 packed PCM slabs and 64 unretired ref descriptors. Pack provider deltas into bounded <=9600-byte even slabs, preserving ref/order; coalescing tiny deltas prevents provider event count alone exhausting the slab budget. Empty/slab metadata is bounded to 65536 bytes, not a per-delta history. Audio storage G+T cannot exceed B; transport copies are separately limited to 96000 bytes; one provider encoded-message scratch buffer is capped at 262144 bytes and one decoded scratch at 196608 bytes, reserved before decoding. Thus maximum raw/scratch/copy/metadata payload memory is 2060288 bytes per session (object/allocator overhead must also be bounded and measured in later runtime acceptance). Count caps apply before allocation, not after a burst. This supports at most 30 seconds of outstanding generated-but-unconfirmed audio, not arbitrary response duration or unlimited API-process concurrency. Global session admission/memory capacity remains a deployment decision.
|
||||||
|
|
||||||
|
Output scheduler reserves a 72000-byte (1500 ms) sliding delivery window: T + R + next_message_bytes <= 72000, plus transport byte/count capacity. It transfers admitted PCM from G only when credits permit; it never dumps a generation burst into the browser. The remaining margin to the browser's 96000-byte limit covers scheduling/report cadence. Browser backlog retains its independent 96000-byte AND 100-message limit. A progress increase releases only 48 * delta_played_ms bytes from that ref's R after validating it against sent_bytes; rounded fractions remain conservatively outstanding. Identical reports release no credits. Transfer reservations to sent accounting atomically on send completion and release failed/cancelled reservations exactly once. At acknowledged retirement (or terminal session teardown), release that ref's remaining R exactly once through a private retirement-credit marker; atomically mark it released and subtract only its then-outstanding ledger balance. Valid final progress may first reduce R; retirement releases only the remainder. Duplicate progress, cleanup acknowledgements, retirement or teardown cannot release it again. This credit release is capacity bookkeeping, not playback evidence: retain frozen generated_bytes, sent_bytes and last_valid_played_ms in the bounded tombstone, including discarded/unconfirmed amounts. Never set played equal to sent/generated or zero evidence counters to manufacture confirmation. Discard cancelled G/T once under their reservation ownership without changing sent/played counters. Normal fully confirmed retirement has zero remaining R and needs no cleanup acknowledgement under 7.1.1; any retirement with unconfirmed audio while continuing a usable session requires acknowledged cleanup; terminal teardown may release resources but never permits continuation. Do not release R merely on interruption, window expiry, terminal generation or cleanup dispatch. Credit release cannot satisfy any missing cleanup/authorization/commitment barrier or itself trigger response.create; 7.1.6 must independently pass. Reported progress cannot free an uncompleted send, widen any cap or grant authority.
|
||||||
|
|
||||||
|
Delivery messages normally pack up to 9600 bytes; cap queued/in-flight output messages at 100 and scheduler reservations at 64 descriptors. Per-connection ingress/egress/control count limits remain as in 7.1.3. Scheduler waits off the provider receive loop for credit; provider control, speech-start, commitment, cancellation and cleanup events continue to be processed while audio waits. Retain a bounded control lane with interruption/terminal controls ahead of unsent audio, preserving ordering for already sent bytes and audio markers. Socket sends have deadlines and must not block the provider receiver. Do not stop reading provider events as flow control: there is no assumed provider-side generation pause command. Decode/admit each delta only within reservoir/scratch limits; fail safely on exhaustion while still attempting bounded cancellation/close.
|
||||||
|
|
||||||
|
Playback-stall detection is per reference, only while its state is open or sealed, playback has not been interrupted/stopped for cleanup, and successfully sent bytes contain at least one reportable unplayed whole millisecond (floor(sent_bytes / 48) > last_valid_played_ms). Finalizing, interrupted and retired refs are ineligible even if their retained sent/played evidence differs. On entering eligibility, initialize a fresh backend monotonic 5-second deadline and unique private timer identity for that ref; do not inherit another ref's send time, progress time or deadline. A first send with only a submillisecond remainder is not eligible; a later successful send that makes a whole millisecond outstanding starts the deadline then. Strictly increasing valid progress for that eligible ref renews its own deadline with a new timer identity if it remains eligible; reaching no reportable remainder invalidates the timer. Newly reportable output after that point starts a new identity/deadline. Another ref's progress, provider generation and equal reports cannot renew it; pause/mute cannot extend it indefinitely. A genuinely eligible ref with no increasing progress for 5 seconds fails LIVE_BUFFER_OVERFLOW/1013.
|
||||||
|
|
||||||
|
Interruption ownership and the state transition to finalizing must atomically invalidate the timer identity with stopping admission/delivery, before browser stop/flush controls. Normal-tail cleanup also invalidates it when cleanup takes ownership. Do not carry a playback-stall deadline into final reporting or cancellation/context cleanup, and do not rearm it on final progress or a duplicate interruption. Each queued timer callback must reenter the same serialized state decision and verify session usability, matching ref/timer identity, current eligibility and actual monotonic deadline expiry before failing. If finalization wins that decision, an already queued callback is a no-op; if a genuine eligible stall failure wins first, the session stays failed and later interruption cannot revive it. Stale callbacks from retirement, a progress renewal or a previous eligibility interval are no-ops. These timer identities remain private.
|
||||||
|
|
||||||
|
An unreportable <1 ms tail consumes credit/backlog until conservative cleanup/retirement, but cannot trigger stalled-playback failure. Finalizing refs retain their R ledger pending acknowledged retirement and the independent final-progress/cancellation/cleanup deadlines in 7.1.2; a cleanup timeout still fails LIVE_CONTEXT_SYNC_FAILED. In-flight T remains subject to its separate 5 s send deadline; interruption does not excuse send uncertainty or relax transport limits. A healthy 100 ms reporter playing at real time frees credits even if generation finishes early. At B's 30-second/slab/descriptor limit, refuse the next delta before allocation, cancel the correlated response, stop admissions/delivery and fail LIVE_BUFFER_OVERFLOW/1013. Unsupported output beyond the bounded backlog is a terminal capacity failure; do not misreport it as browser slowness. Provider-message, input and control caps retain their independent errors. Never silently drop audio while the session continues. On interruption, discard unsent G/T as cancelled, preserve exact sent/played/generated counters for acknowledged context cleanup, and suppress late old output.
|
||||||
|
|
||||||
|
#### 7.1.6 Transcript classes, turn eligibility and response release
|
||||||
|
|
||||||
|
User transcription is independent ASR of committed input, not assistant response completion. Map private input item identity to its original application turn at speech-start/commit. A delayed authorized user transcript emits the existing transcript shape with role=user, original turn_ref and the provider's partial/completed state even when a newer turn is active or the older request was superseded. It must not change current-turn eligibility, resurrect old work, trigger response creation or be displayed under the newest turn. Revalidate session/actor/access epoch before delivery; revoked/closed-session transcripts are suppressed. Retain input mappings/tombstones until session close with at most 256 input turns per session (engineering default); fail rather than guess an expired mapping or evict a pending transcript. Unknown input correlation is an observable protocol failure. Identical transcription events are no-ops; do not synthesize text on ASR failure.
|
||||||
|
|
||||||
|
Assistant transcripts/audio/tool output use private response/item/call-to-turn correlation. An assistant transcript done event is not proof of successful generation or audible completion: it may occur on cancellation. After actual interruption/supersession, suppress late assistant partial/done/completed events and tool outputs; they cannot restore completed display state or output audio. Already visible interrupted assistant text stays marked interrupted, without invented precise truncation. Delayed user transcripts are expressly exempt from that assistant-only suppression rule.
|
||||||
|
|
||||||
|
Normal exchange completion requires a terminal successful response, no pending tool/continuation or unsent G/T, and valid progress confirming all whole-millisecond output. An unconfirmed submillisecond tail receives conservative private cleanup before subsequent response release without automatically relabeling an otherwise completed exchange interrupted. For that normal tail, no active response needs cancellation and no interruption/final-report window is restarted; freeze its existing maximum reportable progress, transition the ref to finalizing with its stall timer invalidated, acknowledge private truncation, then retire the ref before subsequent response release. A new user turn after normal completion emits user_speech_started only; completed transcripts/sources retain their state. Actual interruption means unfinished generation/tool work, unsent audio or meaningful unplayed audio existed when genuine new speech started. Emit turn_interrupted only for that affected old turn. A pending request superseded before any assistant output is cancelled internally; do not fabricate an interrupted answer/transcript. Completed generation with queued playback is still interruptible.
|
||||||
|
|
||||||
|
Use a private monotonic current-turn generation token independent of access_epoch. A genuine speech start advances it, establishes a speaking input turn, makes older unfinished/pending work ineligible and adds every affected older response to the session cleanup set. Duplicate provider event IDs, or repeated speech-start for the same mapped input item/start position, do not advance it or restart cleanup. Distinct authenticated provider input item/start identities in forward media order are genuine subsequent speech; a known older item or delayed older start is not a new turn. Contradictory identities/ordering fail safely. Replays do not become genuine simply because their event_id differs. None of these private IDs/tokens is sent to the browser.
|
||||||
|
|
||||||
|
For every initial response.create, one serialized backend release decision must establish: (1) session_ready and usable session; (2) current input turn is the unsuperseded token holder; (3) correlated speech-stop and provider input_audio_buffer.committed confirmation identify its input item, not a commit for an earlier utterance; (4) actor/session/ownership/expiry/current authorization and pinned access epoch still match; (5) all older generation-terminal, final-progress, cancellation and context-cleanup barriers in the session cleanup set are satisfied; and (6) no conflicting active response or previously consumed initial-create intent exists. Input transcription completion is not a release prerequisite. The operator-only diagnostic text harness instead requires a provider-confirmed created input item; this exemption neither relaxes audio commitment nor adds a public text route. Cleanup finishing while input is still speaking or uncommitted clears only that barrier; it does not create a response.
|
||||||
|
|
||||||
|
Reserve/consume one initial-create intent per current turn before sending, privately correlate response.created to it (serialized single outstanding creation and backend-only metadata), and never blindly retry an uncertain send/acknowledgement. Uncertain creation closes the session; it cannot generate a second response. This is application exactly-once admission within the session, not a claim of provider network idempotency. Duplicate commit, stop, terminal, tool or cleanup events only reevaluate the gate.
|
||||||
|
|
||||||
|
A tool continuation is distinct from initial creation: authorize the existing canonical result once for its owning current-turn token and completed private call ID/hash, wait for the originating response's terminal tool-call state, send its matching function result once, then consume one continuation intent for that completed authorized call set. All input/authorization/cleanup/current-turn gates still apply. Multiple calls in one response produce one continuation after that authorized call set completes; duplicates never produce parallel responses or repeat results. The intent/result ledger is bounded to 256 entries per session; exhaustion fails explicitly. Late results from superseded turns are suppressed, not fed into new context. No public event shape or canonical tool output changes.
|
||||||
|
|
||||||
|
If T3 genuinely starts while T1 cleanup is pending and T2 has not been released, supersede T2, cancel its admitted retrieval/creation intents, and make T3 current. Continue existing T1 cleanup with unchanged deadlines and add any T2-generated output requiring cleanup; never restart old windows on the new turn. Bound the pending cleanup set by existing response/ref/intent limits. Cleanup callbacks record only their own response/barrier identity and cannot capture a turn to release later. Reevaluate the shared gate against the latest token and all outstanding barriers; T1's acknowledgement cannot release T2. If T3 is speaking, wait; if only T2 is committed, wait for T3's commitment. Retain superseded user input for authorized display/context as mapped user speech, without executing a response to it. Provider commitment ordering/correlation and late-event behavior are assumptions to prove in later authorized runtime acceptance.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Transcript status is partial, completed or interrupted. The backend assigns turn_ref at trusted user speech start and retains original-turn correlation for delayed events. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
|
||||||
|
|
||||||
|
Interruption, final progress, acknowledged context cleanup and late-output suppression follow 7.1.2; generation completion is not playback completion. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
|
||||||
|
|
||||||
### 7.2 Internal model tool — `search_knowledge`
|
### 7.2 Internal model tool — `search_knowledge`
|
||||||
|
|
||||||
|
|||||||
@@ -372,9 +372,9 @@ Keep source identity rows as tombstones if allowed. `available` in API is comput
|
|||||||
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
|
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
|
||||||
| close_reason, error_code | text nullable | Normalized reason |
|
| close_reason, error_code | text nullable | Normalized reason |
|
||||||
|
|
||||||
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. No SDP replay field is required for the proposed Gemini WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential.
|
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. No SDP replay field is required for the OpenAI Realtime WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential.
|
||||||
|
|
||||||
API instance owns the direct Gemini Live WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
|
API instance owns the direct OpenAI Realtime WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
|
||||||
|
|
||||||
### 6.2 audit_events
|
### 6.2 audit_events
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
|
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
|
||||||
|
|
||||||
|
Phase 0 amendment (2026-10-08): OpenAI Realtime replaces Gemini Live for voice only. The [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md) supplies the current backend phase sequence and conditional 3-5 day estimate; prior four-day schedule is historical. See [Phase 0 prerequisites and results](../guides/realtime-agent-phase0.md). Extraction/embeddings and HTTP/search contracts are unchanged.
|
||||||
|
|
||||||
## 1. Purpose and authority
|
## 1. Purpose and authority
|
||||||
|
|
||||||
Implement the conditional four-day Live document MVP in
|
Implement the conditional four-day Live document MVP in
|
||||||
@@ -31,7 +33,7 @@ declared format/structure/resource limits must run without developer changes.
|
|||||||
| Upload | New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count |
|
| Upload | New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count |
|
||||||
| QC | Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state |
|
| QC | Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state |
|
||||||
| Retrieval | Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need |
|
| Retrieval | Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need |
|
||||||
| Voice | Direct Gemini Live audio over backend WSS; shared LangChain knowledge tool |
|
| Voice | Direct OpenAI Realtime audio over backend WSS; shared LangChain knowledge tool |
|
||||||
| Evidence | Current-session provider transcripts/sources; durable owned session/tool diagnostics |
|
| Evidence | Current-session provider transcripts/sources; durable owned session/tool diagnostics |
|
||||||
| Deferred | Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI |
|
| Deferred | Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI |
|
||||||
| Settings | Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities |
|
| Settings | Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities |
|
||||||
@@ -214,13 +216,15 @@ If the browser times out, it queries the turn by client request ID. Retrying the
|
|||||||
|
|
||||||
## 9. Live lifecycle
|
## 9. Live lifecycle
|
||||||
|
|
||||||
Create a fresh owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to direct Gemini Live WSS, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
|
Create a fresh owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to direct OpenAI Realtime WSS, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
|
||||||
|
|
||||||
Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations.
|
Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations.
|
||||||
|
|
||||||
States: `creating → connecting → connected → closed`; any nonterminal state may fail/close. Adapter-confirmed setup defines connected, not client assertions. Use deadlines, bounded audio buffers and TTL; provider calls occur outside database transactions. Restart marks previous nonterminal sessions failed and attempts cleanup.
|
States: `creating → connecting → connected → closed`; any nonterminal state may fail/close. Adapter-confirmed setup defines connected, not client assertions. Use deadlines, bounded audio buffers and TTL; provider calls occur outside database transactions. Restart marks previous nonterminal sessions failed and attempts cleanup.
|
||||||
|
|
||||||
Follow-up questions resolve the last unambiguous document/article, but retrieve fresh evidence. New topics clear old anchors; ambiguous references prompt clarification. Missing/conflicting support is disclosed; tool/provider failure is a technical error. On interruption flush playback, mark output partial/interrupted, cancel outstanding work where possible and discard late results. Logout/expiry/removal close sessions. Reconnect requires reconciliation and a new session; provider context recovery is not promised.
|
Follow-up questions resolve the last unambiguous document/article, but retrieve fresh evidence. New topics clear old anchors; ambiguous references prompt clarification. Missing/conflicting support is disclosed; tool/provider failure is a technical error. On actual interruption flush playback, mark affected unfinished assistant output partial/interrupted, cancel response-specific work and discard late assistant/tool results. A normally completed exchange stays completed; delayed authorized user transcripts retain their original turn. Logout/expiry/removal close sessions. Reconnect requires reconciliation and a new session; provider context recovery is not promised.
|
||||||
|
|
||||||
|
Apply the frozen [API Section 7.1](RAG-Phase1-API-Catalog.md) lifecycle/bounds before runtime acceptance: retain refs through queued playback, accept final reports within the bounded interruption window, await private cleanup acknowledgement before continuation, and close on synchronization/overflow failures. The [Phase 0 report](../guides/realtime-agent-phase0.md) records actual whisper-1/fa configuration, retirement dates and read-only calibration preflight; no automatic provider migration. Use both VAD flags false and backend-only targeted cancellation; a narrowly correlated no-active-response race is benign by itself but still requires terminal confirmation and cleanup. Separate the 30 s generated/undrained backlog from paced 1500 ms delivery credits and two-second transport/browser buffers; keep provider controls responsive. Only eligible open/sealed refs have playback-stall timers; finalization atomically invalidates their identities, queued callbacks recheck current state/identity, and each new eligible interval starts fresh. Acknowledged retirement releases remaining credit exactly once while preserving generated/sent/played evidence; final-progress/cancellation/cleanup deadlines and all release barriers remain independent. API 7.1.6 gates exactly-once response/continuation admission on correlated current input commitment, valid authority/epoch and every cleanup barrier. Genuine later speech advances a private current-turn token; old cleanup callbacks cannot release superseded work. These are documentation obligations, not implemented runtime evidence.
|
||||||
|
|
||||||
Capture/resample client audio and convert returned PCM for playback as specified in architecture Section 8.5. Test real Persian names, dates, percentages and amounts. CTI/Asterisk is outside this web MVP and would need an explicitly commissioned audio bridge.
|
Capture/resample client audio and convert returned PCM for playback as specified in architecture Section 8.5. Test real Persian names, dates, percentages and amounts. CTI/Asterisk is outside this web MVP and would need an explicitly commissioned audio bridge.
|
||||||
|
|
||||||
@@ -272,7 +276,7 @@ and reviewer availability; fixed funded extraction/embedding/Live identities and
|
|||||||
vector dimension; account/quotas/Persian capability proof; hosting/connectivity;
|
vector dimension; account/quotas/Persian capability proof; hosting/connectivity;
|
||||||
session TTL, retention/purge, quantitative quality/latency targets and actual
|
session TTL, retention/purge, quantitative quality/latency targets and actual
|
||||||
presentation date. General browser upload, all four example structures,
|
presentation date. General browser upload, all four example structures,
|
||||||
LangChain, existing embedding reuse and direct Gemini Live are confirmed direction.
|
LangChain, existing embedding reuse and direct OpenAI Realtime are confirmed direction.
|
||||||
|
|
||||||
Exact-output retention/review, FAQ inclusion decisions and their forward schema/
|
Exact-output retention/review, FAQ inclusion decisions and their forward schema/
|
||||||
HTTP mechanisms in this revision are implementation proposals made concrete for
|
HTTP mechanisms in this revision are implementation proposals made concrete for
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from the browser, inspects uncertain extraction, activates ready documents and
|
|||||||
starts a Persian voice conversation. Users hear supported document answers and
|
starts a Persian voice conversation. Users hear supported document answers and
|
||||||
see retrieved sources plus available provider transcripts.
|
see retrieved sources plus available provider transcripts.
|
||||||
|
|
||||||
LangChain supplies the RAG/tool integration boundary. Gemini Live manages
|
LangChain supplies the RAG/tool integration boundary. OpenAI Realtime manages
|
||||||
native audio; the backend owns secrets, identity, tools and scope. Existing
|
native audio; the backend owns secrets, identity, tools and scope. Existing
|
||||||
ingestion/embedding Phases 1-4 remain the processing foundation.
|
ingestion/embedding Phases 1-4 remain the processing foundation.
|
||||||
|
|
||||||
@@ -117,7 +117,7 @@ Request clarification rather than choose an arbitrary similarity match.
|
|||||||
|
|
||||||
Interrupt with the Persian equivalent of "Wait, only tell me the exceptions."
|
Interrupt with the Persian equivalent of "Wait, only tell me the exceptions."
|
||||||
Stop/clear queued playback, mark partial output interrupted and suppress cancelled
|
Stop/clear queued playback, mark partial output interrupted and suppress cancelled
|
||||||
tool results. A late result cannot restart the prior answer.
|
tool results. A late result cannot restart the prior answer. The sixteen contract walkthroughs in [API 7.1.4](RAG-Phase1-API-Catalog.md) cover final progress after interruption, completed generation with queued playback, later output segments, duplicate/invalid progress, missing reports and frame/queue overflow, plus fast generation versus stalled playback, cancellation races, delayed user transcription, speaking/uncommitted input and third-turn supersession; these are expected behaviors, not executed browser acceptance.
|
||||||
|
|
||||||
For no supporting evidence, state the limitation. For conflicting evidence,
|
For no supporting evidence, state the limitation. For conflicting evidence,
|
||||||
disclose conflict or ask clarification. For query embedding/search/provider
|
disclose conflict or ask clarification. For query embedding/search/provider
|
||||||
|
|||||||
Reference in New Issue
Block a user