Skip to main content

perspt_agent/tools/handlers/
mod.rs

1//! The open execution plane: an exact-name handler registry the governed
2//! candidate dispatches through.
3//!
4//! A new tool family is a *registration* at the composition root — catalog
5//! entries via `StaticCatalog::with_base`, handlers via
6//! [`CandidateHandlerRegistry::register`], and a capability grant — never an
7//! edit to the loop, the candidate, or the node assembly. The governance
8//! wrapper (catalog → validate → budget → certify → execute → re-certify)
9//! is uniform and lives outside the handlers.
10
11mod deps;
12mod exec;
13pub mod external;
14mod fs;
15pub mod interact;
16mod lsp;
17pub mod subagent;
18mod verify;
19
20use std::collections::BTreeMap;
21use std::sync::Arc;
22
23use anyhow::Result;
24use perspt_sdk::ToolEntry;
25
26use crate::candidate::CandidateWorkspace;
27use crate::toolloop::EffectOutcome;
28
29pub use interact::{
30    AsyncFnInteractionHandler, FnInteractionHandler, InteractionHandler, NonInteractiveHandler,
31};
32pub(crate) use lsp::LspSessions;
33pub use subagent::SubagentRunner;
34
35/// One governed tool executor. Handlers never decide admission, budgets, or
36/// certification — the kernel already did; they only realize the effect
37/// against the reversible candidate.
38#[async_trait::async_trait]
39pub trait CandidateToolHandler: Send + Sync {
40    async fn apply(
41        &self,
42        workspace: &CandidateWorkspace,
43        call: &perspt_sdk::ProviderToolCall,
44        entry: &ToolEntry,
45    ) -> Result<EffectOutcome>;
46}
47
48/// Exact-name registry. Duplicate registration fails closed so a later
49/// family can never silently shadow a builtin.
50pub struct CandidateHandlerRegistry {
51    handlers: BTreeMap<String, Arc<dyn CandidateToolHandler>>,
52    /// Consulted only when no exact name matches — the external (MCP)
53    /// dispatcher, whose namespaced tool names are discovered at runtime.
54    fallback: Option<Arc<dyn CandidateToolHandler>>,
55}
56
57impl std::fmt::Debug for CandidateHandlerRegistry {
58    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        formatter
60            .debug_struct("CandidateHandlerRegistry")
61            .field("handlers", &self.handlers.keys().collect::<Vec<_>>())
62            .finish()
63    }
64}
65
66impl CandidateHandlerRegistry {
67    /// An empty registry, for tests that assemble their own surface.
68    pub fn empty() -> Self {
69        Self {
70            handlers: BTreeMap::new(),
71            fallback: None,
72        }
73    }
74
75    /// The builtin coding-domain execution surface, matching the base
76    /// catalog's executor-backed entries.
77    pub fn with_builtins() -> Self {
78        let mut registry = Self::empty();
79        fs::register_workspace_ops(&mut registry);
80        verify::register(&mut registry);
81        exec::register(&mut registry);
82        lsp::register(&mut registry);
83        deps::register(&mut registry);
84        interact::register(&mut registry);
85        subagent::register(&mut registry);
86        registry
87    }
88
89    pub fn register(
90        &mut self,
91        name: impl Into<String>,
92        handler: Arc<dyn CandidateToolHandler>,
93    ) -> Result<()> {
94        let name = name.into();
95        anyhow::ensure!(
96            !self.handlers.contains_key(&name),
97            "duplicate tool handler registration: {name}"
98        );
99        self.handlers.insert(name, handler);
100        Ok(())
101    }
102
103    pub fn get(&self, name: &str) -> Option<&Arc<dyn CandidateToolHandler>> {
104        self.handlers.get(name)
105    }
106
107    /// Install the fallback handler for names with no exact registration.
108    pub fn set_fallback(&mut self, handler: Arc<dyn CandidateToolHandler>) {
109        self.fallback = Some(handler);
110    }
111
112    pub fn has_fallback(&self) -> bool {
113        self.fallback.is_some()
114    }
115
116    /// Exact name first, then the fallback.
117    pub fn resolve(&self, name: &str) -> Option<&Arc<dyn CandidateToolHandler>> {
118        self.handlers.get(name).or(self.fallback.as_ref())
119    }
120
121    pub fn names(&self) -> impl Iterator<Item = &str> {
122        self.handlers.keys().map(String::as_str)
123    }
124}
125
126impl Default for CandidateHandlerRegistry {
127    fn default() -> Self {
128        Self::with_builtins()
129    }
130}