Repository navigation
Expand file tree
/
Copy pathhooks.rs
More file actions
768 lines (665 loc) · 22.5 KB
/
Copy pathhooks.rs
File metadata and controls
768 lines (665 loc) · 22.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! Hooks system for Cortex CLI.
//!
//! Hooks allow plugins and users to intercept and modify agent behavior
//! at various points in the execution lifecycle.
//!
//! Hook types:
//! - PreToolUse: Before a tool is executed
//! - PostToolUse: After a tool completes
//! - SessionStart: When a session begins
//! - SessionEnd: When a session ends
//! - PreModelCall: Before calling the AI model
//! - PostModelCall: After receiving model response
//! - Stop: Before the agent stops (can prevent exit)
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use crate::error::{CortexError, Result};
/// Hook event types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HookEvent {
/// Before a tool is executed.
PreToolUse,
/// After a tool completes.
PostToolUse,
/// When a session begins.
SessionStart,
/// When a session ends.
SessionEnd,
/// Before calling the AI model.
PreModelCall,
/// After receiving model response.
PostModelCall,
/// Before the agent stops.
Stop,
/// When a message is received from user.
OnUserMessage,
/// When a message is generated by agent.
OnAgentMessage,
/// On any error.
OnError,
}
impl std::fmt::Display for HookEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::PreToolUse => write!(f, "PreToolUse"),
Self::PostToolUse => write!(f, "PostToolUse"),
Self::SessionStart => write!(f, "SessionStart"),
Self::SessionEnd => write!(f, "SessionEnd"),
Self::PreModelCall => write!(f, "PreModelCall"),
Self::PostModelCall => write!(f, "PostModelCall"),
Self::Stop => write!(f, "Stop"),
Self::OnUserMessage => write!(f, "OnUserMessage"),
Self::OnAgentMessage => write!(f, "OnAgentMessage"),
Self::OnError => write!(f, "OnError"),
}
}
}
impl std::str::FromStr for HookEvent {
type Err = CortexError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"pretooluse" | "pre_tool_use" | "pre-tool-use" => Ok(Self::PreToolUse),
"posttooluse" | "post_tool_use" | "post-tool-use" => Ok(Self::PostToolUse),
"sessionstart" | "session_start" | "session-start" => Ok(Self::SessionStart),
"sessionend" | "session_end" | "session-end" => Ok(Self::SessionEnd),
"premodelcall" | "pre_model_call" | "pre-model-call" => Ok(Self::PreModelCall),
"postmodelcall" | "post_model_call" | "post-model-call" => Ok(Self::PostModelCall),
"stop" => Ok(Self::Stop),
"onusermessage" | "on_user_message" | "on-user-message" => Ok(Self::OnUserMessage),
"onagentmessage" | "on_agent_message" | "on-agent-message" => Ok(Self::OnAgentMessage),
"onerror" | "on_error" | "on-error" => Ok(Self::OnError),
_ => Err(CortexError::InvalidInput(format!(
"Unknown hook event: {s}"
))),
}
}
}
/// Context passed to hooks.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookContext {
/// Session ID.
pub session_id: String,
/// Current working directory.
pub cwd: PathBuf,
/// Current turn ID.
pub turn_id: String,
/// Hook-specific data.
pub data: serde_json::Value,
/// Environment variables (optional).
#[serde(default)]
pub env: HashMap<String, String>,
}
impl HookContext {
/// Create a new hook context.
pub fn new(session_id: impl Into<String>, cwd: impl Into<PathBuf>) -> Self {
Self {
session_id: session_id.into(),
cwd: cwd.into(),
turn_id: String::new(),
data: serde_json::Value::Null,
env: HashMap::new(),
}
}
/// Set turn ID.
pub fn with_turn_id(mut self, turn_id: impl Into<String>) -> Self {
self.turn_id = turn_id.into();
self
}
/// Set hook data.
pub fn with_data(mut self, data: serde_json::Value) -> Self {
self.data = data;
self
}
/// Add environment variable.
pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.env.insert(key.into(), value.into());
self
}
}
/// Result from a hook execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookResult {
/// Whether to continue execution.
pub continue_execution: bool,
/// Modified data to pass forward.
pub data: Option<serde_json::Value>,
/// Message to inject (for SessionStart hooks).
pub inject_message: Option<String>,
/// Error message if hook failed.
pub error: Option<String>,
/// Warnings (non-fatal).
#[serde(default)]
pub warnings: Vec<String>,
}
impl HookResult {
/// Create a success result.
pub fn success() -> Self {
Self {
continue_execution: true,
data: None,
inject_message: None,
error: None,
warnings: Vec::new(),
}
}
/// Create a result with modified data.
pub fn with_data(data: serde_json::Value) -> Self {
Self {
continue_execution: true,
data: Some(data),
inject_message: None,
error: None,
warnings: Vec::new(),
}
}
/// Create a result that injects a message.
pub fn inject(message: impl Into<String>) -> Self {
Self {
continue_execution: true,
data: None,
inject_message: Some(message.into()),
error: None,
warnings: Vec::new(),
}
}
/// Create an error result.
pub fn error(message: impl Into<String>) -> Self {
Self {
continue_execution: false,
data: None,
inject_message: None,
error: Some(message.into()),
warnings: Vec::new(),
}
}
/// Create a stop result (prevent action).
pub fn stop() -> Self {
Self {
continue_execution: false,
data: None,
inject_message: None,
error: None,
warnings: Vec::new(),
}
}
/// Add a warning.
pub fn with_warning(mut self, warning: impl Into<String>) -> Self {
self.warnings.push(warning.into());
self
}
}
impl Default for HookResult {
fn default() -> Self {
Self::success()
}
}
/// Hook handler trait.
#[async_trait]
pub trait HookHandler: Send + Sync {
/// Execute the hook.
async fn execute(&self, context: &HookContext) -> Result<HookResult>;
/// Get the hook's name.
fn name(&self) -> &str;
/// Get the hook's description.
fn description(&self) -> &str;
/// Get the events this hook listens to.
fn events(&self) -> Vec<HookEvent>;
/// Get the hook's priority (lower = runs first).
fn priority(&self) -> i32 {
0
}
}
/// Hook definition from config/plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookDefinition {
/// Hook name.
pub name: String,
/// Description.
pub description: String,
/// Event to listen for.
pub event: HookEvent,
/// Priority (lower = runs first).
#[serde(default)]
pub priority: i32,
/// Command to execute (for script hooks).
pub command: Option<String>,
/// Script file to run.
pub script: Option<PathBuf>,
/// Patterns to match (for tool hooks).
#[serde(default)]
pub patterns: Vec<String>,
/// Whether hook is enabled.
#[serde(default = "default_enabled")]
pub enabled: bool,
}
fn default_enabled() -> bool {
true
}
impl HookDefinition {
/// Create a new hook definition.
pub fn new(name: impl Into<String>, event: HookEvent) -> Self {
Self {
name: name.into(),
description: String::new(),
event,
priority: 0,
command: None,
script: None,
patterns: Vec::new(),
enabled: true,
}
}
/// Set description.
pub fn description(mut self, desc: impl Into<String>) -> Self {
self.description = desc.into();
self
}
/// Set command.
pub fn command(mut self, cmd: impl Into<String>) -> Self {
self.command = Some(cmd.into());
self
}
/// Set script path.
pub fn script(mut self, path: impl Into<PathBuf>) -> Self {
self.script = Some(path.into());
self
}
/// Add pattern.
pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
self.patterns.push(pattern.into());
self
}
/// Set priority.
pub fn priority(mut self, priority: i32) -> Self {
self.priority = priority;
self
}
}
/// Script-based hook handler.
pub struct ScriptHookHandler {
definition: HookDefinition,
base_path: PathBuf,
}
impl ScriptHookHandler {
/// Create a new script hook handler.
pub fn new(definition: HookDefinition, base_path: PathBuf) -> Self {
Self {
definition,
base_path,
}
}
/// Check if a tool name matches the hook's patterns.
fn matches_pattern(&self, tool_name: &str) -> bool {
if self.definition.patterns.is_empty() {
return true;
}
self.definition.patterns.iter().any(|pattern| {
// Simple glob matching
if pattern == "*" {
true
} else if pattern.contains('*') {
let parts: Vec<&str> = pattern.split('*').collect();
if parts.len() == 2 {
tool_name.starts_with(parts[0]) && tool_name.ends_with(parts[1])
} else {
tool_name == pattern
}
} else {
tool_name == pattern
}
})
}
}
#[async_trait]
impl HookHandler for ScriptHookHandler {
async fn execute(&self, context: &HookContext) -> Result<HookResult> {
if !self.definition.enabled {
return Ok(HookResult::success());
}
// For tool hooks, check pattern matching
if matches!(
self.definition.event,
HookEvent::PreToolUse | HookEvent::PostToolUse
) && let Some(tool_name) = context.data.get("tool_name").and_then(|v| v.as_str())
&& !self.matches_pattern(tool_name)
{
return Ok(HookResult::success());
}
// Execute command or script
let output = if let Some(ref cmd) = self.definition.command {
// Execute inline command
let output = tokio::process::Command::new("sh")
.arg("-c")
.arg(cmd)
.current_dir(&context.cwd)
.env("CORTEX_SESSION_ID", &context.session_id)
.env("CORTEX_TURN_ID", &context.turn_id)
.env("CORTEX_HOOK_DATA", context.data.to_string())
.envs(&context.env)
.output()
.await?;
String::from_utf8_lossy(&output.stdout).to_string()
} else if let Some(ref script) = self.definition.script {
let script_path = if script.is_absolute() {
script.clone()
} else {
self.base_path.join(script)
};
if !script_path.exists() {
return Ok(HookResult::error(format!(
"Hook script not found: {}",
script_path.display()
)));
}
// Determine interpreter
let ext = script_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("");
let (interpreter, args) = match ext {
"py" => ("python3", vec![]),
"js" => ("node", vec![]),
"ts" => ("npx", vec!["ts-node"]),
"sh" | "bash" => ("bash", vec![]),
_ => ("sh", vec![]),
};
let mut cmd = tokio::process::Command::new(interpreter);
for arg in args {
cmd.arg(arg);
}
cmd.arg(&script_path);
cmd.current_dir(&context.cwd);
cmd.env("CORTEX_SESSION_ID", &context.session_id);
cmd.env("CORTEX_TURN_ID", &context.turn_id);
cmd.env("CORTEX_HOOK_DATA", context.data.to_string());
cmd.envs(&context.env);
let output = cmd.output().await?;
String::from_utf8_lossy(&output.stdout).to_string()
} else {
return Ok(HookResult::success());
};
// Parse output as JSON if possible, otherwise use as message
if let Ok(result) = serde_json::from_str::<HookResult>(&output) {
Ok(result)
} else if !output.trim().is_empty() {
Ok(HookResult::inject(output.trim()))
} else {
Ok(HookResult::success())
}
}
fn name(&self) -> &str {
&self.definition.name
}
fn description(&self) -> &str {
&self.definition.description
}
fn events(&self) -> Vec<HookEvent> {
vec![self.definition.event]
}
fn priority(&self) -> i32 {
self.definition.priority
}
}
/// Hook registry that manages all hooks.
pub struct HookRegistry {
/// Registered hooks by event.
hooks: RwLock<HashMap<HookEvent, Vec<Arc<dyn HookHandler>>>>,
}
impl HookRegistry {
/// Create a new hook registry.
pub fn new() -> Self {
Self {
hooks: RwLock::new(HashMap::new()),
}
}
/// Register a hook handler.
pub async fn register(&self, handler: Arc<dyn HookHandler>) {
let mut hooks = self.hooks.write().await;
for event in handler.events() {
let handlers = hooks.entry(event).or_insert_with(Vec::new);
handlers.push(handler.clone());
// Sort by priority
handlers.sort_by_key(|h| h.priority());
}
}
/// Register a hook from a definition.
pub async fn register_definition(&self, definition: HookDefinition, base_path: PathBuf) {
let handler = Arc::new(ScriptHookHandler::new(definition, base_path));
self.register(handler).await;
}
/// Trigger hooks for an event.
pub async fn trigger(&self, event: HookEvent, context: &HookContext) -> Result<HookResult> {
let hooks = self.hooks.read().await;
let handlers = match hooks.get(&event) {
Some(h) => h.clone(),
None => return Ok(HookResult::success()),
};
drop(hooks); // Release lock before executing handlers
let mut combined_result = HookResult::success();
let mut injected_messages = Vec::new();
for handler in handlers {
let result = handler.execute(context).await?;
// Collect warnings
combined_result.warnings.extend(result.warnings);
// Collect injected messages
if let Some(msg) = result.inject_message {
injected_messages.push(msg);
}
// Update data if modified
if let Some(data) = result.data {
combined_result.data = Some(data);
}
// Stop if hook says to stop
if !result.continue_execution {
combined_result.continue_execution = false;
combined_result.error = result.error;
break;
}
}
// Combine injected messages
if !injected_messages.is_empty() {
combined_result.inject_message = Some(injected_messages.join("\n"));
}
Ok(combined_result)
}
/// Get all registered hooks.
pub async fn list(&self) -> Vec<(HookEvent, Vec<String>)> {
let hooks = self.hooks.read().await;
hooks
.iter()
.map(|(event, handlers)| {
let names: Vec<String> = handlers.iter().map(|h| h.name().to_string()).collect();
(*event, names)
})
.collect()
}
/// Unregister a hook by name.
pub async fn unregister(&self, name: &str) {
let mut hooks = self.hooks.write().await;
for handlers in hooks.values_mut() {
handlers.retain(|h| h.name() != name);
}
}
/// Clear all hooks.
pub async fn clear(&self) {
self.hooks.write().await.clear();
}
}
impl Default for HookRegistry {
fn default() -> Self {
Self::new()
}
}
/// Load hooks from a configuration file.
pub fn load_hooks_from_config(config_path: &Path) -> Result<Vec<HookDefinition>> {
if !config_path.exists() {
return Ok(Vec::new());
}
let content = std::fs::read_to_string(config_path)?;
let config: HooksConfig = serde_json::from_str(&content)
.or_else(|_| toml::from_str(&content))
.map_err(|e| CortexError::InvalidInput(format!("Failed to parse hooks config: {e}")))?;
Ok(config.hooks)
}
/// Hooks configuration file format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HooksConfig {
#[serde(default)]
pub hooks: Vec<HookDefinition>,
}
/// Built-in security hook that monitors for dangerous patterns.
pub struct SecurityHook {
patterns: Vec<SecurityPattern>,
}
#[derive(Debug, Clone)]
struct SecurityPattern {
name: String,
description: String,
regex: regex::Regex,
}
impl SecurityHook {
/// Create a new security hook with default patterns.
pub fn new() -> Self {
let patterns = vec![
SecurityPattern {
name: "command_injection".to_string(),
description: "Potential command injection".to_string(),
regex: regex::Regex::new(r"[;&|`$]").expect("valid regex"),
},
SecurityPattern {
name: "eval_usage".to_string(),
description: "Use of eval() or similar".to_string(),
regex: regex::Regex::new(r"\beval\s*\(").expect("valid regex"),
},
SecurityPattern {
name: "dangerous_html".to_string(),
description: "Potential XSS via innerHTML".to_string(),
regex: regex::Regex::new(r"innerHTML\s*=").expect("valid regex"),
},
SecurityPattern {
name: "os_system".to_string(),
description: "Use of os.system()".to_string(),
regex: regex::Regex::new(r"os\.system\s*\(").expect("valid regex"),
},
SecurityPattern {
name: "subprocess_shell".to_string(),
description: "Subprocess with shell=True".to_string(),
regex: regex::Regex::new(r"subprocess\.[^(]+\([^)]*shell\s*=\s*True")
.expect("valid regex"),
},
SecurityPattern {
name: "pickle_load".to_string(),
description: "Unsafe pickle deserialization".to_string(),
regex: regex::Regex::new(r"pickle\.loads?\s*\(").expect("valid regex"),
},
];
Self { patterns }
}
/// Check content for security issues.
fn check(&self, content: &str) -> Vec<String> {
self.patterns
.iter()
.filter(|p| p.regex.is_match(content))
.map(|p| format!("{}: {}", p.name, p.description))
.collect()
}
}
impl Default for SecurityHook {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl HookHandler for SecurityHook {
async fn execute(&self, context: &HookContext) -> Result<HookResult> {
// Check tool arguments for security issues
let content = context.data.to_string();
let issues = self.check(&content);
if issues.is_empty() {
Ok(HookResult::success())
} else {
let mut result = HookResult::success();
for issue in issues {
result = result.with_warning(format!("Security warning: {issue}"));
}
Ok(result)
}
}
fn name(&self) -> &str {
"security-guidance"
}
fn description(&self) -> &str {
"Monitors for potential security issues in tool calls"
}
fn events(&self) -> Vec<HookEvent> {
vec![HookEvent::PreToolUse]
}
fn priority(&self) -> i32 {
-100 // Run early
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hook_event_parsing() {
assert_eq!(
"PreToolUse".parse::<HookEvent>().unwrap(),
HookEvent::PreToolUse
);
assert_eq!(
"pre_tool_use".parse::<HookEvent>().unwrap(),
HookEvent::PreToolUse
);
assert_eq!(
"session-start".parse::<HookEvent>().unwrap(),
HookEvent::SessionStart
);
}
#[test]
fn test_hook_result() {
let result = HookResult::success();
assert!(result.continue_execution);
assert!(result.error.is_none());
let result = HookResult::error("Failed");
assert!(!result.continue_execution);
assert_eq!(result.error, Some("Failed".to_string()));
let result = HookResult::inject("Hello").with_warning("Be careful");
assert!(result.continue_execution);
assert_eq!(result.inject_message, Some("Hello".to_string()));
assert_eq!(result.warnings.len(), 1);
}
#[test]
fn test_security_hook() {
let hook = SecurityHook::new();
// Test eval detection
let issues = hook.check("eval('code')");
assert!(!issues.is_empty(), "Should detect eval usage");
// Test os.system detection
let issues = hook.check("os.system('ls')");
assert!(!issues.is_empty(), "Should detect os.system usage");
// Test pickle detection
let issues = hook.check("pickle.load(f)");
assert!(!issues.is_empty(), "Should detect pickle.load usage");
// Test safe content (no dangerous patterns)
let issues = hook.check("function hello() { return 42 }");
assert!(issues.is_empty(), "Should not flag safe content");
}
#[tokio::test]
async fn test_hook_registry() {
let registry = HookRegistry::new();
let definition = HookDefinition::new("test-hook", HookEvent::SessionStart)
.description("Test hook")
.command("echo 'Hello from hook'");
registry
.register_definition(definition, PathBuf::from("/tmp"))
.await;
let hooks = registry.list().await;
assert!(!hooks.is_empty());
}
}