Skip to main content

agent_base/tool/
mod.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use serde_json::{Value, json};
6use tokio::sync::mpsc;
7
8use crate::engine::SessionStore;
9use crate::llm::LlmClient;
10use crate::types::{AgentError, AgentResult, SessionId, UserEvent};
11
12pub mod auto_continue;
13pub mod policy;
14pub mod subagent;
15pub mod update_plan;
16
17pub use auto_continue::AutoContinueTool;
18pub use subagent::{SubAgentSessionPolicy, SubAgentTool};
19pub use update_plan::UpdatePlanTool;
20
21pub use policy::ToolPolicy;
22
23#[derive(Clone, Debug, Default)]
24pub struct ToolOutput {
25    pub summary: String,
26    pub raw: Option<Value>,
27    pub control_flow: ToolControlFlow,
28    pub truncation: Option<TruncationInfo>,
29}
30
31#[derive(Clone, Debug)]
32pub struct TruncationInfo {
33    pub original_summary_len: usize,
34    pub original_raw_len: Option<usize>,
35    pub max_allowed_chars: usize,
36}
37
38#[derive(Clone, Debug, Default)]
39pub enum ToolControlFlow {
40    #[default]
41    Break,
42    Continue,
43}
44
45#[derive(Clone)]
46pub struct ToolContext {
47    pub session_id: SessionId,
48    /// Channel for sending user-space events (progress, sub-agent, structured).
49    /// Tools should use `emit_user_event()` or `emit_progress()`.
50    pub user_event_tx: mpsc::UnboundedSender<UserEvent>,
51    pub llm_client: Option<Arc<dyn LlmClient>>,
52    pub session_store: Option<Arc<dyn SessionStore>>,
53    /// Language preference for tool output.
54    /// Defaults to `Language::En` if not set.
55    pub language: crate::types::Language,
56    /// Cancellation token for checking if the operation should be cancelled.
57    pub cancel_token: tokio_util::sync::CancellationToken,
58}
59
60impl ToolContext {
61    /// Send a user-space event (progress, sub-agent forwarding, structured data).
62    pub fn emit_user_event(&self, event: UserEvent) {
63        let _ = self.user_event_tx.send(event);
64    }
65
66    /// Convenience: send a progress event with text.
67    pub fn emit_progress(&self, text: impl Into<String>) {
68        self.emit_user_event(UserEvent::Progress { text: text.into() });
69    }
70}
71
72
73/// Machine-readable metadata for a registered tool — origin, version, and
74/// runtime requirements in a stable shape consumers can inspect without
75/// parsing the LLM-facing definition JSON.
76#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
77pub struct ToolMetadata {
78    /// Tool name (matches [`Tool::name`]).
79    pub name: String,
80    /// Human-readable description (matches the description in [`Tool::definition`]).
81    pub description: String,
82    /// Where this tool comes from: a crate name (e.g. `"phi-tools"`), a
83    /// framework identifier (`"agent-base"`, `"agent-works"`), or
84    /// `"custom"` for user-defined tools.
85    pub origin: String,
86    /// Crate / package version, or `"unknown"` when built outside a crate.
87    pub version: String,
88    /// Optional runtime requirements or capabilities this tool depends on
89    /// (e.g. `["chrome-cdp"]` for browser tools). Empty when there are
90    /// none.
91    pub requirements: Vec<String>,
92}
93
94#[async_trait]
95pub trait Tool: Send + Sync {
96    fn name(&self) -> &'static str;
97    fn definition(&self) -> Value;
98    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<ToolOutput>;
99
100    /// Return `Some(&dyn FrameworkTool)` if this tool is a framework-internal tool
101    /// that needs engine infrastructure injection (EventBus).
102    /// Default returns `None` — user-defined tools need not override this.
103    #[allow(private_interfaces)]
104    fn as_framework_tool(&self) -> Option<&dyn FrameworkTool> {
105        None
106    }
107
108    /// Machine-readable metadata for tool introspection.
109    ///
110    /// The default implementation extracts `name` and `description` from
111    /// [`Tool::name`] and [`Tool::definition`], sets `origin` to `"custom"`,
112    /// and leaves `requirements` empty. Tool authors are encouraged to
113    /// override this to provide an accurate `origin` and `version`.
114    fn metadata(&self) -> ToolMetadata {
115        let name = self.name().to_string();
116        let description = self
117            .definition()
118            .get("function")
119            .and_then(|f| f.get("description"))
120            .and_then(|d| d.as_str())
121            .unwrap_or("")
122            .to_string();
123        ToolMetadata {
124            name,
125            description,
126            origin: "custom".to_string(),
127            version: "unknown".to_string(),
128            requirements: vec![],
129        }
130    }
131}
132
133/// Marker trait for framework-internal tools that require engine infrastructure.
134///
135/// Framework tools implement this trait to receive `EventBus`
136/// references during `AgentBuilder::build()`. User-defined tools do not need this.
137///
138/// All methods have default no-op implementations so only the needed injection
139/// points need to be overridden.
140pub(crate) trait FrameworkTool: Tool {
141    /// Inject the internal event bus. Called once during build.
142    fn set_event_bus(&self, _event_bus: crate::engine::EventBus) {}
143}
144
145#[async_trait]
146pub trait TypedTool: Send + Sync {
147    type Args: serde::de::DeserializeOwned;
148    type Output: serde::Serialize;
149
150    fn name(&self) -> &'static str;
151    fn description(&self) -> &'static str;
152    fn parameters_schema(&self) -> Value;
153    async fn call_typed(&self, args: Self::Args, ctx: &ToolContext) -> AgentResult<Self::Output>;
154
155    fn control_flow() -> ToolControlFlow
156    where
157        Self: Sized,
158    {
159        ToolControlFlow::Break
160    }
161
162    fn format_output(&self, output: Self::Output) -> String {
163        serde_json::to_string(&output).unwrap_or_default()
164    }
165}
166
167#[async_trait]
168impl<T: TypedTool + Send + Sync + 'static> Tool for T {
169    fn name(&self) -> &'static str {
170        TypedTool::name(self)
171    }
172
173    fn definition(&self) -> Value {
174        json!({
175            "type": "function",
176            "function": {
177                "name": self.name(),
178                "description": self.description(),
179                "parameters": self.parameters_schema(),
180            }
181        })
182    }
183
184    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<ToolOutput> {
185        let typed_args: T::Args =
186            serde_json::from_value(args.clone()).map_err(|_| AgentError::ToolArgsInvalid {
187                name: self.name().to_string(),
188                raw: args.to_string(),
189            })?;
190        let output = self.call_typed(typed_args, ctx).await?;
191        let output_json = serde_json::to_value(&output).ok();
192        let summary = self.format_output(output);
193        Ok(ToolOutput {
194            summary,
195            raw: output_json,
196            control_flow: T::control_flow(),
197            truncation: None,
198        })
199    }
200}
201
202pub(crate) type ToolRef = Arc<dyn Tool>;
203
204#[derive(Clone, Default)]
205pub struct ToolRegistry {
206    tools: HashMap<String, ToolRef>,
207}
208
209impl ToolRegistry {
210    pub fn register(&mut self, tool: impl Tool + 'static) {
211        self.tools.insert(tool.name().to_string(), Arc::new(tool));
212    }
213
214    pub fn register_arc(&mut self, tool: Arc<dyn Tool>) {
215        self.tools.insert(tool.name().to_string(), tool);
216    }
217
218    pub fn update(&mut self, tool: impl Tool + 'static) {
219        self.tools.insert(tool.name().to_string(), Arc::new(tool));
220    }
221
222    /// Remove a tool from the registry by name.
223    pub fn remove(&mut self, name: &str) {
224        self.tools.remove(name);
225    }
226
227    pub fn get(&self, name: &str) -> Option<ToolRef> {
228        self.tools.get(name).cloned()
229    }
230
231    pub fn definitions(&self) -> Vec<Value> {
232        self.tools.values().map(|tool| tool.definition()).collect()
233    }
234
235    pub fn len(&self) -> usize {
236        self.tools.len()
237    }
238
239    pub fn is_empty(&self) -> bool {
240        self.tools.is_empty()
241    }
242
243    /// Collect metadata for every registered tool, sorted by name.
244    ///
245    /// This is the preferred introspection API for consumers — it returns a
246    /// stable `ToolMetadata` struct per tool instead of having callers parse
247    /// the LLM-facing JSON definitions.
248    pub fn metadatas(&self) -> Vec<ToolMetadata> {
249        let mut list: Vec<_> = self.tools.values().map(|tool| tool.metadata()).collect();
250        list.sort_by(|a, b| a.name.cmp(&b.name));
251        list
252    }
253
254    /// Inject the internal `EventBus` into framework-provided tools.
255    pub fn inject_event_bus(&self, event_bus: &crate::engine::EventBus) {
256        for tool in self.tools.values() {
257            if let Some(fw) = tool.as_framework_tool() {
258                fw.set_event_bus(event_bus.clone());
259            }
260        }
261    }
262}