Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/openclaw-rs/blob/main/src/gateway.rs # openclaw-rs High-performance sovereign agent runtime in native Rust and Mojo for NVIDIA DGX Spark Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `openclaw-rs / src / gateway.rs` 692 lines ยท 24508 bytes Raw Blame History 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::process::Command; 23 use tokio_stream::wrappers::BroadcastStream; 24 use tower_http::cors::{Any, CorsLayer}; 25 use tracing::info; 26 27 use crate::agent::{AgentEngine, AgentStep}; 28 use crate::heartbeat::HeartbeatEngine; 29 use crate::inference::InferenceEngine; 30 use crate::mojo_bridge::MojoSimdBridge; 31 use crate::persistence::Database; 32 use crate::skills::{SkillExecutionRequest, SkillRegistry}; 33 34 #[derive(Clone)] 35 pub struct GatewayState { 36 pub start_time: Instant, 37 pub db: Arc, 38 pub inference: Arc, 39 pub heartbeat: Arc, 40 pub skills: Arc, 41 pub agent: Arc, 42 } 43 44 #[derive(Serialize)] 45 pub struct HealthResponse { 46 pub status: &'static str, 47 pub engine: &'static str, 48 pub uptime_seconds: u64, 49 pub local_model: String, 50 pub heartbeat_interval_seconds: u64, 51 pub total_heartbeat_ticks: u64, 52 pub database_mode: &'static str, 53 pub mojo_simd_accelerated: bool, 54 pub mojo_simd_version: i32, 55 pub zero_disk_secrets: bool, 56 } 57 58 pub async fn health_handler(State(state): State) -> impl IntoResponse { 59 let uptime = state.start_time.elapsed().as_secs(); 60 let ticks = state.heartbeat.tick_count(); 61 let model = state.inference.model_id(); 62 let mojo_active = MojoSimdBridge::is_mojo_accelerated(); 63 let mojo_ver = MojoSimdBridge::version(); 64 65 Json(HealthResponse { 66 status: "healthy", 67 engine: "openclaw-rs/0.2.0", 68 uptime_seconds: uptime, 69 local_model: model, 70 heartbeat_interval_seconds: state.heartbeat.interval_secs(), 71 total_heartbeat_ticks: ticks, 72 database_mode: "sqlite-wal", 73 mojo_simd_accelerated: mojo_active, 74 mojo_simd_version: mojo_ver, 75 zero_disk_secrets: true, 76 }) 77 } 78 79 #[derive(Deserialize)] 80 pub struct ChatRequest { 81 pub prompt: String, 82 pub system: Option, 83 pub temperature: Option, 84 } 85 86 #[derive(Serialize)] 87 pub struct ChatResponse { 88 pub role: &'static str, 89 pub content: String, 90 pub model: String, 91 pub duration_ms: u128, 92 } 93 94 pub async fn chat_handler( 95 State(state): State, 96 Json(payload): Json, 97 ) -> Result { 98 let start = Instant::now(); 99 let response = state 100 .inference 101 .generate( 102 &payload.prompt, 103 payload.system.as_deref(), 104 payload.temperature, 105 ) 106 .await 107 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; 108 109 let duration = start.elapsed().as_millis(); 110 let model = state.inference.model_id(); 111 112 let _ = state 113 .db 114 .record_turn("user", &payload.prompt, &response, duration as u64); 115 116 Ok(Json(ChatResponse { 117 role: "assistant", 118 content: response, 119 model, 120 duration_ms: duration, 121 })) 122 } 123 124 #[derive(Deserialize)] 125 pub struct AgentRunRequest { 126 pub prompt: String, 127 pub system: Option, 128 pub max_turns: Option, 129 } 130 131 #[derive(Serialize)] 132 pub struct AgentRunResponse { 133 pub status: &'static str, 134 pub prompt: String, 135 pub final_response: String, 136 pub steps: Vec, 137 pub turns_taken: usize, 138 pub duration_ms: u128, 139 pub completed: bool, 140 } 141 142 pub async fn agent_run_handler( 143 State(state): State, 144 Json(payload): Json, 145 ) -> Result { 146 let max_turns = payload.max_turns.unwrap_or(8); 147 let result = state 148 .agent 149 .execute_task(&payload.prompt, payload.system.as_deref(), max_turns) 150 .await 151 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; 152 153 Ok(Json(AgentRunResponse { 154 status: "completed", 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, 174 pub messages: Vec, 175 pub temperature: Option, 176 pub max_tokens: Option, 177 pub stream: Option, 178 } 179 180 pub async fn openai_completions_handler( 181 State(state): State, 182 Json(payload): Json, 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 != "modular-max" 201 && req_model != "openclaw-default" 202 && req_model != "default" 203 { 204 let err_body = json!({ 205 "error": { 206 "message": format!("The model '{}' does not exist or is not supported.", req_model), 207 "type": "invalid_request_error", 208 "param": "model", 209 "code": "model_not_found" 210 } 211 }); 212 return (StatusCode::NOT_FOUND, Json(err_body)).into_response(); 213 } 214 } 215 216 let messages_json: Vec = payload 217 .messages 218 .iter() 219 .map(|m| json!({"role": m.role, "content": m.content})) 220 .collect(); 221 222 let last_user_prompt = payload 223 .messages 224 .iter() 225 .rev() 226 .find(|m| m.role == "user") 227 .map(|m| m.content.as_str()) 228 .unwrap_or("hello") 229 .to_string(); 230 231 if payload.stream == Some(true) { 232 match state 233 .inference 234 .stream_chat(&messages_json, payload.temperature, payload.max_tokens) 235 .await 236 { 237 Ok(res) => { 238 let stream = res.bytes_stream(); 239 let body = Body::from_stream(stream); 240 Response::builder() 241 .header(header::CONTENT_TYPE, "text/event-stream") 242 .header(header::CACHE_CONTROL, "no-cache") 243 .header(header::CONNECTION, "keep-alive") 244 .body(body) 245 .unwrap() 246 } 247 Err(_e) => { 248 let fallback_chunk = json!({ 249 "id": format!("chatcmpl-{}", uuid::Uuid::new_v4()), 250 "object": "chat.completion.chunk", 251 "choices": [{ 252 "delta": {"content": format!("[Fallback]: {}", last_user_prompt)}, 253 "index": 0, 254 "finish_reason": "stop" 255 }] 256 }); 257 let sse_body = format!("data: {}\n\ndata: [DONE]\n\n", fallback_chunk); 258 Response::builder() 259 .header(header::CONTENT_TYPE, "text/event-stream") 260 .body(Body::from(sse_body)) 261 .unwrap() 262 } 263 } 264 } else { 265 let start = Instant::now(); 266 let model = state.inference.model_id(); 267 let result = state 268 .inference 269 .generate_chat(&messages_json, payload.temperature, payload.max_tokens) 270 .await; 271 let duration = start.elapsed().as_millis(); 272 273 match result { 274 Ok(response) => { 275 let _ = state 276 .db 277 .record_turn("user", &last_user_prompt, &response, duration as u64); 278 279 let p_tokens = last_user_prompt.split_whitespace().count(); 280 let c_tokens = response.split_whitespace().count(); 281 282 let resp_body = json!({ 283 "id": format!("chatcmpl-{}", uuid::Uuid::new_v4()), 284 "object": "chat.completion", 285 "created": chrono::Utc::now().timestamp(), 286 "model": model, 287 "choices": [{ 288 "index": 0, 289 "message": { 290 "role": "assistant", 291 "content": response, 292 }, 293 "finish_reason": "stop" 294 }], 295 "usage": { 296 "prompt_tokens": p_tokens, 297 "completion_tokens": c_tokens, 298 "total_tokens": p_tokens + c_tokens, 299 } 300 }); 301 Json(resp_body).into_response() 302 } 303 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(), 304 } 305 } 306 } 307 308 pub async fn openai_models_handler(State(state): State) -> impl IntoResponse { 309 let model = state.inference.model_id(); 310 Json(json!({ 311 "object": "list", 312 "data": [{ 313 "id": model, 314 "object": "model", 315 "created": `1789783086`, 316 "owned_by": "openclaw-rs", 317 }] 318 })) 319 } 320 321 // SSE Events Endpoint 322 pub async fn sse_events_handler( 323 State(state): State, 324 ) -> Sse>> { 325 let rx = state.heartbeat.subscribe(); 326 let stream = BroadcastStream::new(rx).filter_map(|item| async move { 327 match item { 328 Ok(receipt) => { 329 let data = serde_json::to_string(&receipt).unwrap_or_default(); 330 Some(Ok(Event::default().event("heartbeat").data(data))) 331 } 332 Err(_) => None, 333 } 334 }); 335 336 Sse::new(stream).keep_alive(KeepAlive::default()) 337 } 338 339 // Discord Hub Relay 340 #[derive(Deserialize)] 341 pub struct DiscordRelayRequest { 342 pub channel_id: String, 343 pub author: String, 344 pub content: String, 345 } 346 347 pub async fn discord_relay_handler( 348 State(state): State, 349 Json(payload): Json, 350 ) -> impl IntoResponse { 351 let prompt = format!( 352 "[Discord from {} in {}]: {}", 353 payload.author, payload.channel_id, payload.content 354 ); 355 let reply = state 356 .inference 357 .generate(&prompt, None, None) 358 .await 359 .unwrap_or_else(|e| format!("Error: {}", e)); 360 361 let _ = state 362 .db 363 .record_turn(&payload.author, &payload.content, &reply, 10); 364 365 Json(json!({ 366 "status": "relayed", 367 "reply": reply, 368 "timestamp": chrono::Utc::now().to_rfc3339(), 369 })) 370 } 371 372 // Local Shell Executor 373 #[derive(Deserialize)] 374 pub struct ShellRequest { 375 pub command: String, 376 } 377 378 #[derive(Serialize)] 379 pub struct ShellResponse { 380 pub stdout: String, 381 pub stderr: String, 382 pub exit_code: i32, 383 pub success: bool, 384 } 385 386 pub async fn shell_handler( 387 Json(payload): Json, 388 ) -> Result { 389 let output = Command::new("sh") 390 .arg("-c") 391 .arg(&payload.command) 392 .output() 393 .await 394 .map_err(|e| { 395 ( 396 StatusCode::INTERNAL_SERVER_ERROR, 397 format!("Failed to execute command: {}", e), 398 ) 399 })?; 400 401 let stdout = String::from_utf8_lossy(&output.stdout).to_string(); 402 let stderr = String::from_utf8_lossy(&output.stderr).to_string(); 403 let exit_code = output.status.code().unwrap_or(-1); 404 405 Ok(Json(ShellResponse { 406 stdout, 407 stderr, 408 exit_code, 409 success: output.status.success(), 410 })) 411 } 412 413 // Task endpoints 414 #[derive(Deserialize)] 415 pub struct CreateTaskRequest { 416 pub task_type: String, 417 pub payload: String, 418 } 419 420 pub async fn create_task_handler( 421 State(state): State, 422 Json(req): Json, 423 ) -> Result { 424 let id = format!("task-{}", uuid::Uuid::new_v4()); 425 state 426 .db 427 .create_task(&id, &req.task_type, &req.payload) 428 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; 429 430 Ok(Json(json!({ 431 "status": "created", 432 "id": id, 433 "task_type": req.task_type, 434 }))) 435 } 436 437 pub async fn list_tasks_handler( 438 State(state): State, 439 ) -> Result { 440 let tasks = state 441 .db 442 .list_pending_tasks() 443 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; 444 445 Ok(Json(tasks)) 446 } 447 448 pub async fn trigger_heartbeat_handler(State(state): State) -> impl IntoResponse { 449 let receipt = state.heartbeat.pulse_once().await; 450 Json(receipt) 451 } 452 453 // Skills endpoints 454 pub async fn list_skills_handler(State(state): State) -> impl IntoResponse { 455 let list = state.skills.list_skills(); 456 Json(list) 457 } 458 459 pub async fn execute_skill_handler( 460 State(state): State, 461 Json(req): Json, 462 ) -> impl IntoResponse { 463 let res = state.skills.execute(&req); 464 Json(res) 465 } 466 467 pub async fn ws_handler( 468 ws: WebSocketUpgrade, 469 State(state): State, 470 ) -> impl IntoResponse { 471 ws.on_upgrade(move |socket| handle_socket(socket, state)) 472 } 473 474 async fn handle_socket(mut socket: WebSocket, state: GatewayState) { 475 let welcome = json!({ 476 "type": "welcome", 477 "gateway": "openclaw-rs", 478 "engine": "OpenClaw WebSocket Gateway", 479 "status": "connected", 480 "timestamp": chrono::Utc::now().to_rfc3339(), 481 }); 482 483 if socket 484 .send(Message::Text(welcome.to_string())) 485 .await 486 .is_err() 487 { 488 return; 489 } 490 491 let mut pulse_rx = state.heartbeat.subscribe(); 492 493 loop { 494 tokio::select! { 495 pulse = pulse_rx.recv() => { 496 if let Ok(receipt) = pulse { 497 let out = json!({ 498 "type": "heartbeat_pulse", 499 "receipt": receipt, 500 }); 501 if socket.send(Message::Text(out.to_string())).await.is_err() { 502 break; 503 } 504 } 505 } 506 msg = socket.next() => { 507 let Some(Ok(msg)) = msg else { 508 break; 509 }; 510 if let Message::Text(text) = msg { 511 if let Ok(parsed) = serde_json::from_str::(&text) { 512 let msg_type = parsed.get("type").and_then(|v| v.as_str()).unwrap_or("chat"); 513 match msg_type { 514 "ping" => { 515 let pong = json!({"type": "pong", "timestamp": chrono::Utc::now().to_rfc3339()}); 516 let _ = socket.send(Message::Text(pong.to_string())).await; 517 } 518 "heartbeat" => { 519 let receipt = state.heartbeat.pulse_once().await; 520 let out = json!({"type": "heartbeat_receipt", "receipt": receipt}); 521 let _ = socket.send(Message::Text(out.to_string())).await; 522 } 523 "skills_list" => { 524 let list = state.skills.list_skills(); 525 let out = json!({"type": "skills_list", "skills": list}); 526 let _ = socket.send(Message::Text(out.to_string())).await; 527 } 528 "skill_exec" => { 529 let skill_name = parsed.get("skill_name").and_then(|v| v.as_str()).unwrap_or(""); 530 let args = parsed.get("arguments").cloned().unwrap_or_else(|| json!({})); 531 let req = SkillExecutionRequest { 532 skill_name: skill_name.to_string(), 533 arguments: args, 534 }; 535 let res = state.skills.execute(&req); 536 let out = json!({"type": "skill_result", "response": res}); 537 let _ = socket.send(Message::Text(out.to_string())).await; 538 } 539 "agent_run" => { 540 let prompt = parsed.get("prompt").and_then(|v| v.as_str()).unwrap_or(""); 541 let max_turns = parsed.get("max_turns").and_then(|v| v.as_u64()).unwrap_or(8) as usize; 542 let res = state.agent.execute_task(prompt, None, max_turns).await; 543 match res { 544 Ok(exec_result) => { 545 let out = json!({ 546 "type": "agent_result", 547 "result": exec_result, 548 }); 549 let _ = socket.send(Message::Text(out.to_string())).await; 550 } 551 Err(e) => { 552 let out = json!({ 553 "type": "agent_error", 554 "error": e.to_string(), 555 }); 556 let _ = socket.send(Message::Text(out.to_string())).await; 557 } 558 } 559 } 560 "shell" => { 561 let cmd_str = parsed.get("command").and_then(|v| v.as_str()).unwrap_or("echo shell ready"); 562 let res = Command::new("sh").arg("-c").arg(cmd_str).output().await; 563 let out = match res { 564 Ok(o) => json!({ 565 "type": "shell_output", 566 "stdout": String::from_utf8_lossy(&o.stdout), 567 "stderr": String::from_utf8_lossy(&o.stderr), 568 "exit_code": o.status.code().unwrap_or(-1), 569 }), 570 Err(e) => json!({ 571 "type": "shell_error", 572 "error": e.to_string(), 573 }), 574 }; 575 let _ = socket.send(Message::Text(out.to_string())).await; 576 } 577 "simd_eval" => { 578 let sim = MojoSimdBridge::cosine_similarity(&[1.0, 0.0, 0.0, 0.0], &[1.0, 0.0, 0.0, 0.0]); 579 let out = json!({ 580 "type": "simd_result", 581 "cosine_similarity": sim, 582 "accelerated": MojoSimdBridge::is_mojo_accelerated(), 583 "version": MojoSimdBridge::version(), 584 }); 585 let _ = socket.send(Message::Text(out.to_string())).await; 586 } 587 _ => { 588 let prompt = parsed.get("content").and_then(|v| v.as_str()).unwrap_or(&text); 589 let start = Instant::now(); 590 let result = state.inference.generate(prompt, None, None).await; 591 let duration = start.elapsed().as_millis(); 592 593 match result { 594 Ok(reply) => { 595 let _ = state.db.record_turn("ws_user", prompt, &reply, duration as u64); 596 let out = json!({ 597 "type": "response", 598 "content": reply, 599 "duration_ms": duration, 600 "timestamp": chrono::Utc::now().to_rfc3339(), 601 }); 602 if socket.send(Message::Text(out.to_string())).await.is_err() { 603 break; 604 } 605 } 606 Err(err) => { 607 let err_out = json!({ 608 "type": "error", 609 "message": err.to_string(), 610 }); 611 if socket.send(Message::Text(err_out.to_string())).await.is_err() { 612 break; 613 } 614 } 615 } 616 } 617 } 618 } 619 } 620 } 621 } 622 } 623 } 624 625 pub fn create_router(state: GatewayState) -> Router { 626 Router::new() 627 .route("/health", get(health_handler)) 628 .route("/api/v1/health", get(health_handler)) 629 .route("/api/v1/chat", post(chat_handler)) 630 .route("/api/v1/agent/run", post(agent_run_handler)) 631 .route("/api/v1/heartbeat/tick", post(trigger_heartbeat_handler)) 632 .route("/api/v1/events", get(sse_events_handler)) 633 .route("/events", get(sse_events_handler)) 634 .route("/api/v1/discord/relay", post(discord_relay_handler)) 635 .route("/api/v1/shell", post(shell_handler)) 636 .route( 637 "/api/v1/tasks", 638 post(create_task_handler).get(list_tasks_handler), 639 ) 640 .route("/api/v1/skills", get(list_skills_handler)) 641 .route("/api/v1/skills/execute", post(execute_skill_handler)) 642 .route("/v1/chat/completions", post(openai_completions_handler)) 643 .route("/v1/models", get(openai_models_handler)) 644 .route("/ws", get(ws_handler)) 645 .route("/api/v1/ws", get(ws_handler)) 646 .layer( 647 CorsLayer::new() 648 .allow_origin(Any) 649 .allow_methods(Any) 650 .allow_headers(Any), 651 ) 652 .with_state(state) 653 } 654 655 pub async fn start_gateway( 656 state: GatewayState, 657 port: u16, 658 ) -> Result<(), Box> { 659 let app = create_router(state); 660 let addr = SocketAddr::from(([0, 0, 0, 0], port)); 661 info!("OpenClaw Gateway listening on http://{}", addr); 662 663 let listener = tokio::net::TcpListener::bind(addr).await?; 664 axum::serve(listener, app).await?; 665 Ok(()) 666 } 667 668 #[cfg(test)] 669 mod tests { 670 use super::*; 671 672 #[tokio::test] 673 async fn test_gateway_health_handler_unit() { 674 let db = Arc::new(Database::open_in_memory().unwrap()); 675 let inference = Arc::new(InferenceEngine::new(None, None)); 676 let heartbeat = Arc::new(HeartbeatEngine::new(60, db.clone())); 677 let skills = Arc::new(SkillRegistry::new()); 678 let agent = Arc::new(AgentEngine::new(inference.clone(), skills.clone(), Some(db.clone()))); 679 680 let state = GatewayState { 681 start_time: Instant::now(), 682 db, 683 inference, 684 heartbeat, 685 skills, 686 agent, 687 }; 688 689 let res = health_handler(State(state)).await.into_response(); 690 assert_eq!(res.status(), StatusCode::OK); 691 } 692 }