Skip to main content

crabtalk_hooks/
lib.rs

1//! Reusable hook implementations and composition for the Crabtalk runtime.
2//!
3//! `Hooks` is the single `Hook` the runtime `Env` sees — it owns the
4//! sub-hooks registered into it, the dispatch map, per-agent scope
5//! enforcement, agent descriptions, and the late-bound event sink.
6
7use crabllm_core::Tool;
8use parking_lot::RwLock;
9use runtime::Hook;
10use std::{
11    collections::{BTreeMap, BTreeSet},
12    sync::Arc,
13};
14use wcore::{AgentConfig, AgentEvent, ToolDispatch, ToolFuture};
15
16#[cfg(feature = "mcp")]
17pub mod mcp;
18#[cfg(feature = "memory")]
19pub mod memory;
20#[cfg(feature = "os")]
21pub mod os;
22#[cfg(feature = "skill")]
23pub mod skill;
24#[cfg(feature = "memory")]
25mod utils;
26
27#[cfg(feature = "mcp")]
28pub use mcp::McpHook;
29#[cfg(feature = "memory")]
30pub use memory::{DEFAULT_SOUL, Memory, MemoryHook};
31#[cfg(feature = "os")]
32pub use os::OsHook;
33#[cfg(feature = "skill")]
34pub use skill::handler::SkillHook;
35#[cfg(feature = "memory")]
36pub use utils::default_crab;
37
38/// Per-agent scope for dispatch enforcement. Empty vecs = unrestricted.
39#[derive(Default)]
40pub struct AgentScope {
41    pub tools: Vec<String>,
42    pub skills: Vec<String>,
43}
44
45/// Late-bindable sink for `agent:{name}:done` event publishes.
46pub type EventSink = Arc<dyn Fn(&str, &str) + Send + Sync>;
47
48/// Aggregates all sub-hooks behind a single `Hook` impl.
49pub struct Hooks {
50    pub scopes: Arc<RwLock<BTreeMap<String, AgentScope>>>,
51    hooks: BTreeMap<String, Arc<dyn Hook>>,
52    /// Dispatchable but never advertised ambiently, so a surface's own tools
53    /// can't leak into ordinary chat or unattended heartbeats.
54    scoped: BTreeMap<String, Arc<dyn Hook>>,
55    /// Tool names owned by `scoped`, which dispatch lets past the per-agent
56    /// whitelist — declaring one is already the gate.
57    scoped_names: BTreeSet<String>,
58    dispatch_map: BTreeMap<String, Arc<dyn Hook>>,
59    event_sink: RwLock<Option<EventSink>>,
60}
61
62impl Hooks {
63    pub fn new(scopes: Arc<RwLock<BTreeMap<String, AgentScope>>>) -> Self {
64        Self {
65            scopes,
66            hooks: BTreeMap::new(),
67            scoped: BTreeMap::new(),
68            scoped_names: BTreeSet::new(),
69            dispatch_map: BTreeMap::new(),
70            event_sink: RwLock::new(None),
71        }
72    }
73
74    /// Register a sub-hook by name.
75    pub fn register_hook(&mut self, name: impl Into<String>, hook: Arc<dyn Hook>) {
76        for tool in hook.schema() {
77            self.dispatch_map
78                .insert(tool.function.name.clone(), hook.clone());
79        }
80        self.hooks.insert(name.into(), hook);
81    }
82
83    /// Register a sub-hook whose tools a stream must opt into by name with
84    /// [`Hooks::scoped_schema`]; see the `scoped` field.
85    pub fn register_scoped(&mut self, name: impl Into<String>, hook: Arc<dyn Hook>) {
86        for tool in hook.schema() {
87            self.scoped_names.insert(tool.function.name.clone());
88            self.dispatch_map
89                .insert(tool.function.name.clone(), hook.clone());
90        }
91        self.scoped.insert(name.into(), hook);
92    }
93
94    /// Install the late-bound event sink for `agent:{name}:done` events.
95    pub fn set_event_sink(&self, sink: EventSink) {
96        *self.event_sink.write() = Some(sink);
97    }
98
99    /// Apply scoped tool whitelist and scope prompt for sub-agents.
100    fn apply_scope(&self, config: &mut AgentConfig) {
101        let has_scoping = !config.skills.is_empty() || !config.mcps.is_empty();
102        // Skills allowlist + MCP declarations both produce a tool whitelist
103        // that the dispatcher enforces. No declarations → no whitelist needed.
104        if !has_scoping {
105            return;
106        }
107
108        let mut whitelist = Vec::new();
109        let mut scope_lines = Vec::new();
110        for hook in self.hooks.values() {
111            let (tools, line) = hook.scoped_tools(config);
112            whitelist.extend(tools);
113            if let Some(line) = line {
114                scope_lines.push(line);
115            }
116        }
117
118        if !scope_lines.is_empty() {
119            let scope_block = format!("\n\n<scope>\n{}\n</scope>", scope_lines.join("\n"));
120            config.system_prompt.push_str(&scope_block);
121        }
122
123        config.tools = whitelist;
124    }
125}
126
127impl Hook for Hooks {
128    fn schema(&self) -> Vec<Tool> {
129        self.hooks.values().flat_map(|h| h.schema()).collect()
130    }
131
132    /// Unknown names are skipped, so the default — nothing declared — exposes
133    /// no scoped tools at all.
134    fn scoped_schema(&self, names: &[String]) -> Vec<Tool> {
135        names
136            .iter()
137            .filter_map(|name| self.scoped.get(name))
138            .flat_map(|hook| hook.schema())
139            .collect()
140    }
141
142    fn system_prompt(&self) -> Option<String> {
143        let mut prompt = String::new();
144        for hook in self.hooks.values() {
145            if let Some(ref s) = hook.system_prompt() {
146                prompt.push_str(s);
147            }
148        }
149        if prompt.is_empty() {
150            None
151        } else {
152            Some(prompt)
153        }
154    }
155
156    fn on_build_agent(&self, mut config: AgentConfig) -> AgentConfig {
157        // A store that persists only a description composes the identity line
158        // here; one that persists a full prompt already filled this in, so
159        // seeding only when empty leaves it untouched.
160        if config.system_prompt.is_empty() && !config.description.is_empty() {
161            config.system_prompt = format!("You are {}.\n\n{}", config.name, config.description);
162        }
163        if let Some(ref prompt) = self.system_prompt() {
164            config.system_prompt.push_str(prompt);
165        }
166        self.apply_scope(&mut config);
167        config
168    }
169
170    fn on_register_agent(&self, name: &str, config: &AgentConfig) {
171        self.scopes.write().insert(
172            name.to_owned(),
173            AgentScope {
174                tools: config.tools.clone(),
175                skills: config.skills.clone(),
176            },
177        );
178        for hook in self.hooks.values() {
179            hook.on_register_agent(name, config);
180        }
181    }
182
183    fn on_unregister_agent(&self, name: &str) {
184        self.scopes.write().remove(name);
185        for hook in self.hooks.values() {
186            hook.on_unregister_agent(name);
187        }
188    }
189
190    fn on_event(&self, agent: &str, conversation_id: u64, event: &AgentEvent) {
191        for hook in self.hooks.values() {
192            hook.on_event(agent, conversation_id, event);
193        }
194
195        if let AgentEvent::Done(response) = event
196            && let Some(sink) = self.event_sink.read().clone()
197        {
198            let source = format!("agent:{agent}:done");
199            let payload = response.final_response.clone().unwrap_or_default();
200            sink(&source, &payload);
201        }
202    }
203
204    fn preprocess(&self, agent: &str, content: &str) -> Option<String> {
205        for hook in self.hooks.values() {
206            if let Some(result) = hook.preprocess(agent, content) {
207                return Some(result);
208            }
209        }
210        None
211    }
212
213    fn dispatch<'a>(&'a self, name: &'a str, call: ToolDispatch) -> Option<ToolFuture<'a>> {
214        // Scoped tools skip the whitelist — declaring one is already the gate,
215        // and they are never in the persistent whitelist to begin with.
216        if !self.scoped_names.contains(name) {
217            let scopes = self.scopes.read();
218            if let Some(scope) = scopes.get(&call.agent)
219                && !scope.tools.is_empty()
220                && !scope.tools.iter().any(|t| t.as_str() == name)
221            {
222                return Some(Box::pin(async move {
223                    Err(format!("tool not available: {name}"))
224                }));
225            }
226        }
227
228        if let Some(hook) = self.dispatch_map.get(name) {
229            return hook.dispatch(name, call);
230        }
231
232        None
233    }
234}