1use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use std::fmt;
10use std::time::Instant;
11use uuid::Uuid;
12
13use crate::types::CompactStr;
14
15#[cfg(test)]
16use crate::config::constants::tools;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
23#[serde(transparent)]
24pub struct ToolInvocationId(Uuid);
25
26impl ToolInvocationId {
27 #[inline]
29 pub fn new() -> Self {
30 Self(Uuid::new_v4())
31 }
32
33 #[inline]
35 pub fn from_uuid(uuid: Uuid) -> Self {
36 Self(uuid)
37 }
38
39 pub fn parse(s: &str) -> Result<Self, uuid::Error> {
41 Uuid::parse_str(s).map(Self)
42 }
43
44 #[inline]
46 pub fn as_uuid(&self) -> &Uuid {
47 &self.0
48 }
49
50 #[inline]
52 pub fn to_string_hyphenated(&self) -> String {
53 self.0.hyphenated().to_string()
54 }
55
56 #[inline]
58 pub fn short(&self) -> String {
59 self.0.hyphenated().to_string()[..8].to_string()
60 }
61}
62
63impl Default for ToolInvocationId {
64 fn default() -> Self {
65 Self::new()
66 }
67}
68
69impl fmt::Display for ToolInvocationId {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 write!(f, "{}", self.0.hyphenated())
72 }
73}
74
75impl From<Uuid> for ToolInvocationId {
76 fn from(uuid: Uuid) -> Self {
77 Self(uuid)
78 }
79}
80
81#[derive(Debug, Clone)]
86pub struct ToolInvocation {
87 pub id: ToolInvocationId,
89 pub tool_name: CompactStr,
91 pub args: Value,
93 pub session_id: CompactStr,
95 pub attempt: u32,
97 pub parent_id: Option<ToolInvocationId>,
99 pub created_at: Instant,
101}
102
103impl ToolInvocation {
104 pub fn new(tool_name: impl Into<CompactStr>, args: Value, session_id: impl Into<CompactStr>) -> Self {
106 Self {
107 id: ToolInvocationId::new(),
108 tool_name: tool_name.into(),
109 args,
110 session_id: session_id.into(),
111 attempt: 1,
112 parent_id: None,
113 created_at: Instant::now(),
114 }
115 }
116
117 pub fn retry(&self) -> Self {
119 Self {
120 id: ToolInvocationId::new(),
121 tool_name: self.tool_name.clone(),
122 args: self.args.clone(),
123 session_id: self.session_id.clone(),
124 attempt: self.attempt + 1,
125 parent_id: self.parent_id,
126 created_at: Instant::now(),
127 }
128 }
129
130 pub fn child(&self, tool_name: impl Into<CompactStr>, args: Value) -> Self {
132 Self {
133 id: ToolInvocationId::new(),
134 tool_name: tool_name.into(),
135 args,
136 session_id: self.session_id.clone(),
137 attempt: 1,
138 parent_id: Some(self.id),
139 created_at: Instant::now(),
140 }
141 }
142
143 #[inline]
145 pub fn elapsed(&self) -> std::time::Duration {
146 self.created_at.elapsed()
147 }
148
149 #[inline]
151 pub fn is_retry(&self) -> bool {
152 self.attempt > 1
153 }
154
155 #[inline]
157 pub fn is_nested(&self) -> bool {
158 self.parent_id.is_some()
159 }
160}
161
162#[derive(Debug, Clone)]
164#[must_use = "build the invocation before discarding the builder"]
165pub struct InvocationBuilder {
166 tool_name: CompactStr,
167 args: Value,
168 session_id: CompactStr,
169 attempt: u32,
170 parent_id: Option<ToolInvocationId>,
171 id: Option<ToolInvocationId>,
172}
173
174impl InvocationBuilder {
175 pub fn new(tool_name: impl Into<CompactStr>) -> Self {
177 Self {
178 tool_name: tool_name.into(),
179 args: Value::Null,
180 session_id: CompactStr::default(),
181 attempt: 1,
182 parent_id: None,
183 id: None,
184 }
185 }
186
187 pub fn args(mut self, args: Value) -> Self {
189 self.args = args;
190 self
191 }
192
193 pub fn session_id(mut self, session_id: impl Into<CompactStr>) -> Self {
195 self.session_id = session_id.into();
196 self
197 }
198
199 pub fn attempt(mut self, attempt: u32) -> Self {
201 self.attempt = attempt.max(1);
202 self
203 }
204
205 pub fn parent_id(mut self, parent_id: ToolInvocationId) -> Self {
207 self.parent_id = Some(parent_id);
208 self
209 }
210
211 pub fn id(mut self, id: ToolInvocationId) -> Self {
213 self.id = Some(id);
214 self
215 }
216
217 #[must_use]
219 pub fn build(self) -> ToolInvocation {
220 ToolInvocation {
221 id: self.id.unwrap_or_default(),
222 tool_name: self.tool_name,
223 args: self.args,
224 session_id: self.session_id,
225 attempt: self.attempt,
226 parent_id: self.parent_id,
227 created_at: Instant::now(),
228 }
229 }
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235 use serde_json::json;
236
237 #[test]
238 fn test_invocation_id_display() {
239 let id = ToolInvocationId::new();
240 let display = id.to_string();
241 assert_eq!(display.len(), 36); assert!(display.contains('-'));
243 }
244
245 #[test]
246 fn test_invocation_id_short() {
247 let id = ToolInvocationId::new();
248 let short = id.short();
249 assert_eq!(short.len(), 8);
250 }
251
252 #[test]
253 fn test_invocation_id_parse() {
254 let id = ToolInvocationId::new();
255 let s = id.to_string();
256 let parsed = ToolInvocationId::parse(&s).unwrap();
257 assert_eq!(id, parsed);
258 }
259
260 #[test]
261 fn test_invocation_creation() {
262 let inv = ToolInvocation::new("read_file", json!({"path": "/tmp/test"}), "session-123");
263 assert_eq!(inv.tool_name, "read_file");
264 assert_eq!(inv.session_id, "session-123");
265 assert_eq!(inv.attempt, 1);
266 assert!(inv.parent_id.is_none());
267 }
268
269 #[test]
270 fn test_invocation_retry() {
271 let inv = ToolInvocation::new(tools::GREP_FILE, json!({"pattern": "TODO"}), "session-456");
272 let retry = inv.retry();
273
274 assert_ne!(inv.id, retry.id);
275 assert_eq!(retry.attempt, 2);
276 assert_eq!(retry.tool_name, inv.tool_name);
277 assert_eq!(retry.args, inv.args);
278 }
279
280 #[test]
281 fn test_invocation_child() {
282 let parent = ToolInvocation::new("task_tracker", json!({}), "session-789");
283 let child = parent.child("read_file", json!({"path": "/src/main.rs"}));
284
285 assert_eq!(child.parent_id, Some(parent.id));
286 assert_eq!(child.session_id, parent.session_id);
287 assert_eq!(child.attempt, 1);
288 }
289
290 #[test]
291 fn test_builder() {
292 let inv = InvocationBuilder::new("write_file")
293 .args(json!({"path": "/out.txt", "content": "hello"}))
294 .session_id("builder-session")
295 .attempt(3)
296 .build();
297
298 assert_eq!(inv.tool_name, "write_file");
299 assert_eq!(inv.session_id, "builder-session");
300 assert_eq!(inv.attempt, 3);
301 }
302
303 #[test]
304 fn test_builder_with_parent() {
305 let parent_id = ToolInvocationId::new();
306 let inv = InvocationBuilder::new("nested_tool")
307 .session_id("test")
308 .parent_id(parent_id)
309 .build();
310
311 assert_eq!(inv.parent_id, Some(parent_id));
312 assert!(inv.is_nested());
313 }
314
315 #[test]
316 fn test_serde_roundtrip() {
317 let id = ToolInvocationId::new();
318 let json = serde_json::to_string(&id).unwrap();
319 let parsed: ToolInvocationId = serde_json::from_str(&json).unwrap();
320 assert_eq!(id, parsed);
321 }
322}