interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aegis-runtime-mv / src / agent.rs

592 lines · 22919 bytes Raw Blame History
1use serde::{Deserialize, Serialize};
2use serde_json::json;
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5use tracing::info;
6
7use crate::events::{AegisEvent, EventBus, EventEnvelope};
8use crate::failure::{
9 redact_payload_echoes, retry_loop, skill_effect_profile, CancelToken, EffectCertainty,
10 FailureClass, FailureRecord, RetryPolicy, ToolDispatcher, ToolFault,
11};
12use crate::inference::InferenceEngine;
13use crate::persistence::Database;
14use crate::sessions::id::RunId;
15use crate::skills::SkillRegistry;
16
17pub const DEFAULT_MAX_CONTEXT_TOKENS: usize = 8192;
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct ToolExecutionRecord {
21 pub call_id: String,
22 pub tool_name: String,
23 pub arguments: serde_json::Value,
24 pub output: String,
25 pub success: bool,
26 /// Terminal failure provenance. Absent on success and in older records.
27 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub failure: Option<FailureRecord>,
29 /// Earlier failed attempts of this same call, oldest first.
30 #[serde(default, skip_serializing_if = "Vec::is_empty")]
31 pub retry_failures: Vec<FailureRecord>,
32}
33
34/// Failure handling knobs. Defaults keep the old behaviour: one attempt,
35/// no deadline.
36#[derive(Debug, Clone, Copy, Default)]
37pub struct FailurePolicy {
38 pub retry: RetryPolicy,
39 pub tool_timeout: Option<Duration>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct AgentStep {
44 pub step_index: usize,
45 pub thought: Option<String>,
46 pub tool_calls: Vec<ToolExecutionRecord>,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct AgentExecutionResult {
51 pub final_response: String,
52 pub steps: Vec<AgentStep>,
53 pub turns_taken: usize,
54 pub duration_ms: u128,
55 pub completed: bool,
56}
57
58/// Terminal failures exclude recovered attempts (`retry_failures` on a successful call).
59/// Shared by the producer and workflow adapter so transport success cannot mask tool failure.
60pub fn terminal_tool_failure(steps: &[AgentStep]) -> Option<ToolFault> {
61 let calls = || steps.iter().flat_map(|step| step.tool_calls.iter());
62 if let Some(failure) = calls().filter_map(|call| call.failure.as_ref()).next_back() {
63 return Some(ToolFault::new(
64 failure.class,
65 failure.effect_certainty,
66 failure
67 .cause
68 .first()
69 .map(|cause| cause.message.as_str())
70 .unwrap_or("agent tool call failed"),
71 ));
72 }
73 calls().any(|call| !call.success).then(|| {
74 ToolFault::new(
75 FailureClass::Failed,
76 EffectCertainty::Uncertain,
77 "agent tool call failed without a failure record",
78 )
79 })
80}
81
82#[derive(Clone)]
83pub struct AgentEngine {
84 inference: Arc<dyn InferenceEngine>,
85 skills: Arc<SkillRegistry>,
86 db: Option<Arc<Database>>,
87 dispatcher: Arc<dyn ToolDispatcher>,
88 policy: FailurePolicy,
89 cancel: CancelToken,
90 events: Option<(EventBus, Option<String>)>,
91 run_id: Option<String>,
92}
93
94impl AgentEngine {
95 pub fn new(
96 inference: Arc<dyn InferenceEngine>,
97 skills: Arc<SkillRegistry>,
98 db: Option<Arc<Database>>,
99 ) -> Self {
100 Self {
101 inference,
102 dispatcher: skills.clone(),
103 skills,
104 db,
105 policy: FailurePolicy::default(),
106 cancel: CancelToken::new(),
107 events: None,
108 run_id: None,
109 }
110 }
111
112 /// Replaces the tool dispatch seam (default: the skill registry's gated path).
113 pub fn with_dispatcher(mut self, dispatcher: Arc<dyn ToolDispatcher>) -> Self {
114 self.dispatcher = dispatcher;
115 self
116 }
117
118 pub fn with_failure_policy(mut self, policy: FailurePolicy) -> Self {
119 self.policy = policy;
120 self
121 }
122
123 pub fn with_cancel_token(mut self, cancel: CancelToken) -> Self {
124 self.cancel = cancel;
125 self
126 }
127
128 /// Publishes `AegisEvent::StepFailed` on this bus for every failed attempt.
129 pub fn with_event_bus(mut self, bus: EventBus, session_id: Option<String>) -> Self {
130 self.events = Some((bus, session_id));
131 self
132 }
133
134 /// Fixes the run id stamped on failure records (default: a fresh id per task).
135 pub fn with_run_id(mut self, run_id: impl Into<String>) -> Self {
136 self.run_id = Some(run_id.into());
137 self
138 }
139
140 /// One fresh gated dispatch with cancellation and deadline applied.
141 /// A cancel or timeout of a non-idempotent call leaves the effect Uncertain.
142 async fn attempt_tool(
143 &self,
144 name: &str,
145 args: &serde_json::Value,
146 idempotent: bool,
147 ) -> Result<String, ToolFault> {
148 let unknown = if idempotent {
149 EffectCertainty::NoEffect
150 } else {
151 EffectCertainty::Uncertain
152 };
153 if self.cancel.is_cancelled() {
154 return Err(ToolFault::new(
155 FailureClass::Cancelled,
156 EffectCertainty::NoEffect,
157 "cancelled before dispatch",
158 ));
159 }
160 let guarded = async {
161 tokio::select! {
162 r = self.dispatcher.dispatch(name, args) => r,
163 _ = self.cancel.cancelled() => Err(ToolFault::new(
164 FailureClass::Cancelled,
165 unknown,
166 "cancelled while running",
167 )),
168 }
169 };
170 match self.policy.tool_timeout {
171 Some(d) => match tokio::time::timeout(d, guarded).await {
172 Ok(r) => r,
173 Err(_) => Err(ToolFault::new(
174 FailureClass::Timeout,
175 unknown,
176 format!("deadline of {} ms exceeded", d.as_millis()),
177 )),
178 },
179 None => guarded.await,
180 }
181 }
182
183 pub fn skills(&self) -> Arc<SkillRegistry> {
184 self.skills.clone()
185 }
186
187 pub fn estimate_tokens(messages: &[serde_json::Value]) -> usize {
188 let mut count = 0;
189 for m in messages {
190 if let Some(content) = m.get("content").and_then(|c| c.as_str()) {
191 count += (content.split_whitespace().count() * 4) / 3 + 4;
192 }
193 if let Some(calls) = m.get("tool_calls").and_then(|c| c.as_array()) {
194 for call in calls {
195 if let Ok(serialized) = serde_json::to_string(call) {
196 count += (serialized.split_whitespace().count() * 4) / 3 + 4;
197 }
198 }
199 }
200 }
201 count
202 }
203
204 pub fn prune_context_window(
205 messages: &mut Vec<serde_json::Value>,
206 token_budget: usize,
207 ) -> bool {
208 if messages.len() <= 2 {
209 return false;
210 }
211 let mut pruned = false;
212 while messages.len() > 2 && Self::estimate_tokens(messages) > token_budget {
213 // Retain system prompt (index 0) and initial user goal (index 1), prune oldest historical turn
214 messages.remove(2);
215 pruned = true;
216 }
217 pruned
218 }
219
220 pub async fn execute_task(
221 &self,
222 goal: &str,
223 system_override: Option<&str>,
224 max_turns: usize,
225 ) -> Result<AgentExecutionResult, Box<dyn std::error::Error + Send + Sync>> {
226 let start = Instant::now();
227 let tools = self.skills.to_openai_tools();
228
229 let home_dir = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
230 let user = std::env::var("USER").unwrap_or_else(|_| "sovereign".to_string());
231 let default_system = format!(
232 "You are AIEN, a sovereign native AI systems agent running on NVIDIA DGX Spark (Grace Blackwell GB10) as user {user}. Active workspaces reside strictly in {home}/workspace/ (aegis-runtime, aien-harness-publish, etc.) and {home}/atlas-prime-workspace/. Default working directory is {home}/workspace. You have native tools available to run a catalogued local command (bash_eval: git status, git diff, git log -1 --oneline, or ls), inspect files (read_file, list_dir, git_status), and modify files (write_file). Memory search is not connected. Do not claim that it is. 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.",
233 user = user,
234 home = home_dir
235 );
236
237 let sys_prompt = system_override.unwrap_or(&default_system);
238
239 let mut messages: Vec<serde_json::Value> = vec![
240 json!({
241 "role": "system",
242 "content": sys_prompt
243 }),
244 json!({
245 "role": "user",
246 "content": goal
247 }),
248 ];
249
250 let mut steps: Vec<AgentStep> = Vec::new();
251 let mut final_response = String::new();
252 let mut turns_taken = 0;
253 let mut completed = false;
254 let run_id = self
255 .run_id
256 .clone()
257 .unwrap_or_else(|| RunId::new().as_str().to_string());
258 let mut failure_seq: u64 = 0;
259 let mut last_failed_call: Option<String> = None;
260 let mut halted: Option<String> = None;
261
262 for turn in 1..=max_turns {
263 turns_taken = turn;
264 info!("Agent loop turn {}/{}", turn, max_turns);
265
266 // Context window management: trim to budget before sending to model
267 Self::prune_context_window(&mut messages, DEFAULT_MAX_CONTEXT_TOKENS);
268
269 let turn_res = self
270 .inference
271 .generate_chat_with_tools(&messages, Some(&tools), Some(0.2), Some(2048))
272 .await?;
273
274 let thought = turn_res.reasoning.clone();
275 if turn_res.finish_reason.as_deref() == Some("length") {
276 final_response = turn_res
277 .content
278 .filter(|content| !content.trim().is_empty())
279 .unwrap_or_else(|| "Inference truncated before terminal output.".to_string());
280 steps.push(AgentStep {
281 step_index: turn,
282 thought,
283 tool_calls: Vec::new(),
284 });
285 break;
286 }
287 let has_tool_calls = turn_res
288 .tool_calls
289 .as_ref()
290 .map(|calls| !calls.is_empty())
291 .unwrap_or(false);
292
293 if has_tool_calls {
294 let tool_calls = turn_res.tool_calls.unwrap();
295 let mut tool_exec_records = Vec::new();
296
297 let tc_json: Vec<serde_json::Value> = tool_calls
298 .iter()
299 .map(|tc| {
300 json!({
301 "id": tc.id,
302 "type": "function",
303 "function": {
304 "name": tc.function.name,
305 "arguments": tc.function.arguments
306 }
307 })
308 })
309 .collect();
310
311 messages.push(json!({
312 "role": "assistant",
313 "content": turn_res.content.clone().unwrap_or_default(),
314 "tool_calls": tc_json
315 }));
316
317 for tc in tool_calls {
318 info!("Executing tool: {} (call_id: {})", tc.function.name, tc.id);
319 let args: serde_json::Value = serde_json::from_str(&tc.function.arguments)
320 .unwrap_or_else(|_| json!({"raw": tc.function.arguments}));
321
322 // Every attempt is a new gated dispatch (allowlist and probe
323 // gate run again). Retry happens only for idempotent calls
324 // that were refused or unreachable with no effect.
325 let idempotent = skill_effect_profile(&tc.function.name).idempotent;
326 let (result, failed_attempts) =
327 retry_loop(&self.policy.retry, idempotent, |_| {
328 self.attempt_tool(&tc.function.name, &args, idempotent)
329 })
330 .await;
331
332 let mut failure_records: Vec<FailureRecord> = Vec::new();
333 for a in &failed_attempts {
334 failure_seq += 1;
335 let mut rec = FailureRecord::new(
336 failure_seq,
337 run_id.clone(),
338 turn,
339 tc.id.clone(),
340 last_failed_call.clone(),
341 tc.function.name.clone(),
342 a.attempt,
343 a.fault.class,
344 a.fault.certainty,
345 a.created_at,
346 a.failed_at,
347 );
348 let msg = redact_payload_echoes(&a.fault.message, &args);
349 rec.push_cause("tool_dispatch", &msg, Some(&args));
350 if let Some((bus, session_id)) = &self.events {
351 let _ = bus.publish(EventEnvelope::new(
352 AegisEvent::StepFailed {
353 failure: rec.clone(),
354 },
355 session_id.clone(),
356 Some(run_id.clone()),
357 failure_seq,
358 ));
359 }
360 failure_records.push(rec);
361 }
362
363 let (output_str, success) = match &result {
364 Ok(out) => (out.clone(), true),
365 Err(fault) => (redact_payload_echoes(&fault.message, &args), false),
366 };
367 let failure = if success { None } else { failure_records.pop() };
368
369 if let Err(fault) = &result {
370 last_failed_call = Some(tc.id.clone());
371 match fault.class {
372 FailureClass::ApprovalPending => {
373 halted = Some(format!(
374 "Halted: tool call {} is waiting for approval and will not be replayed automatically.",
375 tc.id
376 ));
377 }
378 FailureClass::Cancelled => {
379 halted = Some(format!("Run cancelled during tool call {}.", tc.id));
380 }
381 _ => {}
382 }
383 } else {
384 last_failed_call = None;
385 }
386
387 tool_exec_records.push(ToolExecutionRecord {
388 call_id: tc.id.clone(),
389 tool_name: tc.function.name.clone(),
390 arguments: args,
391 output: output_str.clone(),
392 success,
393 failure,
394 retry_failures: failure_records,
395 });
396
397 messages.push(json!({
398 "role": "tool",
399 "tool_call_id": tc.id,
400 "content": output_str
401 }));
402
403 if halted.is_some() {
404 break;
405 }
406 }
407
408 steps.push(AgentStep {
409 step_index: turn,
410 thought,
411 tool_calls: tool_exec_records,
412 });
413 if let Some(reason) = halted.take() {
414 final_response = reason;
415 break;
416 }
417 } else {
418 let content = turn_res.content.unwrap_or_default();
419 let terminal_text =
420 !content.trim().is_empty() && turn_res.finish_reason.as_deref() == Some("stop");
421 final_response = if content.trim().is_empty() {
422 "Inference ended without terminal text.".to_string()
423 } else {
424 content
425 };
426
427 steps.push(AgentStep {
428 step_index: turn,
429 thought,
430 tool_calls: Vec::new(),
431 });
432
433 completed = terminal_text && terminal_tool_failure(&steps).is_none();
434 break;
435 }
436 }
437
438 if !completed && final_response.is_empty() {
439 final_response = format!(
440 "Agent reached maximum turn limit ({}) before producing terminal output.",
441 max_turns
442 );
443 }
444
445 let duration = start.elapsed().as_millis();
446
447 if let Some(ref db) = self.db {
448 let _ = db.record_turn("agent_autonomous", goal, &final_response, duration as u64);
449 }
450
451 Ok(AgentExecutionResult {
452 final_response,
453 steps,
454 turns_taken,
455 duration_ms: duration,
456 completed,
457 })
458 }
459}
460
461#[cfg(test)]
462mod tests {
463 use super::*;
464 use crate::skills::SkillExecutionRequest;
465 use crate::HttpInferenceBackend;
466
467 #[tokio::test]
468 async fn test_agent_engine_creation_and_skills() {
469 let inference = Arc::new(HttpInferenceBackend::new(None, None));
470 let skills = Arc::new(SkillRegistry::new());
471 let agent = AgentEngine::new(inference, skills.clone(), None);
472
473 let registered = agent.skills().list_skills();
474 assert!(!registered.is_empty());
475 }
476
477 #[test]
478 fn test_agent_token_estimation_and_boundary_pruning() {
479 let mut messages = vec![
480 json!({"role": "system", "content": "You are AEGIS."}),
481 json!({"role": "user", "content": "Initial user task."}),
482 json!({"role": "assistant", "content": "Executing intermediate action step 1."}),
483 json!({"role": "tool", "content": "Output of intermediate step 1 with lots of verbose debugging details here."}),
484 json!({"role": "assistant", "content": "Executing intermediate action step 2."}),
485 json!({"role": "tool", "content": "Output of intermediate step 2."}),
486 ];
487
488 let initial_tokens = AgentEngine::estimate_tokens(&messages);
489 assert!(initial_tokens > 20);
490
491 // Pruning with huge budget should not change messages
492 let pruned_none = AgentEngine::prune_context_window(&mut messages, 10000);
493 assert!(!pruned_none);
494 assert_eq!(messages.len(), 6);
495
496 // Pruning with tiny budget should remove intermediate turns down to index 0 and 1
497 let pruned = AgentEngine::prune_context_window(&mut messages, 10);
498 assert!(pruned);
499 assert_eq!(messages.len(), 2);
500 assert_eq!(messages[0]["role"], "system");
501 assert_eq!(messages[1]["role"], "user");
502
503 // Boundary: calling prune when only 2 messages remain should return false
504 let pruned_again = AgentEngine::prune_context_window(&mut messages, 0);
505 assert!(!pruned_again);
506 assert_eq!(messages.len(), 2);
507 }
508
509 #[tokio::test]
510 async fn test_agent_tool_error_handling_and_recovery() {
511 let inference = Arc::new(HttpInferenceBackend::new(
512 Some("http://127.0.0.1:9999/v1/chat/completions".to_string()),
513 None,
514 ));
515 let skills = Arc::new(SkillRegistry::new());
516 let agent = AgentEngine::new(inference, skills.clone(), None);
517
518 // Unknown tool: the allowlist membrane (pre_dispatch_check) refuses it
519 // before the registry lookup, so the refusal names the allowlist.
520 let unknown_req = SkillExecutionRequest {
521 skill_name: "nonexistent_custom_skill".to_string(),
522 arguments: json!({}),
523 };
524 let res = skills.execute(&unknown_req);
525 assert!(!res.success);
526 assert!(res.error.unwrap().contains("not on the dispatch allowlist"));
527
528 // Test tool parameter validation (e.g. read_file with empty path)
529 let empty_path_req = SkillExecutionRequest {
530 skill_name: "read_file".to_string(),
531 arguments: json!({"path": ""}),
532 };
533 let empty_res = skills.execute(&empty_path_req);
534 assert!(!empty_res.success);
535 assert_eq!(empty_res.error.unwrap(), "Path cannot be empty");
536
537 // Test autonomous agent task execution fail-closed offline error handling
538 let exec_res = agent
539 .execute_task("Run status check on local machine", None, 1)
540 .await;
541 assert!(exec_res.is_err());
542 let err = exec_res.unwrap_err();
543 assert!(err.to_string().contains("Inference endpoint unreachable"));
544 }
545
546 #[tokio::test]
547 async fn test_agent_multiturn_conversational_history() {
548 let app = axum::Router::new().route(
549 "/v1/chat/completions",
550 axum::routing::post(|axum::Json(_body): axum::Json<serde_json::Value>| async {
551 axum::Json(serde_json::json!({
552 "id": "chatcmpl-mock",
553 "object": "chat.completion",
554 "created": 1234567890,
555 "model": "atlas-lightning-omni",
556 "choices": [{
557 "index": 0,
558 "message": {
559 "role": "assistant",
560 "content": "Sovereign task completed."
561 },
562 "finish_reason": "stop"
563 }]
564 }))
565 }),
566 );
567 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
568 let port = listener.local_addr().unwrap().port();
569 tokio::spawn(async move {
570 let _ = axum::serve(listener, app).await;
571 });
572
573 let inference = Arc::new(HttpInferenceBackend::new(
574 Some(format!("http://127.0.0.1:{}/v1/chat/completions", port)),
575 None,
576 ));
577 let skills = Arc::new(SkillRegistry::new());
578 let agent = AgentEngine::new(inference, skills.clone(), None);
579
580 let custom_system = "You are AEGIS sovereign unit test runner.";
581 let result = agent
582 .execute_task("Perform sequential tasks", Some(custom_system), 2)
583 .await
584 .unwrap();
585
586 let _duration = result.duration_ms;
587 assert!(result.turns_taken >= 1);
588 assert_eq!(result.steps.len(), 1);
589 assert!(result.completed);
590 assert_eq!(result.final_response, "Sovereign task completed.");
591 }
592}