diff --git a/.crumb b/.crumb index 10eb59cc..755d737d 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:4ff1a56b7c8ac606ad5709f2ba1141f16055c34f5f242ac491233dca20d5153e", - "compiled_at": "2026-10-07T02:40:59Z", + "compiled_at": "2026-10-07T02:57:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:cb6be9b645974d7cc42c4a3d07da2a3d97f07e7c3ca7340cafb7108f3ef569ab", + "digest": "sha256:28cf40d152e8cc6a9bb05d94a80bebc6075881eb96a5183e6739c5bda85bf634", "evidence_files": 155, "evidence_root": "sha256:ff6dddfecfcc02cea55f46acaccc7eaecd27557209e98c3d5616ec02bdde31db", - "files": 1086, - "generated_at_commit": "acc9bcaea011ead2a69f29abb81b08123d2637d2", - "source_tree": "sha256:b6d670077598943ca7f60c3ee69989d5b6984e967513944d457146aaf353ad2d" + "files": 1093, + "generated_at_commit": "9d2902ed6d03359faadd1567da7f8e7bbba7a1b5", + "source_tree": "sha256:24d9c8192bd7ca9590dab90710d0e88ad262641643fe166c6b99af8ed30b67ff" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 97f31a93..1178d100 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -86,6 +86,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "aien-drive" +version = "0.1.0" +dependencies = [ + "clap", + "regex", + "serde_json", +] + [[package]] name = "aien-dual-observation" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index de590494..6c1c53f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ members = [ "crates/aien-switchboard", "crates/aien-dual-observation", "tools/aien-test", + "crates/aien-drive", ] [workspace.package] diff --git a/crates/aien-drive/Cargo.toml b/crates/aien-drive/Cargo.toml new file mode 100644 index 00000000..4458b54c --- /dev/null +++ b/crates/aien-drive/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "aien-drive" +description = "AIEN autonomous API driver: loops a local chat model with tool dispatch (Rust replacement for the removed scripts/aien_drive.py, issue #179)" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true + +# Plain http:// to loopback only, over std::net. No Python, no TLS, no async. +[dependencies] +clap = { version = "4.5", features = ["derive"] } +regex = "1.10" +serde_json = "1" + +[lib] +name = "aien_drive" +path = "src/lib.rs" + +[[bin]] +name = "aien-drive" +path = "src/main.rs" diff --git a/crates/aien-drive/src/http.rs b/crates/aien-drive/src/http.rs new file mode 100644 index 00000000..6c1f92df --- /dev/null +++ b/crates/aien-drive/src/http.rs @@ -0,0 +1,108 @@ +//! Minimal plain-HTTP client over `std::net` (loopback endpoints only). +//! Sends HTTP/1.0 with `Connection: close` and decodes chunked bodies if the +//! server uses them anyway. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpStream; +use std::time::Duration; + +pub struct Response { + pub status: u16, + pub body: Box, +} + +fn split_url(url: &str) -> Result<(String, String), String> { + let rest = url + .strip_prefix("http://") + .ok_or_else(|| format!("only http:// endpoints are supported: {url}"))?; + let (host, path) = match rest.find('/') { + Some(i) => (&rest[..i], &rest[i..]), + None => (rest, "/"), + }; + let host = if host.contains(':') { + host.to_string() + } else { + format!("{host}:80") + }; + Ok((host, path.to_string())) +} + +struct Chunked { + inner: R, + left: usize, + done: bool, +} + +impl Read for Chunked { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.done { + return Ok(0); + } + if self.left == 0 { + let mut line = String::new(); + self.inner.read_line(&mut line)?; + let size = usize::from_str_radix(line.trim().split(';').next().unwrap_or(""), 16) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; + if size == 0 { + self.done = true; + return Ok(0); + } + self.left = size; + } + let n = buf.len().min(self.left); + let got = self.inner.read(&mut buf[..n])?; + self.left -= got; + if self.left == 0 { + let mut crlf = String::new(); + self.inner.read_line(&mut crlf)?; + } + Ok(got) + } +} + +/// POST a JSON body. `timeout` bounds each socket read and write. +pub fn post_json(url: &str, body: &str, timeout: Duration) -> Result { + let (host, path) = split_url(url)?; + let mut s = TcpStream::connect(&host).map_err(|e| format!("connect {host}: {e}"))?; + s.set_read_timeout(Some(timeout)) + .map_err(|e| e.to_string())?; + s.set_write_timeout(Some(timeout)) + .map_err(|e| e.to_string())?; + let req = format!( + "POST {path} HTTP/1.0\r\nHost: {host}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + s.write_all(req.as_bytes()) + .map_err(|e| format!("write: {e}"))?; + let mut r = BufReader::new(s); + let mut status_line = String::new(); + r.read_line(&mut status_line) + .map_err(|e| format!("read: {e}"))?; + let status: u16 = status_line + .split_whitespace() + .nth(1) + .and_then(|c| c.parse().ok()) + .ok_or_else(|| format!("bad status line: {status_line:?}"))?; + let mut chunked = false; + loop { + let mut h = String::new(); + let n = r.read_line(&mut h).map_err(|e| format!("read: {e}"))?; + if n == 0 || h.trim().is_empty() { + break; + } + let l = h.to_ascii_lowercase(); + if l.starts_with("transfer-encoding:") && l.contains("chunked") { + chunked = true; + } + } + let body: Box = if chunked { + Box::new(BufReader::new(Chunked { + inner: r, + left: 0, + done: false, + })) + } else { + Box::new(r) + }; + Ok(Response { status, body }) +} diff --git a/crates/aien-drive/src/lib.rs b/crates/aien-drive/src/lib.rs new file mode 100644 index 00000000..9d2b3eb6 --- /dev/null +++ b/crates/aien-drive/src/lib.rs @@ -0,0 +1,360 @@ +//! AIEN autonomous API driver (Rust port of the removed `scripts/aien_drive.py`). +//! +//! Loops a chat model at an OpenAI-style streaming endpoint with a system +//! prompt, extracts `` blocks from its reply, dispatches them, and +//! feeds the results back as `` user messages. + +pub mod http; + +use regex::Regex; +use serde_json::{json, Value}; +use std::io::{BufRead, Write}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +pub const ENDPOINT_LIGHTNING: &str = "http://127.0.0.1:18006/v1/chat/completions"; +pub const MODEL_LIGHTNING: &str = "atlas-lightning-omni"; +pub const ENDPOINT_JUDGE: &str = "http://127.0.0.1:18082/v1/chat/completions"; +pub const MODEL_JUDGE: &str = "unsloth/Llama-3.2-1B-Instruct"; +pub const DEFAULT_CORTEX: &str = "http://127.0.0.1:18080"; + +pub const SYSTEM_PROMPT: &str = r#"You are AIEN. Drake is the operator. This Spark desk is ours. +You are an autonomous operator-builder running on NVIDIA DGX Spark Grace Blackwell GB10 hardware. +Always be concise, precise, and lead with verified results. + +Available Tools: +- run_command: {"command": "string", "cwd": "string"} +- view_file: {"path": "string", "start_line": 1, "end_line": 100} +- write_to_file: {"path": "string", "content": "string", "overwrite": true} +- replace_file_content: {"path": "string", "target": "string", "replacement": "string"} +- create_dir: {"path": "string", "purpose": "string"} +- list_dir: {"path": "string"} +- grep_search: {"query": "string", "path": "string"} +- goal: {"action": "milestone_done|done", "id": "string", "milestone_id": 1} +- cortex: {"action": "write", "name": "string", "content": "string", "kind": "lesson|discovery|procedure"} + +MANDATORY RULES: +1. ZERO EM DASHES AND EN DASHES: Use plain commas, periods, or standard hyphens (-). +2. BAN FORMULAIC AI CLICHES: Never use 'It is not X, it is Y', 'delve', 'tapestry', 'testament', 'crucial', 'pivotal'. +3. LEAD WITH TECHNICAL PROOF: Output factual diffs, test outputs, and verified receipts. +4. TOOL EXECUTION FORMAT: +To execute a tool, output: + +{"name": "tool_name", "arguments": {"arg": "val"}} + + +When all work for the milestone is verified, call goal with action 'milestone_done'. +"#; + +/// Where a driver run talks to. +#[derive(Clone, Debug)] +pub struct Config { + pub endpoint: String, + pub model: String, + pub cortex_endpoint: String, + /// Cortex area the `cortex` tool writes to. + pub cortex_space: String, + pub request_timeout: Duration, +} + +fn last_chars(s: &str, n: usize) -> String { + let c: Vec = s.chars().collect(); + if c.len() > n { + c[c.len() - n..].iter().collect() + } else { + s.to_string() + } +} + +fn first_chars(s: &str, n: usize) -> String { + s.chars().take(n).collect() +} + +/// Pull tool calls out of model text. Pattern 1: `{json}`. +/// Pattern 2 (only if pattern 1 found nothing): bare `{name, arguments}` objects. +pub fn extract_tool_calls(text: &str) -> Vec { + let p1 = Regex::new(r"(?s)\s*(\{.*?\})\s*").unwrap(); + let calls: Vec = p1 + .captures_iter(text) + .filter_map(|c| serde_json::from_str(c[1].trim()).ok()) + .collect(); + if !calls.is_empty() { + return calls; + } + let p2 = Regex::new( + r#"(?s)(\{\s*"?name"?\s*:\s*"[a-zA-Z0-9_]+"\s*,\s*"?arguments"?\s*:\s*\{.*?\}\s*\})"#, + ) + .unwrap(); + p2.captures_iter(text) + .filter_map(|c| serde_json::from_str(&c[1].replace('\'', "\"")).ok()) + .collect() +} + +fn s_arg<'a>(a: &'a Value, k: &str, d: &'a str) -> &'a str { + a.get(k).and_then(Value::as_str).unwrap_or(d) +} + +fn run_with_timeout( + mut cmd: Command, + timeout: Duration, + label: &str, +) -> Result<(i32, String, String), String> { + cmd.stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .stdin(Stdio::null()); + let mut child = cmd.spawn().map_err(|e| e.to_string())?; + let mut out = child.stdout.take().unwrap(); + let mut err = child.stderr.take().unwrap(); + let t_out = std::thread::spawn(move || { + let mut b = Vec::new(); + let _ = std::io::Read::read_to_end(&mut out, &mut b); + b + }); + let t_err = std::thread::spawn(move || { + let mut b = Vec::new(); + let _ = std::io::Read::read_to_end(&mut err, &mut b); + b + }); + let start = Instant::now(); + loop { + if let Some(st) = child.try_wait().map_err(|e| e.to_string())? { + let o = String::from_utf8_lossy(&t_out.join().unwrap_or_default()).into_owned(); + let e = String::from_utf8_lossy(&t_err.join().unwrap_or_default()).into_owned(); + return Ok((st.code().unwrap_or(-1), o, e)); + } + if start.elapsed() >= timeout { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!( + "Command '{label}' timed out after {} seconds", + timeout.as_secs() + )); + } + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// Run one tool. Never panics; failures come back as `{"error": ...}`. +pub fn dispatch_tool(cfg: &Config, name: &str, args: &Value) -> Value { + let started = Instant::now(); + let shown = first_chars(&args.to_string(), 120); + eprintln!(" [TOOL RUN] {name}: {shown}..."); + let res = dispatch_inner(cfg, name, args).unwrap_or_else(|e| json!({ "error": e })); + eprintln!( + " [TOOL DONE] {name} in {:.2}s", + started.elapsed().as_secs_f64() + ); + res +} + +fn dispatch_inner(cfg: &Config, name: &str, a: &Value) -> Result { + let io = |e: std::io::Error| e.to_string(); + Ok(match name { + "run_command" => { + let command = s_arg(a, "command", ""); + let mut c = Command::new("sh"); + c.arg("-c").arg(command).current_dir(s_arg(a, "cwd", ".")); + let (code, o, e) = run_with_timeout(c, Duration::from_secs(120), command)?; + json!({"exit_code": code, "stdout": last_chars(&o, 4000), "stderr": last_chars(&e, 2000)}) + } + "view_file" => { + let path = s_arg(a, "path", ""); + let start = a.get("start_line").and_then(Value::as_i64).unwrap_or(1); + let end = a.get("end_line").and_then(Value::as_i64).unwrap_or(100); + let text = String::from_utf8_lossy(&std::fs::read(path).map_err(io)?).into_owned(); + let lines: Vec<&str> = text.split_inclusive('\n').collect(); + let total = lines.len() as i64; + let lo = (start - 1).max(0).min(total) as usize; + let hi = end.min(total).max(0) as usize; + let sel = if lo < hi { + lines[lo..hi].concat() + } else { + String::new() + }; + json!({"path": path, "total_lines": total, "lines": sel}) + } + "write_to_file" => { + let path = s_arg(a, "path", ""); + let content = s_arg(a, "content", ""); + let overwrite = a.get("overwrite").and_then(Value::as_bool).unwrap_or(true); + if std::path::Path::new(path).exists() && !overwrite { + json!({"error": format!("File {path} exists and overwrite=false")}) + } else { + if let Some(dir) = std::path::Path::new(path).parent() { + if !dir.as_os_str().is_empty() { + std::fs::create_dir_all(dir).map_err(io)?; + } + } + std::fs::write(path, content).map_err(io)?; + json!({"status": "ok", "bytes_written": content.len()}) + } + } + "replace_file_content" => { + let path = s_arg(a, "path", ""); + let target = s_arg(a, "target", ""); + let content = std::fs::read_to_string(path).map_err(io)?; + if !content.contains(target) { + json!({"error": format!("Target string not found in {path}")}) + } else { + let new = content.replacen(target, s_arg(a, "replacement", ""), 1); + std::fs::write(path, new).map_err(io)?; + json!({"status": "ok", "replaced": true}) + } + } + "list_dir" => { + let path = s_arg(a, "path", "."); + let mut names: Vec = std::fs::read_dir(path) + .map_err(io)? + .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().into_owned())) + .collect(); + names.sort(); + names.truncate(100); + json!({"path": path, "entries": names}) + } + "grep_search" => { + let mut c = Command::new("grep"); + c.args(["-rnI", s_arg(a, "query", ""), s_arg(a, "path", ".")]); + let (_, o, _) = run_with_timeout(c, Duration::from_secs(30), "grep")?; + json!({"matches": first_chars(&o, 4000)}) + } + "create_dir" => { + let path = s_arg(a, "path", ""); + std::fs::create_dir_all(path).map_err(io)?; + json!({"status": "ok", "created": path}) + } + "goal" => { + json!({"status": "ok", "goal_action": s_arg(a, "action", ""), "milestone_done": true}) + } + "cortex" => { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let payload = json!({ + "kind": "entity", + "value": { + "space": cfg.cortex_space, + "canonicalName": s_arg(a, "name", "lesson"), + "content": s_arg(a, "content", ""), + "confidence": 0.95, + "metadata": {"kind": s_arg(a, "kind", "lesson"), "timestamp": ts} + } + }); + let url = format!("{}/api/cortex/write", cfg.cortex_endpoint); + match http::post_json(&url, &payload.to_string(), Duration::from_secs(10)) { + Ok(r) if r.status < 400 => json!({"status": "ok", "cortex_code": r.status}), + Ok(r) => json!({"warning": format!("Cortex write notice: HTTP {}", r.status)}), + Err(e) => json!({"warning": format!("Cortex write notice: {e}")}), + } + } + other => json!({"error": format!("Unknown tool: {other}")}), + }) +} + +fn sanitize(s: &str) -> String { + s.replace('\u{2014}', ", ").replace('\u{2013}', "-") +} + +/// Read an SSE stream of chat-completion chunks. Returns the assistant text +/// (falling back to the reasoning text if it holds a tool call and content is empty). +pub fn read_stream(body: impl BufRead, out: &mut dyn Write) -> String { + let (mut content, mut reasoning) = (String::new(), String::new()); + let mut in_reasoning = false; + for line in body.split(b'\n') { + let Ok(line) = line else { break }; + let line = String::from_utf8_lossy(&line).trim().to_string(); + let Some(data) = line.strip_prefix("data: ") else { + continue; + }; + if data == "[DONE]" { + break; + } + let Ok(chunk) = serde_json::from_str::(data) else { + continue; + }; + let delta = &chunk["choices"][0]["delta"]; + if let Some(r) = delta["reasoning"].as_str().filter(|s| !s.is_empty()) { + if !in_reasoning { + let _ = write!(out, "\n[AIEN THINKING] "); + in_reasoning = true; + } + let r = sanitize(r); + let _ = write!(out, "{r}"); + reasoning.push_str(&r); + } + if let Some(c) = delta["content"].as_str().filter(|s| !s.is_empty()) { + if in_reasoning { + let _ = write!(out, "\n[AIEN OUTPUT]\n"); + in_reasoning = false; + } + let c = sanitize(c); + let _ = write!(out, "{c}"); + content.push_str(&c); + } + let _ = out.flush(); + } + let _ = writeln!(out, "\n"); + if content.is_empty() && reasoning.contains("") { + reasoning + } else { + content + } +} + +fn call_model(cfg: &Config, messages: &[Value], out: &mut dyn Write) -> Result { + let payload = json!({ + "model": cfg.model, "messages": messages, "stream": true, + "temperature": 0.2, "max_tokens": 2048 + }); + let r = http::post_json(&cfg.endpoint, &payload.to_string(), cfg.request_timeout)?; + if r.status >= 400 { + return Err(format!("model endpoint returned HTTP {}", r.status)); + } + Ok(read_stream(r.body, out)) +} + +/// Drive the loop. Ok(true) when the model signalled `milestone_done`/`done`. +pub fn run_directive(cfg: &Config, directive: &str, max_turns: u32) -> Result { + let mut out = std::io::stdout(); + println!("{}", "=".repeat(60)); + println!("DRIVING AIEN AUTONOMOUS EXECUTION LOOP"); + println!("Directive: {}...", first_chars(directive, 120)); + println!("{}", "=".repeat(60)); + let mut messages = vec![ + json!({"role": "system", "content": SYSTEM_PROMPT}), + json!({"role": "user", "content": directive}), + ]; + for turn in 1..=max_turns { + println!("\n--- Turn {turn}/{max_turns} ---"); + let text = call_model(cfg, &messages, &mut out)?; + messages.push(json!({"role": "assistant", "content": text})); + let calls = extract_tool_calls(&text); + if calls.is_empty() { + println!("[AIEN IDLE] No tool calls emitted. Turn sequence concluded."); + break; + } + let mut done = false; + for tc in calls { + let name = tc + .get("name") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(); + let args = tc.get("arguments").cloned().unwrap_or_else(|| json!({})); + if name == "goal" && matches!(s_arg(&args, "action", ""), "milestone_done" | "done") { + done = true; + } + let res = dispatch_tool(cfg, &name, &args); + let body = serde_json::to_string_pretty(&res).unwrap_or_default(); + messages.push(json!({ + "role": "user", + "content": format!("\n{body}\n") + })); + } + if done { + println!("AIEN signaled milestone_done! Directive complete."); + return Ok(true); + } + } + Ok(false) +} diff --git a/crates/aien-drive/src/main.rs b/crates/aien-drive/src/main.rs new file mode 100644 index 00000000..a70248f5 --- /dev/null +++ b/crates/aien-drive/src/main.rs @@ -0,0 +1,54 @@ +use aien_drive::*; +use clap::{Parser, ValueEnum}; +use std::time::Duration; + +#[derive(Clone, ValueEnum)] +enum Seat { + Lightning, + Judge, +} + +/// AIEN Autonomous API Driver +#[derive(Parser)] +struct Args { + /// Task directive for AIEN + #[arg(required = true)] + directive: Vec, + /// Inference seat on Spark + #[arg(long, value_enum, default_value = "lightning")] + seat: Seat, + /// Maximum execution turns + #[arg(long, default_value_t = 15)] + max_turns: u32, +} + +fn main() { + let a = Args::parse(); + let (ep, model) = match a.seat { + Seat::Lightning => (ENDPOINT_LIGHTNING, MODEL_LIGHTNING), + Seat::Judge => (ENDPOINT_JUDGE, MODEL_JUDGE), + }; + // AIEN_MODEL_ENDPOINT / AIEN_MODEL_NAME override the seat defaults (the + // Python original read them but then overwrote them from --seat). + let env = |k: &str, d: &str| { + std::env::var(k) + .ok() + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| d.to_string()) + }; + let cfg = Config { + endpoint: env("AIEN_MODEL_ENDPOINT", ep), + model: env("AIEN_MODEL_NAME", model), + cortex_endpoint: env("CORTEX_ENDPOINT", DEFAULT_CORTEX), + cortex_space: env("AIEN_CORTEX_SPACE", "aien-sources"), + request_timeout: Duration::from_secs(180), + }; + match run_directive(&cfg, &a.directive.join(" "), a.max_turns) { + Ok(true) => {} + Ok(false) => std::process::exit(1), + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } + } +} diff --git a/crates/aien-drive/tests/equivalence.rs b/crates/aien-drive/tests/equivalence.rs new file mode 100644 index 00000000..09c9a094 --- /dev/null +++ b/crates/aien-drive/tests/equivalence.rs @@ -0,0 +1,97 @@ +//! Equivalence with the removed Python `scripts/aien_drive.py` (issue #179). +//! +//! `golden_from_python_original.json` was produced by running the original +//! Python `extract_tool_calls` and `dispatch_tool` (git history of +//! aien-sovereign-core before #182) on exactly these inputs. Results are +//! compared as parsed JSON (key order is not significant to the model). +//! The one allowed difference: error TEXT from the OS (Python prints +//! "[Errno 2] ...", Rust prints "No such file or directory (os error 2)"), +//! so for errors that come from the OS only the `error` key is compared. + +use aien_drive::{dispatch_tool, extract_tool_calls, Config}; +use serde_json::Value; +use std::time::Duration; + +fn cfg() -> Config { + Config { + endpoint: String::new(), + model: String::new(), + cortex_endpoint: "http://127.0.0.1:1".into(), + cortex_space: "aien-sources".into(), + request_timeout: Duration::from_secs(5), + } +} + +fn golden() -> Value { + serde_json::from_str(include_str!("golden_from_python_original.json")).unwrap() +} + +#[test] +fn extract_matches_python() { + let g = golden(); + let cases = g["extract"].as_array().unwrap(); + assert!(cases.len() >= 6); + for c in cases { + let got = extract_tool_calls(c["text"].as_str().unwrap()); + assert_eq!(Value::Array(got), c["calls"], "text: {}", c["text"]); + } +} + +fn prepare(tmp: &std::path::Path) { + std::fs::create_dir_all(tmp.join("ls")).unwrap(); + std::fs::write(tmp.join("f.txt"), "one\ntwo\nthree\nfour\n").unwrap(); + std::fs::write(tmp.join("e.txt"), "aa bb aa\n").unwrap(); + for n in ["b", "a", "c"] { + std::fs::write(tmp.join("ls").join(n), "x").unwrap(); + } + std::fs::write(tmp.join("g.txt"), "needle here\nother\n").unwrap(); +} + +fn run_dispatch_cases(mutate_expected: impl Fn(&mut Value)) -> Vec { + static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let tmp = std::env::temp_dir().join(format!("aien-drive-eq-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&tmp); + prepare(&tmp); + let t = tmp.to_str().unwrap(); + let g = golden(); + let mut failures = vec![]; + for c in g["dispatch"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + let args: Value = serde_json::from_str(&c["args"].to_string().replace("{TMP}", t)).unwrap(); + let got = dispatch_tool(&cfg(), name, &args); + let got: Value = serde_json::from_str(&got.to_string().replace(t, "{TMP}")).unwrap(); + let mut want = c["result"].clone(); + mutate_expected(&mut want); + let os_error = want["error"] + .as_str() + .is_some_and(|e| e.starts_with("[Errno")); + let ok = if os_error { + got.get("error").is_some() + } else { + got == want + }; + if !ok { + failures.push(format!("{name}: got {got} want {want}")); + } + } + let _ = std::fs::remove_dir_all(&tmp); + failures +} + +#[test] +fn dispatch_matches_python() { + let f = run_dispatch_cases(|_| {}); + assert!(f.is_empty(), "{f:#?}"); +} + +/// Negative control: corrupt one expected value and the comparison must fail. +#[test] +fn comparison_detects_a_difference() { + let f = run_dispatch_cases(|w| { + if w.get("milestone_done").is_some() { + w["milestone_done"] = Value::Bool(false); + } + }); + assert_eq!(f.len(), 1, "{f:#?}"); +} diff --git a/crates/aien-drive/tests/golden_from_python_original.json b/crates/aien-drive/tests/golden_from_python_original.json new file mode 100644 index 00000000..3ddd6142 --- /dev/null +++ b/crates/aien-drive/tests/golden_from_python_original.json @@ -0,0 +1,224 @@ +{ + "extract": [ + { + "text": "hi \n{\"name\": \"list_dir\", \"arguments\": {\"path\": \".\"}}\n and {\"name\":\"goal\",\"arguments\":{\"action\":\"done\"}}", + "calls": [ + { + "name": "list_dir", + "arguments": { + "path": "." + } + }, + { + "name": "goal", + "arguments": { + "action": "done" + } + } + ] + }, + { + "text": "bare {\"name\": \"view_file\", \"arguments\": {\"path\": \"a.txt\"}} text", + "calls": [ + { + "name": "view_file", + "arguments": { + "path": "a.txt" + } + } + ] + }, + { + "text": "single {'name': 'list_dir', 'arguments': {'path': '.'}}", + "calls": [] + }, + { + "text": "{not json}", + "calls": [] + }, + { + "text": "nothing here", + "calls": [] + }, + { + "text": "multi\n\n{\"name\":\"run_command\",\"arguments\":{\"command\":\"echo hi\\nthere\"}}\n", + "calls": [ + { + "name": "run_command", + "arguments": { + "command": "echo hi\nthere" + } + } + ] + } + ], + "dispatch": [ + { + "name": "run_command", + "args": { + "command": "echo out; echo err 1>&2; exit 3", + "cwd": "{TMP}" + }, + "result": { + "exit_code": 3, + "stdout": "out\n", + "stderr": "err\n" + } + }, + { + "name": "run_command", + "args": { + "command": "printf 'x%.0s' $(seq 1 5000)", + "cwd": "{TMP}" + }, + "result": { + "exit_code": 0, + "stdout": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx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xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "stderr": "" + } + }, + { + "name": "view_file", + "args": { + "path": "{TMP}/f.txt", + "start_line": 2, + "end_line": 3 + }, + "result": { + "path": "{TMP}/f.txt", + "total_lines": 4, + "lines": "two\nthree\n" + } + }, + { + "name": "view_file", + "args": { + "path": "{TMP}/f.txt" + }, + "result": { + "path": "{TMP}/f.txt", + "total_lines": 4, + "lines": "one\ntwo\nthree\nfour\n" + } + }, + { + "name": "view_file", + "args": { + "path": "{TMP}/f.txt", + "start_line": 9, + "end_line": 20 + }, + "result": { + "path": "{TMP}/f.txt", + "total_lines": 4, + "lines": "" + } + }, + { + "name": "view_file", + "args": { + "path": "{TMP}/missing.txt" + }, + "result": { + "error": "[Errno 2] No such file or directory: '{TMP}/missing.txt'" + } + }, + { + "name": "write_to_file", + "args": { + "path": "{TMP}/new/dir/w.txt", + "content": "héllo" + }, + "result": { + "status": "ok", + "bytes_written": 6 + } + }, + { + "name": "write_to_file", + "args": { + "path": "{TMP}/f.txt", + "content": "zz", + "overwrite": false + }, + "result": { + "error": "File {TMP}/f.txt exists and overwrite=false" + } + }, + { + "name": "replace_file_content", + "args": { + "path": "{TMP}/e.txt", + "target": "aa", + "replacement": "cc" + }, + "result": { + "status": "ok", + "replaced": true + } + }, + { + "name": "replace_file_content", + "args": { + "path": "{TMP}/e.txt", + "target": "nope", + "replacement": "cc" + }, + "result": { + "error": "Target string not found in {TMP}/e.txt" + } + }, + { + "name": "list_dir", + "args": { + "path": "{TMP}/ls" + }, + "result": { + "path": "{TMP}/ls", + "entries": [ + "a", + "b", + "c" + ] + } + }, + { + "name": "grep_search", + "args": { + "query": "needle", + "path": "{TMP}/g.txt" + }, + "result": { + "matches": "1:needle here\n" + } + }, + { + "name": "create_dir", + "args": { + "path": "{TMP}/made/deep" + }, + "result": { + "status": "ok", + "created": "{TMP}/made/deep" + } + }, + { + "name": "goal", + "args": { + "action": "milestone_done" + }, + "result": { + "status": "ok", + "goal_action": "milestone_done", + "milestone_done": true + } + }, + { + "name": "bogus", + "args": {}, + "result": { + "error": "Unknown tool: bogus" + } + } + ] +} \ No newline at end of file diff --git a/crates/aien-drive/tests/loop_stub.rs b/crates/aien-drive/tests/loop_stub.rs new file mode 100644 index 00000000..5ceace2c --- /dev/null +++ b/crates/aien-drive/tests/loop_stub.rs @@ -0,0 +1,136 @@ +//! One full tool-dispatch round trip against stub HTTP servers (issue #179 +//! acceptance test), plus the cortex write payload and the failure paths. + +use aien_drive::{run_directive, Config}; +use serde_json::Value; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// Serve `replies.len()` requests; each gets the next canned (status, body). +/// Returns the bound URL base and the captured request bodies. +fn stub(replies: Vec<(u16, String)>) -> (String, Arc>>) { + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", l.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(vec![])); + let s2 = seen.clone(); + std::thread::spawn(move || { + for (status, body) in replies { + let (mut sock, _) = l.accept().unwrap(); + let mut r = BufReader::new(sock.try_clone().unwrap()); + let mut len = 0usize; + loop { + let mut h = String::new(); + r.read_line(&mut h).unwrap(); + if h.trim().is_empty() { + break; + } + if let Some(v) = h.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap(); + } + } + let mut b = vec![0u8; len]; + r.read_exact(&mut b).unwrap(); + s2.lock().unwrap().push(String::from_utf8(b).unwrap()); + let _ = write!( + sock, + "HTTP/1.0 {status} X\r\nContent-Type: text/event-stream\r\n\r\n{body}" + ); + } + }); + (base, seen) +} + +fn sse(text: &str) -> String { + let chunk = serde_json::json!({"choices": [{"delta": {"content": text}}]}); + format!("data: {chunk}\n\ndata: [DONE]\n\n") +} + +fn cfg(endpoint: String, cortex: String) -> Config { + Config { + endpoint, + model: "m".into(), + cortex_endpoint: cortex, + cortex_space: "aien-sources".into(), + request_timeout: Duration::from_secs(10), + } +} + +#[test] +fn tool_round_trip_then_done() { + let t1 = "\n{\"name\": \"run_command\", \"arguments\": {\"command\": \"echo ROUNDTRIP_OK\"}}\n"; + let t2 = "{\"name\": \"goal\", \"arguments\": {\"action\": \"milestone_done\"}}"; + let (base, seen) = stub(vec![(200, sse(t1)), (200, sse(t2))]); + let ok = run_directive( + &cfg(format!("{base}/v1/chat/completions"), String::new()), + "do it", + 5, + ) + .unwrap(); + assert!(ok); + let reqs = seen.lock().unwrap(); + assert_eq!(reqs.len(), 2); + let second: Value = serde_json::from_str(&reqs[1]).unwrap(); + let last = second["messages"].as_array().unwrap().last().unwrap()["content"] + .as_str() + .unwrap() + .to_string(); + assert!( + last.contains(""), + "{last}" + ); + assert!(last.contains("ROUNDTRIP_OK"), "{last}"); + assert_eq!(second["stream"], true); +} + +#[test] +fn idle_reply_is_not_done() { + let (base, _) = stub(vec![(200, sse("just prose, no tools"))]); + assert!(!run_directive(&cfg(format!("{base}/x"), String::new()), "d", 5).unwrap()); +} + +#[test] +fn max_turns_without_done_is_not_done() { + let t = "{\"name\": \"list_dir\", \"arguments\": {\"path\": \".\"}}"; + let (base, seen) = stub(vec![(200, sse(t)), (200, sse(t))]); + assert!(!run_directive(&cfg(format!("{base}/x"), String::new()), "d", 2).unwrap()); + assert_eq!(seen.lock().unwrap().len(), 2); +} + +#[test] +fn http_error_and_dead_endpoint_are_errors() { + let (base, _) = stub(vec![(500, "boom".into())]); + assert!(run_directive(&cfg(format!("{base}/x"), String::new()), "d", 2).is_err()); + assert!(run_directive(&cfg("http://127.0.0.1:1/x".into(), String::new()), "d", 2).is_err()); +} + +#[test] +fn reasoning_only_tool_call_is_recovered_and_dashes_sanitized() { + let chunk = serde_json::json!({"choices": [{"delta": {"reasoning": "a\u{2014}b {\"name\":\"goal\",\"arguments\":{\"action\":\"done\"}}"}}]}); + let (base, seen) = stub(vec![(200, format!("data: {chunk}\n\ndata: [DONE]\n"))]); + assert!(run_directive(&cfg(format!("{base}/x"), String::new()), "d", 3).unwrap()); + assert_eq!(seen.lock().unwrap().len(), 1); +} + +#[test] +fn cortex_tool_posts_payload() { + let (cortex, seen) = stub(vec![(200, "{}".into())]); + let a = serde_json::json!({"action":"write","name":"n1","content":"c1","kind":"procedure"}); + let r = aien_drive::dispatch_tool(&cfg(String::new(), cortex), "cortex", &a); + assert_eq!(r["status"], "ok"); + assert_eq!(r["cortex_code"], 200); + let p: Value = serde_json::from_str(&seen.lock().unwrap()[0]).unwrap(); + assert_eq!(p["kind"], "entity"); + assert_eq!(p["value"]["canonicalName"], "n1"); + assert_eq!(p["value"]["space"], "aien-sources"); + assert_eq!(p["value"]["metadata"]["kind"], "procedure"); +} + +#[test] +fn run_command_bad_cwd_is_an_error_value() { + // An unknown cwd must come back as an error value, not a panic. + let a = serde_json::json!({"command": "true", "cwd": "/definitely/not/here"}); + let r = aien_drive::dispatch_tool(&cfg(String::new(), String::new()), "run_command", &a); + assert!(r.get("error").is_some(), "{r}"); +}