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#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
76pub struct ToolMetadata {
77 pub name: String,
79 pub description: String,
81 pub origin: String,
85 pub version: String,
87 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 #[allow(private_interfaces)]
103 fn as_framework_tool(&self) -> Option<&dyn FrameworkTool> {
104 None
105 }
106
107 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
132pub(crate) trait FrameworkTool: Tool {
140 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 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 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 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}