Skip to main content

nenjo_tools/
lib.rs

1//! # nenjo-tools
2//!
3//! Tool trait, types, and built-in tool implementations for the Nenjo agent platform.
4//!
5//! This crate provides:
6//! - The [`Tool`] trait for defining agent capabilities
7//! - Supporting types: [`SecurityPolicy`], [`RuntimeAdapter`], [`AgentMemory`]
8//! - Built-in tool implementations (shell, file I/O, git, search, web, memory, etc.)
9
10use async_trait::async_trait;
11use serde::{Deserialize, Serialize};
12
13// ── Supporting modules ───────────────────────────────────────────
14
15pub mod memory;
16pub mod runtime;
17pub mod security;
18
19// ── Tool implementations ─────────────────────────────────────────
20
21pub mod browser;
22pub mod browser_open;
23pub mod content_search;
24pub mod file_edit;
25pub mod file_read;
26pub mod file_write;
27pub mod git_operations;
28pub mod glob_search;
29pub mod http_request;
30pub mod memory_forget;
31pub mod memory_recall;
32pub mod memory_store;
33pub mod screenshot;
34pub mod shell;
35pub mod web_fetch;
36pub mod web_search_tool;
37
38// ── Re-exports ───────────────────────────────────────────────────
39
40pub use browser::{BrowserTool, ComputerUseConfig};
41pub use browser_open::BrowserOpenTool;
42pub use content_search::ContentSearchTool;
43pub use file_edit::FileEditTool;
44pub use file_read::FileReadTool;
45pub use file_write::FileWriteTool;
46pub use git_operations::GitOperationsTool;
47pub use glob_search::GlobSearchTool;
48pub use http_request::HttpRequestTool;
49pub use memory_forget::MemoryForgetTool;
50pub use memory_recall::MemoryRecallTool;
51pub use memory_store::MemoryStoreTool;
52pub use screenshot::ScreenshotTool;
53pub use shell::ShellTool;
54pub use web_fetch::WebFetchTool;
55pub use web_search_tool::WebSearchTool;
56
57// ── Core types ───────────────────────────────────────────────────
58
59/// Result of a tool execution.
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct ToolResult {
62    pub success: bool,
63    pub output: String,
64    pub error: Option<String>,
65}
66
67/// Classifies a tool's side-effect profile for filtering.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
69#[serde(rename_all = "snake_case")]
70pub enum ToolCategory {
71    /// Pure read/search — no side effects.
72    Read,
73    /// Mutates files, state, or external systems.
74    #[default]
75    Write,
76    /// Both read and write sub-operations (e.g. shell, git).
77    ReadWrite,
78}
79
80impl ToolCategory {
81    pub fn label(self) -> &'static str {
82        match self {
83            Self::Read => "READ",
84            Self::Write => "WRITE",
85            Self::ReadWrite => "READ/WRITE",
86        }
87    }
88
89    pub fn guidance(self) -> &'static str {
90        match self {
91            Self::Read => "Inspects or verifies state without persistent side effects.",
92            Self::Write => {
93                "Mutates persistent state. Use sparingly and avoid repeated calls in one turn."
94            }
95            Self::ReadWrite => {
96                "Can read and mutate state. Use carefully and avoid repeated calls in one turn."
97            }
98        }
99    }
100
101    pub fn is_write_like(self) -> bool {
102        !matches!(self, Self::Read)
103    }
104}
105
106/// Full specification of a tool for LLM registration.
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct ToolSpec {
109    pub name: String,
110    pub description: String,
111    pub parameters: serde_json::Value,
112    #[serde(default)]
113    pub category: ToolCategory,
114}
115
116/// Core tool trait — implement for any agent capability.
117///
118/// Tools are invoked by the agent turn loop when the LLM emits a function
119/// call matching [`Tool::name`]. The JSON arguments from the LLM are passed
120/// to [`Tool::execute`].
121#[async_trait]
122pub trait Tool: Send + Sync {
123    /// Tool name (used in LLM function calling).
124    fn name(&self) -> &str;
125
126    /// Human-readable description shown to the LLM.
127    fn description(&self) -> &str;
128
129    /// JSON Schema for the tool's parameters.
130    fn parameters_schema(&self) -> serde_json::Value;
131
132    /// Execute the tool with the given arguments.
133    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult>;
134
135    /// Tool category for profile-based filtering.
136    ///
137    /// Defaults to [`ToolCategory::Write`] (safe default — tools must opt-in
138    /// to [`ToolCategory::Read`]).
139    fn category(&self) -> ToolCategory {
140        ToolCategory::Write
141    }
142
143    /// Whether calling this tool should immediately end the turn loop.
144    ///
145    /// When `true`, the turn loop will stop after executing this tool without
146    /// pushing the tool result back into the conversation. This is useful for
147    /// tools like `pass_verdict` where the structured arguments are the signal
148    /// and no further LLM interaction is needed.
149    fn is_terminal(&self) -> bool {
150        false
151    }
152
153    /// Build the full spec for LLM registration.
154    fn spec(&self) -> ToolSpec {
155        let category = self.category();
156        ToolSpec {
157            name: self.name().to_string(),
158            description: format!(
159                "[{}] {} {}",
160                category.label(),
161                category.guidance(),
162                self.description()
163            ),
164            parameters: self.parameters_schema(),
165            category,
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    struct DummyTool;
175
176    #[async_trait]
177    impl Tool for DummyTool {
178        fn name(&self) -> &str {
179            "dummy"
180        }
181        fn description(&self) -> &str {
182            "A test tool"
183        }
184        fn parameters_schema(&self) -> serde_json::Value {
185            serde_json::json!({
186                "type": "object",
187                "properties": { "value": { "type": "string" } }
188            })
189        }
190        async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
191            Ok(ToolResult {
192                success: true,
193                output: args["value"].as_str().unwrap_or_default().to_string(),
194                error: None,
195            })
196        }
197    }
198
199    #[test]
200    fn spec_uses_tool_metadata() {
201        let spec = DummyTool.spec();
202        assert_eq!(spec.name, "dummy");
203        assert_eq!(spec.category, ToolCategory::Write);
204    }
205
206    #[tokio::test]
207    async fn execute_returns_output() {
208        let result = DummyTool
209            .execute(serde_json::json!({"value": "hello"}))
210            .await
211            .unwrap();
212        assert!(result.success);
213        assert_eq!(result.output, "hello");
214    }
215
216    #[test]
217    fn tool_result_roundtrip() {
218        let result = ToolResult {
219            success: false,
220            output: String::new(),
221            error: Some("boom".into()),
222        };
223        let json = serde_json::to_string(&result).unwrap();
224        let parsed: ToolResult = serde_json::from_str(&json).unwrap();
225        assert_eq!(parsed.error.as_deref(), Some("boom"));
226    }
227}