agent.rs

  1use collections::{HashMap, IndexMap};
  2use schemars::{JsonSchema, json_schema};
  3use serde::{Deserialize, Serialize};
  4use settings_macros::{MergeFrom, with_fallible_options};
  5use std::sync::Arc;
  6use std::{borrow::Cow, path::PathBuf};
  7
  8use crate::ExtendingVec;
  9
 10use crate::DockPosition;
 11
 12#[with_fallible_options]
 13#[derive(Clone, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom, Debug, Default)]
 14pub struct AgentSettingsContent {
 15    /// Whether the Agent is enabled.
 16    ///
 17    /// Default: true
 18    pub enabled: Option<bool>,
 19    /// Whether to show the agent panel button in the status bar.
 20    ///
 21    /// Default: true
 22    pub button: Option<bool>,
 23    /// Where to dock the agent panel.
 24    ///
 25    /// Default: right
 26    pub dock: Option<DockPosition>,
 27    /// Default width in pixels when the agent panel is docked to the left or right.
 28    ///
 29    /// Default: 640
 30    #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
 31    pub default_width: Option<f32>,
 32    /// Default height in pixels when the agent panel is docked to the bottom.
 33    ///
 34    /// Default: 320
 35    #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
 36    pub default_height: Option<f32>,
 37    /// The default model to use when creating new chats and for other features when a specific model is not specified.
 38    pub default_model: Option<LanguageModelSelection>,
 39    /// Favorite models to show at the top of the model selector.
 40    #[serde(default)]
 41    pub favorite_models: Vec<LanguageModelSelection>,
 42    /// Model to use for the inline assistant. Defaults to default_model when not specified.
 43    pub inline_assistant_model: Option<LanguageModelSelection>,
 44    /// Model to use for the inline assistant when streaming tools are enabled.
 45    ///
 46    /// Default: true
 47    pub inline_assistant_use_streaming_tools: Option<bool>,
 48    /// Model to use for generating git commit messages. Defaults to default_model when not specified.
 49    pub commit_message_model: Option<LanguageModelSelection>,
 50    /// Model to use for generating thread summaries. Defaults to default_model when not specified.
 51    pub thread_summary_model: Option<LanguageModelSelection>,
 52    /// Additional models with which to generate alternatives when performing inline assists.
 53    pub inline_alternatives: Option<Vec<LanguageModelSelection>>,
 54    /// The default profile to use in the Agent.
 55    ///
 56    /// Default: write
 57    pub default_profile: Option<Arc<str>>,
 58    /// Which view type to show by default in the agent panel.
 59    ///
 60    /// Default: "thread"
 61    pub default_view: Option<DefaultAgentView>,
 62    /// The available agent profiles.
 63    pub profiles: Option<IndexMap<Arc<str>, AgentProfileContent>>,
 64    /// Where to show a popup notification when the agent is waiting for user input.
 65    ///
 66    /// Default: "primary_screen"
 67    pub notify_when_agent_waiting: Option<NotifyWhenAgentWaiting>,
 68    /// Whether to play a sound when the agent has either completed its response, or needs user input.
 69    ///
 70    /// Default: false
 71    pub play_sound_when_agent_done: Option<bool>,
 72    /// Whether to display agent edits in single-file editors in addition to the review multibuffer pane.
 73    ///
 74    /// Default: true
 75    pub single_file_review: Option<bool>,
 76    /// Additional parameters for language model requests. When making a request
 77    /// to a model, parameters will be taken from the last entry in this list
 78    /// that matches the model's provider and name. In each entry, both provider
 79    /// and model are optional, so that you can specify parameters for either
 80    /// one.
 81    ///
 82    /// Default: []
 83    #[serde(default)]
 84    pub model_parameters: Vec<LanguageModelParameters>,
 85    /// Whether to show thumb buttons for feedback in the agent panel.
 86    ///
 87    /// Default: true
 88    pub enable_feedback: Option<bool>,
 89    /// Whether to have edit cards in the agent panel expanded, showing a preview of the full diff.
 90    ///
 91    /// Default: true
 92    pub expand_edit_card: Option<bool>,
 93    /// Whether to have terminal cards in the agent panel expanded, showing the whole command output.
 94    ///
 95    /// Default: true
 96    pub expand_terminal_card: Option<bool>,
 97    /// Whether clicking the stop button on a running terminal tool should also cancel the agent's generation.
 98    /// Note that this only applies to the stop button, not to ctrl+c inside the terminal.
 99    ///
100    /// Default: true
101    pub cancel_generation_on_terminal_stop: Option<bool>,
102    /// Whether to always use cmd-enter (or ctrl-enter on Linux or Windows) to send messages in the agent panel.
103    ///
104    /// Default: false
105    pub use_modifier_to_send: Option<bool>,
106    /// Minimum number of lines of height the agent message editor should have.
107    ///
108    /// Default: 4
109    pub message_editor_min_lines: Option<usize>,
110    /// Whether to show turn statistics (elapsed time during generation, final turn duration).
111    ///
112    /// Default: false
113    pub show_turn_stats: Option<bool>,
114    /// Per-tool permission rules for granular control over which tool actions
115    /// require confirmation.
116    ///
117    /// The global `default` applies when no tool-specific rules match.
118    /// For external agent servers (e.g. Claude Agent) that define their own
119    /// permission modes, "deny" and "confirm" still take precedence — the
120    /// external agent's permission system is only used when Zed would allow
121    /// the action. Per-tool regex patterns (`always_allow`, `always_deny`,
122    /// `always_confirm`) match against the tool's text input (command, path,
123    /// URL, etc.).
124    pub tool_permissions: Option<ToolPermissionsContent>,
125}
126
127impl AgentSettingsContent {
128    pub fn set_dock(&mut self, dock: DockPosition) {
129        self.dock = Some(dock);
130    }
131
132    pub fn set_model(&mut self, language_model: LanguageModelSelection) {
133        self.default_model = Some(language_model)
134    }
135
136    pub fn set_inline_assistant_model(&mut self, provider: String, model: String) {
137        self.inline_assistant_model = Some(LanguageModelSelection {
138            provider: provider.into(),
139            model,
140            enable_thinking: false,
141            effort: None,
142        });
143    }
144
145    pub fn set_profile(&mut self, profile_id: Arc<str>) {
146        self.default_profile = Some(profile_id);
147    }
148
149    pub fn add_favorite_model(&mut self, model: LanguageModelSelection) {
150        if !self.favorite_models.contains(&model) {
151            self.favorite_models.push(model);
152        }
153    }
154
155    pub fn remove_favorite_model(&mut self, model: &LanguageModelSelection) {
156        self.favorite_models.retain(|m| m != model);
157    }
158
159    pub fn set_tool_default_permission(&mut self, tool_id: &str, mode: ToolPermissionMode) {
160        let tool_permissions = self.tool_permissions.get_or_insert_default();
161        let tool_rules = tool_permissions
162            .tools
163            .entry(Arc::from(tool_id))
164            .or_default();
165        tool_rules.default = Some(mode);
166    }
167
168    pub fn add_tool_allow_pattern(&mut self, tool_name: &str, pattern: String) {
169        let tool_permissions = self.tool_permissions.get_or_insert_default();
170        let tool_rules = tool_permissions
171            .tools
172            .entry(Arc::from(tool_name))
173            .or_default();
174        let always_allow = tool_rules.always_allow.get_or_insert_default();
175        if !always_allow.0.iter().any(|r| r.pattern == pattern) {
176            always_allow.0.push(ToolRegexRule {
177                pattern,
178                case_sensitive: None,
179            });
180        }
181    }
182
183    pub fn add_tool_deny_pattern(&mut self, tool_name: &str, pattern: String) {
184        let tool_permissions = self.tool_permissions.get_or_insert_default();
185        let tool_rules = tool_permissions
186            .tools
187            .entry(Arc::from(tool_name))
188            .or_default();
189        let always_deny = tool_rules.always_deny.get_or_insert_default();
190        if !always_deny.0.iter().any(|r| r.pattern == pattern) {
191            always_deny.0.push(ToolRegexRule {
192                pattern,
193                case_sensitive: None,
194            });
195        }
196    }
197}
198
199#[with_fallible_options]
200#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, JsonSchema, MergeFrom)]
201pub struct AgentProfileContent {
202    pub name: Arc<str>,
203    #[serde(default)]
204    pub tools: IndexMap<Arc<str>, bool>,
205    /// Whether all context servers are enabled by default.
206    pub enable_all_context_servers: Option<bool>,
207    #[serde(default)]
208    pub context_servers: IndexMap<Arc<str>, ContextServerPresetContent>,
209    /// The default language model selected when using this profile.
210    pub default_model: Option<LanguageModelSelection>,
211}
212
213#[with_fallible_options]
214#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
215pub struct ContextServerPresetContent {
216    pub tools: IndexMap<Arc<str>, bool>,
217}
218
219#[derive(Copy, Clone, Default, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
220#[serde(rename_all = "snake_case")]
221pub enum DefaultAgentView {
222    #[default]
223    Thread,
224    TextThread,
225}
226
227#[derive(
228    Copy,
229    Clone,
230    Default,
231    Debug,
232    Serialize,
233    Deserialize,
234    JsonSchema,
235    MergeFrom,
236    PartialEq,
237    strum::VariantArray,
238    strum::VariantNames,
239)]
240#[serde(rename_all = "snake_case")]
241pub enum NotifyWhenAgentWaiting {
242    #[default]
243    PrimaryScreen,
244    AllScreens,
245    Never,
246}
247
248#[with_fallible_options]
249#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
250pub struct LanguageModelSelection {
251    pub provider: LanguageModelProviderSetting,
252    pub model: String,
253    #[serde(default)]
254    pub enable_thinking: bool,
255    pub effort: Option<String>,
256}
257
258#[with_fallible_options]
259#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
260pub struct LanguageModelParameters {
261    pub provider: Option<LanguageModelProviderSetting>,
262    pub model: Option<String>,
263    #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
264    pub temperature: Option<f32>,
265}
266
267#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, MergeFrom)]
268pub struct LanguageModelProviderSetting(pub String);
269
270impl JsonSchema for LanguageModelProviderSetting {
271    fn schema_name() -> Cow<'static, str> {
272        "LanguageModelProviderSetting".into()
273    }
274
275    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
276        // list the builtin providers as a subset so that we still auto complete them in the settings
277        json_schema!({
278            "anyOf": [
279                {
280                    "type": "string",
281                    "enum": [
282                        "amazon-bedrock",
283                        "anthropic",
284                        "copilot_chat",
285                        "deepseek",
286                        "google",
287                        "lmstudio",
288                        "mistral",
289                        "ollama",
290                        "openai",
291                        "openrouter",
292                        "vercel",
293                        "x_ai",
294                        "zed.dev"
295                    ]
296                },
297                {
298                    "type": "string",
299                }
300            ]
301        })
302    }
303}
304
305impl From<String> for LanguageModelProviderSetting {
306    fn from(provider: String) -> Self {
307        Self(provider)
308    }
309}
310
311impl From<&str> for LanguageModelProviderSetting {
312    fn from(provider: &str) -> Self {
313        Self(provider.to_string())
314    }
315}
316
317#[with_fallible_options]
318#[derive(Default, PartialEq, Deserialize, Serialize, Clone, JsonSchema, MergeFrom, Debug)]
319#[serde(transparent)]
320pub struct AllAgentServersSettings(pub HashMap<String, CustomAgentServerSettings>);
321
322impl std::ops::Deref for AllAgentServersSettings {
323    type Target = HashMap<String, CustomAgentServerSettings>;
324
325    fn deref(&self) -> &Self::Target {
326        &self.0
327    }
328}
329
330impl std::ops::DerefMut for AllAgentServersSettings {
331    fn deref_mut(&mut self) -> &mut Self::Target {
332        &mut self.0
333    }
334}
335
336#[with_fallible_options]
337#[derive(Deserialize, Serialize, Clone, JsonSchema, MergeFrom, Debug, PartialEq)]
338#[serde(tag = "type", rename_all = "snake_case")]
339pub enum CustomAgentServerSettings {
340    Custom {
341        #[serde(rename = "command")]
342        path: PathBuf,
343        #[serde(default, skip_serializing_if = "Vec::is_empty")]
344        args: Vec<String>,
345        /// Default: {}
346        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
347        env: HashMap<String, String>,
348        /// The default mode to use for this agent.
349        ///
350        /// Note: Not only all agents support modes.
351        ///
352        /// Default: None
353        default_mode: Option<String>,
354        /// The default model to use for this agent.
355        ///
356        /// This should be the model ID as reported by the agent.
357        ///
358        /// Default: None
359        default_model: Option<String>,
360        /// The favorite models for this agent.
361        ///
362        /// These are the model IDs as reported by the agent.
363        ///
364        /// Default: []
365        #[serde(default, skip_serializing_if = "Vec::is_empty")]
366        favorite_models: Vec<String>,
367        /// Default values for session config options.
368        ///
369        /// This is a map from config option ID to value ID.
370        ///
371        /// Default: {}
372        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
373        default_config_options: HashMap<String, String>,
374        /// Favorited values for session config options.
375        ///
376        /// This is a map from config option ID to a list of favorited value IDs.
377        ///
378        /// Default: {}
379        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
380        favorite_config_option_values: HashMap<String, Vec<String>>,
381    },
382    Extension {
383        /// Additional environment variables to pass to the agent.
384        ///
385        /// Default: {}
386        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
387        env: HashMap<String, String>,
388        /// The default mode to use for this agent.
389        ///
390        /// Note: Not only all agents support modes.
391        ///
392        /// Default: None
393        default_mode: Option<String>,
394        /// The default model to use for this agent.
395        ///
396        /// This should be the model ID as reported by the agent.
397        ///
398        /// Default: None
399        default_model: Option<String>,
400        /// The favorite models for this agent.
401        ///
402        /// These are the model IDs as reported by the agent.
403        ///
404        /// Default: []
405        #[serde(default, skip_serializing_if = "Vec::is_empty")]
406        favorite_models: Vec<String>,
407        /// Default values for session config options.
408        ///
409        /// This is a map from config option ID to value ID.
410        ///
411        /// Default: {}
412        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
413        default_config_options: HashMap<String, String>,
414        /// Favorited values for session config options.
415        ///
416        /// This is a map from config option ID to a list of favorited value IDs.
417        ///
418        /// Default: {}
419        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
420        favorite_config_option_values: HashMap<String, Vec<String>>,
421    },
422    Registry {
423        /// Additional environment variables to pass to the agent.
424        ///
425        /// Default: {}
426        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
427        env: HashMap<String, String>,
428        /// The default mode to use for this agent.
429        ///
430        /// Note: Not only all agents support modes.
431        ///
432        /// Default: None
433        default_mode: Option<String>,
434        /// The default model to use for this agent.
435        ///
436        /// This should be the model ID as reported by the agent.
437        ///
438        /// Default: None
439        default_model: Option<String>,
440        /// The favorite models for this agent.
441        ///
442        /// These are the model IDs as reported by the agent.
443        ///
444        /// Default: []
445        #[serde(default, skip_serializing_if = "Vec::is_empty")]
446        favorite_models: Vec<String>,
447        /// Default values for session config options.
448        ///
449        /// This is a map from config option ID to value ID.
450        ///
451        /// Default: {}
452        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
453        default_config_options: HashMap<String, String>,
454        /// Favorited values for session config options.
455        ///
456        /// This is a map from config option ID to a list of favorited value IDs.
457        ///
458        /// Default: {}
459        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
460        favorite_config_option_values: HashMap<String, Vec<String>>,
461    },
462}
463
464#[with_fallible_options]
465#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
466pub struct ToolPermissionsContent {
467    /// Global default permission when no tool-specific rules match.
468    /// Individual tools can override this with their own default.
469    /// Default: confirm
470    #[serde(alias = "default_mode")]
471    pub default: Option<ToolPermissionMode>,
472
473    /// Per-tool permission rules.
474    /// Keys are tool names (e.g. terminal, edit_file, fetch) including MCP
475    /// tools (e.g. mcp:server_name:tool_name). Any tool name is accepted;
476    /// even tools without meaningful text input can have a `default` set.
477    #[serde(default)]
478    pub tools: HashMap<Arc<str>, ToolRulesContent>,
479}
480
481#[with_fallible_options]
482#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
483pub struct ToolRulesContent {
484    /// Default mode when no regex rules match.
485    /// When unset, inherits from the global `tool_permissions.default`.
486    #[serde(alias = "default_mode")]
487    pub default: Option<ToolPermissionMode>,
488
489    /// Regexes for inputs to auto-approve.
490    /// For terminal: matches command. For file tools: matches path. For fetch: matches URL.
491    /// For `copy_path` and `move_path`, patterns are matched independently against each
492    /// path (source and destination).
493    /// Patterns accumulate across settings layers (user, project, profile) and cannot be
494    /// removed by a higher-priority layer—only new patterns can be added.
495    /// Default: []
496    pub always_allow: Option<ExtendingVec<ToolRegexRule>>,
497
498    /// Regexes for inputs to auto-reject.
499    /// **SECURITY**: These take precedence over ALL other rules, across ALL settings layers.
500    /// For `copy_path` and `move_path`, patterns are matched independently against each
501    /// path (source and destination).
502    /// Patterns accumulate across settings layers (user, project, profile) and cannot be
503    /// removed by a higher-priority layer—only new patterns can be added.
504    /// Default: []
505    pub always_deny: Option<ExtendingVec<ToolRegexRule>>,
506
507    /// Regexes for inputs that must always prompt.
508    /// Takes precedence over always_allow but not always_deny.
509    /// For `copy_path` and `move_path`, patterns are matched independently against each
510    /// path (source and destination).
511    /// Patterns accumulate across settings layers (user, project, profile) and cannot be
512    /// removed by a higher-priority layer—only new patterns can be added.
513    /// Default: []
514    pub always_confirm: Option<ExtendingVec<ToolRegexRule>>,
515}
516
517#[with_fallible_options]
518#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
519pub struct ToolRegexRule {
520    /// The regex pattern to match.
521    #[serde(default)]
522    pub pattern: String,
523
524    /// Whether the regex is case-sensitive.
525    /// Default: false (case-insensitive)
526    pub case_sensitive: Option<bool>,
527}
528
529#[derive(
530    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom,
531)]
532#[serde(rename_all = "snake_case")]
533pub enum ToolPermissionMode {
534    /// Auto-approve without prompting.
535    Allow,
536    /// Auto-reject with an error.
537    Deny,
538    /// Always prompt for confirmation (default behavior).
539    #[default]
540    Confirm,
541}
542
543impl std::fmt::Display for ToolPermissionMode {
544    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
545        match self {
546            ToolPermissionMode::Allow => write!(f, "Allow"),
547            ToolPermissionMode::Deny => write!(f, "Deny"),
548            ToolPermissionMode::Confirm => write!(f, "Confirm"),
549        }
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    #[test]
558    fn test_set_tool_default_permission_creates_structure() {
559        let mut settings = AgentSettingsContent::default();
560        assert!(settings.tool_permissions.is_none());
561
562        settings.set_tool_default_permission("terminal", ToolPermissionMode::Allow);
563
564        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
565        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
566        assert_eq!(terminal_rules.default, Some(ToolPermissionMode::Allow));
567    }
568
569    #[test]
570    fn test_set_tool_default_permission_updates_existing() {
571        let mut settings = AgentSettingsContent::default();
572
573        settings.set_tool_default_permission("terminal", ToolPermissionMode::Confirm);
574        settings.set_tool_default_permission("terminal", ToolPermissionMode::Allow);
575
576        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
577        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
578        assert_eq!(terminal_rules.default, Some(ToolPermissionMode::Allow));
579    }
580
581    #[test]
582    fn test_set_tool_default_permission_for_mcp_tool() {
583        let mut settings = AgentSettingsContent::default();
584
585        settings.set_tool_default_permission("mcp:github:create_issue", ToolPermissionMode::Allow);
586
587        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
588        let mcp_rules = tool_permissions
589            .tools
590            .get("mcp:github:create_issue")
591            .unwrap();
592        assert_eq!(mcp_rules.default, Some(ToolPermissionMode::Allow));
593    }
594
595    #[test]
596    fn test_add_tool_allow_pattern_creates_structure() {
597        let mut settings = AgentSettingsContent::default();
598        assert!(settings.tool_permissions.is_none());
599
600        settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
601
602        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
603        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
604        let always_allow = terminal_rules.always_allow.as_ref().unwrap();
605        assert_eq!(always_allow.0.len(), 1);
606        assert_eq!(always_allow.0[0].pattern, "^cargo\\s");
607    }
608
609    #[test]
610    fn test_add_tool_allow_pattern_appends_to_existing() {
611        let mut settings = AgentSettingsContent::default();
612
613        settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
614        settings.add_tool_allow_pattern("terminal", "^npm\\s".to_string());
615
616        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
617        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
618        let always_allow = terminal_rules.always_allow.as_ref().unwrap();
619        assert_eq!(always_allow.0.len(), 2);
620        assert_eq!(always_allow.0[0].pattern, "^cargo\\s");
621        assert_eq!(always_allow.0[1].pattern, "^npm\\s");
622    }
623
624    #[test]
625    fn test_add_tool_allow_pattern_does_not_duplicate() {
626        let mut settings = AgentSettingsContent::default();
627
628        settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
629        settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
630        settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
631
632        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
633        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
634        let always_allow = terminal_rules.always_allow.as_ref().unwrap();
635        assert_eq!(
636            always_allow.0.len(),
637            1,
638            "Duplicate patterns should not be added"
639        );
640    }
641
642    #[test]
643    fn test_add_tool_allow_pattern_for_different_tools() {
644        let mut settings = AgentSettingsContent::default();
645
646        settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
647        settings.add_tool_allow_pattern("fetch", "^https?://github\\.com".to_string());
648
649        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
650
651        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
652        assert_eq!(
653            terminal_rules.always_allow.as_ref().unwrap().0[0].pattern,
654            "^cargo\\s"
655        );
656
657        let fetch_rules = tool_permissions.tools.get("fetch").unwrap();
658        assert_eq!(
659            fetch_rules.always_allow.as_ref().unwrap().0[0].pattern,
660            "^https?://github\\.com"
661        );
662    }
663
664    #[test]
665    fn test_add_tool_deny_pattern_creates_structure() {
666        let mut settings = AgentSettingsContent::default();
667        assert!(settings.tool_permissions.is_none());
668
669        settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
670
671        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
672        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
673        let always_deny = terminal_rules.always_deny.as_ref().unwrap();
674        assert_eq!(always_deny.0.len(), 1);
675        assert_eq!(always_deny.0[0].pattern, "^rm\\s");
676    }
677
678    #[test]
679    fn test_add_tool_deny_pattern_appends_to_existing() {
680        let mut settings = AgentSettingsContent::default();
681
682        settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
683        settings.add_tool_deny_pattern("terminal", "^sudo\\s".to_string());
684
685        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
686        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
687        let always_deny = terminal_rules.always_deny.as_ref().unwrap();
688        assert_eq!(always_deny.0.len(), 2);
689        assert_eq!(always_deny.0[0].pattern, "^rm\\s");
690        assert_eq!(always_deny.0[1].pattern, "^sudo\\s");
691    }
692
693    #[test]
694    fn test_add_tool_deny_pattern_does_not_duplicate() {
695        let mut settings = AgentSettingsContent::default();
696
697        settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
698        settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
699        settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
700
701        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
702        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
703        let always_deny = terminal_rules.always_deny.as_ref().unwrap();
704        assert_eq!(
705            always_deny.0.len(),
706            1,
707            "Duplicate patterns should not be added"
708        );
709    }
710
711    #[test]
712    fn test_add_tool_deny_and_allow_patterns_separate() {
713        let mut settings = AgentSettingsContent::default();
714
715        settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
716        settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
717
718        let tool_permissions = settings.tool_permissions.as_ref().unwrap();
719        let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
720
721        let always_allow = terminal_rules.always_allow.as_ref().unwrap();
722        assert_eq!(always_allow.0.len(), 1);
723        assert_eq!(always_allow.0[0].pattern, "^cargo\\s");
724
725        let always_deny = terminal_rules.always_deny.as_ref().unwrap();
726        assert_eq!(always_deny.0.len(), 1);
727        assert_eq!(always_deny.0[0].pattern, "^rm\\s");
728    }
729}