qualia_core_db/services/
poet_llm_authority.rs1use super::webizen_server::WebizenState;
4use crate::llm_agent::{native_request::NativeProductSession, LocalLlmAgent};
5use axum::{
6 http::{HeaderMap, StatusCode},
7 response::{IntoResponse, Response},
8 Json,
9};
10use std::sync::{Arc, Mutex, OnceLock};
11
12static SESSION: OnceLock<Mutex<Option<Arc<NativeProductSession>>>> = OnceLock::new();
13
14pub fn configure(session: Arc<NativeProductSession>) {
18 super::poet_llm_jobs::cancel_all();
19 *SESSION
20 .get_or_init(|| Mutex::new(None))
21 .lock()
22 .unwrap_or_else(|e| e.into_inner()) = Some(session);
23}
24
25pub fn disconnect() {
26 super::poet_llm_jobs::cancel_all();
27 if let Some(slot) = SESSION.get() {
28 *slot.lock().unwrap_or_else(|e| e.into_inner()) = None;
29 }
30}
31
32pub(super) fn authenticate(
35 state: &WebizenState,
36 headers: &HeaderMap,
37) -> Result<Arc<NativeProductSession>, Response> {
38 let token = headers.get("x-qualia-token").and_then(|v| v.to_str().ok());
39 if !state
40 .token
41 .as_deref()
42 .is_some_and(|expected| !expected.is_empty() && Some(expected) == token)
43 {
44 return Err((
45 StatusCode::UNAUTHORIZED,
46 Json(serde_json::json!({
47 "ok": false, "code": "inference_transport_authentication",
48 "diagnostic": "Authenticated native Webizen transport is required"
49 })),
50 )
51 .into_response());
52 }
53 let session = SESSION.get().and_then(|slot| slot.lock().ok().and_then(|s| s.clone()))
54 .ok_or_else(|| (StatusCode::SERVICE_UNAVAILABLE, Json(serde_json::json!({
55 "ok": false, "code": "inference_host_not_configured",
56 "diagnostic": "Native host must bind an authenticated actor, installed policy and model preparation budgets"
57 }))).into_response())?;
58 session.bind().map_err(|_| {
61 (
62 StatusCode::FORBIDDEN,
63 Json(serde_json::json!({
64 "ok": false, "code": "inference_session_expired",
65 "diagnostic": "Native inference session expired or was disconnected"
66 })),
67 )
68 .into_response()
69 })?;
70 Ok(session)
71}
72
73pub(super) fn bind(agent: &LocalLlmAgent, session: &NativeProductSession) -> Result<(), String> {
74 agent
75 .bind_native_governed_request(session.bind().map_err(|e| e.to_string())?)
76 .map_err(|e| e.to_string())
77}