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/aien-sovereign-core-mv/blob/main/crates/aien-drive/src/lib.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. 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 `aien-sovereign-core-mv / crates / aien-drive / src / lib.rs` 418 lines ยท 16890 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! AIEN autonomous API driver (Rust port of the removed `scripts/aien_drive.py`). 17 //! 18 //! Loops a chat model at an OpenAI-style streaming endpoint with a system 19 //! prompt, extracts `` blocks from its reply, dispatches them, and 20 //! feeds the results back as `` user messages. 21 //! 22 //! `run_command` execs one allowlisted program with an argument vector. 23 //! A shell is used only when the operator sets `CommandPolicy::allow_shell`. 24 25 pub mod command; 26 pub mod http; 27 mod paths; 28 29 pub use command::CommandPolicy; 30 31 use regex::Regex; 32 use serde_json::{json, Value}; 33 use std::io::{BufRead, Write}; 34 use std::os::fd::AsRawFd; 35 use std::process::{Command, Stdio}; 36 use std::time::{Duration, Instant}; 37 38 pub const ENDPOINT_LIGHTNING: &str = "http://127.0.0.1:18006/v1/chat/completions"; 39 pub const MODEL_LIGHTNING: &str = "atlas-lightning-omni"; 40 pub const ENDPOINT_JUDGE: &str = "http://127.0.0.1:18082/v1/chat/completions"; 41 pub const MODEL_JUDGE: &str = "unsloth/Llama-3.2-1B-Instruct"; 42 pub const DEFAULT_CORTEX: &str = "http://127.0.0.1:18080"; 43 44 pub const SYSTEM_PROMPT: &str = r#"You are AIEN. Drake is the operator. This Spark desk is ours. 45 You are an autonomous operator-builder running on NVIDIA DGX Spark Grace Blackwell GB10 hardware. 46 Always be concise, precise, and lead with verified results. 47 48 Available Tools: 49 - run_command: {"command": "program and arguments", "cwd": "directory inside the command root"} 50 One allowlisted program plus arguments. No shell syntax: no pipes, semicolons, substitution, or backticks. 51 The operator sets the allowlist and the command root. A shell is an operator opt-in and is off by default. 52 - view_file: {"path": "string", "start_line": 1, "end_line": 100} 53 - write_to_file: {"path": "string", "content": "string", "overwrite": false} 54 - replace_file_content: {"path": "string", "target": "string", "replacement": "string"} 55 - create_dir: {"path": "string", "purpose": "string"} 56 - list_dir: {"path": "string"} 57 - grep_search: {"query": "string", "path": "string"} 58 - goal: {"action": "milestone_done|done", "id": "string", "milestone_id": 1} 59 - cortex: {"action": "write", "name": "string", "content": "string", "kind": "lesson|discovery|procedure"} 60 Cortex writes only when the operator configured a token. The model cannot supply that token. 61 62 MANDATORY RULES: 63 1. ZERO EM DASHES AND EN DASHES: Use plain commas, periods, or standard hyphens (-). 64 2. BAN FORMULAIC AI CLICHES: Never use 'It is not X, it is Y', 'delve', 'tapestry', 'testament', 'crucial', 'pivotal'. 65 3. LEAD WITH TECHNICAL PROOF: Output factual diffs, test outputs, and verified receipts. 66 4. TOOL EXECUTION FORMAT: 67 To execute a tool, output: 68 69 {"name": "tool_name", "arguments": {"arg": "val"}} 70 71 72 When all work for the milestone is verified, call goal with action 'milestone_done'. 73 "#; 74 75 /// Where a driver run talks to. 76 #[derive(Clone, Debug)] 77 pub struct Config { 78 pub endpoint: String, 79 pub model: String, 80 pub cortex_endpoint: String, 81 /// Cortex area the `cortex` tool writes to. 82 pub cortex_space: String, 83 pub request_timeout: Duration, 84 /// Operator policy for `run_command` and the file tools. The model cannot change this. 85 pub command: CommandPolicy, 86 /// Operator credential for the `cortex` tool. Empty means the tool does not run. 87 /// The model cannot set this. 88 pub cortex_token: Option, 89 } 90 91 pub(crate) fn last_chars(s: &str, n: usize) -> String { 92 let c: Vec = s.chars().collect(); 93 if c.len() > n { 94 c[c.len() - n..].iter().collect() 95 } else { 96 s.to_string() 97 } 98 } 99 100 fn first_chars(s: &str, n: usize) -> String { 101 s.chars().take(n).collect() 102 } 103 104 /// Pull tool calls out of model text. Only `{json}` 105 /// in the content channel counts. Bare `{name, arguments}` objects are not 106 /// executed. 107 pub fn extract_tool_calls(text: &str) -> Vec { 108 let text = strip_think_blocks(text); 109 let p1 = Regex::new(r"(?s)\s*(\{.*?\})\s*").unwrap(); 110 p1.captures_iter(&text) 111 .filter_map(|c| serde_json::from_str(c[1].trim()).ok()) 112 .collect() 113 } 114 115 /// Drop model thinking before any tool-call parse. A tool call inside a 116 /// thinking block is not the content channel. An opener that never closes 117 /// (truncated reasoning) hides everything after it. A closer with no opener 118 /// (a chat template that opened the block in the prompt) hides everything 119 /// before it. 120 fn strip_think_blocks(text: &str) -> String { 121 let tag = Regex::new(r"(?i)<(/?)think(?:ing)?>").unwrap(); 122 let mut out = String::new(); 123 let mut open: Option = None; 124 let mut kept_from = 0; 125 for m in tag.captures_iter(text) { 126 let whole = m.get(0).unwrap(); 127 let closing = !m[1].is_empty(); 128 match (open, closing) { 129 (None, false) => { 130 out.push_str(&text[kept_from..whole.start()]); 131 open = Some(whole.start()); 132 } 133 (Some(_), true) => { 134 open = None; 135 kept_from = whole.end(); 136 } 137 // An orphan closer: everything kept so far was reasoning. 138 (None, true) => { 139 out.clear(); 140 kept_from = whole.end(); 141 } 142 (Some(_), false) => {} 143 } 144 } 145 if open.is_none() { 146 out.push_str(&text[kept_from..]); 147 } 148 out 149 } 150 151 fn s_arg<'a>(a: &'a Value, k: &str, d: &'a str) -> &'a str { 152 a.get(k).and_then(Value::as_str).unwrap_or(d) 153 } 154 155 fn run_with_timeout( 156 mut cmd: Command, 157 timeout: Duration, 158 label: &str, 159 ) -> Result<(i32, String, String), String> { 160 cmd.stdout(Stdio::piped()) 161 .stderr(Stdio::piped()) 162 .stdin(Stdio::null()); 163 let mut child = cmd.spawn().map_err(|e| e.to_string())?; 164 let mut out = child.stdout.take().unwrap(); 165 let mut err = child.stderr.take().unwrap(); 166 let t_out = std::thread::spawn(move || { 167 let mut b = Vec::new(); 168 let _ = std::io::Read::read_to_end(&mut out, &mut b); 169 b 170 }); 171 let t_err = std::thread::spawn(move || { 172 let mut b = Vec::new(); 173 let _ = std::io::Read::read_to_end(&mut err, &mut b); 174 b 175 }); 176 let start = Instant::now(); 177 loop { 178 if let Some(st) = child.try_wait().map_err(|e| e.to_string())? { 179 let o = String::from_utf8_lossy(&t_out.join().unwrap_or_default()).into_owned(); 180 let e = String::from_utf8_lossy(&t_err.join().unwrap_or_default()).into_owned(); 181 return Ok((st.code().unwrap_or(-1), o, e)); 182 } 183 if start.elapsed() >= timeout { 184 let _ = child.kill(); 185 let _ = child.wait(); 186 return Err(format!( 187 "Command '{label}' timed out after {} seconds", 188 timeout.as_secs() 189 )); 190 } 191 std::thread::sleep(Duration::from_millis(20)); 192 } 193 } 194 195 /// Run one tool. Never panics; failures come back as `{"error": ...}`. 196 pub fn dispatch_tool(cfg: &Config, name: &str, args: &Value) -> Value { 197 let started = Instant::now(); 198 let shown = first_chars(&args.to_string(), 120); 199 eprintln!(" [TOOL RUN] {name}: {shown}..."); 200 let res = dispatch_inner(cfg, name, args).unwrap_or_else(|e| json!({ "error": e })); 201 eprintln!( 202 " [TOOL DONE] {name} in {:.2}s", 203 started.elapsed().as_secs_f64() 204 ); 205 res 206 } 207 208 fn dispatch_inner(cfg: &Config, name: &str, a: &Value) -> Result { 209 Ok(match name { 210 "run_command" => command::execute(&cfg.command, a)?, 211 "view_file" => { 212 let path = s_arg(a, "path", ""); 213 let start = a.get("start_line").and_then(Value::as_i64).unwrap_or(1); 214 let end = a.get("end_line").and_then(Value::as_i64).unwrap_or(100); 215 let bytes = paths::read_bytes(&cfg.command.root, path)?; 216 let text = String::from_utf8_lossy(&bytes).into_owned(); 217 let lines: Vec<&str> = text.split_inclusive('\n').collect(); 218 let total = lines.len() as i64; 219 let lo = (start - 1).max(0).min(total) as usize; 220 let hi = end.min(total).max(0) as usize; 221 let sel = if lo < hi { 222 lines[lo..hi].concat() 223 } else { 224 String::new() 225 }; 226 json!({"path": path, "total_lines": total, "lines": sel}) 227 } 228 "write_to_file" => { 229 let path = s_arg(a, "path", ""); 230 let content = s_arg(a, "content", ""); 231 let overwrite = a.get("overwrite").and_then(Value::as_bool).unwrap_or(false); 232 let n = paths::write_bytes(&cfg.command.root, path, content.as_bytes(), overwrite)?; 233 json!({"status": "ok", "bytes_written": n}) 234 } 235 "replace_file_content" => { 236 let path = s_arg(a, "path", ""); 237 let target = s_arg(a, "target", ""); 238 let bytes = paths::read_bytes(&cfg.command.root, path)?; 239 let content = String::from_utf8_lossy(&bytes).into_owned(); 240 if !content.contains(target) { 241 json!({"error": format!("Target string not found in {path}")}) 242 } else { 243 let new = content.replacen(target, s_arg(a, "replacement", ""), 1); 244 paths::write_bytes(&cfg.command.root, path, new.as_bytes(), true)?; 245 json!({"status": "ok", "replaced": true}) 246 } 247 } 248 "list_dir" => { 249 let path = s_arg(a, "path", "."); 250 let names = paths::list_dir(&cfg.command.root, path)?; 251 json!({"path": path, "entries": names}) 252 } 253 "grep_search" => { 254 let query = s_arg(a, "query", ""); 255 let path = s_arg(a, "path", "."); 256 let opened = paths::open_existing(&cfg.command.root, path)?; 257 let raw = opened.as_raw_fd(); 258 unsafe { 259 let flags = libc::fcntl(raw, libc::F_GETFD); 260 if flags >= 0 { 261 libc::fcntl(raw, libc::F_SETFD, flags & !libc::FD_CLOEXEC); 262 } 263 } 264 let mut c = Command::new("grep"); 265 c.args(["-rnI", "--", query, &format!("/proc/self/fd/{raw}")]); 266 let (_, o, _) = run_with_timeout(c, Duration::from_secs(30), "grep")?; 267 drop(opened); 268 json!({"matches": first_chars(&o, 4000)}) 269 } 270 "create_dir" => { 271 let path = s_arg(a, "path", ""); 272 paths::create_dir(&cfg.command.root, path)?; 273 json!({"status": "ok", "created": path}) 274 } 275 "goal" => { 276 json!({"status": "ok", "goal_action": s_arg(a, "action", ""), "milestone_done": true}) 277 } 278 "cortex" => { 279 let Some(token) = cfg.cortex_token.as_deref().filter(|t| !t.is_empty()) else { 280 return Err( 281 "cortex rejected: the operator has not configured a cortex token".into(), 282 ); 283 }; 284 let ts = std::time::SystemTime::now() 285 .duration_since(std::time::UNIX_EPOCH) 286 .map(|d| d.as_secs()) 287 .unwrap_or(0); 288 let payload = json!({ 289 "kind": "entity", 290 "value": { 291 "space": cfg.cortex_space, 292 "canonicalName": s_arg(a, "name", "lesson"), 293 "content": s_arg(a, "content", ""), 294 "confidence": 0.95, 295 "metadata": {"kind": s_arg(a, "kind", "lesson"), "timestamp": ts} 296 } 297 }); 298 let url = format!("{}/api/cortex/write", cfg.cortex_endpoint); 299 match http::post_json_auth( 300 &url, 301 &payload.to_string(), 302 Duration::from_secs(10), 303 Some(token), 304 ) { 305 Ok(r) if r.status < 400 => json!({"status": "ok", "cortex_code": r.status}), 306 Ok(r) => json!({"warning": format!("Cortex write notice: HTTP {}", r.status)}), 307 Err(e) => json!({"warning": format!("Cortex write notice: {e}")}), 308 } 309 } 310 other => json!({"error": format!("Unknown tool: {other}")}), 311 }) 312 } 313 314 fn sanitize(s: &str) -> String { 315 s.replace('\u{2014}', ", ").replace('\u{2013}', "-") 316 } 317 318 /// Read an SSE stream of chat-completion chunks. Returns the assistant 319 /// content channel only. Tool calls that appear in reasoning text are not 320 /// a tool-call channel and are not returned for execution. 321 pub fn read_stream(body: impl BufRead, out: &mut dyn Write) -> String { 322 let (mut content, mut reasoning) = (String::new(), String::new()); 323 let mut in_reasoning = false; 324 for line in body.split(b'\n') { 325 let Ok(line) = line else { break }; 326 let line = String::from_utf8_lossy(&line).trim().to_string(); 327 let Some(data) = line.strip_prefix("data: ") else { 328 continue; 329 }; 330 if data == "[DONE]" { 331 break; 332 } 333 let Ok(chunk) = serde_json::from_str::(data) else { 334 continue; 335 }; 336 let delta = &chunk["choices"][0]["delta"]; 337 if let Some(r) = delta["reasoning"].as_str().filter(|s| !s.is_empty()) { 338 if !in_reasoning { 339 let _ = write!(out, "\n[AIEN THINKING] "); 340 in_reasoning = true; 341 } 342 let r = sanitize(r); 343 let _ = write!(out, "{r}"); 344 reasoning.push_str(&r); 345 } 346 if let Some(c) = delta["content"].as_str().filter(|s| !s.is_empty()) { 347 if in_reasoning { 348 let _ = write!(out, "\n[AIEN OUTPUT]\n"); 349 in_reasoning = false; 350 } 351 let c = sanitize(c); 352 let _ = write!(out, "{c}"); 353 content.push_str(&c); 354 } 355 let _ = out.flush(); 356 } 357 let _ = writeln!(out, "\n"); 358 let _ = reasoning; 359 content 360 } 361 362 fn call_model(cfg: &Config, messages: &[Value], out: &mut dyn Write) -> Result { 363 let payload = json!({ 364 "model": cfg.model, "messages": messages, "stream": true, 365 "temperature": 0.2, "max_tokens": 2048 366 }); 367 let r = http::post_json(&cfg.endpoint, &payload.to_string(), cfg.request_timeout)?; 368 if r.status >= 400 { 369 return Err(format!("model endpoint returned HTTP {}", r.status)); 370 } 371 Ok(read_stream(r.body, out)) 372 } 373 374 /// Drive the loop. Ok(true) when the model signalled `milestone_done`/`done`. 375 pub fn run_directive(cfg: &Config, directive: &str, max_turns: u32) -> Result { 376 let mut out = std::io::stdout(); 377 println!("{}", "=".repeat(60)); 378 println!("DRIVING AIEN AUTONOMOUS EXECUTION LOOP"); 379 println!("Directive: {}...", first_chars(directive, 120)); 380 println!("{}", "=".repeat(60)); 381 let mut messages = vec![ 382 json!({"role": "system", "content": SYSTEM_PROMPT}), 383 json!({"role": "user", "content": directive}), 384 ]; 385 for turn in 1..=max_turns { 386 println!("\n--- Turn {turn}/{max_turns} ---"); 387 let text = call_model(cfg, &messages, &mut out)?; 388 messages.push(json!({"role": "assistant", "content": text})); 389 let calls = extract_tool_calls(&text); 390 if calls.is_empty() { 391 println!("[AIEN IDLE] No tool calls emitted. Turn sequence concluded."); 392 break; 393 } 394 let mut done = false; 395 for tc in calls { 396 let name = tc 397 .get("name") 398 .and_then(Value::as_str) 399 .unwrap_or("") 400 .to_string(); 401 let args = tc.get("arguments").cloned().unwrap_or_else(|| json!({})); 402 if name == "goal" && matches!(s_arg(&args, "action", ""), "milestone_done" | "done") { 403 done = true; 404 } 405 let res = dispatch_tool(cfg, &name, &args); 406 let body = serde_json::to_string_pretty(&res).unwrap_or_default(); 407 messages.push(json!({ 408 "role": "user", 409 "content": format!("\n{body}\n") 410 })); 411 } 412 if done { 413 println!("AIEN signaled milestone_done! Directive complete."); 414 return Ok(true); 415 } 416 } 417 Ok(false) 418 }