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