1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
84#[serde(rename_all = "snake_case")]
85pub enum ToolCategory {
86 Read,
88 #[default]
90 Write,
91 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#[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#[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#[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#[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#[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 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 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 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#[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
345#[serde(rename_all = "snake_case")]
346pub enum ToolOrigin {
347 #[default]
349 Host,
350 Mcp,
352 Platform,
354 Harness,
356}
357
358#[async_trait]
360pub trait Tool: Send + Sync {
361 fn name(&self) -> &str;
363
364 fn description(&self) -> &str;
366
367 fn parameters_schema(&self) -> serde_json::Value;
369
370 async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult>;
372
373 fn category(&self) -> ToolCategory {
375 ToolCategory::Write
376 }
377
378 fn origin(&self) -> ToolOrigin {
380 ToolOrigin::Host
381 }
382
383 fn is_terminal(&self) -> bool {
385 false
386 }
387
388 async fn is_available_to_model(&self) -> bool {
394 true
395 }
396
397 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#[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#[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
456pub 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
473pub 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}