1use std::fmt::Write as FmtWrite;
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use tokio::sync::Mutex;
8use tracing::{debug, info, instrument, warn};
9
10use crate::errors::{Result, WinxError};
11use crate::state::bash_state::{generate_thread_id, BashState};
12use crate::types::{
13 normalize_thread_id, AllowedCommands, AllowedGlobs, BashCommandMode, BashMode,
14 CodeWriterConfig, FileEditMode, Initialize, InitializeType, Modes, WriteIfEmptyMode,
15};
16use crate::utils::mmap::read_file_to_string;
17use crate::utils::path::{ensure_directory_exists, expand_user, validate_path_in_workspace};
18
19fn create_playground_dir() -> Result<PathBuf> {
22 let stamp = std::time::SystemTime::now()
23 .duration_since(std::time::UNIX_EPOCH)
24 .map_or(0, |d| d.as_nanos());
25 let dir =
26 std::env::temp_dir().join(format!("winx-playground-{}-{:x}", std::process::id(), stamp));
27 ensure_directory_exists(&dir)?;
28 Ok(dir)
29}
30
31fn command_exists(cmd: &str) -> bool {
33 std::process::Command::new("sh")
34 .args(["-c", &format!("command -v {cmd}")])
35 .output()
36 .is_ok_and(|o| o.status.success())
37}
38
39fn code_writer_state(
40 config: &CodeWriterConfig,
41 workspace_root: &Path,
42) -> (BashCommandMode, FileEditMode, WriteIfEmptyMode) {
43 let mut config = config.clone();
44 config.allowed_globs.normalize();
46 config.allowed_commands.normalize();
47 config.update_relative_globs(&workspace_root.to_string_lossy());
48
49 if let AllowedCommands::List(cmds) = &config.allowed_commands {
50 let bypass = crate::utils::bash_parser::detect_allowlist_bypass(cmds);
51 if !bypass.is_empty() {
52 warn!(
53 commands = ?bypass,
54 "code_writer allowlist includes shell-spawning commands; the command \
55 allowlist is effectively bypassable and does not sandbox the agent"
56 );
57 }
58 }
59
60 (
61 BashCommandMode {
62 bash_mode: BashMode::NormalMode,
63 allowed_commands: config.allowed_commands,
64 },
65 FileEditMode { allowed_globs: config.allowed_globs.clone() },
66 WriteIfEmptyMode { allowed_globs: config.allowed_globs },
67 )
68}
69
70fn mode_to_state(
71 mode: Modes,
72 config: Option<&CodeWriterConfig>,
73 workspace_root: &Path,
74) -> Result<(BashCommandMode, FileEditMode, WriteIfEmptyMode)> {
75 match mode {
76 Modes::Wcgw => Ok((
77 BashCommandMode {
78 bash_mode: BashMode::NormalMode,
79 allowed_commands: AllowedCommands::All("all".to_string()),
80 },
81 FileEditMode { allowed_globs: AllowedGlobs::All("all".to_string()) },
82 WriteIfEmptyMode { allowed_globs: AllowedGlobs::All("all".to_string()) },
83 )),
84 Modes::Architect => Ok((
85 BashCommandMode {
86 bash_mode: BashMode::RestrictedMode,
87 allowed_commands: AllowedCommands::All("all".to_string()),
88 },
89 FileEditMode { allowed_globs: AllowedGlobs::List(vec![]) },
90 WriteIfEmptyMode { allowed_globs: AllowedGlobs::List(vec![]) },
91 )),
92 Modes::CodeWriter => {
93 let config = config.ok_or_else(|| {
94 WinxError::ArgumentParseError(
95 "code_writer_config is required when mode_name is code_writer.".to_string(),
96 )
97 })?;
98 Ok(code_writer_state(config, workspace_root))
99 }
100 }
101}
102
103fn read_initial_files_simple(files: &[String], workspace: &std::path::Path) -> String {
104 let mut output = String::new();
105 for file_path in files {
106 let expanded = expand_user(file_path);
107 let path = if std::path::Path::new(&expanded).is_absolute() {
108 PathBuf::from(&expanded)
109 } else {
110 workspace.join(&expanded)
111 };
112
113 if let Ok(validated) = validate_path_in_workspace(&path, workspace) {
114 if validated.exists() && validated.is_file() {
115 if let Ok(content) = read_file_to_string(&validated, 10_000_000) {
116 let _ = write!(output, "\n{file_path}\n```\n{content}\n```\n");
117 }
118 }
119 }
120 }
121 output
122}
123
124fn prepare_workspace(initialize: &Initialize, response: &mut String) -> Result<PathBuf> {
125 let workspace_path_str = expand_user(&initialize.any_workspace_path);
126 if workspace_path_str.is_empty() {
127 let playground = create_playground_dir()?;
130 let _ = writeln!(
131 response,
132 "No workspace path provided; created a playground at {}",
133 playground.display()
134 );
135 return Ok(playground);
136 }
137
138 let workspace_path = PathBuf::from(&workspace_path_str);
139 let mut folder_to_start = workspace_path.clone();
140
141 if workspace_path.exists() {
142 if workspace_path.is_file() {
143 folder_to_start = workspace_path.parent().unwrap_or(&workspace_path).to_path_buf();
144 let _ =
145 writeln!(response, "Using parent directory of file: {}", folder_to_start.display());
146 } else if workspace_path.is_dir() {
147 let _ = writeln!(response, "Using workspace directory: {}", folder_to_start.display());
148 }
149 } else if workspace_path.is_absolute() {
150 ensure_directory_exists(&workspace_path).map_err(|e| {
151 WinxError::WorkspacePathError(format!("Failed to create workspace: {e}"))
152 })?;
153 let _ = writeln!(response, "Created workspace directory: {}", workspace_path.display());
154 }
155
156 if folder_to_start.exists() {
160 if let Ok(canonical) = folder_to_start.canonicalize() {
161 folder_to_start = canonical;
162 }
163 }
164
165 Ok(folder_to_start)
166}
167
168fn initialize_thread_id(initialize: &Initialize) -> String {
169 let thread_id = normalize_thread_id(&initialize.thread_id);
170 if thread_id.is_empty() {
171 generate_thread_id()
172 } else {
173 thread_id
174 }
175}
176
177fn validate_thread_id(initialize: &Initialize) -> Result<()> {
178 if initialize.init_type != InitializeType::FirstCall
179 && normalize_thread_id(&initialize.thread_id).is_empty()
180 {
181 return Err(WinxError::ThreadIdMismatch(
182 "Thread id should be provided if type != 'first_call', including when resetting."
183 .to_string(),
184 ));
185 }
186
187 Ok(())
188}
189
190fn load_guidelines(workspace: &Path) -> String {
191 let mut output = String::new();
192 let mut candidates = Vec::new();
193 if let Some(home) = home::home_dir() {
194 candidates.push(home.join(".winx").join("AGENTS.md"));
195 candidates.push(home.join(".winx").join("CLAUDE.md"));
196 candidates.push(home.join(".wcgw").join("AGENTS.md"));
197 candidates.push(home.join(".wcgw").join("CLAUDE.md"));
198 }
199 candidates.push(workspace.join("AGENTS.md"));
200 candidates.push(workspace.join("CLAUDE.md"));
201
202 for path in candidates {
203 if path.is_file() {
204 if let Ok(content) = fs::read_to_string(&path) {
205 let _ = writeln!(output, "\n## {}\n{}", path.display(), content);
206 }
207 }
208 }
209 output
210}
211
212#[instrument(level = "info", skip(bash_state_arc, initialize))]
213#[allow(clippy::too_many_lines)]
214pub async fn handle_tool_call(
215 bash_state_arc: &Arc<Mutex<Option<BashState>>>,
216 initialize: Initialize,
217) -> Result<String> {
218 let mut response = String::new();
219
220 info!("Initialize called for workspace: {}", initialize.any_workspace_path);
221
222 validate_thread_id(&initialize)?;
223 let folder_to_start = prepare_workspace(&initialize, &mut response)?;
224 let thread_id = initialize_thread_id(&initialize);
225
226 let mut bash_state_guard = bash_state_arc.lock().await;
227 let mode = Modes::from(&initialize.mode_name);
228 let (bash_command_mode, file_edit_mode, write_if_empty_mode) =
229 mode_to_state(mode, initialize.code_writer_config.as_ref(), &folder_to_start)?;
230
231 match initialize.init_type {
232 InitializeType::FirstCall => {
233 let mut new_bash_state = BashState::new();
234 new_bash_state.current_thread_id.clone_from(&thread_id);
235 new_bash_state.mode = mode;
236 new_bash_state.bash_command_mode = bash_command_mode;
237 new_bash_state.file_edit_mode = file_edit_mode;
238 new_bash_state.write_if_empty_mode = write_if_empty_mode;
239 new_bash_state.initialized = true;
240
241 let resumed_context = if initialize.task_id_to_resume.is_empty() {
242 None
243 } else {
244 crate::tools::context_save::load_saved_context(&initialize.task_id_to_resume)?
245 };
246
247 if let Some((memory_data, snapshot)) = &resumed_context {
248 if let Some(snapshot) = snapshot {
249 new_bash_state.apply_snapshot(snapshot);
250 new_bash_state.current_thread_id.clone_from(&thread_id);
251 }
252 let _ = writeln!(
253 response,
254 "\n# Resumed task {}\nFollowing is the retrieved task context:\n{}",
255 initialize.task_id_to_resume, memory_data
256 );
257 }
258
259 if resumed_context.as_ref().and_then(|(_, snapshot)| snapshot.as_ref()).is_none() {
263 let resumed_root = resumed_context
264 .as_ref()
265 .and_then(|(memory, _)| {
266 crate::tools::context_save::extract_project_root(memory)
267 })
268 .filter(|root| root.exists());
269 let target = resumed_root.as_deref().unwrap_or(folder_to_start.as_path());
270 if target.exists() {
271 new_bash_state.update_cwd(target)?;
272 new_bash_state.update_workspace_root(target)?;
273 }
274 }
275 if new_bash_state.cwd.exists() {
276 new_bash_state.init_pty_shell().await?;
277 }
278
279 let attach_hint = {
280 let pty_guard = new_bash_state.pty_shell.lock().await;
281 pty_guard.as_ref().and_then(|shell| shell.attach_hint.clone())
282 };
283
284 *bash_state_guard = Some(new_bash_state);
285
286 let _ = write!(
287 response,
288 "\n# Environment\nSystem: {}\nMachine: {}\nInitialized in directory: {}\n",
289 std::env::consts::OS,
290 std::env::consts::ARCH,
291 bash_state_guard
292 .as_ref()
293 .map_or(folder_to_start.as_path(), |state| state.cwd.as_path())
294 .display()
295 );
296
297 if command_exists("rg") {
298 let _ = writeln!(
299 response,
300 "\n# Available commands\nUse ripgrep `rg` instead of `grep`/`find -name` — \
301 it's much faster and respects .gitignore."
302 );
303 }
304
305 let _ = writeln!(response, "\nUse thread_id={thread_id} for all winx tool calls.");
306 if let Some(attach_hint) = attach_hint {
307 let _ = writeln!(response, "\nAttach terminal: {attach_hint}");
308 }
309
310 let _ = writeln!(
314 response,
315 "\n{}",
316 crate::utils::mode_prompts::mode_prompt(
317 mode,
318 initialize.code_writer_config.as_ref()
319 )
320 );
321
322 if let Some(cfg) = initialize.code_writer_config.as_ref() {
327 if let AllowedCommands::List(cmds) = &cfg.allowed_commands {
328 let bypass = crate::utils::bash_parser::detect_allowlist_bypass(cmds);
329 if !bypass.is_empty() {
330 let _ = writeln!(
331 response,
332 "\n⚠️ SECURITY: code_writer allowlist includes shell/eval commands ({}). \
333 They execute arbitrary code from string arguments (e.g. `bash -c …`, \
334 `find -exec …`), so the command allowlist is effectively bypassable and \
335 does NOT sandbox the agent. Drop them if you intended a hard restriction.",
336 bypass.join(", ")
337 );
338 }
339 }
340 }
341
342 let active_workspace = bash_state_guard
343 .as_ref()
344 .map_or(folder_to_start.as_path(), |state| state.workspace_root.as_path());
345
346 let guidelines = load_guidelines(active_workspace);
347 if !guidelines.is_empty() {
348 let _ = writeln!(response, "\n# Agent guidelines\n{guidelines}");
349 }
350
351 if let Ok((repo_context, _)) = crate::utils::repo::get_repo_context(active_workspace) {
352 let _ = writeln!(response, "\n# Workspace structure\n{repo_context}");
353 }
354
355 if !initialize.initial_files_to_read.is_empty() {
356 let content =
357 read_initial_files_simple(&initialize.initial_files_to_read, active_workspace);
358 if !content.is_empty() {
359 let _ = writeln!(response, "\n# Requested files\n{content}");
360 }
361 }
362 }
363 InitializeType::UserAskedModeChange => {
364 if let Some(state) = bash_state_guard.as_mut() {
365 state.mode = mode;
366 state.bash_command_mode = bash_command_mode;
367 state.file_edit_mode = file_edit_mode;
368 state.write_if_empty_mode = write_if_empty_mode;
369 let _ = writeln!(response, "Changed mode to: {mode:?}");
370 let _ = writeln!(
371 response,
372 "\n{}",
373 crate::utils::mode_prompts::mode_prompt(
374 mode,
375 initialize.code_writer_config.as_ref()
376 )
377 );
378 } else {
379 return Err(WinxError::BashStateNotInitialized);
380 }
381 }
382 InitializeType::ResetShell => {
383 if let Some(state) = bash_state_guard.as_mut() {
384 state.mode = mode;
385 state.bash_command_mode = bash_command_mode;
386 state.file_edit_mode = file_edit_mode;
387 state.write_if_empty_mode = write_if_empty_mode;
388 state.init_pty_shell().await?;
389 response.push_str("Reset shell (new PTY created)\n");
390 } else {
391 return Err(WinxError::BashStateNotInitialized);
392 }
393 }
394 InitializeType::UserAskedChangeWorkspace => {
395 if let Some(state) = bash_state_guard.as_mut() {
396 if folder_to_start.exists() {
397 state.update_cwd(&folder_to_start)?;
398 state.update_workspace_root(&folder_to_start)?;
399 let _ =
400 writeln!(response, "Changed workspace to: {}", folder_to_start.display());
401 } else {
402 let _ = writeln!(
403 response,
404 "Warning: Workspace path {} does not exist",
405 folder_to_start.display()
406 );
407 }
408 } else {
409 return Err(WinxError::BashStateNotInitialized);
410 }
411 }
412 }
413
414 append_server_instructions(&mut response);
415
416 Ok(response)
417}
418
419fn append_server_instructions(response: &mut String) {
422 response.push_str(
423 "\nAs soon as you encounter \"The user has chosen to disallow the tool call.\", \
424 immediately stop doing everything and ask the user for the reason.\n",
425 );
426 if let Ok(extra) = std::env::var("WINX_SERVER_INSTRUCTIONS") {
427 let extra = extra.trim();
428 if !extra.is_empty() {
429 let _ = write!(response, "\n# Additional instructions\n{extra}\n");
430 }
431 }
432}