openclaw-rs
High-performance sovereign agent runtime in native Rust and Mojo for NVIDIA DGX Spark
Brought by drakestapleton
openclaw-rs / src / agent.rs
| 1 | use serde::{Deserialize, Serialize}; |
| 2 | use serde_json::json; |
| 3 | use std::sync::Arc; |
| 4 | use std::time::Instant; |
| 5 | use tracing::info; |
| 6 | |
| 7 | use crate::inference::InferenceEngine; |
| 8 | use crate::persistence::Database; |
| 9 | use crate::skills::{SkillExecutionRequest, SkillRegistry}; |
| 10 | |
| 11 | pub const DEFAULT_MAX_CONTEXT_TOKENS: usize = 8192; |
| 12 | |
| 13 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 14 | pub struct ToolExecutionRecord { |
| 15 | pub call_id: String, |
| 16 | pub tool_name: String, |
| 17 | pub arguments: serde_json::Value, |
| 18 | pub output: String, |
| 19 | pub success: bool, |
| 20 | } |
| 21 | |
| 22 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 23 | pub struct AgentStep { |
| 24 | pub step_index: usize, |
| 25 | pub thought: Option<String>, |
| 26 | pub tool_calls: Vec<ToolExecutionRecord>, |
| 27 | } |
| 28 | |
| 29 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 30 | pub struct AgentExecutionResult { |
| 31 | pub final_response: String, |
| 32 | pub steps: Vec<AgentStep>, |
| 33 | pub turns_taken: usize, |
| 34 | pub duration_ms: u128, |
| 35 | pub completed: bool, |
| 36 | } |
| 37 | |
| 38 | #[derive(Clone)] |
| 39 | pub struct AgentEngine { |
| 40 | inference: Arc<InferenceEngine>, |
| 41 | skills: Arc<SkillRegistry>, |
| 42 | db: Option<Arc<Database>>, |
| 43 | } |
| 44 | |
| 45 | impl AgentEngine { |
| 46 | pub fn new( |
| 47 | inference: Arc<InferenceEngine>, |
| 48 | skills: Arc<SkillRegistry>, |
| 49 | db: Option<Arc<Database>>, |
| 50 | ) -> Self { |
| 51 | Self { |
| 52 | inference, |
| 53 | skills, |
| 54 | db, |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | pub fn skills(&self) -> Arc<SkillRegistry> { |
| 59 | self.skills.clone() |
| 60 | } |
| 61 | |
| 62 | pub fn estimate_tokens(messages: &[serde_json::Value]) -> usize { |
| 63 | let mut count = 0; |
| 64 | for m in messages { |
| 65 | if let Some(content) = m.get("content").and_then(|c| c.as_str()) { |
| 66 | count += (content.split_whitespace().count() * 4) / 3 + 4; |
| 67 | } |
| 68 | if let Some(calls) = m.get("tool_calls").and_then(|c| c.as_array()) { |
| 69 | for call in calls { |
| 70 | if let Ok(serialized) = serde_json::to_string(call) { |
| 71 | count += (serialized.split_whitespace().count() * 4) / 3 + 4; |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | count |
| 77 | } |
| 78 | |
| 79 | pub fn prune_context_window(messages: &mut Vec<serde_json::Value>, token_budget: usize) -> bool { |
| 80 | if messages.len() <= 2 { |
| 81 | return false; |
| 82 | } |
| 83 | let mut pruned = false; |
| 84 | while messages.len() > 2 && Self::estimate_tokens(messages) > token_budget { |
| 85 | // Retain system prompt (index 0) and initial user goal (index 1), prune oldest historical turn |
| 86 | messages.remove(2); |
| 87 | pruned = true; |
| 88 | } |
| 89 | pruned |
| 90 | } |
| 91 | |
| 92 | pub async fn execute_task( |
| 93 | &self, |
| 94 | goal: &str, |
| 95 | system_override: Option<&str>, |
| 96 | max_turns: usize, |
| 97 | ) -> Result<AgentExecutionResult, Box<dyn std::error::Error + Send + Sync>> { |
| 98 | let start = Instant::now(); |
| 99 | let tools = self.skills.to_openai_tools(); |
| 100 | |
| 101 | let default_system = "You are AIEN, a sovereign native AI systems agent running on NVIDIA DGX Spark (Grace Blackwell GB10) as user drakestapleton. Active workspaces reside strictly in /home/drakestapleton/workspace/ (openclaw-rs, aien-harness-publish, etc.) and /home/drakestapleton/atlas-prime-workspace/. Default working directory is /home/drakestapleton/workspace. You have native tools available to execute commands (bash_eval), inspect files (read_file, list_dir, git_status), modify files (write_file), and query memory (cortex_recall). Never run broad root filesystem scans or find /. Invoke tools directly on specific workspace targets. Adhere strictly to the unslop standard: zero em dashes and zero en dashes, no transitional fluff, and direct technical proof. When finished, provide a concise final summary."; |
| 102 | |
| 103 | let sys_prompt = system_override.unwrap_or(default_system); |
| 104 | |
| 105 | let mut messages: Vec<serde_json::Value> = vec![ |
| 106 | json!({ |
| 107 | "role": "system", |
| 108 | "content": sys_prompt |
| 109 | }), |
| 110 | json!({ |
| 111 | "role": "user", |
| 112 | "content": goal |
| 113 | }), |
| 114 | ]; |
| 115 | |
| 116 | let mut steps: Vec<AgentStep> = Vec::new(); |
| 117 | let mut final_response = String::new(); |
| 118 | let mut turns_taken = 0; |
| 119 | let mut completed = false; |
| 120 | |
| 121 | for turn in 1..=max_turns { |
| 122 | turns_taken = turn; |
| 123 | info!("Agent loop turn {}/{}", turn, max_turns); |
| 124 | |
| 125 | // Context window management: trim to budget before sending to model |
| 126 | Self::prune_context_window(&mut messages, DEFAULT_MAX_CONTEXT_TOKENS); |
| 127 | |
| 128 | let turn_res = self |
| 129 | .inference |
| 130 | .generate_chat_with_tools(&messages, Some(&tools), Some(0.2), Some(2048)) |
| 131 | .await?; |
| 132 | |
| 133 | let thought = turn_res.reasoning.clone(); |
| 134 | let has_tool_calls = turn_res |
| 135 | .tool_calls |
| 136 | .as_ref() |
| 137 | .map(|calls| !calls.is_empty()) |
| 138 | .unwrap_or(false); |
| 139 | |
| 140 | if has_tool_calls { |
| 141 | let tool_calls = turn_res.tool_calls.unwrap(); |
| 142 | let mut tool_exec_records = Vec::new(); |
| 143 | |
| 144 | let tc_json: Vec<serde_json::Value> = tool_calls |
| 145 | .iter() |
| 146 | .map(|tc| { |
| 147 | json!({ |
| 148 | "id": tc.id, |
| 149 | "type": "function", |
| 150 | "function": { |
| 151 | "name": tc.function.name, |
| 152 | "arguments": tc.function.arguments |
| 153 | } |
| 154 | }) |
| 155 | }) |
| 156 | .collect(); |
| 157 | |
| 158 | messages.push(json!({ |
| 159 | "role": "assistant", |
| 160 | "content": turn_res.content.clone().unwrap_or_default(), |
| 161 | "tool_calls": tc_json |
| 162 | })); |
| 163 | |
| 164 | for tc in tool_calls { |
| 165 | info!("Executing tool: {} (call_id: {})", tc.function.name, tc.id); |
| 166 | let args: serde_json::Value = serde_json::from_str(&tc.function.arguments) |
| 167 | .unwrap_or_else(|_| json!({"raw": tc.function.arguments})); |
| 168 | |
| 169 | let req = SkillExecutionRequest { |
| 170 | skill_name: tc.function.name.clone(), |
| 171 | arguments: args.clone(), |
| 172 | }; |
| 173 | |
| 174 | let res = self.skills.execute(&req); |
| 175 | let output_str = if res.success { |
| 176 | res.output.clone() |
| 177 | } else { |
| 178 | res.error.clone().unwrap_or_else(|| "Unknown error".to_string()) |
| 179 | }; |
| 180 | |
| 181 | tool_exec_records.push(ToolExecutionRecord { |
| 182 | call_id: tc.id.clone(), |
| 183 | tool_name: tc.function.name.clone(), |
| 184 | arguments: args, |
| 185 | output: output_str.clone(), |
| 186 | success: res.success, |
| 187 | }); |
| 188 | |
| 189 | messages.push(json!({ |
| 190 | "role": "tool", |
| 191 | "tool_call_id": tc.id, |
| 192 | "content": output_str |
| 193 | })); |
| 194 | } |
| 195 | |
| 196 | steps.push(AgentStep { |
| 197 | step_index: turn, |
| 198 | thought, |
| 199 | tool_calls: tool_exec_records, |
| 200 | }); |
| 201 | } else { |
| 202 | let content = turn_res.content.unwrap_or_default(); |
| 203 | final_response = if !content.trim().is_empty() { |
| 204 | content |
| 205 | } else if let Some(r) = turn_res.reasoning { |
| 206 | r |
| 207 | } else { |
| 208 | "Task processed with zero textual output.".to_string() |
| 209 | }; |
| 210 | |
| 211 | steps.push(AgentStep { |
| 212 | step_index: turn, |
| 213 | thought, |
| 214 | tool_calls: Vec::new(), |
| 215 | }); |
| 216 | |
| 217 | completed = true; |
| 218 | break; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | if !completed && final_response.is_empty() { |
| 223 | final_response = format!( |
| 224 | "Agent reached maximum turn limit ({}) before producing terminal output.", |
| 225 | max_turns |
| 226 | ); |
| 227 | } |
| 228 | |
| 229 | let duration = start.elapsed().as_millis(); |
| 230 | |
| 231 | if let Some(ref db) = self.db { |
| 232 | let _ = db.record_turn( |
| 233 | "agent_autonomous", |
| 234 | goal, |
| 235 | &final_response, |
| 236 | duration as u64, |
| 237 | ); |
| 238 | } |
| 239 | |
| 240 | Ok(AgentExecutionResult { |
| 241 | final_response, |
| 242 | steps, |
| 243 | turns_taken, |
| 244 | duration_ms: duration, |
| 245 | completed, |
| 246 | }) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | #[cfg(test)] |
| 251 | mod tests { |
| 252 | use super::*; |
| 253 | |
| 254 | #[tokio::test] |
| 255 | async fn test_agent_engine_creation_and_skills() { |
| 256 | let inference = Arc::new(InferenceEngine::new(None, None)); |
| 257 | let skills = Arc::new(SkillRegistry::new()); |
| 258 | let agent = AgentEngine::new(inference, skills.clone(), None); |
| 259 | |
| 260 | let registered = agent.skills().list_skills(); |
| 261 | assert!(!registered.is_empty()); |
| 262 | } |
| 263 | |
| 264 | #[test] |
| 265 | fn test_agent_token_estimation_and_boundary_pruning() { |
| 266 | let mut messages = vec![ |
| 267 | json!({"role": "system", "content": "You are OpenClaw."}), |
| 268 | json!({"role": "user", "content": "Initial user task."}), |
| 269 | json!({"role": "assistant", "content": "Executing intermediate action step 1."}), |
| 270 | json!({"role": "tool", "content": "Output of intermediate step 1 with lots of verbose debugging details here."}), |
| 271 | json!({"role": "assistant", "content": "Executing intermediate action step 2."}), |
| 272 | json!({"role": "tool", "content": "Output of intermediate step 2."}), |
| 273 | ]; |
| 274 | |
| 275 | let initial_tokens = AgentEngine::estimate_tokens(&messages); |
| 276 | assert!(initial_tokens > 20); |
| 277 | |
| 278 | // Pruning with huge budget should not change messages |
| 279 | let pruned_none = AgentEngine::prune_context_window(&mut messages, 10000); |
| 280 | assert!(!pruned_none); |
| 281 | assert_eq!(messages.len(), 6); |
| 282 | |
| 283 | // Pruning with tiny budget should remove intermediate turns down to index 0 and 1 |
| 284 | let pruned = AgentEngine::prune_context_window(&mut messages, 10); |
| 285 | assert!(pruned); |
| 286 | assert_eq!(messages.len(), 2); |
| 287 | assert_eq!(messages[0]["role"], "system"); |
| 288 | assert_eq!(messages[1]["role"], "user"); |
| 289 | |
| 290 | // Boundary: calling prune when only 2 messages remain should return false |
| 291 | let pruned_again = AgentEngine::prune_context_window(&mut messages, 0); |
| 292 | assert!(!pruned_again); |
| 293 | assert_eq!(messages.len(), 2); |
| 294 | } |
| 295 | |
| 296 | #[tokio::test] |
| 297 | async fn test_agent_tool_error_handling_and_recovery() { |
| 298 | let inference = Arc::new(InferenceEngine::new( |
| 299 | Some("http://127.0.0.1:9999/v1/chat/completions".to_string()), |
| 300 | None, |
| 301 | )); |
| 302 | let skills = Arc::new(SkillRegistry::new()); |
| 303 | let agent = AgentEngine::new(inference, skills.clone(), None); |
| 304 | |
| 305 | // Test executing unknown tool directly via skills registry |
| 306 | let unknown_req = SkillExecutionRequest { |
| 307 | skill_name: "nonexistent_custom_skill".to_string(), |
| 308 | arguments: json!({}), |
| 309 | }; |
| 310 | let res = skills.execute(&unknown_req); |
| 311 | assert!(!res.success); |
| 312 | assert!(res.error.unwrap().contains("not found in registry")); |
| 313 | |
| 314 | // Test tool parameter validation (e.g. read_file with empty path) |
| 315 | let empty_path_req = SkillExecutionRequest { |
| 316 | skill_name: "read_file".to_string(), |
| 317 | arguments: json!({"path": ""}), |
| 318 | }; |
| 319 | let empty_res = skills.execute(&empty_path_req); |
| 320 | assert!(!empty_res.success); |
| 321 | assert_eq!(empty_res.error.unwrap(), "Path cannot be empty"); |
| 322 | |
| 323 | // Test autonomous agent task execution under local fallback (does not panic) |
| 324 | let exec_res = agent |
| 325 | .execute_task("Run status check on local machine", None, 1) |
| 326 | .await; |
| 327 | assert!(exec_res.is_ok()); |
| 328 | let result = exec_res.unwrap(); |
| 329 | assert!(result.completed); |
| 330 | assert_eq!(result.turns_taken, 1); |
| 331 | assert!(!result.final_response.is_empty()); |
| 332 | } |
| 333 | |
| 334 | #[tokio::test] |
| 335 | async fn test_agent_multiturn_conversational_history() { |
| 336 | let inference = Arc::new(InferenceEngine::new( |
| 337 | Some("http://127.0.0.1:9999/v1/chat/completions".to_string()), |
| 338 | None, |
| 339 | )); |
| 340 | let skills = Arc::new(SkillRegistry::new()); |
| 341 | let agent = AgentEngine::new(inference, skills.clone(), None); |
| 342 | |
| 343 | let custom_system = "You are OpenClaw sovereign unit test runner."; |
| 344 | let result = agent |
| 345 | .execute_task("Perform sequential tasks", Some(custom_system), 2) |
| 346 | .await |
| 347 | .unwrap(); |
| 348 | |
| 349 | let _duration = result.duration_ms; |
| 350 | assert!(result.turns_taken >= 1); |
| 351 | assert_eq!(result.steps.len(), 1); |
| 352 | assert!(result.completed); |
| 353 | } |
| 354 | } |