forge
Explore
Log in

Don't you dare go Hollow

Publish the rag.chat payloads and a GET /ai/capabilities probe

Browse files at this commit

94cffa06a2c8f3d755979a3b068e84e2290223a0Ahmet Kaan GümüşParent: d0dce85
  • feat
    • publish the rag.chat payloads and a GET /ai/capabilities probe
Show full message
✨ feat: publish the rag.chat payloads and a GET /ai/capabilities probe

Add the rag.chat capability's wire contract (scoped question -> answer with
citations), the max-scope-pairs and rate-limit constants, and an authenticated
discovery route listing each capability's connected worker fleet. Document the
payloads and the rag.index reply's file<->doc_id echo in the README.
README.mdmodified+46 -0
@@ -4051,6 +4051,52 @@ is opaque to the transport; its shape belongs to the capability.
4051 rather than answer late. A handled failure is an `err` frame; a crash is just a4051 rather than answer late. A handled failure is an `err` frame; a crash is just a
4052 dropped stream.4052 dropped stream.
4053 4053
4054+### The `rag.chat` capability
4055+
4056+`rag.chat` answers a question **about a school's course-note corpus**, with
4057+citations. Same `Request`/`Response` frames as any capability; only the payload
4058+differs. The service retrieves the relevant passages first and then generates,
4059+so its deadline (90s) is longer than a plain chat turn's.
4060+
4061+The request payload:
4062+
4063+```json
4064+{ "message": "ikinci yasa nedir?", "asker": "01ASKER", "asker_role": "student",
4065+ "scope": [ { "sinif": "11", "ders": "Fizik" } ],
4066+ "history": [ { "role": "user", "content": "merhaba" } ] }
4067+```
4068+
4069+`asker` is the id of the person who asked, so the service can read *their* own
4070+data back through the api reads above (`on_behalf_of`) — a question about "my
4071+marks" is answered from their marks. `asker_role` is their school role, the
4072+same lowercase strings the chatbot request carries. `scope` is a list of
4073+`(sinif, ders)` **pairs**: the corpus is routed by the pair, so a grade and a
4074+subject list sent separately would cross-product into combinations the asker
4075+never named. At most `MAX_RAG_SCOPE_PAIRS` (200) pairs ride one request.
4076+`history` is the same oldest-first tail as `chat.reply`, optional.
4077+
4078+The reply payload:
4079+
4080+```json
4081+{ "text": "F = m·a [1]", "abstained": false, "reason": "",
4082+ "citations": [ { "n": 1, "doc_id": "01DOC", "pages": [3],
4083+ "span_ids": ["s-7"], "ders": "Fizik" } ] }
4084+```
4085+
4086+A refusal that is part of the answer stays here rather than becoming an `err`
4087+frame: `abstained: true` with a short `reason` (`guard_*`, `insufficient_data`,
4088+`model_abstained`, `scope_mismatch`, `role_required`, …) is a completed turn.
4089+Each citation's `n` is the marker `[N]` the answer text uses, so a client
4090+resolves `[N]` by finding the citation whose `n` is `N` and opening the
4091+document `citations[].doc_id` names. `doc_id` is the **corpus** document id —
4092+the backend maps it to the `course_note_file` that owns that PDF.
4093+
4094+For that mapping to exist, the `rag.index` **reply** should echo each indexed
4095+file's ids: the service answers `{"files": [{"id": "<course_note_file id>",
4096+"doc_id": "<corpus doc id>"}]}`, naming the corpus id it assigned to each file
4097+it indexed. The backend pairs the echoed `doc_id` back to the file it sent, so
4098+a later citation's `doc_id` resolves to a downloadable file.
4099+
4054 ### API reads (the other direction)4100 ### API reads (the other direction)
4055 4101
4056 A service usually needs school data to do its work — who asked, their notes,4102 A service usually needs school data to do its work — who asked, their notes,
src/ai/mod.rsmodified+5 -0
@@ -15,6 +15,7 @@
15 //! * [`protocol`] — frames on the wire15 //! * [`protocol`] — frames on the wire
16 //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability16 //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability
17 //! * [`rag`] — the `rag.index` payloads, and the course-note dispatch behind them17 //! * [`rag`] — the `rag.index` payloads, and the course-note dispatch behind them
18+//! * [`rag_chat`] — the `rag.chat` payloads: a scoped question and the citations behind its answer
18 //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`]19 //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`]
19 //! * [`registry`] — who is connected here, and who gets the next request20 //! * [`registry`] — who is connected here, and who gets the next request
20 //! * [`tls`] — the listener's certificate21 //! * [`tls`] — the listener's certificate
@@ -28,6 +29,7 @@ pub mod chat;
28 pub mod error;29 pub mod error;
29 pub mod protocol;30 pub mod protocol;
30 pub mod rag;31 pub mod rag;
32+pub mod rag_chat;
31 pub mod registry;33 pub mod registry;
32 pub mod server;34 pub mod server;
33 pub mod tls;35 pub mod tls;
@@ -35,6 +37,9 @@ pub mod tls;
35 pub use chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};37 pub use chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
36 pub use error::AiError;38 pub use error::AiError;
37 pub use rag::{RagFile, RagIndexPayload};39 pub use rag::{RagFile, RagIndexPayload};
40+pub use rag_chat::{
41+ RagChatReplyPayload, RagChatRequestPayload, RagCitation, RagScopePair, RagTurn,
42+};
38 pub use registry::{AiRegistry, WorkerSnapshot};43 pub use registry::{AiRegistry, WorkerSnapshot};
39 pub use server::{AiBridge, BridgeConfig};44 pub use server::{AiBridge, BridgeConfig};
40 45
src/ai/rag_chat.rsadded+203 -0
@@ -0,0 +1,203 @@
1+//! Payload contract for the `rag.chat` capability.
2+//!
3+//! Same transport as every other capability: this is JSON riding inside a
4+//! [`Request::payload`](crate::ai::protocol::Request::payload) and coming back
5+//! inside [`Response::Ok`](crate::ai::protocol::Response::Ok)`::payload`. One
6+//! request, one answer — retrieval-then-answer is unary here even though it is
7+//! two steps inside the service.
8+//!
9+//! The service answers *about* a school's course-note corpus, so the request
10+//! carries both who is asking (so the service can read that person's own data
11+//! back through the bridge's api reads, as `on_behalf_of`) and the
12+//! `(sınıf, ders)` scope the corpus is routed by. The reply returns the answer
13+//! text plus the citations behind it, so the backend can resolve each cited
14+//! passage to the course-note file it came from.
15+
16+use serde::{Deserialize, Serialize};
17+
18+use crate::ai::chat::ChatRole;
19+
20+/// One `(sınıf, ders)` pair the question is scoped to.
21+///
22+/// The corpus is routed by the **pair**: a grade and a subject list sent
23+/// separately would cross-product into combinations the asker never named, so
24+/// each pair is one scope the service may retrieve from. `sinif` is optional —
25+/// a question about a subject across every grade names `ders` alone — and
26+/// `ders` is required, since a subject-less scope retrieves nothing.
27+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28+pub struct RagScopePair {
29+ /// The class/grade the subject is taught in (`"9"`, `"10"`), or omitted to
30+ /// scope the subject across grades.
31+ #[serde(default)]
32+ pub sinif: Option<String>,
33+ /// The subject/course name the pair is scoped to (Matematik, Fizik). The
34+ /// one field a pair cannot go without.
35+ pub ders: String,
36+}
37+
38+/// One previous message in the RAG conversation.
39+///
40+/// The same `{role, content}` shape the chatbot's history uses — a model's
41+/// `messages` array takes it with no remapping — so the two histories are
42+/// interchangeable.
43+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44+pub struct RagTurn {
45+ pub role: ChatRole,
46+ pub content: String,
47+}
48+
49+/// What the backend asks a RAG service to answer.
50+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51+pub struct RagChatRequestPayload {
52+ /// The user's new question. `history` does *not* contain it.
53+ pub message: String,
54+ /// The id of the user who asked. The service reads that person's own data
55+ /// back through the bridge's api reads (`on_behalf_of`), so a question
56+ /// about "my marks" is answered from *their* marks and never from another
57+ /// student's. Read live from the authenticated session, never taken from a
58+ /// request body.
59+ pub asker: String,
60+ /// The asker's **school role** — `"parent"`, `"student"`, `"teacher"`,
61+ /// `"manager"` or `"admin"`, the same lowercase strings the rest of the
62+ /// API uses. Read live from the session on every request, like the chatbot
63+ /// request's copy, so a service may answer on it: a student must not be
64+ /// handed an answer scoped for a manager.
65+ pub asker_role: String,
66+ /// The `(sınıf, ders)` pairs the question is scoped to — one entry per pair,
67+ /// because the RAG routes corpora by the pair. At most
68+ /// [`MAX_RAG_SCOPE_PAIRS`](crate::constant::MAX_RAG_SCOPE_PAIRS); a request
69+ /// carrying more is refused rather than narrowed.
70+ pub scope: Vec<RagScopePair>,
71+ /// The last N turns of the conversation, **oldest first** — index 0 the
72+ /// furthest back, the final element the turn immediately before `message`.
73+ /// Absent or `[]` means a fresh conversation.
74+ #[serde(default)]
75+ pub history: Vec<RagTurn>,
76+}
77+
78+/// One passage the answer drew on, inside the reply's `citations`.
79+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80+pub struct RagCitation {
81+ /// The marker the answer text uses to point at this passage: `[N]` in
82+ /// `text` resolves to the citation whose `n` is `N`.
83+ pub n: u32,
84+ /// The corpus document id the passage came from. The backend maps it to
85+ /// the course-note file that owns that PDF (the `rag.index` reply echoes
86+ /// this id back per file), so a citation resolves to something a reader can
87+ /// open.
88+ pub doc_id: String,
89+ /// The page numbers within the document the passage spans, when the source
90+ /// is paginated.
91+ #[serde(default)]
92+ pub pages: Vec<i64>,
93+ /// Opaque retrieval span ids within the document, for a client that wants
94+ /// to highlight the exact passage rather than the whole page.
95+ #[serde(default)]
96+ pub span_ids: Vec<String>,
97+ /// The subject the passage belongs to, when the corpus records one.
98+ #[serde(default)]
99+ pub ders: Option<String>,
100+}
101+
102+/// The service's answer, inside `Response::Ok { payload }`.
103+///
104+/// Handled failures do *not* come back here — they use the existing
105+/// [`Response::Err`](crate::ai::protocol::Response::Err) `{ code, message }`,
106+/// so there is exactly one failure shape on the bridge for every capability.
107+/// A refusal that is part of the answer (the service chose not to answer, or
108+/// could not) rides here instead, because it is still an answer: the turn
109+/// completes, no error surfaces.
110+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111+pub struct RagChatReplyPayload {
112+ /// The complete answer text, with `[N]` markers resolving to `citations`.
113+ pub text: String,
114+ /// Whether the service declined to answer rather than answering. A true
115+ /// value is a complete, successful turn — not a failure — and `reason`
116+ /// says why.
117+ #[serde(default)]
118+ pub abstained: bool,
119+ /// Why the service abstained, as a short machine code (`""` when it did
120+ /// not): `guard_*`, `insufficient_data`, `model_abstained`,
121+ /// `scope_mismatch`, `role_required`, or a service-specific code. Empty on
122+ /// an ordinary answer.
123+ #[serde(default)]
124+ pub reason: String,
125+ /// The passages the answer drew on, oldest first.
126+ #[serde(default)]
127+ pub citations: Vec<RagCitation>,
128+}
129+
130+#[cfg(test)]
131+mod tests {
132+ use super::*;
133+ use serde_json::json;
134+
135+ #[test]
136+ fn rag_chat_payload_keys_are_the_documented_wire_names() {
137+ // Services in other languages match on these literals — a rename here
138+ // silently breaks every one of them, so pin the encoding, key names
139+ // included (the exact wire key sets are the contract).
140+ let request = serde_json::to_value(RagChatRequestPayload {
141+ message: "ikinci yasa nedir?".into(),
142+ asker: "01ASKER".into(),
143+ asker_role: "student".into(),
144+ scope: vec![RagScopePair {
145+ sinif: Some("11".into()),
146+ ders: "Fizik".into(),
147+ }],
148+ history: vec![RagTurn {
149+ role: ChatRole::User,
150+ content: "merhaba".into(),
151+ }],
152+ })
153+ .unwrap();
154+ assert_eq!(
155+ request,
156+ json!({
157+ "message": "ikinci yasa nedir?",
158+ "asker": "01ASKER",
159+ "asker_role": "student",
160+ "scope": [{ "sinif": "11", "ders": "Fizik" }],
161+ "history": [{ "role": "user", "content": "merhaba" }],
162+ })
163+ );
164+
165+ let reply = serde_json::to_value(RagChatReplyPayload {
166+ text: "F = m·a [1]".into(),
167+ abstained: false,
168+ reason: String::new(),
169+ citations: vec![RagCitation {
170+ n: 1,
171+ doc_id: "01DOC".into(),
172+ pages: vec![3],
173+ span_ids: vec!["s-7".into()],
174+ ders: Some("Fizik".into()),
175+ }],
176+ })
177+ .unwrap();
178+ assert_eq!(
179+ reply,
180+ json!({
181+ "text": "F = m·a [1]",
182+ "abstained": false,
183+ "reason": "",
184+ "citations": [{
185+ "n": 1,
186+ "doc_id": "01DOC",
187+ "pages": [3],
188+ "span_ids": ["s-7"],
189+ "ders": "Fizik",
190+ }],
191+ })
192+ );
193+
194+ // The three optional fields default to empty on a minimal service
195+ // reply, and a scope pair may omit `sinif`.
196+ let bare: RagChatReplyPayload =
197+ serde_json::from_value(json!({ "text": "bilmiyorum", "abstained": true })).unwrap();
198+ assert_eq!(bare.reason, "");
199+ assert!(bare.citations.is_empty());
200+ let pair: RagScopePair = serde_json::from_value(json!({ "ders": "Matematik" })).unwrap();
201+ assert_eq!(pair.sinif, None);
202+ }
203+}
src/constant.rsmodified+35 -0
@@ -580,6 +580,41 @@ pub const AI_RAG_INDEX_CAPABILITY: &str = "rag.index";
580 /// is fire-and-forget, off the HTTP request path.580 /// is fire-and-forget, off the HTTP request path.
581 pub const AI_RAG_INDEX_TIMEOUT_SECS: u64 = 120;581 pub const AI_RAG_INDEX_TIMEOUT_SECS: u64 = 120;
582 582
583+/// The capability an AI service declares to answer a RAG question over a
584+/// school's course-note corpus. Separate from [`AI_CHAT_CAPABILITY`] on
585+/// purpose: retrieval-then-answer is its own service with its own corpus, and
586+/// a deployment may run one without the other. With no worker carrying it the
587+/// RAG endpoints report the service as unavailable.
588+pub const AI_RAG_CHAT_CAPABILITY: &str = "rag.chat";
589+
590+/// Deadline on one `rag.chat` round trip. Much longer than a plain chat turn
591+/// ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`]): the service first retrieves the
592+/// relevant passages and only then generates an answer, so a question that
593+/// touches several course notes is retrieval plus inference, not inference
594+/// alone.
595+pub const AI_RAG_CHAT_TIMEOUT_SECS: u64 = 90;
596+
597+/// How long a `rag.chat` turn may sit `pending` before a reader projects it as
598+/// failed. The RAG nest mirrors the chatbot's asynchronous send
599+/// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that
600+/// started it, and a restart mid-inference strands the row rather than letting
601+/// anyone answer it, so the same staleness window applies.
602+pub const RAG_PENDING_STALE_SECS: i64 = CHATBOT_PENDING_STALE_SECS;
603+
604+/// The most `(sınıf, ders)` scope pairs one `rag.chat` request may carry. The
605+/// corpus is routed by the **pair** — a grade and a subject list sent
606+/// separately would cross-product into combinations the asker never named — so
607+/// this is the number of pairs handed to the service in one call, bounding
608+/// both the frame size and the service's routing work. A request carrying more
609+/// is refused rather than silently narrowed: dropping pairs would answer a
610+/// question the asker did not ask, scoped to corpora they did not name.
611+pub const MAX_RAG_SCOPE_PAIRS: usize = 200;
612+
613+/// Default per-minute message limit for the RAG nest, when the school sets
614+/// none — a lower ceiling than the chatbot's, since every message here spends
615+/// a retrieval over the whole course-note corpus before it generates anything.
616+pub const DEFAULT_RAG_RATE_LIMIT: u32 = 6;
617+
583 /// Hard ceiling on one chat message's characters — the newtype bound, above618 /// Hard ceiling on one chat message's characters — the newtype bound, above
584 /// which no school setting can reach. Sized for a pasted question with its619 /// which no school setting can reach. Sized for a pasted question with its
585 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.620 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.
src/lib.rsmodified+1 -1
@@ -52,7 +52,7 @@ use crate::web::module_gate::gate;
52 modifiers(&SecurityAddon),52 modifiers(&SecurityAddon),
53 tags(53 tags(
54 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),54 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),
55- (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),55+ (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). `GET /ai/capabilities` (authenticated) lists what connected services are serving right now — one entry per capability with its worker count and in-flight requests — and answers `200 {enabled: false, capabilities: []}` when the bridge is off: a discovery read showing *that* there is no AI fleet, not a dependency probe. See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
56 (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),56 (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),
57 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),57 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),
58 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),58 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
src/web/ai.rsmodified+79 -1
@@ -26,9 +26,11 @@ use crate::ai::tls;
26 use crate::constant::AI_PROTOCOL;26 use crate::constant::AI_PROTOCOL;
27 use crate::error::{AppError, ErrorResponse};27 use crate::error::{AppError, ErrorResponse};
28 use crate::state::AppState;28 use crate::state::AppState;
29+use crate::web::CurrentUser;
30+use std::collections::BTreeMap;
29 31
30 pub fn routes() -> OpenApiRouter<AppState> {32 pub fn routes() -> OpenApiRouter<AppState> {
31- OpenApiRouter::new().routes(routes!(bridge_certificate))33+ OpenApiRouter::new().routes(routes!(bridge_certificate, capabilities))
32 }34 }
33 35
34 /// Everything a service needs to reach the bridge, except the shared token36 /// Everything a service needs to reach the bridge, except the shared token
@@ -82,6 +84,82 @@ async fn bridge_certificate(
82 }))84 }))
83 }85 }
84 86
87+/// What the bridge can currently do, grouped by capability.
88+#[derive(Serialize, ToSchema)]
89+pub struct CapabilitiesResponse {
90+ /// Whether a bridge is listening at all (`AI_QUIC_ADDR` set). `false` here
91+ /// is a discovery answer, not an error: the deployment simply runs no AI.
92+ enabled: bool,
93+ /// The wire protocol the bridge speaks, currently `hab/2`.
94+ #[schema(example = "hab/2")]
95+ protocol: String,
96+ /// One entry per capability any connected worker serves, sorted by name.
97+ capabilities: Vec<CapabilityWorkers>,
98+}
99+
100+/// One capability's live fleet: how many workers serve it, and the work in
101+/// flight across them.
102+#[derive(Serialize, ToSchema)]
103+pub struct CapabilityWorkers {
104+ /// The capability string a service declared, e.g. `chat.reply` or
105+ /// `rag.chat`.
106+ #[schema(example = "chat.reply")]
107+ capability: String,
108+ /// How many connected workers have declared this capability.
109+ workers: usize,
110+ /// Requests currently being answered across those workers.
111+ inflight: u64,
112+}
113+
114+/// The capabilities connected AI services are serving right now, per
115+/// capability, with the work in flight — a discovery read for an operator or a
116+/// service deciding what it may ask this bridge to do.
117+///
118+/// **`200`, even with the bridge off.** This lists what is available rather
119+/// than probing a dependency, so a disabled bridge answers `enabled: false`
120+/// and an empty list, not a `503` — a caller learns *that* there is no AI
121+/// fleet rather than that the request itself failed.
122+#[utoipa::path(
123+ get,
124+ path = "/capabilities",
125+ tag = "ai",
126+ responses(
127+ (status = 200, description = "Every capability a connected worker serves, grouped and sorted", body = CapabilitiesResponse),
128+ (status = 401, description = "No authenticated session", body = ErrorResponse),
129+ ),
130+)]
131+async fn capabilities(
132+ State(state): State<AppState>,
133+ _user: CurrentUser,
134+) -> Json<CapabilitiesResponse> {
135+ let (enabled, workers) = match &state.ai {
136+ Some(bridge) => (true, bridge.workers()),
137+ None => (false, Vec::new()),
138+ };
139+ // A worker serving N capabilities counts once toward each of them, so the
140+ // group totals are per-capability fleets, not a partition of the workers.
141+ let mut by_capability: BTreeMap<String, (usize, u64)> = BTreeMap::new();
142+ for worker in workers {
143+ for capability in &worker.capabilities {
144+ let entry = by_capability.entry(capability.clone()).or_insert((0, 0));
145+ entry.0 += 1;
146+ entry.1 += worker.inflight as u64;
147+ }
148+ }
149+ Json(CapabilitiesResponse {
150+ enabled,
151+ protocol: AI_PROTOCOL.to_string(),
152+ capabilities: by_capability
153+ .into_iter()
154+ .map(|(capability, (workers, inflight))| CapabilityWorkers {
155+ capability,
156+ workers,
157+ inflight,
158+ })
159+ .collect(),
160+ })
161+}
162+
85 /// Wrap DER bytes as a PEM certificate: base64 in 64-character lines between163 /// Wrap DER bytes as a PEM certificate: base64 in 64-character lines between
86 /// the standard armour, which is what every TLS library's loader expects.164 /// the standard armour, which is what every TLS library's loader expects.
87 fn to_pem(der: &[u8]) -> String {165 fn to_pem(der: &[u8]) -> String {
tests/ai_protocol.rsmodified+83 -0
@@ -1016,6 +1016,89 @@ async fn a_chat_request_names_the_askers_school_role() {
1016 .await;1016 .await;
1017 }1017 }
1018 1018
1019+// ------------------------------------------------- rag.chat payload keys --
1020+//
1021+// `rag.chat` is the other capability whose payload is a published contract.
1022+// In this wave nothing in the HTTP surface builds one yet, so its payload is
1023+// pinned by putting the crate's own payload through the real bridge and reading
1024+// the bytes exactly as a foreign service would: raw frames, and the documented
1025+// key sets — never parsed back through the crate's payload structs.
1026+
1027+#[tokio::test]
1028+async fn rag_chat_payloads_carry_the_documented_wire_keys() {
1029+ use hezarfen_backend::ai::{
1030+ RagChatReplyPayload, RagChatRequestPayload, RagCitation, RagScopePair,
1031+ };
1032+
1033+ let bridge = bridge().await;
1034+ let service = raw::handshake(&bridge, &raw::hello("rag", "rag.chat")).await;
1035+ await_workers(&bridge, 1).await;
1036+
1037+ let request = serde_json::to_value(RagChatRequestPayload {
1038+ message: "ikinci yasa nedir?".into(),
1039+ asker: "01ASKER".into(),
1040+ asker_role: "student".into(),
1041+ scope: vec![RagScopePair {
1042+ sinif: Some("11".into()),
1043+ ders: "Fizik".into(),
1044+ }],
1045+ history: Vec::new(),
1046+ })
1047+ .unwrap();
1048+ let call = dispatch(&bridge, "rag.chat", request);
1049+
1050+ let (frame, bytes, send, _recv) = raw::take_request(&service.conn).await;
1051+ assert_eq!(frame["capability"], "rag.chat");
1052+ assert_eq!(
1053+ raw::keys(&frame["payload"]),
1054+ ["asker", "asker_role", "history", "message", "scope"],
1055+ "the documented rag.chat request payload keys"
1056+ );
1057+ assert_eq!(
1058+ raw::keys(&frame["payload"]["scope"][0]),
1059+ ["ders", "sinif"],
1060+ "a scope pair is routed by (sinif, ders)"
1061+ );
1062+ // Byte-level: the `(sinif, ders)` pair set, not a re-wrapped shape.
1063+ let text = String::from_utf8(bytes).expect("the frame body is UTF-8 JSON");
1064+ assert!(
1065+ text.contains(r#""scope":[{"sinif":"11","ders":"Fizik"}]"#),
1066+ "{text}"
1067+ );
1068+
1069+ let reply = serde_json::to_value(RagChatReplyPayload {
1070+ text: "F = m·a [1]".into(),
1071+ abstained: false,
1072+ reason: String::new(),
1073+ citations: vec![RagCitation {
1074+ n: 1,
1075+ doc_id: "01DOC".into(),
1076+ pages: vec![3],
1077+ span_ids: vec!["s-7".into()],
1078+ ders: Some("Fizik".into()),
1079+ }],
1080+ })
1081+ .unwrap();
1082+ let id = frame["id"].as_str().expect("trace id").to_string();
1083+ raw::answer(
1084+ send,
1085+ format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{reply}}}"#).as_bytes(),
1086+ )
1087+ .await;
1088+
1089+ let answer = call.await.unwrap().unwrap();
1090+ assert_eq!(
1091+ raw::keys(&answer),
1092+ ["abstained", "citations", "reason", "text"],
1093+ "the documented rag.chat reply payload keys"
1094+ );
1095+ assert_eq!(
1096+ raw::keys(&answer["citations"][0]),
1097+ ["ders", "doc_id", "n", "pages", "span_ids"],
1098+ "the documented citation keys"
1099+ );
1100+}
1101+
1019 // ------------------------------------------------------------- api reads --1102 // ------------------------------------------------------------- api reads --
1020 //1103 //
1021 // The other direction: a service opens its own stream and asks the school API1104 // The other direction: a service opens its own stream and asks the school API
tests/e2e.rsmodified+30 -0
@@ -2048,6 +2048,36 @@ async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() {
2048 assert_eq!(&polled, streamed, "the two reads must not disagree");2048 assert_eq!(&polled, streamed, "the two reads must not disagree");
2049 }2049 }
2050 2050
2051+#[tokio::test]
2052+async fn capabilities_reports_a_registered_chat_service() {
2053+ // A discovery read: once the fake `chat.reply` service has dialled in,
2054+ // `GET /ai/capabilities` lists that capability with its worker fleet.
2055+ let service = chat_service("F = ma").await;
2056+ let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await;
2057+ let ali = client();
2058+ register(&ali, &base, "ali").await;
2059+ login(&ali, &base, "ali").await;
2060+
2061+ let caps: Value = ali
2062+ .get(format!("{base}/ai/capabilities"))
2063+ .send()
2064+ .await
2065+ .unwrap()
2066+ .json()
2067+ .await
2068+ .unwrap();
2069+ assert_eq!(caps["enabled"], json!(true));
2070+ assert_eq!(caps["protocol"], json!("hab/2"));
2071+ let row = caps["capabilities"]
2072+ .as_array()
2073+ .expect("a capabilities array")
2074+ .iter()
2075+ .find(|c| c["capability"] == json!("chat.reply"))
2076+ .expect("the fake service serves chat.reply");
2077+ assert_eq!(row["workers"], json!(1));
2078+ assert!(row["inflight"].is_u64(), "{row}");
2079+}
2080+
2051 #[tokio::test]2081 #[tokio::test]
2052 async fn chat_stream_delivers_deltas_then_done_over_http() {2082 async fn chat_stream_delivers_deltas_then_done_over_http() {
2053 let answer = long_answer();2083 let answer = long_answer();