1use std::path::PathBuf;
5
6use schemars::JsonSchema;
7use serde::Deserialize;
8
9use zeph_common::ToolName;
10
11use crate::executor::{
12 ClaimSource, ToolCall, ToolError, ToolExecutor, ToolOutput, deserialize_params,
13};
14use crate::registry::{InvocationHint, ToolDef};
15
16const TOOL_NAME: &str = "set_working_directory";
17
18const TOOL_DESCRIPTION: &str = "Change the agent's working directory. \
19Shell commands (`bash`) run in child processes — a `cd` inside them does NOT persist. \
20Use this tool when you need to change the working context for subsequent operations. \
21Returns the new absolute working directory path on success.";
22
23#[derive(Deserialize, JsonSchema)]
24struct SetCwdParams {
25 path: String,
27}
28
29#[derive(Debug, Default)]
35pub struct SetCwdExecutor;
36
37impl ToolExecutor for SetCwdExecutor {
38 async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
39 if call.tool_id != TOOL_NAME {
40 return Ok(None);
41 }
42 let params: SetCwdParams = deserialize_params(&call.params)?;
43 let target = PathBuf::from(¶ms.path);
44
45 let resolved = if target.is_absolute() {
47 target
48 } else {
49 std::env::current_dir()
50 .map_err(ToolError::Execution)?
51 .join(target)
52 };
53
54 std::env::set_current_dir(&resolved).map_err(ToolError::Execution)?;
55
56 let new_cwd = std::env::current_dir().map_err(ToolError::Execution)?;
57 let summary = new_cwd.display().to_string();
58
59 Ok(Some(ToolOutput {
60 tool_name: ToolName::new(TOOL_NAME),
61 summary,
62 blocks_executed: 1,
63 filter_stats: None,
64 diff: None,
65 streamed: false,
66 terminal_id: None,
67 locations: None,
68 raw_response: None,
69 claim_source: Some(ClaimSource::FileSystem),
70 }))
71 }
72
73 fn tool_definitions(&self) -> Vec<ToolDef> {
74 vec![ToolDef {
75 id: TOOL_NAME.into(),
76 description: TOOL_DESCRIPTION.into(),
77 schema: schemars::schema_for!(SetCwdParams),
78 invocation: InvocationHint::ToolCall,
79 }]
80 }
81
82 fn is_tool_retryable(&self, _tool_id: &str) -> bool {
83 false
84 }
85
86 async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
87 Ok(None)
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use super::*;
94
95 fn make_call(path: &str) -> ToolCall {
96 let mut params = serde_json::Map::new();
97 params.insert(
98 "path".to_owned(),
99 serde_json::Value::String(path.to_owned()),
100 );
101 ToolCall {
102 tool_id: ToolName::new(TOOL_NAME),
103 params,
104 caller_id: None,
105 }
106 }
107
108 #[tokio::test]
109 async fn set_cwd_changes_process_cwd() {
110 let original_cwd = std::env::current_dir().unwrap();
111 let dir = tempfile::tempdir().unwrap();
112 let executor = SetCwdExecutor;
113 let call = make_call(dir.path().to_str().unwrap());
114 let result = executor.execute_tool_call(&call).await.unwrap();
115 assert!(result.is_some());
116 let out = result.unwrap();
117 let new_cwd = std::env::current_dir().unwrap();
119 assert_eq!(out.summary, new_cwd.display().to_string());
120 let _ = std::env::set_current_dir(&original_cwd);
122 }
123
124 #[tokio::test]
125 async fn set_cwd_returns_none_for_unknown_tool() {
126 let executor = SetCwdExecutor;
127 let call = ToolCall {
128 tool_id: ToolName::new("other_tool"),
129 params: serde_json::Map::new(),
130 caller_id: None,
131 };
132 let result = executor.execute_tool_call(&call).await.unwrap();
133 assert!(result.is_none());
134 }
135
136 #[tokio::test]
137 async fn set_cwd_errors_on_nonexistent_path() {
138 let executor = SetCwdExecutor;
139 let call = make_call("/nonexistent/path/that/does/not/exist");
140 let result = executor.execute_tool_call(&call).await;
141 assert!(result.is_err());
142 }
143
144 #[test]
145 fn tool_definitions_contains_set_working_directory() {
146 let executor = SetCwdExecutor;
147 let defs = executor.tool_definitions();
148 assert_eq!(defs.len(), 1);
149 assert_eq!(defs[0].id.as_ref(), TOOL_NAME);
150 }
151}