- Organize architecture, specifications, plans, and guides into dedicated subdirectories under docs/ - Remove legacy and duplicate documents from data/documents/ - Update AGENTS.md, README.md, and agent skills to target canonical docs paths
407 lines
32 KiB
Markdown
407 lines
32 KiB
Markdown
# RAG Assistant — Phase 1 API Catalog
|
||
|
||
Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational.
|
||
|
||
Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1.
|
||
|
||
## 1. Transport and common conventions
|
||
|
||
Base path `/api/v1`; UTF-8 JSON except multipart upload; same-origin HTTPS. UUIDs identify application records. Timestamps are UTC RFC3339. `null` means unavailable, not an invented source location. Unexpected request fields return 422. Example UUIDs are illustrative.
|
||
|
||
Secure HttpOnly `rag_session` cookie authenticates requests. Login and all mutations enforce trusted Origin; authenticated mutations also require `X-CSRF-Token`. `/me` returns a CSRF token for refresh. No frontend persistent provider key, organization ID override or model override is accepted.
|
||
|
||
Roles: `admin` and `user`. Both can create owned voice conversations and read/control their own Live state. Only admin manages uploads, review, retry and selection. Hidden resource access returns 404. Admin does not implicitly own all conversations. Full text chat/history, delete UI and settings mutation are deferred.
|
||
|
||
Lists use `limit` (default 20, maximum 100) and opaque `cursor`. Stable ordering is `(created_at DESC,id DESC)` except messages, ordered by ascending `sequence_no`. Responses use `{items:[],next_cursor:null}`. Unknown/invalid cursor returns 422. No total count is promised.
|
||
|
||
`X-Request-ID` response header and `error.request_id` correlate logs. Servers generate one if none is valid. `Idempotency-Key` is required on upload, manual ingestion retry and delete; UUID `client_request_id` is required in create-conversation, chat and create-live bodies. Keys are scoped to actor/organization and operation as specified below. Reuse with different normalized input returns 409.
|
||
|
||
Proposed field limits: deferred text message 8000 characters; assistant name 120; instruction 8000; search query 2000; conversation title 120; document title 200; review note 2000. File limits/formats and audio frame caps come from deployment configuration and are exposed as capabilities where useful. These are implementation defaults to confirm, not provider guarantees.
|
||
|
||
## 2. Endpoint inventory
|
||
|
||
| ID | Method and path | Access | Success | Delivery |
|
||
| --- | --- | --- | --- | --- |
|
||
| A01 | POST `/auth/login` | Public, trusted Origin | 200 + cookie | MVP |
|
||
| A02 | POST `/auth/logout` | Authenticated; expired/missing session accepted | 204 | MVP |
|
||
| A03 | GET `/me` | Authenticated | 200 | MVP |
|
||
| D01 | POST `/documents` | Admin | 202 | MVP |
|
||
| D02 | GET `/documents` | Admin | 200 | MVP |
|
||
| D03 | GET `/documents/{document_id}` | Admin | 200 | MVP |
|
||
| D04 | POST `/documents/{document_id}/retry` | Admin | 202 | MVP |
|
||
| D05 | DELETE `/documents/{document_id}?expected_revision=N` | Admin | 202 | Deferred |
|
||
| D06 | GET `/documents/{document_id}/extraction-review` | Admin | 200 | MVP |
|
||
| D07 | POST `/documents/{document_id}/extraction-review/decisions` | Admin | 200 | MVP |
|
||
| K01 | GET `/knowledge-selection` | Admin | 200 | MVP |
|
||
| K02 | PATCH `/knowledge-selection` | Admin | 200 | MVP |
|
||
| F01 | GET `/configuration` | Authenticated | 200 | MVP |
|
||
| F02 | PATCH `/configuration` | Admin | 200 | Deferred |
|
||
| C01 | POST `/conversations` | Authenticated | 201 | MVP: voice only |
|
||
| C02 | GET `/conversations` | Owner | 200 | Deferred |
|
||
| C03 | GET `/conversations/{conversation_id}/messages` | Owner | 200 | Deferred |
|
||
| T01 | POST `/chat` | Owner of text conversation | 200 or 202 | Deferred |
|
||
| T02 | GET `/conversations/{conversation_id}/turns/{client_request_id}` | Owner | 200 | Deferred |
|
||
| V01 | POST `/voice/sessions` | Owner of voice conversation | 201 or 202 | MVP |
|
||
| V02 | GET `/voice/sessions/{session_id}` | Owner | 200 | MVP |
|
||
| V03 | GET `/voice/sessions/by-request/{client_request_id}` | Owner | 200 | MVP |
|
||
| V04 | POST `/voice/sessions/{session_id}/close` | Owner | 200 | MVP |
|
||
| H01 | GET `/health/live` | Deployment health access | 200 | MVP |
|
||
| H02 | GET `/health/ready` | Deployment health access | 200 or 503 | MVP |
|
||
|
||
Delivery labels define the current MVP. Deferred sections preserve future contracts, not routes required to ship now. F01 is read-only settings/capabilities; C01 only accepts mode=voice in this milestone. The old prototype POST /chat is not a scoped MVP consumer and must not be exposed as an authenticated replacement.
|
||
|
||
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider Gemini WSS connection. Internal model tools have no public REST route.
|
||
|
||
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_knowledge` is internal and has no public HTTP route.
|
||
|
||
## 3. Authentication
|
||
|
||
### A01 — Login
|
||
|
||
```json
|
||
{"username":"demo.admin","password":"<password>"}
|
||
```
|
||
|
||
```json
|
||
{"user":{"id":"01000000-0000-4000-8000-000000000001","username":"demo.admin","role":"admin","organization_id":"02000000-0000-4000-8000-000000000001"},"csrf_token":"<session-csrf-token>","expires_at":"2026-10-05T18:00:00Z"}
|
||
```
|
||
|
||
Credentials invalid: 401 `INVALID_CREDENTIALS`; throttled: 429. Do not distinguish missing username from wrong password. Expiry above is illustrative. Set Secure/HttpOnly/SameSite=Lax cookie; rotate tokens after successful login.
|
||
|
||
### A02 — Logout
|
||
|
||
No body. Revoke current session, clear cookie and close owned live sessions linked to it. Repeated logout returns 204. For a valid session require CSRF; missing/expired session may simply clear cookie after Origin validation.
|
||
|
||
### A03 — Current identity
|
||
|
||
No body. Same identity/CSRF/expiry shape as login. Missing/expired session returns 401 `AUTH_REQUIRED`.
|
||
|
||
## 4. Documents and selected knowledge
|
||
|
||
### D01 — Upload
|
||
|
||
`multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive.
|
||
|
||
Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PNG with byte/signature/package/image bounds and correct MIME. D01 accepts new files without a repository filename/hash allowlist. The four examples are acceptance fixtures, not upload eligibility. Stream/spool within configured limits; do not buffer an unbounded request. These engineering defaults do not imply every layout is extractable or total corpus capacity is unlimited. D01 HTTP transport remains planned.
|
||
|
||
```json
|
||
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false}
|
||
```
|
||
|
||
202 acknowledges durable metadata/job creation, not completed processing. Replay same upload returns these stable identities with current processing state and header `Idempotency-Replayed: true`. Scope key to organization; hash bytes and normalized title. 413 `FILE_TOO_LARGE`, 415 `UNSUPPORTED_FILE_TYPE`, 422 `INVALID_FILE`, 409 `IDEMPOTENCY_CONFLICT`. A parser failure after acceptance is represented by document status, not a later HTTP response to upload.
|
||
|
||
### D02 — List
|
||
|
||
Query: common pagination; optional `status=queued|processing|ready|failed`, `is_active=true|false`. Exclude deleted documents. Items use the D03 shape, except potentially omit verbose error detail. Return current `knowledge_revision` alongside the list.
|
||
|
||
### D03 — Detail / processing polling
|
||
|
||
```json
|
||
{"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}}
|
||
```
|
||
|
||
`searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail may include `review_required:false` for other outcomes. D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.
|
||
|
||
### D04 — Retry failed processing
|
||
|
||
No body; required `Idempotency-Key`. Eligible only for failed undeleted document and retained original. Requeue same job, reset attempt count, increment retry generation and audit. Same key replays without incrementing twice.
|
||
|
||
```json
|
||
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","retry_generation":1}
|
||
```
|
||
|
||
409 `DOCUMENT_NOT_RETRYABLE` for running/ready/unrecoverable failure; 404 hidden/deleted. Review-required retry becomes eligible only after all currently pending evidence-bound approvals exist; additional pages can require later review. An unapproved candidate returns 409 `EXTRACTION_REVIEW_PENDING`; rejection stays failed. Successful factual-corpus review is a separate precondition where required. No ready document is reindexed through retry. The retry-key record is retained in audit metadata with a database uniqueness constraint.
|
||
|
||
### D06 - Read retained extraction/factual review
|
||
|
||
Admin-only, paginated bounded review candidates. No provider calls. Return 404
|
||
for hidden/deleted documents. A document with no pending candidates returns an
|
||
empty items list. Example application shape:
|
||
|
||
```json
|
||
{"document_id":"10000000-0000-4000-8000-000000000001","status":"failed","review_required":true,"items":[{"evidence_sha256":"<server-computed-digest>","review_kind":"extraction","location":{"page":1,"section":"pdf/page/1"},"blocks":[{"block_id":"pdf/page/1/block/1","text":"<retained exact extraction>","group_id":null}],"required_checks":["readability","order","completeness","numbers","dates","negation","exceptions"],"decision":null,"preview_path":"/api/v1/documents/10000000-0000-4000-8000-000000000001/extraction-review/<digest>/preview"}],"next_cursor":null}
|
||
```
|
||
|
||
Serve the retained image on authenticated GET
|
||
`/documents/{document_id}/extraction-review/{evidence_sha256}/preview`.
|
||
This is a D06 subresource with the same admin/organization/candidate checks,
|
||
configured byte/pixel limits, a validated image MIME and Cache-Control: no-store.
|
||
It accepts no raw path or redirect and exposes no internal storage key.
|
||
For factual_corpus candidates, preview_path may be null and blocks are grouped
|
||
Q&A and their governing context with real source locators from the retained complete
|
||
extraction. Context association is deterministic; ambiguous scope fails visibly.
|
||
required_checks then includes factual
|
||
authority, whole-pair association, behavioral separation and placeholders.
|
||
Locators/digests are actual server values; illustrative strings are not API values.
|
||
|
||
### D07 - Decide on retained evidence
|
||
|
||
Required Idempotency-Key; normal admin Origin/CSRF checks. Server derives actor.
|
||
One candidate decision per request; UI may submit multiple requests.
|
||
|
||
```json
|
||
{"evidence_sha256":"<digest-from-D06>","decision":"approve","checked":["readability","order","completeness","numbers","dates","negation","exceptions"],"note":"Compared retained extraction against the original page.","excluded_group_ids":[]}
|
||
```
|
||
|
||
200 returns document_id, evidence_sha256, decision and review_required indicating
|
||
whether current pending decisions remain. It does not enqueue, activate or
|
||
mark ready; D04 resumes the same failed job with its own key.
|
||
|
||
Allow approve/reject only. Require a nonblank bounded note; approval checked
|
||
must match the server-required check set. For extraction, excluded_group_ids
|
||
must be empty. For factual_corpus, permit only whole existing Q&A group IDs
|
||
to exclude unapproved facts, behavioral entries or live-data placeholders.
|
||
Store the inclusion manifest separately; never edit original/faithful extraction.
|
||
An empty eligible factual set cannot be indexed.
|
||
|
||
Scope idempotency to organization/actor/document/extraction_review/key; hash
|
||
the canonical decision, checks, note, evidence digest and excluded group IDs.
|
||
Replay is resolved before new state checks but after authorization; it returns
|
||
the saved decision without mutating current candidate state. Changed payload
|
||
returns 409 IDEMPOTENCY_CONFLICT. A new conflicting decision for an already
|
||
decided candidate returns 409 REVIEW_ALREADY_DECIDED. Removed/superseded evidence,
|
||
wrong failed-job state or profile/source mismatch returns 409 REVIEW_STALE.
|
||
Invalid digest/check/group shape returns 422 VALIDATION_ERROR.
|
||
|
||
A valid digest alone grants no access. Recompute/validate trusted retained
|
||
candidate identity under the document/job locks; don't trust client blocks,
|
||
paths, models or reviewer fields. Rejecting keeps zero publication and a safe
|
||
failure reason. Lost worker ownership cannot attach candidates; an admin cannot
|
||
approve a fresh OCR response using an old digest.
|
||
|
||
### D05 — Delete (deferred HTTP/UI)
|
||
|
||
Required `expected_revision` is the current knowledge revision; required idempotency key. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response.
|
||
|
||
```json
|
||
{"document_id":"10000000-0000-4000-8000-000000000001","deleted":true,"knowledge_revision":3,"access_epoch":2,"cleanup_status":"pending_policy"}
|
||
```
|
||
|
||
202; 409 `REVISION_CONFLICT` on stale initial request. Replay same delete/key returns recorded result before revision validation. A new delete request for an already-deleted owned document can return its tombstone result without changing revisions. No read or search route restores eligibility.
|
||
|
||
### K01 — Get selection
|
||
|
||
```json
|
||
{"revision":1,"access_epoch":1,"document_ids":[]}
|
||
```
|
||
|
||
### K02 — Replace selected set
|
||
|
||
This replaces the entire set, not a delta. UI reads current selection before toggling a document.
|
||
|
||
```json
|
||
{"expected_revision":1,"document_ids":["10000000-0000-4000-8000-000000000001"]}
|
||
```
|
||
|
||
```json
|
||
{"revision":2,"access_epoch":1,"document_ids":["10000000-0000-4000-8000-000000000001"],"conversations_invalidated":false}
|
||
```
|
||
|
||
Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected IDs in details; no partial update. Hidden ID: 404. Stale revision: 409 `REVISION_CONFLICT`. No-op preserves revision. Removing an active ID increments epoch and sets `conversations_invalidated=true`; all older organization conversations become unusable for new turns. After a timeout GET current state instead of blindly repeating with an old revision.
|
||
|
||
## 5. Configuration (read-only in MVP)
|
||
|
||
### F01 — Read
|
||
|
||
```json
|
||
{"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":null}}
|
||
```
|
||
|
||
Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.
|
||
|
||
### F02 — Update (deferred)
|
||
|
||
```json
|
||
{"expected_revision":1,"assistant_name":"HR Assistant","instruction":"Use formal Persian and state when supporting evidence is missing."}
|
||
```
|
||
|
||
200 returns F01 with incremented revision. Both fields are required; no-op preserves revision. Stale value: 409 `REVISION_CONFLICT`. Text applies on subsequent turns; existing live session keeps its snapshot until restarted. Settings cannot relax system authorization or grounding rules.
|
||
|
||
## 6. Conversations and deferred text
|
||
|
||
### C01 — Create
|
||
|
||
```json
|
||
{"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"voice","title":"Working hours"}
|
||
```
|
||
|
||
```json
|
||
{"id":"60000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours","status":"active","access_epoch":1,"created_at":"2026-10-05T09:05:00Z"}
|
||
```
|
||
|
||
The current MVP accepts `mode=voice` only; text/mixed requests return 409 `MODE_MISMATCH`. Follow-up text support uses a separate mode and must not silently alter the voice contract. Title optional. Idempotency scope `(owner,client_request_id)`; same payload replays original 201. Different payload 409. New conversation snapshots current epoch. Voice history cannot be continued as text in Phase 1.
|
||
|
||
### C02 — List own conversations (deferred history UI)
|
||
|
||
Common pagination, optional `mode`. Items use C01 response plus `updated_at`; derive `status=stale` when epoch differs. Status values: active, stale, closed. List excludes other users regardless of role.
|
||
|
||
### C03 — Read messages (deferred)
|
||
|
||
Common pagination, ascending sequence. Voice can return no durable messages: current-session answer transcripts are delivered through Live events when available; durable full voice history is deferred. Old text history remains viewable even when stale.
|
||
|
||
```json
|
||
{"conversation_id":"60000000-0000-4000-8000-000000000001","conversation_status":"active","items":[{"id":"70000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","sequence_no":1,"role":"user","content":"What are the Thursday opening hours?","created_at":"2026-10-05T09:06:00Z","sources":[]}],"next_cursor":null}
|
||
```
|
||
|
||
Assistant items also expose `turn_status` and source objects. Failed turns remain visible as state, not fabricated assistant answers. A user message may exist without an assistant reply; UI follows turn status.
|
||
|
||
### T01 — Submit text turn (deferred)
|
||
|
||
```json
|
||
{"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"What are the Thursday opening hours?"}
|
||
```
|
||
|
||
```json
|
||
{"conversation_id":"60000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","status":"answered","message_id":"70000000-0000-4000-8000-000000000002","answer":"The illustrative working-hours document states Thursday closing is noon.","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"Illustrative Thursday hours: 08:00 to 12:00.","location":{"page":2,"section":null},"available":true}],"error":null}
|
||
```
|
||
|
||
200 returns terminal execution: answered, needs_clarification, insufficient_information or failed. `answer`/`message_id` are null on failed, with normalized error. A successfully processed unsupported question uses insufficient_information, human-readable answer and usually empty sources. Failed generation is not reported as a successful answer.
|
||
|
||
202 returns a running turn shape with `answer:null`, `message_id:null`, empty sources, `error:null` and `Location` pointing to T02. This occurs on duplicate running request or when the initial response deadline expires while the owned task is still running. Do not start a second task. Client disconnection must not silently create duplicate execution.
|
||
|
||
Scope key `(conversation_id,client_request_id)`. Changed message under same key: 409. Another different request while one runs: 409 `CONVERSATION_BUSY`. Wrong mode: 409 `MODE_MISMATCH`. Stale epoch: 409 `CONVERSATION_STALE`. Admission failures use the common HTTP error envelope; failures after a turn is persisted use its failed terminal result. Retry completed failures only with a new request ID.
|
||
|
||
### T02 — Recover/poll turn (deferred)
|
||
|
||
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
|
||
|
||
## 7. Voice contract — direct Gemini Live; proposed application WSS
|
||
|
||
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.
|
||
|
||
### V01 — Create session (HTTP)
|
||
|
||
```json
|
||
{"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001"}
|
||
```
|
||
|
||
```json
|
||
{"session_id":"a0000000-0000-4000-8000-000000000001","conversation_id":"61000000-0000-4000-8000-000000000001","status":"connecting","stream_path":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001/stream","expires_at":"2026-10-06T09:30:00Z","poll_url":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"}
|
||
```
|
||
|
||
Voice conversation must be owned and current-epoch. Reserve session before provider creation. Scope key `(owner,client_request_id)`; hash normalized conversation/create options, with no SDP. Changed payload is 409. One nonterminal session per conversation. Duplicate creation returns 202 and the existing ID/state; completed replay returns 201 with the same still-eligible session. Replay never creates another provider connection. Closed/failed/expired returns 409 `LIVE_SESSION_UNUSABLE`.
|
||
|
||
No persistent provider secret or provider credential is returned. Backend adapter installs tools/Persian policy and enables available transcription before marking usable. Provider timeout leaves failed/uncertain reservation: inspect with V03, never blind recreation. 503 can represent a capability failure before reservation. `connecting` is not proof of working audio.
|
||
|
||
### V02 — Poll state, diagnostics and recent retrieved sources (HTTP)
|
||
|
||
```json
|
||
{"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-06T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-06T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","excerpt":"<verified source passage>","location":{"page":1,"section":"<verified clause>"},"available":true}]}]}
|
||
```
|
||
|
||
Illustrative payload; not an extracted source quotation. At most 20 recent results, chronological, deduplicate by tool_call_id. Sources are retrieved evidence unless exact answer attribution is verified. Redact revoked excerpts and mark unavailable. States: creating, connecting, connected, closed, failed. Poll approximately every 2 seconds while active; stop at terminal state. Polling is not durable transcript recovery. A client cannot claim connected state or inject a trusted tool result.
|
||
|
||
### V03 — Recover creation by request ID (HTTP)
|
||
|
||
200 returns V01's session/path shape if reservation remains eligible, otherwise terminal state and `stream_path:null`. Owner-only, 404 if no reservation, never creates a session. Before starting a fresh request after media loss, reconcile/close the old session. The old path does not restore provider context.
|
||
|
||
### V04 — Close (HTTP)
|
||
|
||
No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Already terminal returns its existing state. Close application stream/microphone/playback and attempt provider cleanup. Unresolved cleanup is logged and bounded by expiry; logout, auth expiry, epoch revocation and provider loss also close the session.
|
||
|
||
### 7.1 Application Live stream (WebSocket)
|
||
|
||
Proposed WSS upgrade on the V01 `stream_path`: authenticate cookie, trusted Origin, owner, auth session, current epoch and unexpired reservation before accepting. HTTP creation requires normal CSRF; the browser WebSocket handshake uses cookie/Origin validation, not an assumed arbitrary CSRF header. Reject extra caller/model scope. One media connection per session; an additional connection is refused and does not open another provider session.
|
||
|
||
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.
|
||
|
||
Illustrative proposed control/event shapes:
|
||
|
||
```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}}
|
||
```
|
||
|
||
```json
|
||
{"type":"transcript","turn_ref":"live-turn-1","role":"assistant","text":"<provider-supplied Persian transcript>","status":"completed"}
|
||
```
|
||
|
||
```json
|
||
{"type":"sources","turn_ref":"live-turn-1","tool_call_id":"call-1","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","location":{"page":1,"section":null}}]}
|
||
```
|
||
|
||
```json
|
||
{"type":"turn_interrupted","turn_ref":"live-turn-1","cancelled_tool_call_ids":["call-1"]}
|
||
```
|
||
|
||
```json
|
||
{"type":"error","turn_ref":"live-turn-2","error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
|
||
```
|
||
|
||
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.
|
||
|
||
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.
|
||
|
||
### 7.2 Internal model tool — `search_knowledge`
|
||
|
||
Model arguments, identical for the internal text-query harness, later text chat and Live. The LangChain tool uses this schema while trusted dispatcher context supplies authority:
|
||
|
||
```json
|
||
{"query":"What are the conditions and exceptions of the circular?","context":"The circular identified as source S1 in the preceding exchange."}
|
||
```
|
||
|
||
`query` required, 1–2000 characters; optional `context` proposed maximum 2000 characters, a conversation-resolved textual reference. Reject unknown fields. Context does not grant permission or turn previous model prose into evidence. No model-supplied organization/user IDs or paths; supported document filters remain deferred. Backend derives identity, current selected ready/active/undeleted scope, profile, bounded top_k/evidence size and execution IDs.
|
||
|
||
Illustrative successful result; text/location must be populated from actual retained chunks, never from these placeholders:
|
||
|
||
```json
|
||
{
|
||
"status":"ok",
|
||
"knowledge_revision":2,
|
||
"sources":[{
|
||
"source_ref":"S1",
|
||
"document_id":"10000000-0000-4000-8000-000000000001",
|
||
"chunk_id":"30000000-0000-4000-8000-000000000001",
|
||
"title":"Illustrative administrative circular",
|
||
"text":"<verified decision together with conditions and exclusions>",
|
||
"location":{"page":1,"section":"<verified clause or heading>"}
|
||
}],
|
||
"warnings":[]
|
||
}
|
||
```
|
||
|
||
```json
|
||
{"status":"no_evidence","knowledge_revision":2,"sources":[],"warnings":["insufficient_support"]}
|
||
```
|
||
|
||
```json
|
||
{"status":"error","sources":[],"error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
|
||
```
|
||
|
||
`no_evidence` is completed retrieval with insufficient support, not a provider failure. Contradictory passages may be returned with `warnings:["conflicting_evidence"]`; ask clarification or disclose conflict instead of silently resolving policy. `error` also covers provider unavailable/profile mismatch/revoked context, with normalized codes and safe retryability. Document claims require current supporting passages; greeting/clarification may omit search.
|
||
|
||
Locators use existing `location.page/section`. DOCX and image use page null, with table/row/Q&A or visual-group location in section. Same search backend/profile serves all extracted text. Source refs are unique across a turn and validated against returned evidence.
|
||
|
||
Deduplicate by parent session/turn plus provider call ID and normalized argument hash. Same running call waits; same completed call replays only after fresh eligibility/epoch checks; changed payload conflicts. Cancelled/closed/stale-parent results are not sent back to generate a new answer. No tool request becomes a public REST upload/search endpoint. The MVP persists voice tool_calls independently of deferred text turns/messages/citations. Cancelled work is terminal failed with a cancellation reason and cannot be replayed to resume speech.
|
||
|
||
## 8. Health
|
||
|
||
H01: 200 `{"status":"ok"}` when the process is alive. H02: 200 `{"status":"ready","ingestion":"available"}` or degraded ingestion marker if worker heartbeat is stale; 503 `{"status":"not_ready"}` for required DB/schema/storage failure. Health responses never disclose connection strings or provider keys. Provider outages surface in relevant business operations, not liveness.
|
||
|
||
## 9. Error envelope and mapping
|
||
|
||
```json
|
||
{"error":{"code":"REVISION_CONFLICT","message":"Selection changed; reload and try again.","request_id":"req-example","retryable":false,"details":{"current_revision":3}}}
|
||
```
|
||
|
||
| HTTP | Codes / use | Client action |
|
||
| --- | --- | --- |
|
||
| 401 | AUTH_REQUIRED, INVALID_CREDENTIALS | Login; do not retry provider work |
|
||
| 403 | FORBIDDEN, CSRF_INVALID | Show denial or refresh session token |
|
||
| 404 | NOT_FOUND | Stop; do not expose ownership details |
|
||
| 409 | REVISION_CONFLICT | Read latest selection/configuration |
|
||
| 409 | IDEMPOTENCY_CONFLICT | Correct client request/key handling |
|
||
| 409 | CONVERSATION_BUSY, CONVERSATION_STALE, MODE_MISMATCH | Poll current turn, start fresh conversation, or correct mode |
|
||
| 409 | DOCUMENT_NOT_READY, DOCUMENT_NOT_RETRYABLE, LIVE_SESSION_UNUSABLE | Follow returned state |
|
||
| 409 | EXTRACTION_REVIEW_PENDING, REVIEW_STALE, REVIEW_ALREADY_DECIDED | Refresh exact review evidence or follow the recorded decision |
|
||
| 413/415/422 | FILE_TOO_LARGE, UNSUPPORTED_FILE_TYPE, VALIDATION_ERROR | Correct input |
|
||
| 429 | RATE_LIMITED | Honor Retry-After; reuse key when retrying same operation |
|
||
| 503 | DEPENDENCY_UNAVAILABLE | Show service failure; reconcile state before retry |
|
||
|
||
Inside persisted jobs/sessions/tool calls, normalized codes include PROVIDER_TIMEOUT, PROVIDER_UNAVAILABLE, SEARCH_FAILED, PROCESS_INTERRUPTED, CONVERSATION_STALE, TOOL_CANCELLED and EXTRACTION_REVIEW_REQUIRED. Review-required is a controlled human-action failure, not an automatic transient-provider retry. INVALID_CITATION and failed text-turn responses belong to the deferred text contract. An HTTP 200 failed-turn result still represents application failure. Technical retryability does not authorize automatic regeneration under a new key.
|
||
|
||
## 10. Frontend implementation order and exclusions
|
||
|
||
Prove real native audio/tools early. Build A01/A03, bounded upload/polling, D06/D07 review and D04 resume, selection, C01 voice creation, V01-V04/WSS and read-only F01 capabilities. Full T01/T02/messages and settings editing are deferred. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context.
|
||
|
||
Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses.
|