1use async_trait::async_trait;
2use serde_json::Value;
3use std::sync::Arc;
4use troupekit_core::http::{HttpError, HttpErrorKind};
5use troupekit_core::ids::RunId;
6use troupekit_core::tool::{HostedTool, ToolSpec};
7
8#[derive(Debug, Clone, Default)]
13pub struct ToolContext {
14 pub run_id: Option<RunId>,
15 pub idempotency_key: Option<String>,
16}
17
18impl ToolContext {
19 pub fn for_call(run_id: RunId, step: u64, index: usize) -> ToolContext {
23 ToolContext {
24 run_id: Some(run_id),
25 idempotency_key: Some(format!("{run_id}:{step}:{index}")),
26 }
27 }
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ToolOutput {
35 pub content: String,
36 pub is_error: bool,
37}
38
39impl ToolOutput {
40 pub fn text(content: impl Into<String>) -> Self {
43 Self {
44 content: content.into(),
45 is_error: false,
46 }
47 }
48
49 pub fn error(content: impl Into<String>) -> Self {
52 Self {
53 content: content.into(),
54 is_error: true,
55 }
56 }
57
58 pub fn from_result(result: Result<ToolOutput, ToolError>) -> Self {
62 result.unwrap_or_else(|e| Self::error(e.to_string()))
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
70pub enum ToolError {
71 #[error("invalid arguments: {0}")]
72 InvalidArgs(String),
73 #[error("unknown tool: {0}")]
74 UnknownTool(String),
75 #[error("duplicate tool: {0}")]
76 DuplicateTool(String),
77 #[error("invalid tool spec: {0}")]
78 InvalidSpec(String),
79 #[error("config: {0}")]
80 Config(String),
81 #[error("blocked: {0}")]
82 Blocked(String),
83 #[error("http: {0}")]
84 Http(String),
85 #[error("decode: {0}")]
86 Decode(String),
87 #[error("failed: {0}")]
88 Failed(String),
89}
90
91impl From<HttpError> for ToolError {
92 fn from(e: HttpError) -> Self {
93 match e.kind {
94 HttpErrorKind::Invalid => ToolError::InvalidArgs(e.message),
95 HttpErrorKind::Blocked => ToolError::Blocked(e.message),
96 _ => ToolError::Http(e.message),
97 }
98 }
99}
100
101#[async_trait]
105pub trait Tool: Send + Sync {
106 fn spec(&self) -> &ToolSpec;
108
109 async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError>;
112
113 fn uses_network(&self) -> bool {
117 false
118 }
119}
120
121struct Networked(Arc<dyn Tool>);
122
123#[async_trait]
124impl Tool for Networked {
125 fn spec(&self) -> &ToolSpec {
126 self.0.spec()
127 }
128
129 async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
130 self.0.call(args, ctx).await
131 }
132
133 fn uses_network(&self) -> bool {
134 true
135 }
136}
137
138pub(crate) fn networked(inner: Arc<dyn Tool>) -> Arc<dyn Tool> {
142 let tool: Arc<dyn Tool> = Arc::new(Networked(inner));
143 assert!(tool.uses_network(), "a networked tool reports the network");
144 tool
145}
146
147struct Hosted {
148 inner: Arc<dyn Tool>,
149 spec: ToolSpec,
150}
151
152#[async_trait]
153impl Tool for Hosted {
154 fn spec(&self) -> &ToolSpec {
155 &self.spec
156 }
157
158 async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
159 self.inner.call(args, ctx).await
160 }
161
162 fn uses_network(&self) -> bool {
163 true
164 }
165}
166
167pub fn hosted(inner: Arc<dyn Tool>, kind: HostedTool) -> Arc<dyn Tool> {
171 assert_eq!(
172 inner.spec().name,
173 kind.name(),
174 "a hosted stand-in carries the hosted tool's name"
175 );
176 let spec = ToolSpec {
177 hosted: Some(kind),
178 ..inner.spec().clone()
179 };
180 Arc::new(Hosted { inner, spec })
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn hosted_stand_in_reports_the_network() {
189 let inner = crate::typed::typed_tool(
190 "web_search",
191 "Search.",
192 |_a: serde_json::Value, _c: ToolContext| async { Ok(ToolOutput::text("x")) },
193 );
194 let inner: Arc<dyn Tool> = Arc::new(inner);
195 assert!(!inner.uses_network(), "a plain tool stays local by default");
196 assert!(hosted(inner, HostedTool::WebSearch { max_uses: 1 }).uses_network());
197 }
198
199 #[test]
200 fn for_call_builds_stable_keys() {
201 let run = RunId::new();
202 let a = ToolContext::for_call(run, 3, 1);
203 assert_eq!(a.run_id, Some(run));
204 assert_eq!(a.idempotency_key, Some(format!("{run}:3:1")));
205 assert_eq!(
206 ToolContext::for_call(run, 3, 1).idempotency_key,
207 a.idempotency_key
208 );
209 assert_ne!(
210 ToolContext::for_call(run, 4, 1).idempotency_key,
211 a.idempotency_key
212 );
213 assert_eq!(ToolContext::default().idempotency_key, None);
214 }
215}