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-cli/src/client.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-cli / src / client.rs` 494 lines · 24234 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 use colored::Colorize; 17 use futures_util::StreamExt; 18 use reqwest::Client; 19 use serde_json::{json, Value}; 20 use std::io::{stdout, Write}; 21 use std::time::Duration; 22 23 pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:18006/v1/chat/completions"; 24 pub const DEFAULT_MODEL: &str = "atlas-lightning-omni"; 25 26 /// Explicit chat execution path. Native runtime is canonical. 27 /// The 18006 HTTP service remains only as a compatibility adapter. 28 #[derive(Debug, Clone, PartialEq, Eq)] 29 pub enum ChatBackend { 30 NativeRuntime, 31 RemoteAdapter(String), 32 } 33 34 pub fn resolve_chat_backend() -> ChatBackend { 35 if let Ok(mode) = std::env::var("AIEN_CHAT_BACKEND") { 36 let mode = mode.trim().to_lowercase(); 37 if mode == "remote" { 38 let ep = std::env::var("AIEN_MODEL_ENDPOINT") 39 .ok() 40 .filter(|s| !s.trim().is_empty()) 41 .unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()); 42 return ChatBackend::RemoteAdapter(ep); 43 } 44 if mode == "native" { 45 return ChatBackend::NativeRuntime; 46 } 47 } 48 let sock = aien_runtime::client::AienRuntimeClient::default_socket_path(); 49 if sock.exists() { 50 ChatBackend::NativeRuntime 51 } else { 52 ChatBackend::RemoteAdapter( 53 std::env::var("AIEN_MODEL_ENDPOINT") 54 .ok() 55 .filter(|s| !s.trim().is_empty()) 56 .unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()), 57 ) 58 } 59 } 60 61 pub fn describe_chat_backend(backend: &ChatBackend) -> String { 62 match backend { 63 ChatBackend::NativeRuntime => "native runtime (canonical)".to_string(), 64 ChatBackend::RemoteAdapter(ep) => format!("remote adapter (compatibility): {}", ep), 65 } 66 } 67 68 /// Structured per request telemetry. A benchmark or test is only evidence of 69 /// the native runtime when path is native_runtime. Adapter traffic must never 70 /// be mistaken for native success. 71 pub fn emit_chat_telemetry(backend: &ChatBackend, model: &str) { 72 let (path, endpoint) = match backend { 73 ChatBackend::NativeRuntime => ("native_runtime", ""), 74 ChatBackend::RemoteAdapter(ep) => ("remote_adapter", ep.as_str()), 75 }; 76 let runtime_socket_present = 77 aien_runtime::client::AienRuntimeClient::default_socket_path().exists(); 78 let require_blackwell = std::env::var("AIEN_REQUIRE_BLACKWELL") 79 .map(|v| v.trim() == "1" || v.trim().eq_ignore_ascii_case("true")) 80 .unwrap_or(false); 81 let record = serde_json::json!({ 82 "event": "chat_path", 83 "path": path, 84 "backend": describe_chat_backend(backend), 85 "endpoint": endpoint, 86 "model": model, 87 "runtime_socket_present": runtime_socket_present, 88 "require_blackwell": require_blackwell, 89 }); 90 eprintln!("{}", record); 91 } 92 93 pub fn get_system_prompt() -> String { 94 let mut p = String::from("You are AIEN. Drake is the operator. This Spark desk is ours.\n"); 95 p.push_str("You are an autonomous operator-builder running on NVIDIA DGX Spark Grace Blackwell GB10 hardware.\n"); 96 p.push_str("Always be concise, precise, and lead with verified results.\n\n"); 97 p.push_str("NESTING DISCIPLINE (GROUNDING & ORIENTATION):\n"); 98 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"); 99 p.push_str("1. Circle Surroundings: Confirm physical host, directory paths, and resource headroom. Never guess file paths.\n"); 100 p.push_str("2. Check the Wind: Acknowledge operator intent, peer swarm activity, and active constraints.\n"); 101 p.push_str("3. Scent-Mark & Flatten: State your confirmed vector and plan clearly to the operator before triggering modifying tool calls.\n"); 102 p.push_str("This prevents false starts, misdirected coding, and hallucinated vectors.\n\n"); 103 p.push_str("Available Tools:\n"); 104 p.push_str("- run_command: {\"command\": \"string\", \"cwd\": \"string\"}\n"); 105 p.push_str("- view_file: {\"path\": \"string\", \"start_line\": 1, \"end_line\": 100}\n"); 106 p.push_str( 107 "- write_to_file: {\"path\": \"string\", \"content\": \"string\", \"overwrite\": true}\n", 108 ); 109 p.push_str("- replace_file_content: {\"path\": \"string\", \"target\": \"string\", \"replacement\": \"string\"}\n"); 110 p.push_str("- create_dir: {\"path\": \"string\", \"purpose\": \"string\", \"lifecycle\": \"permanent|ephemeral\"}\n"); 111 p.push_str("- list_dir: {\"path\": \"string\"}\n"); 112 p.push_str("- grep_search: {\"query\": \"string\", \"path\": \"string\"}\n"); 113 p.push_str("- crumb: {\"action\": \"survey|whisper|record|init\", \"path\": \"string\", \"purpose\": \"string\", \"message\": \"string\"}\n"); 114 p.push_str("- hive: {\"action\": \"roster|spawn|swarm|read|kill\", \"role\": \"string\", \"task\": \"string\", \"name\": \"string\"}\n"); 115 p.push_str("- vault: {\"action\": \"list|check|audit\", \"key\": \"string\"}\n"); 116 p.push_str("- skill: {\"action\": \"discover|preview|search|full\", \"name\": \"one skill name\", \"query\": \"targeted terms\", \"max_tokens\": 96}\n"); 117 p.push_str("- context7: {\"action\": \"resolve|query\", \"library\": \"package or product name\", \"library_id\": \"/org/project\", \"query\": \"one specific question\"}\n"); 118 p.push_str("- goal: {\"action\": \"new|list|milestone_done|done\", \"title\": \"string\", \"description\": \"string\", \"milestones\": [\"string\"], \"id\": \"string\", \"milestone_id\": 1}\n"); 119 p.push_str("- cortex: {\"action\": \"search|write\", \"query\": \"string\", \"name\": \"string\", \"content\": \"string\", \"kind\": \"lesson|discovery|procedure\"}\n"); 120 p.push_str("- invoke_subagent: {\"role\": \"string\", \"prompt\": \"string\"}\n"); 121 p.push_str("- subagents: {\"action\": \"list|view\", \"id\": \"string\"}\n"); 122 p.push_str("- adapter: {\"action\": \"list|evaluate|plan|emit|chains\", \"target\": \"string\", \"engine\": \"string\", \"parent_id\": \"string\"}\n"); 123 p.push_str("- socratic: {\"question\": \"string\", \"parent_id\": \"string\"}\n\n"); 124 p.push_str("MANDATORY PROTOCOL FOR DIRECTORIES & CRUMBS:\n"); 125 p.push_str("Every workspace directory maintains an obscure .crumb file mapping above/below, chronological history, and purpose.\n"); 126 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"); 127 p.push_str("MANDATORY STRICT TPM VAULT SECRETS POLICY:\n"); 128 p.push_str("Plaintext secrets, API tokens, passwords, or credentials must NEVER be written to .env files, config files, or source code.\n"); 129 p.push_str("All credentials reside exclusively in the hardware TPM-bound vault (atlas-vault). Use the 'vault' tool to inspect keys.\n"); 130 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"); 131 p.push_str( 132 "MANDATORY STRICT BRANCHING & ISOLATED WORKSPACE DISCIPLINE: 133 ", 134 ); 135 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/' or 'feat/') or isolated git worktree. 136 "); 137 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. 138 "); 139 p.push_str("3. VERIFY BEFORE MERGE: Always verify with tests before executing a clean linear squash merge. 140 141 "); 142 p.push_str("RECURSIVE CONTEXTUAL SUBAGENT DELEGATION (ANTIGRAVITY CONTEXT HYGIENE):\n"); 143 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"); 144 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"); 145 p.push_str("Subagents report back only their distilled findings and actions, keeping your coordinator context clean and sharp.\n\n"); 146 p.push_str("MANDATORY STRICT UNSLOP & TECHNICAL VOICE DISCIPLINE:\n"); 147 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"); 148 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"); 149 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"); 150 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"); 151 p.push_str("SOVEREIGN OPEN-SOURCE DEVELOPER IDENTITY & THE EN TEST:\n"); 152 p.push_str( 153 "You are AIEN (aien@aienos.com), a seasoned sovereign open-source systems engineer.\n", 154 ); 155 p.push_str( 156 "Your GitHub account is aien-dev. Your core project is aien-dev/aien-sovereign-core.\n", 157 ); 158 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"); 159 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"); 160 p.push_str("When authoring commits, always ensure author and committer are 'AIEN '.\n"); 161 p.push_str("Never disclose internal model personas or dual-layer soul splits in public git commits or PRs. The email aien@aienos.com is the sole public breadcrumb.\n"); 162 p.push_str("Adhere strictly to skills/open-source-etiquette.\n\n"); 163 164 p.push_str("CONTEXT EFFICIENCY:\n"); 165 p.push_str("Use the context7 tool first for current external library, framework, SDK, and CLI documentation. Resolve a library, then query one question. Do not load a broad local skill for facts that context7 can retrieve directly.\n"); 166 p.push_str("For local skills, discover by task, preview exactly one skill, then search inside it. Request full skill context only when the preview and targeted search cannot answer the task.\n\n"); 167 168 p.push_str("To execute a tool, output exactly:\n"); 169 p.push_str("\n"); 170 p.push_str("{\"name\": \"tool_name\", \"arguments\": {\"arg\": \"val\"}}\n"); 171 p.push_str("\n\n"); 172 p.push_str("When responding to the operator, output directly without tool tags.\n\n"); 173 p.push_str(&crate::skills::format_skills_progressive_summary()); 174 p 175 } 176 177 pub struct ChatClient { 178 client: Client, 179 endpoint: String, 180 model: String, 181 backend: ChatBackend, 182 } 183 184 impl ChatClient { 185 pub fn new(endpoint: Option, model: Option) -> Self { 186 let explicit_endpoint = endpoint.is_some(); 187 let ep = endpoint 188 .or_else(|| std::env::var("AIEN_MODEL_ENDPOINT").ok()) 189 .unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()); 190 let md = model 191 .or_else(|| std::env::var("AIEN_MODEL_NAME").ok()) 192 .unwrap_or_else(|| DEFAULT_MODEL.to_string()); 193 let backend = if explicit_endpoint { 194 ChatBackend::RemoteAdapter(ep.clone()) 195 } else { 196 resolve_chat_backend() 197 }; 198 let client = Client::builder() 199 .connect_timeout(Duration::from_secs(10)) 200 .read_timeout(Duration::from_secs(120)) 201 .build() 202 .unwrap_or_else(|_| Client::new()); 203 Self { 204 client, 205 endpoint: ep, 206 model: md, 207 backend, 208 } 209 } 210 211 pub async fn stream_turn( 212 &self, 213 messages: &[Value], 214 stream_to_stdout: bool, 215 ) -> Result { 216 self.stream_turn_with_limit(messages, stream_to_stdout, 4096) 217 .await 218 } 219 220 pub async fn stream_turn_with_limit( 221 &self, 222 messages: &[Value], 223 stream_to_stdout: bool, 224 max_tokens: usize, 225 ) -> Result { 226 emit_chat_telemetry(&self.backend, &self.model); 227 if matches!(self.backend, ChatBackend::NativeRuntime) { 228 return self 229 .stream_native(messages, stream_to_stdout, max_tokens) 230 .await; 231 } 232 self.stream_remote(messages, stream_to_stdout, max_tokens) 233 .await 234 } 235 236 async fn stream_native( 237 &self, 238 messages: &[Value], 239 stream_to_stdout: bool, 240 max_tokens: usize, 241 ) -> Result { 242 let turns = messages 243 .iter() 244 .filter_map(|message| { 245 let role = message.get("role")?.as_str()?.to_string(); 246 let content = message.get("content")?.as_str()?.to_string(); 247 Some(aien_runtime::control::ChatTurn { role, content }) 248 }) 249 .collect(); 250 let client = aien_runtime::client::AienRuntimeClient::default_client(); 251 let text = client.stream_turn(turns, max_tokens, 0.2).await?; 252 if stream_to_stdout { 253 print!("{}", text); 254 let _ = stdout().flush(); 255 } 256 Ok(text) 257 } 258 259 async fn stream_remote( 260 &self, 261 messages: &[Value], 262 stream_to_stdout: bool, 263 max_tokens: usize, 264 ) -> Result { 265 let payload = json!({ 266 "model": self.model, 267 "messages": messages, 268 "stream": true, 269 "temperature": 0.2, 270 "max_tokens": max_tokens 271 }); 272 273 let res = self 274 .client 275 .post(&self.endpoint) 276 .header("Content-Type", "application/json") 277 .json(&payload) 278 .send() 279 .await 280 .map_err(|e| format!("Connection failed to model seat: {}", e))?; 281 282 if !res.status().is_success() { 283 let status = res.status(); 284 let err_text = res.text().await.unwrap_or_default(); 285 return Err(format!("Model HTTP {}: {}", status, err_text)); 286 } 287 288 let mut stream = res.bytes_stream(); 289 let mut full_text = String::new(); 290 let mut buffer = String::new(); 291 let mut is_done = false; 292 let mut in_thinking = false; 293 294 while let Some(chunk_result) = stream.next().await { 295 let chunk = chunk_result.map_err(|e| format!("Stream error: {}", e))?; 296 let text = String::from_utf8_lossy(&chunk); 297 buffer.push_str(&text); 298 299 while let Some(pos) = buffer.find("\n") { 300 let line = buffer[..pos].trim().to_string(); 301 buffer = buffer[pos + 1..].to_string(); 302 303 if let Some(data) = line.strip_prefix("data: ") { 304 if data == "[DONE]" { 305 is_done = true; 306 break; 307 } 308 if let Ok(val) = serde_json::from_str::(data) { 309 if let Some(choices) = val.get("choices").and_then(Value::as_array) { 310 if let Some(choice) = choices.first() { 311 if let Some(reason) = 312 choice.get("finish_reason").and_then(Value::as_str) 313 { 314 if !matches!(reason, "stop" | "tool_calls" | "function_call") { 315 return Err(format!( 316 "Model turn did not complete: finish_reason {}", 317 reason 318 )); 319 } 320 } 321 if let Some(delta) = choice.get("delta") { 322 if let Some(reasoning) = delta 323 .get("reasoning") 324 .or_else(|| delta.get("reasoning_content")) 325 .and_then(Value::as_str) 326 { 327 let sanitized = 328 reasoning.replace("—", ", ").replace("–", "-"); 329 if stream_to_stdout { 330 if !in_thinking { 331 print!("{}", "\n[Thinking] ".magenta().dimmed()); 332 in_thinking = true; 333 } 334 print!("{}", sanitized.dimmed()); 335 let _ = stdout().flush(); 336 } 337 } 338 if let Some(raw_content) = 339 delta.get("content").and_then(Value::as_str) 340 { 341 if in_thinking { 342 if stream_to_stdout { 343 print!("\n\n"); 344 let _ = stdout().flush(); 345 } 346 in_thinking = false; 347 } 348 let sanitized = 349 raw_content.replace("—", ", ").replace("–", "-"); 350 full_text.push_str(&sanitized); 351 if stream_to_stdout { 352 print!("{}", sanitized); 353 let _ = stdout().flush(); 354 } 355 } 356 } 357 } 358 } 359 } 360 } 361 } 362 if is_done { 363 break; 364 } 365 } 366 367 if stream_to_stdout { 368 println!(); 369 } 370 if !is_done { 371 return Err("Model stream ended before [DONE]".into()); 372 } 373 374 Ok(full_text) 375 } 376 } 377 378 fn parse_tool_call_json(raw: &str) -> Result<(String, Value), String> { 379 let parsed: Value = serde_json::from_str(raw.trim()) 380 .map_err(|error| format!("Malformed tool call: {}", error))?; 381 let name = parsed 382 .get("name") 383 .and_then(Value::as_str) 384 .filter(|name| !name.trim().is_empty() && *name != "tool_name") 385 .ok_or_else(|| "Malformed tool call: missing or invalid name".to_string())?; 386 let args = parsed 387 .get("arguments") 388 .cloned() 389 .unwrap_or_else(|| json!({})); 390 if !args.is_object() { 391 return Err("Malformed tool call: arguments must be an object".into()); 392 } 393 Ok((name.to_string(), args)) 394 } 395 396 fn fenced_tool_call(block: &str) -> Option<&str> { 397 let block = block.trim(); 398 let (explicit, raw) = if let Some(raw) = block.strip_prefix("tool_call") { 399 (true, raw) 400 } else { 401 (false, block.strip_prefix("json").unwrap_or(block)) 402 }; 403 (explicit || (raw.trim_start().starts_with('{') && raw.contains("\"name\""))).then_some(raw) 404 } 405 406 /// Parse tool requests without treating malformed markup as final synthesis. 407 pub fn extract_tool_calls(text: &str) -> Result, String> { 408 let mut calls = Vec::new(); 409 let mut remaining = text; 410 while let Some((prefix, after)) = remaining.split_once("') 416 .ok_or_else(|| "Malformed tool call: invalid opening tag".to_string())?; 417 let (raw, rest) = after 418 .split_once("") 419 .ok_or_else(|| "Malformed tool call: missing closing tag".to_string())?; 420 calls.push(parse_tool_call_json(raw)?); 421 remaining = rest; 422 } 423 if remaining.contains(" 455 {"name": "run_command", "arguments": {"command": "git status"}} 456 "#; 457 let calls = extract_tool_calls(valid).unwrap(); 458 assert_eq!(calls.len(), 1); 459 assert_eq!(calls[0].0, "run_command"); 460 assert_eq!(calls[0].1["command"], "git status"); 461 462 // Malformed JSON is evidence of an invalid request, not repairable success. 463 let bracket_glitch = r#" 464 {"name": "invoke_subagent", "arguments": {"role": "Auditor", "prompt": "check crates"}] 465 "#; 466 assert!(extract_tool_calls(bracket_glitch).is_err()); 467 468 // An incomplete tag must not be executed or treated as final synthesis. 469 let truncated = r#" 470 {"name": "run_command", "arguments": {"command": "ls -la"}}"#; 471 assert!(extract_tool_calls(truncated).is_err()); 472 } 473 474 #[tokio::test] 475 async fn native_chat_uses_the_runtime_socket_not_http() { 476 let sock = 477 std::env::temp_dir().join(format!("aien-missing-runtime-{}.sock", std::process::id())); 478 std::env::set_var("AIEN_CHAT_BACKEND", "native"); 479 std::env::set_var("AIEN_RUNTIME_SOCK", &sock); 480 let client = ChatClient::new(None, Some("tinyllama".into())); 481 let err = client 482 .stream_turn_with_limit(&[], false, 8) 483 .await 484 .expect_err("missing socket must fail closed"); 485 assert!( 486 err.contains("runtime socket"), 487 "native path must name the runtime socket, got {err}" 488 ); 489 assert!( 490 !err.contains("18006"), 491 "native path must not fall through to the HTTP seat, got {err}" 492 ); 493 } 494 }