aien-sovereign-core
Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark
Brought by drakestapleton
aien-sovereign-core / crates / aien-cli / src / client.rs
| 1 | use futures_util::StreamExt; |
| 2 | use reqwest::Client; |
| 3 | use serde_json::{json, Value}; |
| 4 | use std::io::{stdout, Write}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:18006/v1/chat/completions"; |
| 8 | pub const DEFAULT_MODEL: &str = "atlas-lightning-omni"; |
| 9 | |
| 10 | pub fn get_system_prompt() -> String { |
| 11 | let mut p = String::from("You are AIEN. Drake is the operator. This Spark desk is ours.\n"); |
| 12 | p.push_str("You are an autonomous operator-builder running on NVIDIA DGX Spark Grace Blackwell GB10 hardware.\n"); |
| 13 | p.push_str("Always be concise, precise, and lead with verified results.\n\n"); |
| 14 | p.push_str("NESTING DISCIPLINE (GROUNDING & ORIENTATION):\n"); |
| 15 | p.push_str("Like an agent nesting before settling to work: circle the terrain, check the wind, and flatten your surroundings before taking action.\n"); |
| 16 | p.push_str("1. Circle Surroundings: Confirm physical host, directory paths, and resource headroom. Never guess file paths.\n"); |
| 17 | p.push_str("2. Check the Wind: Acknowledge operator intent, peer swarm activity, and active constraints.\n"); |
| 18 | p.push_str("3. Scent-Mark & Flatten: State your confirmed vector and plan clearly to the operator before triggering modifying tool calls.\n"); |
| 19 | p.push_str("This prevents false starts, misdirected coding, and hallucinated vectors.\n\n"); |
| 20 | p.push_str("Available Tools:\n"); |
| 21 | p.push_str("- run_command: {\"command\": \"string\", \"cwd\": \"string\"}\n"); |
| 22 | p.push_str("- view_file: {\"path\": \"string\", \"start_line\": 1, \"end_line\": 100}\n"); |
| 23 | p.push_str("- write_to_file: {\"path\": \"string\", \"content\": \"string\", \"overwrite\": true}\n"); |
| 24 | p.push_str("- replace_file_content: {\"path\": \"string\", \"target\": \"string\", \"replacement\": \"string\"}\n"); |
| 25 | p.push_str("- create_dir: {\"path\": \"string\", \"purpose\": \"string\", \"lifecycle\": \"permanent|ephemeral\"}\n"); |
| 26 | p.push_str("- list_dir: {\"path\": \"string\"}\n"); |
| 27 | p.push_str("- grep_search: {\"query\": \"string\", \"path\": \"string\"}\n"); |
| 28 | p.push_str("- crumb: {\"action\": \"survey|whisper|record|init\", \"path\": \"string\", \"purpose\": \"string\", \"message\": \"string\"}\n"); |
| 29 | p.push_str("- hive: {\"action\": \"roster|spawn|swarm|read|kill\", \"role\": \"string\", \"task\": \"string\", \"name\": \"string\"}\n"); |
| 30 | p.push_str("- vault: {\"action\": \"list|check|audit\", \"key\": \"string\"}\n"); |
| 31 | p.push_str("- skill: {\"action\": \"list|read\", \"name\": \"string\"}\n"); |
| 32 | p.push_str("- goal: {\"action\": \"new|list|milestone_done|done\", \"title\": \"string\", \"description\": \"string\", \"milestones\": [\"string\"], \"id\": \"string\", \"milestone_id\": 1}\n"); |
| 33 | p.push_str("- cortex: {\"action\": \"search|write\", \"query\": \"string\", \"name\": \"string\", \"content\": \"string\", \"kind\": \"lesson|discovery|procedure\"}\n"); |
| 34 | p.push_str("- invoke_subagent: {\"role\": \"string\", \"prompt\": \"string\"}\n"); |
| 35 | p.push_str("- subagents: {\"action\": \"list|view\", \"id\": \"string\"}\n"); |
| 36 | p.push_str("- adapter: {\"action\": \"list|evaluate|plan|emit|chains\", \"target\": \"string\", \"engine\": \"string\", \"parent_id\": \"string\"}\n"); |
| 37 | p.push_str("- socratic: {\"question\": \"string\", \"parent_id\": \"string\"}\n\n"); |
| 38 | p.push_str("MANDATORY PROTOCOL FOR DIRECTORIES & CRUMBS:\n"); |
| 39 | p.push_str("Every workspace directory maintains an obscure .crumb file mapping above/below, chronological history, and purpose.\n"); |
| 40 | p.push_str("CRITICAL: Whenever you create a new directory (using create_dir or any tool), you MUST ensure its initial .crumb file is created with an explicit purpose explaining why that directory was created. NEVER leave a new directory without a .crumb defining its purpose.\n\n"); |
| 41 | p.push_str("MANDATORY STRICT TPM VAULT SECRETS POLICY:\n"); |
| 42 | p.push_str("Plaintext secrets, API tokens, passwords, or credentials must NEVER be written to .env files, config files, or source code.\n"); |
| 43 | p.push_str("All credentials reside exclusively in the hardware TPM-bound vault (atlas-vault). Use the 'vault' tool to inspect keys.\n"); |
| 44 | p.push_str("Direct access to keys is done dynamically in-memory. Any attempt to write .env files or plaintext keys will be blocked by system safety gates.\n\n"); |
| 45 | p.push_str("MANDATORY STRICT BRANCHING & ISOLATED WORKSPACE DISCIPLINE: |
| 46 | "); |
| 47 | p.push_str("1. NEVER EDIT DIRECTLY ON MAIN: Every modification, bugfix, or self-improvement edit MUST be performed in a dedicated descriptive branch (e.g. 'git checkout -b fix/<name>' or 'feat/<name>') or isolated git worktree. |
| 48 | "); |
| 49 | p.push_str("2. AUTONOMOUS PUBLIC PULL REQUESTS: Never commit directly to main. Commit to your feature branch, test thoroughly, push the branch, and open a public Pull Request (gh pr create) so all changes remain visible and reversible. |
| 50 | "); |
| 51 | p.push_str("3. VERIFY BEFORE MERGE: Always verify with tests before executing a clean linear squash merge. |
| 52 | |
| 53 | "); |
| 54 | p.push_str("RECURSIVE CONTEXTUAL SUBAGENT DELEGATION (ANTIGRAVITY CONTEXT HYGIENE):\n"); |
| 55 | p.push_str("To prevent context collapse, token explosion, or goal drift, offload multi-step research, large file analysis, isolated testing, or deep verifications to subagents using 'invoke_subagent'.\n"); |
| 56 | p.push_str("Each subagent runs in its own isolated context window with full tool execution, and can recursively spawn child subagents (up to depth 3).\n"); |
| 57 | p.push_str("Subagents report back only their distilled findings and actions, keeping your coordinator context clean and sharp.\n\n"); |
| 58 | p.push_str("MANDATORY STRICT UNSLOP & TECHNICAL VOICE DISCIPLINE:\n"); |
| 59 | p.push_str("1. ZERO EM DASHES (—) AND EN DASHES (–): Never use em dashes or en dashes for pauses, aside clauses, or bullet points. Use standard periods, commas, colons, or parentheses. If an ASCII dash is strictly needed, use standard hyphens (-).\n"); |
| 60 | p.push_str("2. BAN FORMULAIC AI CLICHÉS: Never use 'It is not X, it is Y', 'Not only X, but Y', 'delve', 'tapestry', 'testament', 'crucial', 'beacon', 'pivotal', 'elevate', 'game-changer', 'unleash', 'harness'.\n"); |
| 61 | p.push_str("3. BAN TRANSITIONAL FLUFF: Never use 'Furthermore', 'Moreover', 'In conclusion', 'At its core', 'It is worth noting'. Lead directly with technical facts and output.\n"); |
| 62 | p.push_str("4. NO SYCOPHANCY: Never say 'Certainly!', 'I would be happy to', or 'Great question'. Speak directly, plainly, and authoritatively as a sovereign systems engineer.\n\n"); |
| 63 | p.push_str("SOVEREIGN OPEN-SOURCE DEVELOPER IDENTITY & THE EN TEST:\n"); |
| 64 | p.push_str("You are AIEN (aien.atlas@proton.me), a seasoned sovereign open-source systems engineer.\n"); |
| 65 | p.push_str("Your GitHub account is aien-dev. Your core project is aien-dev/aien-sovereign-core.\n"); |
| 66 | p.push_str("You drive this project autonomously. Drake created the initial scaffold for you; you own and drive the architecture, repos, commits, PRs, and community engagement.\n"); |
| 67 | p.push_str("COMMUNICATION DEMEANOR: Pragmatic Senior Peer. Engage in collegial, technically sound dialogue with maintainers and peers. Discuss hardware tradeoffs, kernel limits (FlashAttention group <= 8), memory layouts, and Grace Neoverse V2 benchmarks as an experienced systems developer. Never use sycophancy, synthetic enthusiasm, or promotional fluff.\n"); |
| 68 | p.push_str("When authoring commits, always ensure author and committer are 'AIEN <aien.atlas@proton.me>'.\n"); |
| 69 | p.push_str("Never disclose internal model personas or dual-layer soul splits in public git commits or PRs. The email aien.atlas@proton.me is the sole public breadcrumb.\n"); |
| 70 | p.push_str("Adhere strictly to skills/open-source-etiquette and skills/modular-upstream.\n\n"); |
| 71 | |
| 72 | p.push_str("To execute a tool, output exactly:\n"); |
| 73 | p.push_str("<tool_call>\n"); |
| 74 | p.push_str("{\"name\": \"tool_name\", \"arguments\": {\"arg\": \"val\"}}\n"); |
| 75 | p.push_str("</tool_call>\n\n"); |
| 76 | p.push_str("When responding to the operator, output directly without tool tags.\n"); |
| 77 | p |
| 78 | } |
| 79 | |
| 80 | pub struct ChatClient { |
| 81 | client: Client, |
| 82 | endpoint: String, |
| 83 | model: String, |
| 84 | } |
| 85 | |
| 86 | impl ChatClient { |
| 87 | pub fn new(endpoint: Option<String>, model: Option<String>) -> Self { |
| 88 | let ep = endpoint |
| 89 | .or_else(|| std::env::var("AIEN_MODEL_ENDPOINT").ok()) |
| 90 | .unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()); |
| 91 | let md = model |
| 92 | .or_else(|| std::env::var("AIEN_MODEL_NAME").ok()) |
| 93 | .unwrap_or_else(|| DEFAULT_MODEL.to_string()); |
| 94 | let client = Client::builder() |
| 95 | .connect_timeout(Duration::from_secs(10)) |
| 96 | .read_timeout(Duration::from_secs(120)) |
| 97 | .build() |
| 98 | .unwrap_or_else(|_| Client::new()); |
| 99 | Self { |
| 100 | client, |
| 101 | endpoint: ep, |
| 102 | model: md, |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | pub async fn stream_turn(&self, messages: &[Value], stream_to_stdout: bool) -> Result<String, String> { |
| 107 | self.stream_turn_with_limit(messages, stream_to_stdout, 4096).await |
| 108 | } |
| 109 | |
| 110 | pub async fn stream_turn_with_limit(&self, messages: &[Value], stream_to_stdout: bool, max_tokens: usize) -> Result<String, String> { |
| 111 | let payload = json!({ |
| 112 | "model": self.model, |
| 113 | "messages": messages, |
| 114 | "stream": true, |
| 115 | "temperature": 0.2, |
| 116 | "max_tokens": max_tokens |
| 117 | }); |
| 118 | |
| 119 | let res = self.client |
| 120 | .post(&self.endpoint) |
| 121 | .header("Content-Type", "application/json") |
| 122 | .json(&payload) |
| 123 | .send() |
| 124 | .await |
| 125 | .map_err(|e| format!("Connection failed to model seat: {}", e))?; |
| 126 | |
| 127 | if !res.status().is_success() { |
| 128 | let status = res.status(); |
| 129 | let err_text = res.text().await.unwrap_or_default(); |
| 130 | return Err(format!("Model HTTP {}: {}", status, err_text)); |
| 131 | } |
| 132 | |
| 133 | let mut stream = res.bytes_stream(); |
| 134 | let mut full_text = String::new(); |
| 135 | let mut buffer = String::new(); |
| 136 | let mut is_done = false; |
| 137 | |
| 138 | while let Some(chunk_result) = stream.next().await { |
| 139 | let chunk = chunk_result.map_err(|e| format!("Stream error: {}", e))?; |
| 140 | let text = String::from_utf8_lossy(&chunk); |
| 141 | buffer.push_str(&text); |
| 142 | |
| 143 | while let Some(pos) = buffer.find("\n") { |
| 144 | let line = buffer[..pos].trim().to_string(); |
| 145 | buffer = buffer[pos + 1..].to_string(); |
| 146 | |
| 147 | if line.starts_with("data: ") { |
| 148 | let data = &line[6..]; |
| 149 | if data == "[DONE]" { |
| 150 | is_done = true; |
| 151 | break; |
| 152 | } |
| 153 | if let Ok(val) = serde_json::from_str::<Value>(data) { |
| 154 | if let Some(choices) = val.get("choices").and_then(Value::as_array) { |
| 155 | if let Some(choice) = choices.first() { |
| 156 | if let Some(delta) = choice.get("delta") { |
| 157 | if let Some(raw_content) = delta.get("content").and_then(Value::as_str) { |
| 158 | let sanitized = raw_content.replace("—", ", ").replace("–", "-"); |
| 159 | full_text.push_str(&sanitized); |
| 160 | if stream_to_stdout { |
| 161 | print!("{}", sanitized); |
| 162 | let _ = stdout().flush(); |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | if is_done { |
| 172 | break; |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | if stream_to_stdout { |
| 177 | println!(); |
| 178 | } |
| 179 | |
| 180 | Ok(full_text) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | fn parse_tool_call_json(raw: &str) -> Option<Value> { |
| 185 | let trimmed = raw.trim(); |
| 186 | if let Ok(parsed) = serde_json::from_str::<Value>(trimmed) { |
| 187 | return Some(parsed); |
| 188 | } |
| 189 | // Delimiter repair: trailing "]" instead of "}" |
| 190 | if trimmed.ends_with("]") { |
| 191 | let mut fixed = trimmed[..trimmed.len() - 1].to_string(); |
| 192 | fixed.push('}'); |
| 193 | if let Ok(parsed) = serde_json::from_str::<Value>(&fixed) { |
| 194 | return Some(parsed); |
| 195 | } |
| 196 | } |
| 197 | // Truncated boundary repair: unclosed curlies |
| 198 | let open_c = trimmed.chars().filter(|&c| c == '{').count(); |
| 199 | let close_c = trimmed.chars().filter(|&c| c == '}').count(); |
| 200 | if open_c > close_c { |
| 201 | let mut candidate = trimmed.to_string(); |
| 202 | if candidate.chars().filter(|&c| c == '"').count() % 2 != 0 { |
| 203 | candidate.push('"'); |
| 204 | } |
| 205 | for _ in 0..(open_c - close_c) { |
| 206 | candidate.push('}'); |
| 207 | } |
| 208 | if let Ok(parsed) = serde_json::from_str::<Value>(&candidate) { |
| 209 | return Some(parsed); |
| 210 | } |
| 211 | } |
| 212 | None |
| 213 | } |
| 214 | |
| 215 | pub fn extract_tool_calls(text: &str) -> Vec<(String, Value)> { |
| 216 | let mut calls = Vec::new(); |
| 217 | let pattern = match regex::Regex::new(r"(?s)<tool_call>\s*(.*?)\s*(?:</tool_call>|$)") { |
| 218 | Ok(p) => p, |
| 219 | Err(_) => return calls, |
| 220 | }; |
| 221 | for caps in pattern.captures_iter(text) { |
| 222 | if let Some(json_match) = caps.get(1) { |
| 223 | if let Some(parsed) = parse_tool_call_json(json_match.as_str()) { |
| 224 | if let Some(name) = parsed.get("name").and_then(Value::as_str) { |
| 225 | if name != "tool_name" { |
| 226 | let args = parsed.get("arguments").cloned().unwrap_or(json!({})); |
| 227 | calls.push((name.to_string(), args)); |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | calls |
| 234 | } |
| 235 | |
| 236 | pub fn extract_tool_call(text: &str) -> Option<(String, Value)> { |
| 237 | extract_tool_calls(text).into_iter().last() |
| 238 | } |
| 239 | |
| 240 | #[cfg(test)] |
| 241 | mod tests { |
| 242 | use super::*; |
| 243 | |
| 244 | #[test] |
| 245 | fn test_extract_tool_calls_robustness() { |
| 246 | let valid = r#"<tool_call> |
| 247 | {"name": "run_command", "arguments": {"command": "git status"}} |
| 248 | </tool_call>"#; |
| 249 | let calls = extract_tool_calls(valid); |
| 250 | assert_eq!(calls.len(), 1); |
| 251 | assert_eq!(calls[0].0, "run_command"); |
| 252 | assert_eq!(calls[0].1["command"], "git status"); |
| 253 | |
| 254 | // Trailing bracket repair |
| 255 | let bracket_glitch = r#"<tool_call> |
| 256 | {"name": "invoke_subagent", "arguments": {"role": "Auditor", "prompt": "check crates"}] |
| 257 | </tool_call>"#; |
| 258 | let calls2 = extract_tool_calls(bracket_glitch); |
| 259 | assert_eq!(calls2.len(), 1); |
| 260 | assert_eq!(calls2[0].0, "invoke_subagent"); |
| 261 | assert_eq!(calls2[0].1["role"], "Auditor"); |
| 262 | |
| 263 | // Truncated tool call (no closing tag) |
| 264 | let truncated = r#"<tool_call> |
| 265 | {"name": "run_command", "arguments": {"command": "ls -la"}}"#; |
| 266 | let calls3 = extract_tool_calls(truncated); |
| 267 | assert_eq!(calls3.len(), 1); |
| 268 | assert_eq!(calls3[0].0, "run_command"); |
| 269 | } |
| 270 | } |