codive-core 0.1.0

Core types, traits, and utilities for Codive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Tool trait and registry for the Agent system
//!
//! This module defines the [`Tool`] trait that all tools must implement,
//! and the [`ToolRegistry`] for managing available tools.
//!
//! # Architecture
//!
//! Tools are the primary way the agent interacts with the outside world:
//! - Reading/writing files
//! - Executing commands
//! - Making web requests
//! - etc.
//!
//! Each tool has:
//! - A unique name
//! - A description (shown to the LLM)
//! - A JSON Schema for parameters
//! - An async execute method
//!
//! # Example
//!
//! ```rust,ignore
//! use codive_core::tool::{Tool, ToolOutput};
//! use async_trait::async_trait;
//!
//! struct EchoTool;
//!
//! #[async_trait]
//! impl Tool for EchoTool {
//!     fn name(&self) -> &str { "echo" }
//!     fn description(&self) -> &str { "Echoes back the input" }
//!     fn parameters_schema(&self) -> serde_json::Value {
//!         serde_json::json!({
//!             "type": "object",
//!             "properties": {
//!                 "message": { "type": "string" }
//!             },
//!             "required": ["message"]
//!         })
//!     }
//!     async fn execute(&self, params: serde_json::Value) -> ToolOutput {
//!         let message = params["message"].as_str().unwrap_or("no message");
//!         ToolOutput::success(message)
//!     }
//! }
//! ```

use codive_prompts::PromptStore;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

// ============================================================================
// ToolOutput
// ============================================================================

/// Metadata about a file change from a tool execution
///
/// This is used by write/edit tools to capture the before/after state
/// of files they modify, enabling diff display in the TUI.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileChangeMetadata {
    /// Path to the modified file
    pub file_path: String,
    /// Content before the change (None for new files)
    pub old_content: Option<String>,
    /// Content after the change
    pub new_content: String,
}

/// The output of a tool execution
///
/// Tools return this to indicate success or failure. The output is
/// always a string that will be sent back to the LLM.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolOutput {
    /// The output content (success message or error details)
    pub content: String,
    /// Whether the execution was successful
    pub is_error: bool,
    /// Optional metadata about file changes (for diff display)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_change: Option<FileChangeMetadata>,
}

impl ToolOutput {
    /// Create a successful tool output
    pub fn success(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            is_error: false,
            file_change: None,
        }
    }

    /// Create an error tool output
    pub fn error(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            is_error: true,
            file_change: None,
        }
    }

    /// Check if this output represents a successful execution
    pub fn is_success(&self) -> bool {
        !self.is_error
    }

    /// Attach file change metadata to the output (builder pattern)
    pub fn with_file_change(
        mut self,
        file_path: impl Into<String>,
        old_content: Option<String>,
        new_content: impl Into<String>,
    ) -> Self {
        self.file_change = Some(FileChangeMetadata {
            file_path: file_path.into(),
            old_content,
            new_content: new_content.into(),
        });
        self
    }
}

// ============================================================================
// Tool Trait
// ============================================================================

/// A tool that can be executed by the agent
///
/// Tools are the primary way the agent interacts with the outside world.
/// Each tool must be:
/// - `Send` - Can be transferred between threads
/// - `Sync` - Can be shared between threads
///
/// # Implementing a Tool
///
/// 1. Define a struct for your tool
/// 2. Implement the `Tool` trait
/// 3. Register it with `ToolRegistry`
///
/// # Thread Safety
///
/// The `Send + Sync` bounds are required because:
/// - Tools may be called from different async tasks
/// - The registry holds tools as `Arc<dyn Tool>`
/// - Multiple requests may use the same tool concurrently
#[async_trait]
pub trait Tool: Send + Sync {
    /// The unique name of this tool
    ///
    /// This is used by the LLM to call the tool and must be unique
    /// within a registry.
    fn name(&self) -> &str;

    /// A human-readable description of what this tool does
    ///
    /// This is shown to the LLM to help it decide when to use the tool.
    /// Be clear and concise about the tool's purpose and capabilities.
    fn description(&self) -> &str;

    /// JSON Schema describing the tool's parameters
    ///
    /// This schema is sent to the LLM so it knows what parameters
    /// to provide. Use standard JSON Schema format.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "type": "object",
    ///   "properties": {
    ///     "path": {
    ///       "type": "string",
    ///       "description": "The file path to read"
    ///     }
    ///   },
    ///   "required": ["path"]
    /// }
    /// ```
    fn parameters_schema(&self) -> serde_json::Value;

    /// Execute the tool with the given parameters
    ///
    /// Parameters are passed as a JSON value matching the schema
    /// returned by `parameters_schema()`.
    ///
    /// # Returns
    ///
    /// A `ToolOutput` indicating success or failure with a message.
    async fn execute(&self, params: serde_json::Value) -> ToolOutput;
}

// ============================================================================
// ToolInfo
// ============================================================================

/// Static information about a tool (for serialization to LLM)
///
/// This struct contains just the metadata needed to tell the LLM
/// about available tools. It's separate from `Tool` because it
/// can be serialized.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolInfo {
    /// The tool's name
    pub name: String,
    /// The tool's description
    pub description: String,
    /// JSON Schema for parameters
    pub parameters: serde_json::Value,
}

impl ToolInfo {
    /// Create ToolInfo from a Tool implementation
    pub fn from_tool(tool: &dyn Tool) -> Self {
        Self {
            name: tool.name().to_string(),
            description: tool.description().to_string(),
            parameters: tool.parameters_schema(),
        }
    }
}

// ============================================================================
// ToolRegistry
// ============================================================================

/// A registry of available tools
///
/// The registry stores tools and provides lookup by name.
/// Tools are stored as `Arc<dyn Tool>` to allow sharing.
///
/// # Thread Safety
///
/// The registry uses `Arc` for thread-safe sharing of tools.
/// Multiple async tasks can look up and execute tools concurrently.
///
/// # Example
///
/// ```rust,ignore
/// let mut registry = ToolRegistry::new();
/// registry.register(Arc::new(MyTool));
///
/// if let Some(tool) = registry.get("my_tool") {
///     let output = tool.execute(params).await;
/// }
/// ```
#[derive(Default)]
pub struct ToolRegistry {
    tools: HashMap<String, Arc<dyn Tool>>,
}

impl ToolRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            tools: HashMap::new(),
        }
    }

    /// Register a tool
    ///
    /// If a tool with the same name already exists, it will be replaced.
    pub fn register(&mut self, tool: Arc<dyn Tool>) {
        let name = tool.name().to_string();
        self.tools.insert(name, tool);
    }

    /// Get a tool by name
    ///
    /// Returns `None` if no tool with that name is registered.
    pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
        self.tools.get(name).cloned()
    }

    /// Check if a tool is registered
    pub fn contains(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Get the number of registered tools
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Check if the registry is empty
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Get info for all registered tools
    ///
    /// Returns a vector of `ToolInfo` suitable for sending to an LLM.
    pub fn tool_infos(&self) -> Vec<ToolInfo> {
        self.tools
            .values()
            .map(|tool| ToolInfo::from_tool(tool.as_ref()))
            .collect()
    }

    /// Get info for all registered tools with descriptions from PromptStore
    ///
    /// This allows tool descriptions to be overridden via the prompt configuration.
    /// If a tool has an override in the PromptStore, that description is used;
    /// otherwise, falls back to the tool's built-in description.
    pub fn tool_infos_with_store(&self, store: &PromptStore) -> Vec<ToolInfo> {
        self.tools
            .values()
            .map(|tool| {
                let description = store
                    .tool(tool.name())
                    .unwrap_or_else(|| tool.description())
                    .to_string();

                ToolInfo {
                    name: tool.name().to_string(),
                    description,
                    parameters: tool.parameters_schema(),
                }
            })
            .collect()
    }

    /// Get the names of all registered tools
    pub fn names(&self) -> Vec<&str> {
        self.tools.keys().map(|s| s.as_str()).collect()
    }

    /// Remove a tool by name
    ///
    /// Returns the removed tool if it existed.
    pub fn unregister(&mut self, name: &str) -> Option<Arc<dyn Tool>> {
        self.tools.remove(name)
    }
}

// Allow debug printing of the registry
impl std::fmt::Debug for ToolRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToolRegistry")
            .field("tools", &self.names())
            .finish()
    }
}

// ============================================================================
// RUST CONCEPTS EXPLAINED (for learning)
// ============================================================================
//
// 1. `#[async_trait]`
//    - Rust doesn't natively support async fn in traits (yet - it's coming!)
//    - `async_trait` macro transforms async fns into boxed futures
//    - This has a small runtime cost but enables async traits
//
// 2. `Send + Sync` bounds
//    - `Send` = safe to transfer between threads
//    - `Sync` = safe to share references between threads
//    - Required for tools that may be called from different async tasks
//    - Most types are Send + Sync by default
//
// 3. `dyn Tool`
//    - "Dynamic dispatch" - the concrete type is determined at runtime
//    - Contrast with generics (static dispatch, type known at compile time)
//    - Allows storing different tool types in the same HashMap
//
// 4. `Arc<dyn Tool>`
//    - `Arc` = Atomic Reference Counted pointer (thread-safe)
//    - Allows multiple owners of the same tool
//    - When last Arc is dropped, the tool is deallocated
//
// 5. `HashMap<String, Arc<dyn Tool>>`
//    - Tools indexed by name for O(1) lookup
//    - `Arc<dyn Tool>` allows storing any type implementing Tool
//
// 6. Why `&str` in trait vs `String` in ToolInfo?
//    - Trait returns `&str` - avoids allocation, caller can convert if needed
//    - ToolInfo stores `String` - owns its data for serialization
//
// 7. `impl Trait` vs generics
//    - `impl Into<String>` - accepts anything convertible to String
//    - More flexible API: can pass &str, String, Cow<str>, etc.
//
// **📚 Read:**
// - [Rust Book Ch 10.2 - Traits](https://doc.rust-lang.org/book/ch10-02-traits.html)
// - [Rust Book Ch 17.2 - Trait Objects](https://doc.rust-lang.org/book/ch17-02-trait-objects.html)
// - [Async Book Ch 4 - Pinning](https://rust-lang.github.io/async-book/04_pinning/01_chapter.html)

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // A simple test tool for unit tests
    struct TestTool {
        name: String,
    }

    impl TestTool {
        fn new(name: impl Into<String>) -> Self {
            Self { name: name.into() }
        }
    }

    #[async_trait]
    impl Tool for TestTool {
        fn name(&self) -> &str {
            &self.name
        }

        fn description(&self) -> &str {
            "A test tool for unit tests"
        }

        fn parameters_schema(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "input": { "type": "string" }
                }
            })
        }

        async fn execute(&self, params: serde_json::Value) -> ToolOutput {
            let input = params
                .get("input")
                .and_then(|v| v.as_str())
                .unwrap_or("default");
            ToolOutput::success(format!("Processed: {}", input))
        }
    }

    #[test]
    fn test_tool_output_success() {
        let output = ToolOutput::success("done");
        assert!(output.is_success());
        assert!(!output.is_error);
        assert_eq!(output.content, "done");
    }

    #[test]
    fn test_tool_output_error() {
        let output = ToolOutput::error("failed");
        assert!(!output.is_success());
        assert!(output.is_error);
        assert_eq!(output.content, "failed");
    }

    #[test]
    fn test_registry_register_and_get() {
        let mut registry = ToolRegistry::new();
        assert!(registry.is_empty());

        registry.register(Arc::new(TestTool::new("test")));
        assert!(!registry.is_empty());
        assert_eq!(registry.len(), 1);
        assert!(registry.contains("test"));

        let tool = registry.get("test").unwrap();
        assert_eq!(tool.name(), "test");
    }

    #[test]
    fn test_registry_get_nonexistent() {
        let registry = ToolRegistry::new();
        assert!(registry.get("nonexistent").is_none());
    }

    #[test]
    fn test_registry_multiple_tools() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(TestTool::new("tool1")));
        registry.register(Arc::new(TestTool::new("tool2")));
        registry.register(Arc::new(TestTool::new("tool3")));

        assert_eq!(registry.len(), 3);
        assert!(registry.contains("tool1"));
        assert!(registry.contains("tool2"));
        assert!(registry.contains("tool3"));
    }

    #[test]
    fn test_registry_replace_tool() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(TestTool::new("test")));
        registry.register(Arc::new(TestTool::new("test"))); // Same name

        // Should still have just one tool
        assert_eq!(registry.len(), 1);
    }

    #[test]
    fn test_registry_unregister() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(TestTool::new("test")));
        assert!(registry.contains("test"));

        let removed = registry.unregister("test");
        assert!(removed.is_some());
        assert!(!registry.contains("test"));
        assert!(registry.is_empty());
    }

    #[test]
    fn test_registry_names() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(TestTool::new("alpha")));
        registry.register(Arc::new(TestTool::new("beta")));

        let mut names = registry.names();
        names.sort();
        assert_eq!(names, vec!["alpha", "beta"]);
    }

    #[test]
    fn test_tool_info_from_tool() {
        let tool = TestTool::new("my_tool");
        let info = ToolInfo::from_tool(&tool);

        assert_eq!(info.name, "my_tool");
        assert_eq!(info.description, "A test tool for unit tests");
        assert!(info.parameters.is_object());
    }

    #[test]
    fn test_registry_tool_infos() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(TestTool::new("tool1")));
        registry.register(Arc::new(TestTool::new("tool2")));

        let infos = registry.tool_infos();
        assert_eq!(infos.len(), 2);
    }

    #[tokio::test]
    async fn test_tool_execute() {
        let tool = TestTool::new("test");
        let output = tool.execute(serde_json::json!({"input": "hello"})).await;

        assert!(output.is_success());
        assert_eq!(output.content, "Processed: hello");
    }

    #[tokio::test]
    async fn test_tool_execute_via_registry() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(TestTool::new("test")));

        let tool = registry.get("test").unwrap();
        let output = tool.execute(serde_json::json!({"input": "world"})).await;

        assert!(output.is_success());
        assert_eq!(output.content, "Processed: world");
    }

    #[test]
    fn test_registry_debug() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(TestTool::new("test")));

        let debug = format!("{:?}", registry);
        assert!(debug.contains("ToolRegistry"));
        assert!(debug.contains("test"));
    }
}