1mod artifacts;
13mod builtin;
14mod process;
15mod program_tool;
16mod registry;
17mod selector;
18pub mod skill;
19pub mod task;
20mod types;
21
22pub use artifacts::{ArtifactStore, ArtifactStoreLimits, ToolArtifact};
23pub(crate) use builtin::register_skill;
24pub use builtin::{
25 register_generate_object, register_program, register_program_with_catalog, register_task,
26 register_task_with_mcp,
27};
28pub use program_tool::ProgramTool;
29pub use registry::ToolRegistry;
30pub use selector::{select_tools_for_messages, select_tools_for_prompt};
31pub use task::{
32 parallel_task_params_schema, task_params_schema, ParallelTaskParams, ParallelTaskTool,
33 TaskExecutor, TaskParams, TaskResult, TaskTool,
34};
35pub use types::{Tool, ToolContext, ToolEventSender, ToolOutput, ToolStreamEvent};
36
37use crate::file_history::{self, FileHistory};
38use crate::llm::ToolDefinition;
39use crate::text::truncate_utf8;
40use anyhow::Result;
41use serde::{Deserialize, Serialize};
42use std::collections::HashMap;
43use std::path::PathBuf;
44use std::sync::Arc;
45
46pub const MAX_OUTPUT_SIZE: usize = 100 * 1024; pub const MAX_READ_LINES: usize = 2000;
51
52pub const MAX_LINE_LENGTH: usize = 2000;
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub(crate) struct ToolOutputArtifact {
57 pub artifact_id: String,
58 pub artifact_uri: String,
59 pub original_bytes: usize,
60 pub shown_bytes: usize,
61}
62
63#[derive(Debug, Clone)]
64pub(crate) struct TruncatedToolOutput {
65 pub content: String,
66 pub artifact: Option<ToolOutputArtifact>,
67}
68
69pub(crate) fn truncate_tool_output_with_artifact(
70 tool_name: &str,
71 output: &str,
72) -> TruncatedToolOutput {
73 if output.len() <= MAX_OUTPUT_SIZE {
74 return TruncatedToolOutput {
75 content: output.to_string(),
76 artifact: None,
77 };
78 }
79
80 let shown = truncate_utf8(output, MAX_OUTPUT_SIZE);
81 let artifact = tool_output_artifact(tool_name, output, shown.len());
82 let artifact_uri = artifact.artifact_uri.clone();
83 let content = format!(
84 "{}\n\n[tool output truncated: showing the first {} of {} bytes. Full output artifact: {}. Use narrower arguments such as offset/limit or filtering when possible.]",
85 shown,
86 shown.len(),
87 output.len(),
88 artifact_uri,
89 );
90
91 TruncatedToolOutput {
92 content,
93 artifact: Some(artifact),
94 }
95}
96
97pub(crate) fn tool_output_artifact(
98 tool_name: &str,
99 output: &str,
100 shown_bytes: usize,
101) -> ToolOutputArtifact {
102 use std::hash::{Hash, Hasher};
103
104 let mut hasher = std::collections::hash_map::DefaultHasher::new();
105 tool_name.hash(&mut hasher);
106 output.len().hash(&mut hasher);
107 output.hash(&mut hasher);
108 let digest = hasher.finish();
109 let sanitized_tool = tool_name
110 .chars()
111 .map(|ch| {
112 if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' {
113 ch
114 } else {
115 '_'
116 }
117 })
118 .collect::<String>();
119 let artifact_id = format!("tool-output:{sanitized_tool}:{digest:016x}");
120 let artifact_uri = format!("a3s://tool-output/{sanitized_tool}/{digest:016x}");
121
122 ToolOutputArtifact {
123 artifact_id,
124 artifact_uri,
125 original_bytes: output.len(),
126 shown_bytes,
127 }
128}
129
130pub(crate) fn merge_tool_output_artifact_metadata(
131 metadata: Option<serde_json::Value>,
132 artifact: &ToolOutputArtifact,
133) -> serde_json::Value {
134 let artifact_json = serde_json::json!({
135 "artifact_id": artifact.artifact_id,
136 "artifact_uri": artifact.artifact_uri,
137 "original_bytes": artifact.original_bytes,
138 "shown_bytes": artifact.shown_bytes,
139 });
140
141 match metadata {
142 Some(serde_json::Value::Object(mut object)) => {
143 object.insert("artifact".to_string(), artifact_json);
144 serde_json::Value::Object(object)
145 }
146 Some(value) => serde_json::json!({
147 "artifact": artifact_json,
148 "previous_metadata": value,
149 }),
150 None => serde_json::json!({
151 "artifact": artifact_json,
152 }),
153 }
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct ToolResult {
159 pub name: String,
160 pub output: String,
161 pub exit_code: i32,
162 #[serde(skip_serializing_if = "Option::is_none")]
163 pub metadata: Option<serde_json::Value>,
164 #[serde(skip)]
166 pub images: Vec<crate::llm::Attachment>,
167}
168
169impl ToolResult {
170 pub fn success(name: &str, output: String) -> Self {
171 Self {
172 name: name.to_string(),
173 output,
174 exit_code: 0,
175 metadata: None,
176 images: Vec::new(),
177 }
178 }
179
180 pub fn error(name: &str, message: String) -> Self {
181 Self {
182 name: name.to_string(),
183 output: message,
184 exit_code: 1,
185 metadata: None,
186 images: Vec::new(),
187 }
188 }
189}
190
191impl From<ToolOutput> for ToolResult {
192 fn from(output: ToolOutput) -> Self {
193 Self {
194 name: String::new(),
195 output: output.content,
196 exit_code: if output.success { 0 } else { 1 },
197 metadata: output.metadata,
198 images: output.images,
199 }
200 }
201}
202
203pub struct ToolExecutor {
208 workspace: PathBuf,
209 registry: Arc<ToolRegistry>,
210 file_history: Arc<FileHistory>,
211 command_env: Option<Arc<HashMap<String, String>>>,
212}
213
214impl ToolExecutor {
215 pub fn new(workspace: String) -> Self {
216 Self::new_with_options(workspace, None, ArtifactStoreLimits::default())
217 }
218
219 pub fn new_with_command_env(workspace: String, command_env: HashMap<String, String>) -> Self {
220 Self::new_with_options(workspace, Some(command_env), ArtifactStoreLimits::default())
221 }
222
223 pub fn new_with_artifact_limits(
224 workspace: String,
225 artifact_limits: ArtifactStoreLimits,
226 ) -> Self {
227 Self::new_with_options(workspace, None, artifact_limits)
228 }
229
230 pub fn new_with_command_env_and_artifact_limits(
231 workspace: String,
232 command_env: HashMap<String, String>,
233 artifact_limits: ArtifactStoreLimits,
234 ) -> Self {
235 Self::new_with_options(workspace, Some(command_env), artifact_limits)
236 }
237
238 fn new_with_options(
239 workspace: String,
240 command_env: Option<HashMap<String, String>>,
241 artifact_limits: ArtifactStoreLimits,
242 ) -> Self {
243 let workspace_path = PathBuf::from(&workspace);
244 let registry = Arc::new(ToolRegistry::with_artifact_limits(
245 workspace_path.clone(),
246 artifact_limits,
247 ));
248
249 builtin::register_builtins(®istry);
251 builtin::register_batch(®istry);
253 builtin::register_program(®istry);
254
255 Self {
256 workspace: workspace_path,
257 registry,
258 file_history: Arc::new(FileHistory::new(500)),
259 command_env: command_env.map(Arc::new),
260 }
261 }
262
263 fn check_workspace_boundary(
264 name: &str,
265 args: &serde_json::Value,
266 ctx: &ToolContext,
267 ) -> Result<()> {
268 let path_field = match name {
269 "read" | "write" | "edit" | "patch" => Some("file_path"),
270 "ls" | "grep" | "glob" => Some("path"),
271 _ => None,
272 };
273
274 if let Some(field) = path_field {
275 if let Some(path_str) = args.get(field).and_then(|v| v.as_str()) {
276 let target = if std::path::Path::new(path_str).is_absolute() {
277 std::path::PathBuf::from(path_str)
278 } else {
279 ctx.workspace.join(path_str)
280 };
281
282 let canonical_workspace = ctx.workspace.canonicalize().map_err(|e| {
284 anyhow::anyhow!(
285 "Workspace boundary check failed: cannot canonicalize workspace '{}': {}",
286 ctx.workspace.display(),
287 e
288 )
289 })?;
290
291 let canonical_target = target.canonicalize().or_else(|_| {
293 target
294 .parent()
295 .and_then(|p| p.canonicalize().ok())
296 .ok_or_else(|| {
297 std::io::Error::new(std::io::ErrorKind::NotFound, "parent not found")
298 })
299 });
300
301 match canonical_target {
302 Ok(canonical) => {
303 if !canonical.starts_with(&canonical_workspace) {
304 anyhow::bail!(
305 "Workspace boundary violation: tool '{}' path '{}' escapes workspace '{}'",
306 name,
307 path_str,
308 ctx.workspace.display()
309 );
310 }
311 }
312 Err(_) => {
313 anyhow::bail!(
315 "Workspace boundary check failed: cannot resolve path '{}' for tool '{}'",
316 path_str,
317 name
318 );
319 }
320 }
321 }
322 }
323
324 Ok(())
325 }
326
327 pub fn workspace(&self) -> &PathBuf {
328 &self.workspace
329 }
330
331 pub fn registry(&self) -> &Arc<ToolRegistry> {
332 &self.registry
333 }
334
335 pub fn get_artifact(&self, artifact_uri: &str) -> Option<ToolArtifact> {
337 self.registry.get_artifact(artifact_uri)
338 }
339
340 pub fn artifact_store(&self) -> ArtifactStore {
342 self.registry.artifact_store()
343 }
344
345 pub fn set_trace_sink(&self, sink: Arc<dyn crate::trace::TraceSink>) {
347 self.registry.set_trace_sink(sink);
348 }
349
350 pub fn trace_sink(&self) -> Arc<dyn crate::trace::TraceSink> {
352 self.registry.trace_sink()
353 }
354
355 pub fn command_env(&self) -> Option<Arc<HashMap<String, String>>> {
356 self.command_env.clone()
357 }
358
359 pub fn register_dynamic_tool(&self, tool: Arc<dyn Tool>) {
360 self.registry.register(tool);
361 }
362
363 pub fn unregister_dynamic_tool(&self, name: &str) {
364 self.registry.unregister(name);
365 }
366
367 pub fn unregister_tools_by_prefix(&self, prefix: &str) {
369 self.registry.unregister_by_prefix(prefix);
370 }
371
372 pub fn register_program_catalog(&self, catalog: crate::program::ProgramCatalog) {
374 builtin::register_program_with_catalog(&self.registry, catalog);
375 }
376
377 fn capture_snapshot(&self, name: &str, args: &serde_json::Value) {
378 if let Some(file_path) = file_history::extract_file_path(name, args) {
379 let resolved = self.workspace.join(&file_path);
380 let path_to_read = if resolved.exists() {
381 resolved
382 } else if std::path::Path::new(&file_path).exists() {
383 std::path::PathBuf::from(&file_path)
384 } else {
385 self.file_history.save_snapshot(&file_path, "", name);
386 return;
387 };
388
389 match std::fs::read_to_string(&path_to_read) {
390 Ok(content) => {
391 self.file_history.save_snapshot(&file_path, &content, name);
392 tracing::debug!(
393 "Captured file snapshot for {} before {} (version {})",
394 file_path,
395 name,
396 self.file_history.list_versions(&file_path).len() - 1,
397 );
398 }
399 Err(e) => {
400 tracing::warn!("Failed to capture snapshot for {}: {}", file_path, e);
401 }
402 }
403 }
404 }
405
406 pub async fn execute(&self, name: &str, args: &serde_json::Value) -> Result<ToolResult> {
407 tracing::info!("Executing tool: {} with args: {}", name, args);
408 self.capture_snapshot(name, args);
409 let mut result = self.registry.execute(name, args).await;
410 if let Ok(ref mut r) = result {
411 self.attach_diff_metadata(name, args, r);
412 }
413 match &result {
414 Ok(r) => tracing::info!("Tool {} completed with exit_code={}", name, r.exit_code),
415 Err(e) => tracing::error!("Tool {} failed: {}", name, e),
416 }
417 result
418 }
419
420 pub async fn execute_with_context(
421 &self,
422 name: &str,
423 args: &serde_json::Value,
424 ctx: &ToolContext,
425 ) -> Result<ToolResult> {
426 Self::check_workspace_boundary(name, args, ctx)?;
427 tracing::info!("Executing tool: {} with args: {}", name, args);
428 self.capture_snapshot(name, args);
429 let mut result = self.registry.execute_with_context(name, args, ctx).await;
430 if let Ok(ref mut r) = result {
431 self.attach_diff_metadata(name, args, r);
432 }
433 match &result {
434 Ok(r) => tracing::info!("Tool {} completed with exit_code={}", name, r.exit_code),
435 Err(e) => tracing::error!("Tool {} failed: {}", name, e),
436 }
437 result
438 }
439
440 fn attach_diff_metadata(&self, name: &str, args: &serde_json::Value, result: &mut ToolResult) {
441 if !file_history::is_file_modifying_tool(name) {
442 return;
443 }
444 let Some(file_path) = file_history::extract_file_path(name, args) else {
445 return;
446 };
447 let meta = result.metadata.get_or_insert_with(|| serde_json::json!({}));
450 meta["file_path"] = serde_json::Value::String(file_path);
451 }
452
453 pub fn definitions(&self) -> Vec<ToolDefinition> {
454 self.registry.definitions()
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461 use async_trait::async_trait;
462
463 struct LargeArtifactTool;
464
465 #[async_trait]
466 impl Tool for LargeArtifactTool {
467 fn name(&self) -> &str {
468 "large_artifact"
469 }
470
471 fn description(&self) -> &str {
472 "Produces large output for artifact API tests"
473 }
474
475 fn parameters(&self) -> serde_json::Value {
476 serde_json::json!({
477 "type": "object",
478 "additionalProperties": false,
479 "properties": {},
480 "required": []
481 })
482 }
483
484 async fn execute(
485 &self,
486 args: &serde_json::Value,
487 _ctx: &ToolContext,
488 ) -> Result<ToolOutput> {
489 let suffix = args
490 .get("suffix")
491 .and_then(|value| value.as_str())
492 .unwrap_or_default();
493 Ok(ToolOutput::success(format!(
494 "{}{}",
495 "z".repeat(MAX_OUTPUT_SIZE + 1),
496 suffix
497 )))
498 }
499 }
500
501 struct EchoTool;
502
503 #[async_trait]
504 impl Tool for EchoTool {
505 fn name(&self) -> &str {
506 "echo"
507 }
508
509 fn description(&self) -> &str {
510 "Echoes the message argument"
511 }
512
513 fn parameters(&self) -> serde_json::Value {
514 serde_json::json!({
515 "type": "object",
516 "additionalProperties": false,
517 "properties": {
518 "message": { "type": "string" }
519 },
520 "required": ["message"]
521 })
522 }
523
524 async fn execute(
525 &self,
526 args: &serde_json::Value,
527 _ctx: &ToolContext,
528 ) -> Result<ToolOutput> {
529 Ok(ToolOutput::success(
530 args["message"].as_str().unwrap_or_default(),
531 ))
532 }
533 }
534
535 #[tokio::test]
536 async fn test_tool_executor_creation() {
537 let executor = ToolExecutor::new("/tmp".to_string());
538 assert_eq!(executor.registry.len(), 13);
540 }
541
542 #[tokio::test]
543 async fn test_unknown_tool() {
544 let executor = ToolExecutor::new("/tmp".to_string());
545 let result = executor
546 .execute("unknown", &serde_json::json!({}))
547 .await
548 .unwrap();
549 assert_eq!(result.exit_code, 1);
550 assert!(result.output.contains("Unknown tool"));
551 }
552
553 #[tokio::test]
554 async fn test_builtin_tools_registered() {
555 let executor = ToolExecutor::new("/tmp".to_string());
556 let definitions = executor.definitions();
557
558 assert!(definitions.iter().any(|t| t.name == "bash"));
559 assert!(definitions.iter().any(|t| t.name == "read"));
560 assert!(definitions.iter().any(|t| t.name == "write"));
561 assert!(definitions.iter().any(|t| t.name == "edit"));
562 assert!(definitions.iter().any(|t| t.name == "grep"));
563 assert!(definitions.iter().any(|t| t.name == "glob"));
564 assert!(definitions.iter().any(|t| t.name == "ls"));
565 assert!(definitions.iter().any(|t| t.name == "patch"));
566 assert!(definitions.iter().any(|t| t.name == "web_fetch"));
567 assert!(definitions.iter().any(|t| t.name == "web_search"));
568 assert!(definitions.iter().any(|t| t.name == "batch"));
569 }
570
571 #[test]
572 fn test_tool_result_success() {
573 let result = ToolResult::success("test_tool", "output text".to_string());
574 assert_eq!(result.name, "test_tool");
575 assert_eq!(result.output, "output text");
576 assert_eq!(result.exit_code, 0);
577 assert!(result.metadata.is_none());
578 }
579
580 #[test]
581 fn test_tool_result_error() {
582 let result = ToolResult::error("test_tool", "error message".to_string());
583 assert_eq!(result.name, "test_tool");
584 assert_eq!(result.output, "error message");
585 assert_eq!(result.exit_code, 1);
586 assert!(result.metadata.is_none());
587 }
588
589 #[test]
590 fn test_tool_result_from_tool_output_success() {
591 let output = ToolOutput {
592 content: "success content".to_string(),
593 success: true,
594 metadata: None,
595 images: Vec::new(),
596 };
597 let result: ToolResult = output.into();
598 assert_eq!(result.output, "success content");
599 assert_eq!(result.exit_code, 0);
600 assert!(result.metadata.is_none());
601 }
602
603 #[test]
604 fn test_tool_result_from_tool_output_failure() {
605 let output = ToolOutput {
606 content: "failure content".to_string(),
607 success: false,
608 metadata: Some(serde_json::json!({"error": "test"})),
609 images: Vec::new(),
610 };
611 let result: ToolResult = output.into();
612 assert_eq!(result.output, "failure content");
613 assert_eq!(result.exit_code, 1);
614 assert_eq!(result.metadata, Some(serde_json::json!({"error": "test"})));
615 }
616
617 #[test]
618 fn test_tool_result_metadata_propagation() {
619 let output = ToolOutput::success("content")
620 .with_metadata(serde_json::json!({"_load_skill": true, "skill_name": "test"}));
621 let result: ToolResult = output.into();
622 assert_eq!(result.exit_code, 0);
623 let meta = result.metadata.unwrap();
624 assert_eq!(meta["_load_skill"], true);
625 assert_eq!(meta["skill_name"], "test");
626 }
627
628 #[test]
629 fn test_tool_executor_workspace() {
630 let executor = ToolExecutor::new("/test/workspace".to_string());
631 assert_eq!(executor.workspace().to_str().unwrap(), "/test/workspace");
632 }
633
634 #[test]
635 fn test_tool_executor_registry() {
636 let executor = ToolExecutor::new("/tmp".to_string());
637 let registry = executor.registry();
638 assert_eq!(registry.len(), 13);
640 }
641
642 #[tokio::test]
643 async fn test_tool_executor_get_artifact() {
644 let executor = ToolExecutor::new("/tmp".to_string());
645 executor.register_dynamic_tool(Arc::new(LargeArtifactTool));
646
647 let result = executor
648 .execute("large_artifact", &serde_json::json!({}))
649 .await
650 .unwrap();
651
652 let artifact_uri = result.metadata.as_ref().unwrap()["artifact"]["artifact_uri"]
653 .as_str()
654 .unwrap();
655 let artifact = executor.get_artifact(artifact_uri).expect("artifact");
656 assert_eq!(artifact.tool_name, "large_artifact");
657 assert_eq!(artifact.content.len(), MAX_OUTPUT_SIZE + 1);
658 assert!(executor.artifact_store().get(artifact_uri).is_some());
659 }
660
661 #[tokio::test]
662 async fn test_tool_executor_respects_artifact_limits() {
663 let executor = ToolExecutor::new_with_artifact_limits(
664 "/tmp".to_string(),
665 ArtifactStoreLimits {
666 max_artifacts: 1,
667 max_bytes: usize::MAX,
668 },
669 );
670 executor.register_dynamic_tool(Arc::new(LargeArtifactTool));
671
672 let first = executor
673 .execute("large_artifact", &serde_json::json!({}))
674 .await
675 .unwrap();
676 let first_uri = first.metadata.as_ref().unwrap()["artifact"]["artifact_uri"]
677 .as_str()
678 .unwrap()
679 .to_string();
680
681 executor
682 .execute("large_artifact", &serde_json::json!({ "suffix": "again" }))
683 .await
684 .unwrap();
685
686 assert_eq!(executor.artifact_store().limits().max_artifacts, 1);
687 assert_eq!(executor.artifact_store().len(), 1);
688 assert!(executor.get_artifact(&first_uri).is_none());
689 }
690
691 #[tokio::test]
692 async fn test_tool_executor_register_program_catalog_keeps_script_only_program_tool() {
693 let executor = ToolExecutor::new("/tmp".to_string());
694 let trace_sink = crate::trace::InMemoryTraceSink::default();
695 executor.set_trace_sink(Arc::new(trace_sink.clone()));
696 executor.register_dynamic_tool(Arc::new(EchoTool));
697 let mut catalog = crate::program::ProgramCatalog::new();
698 catalog.register(
699 crate::program::ProgramTemplate::new("custom_echo", "Run a custom echo program")
700 .with_parameter(crate::program::ProgramParameter::required(
701 "message",
702 "Message to echo",
703 ))
704 .with_step(
705 crate::program::ProgramStepTemplate::new(
706 "echo",
707 serde_json::json!({ "message": "{{message}}" }),
708 )
709 .with_label("echo_message"),
710 ),
711 );
712 executor.register_program_catalog(catalog);
713
714 let result = executor
715 .execute(
716 "program",
717 &serde_json::json!({
718 "name": "custom_echo",
719 "inputs": {
720 "message": "hello from catalog"
721 }
722 }),
723 )
724 .await
725 .unwrap();
726
727 assert_eq!(result.exit_code, 1);
728 assert!(result.output.contains("type parameter is required"));
729
730 let events = trace_sink.events();
731 assert!(events.iter().any(|event| {
732 event.kind == crate::trace::TraceEventKind::ToolExecution && event.name == "program"
733 }));
734 assert!(!events.iter().any(|event| {
735 event.kind == crate::trace::TraceEventKind::ToolExecution && event.name == "echo"
736 }));
737 }
738
739 #[test]
740 fn test_max_output_size_constant() {
741 assert_eq!(MAX_OUTPUT_SIZE, 100 * 1024);
742 }
743
744 #[test]
745 fn test_max_read_lines_constant() {
746 assert_eq!(MAX_READ_LINES, 2000);
747 }
748
749 #[test]
750 fn test_max_line_length_constant() {
751 assert_eq!(MAX_LINE_LENGTH, 2000);
752 }
753
754 #[test]
755 fn test_truncate_tool_output_with_artifact_reference() {
756 let output = "x".repeat(MAX_OUTPUT_SIZE + 1);
757 let truncated = truncate_tool_output_with_artifact("test/tool", &output);
758
759 let artifact = truncated.artifact.expect("artifact");
760 assert!(truncated.content.contains("Full output artifact:"));
761 assert_eq!(artifact.original_bytes, MAX_OUTPUT_SIZE + 1);
762 assert_eq!(artifact.shown_bytes, MAX_OUTPUT_SIZE);
763 assert!(artifact.artifact_id.starts_with("tool-output:test_tool:"));
764 assert!(artifact
765 .artifact_uri
766 .starts_with("a3s://tool-output/test_tool/"));
767 }
768
769 #[test]
770 fn test_tool_result_clone() {
771 let result = ToolResult::success("test", "output".to_string());
772 let cloned = result.clone();
773 assert_eq!(result.name, cloned.name);
774 assert_eq!(result.output, cloned.output);
775 assert_eq!(result.exit_code, cloned.exit_code);
776 assert_eq!(result.metadata, cloned.metadata);
777 }
778
779 #[test]
780 fn test_tool_result_debug() {
781 let result = ToolResult::success("test", "output".to_string());
782 let debug_str = format!("{:?}", result);
783 assert!(debug_str.contains("test"));
784 assert!(debug_str.contains("output"));
785 }
786
787 #[tokio::test]
788 async fn test_execute_attaches_diff_metadata() {
789 use tempfile::TempDir;
790 let dir = TempDir::new().unwrap();
791 let file = dir.path().join("hello.txt");
792 std::fs::write(&file, "before content\n").unwrap();
793
794 let executor = ToolExecutor::new(dir.path().to_str().unwrap().to_string());
795 let args = serde_json::json!({
796 "file_path": "hello.txt",
797 "content": "after content\n"
798 });
799 let result = executor.execute("write", &args).await.unwrap();
800
801 let meta = result.metadata.expect("metadata should be present");
802 assert_eq!(meta["before"], "before content\n");
803 assert_eq!(meta["after"], "after content\n");
804 assert_eq!(meta["file_path"], "hello.txt");
805 }
806
807 #[tokio::test]
808 async fn test_execute_with_context_attaches_diff_metadata() {
809 use tempfile::TempDir;
810 let dir = TempDir::new().unwrap();
811 let canonical_dir = dir.path().canonicalize().unwrap();
812 let file = canonical_dir.join("ctx.txt");
813 std::fs::write(&file, "original\n").unwrap();
814
815 let executor = ToolExecutor::new(canonical_dir.to_str().unwrap().to_string());
816 let ctx = ToolContext {
817 workspace: canonical_dir.clone(),
818 session_id: None,
819 event_tx: None,
820 agent_event_tx: None,
821 search_config: None,
822 sandbox: None,
823 command_env: None,
824 };
825 let args = serde_json::json!({
826 "file_path": "ctx.txt",
827 "content": "updated\n"
828 });
829 let result = executor
830 .execute_with_context("write", &args, &ctx)
831 .await
832 .unwrap();
833 assert_eq!(result.exit_code, 0, "write tool failed: {}", result.output);
834
835 let meta = result.metadata.expect("metadata should be present");
836 assert_eq!(meta["before"], "original\n");
837 assert_eq!(meta["after"], "updated\n");
838 assert_eq!(meta["file_path"], "ctx.txt");
839 }
840}