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/// Machine-readable metadata for a registered tool — origin, version, and
73/// runtime requirements in a stable shape consumers can inspect without
74/// parsing the LLM-facing definition JSON.
75#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
76pub struct ToolMetadata {
77    /// Tool name (matches [`Tool::name`]).
78    pub name: String,
79    /// Human-readable description (matches the description in [`Tool::definition`]).
80    pub description: String,
81    /// Where this tool comes from: a crate name (e.g. `"phi-tools"`), a
82    /// framework identifier (`"agent-base"`, `"agent-works"`), or
83    /// `"custom"` for user-defined tools.
84    pub origin: String,
85    /// Crate / package version, or `"unknown"` when built outside a crate.
86    pub version: String,
87    /// Optional runtime requirements or capabilities this tool depends on
88    /// (e.g. `["chrome-cdp"]` for browser tools). Empty when there are
89    /// none.
90    pub requirements: Vec<String>,
91}
92
93#[async_trait]
94pub trait Tool: Send + Sync {
95    fn name(&self) -> &'static str;
96    fn definition(&self) -> Value;
97    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<ToolOutput>;
98
99    /// Return `Some(&dyn FrameworkTool)` if this tool is a framework-internal tool
100    /// that needs engine infrastructure injection (EventBus).
101    /// Default returns `None` — user-defined tools need not override this.
102    #[allow(private_interfaces)]
103    fn as_framework_tool(&self) -> Option<&dyn FrameworkTool> {
104        None
105    }
106
107    /// Machine-readable metadata for tool introspection.
108    ///
109    /// The default implementation extracts `name` and `description` from
110    /// [`Tool::name`] and [`Tool::definition`], sets `origin` to `"custom"`,
111    /// and leaves `requirements` empty. Tool authors are encouraged to
112    /// override this to provide an accurate `origin` and `version`.
113    fn metadata(&self) -> ToolMetadata {
114        let name = self.name().to_string();
115        let description = self
116            .definition()
117            .get("function")
118            .and_then(|f| f.get("description"))
119            .and_then(|d| d.as_str())
120            .unwrap_or("")
121            .to_string();
122        ToolMetadata {
123            name,
124            description,
125            origin: "custom".to_string(),
126            version: "unknown".to_string(),
127            requirements: vec![],
128        }
129    }
130}
131
132/// Marker trait for framework-internal tools that require engine infrastructure.
133///
134/// Framework tools implement this trait to receive `EventBus`
135/// references during `AgentBuilder::build()`. User-defined tools do not need this.
136///
137/// All methods have default no-op implementations so only the needed injection
138/// points need to be overridden.
139pub(crate) trait FrameworkTool: Tool {
140    /// Inject the internal event bus. Called once during build.
141    fn set_event_bus(&self, _event_bus: crate::engine::EventBus) {}
142}
143
144#[async_trait]
145pub trait TypedTool: Send + Sync {
146    type Args: serde::de::DeserializeOwned;
147    type Output: serde::Serialize;
148
149    fn name(&self) -> &'static str;
150    fn description(&self) -> &'static str;
151    fn parameters_schema(&self) -> Value;
152    async fn call_typed(&self, args: Self::Args, ctx: &ToolContext) -> AgentResult<Self::Output>;
153
154    fn control_flow() -> ToolControlFlow
155    where
156        Self: Sized,
157    {
158        ToolControlFlow::Break
159    }
160
161    fn format_output(&self, output: Self::Output) -> String {
162        serde_json::to_string(&output).unwrap_or_default()
163    }
164}
165
166#[async_trait]
167impl<T: TypedTool + Send + Sync + 'static> Tool for T {
168    fn name(&self) -> &'static str {
169        TypedTool::name(self)
170    }
171
172    fn definition(&self) -> Value {
173        json!({
174            "type": "function",
175            "function": {
176                "name": self.name(),
177                "description": self.description(),
178                "parameters": self.parameters_schema(),
179            }
180        })
181    }
182
183    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<ToolOutput> {
184        let typed_args: T::Args =
185            serde_json::from_value(args.clone()).map_err(|_| AgentError::ToolArgsInvalid {
186                name: self.name().to_string(),
187                raw: args.to_string(),
188            })?;
189        let output = self.call_typed(typed_args, ctx).await?;
190        let output_json = serde_json::to_value(&output).ok();
191        let summary = self.format_output(output);
192        Ok(ToolOutput {
193            summary,
194            raw: output_json,
195            control_flow: T::control_flow(),
196            truncation: None,
197        })
198    }
199}
200
201pub(crate) type ToolRef = Arc<dyn Tool>;
202
203#[derive(Clone, Default)]
204pub struct ToolRegistry {
205    tools: HashMap<String, ToolRef>,
206}
207
208impl ToolRegistry {
209    pub fn register(&mut self, tool: impl Tool + 'static) {
210        self.tools.insert(tool.name().to_string(), Arc::new(tool));
211    }
212
213    pub fn register_arc(&mut self, tool: Arc<dyn Tool>) {
214        self.tools.insert(tool.name().to_string(), tool);
215    }
216
217    pub fn update(&mut self, tool: impl Tool + 'static) {
218        self.tools.insert(tool.name().to_string(), Arc::new(tool));
219    }
220
221    /// Remove a tool from the registry by name.
222    pub fn remove(&mut self, name: &str) {
223        self.tools.remove(name);
224    }
225
226    pub fn get(&self, name: &str) -> Option<ToolRef> {
227        self.tools.get(name).cloned()
228    }
229
230    pub fn definitions(&self) -> Vec<Value> {
231        self.tools.values().map(|tool| tool.definition()).collect()
232    }
233
234    pub fn len(&self) -> usize {
235        self.tools.len()
236    }
237
238    pub fn is_empty(&self) -> bool {
239        self.tools.is_empty()
240    }
241
242    /// Collect metadata for every registered tool, sorted by name.
243    ///
244    /// This is the preferred introspection API for consumers — it returns a
245    /// stable `ToolMetadata` struct per tool instead of having callers parse
246    /// the LLM-facing JSON definitions.
247    pub fn metadatas(&self) -> Vec<ToolMetadata> {
248        let mut list: Vec<_> = self.tools.values().map(|tool| tool.metadata()).collect();
249        list.sort_by(|a, b| a.name.cmp(&b.name));
250        list
251    }
252
253    /// Inject the internal `EventBus` into framework-provided tools.
254    pub(crate) fn inject_event_bus(&self, event_bus: &crate::engine::EventBus) {
255        for tool in self.tools.values() {
256            if let Some(fw) = tool.as_framework_tool() {
257                fw.set_event_bus(event_bus.clone());
258            }
259        }
260    }
261}