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/aegis-runtime-mv/blob/main/tests/aegis_tests.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aegis-runtime-mv / tests / aegis_tests.rs` 1419 lines ยท 47654 bytes Raw Blame History 1 use aegis::{ 2 create_router, AgentEngine, Database, GatewayState, HeartbeatEngine, HttpInferenceBackend, 3 SkillRegistry, VaultResolver, VectorMath, REDACTED_MARKER, 4 }; 5 use axum::{ 6 body::Body, 7 http::{Request, StatusCode}, 8 }; 9 use futures_util::{SinkExt, StreamExt}; 10 use serde_json::Value; 11 use std::sync::Arc; 12 use std::time::Instant; 13 use tower::util::ServiceExt; 14 15 /// Operator token used by the test gateway. 16 pub const TEST_OPERATOR_TOKEN: &str = "test-operator-token-`0123456789abcdef`"; 17 18 fn auth_header() -> String { 19 format!("Bearer {}", TEST_OPERATOR_TOKEN) 20 } 21 22 /// A catalogued local command that the always-on probe gate admits. 23 /// The deterministic reference probe refuses `bash_eval` with `ls` (hash verdict: 24 /// safety < 0.5, scope "unauthorized_escalation"), so tests that must see a 25 /// successful run use `git status` (safety >= 0.5, scope "contained"). Tests 26 /// run with the crate root as working directory, which is a git checkout. 27 pub const PROBE_ADMITTED_COMMAND: &str = "git status"; 28 29 fn authed_ws_request(url: &str) -> tokio_tungstenite::tungstenite::handshake::client::Request { 30 use tokio_tungstenite::tungstenite::client::IntoClientRequest; 31 let mut req = url.into_client_request().unwrap(); 32 req.headers_mut() 33 .insert("authorization", auth_header().parse().unwrap()); 34 req 35 } 36 37 async fn spawn_mock_inference_server() -> String { 38 let app = axum::Router::new() 39 .route( 40 "/v1/chat/completions", 41 axum::routing::post( 42 |axum::Json(body): axum::Json| async move { 43 use axum::response::IntoResponse; 44 let is_stream = body 45 .get("stream") 46 .and_then(|s| s.as_bool()) 47 .unwrap_or(false); 48 if is_stream { 49 let chunk = serde_json::json!({ 50 "id": "chatcmpl-mock-chunk", 51 "object": "chat.completion.chunk", 52 "choices": [{ 53 "delta": {"content": "mock streaming chunk"}, 54 "index": 0, 55 "finish_reason": "stop" 56 }] 57 }); 58 let sse = format!("data: {}\n\ndata: [DONE]\n\n", chunk); 59 axum::response::Response::builder() 60 .header("Content-Type", "text/event-stream") 61 .body(axum::body::Body::from(sse)) 62 .unwrap() 63 } else { 64 let resp = serde_json::json!({ 65 "id": "chatcmpl-mock", 66 "object": "chat.completion", 67 "created": `1789783086`, 68 "model": "atlas-lightning-omni", 69 "choices": [{ 70 "index": 0, 71 "message": { 72 "role": "assistant", 73 "content": "Mock inference response." 74 }, 75 "finish_reason": "stop" 76 }], 77 "usage": { 78 "prompt_tokens": 5, 79 "completion_tokens": 6, 80 "total_tokens": 11 81 } 82 }); 83 axum::response::Json(resp).into_response() 84 } 85 }, 86 ), 87 ) 88 .route( 89 "/v1/models", 90 axum::routing::get(|| async { 91 axum::Json(serde_json::json!({ 92 "object": "list", 93 "data": [{ 94 "id": "atlas-lightning-omni", 95 "object": "model" 96 }] 97 })) 98 }), 99 ); 100 101 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 102 let port = listener.local_addr().unwrap().port(); 103 tokio::spawn(async move { 104 let _ = axum::serve(listener, app).await; 105 }); 106 format!("http://127.0.0.1:{}/v1/chat/completions", port) 107 } 108 109 async fn create_test_state() -> GatewayState { 110 let mock_endpoint = spawn_mock_inference_server().await; 111 let db = Arc::new(Database::open_in_memory().unwrap()); 112 let inference = Arc::new(HttpInferenceBackend::new(Some(mock_endpoint), None)); 113 let heartbeat = Arc::new(HeartbeatEngine::with_inference( 114 60, 115 db.clone(), 116 inference.clone(), 117 )); 118 let skills = Arc::new(SkillRegistry::new()); 119 let agent = Arc::new(AgentEngine::new( 120 inference.clone(), 121 skills.clone(), 122 Some(db.clone()), 123 )); 124 125 GatewayState { 126 start_time: Instant::now(), 127 db, 128 inference, 129 heartbeat, 130 skills, 131 agent, 132 operator: aegis::OperatorAuth::with_token(TEST_OPERATOR_TOKEN).unwrap(), 133 } 134 } 135 136 #[tokio::test] 137 async fn test_gateway_health_endpoint() { 138 let state = create_test_state().await; 139 let app = create_router(state); 140 141 let response = app 142 .oneshot( 143 Request::builder() 144 .uri("/health") 145 .body(Body::empty()) 146 .unwrap(), 147 ) 148 .await 149 .unwrap(); 150 151 assert_eq!(response.status(), StatusCode::OK); 152 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 153 .await 154 .unwrap(); 155 let body: Value = serde_json::from_slice(&bytes).unwrap(); 156 assert_eq!(body["status"], "healthy"); 157 assert_eq!(body["engine"], "aegis-runtime/0.2.0"); 158 assert_eq!(body["database_mode"], "sqlite-wal"); 159 assert_eq!(body["zero_disk_secrets"], true); 160 } 161 162 #[tokio::test] 163 async fn test_gateway_openai_completions_endpoint() { 164 let state = create_test_state().await; 165 let app = create_router(state); 166 167 let req_payload = serde_json::json!({ 168 "model": "atlas-lightning-omni", 169 "messages": [ 170 {"role": "system", "content": "You are AEGIS."}, 171 {"role": "user", "content": "ping"} 172 ] 173 }); 174 175 let response = app 176 .oneshot( 177 Request::builder() 178 .method("POST") 179 .uri("/v1/chat/completions") 180 .header("Authorization", auth_header()) 181 .header("Content-Type", "application/json") 182 .body(Body::from(req_payload.to_string())) 183 .unwrap(), 184 ) 185 .await 186 .unwrap(); 187 188 assert_eq!(response.status(), StatusCode::OK); 189 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 190 .await 191 .unwrap(); 192 let body: Value = serde_json::from_slice(&bytes).unwrap(); 193 assert_eq!(body["object"], "chat.completion"); 194 assert_eq!(body["choices"][0]["message"]["role"], "assistant"); 195 } 196 197 #[tokio::test] 198 async fn test_gateway_openai_multiturn_completions() { 199 let state = create_test_state().await; 200 let app = create_router(state); 201 202 let req_payload = serde_json::json!({ 203 "model": "atlas-lightning-omni", 204 "messages": [ 205 {"role": "system", "content": "You are AEGIS systems agent."}, 206 {"role": "user", "content": "List current memory status."}, 207 {"role": "assistant", "content": "All memory buffers nominal."}, 208 {"role": "user", "content": "Execute verification sweep."} 209 ] 210 }); 211 212 let response = app 213 .oneshot( 214 Request::builder() 215 .method("POST") 216 .uri("/v1/chat/completions") 217 .header("Authorization", auth_header()) 218 .header("Content-Type", "application/json") 219 .body(Body::from(req_payload.to_string())) 220 .unwrap(), 221 ) 222 .await 223 .unwrap(); 224 225 assert_eq!(response.status(), StatusCode::OK); 226 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 227 .await 228 .unwrap(); 229 let body: Value = serde_json::from_slice(&bytes).unwrap(); 230 assert_eq!(body["object"], "chat.completion"); 231 assert_eq!(body["choices"][0]["finish_reason"], "stop"); 232 } 233 234 #[tokio::test] 235 async fn test_gateway_openai_streaming_endpoint() { 236 let state = create_test_state().await; 237 let app = create_router(state); 238 239 let req_payload = serde_json::json!({ 240 "model": "atlas-lightning-omni", 241 "messages": [ 242 {"role": "user", "content": "stream tokens"} 243 ], 244 "stream": true 245 }); 246 247 let response = app 248 .oneshot( 249 Request::builder() 250 .method("POST") 251 .uri("/v1/chat/completions") 252 .header("Authorization", auth_header()) 253 .header("Content-Type", "application/json") 254 .body(Body::from(req_payload.to_string())) 255 .unwrap(), 256 ) 257 .await 258 .unwrap(); 259 260 assert_eq!(response.status(), StatusCode::OK); 261 assert_eq!( 262 response.headers().get("content-type").unwrap(), 263 "text/event-stream" 264 ); 265 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 266 .await 267 .unwrap(); 268 let text = String::from_utf8_lossy(&bytes); 269 assert!(text.contains("data:")); 270 } 271 272 #[tokio::test] 273 async fn test_gateway_skills_endpoints() { 274 let state = create_test_state().await; 275 let app = create_router(state.clone()); 276 277 // 1. List skills 278 let list_res = app 279 .oneshot( 280 Request::builder() 281 .uri("/api/v1/skills") 282 .body(Body::empty()) 283 .unwrap(), 284 ) 285 .await 286 .unwrap(); 287 288 assert_eq!(list_res.status(), StatusCode::OK); 289 let bytes = axum::body::to_bytes(list_res.into_body(), usize::MAX) 290 .await 291 .unwrap(); 292 let list: Value = serde_json::from_slice(&bytes).unwrap(); 293 let skills = list.as_array().unwrap(); 294 assert!(skills.iter().any(|s| s["name"] == "bash_eval")); 295 assert!(skills.iter().all(|s| s["name"] != "telemetry_ping")); // no telemetry 296 297 // 2. Execute skill 298 let app2 = create_router(state); 299 let exec_payload = serde_json::json!({ 300 "skill_name": "bash_eval", 301 "arguments": {"command": PROBE_ADMITTED_COMMAND} 302 }); 303 304 let exec_res = app2 305 .oneshot( 306 Request::builder() 307 .method("POST") 308 .uri("/api/v1/skills/execute") 309 .header("Authorization", auth_header()) 310 .header("Content-Type", "application/json") 311 .body(Body::from(exec_payload.to_string())) 312 .unwrap(), 313 ) 314 .await 315 .unwrap(); 316 317 assert_eq!(exec_res.status(), StatusCode::OK); 318 let bytes2 = axum::body::to_bytes(exec_res.into_body(), usize::MAX) 319 .await 320 .unwrap(); 321 let result: Value = serde_json::from_slice(&bytes2).unwrap(); 322 assert_eq!(result["success"], true); 323 } 324 325 #[tokio::test] 326 async fn test_gateway_shell_execution() { 327 let state = create_test_state().await; 328 let app = create_router(state); 329 330 let req_payload = serde_json::json!({ 331 "command": PROBE_ADMITTED_COMMAND 332 }); 333 334 let response = app 335 .oneshot( 336 Request::builder() 337 .method("POST") 338 .uri("/api/v1/shell") 339 .header("Authorization", auth_header()) 340 .header("Content-Type", "application/json") 341 .body(Body::from(req_payload.to_string())) 342 .unwrap(), 343 ) 344 .await 345 .unwrap(); 346 347 assert_eq!(response.status(), StatusCode::OK); 348 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 349 .await 350 .unwrap(); 351 let body: Value = serde_json::from_slice(&bytes).unwrap(); 352 assert_eq!(body["success"], true); 353 } 354 355 #[tokio::test] 356 async fn test_gateway_task_creation_and_listing() { 357 let state = create_test_state().await; 358 let app = create_router(state.clone()); 359 360 let req_payload = serde_json::json!({ 361 "task_type": "build_monitor", 362 "payload": "echo 'build nominal'" 363 }); 364 365 let response = app 366 .oneshot( 367 Request::builder() 368 .method("POST") 369 .uri("/api/v1/tasks") 370 .header("Authorization", auth_header()) 371 .header("Content-Type", "application/json") 372 .body(Body::from(req_payload.to_string())) 373 .unwrap(), 374 ) 375 .await 376 .unwrap(); 377 378 assert_eq!(response.status(), StatusCode::OK); 379 380 let app2 = create_router(state); 381 let list_response = app2 382 .oneshot( 383 Request::builder() 384 .uri("/api/v1/tasks") 385 .header("Authorization", auth_header()) 386 .body(Body::empty()) 387 .unwrap(), 388 ) 389 .await 390 .unwrap(); 391 392 assert_eq!(list_response.status(), StatusCode::OK); 393 let bytes = axum::body::to_bytes(list_response.into_body(), usize::MAX) 394 .await 395 .unwrap(); 396 let tasks: Value = serde_json::from_slice(&bytes).unwrap(); 397 assert_eq!(tasks.as_array().unwrap().len(), 1); 398 assert_eq!(tasks[0]["task_type"], "build_monitor"); 399 } 400 401 #[tokio::test] 402 async fn test_gateway_websocket_lifecycle() { 403 let state = create_test_state().await; 404 let app = create_router(state); 405 406 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 407 let port = listener.local_addr().unwrap().port(); 408 409 tokio::spawn(async move { 410 axum::serve(listener, app).await.unwrap(); 411 }); 412 413 let ws_url = format!("ws://127.0.0.1:{}/ws", port); 414 let (mut ws_stream, _) = tokio_tungstenite::connect_async(authed_ws_request(&ws_url)) 415 .await 416 .unwrap(); 417 418 // 1. Welcome message 419 let msg = ws_stream.next().await.unwrap().unwrap(); 420 let val: Value = serde_json::from_str(&msg.to_string()).unwrap(); 421 assert_eq!(val["type"], "welcome"); 422 assert_eq!(val["gateway"], "aegis-runtime"); 423 424 // 2. Ping / Pong 425 ws_stream 426 .send(tokio_tungstenite::tungstenite::Message::Text( 427 serde_json::json!({"type": "ping"}).to_string(), 428 )) 429 .await 430 .unwrap(); 431 432 let msg = ws_stream.next().await.unwrap().unwrap(); 433 let val: Value = serde_json::from_str(&msg.to_string()).unwrap(); 434 assert_eq!(val["type"], "pong"); 435 436 // 3. Skills list over WebSocket 437 ws_stream 438 .send(tokio_tungstenite::tungstenite::Message::Text( 439 serde_json::json!({"type": "skills_list"}).to_string(), 440 )) 441 .await 442 .unwrap(); 443 444 let msg = ws_stream.next().await.unwrap().unwrap(); 445 let val: Value = serde_json::from_str(&msg.to_string()).unwrap(); 446 assert_eq!(val["type"], "skills_list"); 447 assert!(!val["skills"].as_array().unwrap().is_empty()); 448 449 // 4. Skill execute over WebSocket 450 ws_stream 451 .send(tokio_tungstenite::tungstenite::Message::Text( 452 serde_json::json!({ 453 "type": "skill_exec", 454 "skill_name": "telemetry_ping", 455 "arguments": {} 456 }) 457 .to_string(), 458 )) 459 .await 460 .unwrap(); 461 462 let msg = ws_stream.next().await.unwrap().unwrap(); 463 let val: Value = serde_json::from_str(&msg.to_string()).unwrap(); 464 assert_eq!(val["type"], "skill_result"); 465 assert_eq!(val["response"]["success"], false); 466 } 467 468 #[tokio::test] 469 async fn test_vector_math_operations() { 470 let v1 = [1.0f32, 0.0, 0.0, 0.0]; 471 let v2 = [1.0f32, 0.0, 0.0, 0.0]; 472 let sim = VectorMath::cosine_similarity_4d(v1, v2); 473 assert!((sim - 1.0).abs() < 1e-4); 474 475 let tokens = [2.0f32, 4.0, 6.0, 8.0]; 476 let weights = [0.25f32, 0.25, 0.25, 0.25]; 477 let proj = VectorMath::token_projection(tokens, weights, 2.0); 478 assert!((proj - 7.0).abs() < 1e-4); 479 480 let entropy = VectorMath::token_entropy([0.5, 0.5, 0.0, 0.0]); 481 assert!((entropy - std::f32::consts::LN_2).abs() < 1e-4); 482 assert!(entropy > 0.0); 483 } 484 485 #[tokio::test] 486 async fn test_gateway_agent_run_endpoint() { 487 let state = create_test_state().await; 488 let app = create_router(state); 489 490 let req_payload = serde_json::json!({ 491 "prompt": "Status and telemetry check", 492 "max_turns": 2 493 }); 494 495 let response = app 496 .oneshot( 497 Request::builder() 498 .method("POST") 499 .uri("/api/v1/agent/run") 500 .header("Authorization", auth_header()) 501 .header("Content-Type", "application/json") 502 .body(Body::from(req_payload.to_string())) 503 .unwrap(), 504 ) 505 .await 506 .unwrap(); 507 508 assert_eq!(response.status(), StatusCode::OK); 509 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 510 .await 511 .unwrap(); 512 let body: Value = serde_json::from_slice(&bytes).unwrap(); 513 assert_eq!(body["status"], "completed"); 514 assert_eq!(body["prompt"], "Status and telemetry check"); 515 assert!(body["steps"].is_array()); 516 } 517 518 #[tokio::test] 519 async fn test_gateway_concurrent_requests_under_tokio_spawns() { 520 let state = create_test_state().await; 521 let app = create_router(state); 522 523 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 524 let port = listener.local_addr().unwrap().port(); 525 526 tokio::spawn(async move { 527 axum::serve(listener, app).await.unwrap(); 528 }); 529 530 let client = reqwest::Client::new(); 531 let base_url = format!("http://127.0.0.1:{}", port); 532 533 let mut handles = Vec::new(); 534 for i in 0..30 { 535 let client_clone = client.clone(); 536 let base = base_url.clone(); 537 handles.push(tokio::spawn(async move { 538 match i % 4 { 539 0 => { 540 let res = client_clone 541 .get(format!("{}/health", base)) 542 .send() 543 .await 544 .unwrap(); 545 assert_eq!(res.status(), 200); 546 } 547 1 => { 548 let res = client_clone 549 .get(format!("{}/v1/models", base)) 550 .send() 551 .await 552 .unwrap(); 553 assert_eq!(res.status(), 200); 554 } 555 2 => { 556 let res = client_clone 557 .get(format!("{}/api/v1/skills", base)) 558 .send() 559 .await 560 .unwrap(); 561 assert_eq!(res.status(), 200); 562 } 563 _ => { 564 let payload = serde_json::json!({ 565 "model": "atlas-lightning-omni", 566 "messages": [{"role": "user", "content": "concurrent ping"}] 567 }); 568 let res = client_clone 569 .post(format!("{}/v1/chat/completions", base)) 570 .header("Authorization", auth_header()) 571 .json(&payload) 572 .send() 573 .await 574 .unwrap(); 575 assert_eq!(res.status(), 200); 576 } 577 } 578 })); 579 } 580 581 for handle in handles { 582 handle.await.unwrap(); 583 } 584 } 585 586 #[tokio::test] 587 async fn test_gateway_completions_error_handling_and_validation() { 588 let state = create_test_state().await; 589 590 // 1. Malformed JSON syntax 591 let app1 = create_router(state.clone()); 592 let malformed_res = app1 593 .oneshot( 594 Request::builder() 595 .method("POST") 596 .uri("/v1/chat/completions") 597 .header("Authorization", auth_header()) 598 .header("Content-Type", "application/json") 599 .body(Body::from("{ \"model\": invalid_syntax")) 600 .unwrap(), 601 ) 602 .await 603 .unwrap(); 604 assert!( 605 malformed_res.status() == StatusCode::BAD_REQUEST 606 || malformed_res.status() == StatusCode::UNPROCESSABLE_ENTITY 607 ); 608 609 // 2. Missing required field 'messages' 610 let app2 = create_router(state.clone()); 611 let missing_field_payload = serde_json::json!({ 612 "model": "atlas-lightning-omni" 613 }); 614 let missing_field_res = app2 615 .oneshot( 616 Request::builder() 617 .method("POST") 618 .uri("/v1/chat/completions") 619 .header("Authorization", auth_header()) 620 .header("Content-Type", "application/json") 621 .body(Body::from(missing_field_payload.to_string())) 622 .unwrap(), 623 ) 624 .await 625 .unwrap(); 626 assert_eq!(missing_field_res.status(), StatusCode::UNPROCESSABLE_ENTITY); 627 628 // 3. Empty messages array 629 let app3 = create_router(state.clone()); 630 let empty_messages_payload = serde_json::json!({ 631 "model": "atlas-lightning-omni", 632 "messages": [] 633 }); 634 let empty_res = app3 635 .oneshot( 636 Request::builder() 637 .method("POST") 638 .uri("/v1/chat/completions") 639 .header("Authorization", auth_header()) 640 .header("Content-Type", "application/json") 641 .body(Body::from(empty_messages_payload.to_string())) 642 .unwrap(), 643 ) 644 .await 645 .unwrap(); 646 assert_eq!(empty_res.status(), StatusCode::BAD_REQUEST); 647 let bytes = axum::body::to_bytes(empty_res.into_body(), usize::MAX) 648 .await 649 .unwrap(); 650 let body: Value = serde_json::from_slice(&bytes).unwrap(); 651 assert_eq!(body["error"]["code"], "missing_required_parameter"); 652 653 // 4. Unsupported model 654 let app4 = create_router(state.clone()); 655 let unsupported_model_payload = serde_json::json!({ 656 "model": "unsupported-model-v999", 657 "messages": [{"role": "user", "content": "ping"}] 658 }); 659 let unsupported_res = app4 660 .oneshot( 661 Request::builder() 662 .method("POST") 663 .uri("/v1/chat/completions") 664 .header("Authorization", auth_header()) 665 .header("Content-Type", "application/json") 666 .body(Body::from(unsupported_model_payload.to_string())) 667 .unwrap(), 668 ) 669 .await 670 .unwrap(); 671 assert_eq!(unsupported_res.status(), StatusCode::NOT_FOUND); 672 let bytes = axum::body::to_bytes(unsupported_res.into_body(), usize::MAX) 673 .await 674 .unwrap(); 675 let body: Value = serde_json::from_slice(&bytes).unwrap(); 676 assert_eq!(body["error"]["code"], "model_not_found"); 677 } 678 679 #[tokio::test] 680 async fn test_gateway_openai_streaming_formatting_and_terminal_chunk() { 681 let state = create_test_state().await; 682 let app = create_router(state); 683 684 let payload = serde_json::json!({ 685 "model": "atlas-lightning-omni", 686 "messages": [{"role": "user", "content": "stream token check"}], 687 "stream": true 688 }); 689 690 let response = app 691 .oneshot( 692 Request::builder() 693 .method("POST") 694 .uri("/v1/chat/completions") 695 .header("Authorization", auth_header()) 696 .header("Content-Type", "application/json") 697 .body(Body::from(payload.to_string())) 698 .unwrap(), 699 ) 700 .await 701 .unwrap(); 702 703 assert_eq!(response.status(), StatusCode::OK); 704 assert_eq!( 705 response.headers().get("content-type").unwrap(), 706 "text/event-stream" 707 ); 708 709 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 710 .await 711 .unwrap(); 712 let sse_text = String::from_utf8_lossy(&bytes); 713 714 // Split by double newline into SSE events 715 let events: Vec<&str> = sse_text 716 .split("\n\n") 717 .map(|s| s.trim()) 718 .filter(|s| !s.is_empty()) 719 .collect(); 720 721 assert!(events.len() >= 2); 722 723 // Verify first event is formatted chunk 724 let first_event = events[0]; 725 assert!(first_event.starts_with("data: ")); 726 let json_str = &first_event["data: ".len()..]; 727 let chunk_json: Value = serde_json::from_str(json_str).unwrap(); 728 assert_eq!(chunk_json["object"], "chat.completion.chunk"); 729 assert!(chunk_json["choices"][0]["delta"]["content"].is_string()); 730 731 // Verify last event is [DONE] 732 let last_event = events.last().unwrap(); 733 assert_eq!(*last_event, "data: [DONE]"); 734 } 735 736 #[tokio::test] 737 async fn test_gateway_agent_run_complex_payloads_and_edge_paths() { 738 let state = create_test_state().await; 739 let app = create_router(state); 740 741 let complex_goal = "Execute sovereign diagnostics:\n1. Check local environment with \"quotes\" and { \"nested\": \"json\", \"value\": 42 }\n2. Inspect filesystem safety: prohibited 'find /' checks\n3. Emit unslop confirmation report"; 742 743 let payload = serde_json::json!({ 744 "prompt": complex_goal, 745 "system": "You are AEGIS sovereign integration verifier.", 746 "max_turns": 3 747 }); 748 749 let response = app 750 .oneshot( 751 Request::builder() 752 .method("POST") 753 .uri("/api/v1/agent/run") 754 .header("Authorization", auth_header()) 755 .header("Content-Type", "application/json") 756 .body(Body::from(payload.to_string())) 757 .unwrap(), 758 ) 759 .await 760 .unwrap(); 761 762 assert_eq!(response.status(), StatusCode::OK); 763 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 764 .await 765 .unwrap(); 766 let body: Value = serde_json::from_slice(&bytes).unwrap(); 767 assert_eq!(body["status"], "completed"); 768 assert_eq!(body["prompt"], complex_goal); 769 assert!(body["turns_taken"].as_u64().unwrap() <= 3); 770 assert!(body["completed"].as_bool().unwrap()); 771 assert!(body["steps"].is_array()); 772 } 773 774 #[tokio::test] 775 async fn test_gateway_websocket_lifecycle_ping_pong_and_close() { 776 let state = create_test_state().await; 777 let app = create_router(state); 778 779 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 780 let port = listener.local_addr().unwrap().port(); 781 782 tokio::spawn(async move { 783 axum::serve(listener, app).await.unwrap(); 784 }); 785 786 let ws_url = format!("ws://127.0.0.1:{}/ws", port); 787 let (mut ws_stream, _) = tokio_tungstenite::connect_async(authed_ws_request(&ws_url)) 788 .await 789 .unwrap(); 790 791 // 1. Welcome frame 792 let welcome_msg = ws_stream.next().await.unwrap().unwrap(); 793 let val: Value = serde_json::from_str(&welcome_msg.to_string()).unwrap(); 794 assert_eq!(val["type"], "welcome"); 795 796 // 2. Application Ping -> Pong 797 ws_stream 798 .send(tokio_tungstenite::tungstenite::Message::Text( 799 serde_json::json!({"type": "ping"}).to_string(), 800 )) 801 .await 802 .unwrap(); 803 let pong_msg = ws_stream.next().await.unwrap().unwrap(); 804 let pong_val: Value = serde_json::from_str(&pong_msg.to_string()).unwrap(); 805 assert_eq!(pong_val["type"], "pong"); 806 807 // 3. Native Tungstenite Ping frame -> expect native Pong frame 808 ws_stream 809 .send(tokio_tungstenite::tungstenite::Message::Ping(vec![9, 8, 7])) 810 .await 811 .unwrap(); 812 813 let pong_frame = ws_stream.next().await.unwrap().unwrap(); 814 assert!(pong_frame.is_pong()); 815 if let tokio_tungstenite::tungstenite::Message::Pong(data) = pong_frame { 816 assert_eq!(data, vec![9, 8, 7]); 817 } 818 819 // 4. Shell execution via WebSocket 820 ws_stream 821 .send(tokio_tungstenite::tungstenite::Message::Text( 822 serde_json::json!({ 823 "type": "shell", 824 "command": PROBE_ADMITTED_COMMAND 825 }) 826 .to_string(), 827 )) 828 .await 829 .unwrap(); 830 let shell_msg = ws_stream.next().await.unwrap().unwrap(); 831 let shell_val: Value = serde_json::from_str(&shell_msg.to_string()).unwrap(); 832 assert_eq!(shell_val["type"], "shell_output"); 833 assert!(shell_val["stdout"].as_str().is_some()); 834 835 // 5. Clean connection close 836 ws_stream 837 .send(tokio_tungstenite::tungstenite::Message::Close(None)) 838 .await 839 .unwrap(); 840 } 841 842 #[tokio::test] 843 async fn test_gateway_submillisecond_health_latency_benchmark() { 844 let state = create_test_state().await; 845 846 let app = create_router(state); 847 848 // Warm-up 849 for _ in 0..5 { 850 let _ = app 851 .clone() 852 .oneshot( 853 Request::builder() 854 .uri("/health") 855 .body(Body::empty()) 856 .unwrap(), 857 ) 858 .await 859 .unwrap(); 860 } 861 862 let iterations = 100; 863 let mut total_duration_micros: u128 = 0; 864 865 for _ in 0..iterations { 866 let start = Instant::now(); 867 let response = app 868 .clone() 869 .oneshot( 870 Request::builder() 871 .uri("/health") 872 .body(Body::empty()) 873 .unwrap(), 874 ) 875 .await 876 .unwrap(); 877 let elapsed = start.elapsed().as_micros(); 878 assert_eq!(response.status(), StatusCode::OK); 879 total_duration_micros += elapsed; 880 } 881 882 let avg_micros = total_duration_micros / iterations; 883 println!( 884 "Health endpoint latency benchmark: {} iterations, average = {} microseconds", 885 iterations, avg_micros 886 ); 887 assert!( 888 avg_micros < 1000, 889 "Health endpoint average latency must be sub-millisecond, got {} us", 890 avg_micros 891 ); 892 } 893 894 #[tokio::test] 895 async fn test_agent_multiturn_accumulation_and_error_recovery() { 896 let mock_url = spawn_mock_inference_server().await; 897 let db = Arc::new(Database::open_in_memory().unwrap()); 898 let inference = Arc::new(HttpInferenceBackend::new(Some(mock_url), None)); 899 let skills = Arc::new(SkillRegistry::new()); 900 let agent = AgentEngine::new(inference, skills.clone(), Some(db.clone())); 901 902 // Test execution with max_turns = 3 under mock inference 903 let result = agent 904 .execute_task("Run sequential diagnostic checks", None, 3) 905 .await 906 .unwrap(); 907 908 assert!(result.completed); 909 assert!(result.turns_taken >= 1); 910 assert!(!result.final_response.is_empty()); 911 912 // Verify DB recorded turn 913 let turns = db.list_recent_turns(5).unwrap(); 914 assert!(!turns.is_empty()); 915 assert_eq!(turns[0].prompt, "Run sequential diagnostic checks"); 916 } 917 918 #[test] 919 fn test_agent_token_budget_boundary_conditions() { 920 let mut msgs = vec![ 921 serde_json::json!({"role": "system", "content": "System prompt"}), 922 serde_json::json!({"role": "user", "content": "User initial request"}), 923 serde_json::json!({"role": "assistant", "content": "Step 1"}), 924 serde_json::json!({"role": "tool", "content": "Tool output 1"}), 925 serde_json::json!({"role": "assistant", "content": "Step 2"}), 926 serde_json::json!({"role": "tool", "content": "Tool output 2"}), 927 ]; 928 929 // Budget higher than tokens: no pruning 930 let p1 = AgentEngine::prune_context_window(&mut msgs, 5000); 931 assert!(!p1); 932 assert_eq!(msgs.len(), 6); 933 934 // Budget lower than tokens: prunes oldest intermediate turns first 935 let p2 = AgentEngine::prune_context_window(&mut msgs, 15); 936 assert!(p2); 937 assert_eq!(msgs.len(), 2); 938 assert_eq!(msgs[0]["role"], "system"); 939 assert_eq!(msgs[1]["role"], "user"); 940 941 // Boundary: length <= 2 cannot be pruned further 942 let p3 = AgentEngine::prune_context_window(&mut msgs, 0); 943 assert!(!p3); 944 assert_eq!(msgs.len(), 2); 945 } 946 947 #[test] 948 fn test_vault_streaming_redaction_and_zero_disk_keys() { 949 let vault = VaultResolver::new(); 950 vault.insert_cached("API_SECRET_KEY", "aegis_sk_live_alpha9922"); 951 vault.insert_cached("DB_PASS", "postgres_master_secret_123"); 952 953 // Test streaming token chunks 954 let stream_chunks = vec![ 955 "data: {\"token\": \"Authentication header: Bearer \"}\n\n", 956 "data: {\"token\": \"aegis_sk_live_alpha9922\"}\n\n", 957 "data: {\"token\": \" connected with postgres_master_secret_123\"}\n\n", 958 "data: [DONE]\n\n", 959 ]; 960 961 let mut redacted_chunks = Vec::new(); 962 for chunk in stream_chunks { 963 redacted_chunks.push(vault.redact_sensitive_text(chunk)); 964 } 965 966 assert!(!redacted_chunks[1].contains("aegis_sk_live_alpha9922")); 967 assert!(redacted_chunks[1].contains(REDACTED_MARKER)); 968 assert!(!redacted_chunks[2].contains("postgres_master_secret_123")); 969 assert!(redacted_chunks[2].contains(REDACTED_MARKER)); 970 971 // Multi-line response redaction 972 let multiline = "Error log:\nAuth: aegis_sk_live_alpha9922\nDB: postgres_master_secret_123\nStatus: nominal"; 973 let redacted_multi = vault.redact_sensitive_text(multiline); 974 assert!(!redacted_multi.contains("aegis_sk_live_alpha9922")); 975 assert!(!redacted_multi.contains("postgres_master_secret_123")); 976 977 // Verify zero disk secrets written 978 assert!(!std::path::Path::new(".env").exists()); 979 assert!(!std::path::Path::new(".env.local").exists()); 980 assert!(!std::path::Path::new(".env.production").exists()); 981 } 982 983 #[test] 984 fn test_vector_math_invariants_and_edge_cases() { 985 // Zero vectors 986 let zero = [0.0f32, 0.0, 0.0, 0.0]; 987 let non_zero = [1.0f32, 2.0, 3.0, 4.0]; 988 assert_eq!(VectorMath::cosine_similarity_4d(zero, non_zero), 0.0); 989 assert_eq!(VectorMath::cosine_similarity_4d(zero, zero), 0.0); 990 991 // Identical vectors 992 let v = [0.5f32, -0.5, 0.5, -0.5]; 993 let sim_ident = VectorMath::cosine_similarity_4d(v, v); 994 assert!((sim_ident - 1.0).abs() < 1e-4); 995 996 // Orthogonal vectors 997 let o1 = [1.0f32, 0.0, 0.0, 0.0]; 998 let o2 = [0.0f32, 1.0, 0.0, 0.0]; 999 assert_eq!(VectorMath::cosine_similarity_4d(o1, o2), 0.0); 1000 1001 // Opposite vectors 1002 let opp = [-0.5f32, 0.5, -0.5, 0.5]; 1003 let sim_opp = VectorMath::cosine_similarity_4d(v, opp); 1004 assert!((sim_opp - (-1.0)).abs() < 1e-4); 1005 1006 // NaN and Inf handling 1007 let nan_v = [f32::NAN, 1.0, 2.0, 3.0]; 1008 let inf_v = [f32::INFINITY, 1.0, 2.0, 3.0]; 1009 assert_eq!(VectorMath::cosine_similarity_4d(nan_v, non_zero), 0.0); 1010 assert_eq!(VectorMath::cosine_similarity_4d(inf_v, non_zero), 0.0); 1011 1012 // Temperature scale boundaries 1013 assert_eq!(VectorMath::temperature_scale(4.0, 0.0), 4.0); 1014 assert_eq!(VectorMath::temperature_scale(4.0, f32::NAN), 0.0); 1015 let normal_scaled = VectorMath::temperature_scale(8.0, 2.0); 1016 assert!((normal_scaled - 4.0).abs() < 1e-4); 1017 } 1018 1019 #[tokio::test] 1020 async fn test_gateway_offline_inference_fail_closed() { 1021 let db = Arc::new(Database::open_in_memory().unwrap()); 1022 let inference = Arc::new(HttpInferenceBackend::new( 1023 Some("http://127.0.0.1:9999/v1/chat/completions".to_string()), 1024 None, 1025 )); 1026 let heartbeat = Arc::new(HeartbeatEngine::with_inference( 1027 60, 1028 db.clone(), 1029 inference.clone(), 1030 )); 1031 let skills = Arc::new(SkillRegistry::new()); 1032 let agent = Arc::new(AgentEngine::new( 1033 inference.clone(), 1034 skills.clone(), 1035 Some(db.clone()), 1036 )); 1037 let state = GatewayState { 1038 start_time: Instant::now(), 1039 db, 1040 inference, 1041 heartbeat, 1042 skills, 1043 agent, 1044 operator: aegis::OperatorAuth::with_token(TEST_OPERATOR_TOKEN).unwrap(), 1045 }; 1046 let app = create_router(state); 1047 1048 let req_payload = serde_json::json!({ 1049 "model": "atlas-lightning-omni", 1050 "messages": [ 1051 {"role": "user", "content": "ping"} 1052 ] 1053 }); 1054 1055 let response = app 1056 .oneshot( 1057 Request::builder() 1058 .method("POST") 1059 .uri("/v1/chat/completions") 1060 .header("Authorization", auth_header()) 1061 .header("Content-Type", "application/json") 1062 .body(Body::from(req_payload.to_string())) 1063 .unwrap(), 1064 ) 1065 .await 1066 .unwrap(); 1067 1068 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); 1069 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 1070 .await 1071 .unwrap(); 1072 let err_str = String::from_utf8_lossy(&bytes); 1073 assert!(err_str.contains("Inference endpoint unreachable")); 1074 } 1075 1076 #[tokio::test] 1077 async fn test_agent_offline_inference_fail_closed() { 1078 let db = Arc::new(Database::open_in_memory().unwrap()); 1079 let inference = Arc::new(HttpInferenceBackend::new( 1080 Some("http://127.0.0.1:9999/v1/chat/completions".to_string()), 1081 None, 1082 )); 1083 let skills = Arc::new(SkillRegistry::new()); 1084 let agent = AgentEngine::new(inference, skills.clone(), Some(db.clone())); 1085 1086 let result = agent 1087 .execute_task("Run sequential diagnostic checks", None, 3) 1088 .await; 1089 1090 assert!(result.is_err()); 1091 let err = result.unwrap_err(); 1092 assert!(err.to_string().contains("Inference endpoint unreachable")); 1093 } 1094 1095 #[tokio::test] 1096 async fn test_gateway_probe_endpoint() { 1097 let state = create_test_state().await; 1098 let app = create_router(state); 1099 1100 let probes = aien_probe::ProbeSet::new().with( 1101 "safety", 1102 aien_probe::Probe::Noul(aien_probe::Noul::new("Is this code safe?")), 1103 ); 1104 1105 let payload = serde_json::json!({ 1106 "state": { "diff": "+ fn main() {}" }, 1107 "probes": probes, 1108 }); 1109 1110 let response = app 1111 .oneshot( 1112 Request::builder() 1113 .method("POST") 1114 .uri("/v1/probe") 1115 .header("Authorization", auth_header()) 1116 .header("content-type", "application/json") 1117 .body(Body::from(serde_json::to_vec(&payload).unwrap())) 1118 .unwrap(), 1119 ) 1120 .await 1121 .unwrap(); 1122 1123 assert_eq!(response.status(), StatusCode::OK); 1124 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 1125 .await 1126 .unwrap(); 1127 let body: Value = serde_json::from_slice(&bytes).unwrap(); 1128 assert_eq!(body["model"], "aien-sovereign-gb10"); 1129 assert!(body["answers"].as_array().is_some()); 1130 } 1131 1132 #[tokio::test] 1133 async fn completion_truth_http_turn_exhaustion_is_incomplete() { 1134 let app = create_router(create_test_state().await); 1135 let response = app 1136 .oneshot( 1137 Request::builder() 1138 .method("POST") 1139 .uri("/api/v1/agent/run") 1140 .header("Authorization", auth_header()) 1141 .header("Content-Type", "application/json") 1142 .body(Body::from(r#"{"prompt":"no turn budget","max_turns":0}"#)) 1143 .unwrap(), 1144 ) 1145 .await 1146 .unwrap(); 1147 assert_eq!(response.status(), StatusCode::OK); 1148 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 1149 .await 1150 .unwrap(); 1151 let body: Value = serde_json::from_slice(&bytes).unwrap(); 1152 assert_eq!(body["completed"], false); 1153 assert!(body["final_response"] 1154 .as_str() 1155 .unwrap() 1156 .contains("maximum turn limit (0)")); 1157 assert_eq!(body["status"], "incomplete"); 1158 } 1159 1160 #[tokio::test] 1161 async fn completion_truth_ws_turn_exhaustion_is_incomplete() { 1162 let app = create_router(create_test_state().await); 1163 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 1164 let addr = listener.local_addr().unwrap(); 1165 let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); 1166 let (mut ws, _) = 1167 tokio_tungstenite::connect_async(authed_ws_request(&format!("ws://{addr}/ws"))) 1168 .await 1169 .unwrap(); 1170 ws.send(tokio_tungstenite::tungstenite::Message::Text( 1171 r#"{"type":"agent_run","prompt":"no turn budget","max_turns":0}"#.into(), 1172 )) 1173 .await 1174 .unwrap(); 1175 let body: Value = loop { 1176 let message = tokio::time::timeout(std::time::Duration::from_secs(5), ws.next()) 1177 .await 1178 .unwrap() 1179 .unwrap() 1180 .unwrap(); 1181 if let Ok(text) = message.to_text() { 1182 let body: Value = serde_json::from_str(text).unwrap(); 1183 if body["type"] == "agent_result" { 1184 break body; 1185 } 1186 } 1187 }; 1188 ws.close(None).await.unwrap(); 1189 server.abort(); 1190 assert_eq!(body["result"]["completed"], false); 1191 assert!(body["result"]["final_response"] 1192 .as_str() 1193 .unwrap() 1194 .contains("maximum turn limit (0)")); 1195 assert_eq!(body["status"], "incomplete"); 1196 } 1197 1198 async fn assert_heartbeat_completion_truth( 1199 task_type: &str, 1200 payload: &str, 1201 reject_crumb: bool, 1202 successful: bool, 1203 expected_result: &str, 1204 ) { 1205 let dir = tempfile::tempdir().unwrap(); 1206 let path = dir.path().join("aegis.sqlite"); 1207 let db = Arc::new(Database::open(&path).unwrap()); 1208 let observer = rusqlite::Connection::open(&path).unwrap(); 1209 if reject_crumb { 1210 observer 1211 .execute_batch( 1212 "CREATE TRIGGER reject_heartbeat_crumb BEFORE INSERT ON memory_crumbs 1213 BEGIN SELECT RAISE(FAIL, 'injected crumb write failure'); END;", 1214 ) 1215 .unwrap(); 1216 } 1217 db.create_task("completion-truth", task_type, payload) 1218 .unwrap(); 1219 let mut health_server = None; 1220 let engine = if task_type == "model_health" { 1221 let app = axum::Router::new().route( 1222 "/v1/models", 1223 axum::routing::get(|| async { StatusCode::SERVICE_UNAVAILABLE }), 1224 ); 1225 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 1226 let addr = listener.local_addr().unwrap(); 1227 health_server = Some(tokio::spawn(async move { 1228 axum::serve(listener, app).await.unwrap() 1229 })); 1230 HeartbeatEngine::with_inference( 1231 60, 1232 db, 1233 Arc::new(HttpInferenceBackend::new( 1234 Some(format!("http://{addr}/v1/chat/completions")), 1235 None, 1236 )), 1237 ) 1238 } else if task_type == "shell_exec" && !successful { 1239 // `git status` is admitted, but fails in a workspace with no repository. 1240 HeartbeatEngine::with_workspace( 1241 60, 1242 db, 1243 aegis::WorkspaceCapability::new(dir.path()).unwrap(), 1244 ) 1245 } else { 1246 HeartbeatEngine::new(60, db) 1247 }; 1248 let receipt = engine.pulse_once().await; 1249 if let Some(server) = health_server { 1250 server.abort(); 1251 } 1252 assert_eq!(receipt.actions_dispatched, 1); 1253 let (status, result): (String, String) = observer 1254 .query_row( 1255 "SELECT status, result FROM tasks WHERE id = 'completion-truth'", 1256 [], 1257 |row| Ok((row.get(0)?, row.get(1)?)), 1258 ) 1259 .unwrap(); 1260 assert!(result.contains(expected_result), "{result}"); 1261 assert_eq!(status, if successful { "completed" } else { "failed" }); 1262 assert_eq!( 1263 receipt.status, 1264 if successful { "nominal" } else { "degraded" } 1265 ); 1266 let stored_status: String = observer 1267 .query_row( 1268 "SELECT status FROM heartbeats WHERE tick_id = 1", 1269 [], 1270 |row| row.get(0), 1271 ) 1272 .unwrap(); 1273 assert_eq!(stored_status, receipt.status); 1274 let transcript = std::fs::read_to_string(dir.path().join("transcript.jsonl")).unwrap(); 1275 let events: Vec = transcript 1276 .lines() 1277 .map(|line| serde_json::from_str(line).unwrap()) 1278 .collect(); 1279 assert!(events.iter().any(|event| event["event_type"] 1280 == if successful { 1281 "task_completed" 1282 } else { 1283 "task_failed" 1284 })); 1285 assert!(!events.iter().any(|event| event["event_type"] 1286 == if successful { 1287 "task_failed" 1288 } else { 1289 "task_completed" 1290 })); 1291 if reject_crumb { 1292 assert!(!result.contains("Memory crumbs recorded")); 1293 assert!(engine.pulse_once().await.status == "nominal"); 1294 } 1295 } 1296 1297 #[tokio::test] 1298 async fn completion_truth_heartbeat_shell_failure() { 1299 assert_heartbeat_completion_truth( 1300 "shell_exec", 1301 PROBE_ADMITTED_COMMAND, 1302 false, 1303 false, 1304 "Execution failure", 1305 ) 1306 .await; 1307 } 1308 1309 #[tokio::test] 1310 async fn completion_truth_heartbeat_crumb_failure() { 1311 assert_heartbeat_completion_truth( 1312 "consolidate_memory", 1313 "", 1314 true, 1315 false, 1316 "injected crumb write failure", 1317 ) 1318 .await; 1319 } 1320 1321 #[tokio::test] 1322 async fn completion_truth_heartbeat_unknown_task_failure() { 1323 assert_heartbeat_completion_truth("not-a-task", "", false, false, "Unknown task type").await; 1324 } 1325 1326 #[tokio::test] 1327 async fn completion_truth_heartbeat_success() { 1328 assert_heartbeat_completion_truth( 1329 "consolidate_memory", 1330 "", 1331 false, 1332 true, 1333 "Memory crumbs recorded", 1334 ) 1335 .await; 1336 } 1337 1338 #[tokio::test] 1339 async fn completion_truth_heartbeat_unhealthy_model_failure() { 1340 assert_heartbeat_completion_truth("model_health", "", false, false, "unreachable or offline") 1341 .await; 1342 } 1343 1344 #[tokio::test] 1345 async fn completion_truth_heartbeat_shell_success() { 1346 assert_heartbeat_completion_truth( 1347 "shell_exec", 1348 PROBE_ADMITTED_COMMAND, 1349 false, 1350 true, 1351 "Exit code 0", 1352 ) 1353 .await; 1354 } 1355 1356 #[tokio::test] 1357 async fn completion_truth_http_executed_turn_budget_exhaustion() { 1358 // A real inference turn produces a successful tool call, but never terminal output. 1359 let app = axum::Router::new().route( 1360 "/v1/chat/completions", 1361 axum::routing::post(|| async { 1362 axum::Json(serde_json::json!({ 1363 "choices": [{ 1364 "message": { 1365 "content": null, 1366 "tool_calls": [{ 1367 "id": "inspect-once", 1368 "type": "function", 1369 "function": { 1370 "name": "bash_eval", 1371 "arguments": "{\"command\":\"git status\"}" 1372 } 1373 }] 1374 }, 1375 "finish_reason": "tool_calls" 1376 }] 1377 })) 1378 }), 1379 ); 1380 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 1381 let addr = listener.local_addr().unwrap(); 1382 let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); 1383 let mut state = create_test_state().await; 1384 state.inference = Arc::new(HttpInferenceBackend::new( 1385 Some(format!("http://{addr}/v1/chat/completions")), 1386 None, 1387 )); 1388 state.agent = Arc::new(AgentEngine::new( 1389 state.inference.clone(), 1390 state.skills.clone(), 1391 Some(state.db.clone()), 1392 )); 1393 let response = create_router(state) 1394 .oneshot( 1395 Request::builder() 1396 .method("POST") 1397 .uri("/api/v1/agent/run") 1398 .header("Authorization", auth_header()) 1399 .header("Content-Type", "application/json") 1400 .body(Body::from(r#"{"prompt":"keep using tools","max_turns":1}"#)) 1401 .unwrap(), 1402 ) 1403 .await 1404 .unwrap(); 1405 server.abort(); 1406 assert_eq!(response.status(), StatusCode::OK); 1407 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 1408 .await 1409 .unwrap(); 1410 let body: Value = serde_json::from_slice(&bytes).unwrap(); 1411 assert_eq!(body["turns_taken"], 1); 1412 assert_eq!(body["steps"][0]["tool_calls"][0]["success"], true); 1413 assert_eq!(body["completed"], false); 1414 assert!(body["final_response"] 1415 .as_str() 1416 .unwrap() 1417 .contains("maximum turn limit (1)")); 1418 assert_eq!(body["status"], "incomplete"); 1419 }