Skip to main content

nenjo_tool_api/
lib.rs

1//! Shared tool contracts for Nenjo agents, model providers, and runtimes.
2//!
3//! This crate owns the common tool API surface used across the Nenjo workspace.
4//! It is deliberately independent from the rest of the workspace so model
5//! integrations, SDK code, and worker runtimes can agree on tool schemas and
6//! execution results without depending on each other.
7//!
8//! The main entry points are:
9//!
10//! - [`Tool`], the async trait implemented by concrete tool runtimes.
11//! - [`ToolSpec`], the JSON-schema-backed metadata sent to model providers.
12//! - [`ToolCategory`], the side-effect classification used for guidance and
13//!   filtering.
14//! - [`ToolCall`], [`ToolResult`], and [`ToolResultMessage`], the request and
15//!   result payloads that flow through tool execution.
16//! - [`ToolAutonomy`] and [`ToolSecurity`], the SDK-level policy inputs used
17//!   when constructing tools.
18//!
19//! # Example
20//!
21//! ```rust
22//! use async_trait::async_trait;
23//! use serde_json::json;
24//! use nenjo_tool_api::{Tool, ToolCategory, ToolResult};
25//!
26//! struct EchoTool;
27//!
28//! #[async_trait]
29//! impl Tool for EchoTool {
30//!     fn name(&self) -> &str {
31//!         "echo"
32//!     }
33//!
34//!     fn description(&self) -> &str {
35//!         "Echoes a message back to the caller."
36//!     }
37//!
38//!     fn parameters_schema(&self) -> serde_json::Value {
39//!         json!({
40//!             "type": "object",
41//!             "properties": {
42//!                 "message": { "type": "string" }
43//!             },
44//!             "required": ["message"]
45//!         })
46//!     }
47//!
48//!     fn category(&self) -> ToolCategory {
49//!         ToolCategory::Read
50//!     }
51//!
52//!     async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
53//!         Ok(ToolResult::success(
54//!             args["message"].as_str().unwrap_or_default(),
55//!         ))
56//!     }
57//! }
58//! ```
59
60use async_trait::async_trait;
61pub use nenjo_content::{
62    ArtifactId, ArtifactInput, ArtifactInputSource, ArtifactInstruction, ArtifactRef, ArtifactSize,
63    MediaType, Sha256Digest, is_utf8_text_media_type,
64};
65use serde::{Deserialize, Serialize};
66use std::fmt::Display;
67use std::path::PathBuf;
68
69pub mod async_ops;
70
71pub use async_ops::{
72    AsyncControl, AsyncControls, AsyncOperationKind, AsyncOperationSignalKind,
73    AsyncOperationStartReceipt, AsyncOperationStatus, INSPECT_TOOL_NAME, InspectOperationsArgs,
74    SEND_INPUT_TOOL_NAME, STOP_TOOL_NAME, SendOperationInputArgs, StopOperationsArgs,
75    WAIT_TOOL_NAME, WaitOperationsArgs, deserialize_u64_from_json_number,
76    deserialize_usize_from_json_number, inspect_operations_parameters_schema,
77    send_operation_input_parameters_schema, stop_operations_parameters_schema,
78    wait_operations_parameters_schema,
79};
80
81/// Classifies a tool's side-effect profile for filtering and model guidance.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
83#[serde(rename_all = "snake_case")]
84pub enum ToolCategory {
85    /// Pure read/search with no persistent side effects.
86    Read,
87    /// Mutates files, state, or external systems.
88    #[default]
89    Write,
90    /// Both read and write sub-operations.
91    ReadWrite,
92}
93
94impl ToolCategory {
95    pub fn label(self) -> &'static str {
96        match self {
97            Self::Read => "READ",
98            Self::Write => "WRITE",
99            Self::ReadWrite => "READ/WRITE",
100        }
101    }
102
103    pub fn guidance(self) -> &'static str {
104        match self {
105            Self::Read => "Inspects or verifies state without persistent side effects.",
106            Self::Write => {
107                "Mutates persistent state. Use sparingly and avoid repeated calls in one turn."
108            }
109            Self::ReadWrite => {
110                "Can read and mutate state. Use carefully and avoid repeated calls in one turn."
111            }
112        }
113    }
114
115    pub fn is_write_like(self) -> bool {
116        !matches!(self, Self::Read)
117    }
118}
119
120/// Full specification of a tool for LLM registration.
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct ToolSpec {
123    pub name: String,
124    pub description: String,
125    pub parameters: serde_json::Value,
126    #[serde(default)]
127    pub category: ToolCategory,
128}
129
130/// A tool call requested by the LLM.
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
132pub struct ToolCall {
133    pub id: String,
134    pub name: String,
135    pub arguments: String,
136}
137
138impl Display for ToolCall {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        write!(f, "name={} arguments={}", self.name, self.arguments)
141    }
142}
143
144/// A tool result to feed back to the LLM.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct ToolResultMessage {
147    pub tool_call_id: String,
148    pub output: ToolOutput,
149}
150
151impl ToolResultMessage {
152    pub fn text(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
153        Self {
154            tool_call_id: tool_call_id.into(),
155            output: ToolOutput::text(content),
156        }
157    }
158
159    pub fn new(tool_call_id: impl Into<String>, output: ToolOutput) -> Self {
160        Self {
161            tool_call_id: tool_call_id.into(),
162            output,
163        }
164    }
165
166    pub fn with_artifact(mut self, artifact: ArtifactRef) -> Self {
167        self.output.push_artifact(artifact);
168        self
169    }
170}
171
172/// One ordered part of a tool's durable output.
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174#[serde(tag = "type", content = "value", rename_all = "snake_case")]
175pub enum ToolOutputPart {
176    Text(String),
177    Artifact(ArtifactRef),
178}
179
180/// Ordered, serializable tool output without decrypted bytes or host paths.
181#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(transparent)]
183pub struct ToolOutput(Vec<ToolOutputPart>);
184
185impl ToolOutput {
186    pub fn empty() -> Self {
187        Self::default()
188    }
189
190    pub fn text(value: impl Into<String>) -> Self {
191        Self(vec![ToolOutputPart::Text(value.into())])
192    }
193
194    pub fn from_parts(parts: Vec<ToolOutputPart>) -> Self {
195        Self(parts)
196    }
197
198    pub fn parts(&self) -> &[ToolOutputPart] {
199        &self.0
200    }
201
202    pub fn parts_mut(&mut self) -> &mut [ToolOutputPart] {
203        &mut self.0
204    }
205
206    pub fn push_text(&mut self, value: impl Into<String>) {
207        self.0.push(ToolOutputPart::Text(value.into()));
208    }
209
210    pub fn push_artifact(&mut self, artifact: ArtifactRef) {
211        self.0.push(ToolOutputPart::Artifact(artifact));
212    }
213
214    /// Retain artifact parts selected for an ephemeral model request.
215    /// Text parts are always preserved.
216    pub fn retain_artifacts(&mut self, mut retain: impl FnMut(&ArtifactRef) -> bool) {
217        self.0.retain(|part| match part {
218            ToolOutputPart::Text(_) => true,
219            ToolOutputPart::Artifact(artifact) => retain(artifact),
220        });
221    }
222
223    pub fn has_artifacts(&self) -> bool {
224        self.0
225            .iter()
226            .any(|part| matches!(part, ToolOutputPart::Artifact(_)))
227    }
228
229    pub fn is_empty(&self) -> bool {
230        self.0.is_empty()
231            || self.0.iter().all(|part| match part {
232                ToolOutputPart::Text(text) => text.is_empty(),
233                ToolOutputPart::Artifact(_) => false,
234            })
235    }
236
237    pub fn clear(&mut self) {
238        self.0.clear();
239    }
240
241    pub fn contains(&self, pattern: &str) -> bool {
242        self.text_content().contains(pattern)
243    }
244
245    /// Concatenate textual parts for logs, previews, and text-only UI surfaces.
246    pub fn text_content(&self) -> String {
247        self.0
248            .iter()
249            .filter_map(|part| match part {
250                ToolOutputPart::Text(text) => Some(text.as_str()),
251                ToolOutputPart::Artifact(_) => None,
252            })
253            .collect::<Vec<_>>()
254            .join("\n")
255    }
256
257    /// Borrow the sole text part without allocating.
258    pub fn as_text(&self) -> Option<&str> {
259        match self.0.as_slice() {
260            [ToolOutputPart::Text(text)] => Some(text),
261            [] | [ToolOutputPart::Artifact(_)] | [_, _, ..] => None,
262        }
263    }
264
265    pub fn len(&self) -> usize {
266        self.text_content().len()
267    }
268}
269
270impl From<String> for ToolOutput {
271    fn from(value: String) -> Self {
272        Self::text(value)
273    }
274}
275
276impl From<&str> for ToolOutput {
277    fn from(value: &str) -> Self {
278        Self::text(value)
279    }
280}
281
282impl Display for ToolOutput {
283    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        formatter.write_str(&self.text_content())
285    }
286}
287
288impl PartialEq<&str> for ToolOutput {
289    fn eq(&self, other: &&str) -> bool {
290        self.text_content() == *other
291    }
292}
293
294impl PartialEq<ToolOutput> for &str {
295    fn eq(&self, other: &ToolOutput) -> bool {
296        other == self
297    }
298}
299
300/// Result of a tool execution.
301#[derive(Debug, Clone, Serialize, Deserialize)]
302pub struct ToolResult {
303    pub success: bool,
304    pub output: ToolOutput,
305    pub error: Option<String>,
306}
307
308impl ToolResult {
309    pub fn success(output: impl Into<String>) -> Self {
310        Self {
311            success: true,
312            output: ToolOutput::text(output),
313            error: None,
314        }
315    }
316
317    pub fn failure(error: impl Into<String>) -> Self {
318        Self {
319            success: false,
320            output: ToolOutput::empty(),
321            error: Some(error.into()),
322        }
323    }
324
325    pub fn with_artifact(mut self, artifact: ArtifactRef) -> Self {
326        self.output.push_artifact(artifact);
327        self
328    }
329
330    pub fn with_artifacts(mut self, artifacts: Vec<ArtifactRef>) -> Self {
331        for artifact in artifacts {
332            self.output.push_artifact(artifact);
333        }
334        self
335    }
336}
337
338/// Runtime ownership surface for a tool.
339///
340/// This is intentionally separate from read/write category. It describes who
341/// owns tool availability and scoping so runtimes can rebuild or inherit tools
342/// correctly across abilities, domains, and sub-agents.
343#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
344#[serde(rename_all = "snake_case")]
345pub enum ToolOrigin {
346    /// Host/runtime tools such as shell, files, git, web, and memory.
347    #[default]
348    Host,
349    /// External MCP server tools governed by an agent or ability MCP assignment.
350    Mcp,
351    /// Platform resource tools whose availability is governed by platform scopes.
352    Platform,
353    /// Harness orchestration tools such as ability or sub-agent control.
354    Harness,
355}
356
357/// Core tool trait for agent capabilities.
358#[async_trait]
359pub trait Tool: Send + Sync {
360    /// Tool name used in LLM function calling.
361    fn name(&self) -> &str;
362
363    /// Human-readable description shown to the LLM.
364    fn description(&self) -> &str;
365
366    /// JSON Schema for the tool's parameters.
367    fn parameters_schema(&self) -> serde_json::Value;
368
369    /// Execute the tool with the given arguments.
370    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult>;
371
372    /// Tool category for profile-based filtering.
373    fn category(&self) -> ToolCategory {
374        ToolCategory::Write
375    }
376
377    /// Runtime ownership surface for this tool.
378    fn origin(&self) -> ToolOrigin {
379        ToolOrigin::Host
380    }
381
382    /// Whether calling this tool should immediately end the turn loop.
383    fn is_terminal(&self) -> bool {
384        false
385    }
386
387    /// Whether this tool should be advertised to the model for the next request.
388    ///
389    /// Tools remain registered for execution when hidden. Runtime control tools
390    /// can use this hook to appear only after their corresponding capability has
391    /// been activated.
392    async fn is_available_to_model(&self) -> bool {
393        true
394    }
395
396    /// Build the full spec for LLM registration.
397    fn spec(&self) -> ToolSpec {
398        let category = self.category();
399        ToolSpec {
400            name: self.name().to_string(),
401            description: format!(
402                "[{}] {} {}",
403                category.label(),
404                category.guidance(),
405                self.description()
406            ),
407            parameters: self.parameters_schema(),
408            category,
409        }
410    }
411}
412
413/// High-level autonomy requested while constructing runtime tools.
414#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
415#[serde(rename_all = "lowercase")]
416pub enum ToolAutonomy {
417    ReadOnly,
418    #[default]
419    Supervised,
420    Full,
421}
422
423/// SDK-level tool construction policy.
424///
425/// Concrete runtimes can translate this into their own enforcement policy.
426#[derive(Debug, Clone)]
427pub struct ToolSecurity {
428    pub autonomy: ToolAutonomy,
429    pub workspace_dir: PathBuf,
430    pub forwarded_env_names: Vec<String>,
431}
432
433impl Default for ToolSecurity {
434    fn default() -> Self {
435        let home = std::env::var("HOME")
436            .map(PathBuf::from)
437            .unwrap_or_else(|_| PathBuf::from("."));
438        Self {
439            autonomy: ToolAutonomy::Supervised,
440            workspace_dir: home.join(".nenjo").join("workspace"),
441            forwarded_env_names: Vec::new(),
442        }
443    }
444}
445
446impl ToolSecurity {
447    pub fn with_workspace_dir(workspace_dir: PathBuf) -> Self {
448        Self {
449            workspace_dir,
450            ..Default::default()
451        }
452    }
453}
454
455/// Sanitize a tool function name to match the strict OpenAI pattern
456/// `^[a-zA-Z0-9_-]+$`.
457///
458/// Used by OpenAI, DeepSeek, and other strict providers. Replaces dots, slashes,
459/// and any other disallowed characters with `_`.
460pub fn sanitize_tool_name(name: &str) -> String {
461    name.chars()
462        .map(|c| {
463            if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
464                c
465            } else {
466                '_'
467            }
468        })
469        .collect()
470}
471
472/// Light sanitization for lenient providers (Ollama) while preserving dots used
473/// in MCP namespaced tool names.
474pub fn sanitize_tool_name_lenient(name: &str) -> String {
475    name.chars()
476        .map(|c| {
477            if c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.') {
478                c
479            } else {
480                '_'
481            }
482        })
483        .collect()
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489
490    struct DummyTool;
491
492    #[async_trait]
493    impl Tool for DummyTool {
494        fn name(&self) -> &str {
495            "dummy"
496        }
497
498        fn description(&self) -> &str {
499            "A test tool"
500        }
501
502        fn parameters_schema(&self) -> serde_json::Value {
503            serde_json::json!({
504                "type": "object",
505                "properties": { "value": { "type": "string" } }
506            })
507        }
508
509        async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
510            Ok(ToolResult {
511                success: true,
512                output: args["value"]
513                    .as_str()
514                    .unwrap_or_default()
515                    .to_string()
516                    .into(),
517                error: None,
518            })
519        }
520    }
521
522    #[test]
523    fn spec_uses_tool_metadata() {
524        let spec = DummyTool.spec();
525        assert_eq!(spec.name, "dummy");
526        assert_eq!(spec.category, ToolCategory::Write);
527    }
528
529    #[tokio::test]
530    async fn execute_returns_output() {
531        let result = DummyTool
532            .execute(serde_json::json!({"value": "hello"}))
533            .await
534            .unwrap();
535        assert!(result.success);
536        assert_eq!(result.output.text_content(), "hello");
537    }
538
539    #[test]
540    fn tool_result_roundtrip() {
541        let result = ToolResult {
542            success: false,
543            output: String::new().into(),
544            error: Some("boom".into()),
545        };
546        let json = serde_json::to_string(&result).unwrap();
547        let parsed: ToolResult = serde_json::from_str(&json).unwrap();
548        assert_eq!(parsed.error.as_deref(), Some("boom"));
549    }
550
551    #[test]
552    fn tool_result_artifacts_are_immutable_refs_without_input_provenance() {
553        let artifact = ArtifactRef::new(
554            nenjo_content::ArtifactId::parse(uuid::Uuid::new_v4()).unwrap(),
555            nenjo_content::Sha256Digest::parse(&format!("sha256:{}", "a".repeat(64))).unwrap(),
556            nenjo_content::MediaType::parse("image/png").unwrap(),
557            nenjo_content::ArtifactSize::new(12),
558        );
559        let encoded =
560            serde_json::to_value(ToolResult::success("image ready").with_artifact(artifact))
561                .unwrap();
562
563        let artifact = &encoded["output"][1]["value"];
564        assert_eq!(artifact["media_type"], "image/png");
565        assert!(artifact.get("source").is_none());
566        assert!(artifact.get("bytes").is_none());
567        assert!(artifact.get("path").is_none());
568    }
569
570    #[test]
571    fn sanitize_tool_name_replaces_dots_and_slashes() {
572        assert_eq!(
573            sanitize_tool_name("app.nenjo.platform/tasks"),
574            "app_nenjo_platform_tasks"
575        );
576    }
577
578    #[test]
579    fn sanitize_tool_name_preserves_valid_chars() {
580        assert_eq!(sanitize_tool_name("my-tool_v2"), "my-tool_v2");
581    }
582
583    #[test]
584    fn sanitize_tool_name_lenient_preserves_dots() {
585        assert_eq!(
586            sanitize_tool_name_lenient("app.nenjo.platform/tasks"),
587            "app.nenjo.platform_tasks"
588        );
589    }
590}