interplane.Get Omega
Read in your language

aien-sovereign-core

Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core / crates / aien-cli / src / cortex.rs

234 lines · 10339 bytes Raw Blame History
1use reqwest::Client;
2use serde_json::{json, Value};
3use std::fs;
4use std::path::Path;
5use colored::*;
6
7const CORTEX_BASE_URL: &str = "http://127.0.0.1:18080";
8const CORTEX_TOKEN_PATH: &str = "/home/drakestapleton/.config/cortex/token";
9
10pub fn get_cortex_token() -> String {
11 let p = Path::new(CORTEX_TOKEN_PATH);
12 if p.exists() {
13 fs::read_to_string(p).unwrap_or_default().trim().to_string()
14 } else {
15 String::new()
16 }
17}
18
19pub async fn write_to_cortex(canonical_name: &str, content: &str, entity_type: &str, metadata: Value) -> Result<Value, String> {
20 let token = get_cortex_token();
21 if token.is_empty() {
22 return Err("Missing Cortex token in ~/.config/cortex/token".to_string());
23 }
24
25 let et = if entity_type.is_empty() { "discovery" } else { entity_type };
26 let payload = json!({
27 "kind": "entity",
28 "value": {
29 "space": "atlas-memory",
30 "entityType": et,
31 "canonicalName": canonical_name,
32 "content": content,
33 "metadata": metadata,
34 }
35 });
36
37 let client = Client::new();
38 let resp = client.post(format!("{}/api/cortex/write", CORTEX_BASE_URL))
39 .header("Authorization", format!("Bearer {}", token))
40 .header("Content-Type", "application/json")
41 .header("Accept", "application/json")
42 .json(&payload)
43 .send()
44 .await
45 .map_err(|e| format!("Failed to connect to Cortex (18080): {}", e))?;
46
47 if !resp.status().is_success() {
48 let status = resp.status();
49 let body = resp.text().await.unwrap_or_default();
50 return Err(format!("Cortex write failed [{}]: {}", status, body));
51 }
52
53 let res_json = resp.json::<Value>().await.map_err(|e| format!("Invalid JSON response: {}", e))?;
54 Ok(res_json)
55}
56
57pub async fn search_cortex(query: &str, limit: usize) -> Result<Vec<Value>, String> {
58 let token = get_cortex_token();
59 let url = format!("{}/api/cortex/search?q={}&space=atlas-memory&limit={}", CORTEX_BASE_URL, query.replace(" ", "%20"), limit);
60 let client = Client::new();
61 let mut req = client.get(&url).header("Accept", "application/json");
62 if !token.is_empty() {
63 req = req.header("Authorization", format!("Bearer {}", token));
64 }
65
66 let resp = req.send().await.map_err(|e| format!("Cortex connection failed: {}", e))?;
67 if let Ok(data) = resp.json::<Value>().await {
68 if let Some(arr) = data.get("results").and_then(Value::as_array) {
69 return Ok(arr.clone());
70 }
71 }
72 Ok(Vec::new())
73}
74
75/// Automatically assembles relevant memories and procedures from Spark Cortex based on active task context.
76pub async fn assemble_cortex_recall(query: &str, limit: usize) -> Option<String> {
77 let trimmed = query.trim();
78 if trimmed.len() < 3 {
79 return None;
80 }
81
82 // Clean query: take first 150 chars or first line to avoid giant search strings
83 let clean_query = if let Some(idx) = trimmed.find('\n') {
84 &trimmed[..idx]
85 } else if trimmed.len() > 150 {
86 &trimmed[..150]
87 } else {
88 trimmed
89 };
90
91 match search_cortex(clean_query, limit).await {
92 Ok(items) if !items.is_empty() => {
93 let mut recall_entries = Vec::new();
94 for it in items {
95 let name = it.get("canonicalName").and_then(Value::as_str).unwrap_or("Untitled");
96 let score = it.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
97 let content = it.get("content").and_then(Value::as_str).unwrap_or("");
98 let kind = it.get("entityType").and_then(Value::as_str).unwrap_or("memory");
99
100 if score >= 0.05 {
101 let snippet = if content.len() > 300 { &content[..300] } else { content };
102 recall_entries.push(format!("• [{}] {} (relevance: {:.2}):\n {}", kind, name, score, snippet.trim()));
103 }
104 }
105
106 if recall_entries.is_empty() {
107 return None;
108 }
109
110 Some(format!(
111 "<cortex-recall>\nVerified durable knowledge recalled from Spark Cortex:\n{}\n</cortex-recall>",
112 recall_entries.join("\n")
113 ))
114 }
115 _ => None,
116 }
117}
118
119/// Asynchronously capture an action outcome or lesson into Spark Cortex without blocking execution.
120pub fn trigger_background_capture(action: &str, target: &str, details: &str) {
121 let action_owned = action.to_string();
122 let target_owned = target.to_string();
123 let details_owned = details.to_string();
124
125 tokio::spawn(async move {
126 let canonical_name = format!("discovery-{}-{}", action_owned.replace(" ", "-"), chrono::Utc::now().timestamp());
127 let content = format!("Autonomous action '{}' executed on target '{}'. Summary: {}", action_owned, target_owned, details_owned);
128 let metadata = json!({
129 "source": "aien-cli-auto-capture",
130 "action": action_owned,
131 "target": target_owned,
132 "timestamp": chrono::Utc::now().to_rfc3339()
133 });
134 let _ = write_to_cortex(&canonical_name, &content, "discovery", metadata).await;
135 });
136}
137
138pub async fn handle_cortex_command(parts: &[&str]) {
139 if parts.is_empty() {
140 println!("Usage: /cortex [search <query> | write <name> | <content>]");
141 return;
142 }
143
144 match parts[0] {
145 "search" | "find" => {
146 let q = parts[1..].join(" ");
147 println!("{}", format!("Searching Cortex (atlas-memory) for '{}'...", q).yellow());
148 match search_cortex(&q, 5).await {
149 Ok(items) if !items.is_empty() => {
150 println!("{}", format!("\nCortex Knowledge Recall ({} found):", items.len()).cyan().bold());
151 for (i, it) in items.iter().enumerate() {
152 let name = it.get("canonicalName").and_then(Value::as_str).unwrap_or("Untitled");
153 let score = it.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
154 let content = it.get("content").and_then(Value::as_str).unwrap_or("");
155 let snippet = if content.len() > 180 { &content[..180] } else { content };
156 println!("{}. {} ({:.2})", i + 1, name.bold().yellow(), score);
157 println!(" {}\n", snippet.dimmed());
158 }
159 },
160 Ok(_) => println!("{}", "No matching entities found in atlas-memory.".dimmed()),
161 Err(e) => println!("{}", format!("Error querying Cortex: {}", e).red()),
162 }
163 },
164 "write" | "remember" => {
165 let full_text = parts[1..].join(" ");
166 let split: Vec<&str> = full_text.split('|').collect();
167 if split.len() < 2 {
168 println!("Usage: /cortex write <canonical_name> | <content>");
169 return;
170 }
171 let name = split[0].trim();
172 let content = split[1..].join("|").trim().to_string();
173
174 println!("{}", format!("Committing memory entity '{}' to Spark Cortex...", name).yellow());
175 match write_to_cortex(name, &content, "lesson", json!({"source": "aien-cli", "author": "operator"})).await {
176 Ok(res) => {
177 let r_id = res.get("receipt").and_then(|r| r.get("id")).and_then(Value::as_str).unwrap_or("confirmed");
178 println!("{}", format!("✓ Committed to Spark Cortex Memory! Receipt: {}", r_id).green().bold());
179 },
180 Err(e) => println!("{}", format!("Failed to commit to Cortex: {}", e).red().bold()),
181 }
182 },
183 _ => {
184 let q = parts.join(" ");
185 println!("{}", format!("Searching Cortex (atlas-memory) for '{}'...", q).yellow());
186 match search_cortex(&q, 5).await {
187 Ok(items) if !items.is_empty() => {
188 println!("{}", format!("\nCortex Knowledge Recall ({} found):", items.len()).cyan().bold());
189 for (i, it) in items.iter().enumerate() {
190 let name = it.get("canonicalName").and_then(Value::as_str).unwrap_or("Untitled");
191 let score = it.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
192 let content = it.get("content").and_then(Value::as_str).unwrap_or("");
193 let snippet = if content.len() > 180 { &content[..180] } else { content };
194 println!("{}. {} ({:.2})", i + 1, name.bold().yellow(), score);
195 println!(" {}\n", snippet.dimmed());
196 }
197 },
198 Ok(_) => println!("{}", "No matching entities found in atlas-memory.".dimmed()),
199 Err(e) => println!("{}", format!("Error querying Cortex: {}", e).red()),
200 }
201 }
202 }
203}
204
205pub async fn cortex_dispatch_tool(args: &Value) -> Value {
206 let action = args.get("action").and_then(Value::as_str).unwrap_or("search");
207
208 match action {
209 "write" | "remember" => {
210 let name = args.get("name").and_then(Value::as_str).unwrap_or("unnamed_memory");
211 let content = args.get("content").and_then(Value::as_str).unwrap_or("");
212 let kind = args.get("kind").and_then(Value::as_str).unwrap_or("discovery");
213 let meta = args.get("metadata").cloned().unwrap_or(json!({"source": "model_dispatch"}));
214
215 match write_to_cortex(name, content, kind, meta).await {
216 Ok(receipt) => json!({
217 "status": "ok",
218 "receipt": receipt,
219 "message": format!("Committed '{}' to Spark Cortex (atlas-memory).", name)
220 }),
221 Err(e) => json!({"status": "error", "error": e})
222 }
223 },
224 "search" => {
225 let q = args.get("query").and_then(Value::as_str).unwrap_or("");
226 let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(5) as usize;
227 match search_cortex(q, limit).await {
228 Ok(results) => json!({"status": "ok", "results": results}),
229 Err(e) => json!({"status": "error", "error": e})
230 }
231 },
232 _ => json!({"error": format!("Unknown cortex action '{}'", action)})
233 }
234}