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 / main.rs

430 lines · 16704 bytes Raw Blame History
1use aegis::{
2 start_gateway, AgentEngine, Database, EmbeddedInferenceBackend, GatewayState, HeartbeatEngine,
3 HttpInferenceBackend, InferenceEngine, SkillRegistry, VectorMath,
4};
5use clap::{Parser, Subcommand};
6use std::path::Path;
7use std::sync::Arc;
8use std::time::Instant;
9use tracing::{info, Level};
10use tracing_subscriber::FmtSubscriber;
11
12#[derive(Parser)]
13#[command(name = "aegis")]
14#[command(version = "0.2.0")]
15#[command(about = "Sovereign Agent Runtime on Grace Blackwell GB10", long_about = None)]
16struct Cli {
17 #[command(subcommand)]
18 command: Option<Commands>,
19}
20
21#[derive(Subcommand)]
22enum Commands {
23 /// Start the Axum WebSocket, SSE, and HTTP gateway with autonomous heartbeat
24 Serve {
25 #[arg(short, long, default_value = "18096")]
26 port: u16,
27 /// Listen address. Loopback by default; anything else needs --allow-non-loopback-bind.
28 #[arg(long, default_value = "127.0.0.1")]
29 bind: String,
30 /// Explicit opt-in to listen on a non-loopback address.
31 #[arg(long, default_value_t = false)]
32 allow_non_loopback_bind: bool,
33 /// File holding the operator token (else AEGIS_OPERATOR_TOKEN).
34 #[arg(long)]
35 operator_token_file: Option<String>,
36 #[arg(long, default_value = "embedded")]
37 inference: String,
38 #[arg(long, default_value = "http://127.0.0.1:18006/v1/chat/completions")]
39 /// OpenAI-compatible chat endpoint used with `--inference http` (the local model seat on port 18006 by default).
40 model_url: String,
41 #[arg(long)]
42 model_path: Option<String>,
43 #[arg(long)]
44 tokenizer_path: Option<String>,
45 #[arg(long, default_value = "aegis.sqlite")]
46 db_path: String,
47 #[arg(long, default_value = "60")]
48 heartbeat_secs: u64,
49 },
50 /// Fail unknown legacy running tasks without executing them. Stop every database writer first.
51 MigrateLegacyTasks {
52 #[arg(long, default_value = "aegis.sqlite")]
53 db_path: String,
54 /// Acknowledge all task writers, including old binaries, are stopped.
55 #[arg(long)]
56 quiescent: bool,
57 },
58 /// Run a single heartbeat tick immediately
59 Tick {
60 #[arg(long, default_value = "aegis.sqlite")]
61 db_path: String,
62 },
63 /// Run persistent background heartbeat daemon loop
64 Heartbeat {
65 #[arg(long, default_value = "embedded")]
66 inference: String,
67 #[arg(long, default_value = "http://127.0.0.1:18006/v1/chat/completions")]
68 /// OpenAI-compatible chat endpoint used with `--inference http` (the local model seat on port 18006 by default).
69 model_url: String,
70 #[arg(long)]
71 model_path: Option<String>,
72 #[arg(long)]
73 tokenizer_path: Option<String>,
74 #[arg(long, default_value = "aegis.sqlite")]
75 db_path: String,
76 #[arg(long, default_value = "30")]
77 heartbeat_secs: u64,
78 },
79 /// Send a direct prompt to the inference engine
80 Ask {
81 prompt: String,
82 #[arg(long, default_value = "embedded")]
83 inference: String,
84 #[arg(long, default_value = "http://127.0.0.1:18006/v1/chat/completions")]
85 /// OpenAI-compatible chat endpoint used with `--inference http` (the local model seat on port 18006 by default).
86 model_url: String,
87 #[arg(long)]
88 model_path: Option<String>,
89 #[arg(long)]
90 tokenizer_path: Option<String>,
91 },
92 /// Execute an autonomous agent task with multi-turn tool calling
93 Agent {
94 prompt: String,
95 #[arg(long, default_value = "embedded")]
96 inference: String,
97 #[arg(long, default_value = "http://127.0.0.1:18006/v1/chat/completions")]
98 /// OpenAI-compatible chat endpoint used with `--inference http` (the local model seat on port 18006 by default).
99 model_url: String,
100 #[arg(long)]
101 model_path: Option<String>,
102 #[arg(long)]
103 tokenizer_path: Option<String>,
104 #[arg(long, default_value = "aegis.sqlite")]
105 db_path: String,
106 #[arg(long, default_value = "8")]
107 max_turns: usize,
108 },
109 /// Evaluate the built-in vector math operations
110 Simd {
111 #[arg(long, default_value = "10")]
112 steps: i32,
113 },
114 /// Display runtime status and system health
115 Status {
116 #[arg(long, default_value = "embedded")]
117 inference: String,
118 #[arg(long, default_value = "http://127.0.0.1:18006/v1/chat/completions")]
119 /// OpenAI-compatible chat endpoint used with `--inference http` (the local model seat on port 18006 by default).
120 model_url: String,
121 #[arg(long)]
122 model_path: Option<String>,
123 #[arg(long)]
124 tokenizer_path: Option<String>,
125 #[arg(long, default_value = "aegis.sqlite")]
126 db_path: String,
127 },
128}
129
130fn resolve_inference_engine(
131 mode: &str,
132 model_url: &str,
133 model_path: Option<&str>,
134 tokenizer_path: Option<&str>,
135) -> Result<Arc<dyn InferenceEngine>, Box<dyn std::error::Error>> {
136 if mode == "http" {
137 info!(
138 "Binding AEGIS to external HTTP inference daemon at {}",
139 model_url
140 );
141 Ok(Arc::new(HttpInferenceBackend::new(
142 Some(model_url.to_string()),
143 None,
144 )))
145 } else {
146 info!("Binding AEGIS to in-process EmbeddedInferenceBackend (NativeTransformerBackend)...");
147 let backend = EmbeddedInferenceBackend::load_or_fallback(model_path, tokenizer_path)
148 .map_err(|e| anyhow::anyhow!(e))?;
149 info!(
150 "In-process embedded inference backend active: {}",
151 backend.model_id()
152 );
153 Ok(Arc::new(backend))
154 }
155}
156
157/// One-time migration for the openclaw-rs -> aegis-runtime rename.
158/// The database default was `openclaw.sqlite`; it is now `aegis.sqlite`.
159/// If the new file does not exist but the legacy one does, copy it forward
160/// so existing installations keep their data. Explicit `--db-path` values
161/// are always respected literally and never migrated.
162fn migrate_legacy_db_if_needed() {
163 let new_path = std::path::Path::new("aegis.sqlite");
164 let legacy_path = std::path::Path::new("openclaw.sqlite");
165 if !new_path.exists() && legacy_path.exists() {
166 match std::fs::copy(legacy_path, new_path) {
167 Ok(_) => eprintln!("Migrated legacy openclaw.sqlite -> aegis.sqlite"),
168 Err(e) => eprintln!("Warning: could not migrate openclaw.sqlite: {}", e),
169 }
170 }
171}
172
173#[tokio::main]
174async fn main() -> Result<(), Box<dyn std::error::Error>> {
175 let subscriber = FmtSubscriber::builder()
176 .with_max_level(Level::INFO)
177 .finish();
178 tracing::subscriber::set_global_default(subscriber).ok();
179
180 let cli = Cli::parse();
181 if !matches!(&cli.command, Some(Commands::MigrateLegacyTasks { .. })) {
182 migrate_legacy_db_if_needed();
183 }
184
185 match cli.command.unwrap_or(Commands::Serve {
186 port: 18096,
187 bind: "127.0.0.1".to_string(),
188 allow_non_loopback_bind: false,
189 operator_token_file: None,
190 inference: "embedded".to_string(),
191 model_url: "http://127.0.0.1:18006/v1/chat/completions".to_string(),
192 model_path: None,
193 tokenizer_path: None,
194 db_path: "aegis.sqlite".to_string(),
195 heartbeat_secs: 60,
196 }) {
197 Commands::Serve {
198 port,
199 bind,
200 allow_non_loopback_bind,
201 operator_token_file,
202 inference: inference_mode,
203 model_url,
204 model_path,
205 tokenizer_path,
206 db_path,
207 heartbeat_secs,
208 } => {
209 info!("Initializing AEGIS engine on Grace Blackwell GB10...");
210 // Refuse a bad listen address or a malformed token before starting anything.
211 let addr = aegis::resolve_bind_addr(&bind, port, allow_non_loopback_bind)
212 .map_err(|e| anyhow::anyhow!(e))?;
213 let operator = aegis::OperatorAuth::load(operator_token_file.as_deref().map(Path::new))
214 .map_err(|e| anyhow::anyhow!(e))?;
215 let db = Arc::new(Database::open(Path::new(&db_path))?);
216 let inference = resolve_inference_engine(
217 &inference_mode,
218 &model_url,
219 model_path.as_deref(),
220 tokenizer_path.as_deref(),
221 )?;
222 let heartbeat = Arc::new(HeartbeatEngine::with_inference(
223 heartbeat_secs,
224 db.clone(),
225 inference.clone(),
226 ));
227 let skills = Arc::new(SkillRegistry::new());
228 let agent = Arc::new(AgentEngine::new(
229 inference.clone(),
230 skills.clone(),
231 Some(db.clone()),
232 ));
233
234 heartbeat.clone().start_loop().await;
235
236 let state = GatewayState {
237 start_time: Instant::now(),
238 db: db.clone(),
239 inference: inference.clone(),
240 heartbeat: heartbeat.clone(),
241 skills: skills.clone(),
242 agent: agent.clone(),
243 operator,
244 };
245
246 info!("Starting Axum sub-millisecond gateway on {}", addr);
247 start_gateway(state, addr).await?;
248 }
249 Commands::MigrateLegacyTasks { db_path, quiescent } => {
250 let migrated = Database::migrate_legacy_running_tasks(Path::new(&db_path), quiescent)?;
251 println!(
252 "Migrated {} legacy running tasks to failed: abandoned: outcome unknown",
253 migrated
254 );
255 }
256 Commands::Tick { db_path } => {
257 info!("Executing single autonomous heartbeat tick...");
258 let db = Arc::new(Database::open(Path::new(&db_path))?);
259 let heartbeat = HeartbeatEngine::new(60, db);
260 let receipt = heartbeat.pulse_once().await;
261 info!("Heartbeat tick completed successfully: {:?}", receipt.notes);
262 }
263 Commands::Heartbeat {
264 inference: inference_mode,
265 model_url,
266 model_path,
267 tokenizer_path,
268 db_path,
269 heartbeat_secs,
270 } => {
271 info!("Initializing AEGIS persistent heartbeat daemon on Grace Blackwell GB10...");
272 let db = Arc::new(Database::open(Path::new(&db_path))?);
273 let inference = resolve_inference_engine(
274 &inference_mode,
275 &model_url,
276 model_path.as_deref(),
277 tokenizer_path.as_deref(),
278 )?;
279 let heartbeat = Arc::new(HeartbeatEngine::with_inference(
280 heartbeat_secs,
281 db.clone(),
282 inference.clone(),
283 ));
284
285 info!(
286 "Starting AEGIS persistent heartbeat daemon loop (interval: {}s)...",
287 heartbeat_secs
288 );
289 let mut interval =
290 tokio::time::interval(std::time::Duration::from_secs(heartbeat_secs));
291 loop {
292 interval.tick().await;
293 let receipt = heartbeat.pulse_once().await;
294 info!(
295 "Heartbeat pulse #{}: status={}, tasks={}, actions={}",
296 receipt.tick_id,
297 receipt.status,
298 receipt.tasks_scanned,
299 receipt.actions_dispatched
300 );
301 }
302 }
303 Commands::Ask {
304 prompt,
305 inference: inference_mode,
306 model_url,
307 model_path,
308 tokenizer_path,
309 } => {
310 let inference = resolve_inference_engine(
311 &inference_mode,
312 &model_url,
313 model_path.as_deref(),
314 tokenizer_path.as_deref(),
315 )?;
316 println!(
317 "Dispatching query to inference engine ({}): {}",
318 inference.model_id(),
319 prompt
320 );
321 match inference.generate(&prompt, None, None).await {
322 Ok(reply) => println!("\n{}", reply),
323 Err(err) => eprintln!("Inference error: {}", err),
324 }
325 }
326 Commands::Agent {
327 prompt,
328 inference: inference_mode,
329 model_url,
330 model_path,
331 tokenizer_path,
332 db_path,
333 max_turns,
334 } => {
335 println!("=== AEGIS Sovereign Agent Execution ===");
336 println!("Task Goal: {}", prompt);
337 let inference = resolve_inference_engine(
338 &inference_mode,
339 &model_url,
340 model_path.as_deref(),
341 tokenizer_path.as_deref(),
342 )?;
343 println!("Target Engine: {}", inference.model_id());
344 println!("Endpoint: {}", inference.endpoint());
345 println!("------------------------------------------------------------");
346
347 let db = Arc::new(Database::open(Path::new(&db_path))?);
348 let skills = Arc::new(SkillRegistry::new());
349 let agent = AgentEngine::new(inference, skills, Some(db));
350
351 match agent.execute_task(&prompt, None, max_turns).await {
352 Ok(result) => {
353 for step in &result.steps {
354 println!("\n[Step {}]", step.step_index);
355 if let Some(ref thought) = step.thought {
356 let first_line = thought.lines().next().unwrap_or("");
357 println!(" Thought: {}", first_line);
358 }
359 for tc in &step.tool_calls {
360 println!(" Tool Call: {}({})", tc.tool_name, tc.arguments);
361 let preview: String =
362 tc.output.lines().take(3).collect::<Vec<_>>().join("\n ");
363 println!(" Result (success={}):\n {}", tc.success, preview);
364 }
365 }
366 println!("\n=================== Terminal Output ===================");
367 println!("{}", result.final_response);
368 println!("=======================================================");
369 println!(
370 "Total Turns: {} | Duration: {}ms | Completed: {}",
371 result.turns_taken, result.duration_ms, result.completed
372 );
373 }
374 Err(err) => eprintln!("Agent execution error: {}", err),
375 }
376 }
377 Commands::Simd { steps } => {
378 println!("=== Vector Math Evaluation (pure Rust) ===");
379
380 let v1 = [1.0f32, 0.0, 0.0, 0.0];
381 let v2 = [0.9f32, 0.1, 0.0, 0.0];
382 let sim = VectorMath::cosine_similarity_4d(v1, v2);
383 println!("Cosine Similarity ([1,0,0,0] vs [0.9,0.1,0,0]): {:.6}", sim);
384
385 let acc = VectorMath::accumulate(1.0, 1.05, steps);
386 println!(
387 "Accumulate (base=1.0, scale=1.05, steps={}): {:.6}",
388 steps, acc
389 );
390
391 let entropy = VectorMath::token_entropy([0.7, 0.2, 0.08, 0.02]);
392 println!("Token Entropy (Shannon): {:.6} nats", entropy);
393
394 let proj =
395 VectorMath::token_projection([1.0, 2.0, 3.0, 4.0], [0.5, 0.5, 0.5, 0.5], 1.0);
396 println!("Token Projection: {:.6}", proj);
397 }
398 Commands::Status {
399 inference: inference_mode,
400 model_url,
401 model_path,
402 tokenizer_path,
403 db_path,
404 } => {
405 println!("=== AEGIS Sovereign Runtime Status ===");
406 println!("Architecture: Pure native Rust + In-Process NativeTransformer");
407 println!("Hardware Target: Grace Blackwell GB10 (aarch64-unknown-linux-gnu)");
408 println!("Database: SQLite WAL ({})", db_path);
409 let inference = resolve_inference_engine(
410 &inference_mode,
411 &model_url,
412 model_path.as_deref(),
413 tokenizer_path.as_deref(),
414 )?;
415 println!("Inference Backend: {}", inference.model_id());
416 println!("Inference Endpoint: {}", inference.endpoint());
417 let healthy = inference.check_health().await;
418 println!(
419 "Inference Engine Status: {}",
420 if healthy {
421 "ONLINE"
422 } else {
423 "OFFLINE (Fallback Active)"
424 }
425 );
426 }
427 }
428
429 Ok(())
430}