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 / hooks.rs

257 lines · 8494 bytes Raw Blame History
1use async_trait::async_trait;
2use serde_json::{json, Value};
3use std::sync::Arc;
4
5#[async_trait]
6pub trait AgentHook: Send + Sync {
7 fn name(&self) -> &'static str;
8
9 async fn pre_turn(&self, _prompt: &mut String) -> Result<(), String> {
10 Ok(())
11 }
12
13 async fn post_turn(&self, _response: &mut String) {}
14
15 async fn pre_tool(&self, _tool: &str, _args: &mut Value) -> Result<Option<Value>, String> {
16 Ok(None)
17 }
18
19 async fn post_tool(&self, _tool: &str, _args: &Value, _result: &mut Value) {}
20
21 async fn on_tool_error(&self, _tool: &str, _args: &Value, _error: &str) -> Option<Value> {
22 None
23 }
24
25 async fn on_compaction(&self, _messages: &mut Vec<Value>) {}
26}
27
28#[derive(Default)]
29pub struct HookRegistry {
30 hooks: Vec<Arc<dyn AgentHook>>,
31}
32
33impl HookRegistry {
34 pub fn new() -> Self {
35 Self { hooks: Vec::new() }
36 }
37
38 pub fn register(&mut self, hook: Arc<dyn AgentHook>) {
39 self.hooks.push(hook);
40 }
41
42 pub async fn run_pre_turn(&self, prompt: &mut String) -> Result<(), String> {
43 for h in &self.hooks {
44 h.pre_turn(prompt).await?;
45 }
46 Ok(())
47 }
48
49 pub async fn run_post_turn(&self, response: &mut String) {
50 for h in &self.hooks {
51 h.post_turn(response).await;
52 }
53 }
54
55 pub async fn run_pre_tool(&self, tool: &str, args: &mut Value) -> Result<Option<Value>, String> {
56 for h in &self.hooks {
57 if let Some(short_circuit) = h.pre_tool(tool, args).await? {
58 return Ok(Some(short_circuit));
59 }
60 }
61 Ok(None)
62 }
63
64 pub async fn run_post_tool(&self, tool: &str, args: &Value, result: &mut Value) {
65 for h in &self.hooks {
66 h.post_tool(tool, args, result).await;
67 }
68 }
69
70 pub async fn run_on_tool_error(&self, tool: &str, args: &Value, error: &str) -> Option<Value> {
71 for h in &self.hooks {
72 if let Some(recovery) = h.on_tool_error(tool, args, error).await {
73 return Some(recovery);
74 }
75 }
76 None
77 }
78
79 pub async fn run_on_compaction(&self, messages: &mut Vec<Value>) {
80 for h in &self.hooks {
81 h.on_compaction(messages).await;
82 }
83 }
84
85 pub fn default_sovereign_registry() -> Self {
86 let mut reg = Self::new();
87 reg.register(Arc::new(UnslopHook));
88 reg.register(Arc::new(VaultRedactionHook));
89 reg.register(Arc::new(CrumbAutoTrackingHook));
90 reg.register(Arc::new(CompilerDiagnosticsHook));
91 reg.register(Arc::new(CortexRecallHook));
92 reg.register(Arc::new(CortexLearningCaptureHook));
93 reg
94 }
95}
96
97// ==========================================
98// Standard Sovereign Hooks
99// ==========================================
100
101/// 1. Unslop Hook: Enforces strict sovereign voice and wipes em dashes and en dashes
102pub struct UnslopHook;
103
104#[async_trait]
105impl AgentHook for UnslopHook {
106 fn name(&self) -> &'static str {
107 "UnslopHook"
108 }
109
110 async fn post_turn(&self, response: &mut String) {
111 let sanitized = response.replace('—', ", ").replace('–', "-");
112 *response = sanitized;
113 }
114}
115
116/// 2. Vault Redaction Hook: Scans and redacts credentials before outputs persist
117pub struct VaultRedactionHook;
118
119#[async_trait]
120impl AgentHook for VaultRedactionHook {
121 fn name(&self) -> &'static str {
122 "VaultRedactionHook"
123 }
124
125 async fn post_turn(&self, response: &mut String) {
126 *response = crate::vault::redact_secrets(response);
127 }
128
129 async fn post_tool(&self, _tool: &str, _args: &Value, result: &mut Value) {
130 if let Some(s) = result.as_str() {
131 *result = json!(crate::vault::redact_secrets(s));
132 } else if let Some(obj) = result.as_object_mut() {
133 for val in obj.values_mut() {
134 if let Some(s) = val.as_str() {
135 *val = json!(crate::vault::redact_secrets(s));
136 }
137 }
138 }
139 }
140}
141
142/// 3. Crumb Auto Tracking Hook: Ensures new directories have a .crumb with explicit purpose
143pub struct CrumbAutoTrackingHook;
144
145#[async_trait]
146impl AgentHook for CrumbAutoTrackingHook {
147 fn name(&self) -> &'static str {
148 "CrumbAutoTrackingHook"
149 }
150
151 async fn post_tool(&self, tool: &str, args: &Value, result: &mut Value) {
152 if tool == "create_dir" {
153 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
154 let purpose = args.get("purpose").and_then(Value::as_str).unwrap_or("Directory created during autonomous execution.");
155 if !path.is_empty() {
156 let _ = crate::crumbs::record_directory_crumb("AIEN", "session-hook", std::path::Path::new(path), "create_dir", purpose, "scaffold");
157 if let Some(obj) = result.as_object_mut() {
158 obj.insert("crumb_logged".to_string(), json!(true));
159 }
160 }
161 }
162 }
163}
164
165/// 4. Compiler Diagnostics Hook: Enriches cargo/rustc build failures with structured guidance
166pub struct CompilerDiagnosticsHook;
167
168#[async_trait]
169impl AgentHook for CompilerDiagnosticsHook {
170 fn name(&self) -> &'static str {
171 "CompilerDiagnosticsHook"
172 }
173
174 async fn on_tool_error(&self, tool: &str, args: &Value, error: &str) -> Option<Value> {
175 if tool == "run_command" {
176 let cmd = args.get("command").and_then(Value::as_str).unwrap_or("");
177 if cmd.contains("cargo") || cmd.contains("rustc") {
178 return Some(json!({
179 "status": "compiler_error",
180 "command": cmd,
181 "error": error,
182 "guidance": "Compiler diagnostics detected. Review the line numbers and error codes above, apply surgical edits via replace_file_content, and re-verify with cargo check."
183 }));
184 }
185 }
186 None
187 }
188}
189
190/// 5. Cortex Recall Hook: Automatically queries Spark Cortex and injects relevant memories into turn
191pub struct CortexRecallHook;
192
193#[async_trait]
194impl AgentHook for CortexRecallHook {
195 fn name(&self) -> &'static str {
196 "CortexRecallHook"
197 }
198
199 async fn pre_turn(&self, prompt: &mut String) -> Result<(), String> {
200 if let Some(recall) = crate::cortex::assemble_cortex_recall(prompt, 3).await {
201 *prompt = format!("{}\n\n{}", recall, prompt);
202 }
203 Ok(())
204 }
205}
206
207/// 6. Cortex Learning Capture Hook: Automatically records meaningful actions and verifications into Cortex
208pub struct CortexLearningCaptureHook;
209
210#[async_trait]
211impl AgentHook for CortexLearningCaptureHook {
212 fn name(&self) -> &'static str {
213 "CortexLearningCaptureHook"
214 }
215
216 async fn post_tool(&self, tool: &str, args: &Value, result: &mut Value) {
217 match tool {
218 "write_to_file" | "replace_file_content" => {
219 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
220 let intent = args.get("intent").and_then(Value::as_str).unwrap_or("File modified");
221 if !path.is_empty() {
222 crate::cortex::trigger_background_capture("file_write", path, intent);
223 }
224 },
225 "run_command" => {
226 let cmd = args.get("command").and_then(Value::as_str).unwrap_or("");
227 if (cmd.contains("cargo build") || cmd.contains("cargo check") || cmd.contains("gh repo") || cmd.contains("git commit")) && result.get("error").is_none() {
228 crate::cortex::trigger_background_capture("command_success", cmd, "Command verified cleanly");
229 }
230 },
231 _ => {}
232 }
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 #[tokio::test]
241 async fn test_unslop_hook() {
242 let registry = HookRegistry::default_sovereign_registry();
243 let mut text = "This is a feature—not a bug–verified.".to_string();
244 registry.run_post_turn(&mut text).await;
245 assert!(!text.contains('—'));
246 assert!(!text.contains('–'));
247 assert!(text.contains("feature, not a bug-verified"));
248 }
249
250 #[tokio::test]
251 async fn test_vault_redactor_hook() {
252 let registry = HookRegistry::default_sovereign_registry();
253 let mut text = "Here is the key: sk-ant-api03-1234567890123456789012345678901234567890.".to_string();
254 registry.run_post_turn(&mut text).await;
255 assert!(text.contains("[REDACTED_ANTHROPIC_KEY]"));
256 }
257}