1use async_trait::async_trait;
63use serde::{Deserialize, Serialize};
64use std::fmt::Display;
65use std::path::PathBuf;
66
67pub mod async_ops;
68
69pub use async_ops::{
70 AsyncControl, AsyncControls, AsyncOperationKind, AsyncOperationSignalKind,
71 AsyncOperationStartReceipt, AsyncOperationStatus, INSPECT_TOOL_NAME, InspectOperationsArgs,
72 SEND_INPUT_TOOL_NAME, STOP_TOOL_NAME, SendOperationInputArgs, StopOperationsArgs,
73 WAIT_TOOL_NAME, WaitOperationsArgs, deserialize_u64_from_json_number,
74 deserialize_usize_from_json_number, inspect_operations_parameters_schema,
75 send_operation_input_parameters_schema, stop_operations_parameters_schema,
76 wait_operations_parameters_schema,
77};
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
81#[serde(rename_all = "snake_case")]
82pub enum ToolCategory {
83 Read,
85 #[default]
87 Write,
88 ReadWrite,
90}
91
92impl ToolCategory {
93 pub fn label(self) -> &'static str {
94 match self {
95 Self::Read => "READ",
96 Self::Write => "WRITE",
97 Self::ReadWrite => "READ/WRITE",
98 }
99 }
100
101 pub fn guidance(self) -> &'static str {
102 match self {
103 Self::Read => "Inspects or verifies state without persistent side effects.",
104 Self::Write => {
105 "Mutates persistent state. Use sparingly and avoid repeated calls in one turn."
106 }
107 Self::ReadWrite => {
108 "Can read and mutate state. Use carefully and avoid repeated calls in one turn."
109 }
110 }
111 }
112
113 pub fn is_write_like(self) -> bool {
114 !matches!(self, Self::Read)
115 }
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct ToolSpec {
121 pub name: String,
122 pub description: String,
123 pub parameters: serde_json::Value,
124 #[serde(default)]
125 pub category: ToolCategory,
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct ToolCall {
131 pub id: String,
132 pub name: String,
133 pub arguments: String,
134}
135
136impl Display for ToolCall {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 write!(f, "name={} arguments={}", self.name, self.arguments)
139 }
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct ToolResultMessage {
145 pub tool_call_id: String,
146 pub content: String,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct ToolResult {
152 pub success: bool,
153 pub output: String,
154 pub error: Option<String>,
155}
156
157#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
163#[serde(rename_all = "snake_case")]
164pub enum ToolOrigin {
165 #[default]
167 Host,
168 Mcp,
170 Platform,
172 Harness,
174}
175
176#[async_trait]
178pub trait Tool: Send + Sync {
179 fn name(&self) -> &str;
181
182 fn description(&self) -> &str;
184
185 fn parameters_schema(&self) -> serde_json::Value;
187
188 async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult>;
190
191 fn category(&self) -> ToolCategory {
193 ToolCategory::Write
194 }
195
196 fn origin(&self) -> ToolOrigin {
198 ToolOrigin::Host
199 }
200
201 fn is_terminal(&self) -> bool {
203 false
204 }
205
206 async fn is_available_to_model(&self) -> bool {
212 true
213 }
214
215 fn spec(&self) -> ToolSpec {
217 let category = self.category();
218 ToolSpec {
219 name: self.name().to_string(),
220 description: format!(
221 "[{}] {} {}",
222 category.label(),
223 category.guidance(),
224 self.description()
225 ),
226 parameters: self.parameters_schema(),
227 category,
228 }
229 }
230}
231
232#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
234#[serde(rename_all = "lowercase")]
235pub enum ToolAutonomy {
236 ReadOnly,
237 #[default]
238 Supervised,
239 Full,
240}
241
242#[derive(Debug, Clone)]
246pub struct ToolSecurity {
247 pub autonomy: ToolAutonomy,
248 pub workspace_dir: PathBuf,
249 pub forwarded_env_names: Vec<String>,
250}
251
252impl Default for ToolSecurity {
253 fn default() -> Self {
254 let home = std::env::var("HOME")
255 .map(PathBuf::from)
256 .unwrap_or_else(|_| PathBuf::from("."));
257 Self {
258 autonomy: ToolAutonomy::Supervised,
259 workspace_dir: home.join(".nenjo").join("workspace"),
260 forwarded_env_names: Vec::new(),
261 }
262 }
263}
264
265impl ToolSecurity {
266 pub fn with_workspace_dir(workspace_dir: PathBuf) -> Self {
267 Self {
268 workspace_dir,
269 ..Default::default()
270 }
271 }
272}
273
274pub fn sanitize_tool_name(name: &str) -> String {
280 name.chars()
281 .map(|c| {
282 if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
283 c
284 } else {
285 '_'
286 }
287 })
288 .collect()
289}
290
291pub fn sanitize_tool_name_lenient(name: &str) -> String {
294 name.chars()
295 .map(|c| {
296 if c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.') {
297 c
298 } else {
299 '_'
300 }
301 })
302 .collect()
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 struct DummyTool;
310
311 #[async_trait]
312 impl Tool for DummyTool {
313 fn name(&self) -> &str {
314 "dummy"
315 }
316
317 fn description(&self) -> &str {
318 "A test tool"
319 }
320
321 fn parameters_schema(&self) -> serde_json::Value {
322 serde_json::json!({
323 "type": "object",
324 "properties": { "value": { "type": "string" } }
325 })
326 }
327
328 async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
329 Ok(ToolResult {
330 success: true,
331 output: args["value"].as_str().unwrap_or_default().to_string(),
332 error: None,
333 })
334 }
335 }
336
337 #[test]
338 fn spec_uses_tool_metadata() {
339 let spec = DummyTool.spec();
340 assert_eq!(spec.name, "dummy");
341 assert_eq!(spec.category, ToolCategory::Write);
342 }
343
344 #[tokio::test]
345 async fn execute_returns_output() {
346 let result = DummyTool
347 .execute(serde_json::json!({"value": "hello"}))
348 .await
349 .unwrap();
350 assert!(result.success);
351 assert_eq!(result.output, "hello");
352 }
353
354 #[test]
355 fn tool_result_roundtrip() {
356 let result = ToolResult {
357 success: false,
358 output: String::new(),
359 error: Some("boom".into()),
360 };
361 let json = serde_json::to_string(&result).unwrap();
362 let parsed: ToolResult = serde_json::from_str(&json).unwrap();
363 assert_eq!(parsed.error.as_deref(), Some("boom"));
364 }
365
366 #[test]
367 fn sanitize_tool_name_replaces_dots_and_slashes() {
368 assert_eq!(
369 sanitize_tool_name("app.nenjo.platform/tasks"),
370 "app_nenjo_platform_tasks"
371 );
372 }
373
374 #[test]
375 fn sanitize_tool_name_preserves_valid_chars() {
376 assert_eq!(sanitize_tool_name("my-tool_v2"), "my-tool_v2");
377 }
378
379 #[test]
380 fn sanitize_tool_name_lenient_preserves_dots() {
381 assert_eq!(
382 sanitize_tool_name_lenient("app.nenjo.platform/tasks"),
383 "app.nenjo.platform_tasks"
384 );
385 }
386}