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 pub user_event_tx: mpsc::UnboundedSender<UserEvent>,
51 pub llm_client: Option<Arc<dyn LlmClient>>,
52 pub session_store: Option<Arc<dyn SessionStore>>,
53 pub language: crate::types::Language,
56 pub cancel_token: tokio_util::sync::CancellationToken,
58}
59
60impl ToolContext {
61 pub fn emit_user_event(&self, event: UserEvent) {
63 let _ = self.user_event_tx.send(event);
64 }
65
66 pub fn emit_progress(&self, text: impl Into<String>) {
68 self.emit_user_event(UserEvent::Progress { text: text.into() });
69 }
70}
71
72
73#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
77pub struct ToolMetadata {
78 pub name: String,
80 pub description: String,
82 pub origin: String,
86 pub version: String,
88 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 #[allow(private_interfaces)]
104 fn as_framework_tool(&self) -> Option<&dyn FrameworkTool> {
105 None
106 }
107
108 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
133pub(crate) trait FrameworkTool: Tool {
141 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 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 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 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}