aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / src / gateway.rs
| 1 | use axum::{ |
| 2 | body::Body, |
| 3 | extract::{ |
| 4 | ws::{Message, WebSocket, WebSocketUpgrade}, |
| 5 | State, |
| 6 | }, |
| 7 | http::{header, StatusCode}, |
| 8 | response::{ |
| 9 | sse::{Event, KeepAlive, Sse}, |
| 10 | IntoResponse, Response, |
| 11 | }, |
| 12 | routing::{get, post}, |
| 13 | Json, Router, |
| 14 | }; |
| 15 | use futures_util::StreamExt; |
| 16 | use serde::{Deserialize, Serialize}; |
| 17 | use serde_json::json; |
| 18 | use std::convert::Infallible; |
| 19 | use std::net::SocketAddr; |
| 20 | use std::sync::Arc; |
| 21 | use std::time::Instant; |
| 22 | use tokio_stream::wrappers::BroadcastStream; |
| 23 | use tower_http::cors::{Any, CorsLayer}; |
| 24 | use tracing::info; |
| 25 | |
| 26 | use crate::agent::{AgentEngine, AgentStep}; |
| 27 | use crate::heartbeat::HeartbeatEngine; |
| 28 | use crate::inference::InferenceEngine; |
| 29 | use crate::persistence::Database; |
| 30 | use crate::skills::{SkillExecutionRequest, SkillRegistry}; |
| 31 | use crate::vector_math::VectorMath; |
| 32 | |
| 33 | #[derive(Clone)] |
| 34 | pub struct GatewayState { |
| 35 | pub start_time: Instant, |
| 36 | pub db: Arc<Database>, |
| 37 | pub inference: Arc<dyn InferenceEngine>, |
| 38 | pub heartbeat: Arc<HeartbeatEngine>, |
| 39 | pub skills: Arc<SkillRegistry>, |
| 40 | pub agent: Arc<AgentEngine>, |
| 41 | /// Operator token checked on every non-public route. |
| 42 | pub operator: crate::auth::OperatorAuth, |
| 43 | } |
| 44 | |
| 45 | #[derive(Serialize)] |
| 46 | pub struct HealthResponse { |
| 47 | pub status: &'static str, |
| 48 | pub engine: &'static str, |
| 49 | pub uptime_seconds: u64, |
| 50 | pub local_model: String, |
| 51 | pub heartbeat_interval_seconds: u64, |
| 52 | pub total_heartbeat_ticks: u64, |
| 53 | pub database_mode: &'static str, |
| 54 | pub zero_disk_secrets: bool, |
| 55 | } |
| 56 | |
| 57 | pub async fn health_handler(State(state): State<GatewayState>) -> impl IntoResponse { |
| 58 | let uptime = state.start_time.elapsed().as_secs(); |
| 59 | let ticks = state.heartbeat.tick_count(); |
| 60 | let model = state.inference.model_id(); |
| 61 | |
| 62 | Json(HealthResponse { |
| 63 | status: "healthy", |
| 64 | engine: "aegis-runtime/0.2.0", |
| 65 | uptime_seconds: uptime, |
| 66 | local_model: model, |
| 67 | heartbeat_interval_seconds: state.heartbeat.interval_secs(), |
| 68 | total_heartbeat_ticks: ticks, |
| 69 | database_mode: "sqlite-wal", |
| 70 | zero_disk_secrets: true, |
| 71 | }) |
| 72 | } |
| 73 | |
| 74 | #[derive(Deserialize)] |
| 75 | pub struct ChatRequest { |
| 76 | pub prompt: String, |
| 77 | pub system: Option<String>, |
| 78 | pub temperature: Option<f32>, |
| 79 | } |
| 80 | |
| 81 | #[derive(Serialize)] |
| 82 | pub struct ChatResponse { |
| 83 | pub role: &'static str, |
| 84 | pub content: String, |
| 85 | pub model: String, |
| 86 | pub duration_ms: u128, |
| 87 | } |
| 88 | |
| 89 | pub async fn chat_handler( |
| 90 | State(state): State<GatewayState>, |
| 91 | Json(payload): Json<ChatRequest>, |
| 92 | ) -> Result<impl IntoResponse, (StatusCode, String)> { |
| 93 | let start = Instant::now(); |
| 94 | let response = state |
| 95 | .inference |
| 96 | .generate( |
| 97 | &payload.prompt, |
| 98 | payload.system.as_deref(), |
| 99 | payload.temperature, |
| 100 | ) |
| 101 | .await |
| 102 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; |
| 103 | |
| 104 | let duration = start.elapsed().as_millis(); |
| 105 | let model = state.inference.model_id(); |
| 106 | |
| 107 | let _ = state |
| 108 | .db |
| 109 | .record_turn("user", &payload.prompt, &response, duration as u64); |
| 110 | |
| 111 | Ok(Json(ChatResponse { |
| 112 | role: "assistant", |
| 113 | content: response, |
| 114 | model, |
| 115 | duration_ms: duration, |
| 116 | })) |
| 117 | } |
| 118 | |
| 119 | #[derive(Deserialize)] |
| 120 | pub struct AgentRunRequest { |
| 121 | pub prompt: String, |
| 122 | pub system: Option<String>, |
| 123 | pub max_turns: Option<usize>, |
| 124 | } |
| 125 | |
| 126 | #[derive(Serialize)] |
| 127 | pub struct AgentRunResponse { |
| 128 | /// `completed` only for terminal output, otherwise `incomplete`. |
| 129 | pub status: &'static str, |
| 130 | pub prompt: String, |
| 131 | pub final_response: String, |
| 132 | pub steps: Vec<AgentStep>, |
| 133 | pub turns_taken: usize, |
| 134 | pub duration_ms: u128, |
| 135 | pub completed: bool, |
| 136 | } |
| 137 | |
| 138 | pub async fn agent_run_handler( |
| 139 | State(state): State<GatewayState>, |
| 140 | Json(payload): Json<AgentRunRequest>, |
| 141 | ) -> Result<impl IntoResponse, (StatusCode, String)> { |
| 142 | let max_turns = payload.max_turns.unwrap_or(8); |
| 143 | let result = state |
| 144 | .agent |
| 145 | .execute_task(&payload.prompt, payload.system.as_deref(), max_turns) |
| 146 | .await |
| 147 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; |
| 148 | |
| 149 | Ok(Json(AgentRunResponse { |
| 150 | status: if result.completed { |
| 151 | "completed" |
| 152 | } else { |
| 153 | "incomplete" |
| 154 | }, |
| 155 | prompt: payload.prompt, |
| 156 | final_response: result.final_response, |
| 157 | steps: result.steps, |
| 158 | turns_taken: result.turns_taken, |
| 159 | duration_ms: result.duration_ms, |
| 160 | completed: result.completed, |
| 161 | })) |
| 162 | } |
| 163 | |
| 164 | // OpenAI-compatible Chat Completions API with streaming and multi-turn support |
| 165 | #[derive(Deserialize, Serialize, Clone)] |
| 166 | pub struct OpenAiMessage { |
| 167 | pub role: String, |
| 168 | pub content: String, |
| 169 | } |
| 170 | |
| 171 | #[derive(Deserialize)] |
| 172 | pub struct OpenAiChatRequest { |
| 173 | pub model: Option<String>, |
| 174 | pub messages: Vec<OpenAiMessage>, |
| 175 | pub temperature: Option<f32>, |
| 176 | pub max_tokens: Option<u32>, |
| 177 | pub stream: Option<bool>, |
| 178 | } |
| 179 | |
| 180 | pub async fn openai_completions_handler( |
| 181 | State(state): State<GatewayState>, |
| 182 | Json(payload): Json<OpenAiChatRequest>, |
| 183 | ) -> Response { |
| 184 | if payload.messages.is_empty() { |
| 185 | let err_body = json!({ |
| 186 | "error": { |
| 187 | "message": "Missing required parameter: 'messages' must contain at least one message.", |
| 188 | "type": "invalid_request_error", |
| 189 | "param": "messages", |
| 190 | "code": "missing_required_parameter" |
| 191 | } |
| 192 | }); |
| 193 | return (StatusCode::BAD_REQUEST, Json(err_body)).into_response(); |
| 194 | } |
| 195 | |
| 196 | if let Some(ref req_model) = payload.model { |
| 197 | let supported_model = state.inference.model_id(); |
| 198 | if req_model != &supported_model |
| 199 | && req_model != "atlas-lightning-omni" |
| 200 | && req_model != "aegis-default" |
| 201 | && req_model != "default" |
| 202 | { |
| 203 | let err_body = json!({ |
| 204 | "error": { |
| 205 | "message": format!("The model '{}' does not exist or is not supported.", req_model), |
| 206 | "type": "invalid_request_error", |
| 207 | "param": "model", |
| 208 | "code": "model_not_found" |
| 209 | } |
| 210 | }); |
| 211 | return (StatusCode::NOT_FOUND, Json(err_body)).into_response(); |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | let messages_json: Vec<serde_json::Value> = payload |
| 216 | .messages |
| 217 | .iter() |
| 218 | .map(|m| json!({"role": m.role, "content": m.content})) |
| 219 | .collect(); |
| 220 | |
| 221 | let last_user_prompt = payload |
| 222 | .messages |
| 223 | .iter() |
| 224 | .rev() |
| 225 | .find(|m| m.role == "user") |
| 226 | .map(|m| m.content.as_str()) |
| 227 | .unwrap_or("hello") |
| 228 | .to_string(); |
| 229 | |
| 230 | if payload.stream == Some(true) { |
| 231 | match state |
| 232 | .inference |
| 233 | .stream_chat(&messages_json, payload.temperature, payload.max_tokens) |
| 234 | .await |
| 235 | { |
| 236 | Ok(stream) => { |
| 237 | let body = Body::from_stream(stream); |
| 238 | Response::builder() |
| 239 | .header(header::CONTENT_TYPE, "text/event-stream") |
| 240 | .header(header::CACHE_CONTROL, "no-cache") |
| 241 | .header(header::CONNECTION, "keep-alive") |
| 242 | .body(body) |
| 243 | .unwrap() |
| 244 | } |
| 245 | Err(_e) => { |
| 246 | let fallback_chunk = json!({ |
| 247 | "id": format!("chatcmpl-{}", uuid::Uuid::new_v4()), |
| 248 | "object": "chat.completion.chunk", |
| 249 | "choices": [{ |
| 250 | "delta": {"content": format!("[Fallback]: {}", last_user_prompt)}, |
| 251 | "index": 0, |
| 252 | "finish_reason": "stop" |
| 253 | }] |
| 254 | }); |
| 255 | let sse_body = format!("data: {}\n\ndata: [DONE]\n\n", fallback_chunk); |
| 256 | Response::builder() |
| 257 | .header(header::CONTENT_TYPE, "text/event-stream") |
| 258 | .body(Body::from(sse_body)) |
| 259 | .unwrap() |
| 260 | } |
| 261 | } |
| 262 | } else { |
| 263 | let start = Instant::now(); |
| 264 | let model = state.inference.model_id(); |
| 265 | let result = state |
| 266 | .inference |
| 267 | .generate_chat(&messages_json, payload.temperature, payload.max_tokens) |
| 268 | .await; |
| 269 | let duration = start.elapsed().as_millis(); |
| 270 | |
| 271 | match result { |
| 272 | Ok(response) => { |
| 273 | let _ = state |
| 274 | .db |
| 275 | .record_turn("user", &last_user_prompt, &response, duration as u64); |
| 276 | |
| 277 | let p_tokens = last_user_prompt.split_whitespace().count(); |
| 278 | let c_tokens = response.split_whitespace().count(); |
| 279 | |
| 280 | let resp_body = json!({ |
| 281 | "id": format!("chatcmpl-{}", uuid::Uuid::new_v4()), |
| 282 | "object": "chat.completion", |
| 283 | "created": chrono::Utc::now().timestamp(), |
| 284 | "model": model, |
| 285 | "choices": [{ |
| 286 | "index": 0, |
| 287 | "message": { |
| 288 | "role": "assistant", |
| 289 | "content": response, |
| 290 | }, |
| 291 | "finish_reason": "stop" |
| 292 | }], |
| 293 | "usage": { |
| 294 | "prompt_tokens": p_tokens, |
| 295 | "completion_tokens": c_tokens, |
| 296 | "total_tokens": p_tokens + c_tokens, |
| 297 | } |
| 298 | }); |
| 299 | Json(resp_body).into_response() |
| 300 | } |
| 301 | Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(), |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | pub async fn openai_models_handler(State(state): State<GatewayState>) -> impl IntoResponse { |
| 307 | let model = state.inference.model_id(); |
| 308 | Json(json!({ |
| 309 | "object": "list", |
| 310 | "data": [{ |
| 311 | "id": model, |
| 312 | "object": "model", |
| 313 | "created": 1789783086, |
| 314 | "owned_by": "aegis-runtime", |
| 315 | }] |
| 316 | })) |
| 317 | } |
| 318 | |
| 319 | // SSE Events Endpoint |
| 320 | pub async fn sse_events_handler( |
| 321 | State(state): State<GatewayState>, |
| 322 | ) -> Sse<impl futures_util::Stream<Item = Result<Event, Infallible>>> { |
| 323 | let rx = state.heartbeat.subscribe(); |
| 324 | let stream = BroadcastStream::new(rx).filter_map(|item| async move { |
| 325 | match item { |
| 326 | Ok(receipt) => { |
| 327 | let data = serde_json::to_string(&receipt).unwrap_or_default(); |
| 328 | Some(Ok(Event::default().event("heartbeat").data(data))) |
| 329 | } |
| 330 | Err(_) => None, |
| 331 | } |
| 332 | }); |
| 333 | |
| 334 | Sse::new(stream).keep_alive(KeepAlive::default()) |
| 335 | } |
| 336 | |
| 337 | // Discord Hub Relay |
| 338 | #[derive(Deserialize)] |
| 339 | pub struct DiscordRelayRequest { |
| 340 | pub channel_id: String, |
| 341 | pub author: String, |
| 342 | pub content: String, |
| 343 | } |
| 344 | |
| 345 | pub async fn discord_relay_handler( |
| 346 | State(state): State<GatewayState>, |
| 347 | Json(payload): Json<DiscordRelayRequest>, |
| 348 | ) -> impl IntoResponse { |
| 349 | let prompt = format!( |
| 350 | "[Discord from {} in {}]: {}", |
| 351 | payload.author, payload.channel_id, payload.content |
| 352 | ); |
| 353 | let reply = state |
| 354 | .inference |
| 355 | .generate(&prompt, None, None) |
| 356 | .await |
| 357 | .unwrap_or_else(|e| format!("Error: {}", e)); |
| 358 | |
| 359 | let _ = state |
| 360 | .db |
| 361 | .record_turn(&payload.author, &payload.content, &reply, 10); |
| 362 | |
| 363 | Json(json!({ |
| 364 | "status": "relayed", |
| 365 | "reply": reply, |
| 366 | "timestamp": chrono::Utc::now().to_rfc3339(), |
| 367 | })) |
| 368 | } |
| 369 | |
| 370 | // Local Shell Executor |
| 371 | #[derive(Deserialize)] |
| 372 | pub struct ShellRequest { |
| 373 | pub command: String, |
| 374 | } |
| 375 | |
| 376 | #[derive(Serialize)] |
| 377 | pub struct ShellResponse { |
| 378 | pub stdout: String, |
| 379 | pub stderr: String, |
| 380 | pub exit_code: i32, |
| 381 | pub success: bool, |
| 382 | } |
| 383 | |
| 384 | pub async fn shell_handler( |
| 385 | State(state): State<GatewayState>, |
| 386 | Json(payload): Json<ShellRequest>, |
| 387 | ) -> Result<impl IntoResponse, (StatusCode, String)> { |
| 388 | match state |
| 389 | .skills |
| 390 | .workspace() |
| 391 | .dispatch_shell_gated(&payload.command, None, 15) |
| 392 | .await |
| 393 | { |
| 394 | Ok(stdout) => Ok(Json(ShellResponse { |
| 395 | stdout, |
| 396 | stderr: String::new(), |
| 397 | exit_code: 0, |
| 398 | success: true, |
| 399 | })), |
| 400 | Err(e) => Ok(Json(ShellResponse { |
| 401 | stdout: String::new(), |
| 402 | stderr: e.to_string(), |
| 403 | exit_code: 1, |
| 404 | success: false, |
| 405 | })), |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | // Task endpoints |
| 410 | #[derive(Deserialize)] |
| 411 | pub struct CreateTaskRequest { |
| 412 | pub task_type: String, |
| 413 | pub payload: String, |
| 414 | } |
| 415 | |
| 416 | pub async fn create_task_handler( |
| 417 | State(state): State<GatewayState>, |
| 418 | Json(req): Json<CreateTaskRequest>, |
| 419 | ) -> Result<impl IntoResponse, (StatusCode, String)> { |
| 420 | let id = format!("task-{}", uuid::Uuid::new_v4()); |
| 421 | state |
| 422 | .db |
| 423 | .create_task(&id, &req.task_type, &req.payload) |
| 424 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; |
| 425 | |
| 426 | Ok(Json(json!({ |
| 427 | "status": "created", |
| 428 | "id": id, |
| 429 | "task_type": req.task_type, |
| 430 | }))) |
| 431 | } |
| 432 | |
| 433 | pub async fn list_tasks_handler( |
| 434 | State(state): State<GatewayState>, |
| 435 | ) -> Result<impl IntoResponse, (StatusCode, String)> { |
| 436 | let tasks = state |
| 437 | .db |
| 438 | .list_pending_tasks() |
| 439 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; |
| 440 | |
| 441 | Ok(Json(tasks)) |
| 442 | } |
| 443 | |
| 444 | pub async fn trigger_heartbeat_handler(State(state): State<GatewayState>) -> impl IntoResponse { |
| 445 | let receipt = state.heartbeat.pulse_once().await; |
| 446 | Json(receipt) |
| 447 | } |
| 448 | |
| 449 | // Skills endpoints |
| 450 | pub async fn list_skills_handler(State(state): State<GatewayState>) -> impl IntoResponse { |
| 451 | let list = state.skills.advertised_skills(); |
| 452 | Json(list) |
| 453 | } |
| 454 | |
| 455 | pub async fn execute_skill_handler( |
| 456 | State(state): State<GatewayState>, |
| 457 | Json(req): Json<SkillExecutionRequest>, |
| 458 | ) -> impl IntoResponse { |
| 459 | // Membrane + probe gate (always on), then the handler. |
| 460 | let res = state.skills.execute_gated(&req).await; |
| 461 | Json(res) |
| 462 | } |
| 463 | |
| 464 | pub async fn ws_handler( |
| 465 | ws: WebSocketUpgrade, |
| 466 | State(state): State<GatewayState>, |
| 467 | ) -> impl IntoResponse { |
| 468 | ws.on_upgrade(move |socket| handle_socket(socket, state)) |
| 469 | } |
| 470 | |
| 471 | async fn handle_socket(mut socket: WebSocket, state: GatewayState) { |
| 472 | let welcome = json!({ |
| 473 | "type": "welcome", |
| 474 | "gateway": "aegis-runtime", |
| 475 | "engine": "AEGIS WebSocket Gateway", |
| 476 | "status": "connected", |
| 477 | "timestamp": chrono::Utc::now().to_rfc3339(), |
| 478 | }); |
| 479 | |
| 480 | if socket |
| 481 | .send(Message::Text(welcome.to_string())) |
| 482 | .await |
| 483 | .is_err() |
| 484 | { |
| 485 | return; |
| 486 | } |
| 487 | |
| 488 | let mut pulse_rx = state.heartbeat.subscribe(); |
| 489 | |
| 490 | loop { |
| 491 | tokio::select! { |
| 492 | pulse = pulse_rx.recv() => { |
| 493 | if let Ok(receipt) = pulse { |
| 494 | let out = json!({ |
| 495 | "type": "heartbeat_pulse", |
| 496 | "receipt": receipt, |
| 497 | }); |
| 498 | if socket.send(Message::Text(out.to_string())).await.is_err() { |
| 499 | break; |
| 500 | } |
| 501 | } |
| 502 | } |
| 503 | msg = socket.next() => { |
| 504 | let Some(Ok(msg)) = msg else { |
| 505 | break; |
| 506 | }; |
| 507 | if let Message::Text(text) = msg { |
| 508 | if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&text) { |
| 509 | let msg_type = parsed.get("type").and_then(|v| v.as_str()).unwrap_or("chat"); |
| 510 | match msg_type { |
| 511 | "ping" => { |
| 512 | let pong = json!({"type": "pong", "timestamp": chrono::Utc::now().to_rfc3339()}); |
| 513 | let _ = socket.send(Message::Text(pong.to_string())).await; |
| 514 | } |
| 515 | "heartbeat" => { |
| 516 | let receipt = state.heartbeat.pulse_once().await; |
| 517 | let out = json!({"type": "heartbeat_receipt", "receipt": receipt}); |
| 518 | let _ = socket.send(Message::Text(out.to_string())).await; |
| 519 | } |
| 520 | "skills_list" => { |
| 521 | let list = state.skills.advertised_skills(); |
| 522 | let out = json!({"type": "skills_list", "skills": list}); |
| 523 | let _ = socket.send(Message::Text(out.to_string())).await; |
| 524 | } |
| 525 | "skill_exec" => { |
| 526 | let skill_name = parsed.get("skill_name").and_then(|v| v.as_str()).unwrap_or(""); |
| 527 | let args = parsed.get("arguments").cloned().unwrap_or_else(|| json!({})); |
| 528 | let req = SkillExecutionRequest { |
| 529 | skill_name: skill_name.to_string(), |
| 530 | arguments: args, |
| 531 | }; |
| 532 | let res = state.skills.execute_gated(&req).await; |
| 533 | let out = json!({"type": "skill_result", "response": res}); |
| 534 | let _ = socket.send(Message::Text(out.to_string())).await; |
| 535 | } |
| 536 | "agent_run" => { |
| 537 | let prompt = parsed.get("prompt").and_then(|v| v.as_str()).unwrap_or(""); |
| 538 | let max_turns = parsed.get("max_turns").and_then(|v| v.as_u64()).unwrap_or(8) as usize; |
| 539 | let res = state.agent.execute_task(prompt, None, max_turns).await; |
| 540 | match res { |
| 541 | Ok(exec_result) => { |
| 542 | let out = json!({ |
| 543 | "type": "agent_result", |
| 544 | "status": if exec_result.completed { "completed" } else { "incomplete" }, |
| 545 | "result": exec_result, |
| 546 | }); |
| 547 | let _ = socket.send(Message::Text(out.to_string())).await; |
| 548 | } |
| 549 | Err(e) => { |
| 550 | let out = json!({ |
| 551 | "type": "agent_error", |
| 552 | "error": e.to_string(), |
| 553 | }); |
| 554 | let _ = socket.send(Message::Text(out.to_string())).await; |
| 555 | } |
| 556 | } |
| 557 | } |
| 558 | "shell" => { |
| 559 | let cmd_str = parsed.get("command").and_then(|v| v.as_str()).unwrap_or("echo shell ready"); |
| 560 | let out = match state.skills.workspace().dispatch_shell_gated(cmd_str, None, 15).await { |
| 561 | Ok(stdout) => json!({ |
| 562 | "type": "shell_output", |
| 563 | "stdout": stdout, |
| 564 | "stderr": "", |
| 565 | "exit_code": 0, |
| 566 | }), |
| 567 | Err(e) => json!({ |
| 568 | "type": "shell_error", |
| 569 | "error": e.to_string(), |
| 570 | }), |
| 571 | }; |
| 572 | let _ = socket.send(Message::Text(out.to_string())).await; |
| 573 | } |
| 574 | "simd_eval" => { |
| 575 | let sim = VectorMath::cosine_similarity(&[1.0, 0.0, 0.0, 0.0], &[1.0, 0.0, 0.0, 0.0]); |
| 576 | let out = json!({ |
| 577 | "type": "simd_result", |
| 578 | "cosine_similarity": sim, |
| 579 | }); |
| 580 | let _ = socket.send(Message::Text(out.to_string())).await; |
| 581 | } |
| 582 | _ => { |
| 583 | let prompt = parsed.get("content").and_then(|v| v.as_str()).unwrap_or(&text); |
| 584 | let start = Instant::now(); |
| 585 | let result = state.inference.generate(prompt, None, None).await; |
| 586 | let duration = start.elapsed().as_millis(); |
| 587 | |
| 588 | match result { |
| 589 | Ok(reply) => { |
| 590 | let _ = state.db.record_turn("ws_user", prompt, &reply, duration as u64); |
| 591 | let out = json!({ |
| 592 | "type": "response", |
| 593 | "content": reply, |
| 594 | "duration_ms": duration, |
| 595 | "timestamp": chrono::Utc::now().to_rfc3339(), |
| 596 | }); |
| 597 | if socket.send(Message::Text(out.to_string())).await.is_err() { |
| 598 | break; |
| 599 | } |
| 600 | } |
| 601 | Err(err) => { |
| 602 | let err_out = json!({ |
| 603 | "type": "error", |
| 604 | "message": err.to_string(), |
| 605 | }); |
| 606 | if socket.send(Message::Text(err_out.to_string())).await.is_err() { |
| 607 | break; |
| 608 | } |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | } |
| 614 | } |
| 615 | } |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | #[derive(Deserialize)] |
| 621 | pub struct ProbeApiRequest { |
| 622 | pub state: serde_json::Value, |
| 623 | pub probes: aien_probe::ProbeSet, |
| 624 | } |
| 625 | |
| 626 | #[derive(Serialize)] |
| 627 | pub struct ProbeApiResponse { |
| 628 | pub model: String, |
| 629 | pub answers: Vec<(String, aien_probe::Answer)>, |
| 630 | pub latency_micros: u64, |
| 631 | } |
| 632 | |
| 633 | pub async fn probe_handler( |
| 634 | Json(payload): Json<ProbeApiRequest>, |
| 635 | ) -> Result<Json<ProbeApiResponse>, (StatusCode, String)> { |
| 636 | let engine = aien_probe::ProbeEngine::new(aien_probe::DeterministicReferenceBackend::new()); |
| 637 | let response = engine |
| 638 | .evaluate(&payload.state, &payload.probes) |
| 639 | .await |
| 640 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; |
| 641 | |
| 642 | Ok(Json(ProbeApiResponse { |
| 643 | model: "aien-sovereign-gb10".to_string(), |
| 644 | answers: response.answers, |
| 645 | latency_micros: response.latency_micros, |
| 646 | })) |
| 647 | } |
| 648 | |
| 649 | /// Every route sits behind `auth::require_operator`: deny by default, a short |
| 650 | /// list of read-only GET routes is public, everything else needs the token. |
| 651 | pub fn create_router(state: GatewayState) -> Router { |
| 652 | let operator = state.operator.clone(); |
| 653 | Router::new() |
| 654 | .route("/health", get(health_handler)) |
| 655 | .route("/api/v1/health", get(health_handler)) |
| 656 | .route("/api/v1/chat", post(chat_handler)) |
| 657 | .route("/api/v1/agent/run", post(agent_run_handler)) |
| 658 | .route("/api/v1/heartbeat/tick", post(trigger_heartbeat_handler)) |
| 659 | .route("/api/v1/events", get(sse_events_handler)) |
| 660 | .route("/events", get(sse_events_handler)) |
| 661 | .route("/api/v1/discord/relay", post(discord_relay_handler)) |
| 662 | .route("/api/v1/shell", post(shell_handler)) |
| 663 | .route( |
| 664 | "/api/v1/tasks", |
| 665 | post(create_task_handler).get(list_tasks_handler), |
| 666 | ) |
| 667 | .route("/api/v1/skills", get(list_skills_handler)) |
| 668 | .route("/api/v1/skills/execute", post(execute_skill_handler)) |
| 669 | .route("/v1/chat/completions", post(openai_completions_handler)) |
| 670 | .route("/v1/models", get(openai_models_handler)) |
| 671 | .route("/v1/probe", post(probe_handler)) |
| 672 | .route("/ws", get(ws_handler)) |
| 673 | .route("/api/v1/ws", get(ws_handler)) |
| 674 | // Auth wraps every route (including unknown paths), inside CORS. |
| 675 | .layer(axum::middleware::from_fn_with_state( |
| 676 | operator, |
| 677 | crate::auth::require_operator, |
| 678 | )) |
| 679 | .layer( |
| 680 | CorsLayer::new() |
| 681 | .allow_origin(Any) |
| 682 | .allow_methods(Any) |
| 683 | .allow_headers(Any), |
| 684 | ) |
| 685 | .with_state(state) |
| 686 | } |
| 687 | |
| 688 | /// Listens on `addr`. Callers build it with `auth::resolve_bind_addr`, which |
| 689 | /// refuses non-loopback addresses unless the operator opted in. |
| 690 | pub async fn start_gateway( |
| 691 | state: GatewayState, |
| 692 | addr: SocketAddr, |
| 693 | ) -> Result<(), Box<dyn std::error::Error>> { |
| 694 | if !state.operator.is_configured() { |
| 695 | tracing::warn!( |
| 696 | "No operator token configured ({}); protected routes will refuse every request", |
| 697 | crate::auth::OPERATOR_TOKEN_ENV |
| 698 | ); |
| 699 | } |
| 700 | let app = create_router(state); |
| 701 | info!("AEGIS Gateway listening on http://{}", addr); |
| 702 | |
| 703 | let listener = tokio::net::TcpListener::bind(addr).await?; |
| 704 | axum::serve(listener, app).await?; |
| 705 | Ok(()) |
| 706 | } |
| 707 | |
| 708 | #[cfg(test)] |
| 709 | mod tests { |
| 710 | use super::*; |
| 711 | use crate::HttpInferenceBackend; |
| 712 | |
| 713 | #[tokio::test] |
| 714 | async fn test_gateway_health_handler_unit() { |
| 715 | let db = Arc::new(Database::open_in_memory().unwrap()); |
| 716 | let inference = Arc::new(HttpInferenceBackend::new(None, None)); |
| 717 | let heartbeat = Arc::new(HeartbeatEngine::new(60, db.clone())); |
| 718 | let skills = Arc::new(SkillRegistry::new()); |
| 719 | let agent = Arc::new(AgentEngine::new( |
| 720 | inference.clone(), |
| 721 | skills.clone(), |
| 722 | Some(db.clone()), |
| 723 | )); |
| 724 | |
| 725 | let state = GatewayState { |
| 726 | start_time: Instant::now(), |
| 727 | db, |
| 728 | inference, |
| 729 | heartbeat, |
| 730 | skills, |
| 731 | agent, |
| 732 | operator: crate::auth::OperatorAuth::disabled(), |
| 733 | }; |
| 734 | |
| 735 | let res = health_handler(State(state)).await.into_response(); |
| 736 | assert_eq!(res.status(), StatusCode::OK); |
| 737 | } |
| 738 | } |