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
114struct Hosted {
115 inner: Arc<dyn Tool>,
116 spec: ToolSpec,
117}
118
119#[async_trait]
120impl Tool for Hosted {
121 fn spec(&self) -> &ToolSpec {
122 &self.spec
123 }
124
125 async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
126 self.inner.call(args, ctx).await
127 }
128}
129
130pub fn hosted(inner: Arc<dyn Tool>, kind: HostedTool) -> Arc<dyn Tool> {
134 assert_eq!(
135 inner.spec().name,
136 kind.name(),
137 "a hosted stand-in carries the hosted tool's name"
138 );
139 let spec = ToolSpec {
140 hosted: Some(kind),
141 ..inner.spec().clone()
142 };
143 Arc::new(Hosted { inner, spec })
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149
150 #[test]
151 fn for_call_builds_stable_keys() {
152 let run = RunId::new();
153 let a = ToolContext::for_call(run, 3, 1);
154 assert_eq!(a.run_id, Some(run));
155 assert_eq!(a.idempotency_key, Some(format!("{run}:3:1")));
156 assert_eq!(
157 ToolContext::for_call(run, 3, 1).idempotency_key,
158 a.idempotency_key
159 );
160 assert_ne!(
161 ToolContext::for_call(run, 4, 1).idempotency_key,
162 a.idempotency_key
163 );
164 assert_eq!(ToolContext::default().idempotency_key, None);
165 }
166}