Skip to main content

vtcode_config/subagents/
mod.rs

1use anyhow::{Context, Result, anyhow, bail};
2use serde::{Deserialize, Serialize};
3use serde_json::{Map as JsonMap, Value as JsonValue};
4use std::collections::BTreeMap;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::sync::LazyLock;
8use vtcode_commons::VtCodePaths;
9use vtcode_commons::reasoning::ReasoningEffortLevel;
10
11use crate::constants::tools;
12use crate::constants::ui;
13use crate::core::permissions::{AgentPermissionsConfig, PermissionDefault};
14use crate::core::tools::ToolPolicy;
15use crate::hooks::{HookCommandConfig, HookCommandKind, HookGroupConfig, HooksConfig};
16
17use self::permissions::is_mutating_tool_name;
18
19mod builtin;
20mod discovery;
21mod parse;
22mod permissions;
23
24pub use builtin::{
25    builtin_plan_agent, builtin_primary_auto_agent, builtin_primary_build_agent, builtin_primary_coordinator_agent,
26    builtin_primary_duck_agent, builtin_subagents,
27};
28pub use discovery::{discover_subagents, load_subagent_from_file};
29
30#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
31#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
32#[serde(rename_all = "snake_case")]
33pub enum SubagentSource {
34    Cli,
35    ProjectVtcode,
36    ProjectClaude,
37    ProjectCodex,
38    UserVtcode,
39    UserClaude,
40    UserCodex,
41    Plugin { plugin: String },
42    Builtin,
43}
44
45impl SubagentSource {
46    #[must_use]
47    const fn priority(&self) -> usize {
48        match self {
49            Self::Cli => 0,
50            Self::ProjectVtcode => 1,
51            Self::ProjectClaude => 2,
52            Self::ProjectCodex => 3,
53            Self::UserVtcode => 4,
54            Self::UserClaude => 5,
55            Self::UserCodex => 6,
56            Self::Plugin { .. } => 7,
57            Self::Builtin => 8,
58        }
59    }
60
61    #[must_use]
62    pub fn label(&self) -> String {
63        match self {
64            Self::Cli => "cli".to_string(),
65            Self::ProjectVtcode => "project:.vtcode".to_string(),
66            Self::ProjectClaude => "project:.claude".to_string(),
67            Self::ProjectCodex => "project:.codex".to_string(),
68            Self::UserVtcode => "user:canonical-config".to_string(),
69            Self::UserClaude => "user:~/.claude".to_string(),
70            Self::UserCodex => "user:~/.codex".to_string(),
71            Self::Plugin { plugin } => format!("plugin:{plugin}"),
72            Self::Builtin => "builtin".to_string(),
73        }
74    }
75
76    #[must_use]
77    const fn vtcode_native(&self) -> bool {
78        matches!(self, Self::ProjectVtcode | Self::UserVtcode | Self::Cli)
79    }
80}
81
82#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
83#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
84#[serde(rename_all = "snake_case")]
85pub enum SubagentMemoryScope {
86    User,
87    Project,
88    Local,
89}
90
91#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
92#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Default)]
93#[serde(rename_all = "snake_case")]
94pub enum AgentMode {
95    Primary,
96    #[default]
97    Subagent,
98    All,
99}
100
101/// Subagent isolation mode
102#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
104#[serde(rename_all = "snake_case")]
105pub enum IsolationMode {
106    /// Full isolation (separate process)
107    Full,
108    /// Git worktree isolation
109    Worktree,
110}
111
112#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
113#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
114#[serde(untagged)]
115pub enum SubagentMcpServer {
116    Named(String),
117    Inline(BTreeMap<String, JsonValue>),
118}
119
120#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
121#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
122#[serde(rename_all = "snake_case")]
123pub enum AgentSpecFieldClass {
124    Shared,
125    PrimaryMetadata,
126    PrimaryRuntime,
127    SubagentOnly,
128    Availability,
129}
130
131#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
132#[derive(Debug, Clone, Deserialize, Serialize)]
133pub struct SubagentSpec {
134    pub name: String,
135    pub description: String,
136    #[serde(default)]
137    pub prompt: String,
138    #[serde(default)]
139    pub tools: Option<Vec<String>>,
140    #[serde(default)]
141    pub disallowed_tools: Vec<String>,
142    #[serde(default)]
143    pub model: Option<String>,
144    #[serde(default)]
145    pub color: Option<String>,
146    #[serde(default)]
147    pub reasoning_effort: Option<ReasoningEffortLevel>,
148    pub permissions: AgentPermissionsConfig,
149    #[serde(default)]
150    pub skills: Vec<String>,
151    #[serde(default)]
152    pub mcp_servers: Vec<SubagentMcpServer>,
153    #[serde(default)]
154    pub hooks: Option<HooksConfig>,
155    #[serde(default)]
156    pub background: bool,
157    #[serde(default)]
158    pub mode: AgentMode,
159    #[serde(default)]
160    pub max_turns: Option<usize>,
161    #[serde(default)]
162    pub nickname_candidates: Vec<String>,
163    #[serde(default)]
164    pub initial_prompt: Option<String>,
165    #[serde(default)]
166    pub memory: Option<SubagentMemoryScope>,
167    #[serde(default)]
168    pub isolation: Option<IsolationMode>,
169    #[serde(default)]
170    pub aliases: Vec<String>,
171    pub source: SubagentSource,
172    #[serde(default)]
173    pub file_path: Option<PathBuf>,
174    #[serde(default)]
175    pub warnings: Vec<String>,
176    /// Per-tool policy overrides applied when this agent becomes active.
177    /// Keys are tool names, values are the policy to enforce.
178    /// Applied on top of (and overriding) the global `[tools.policies]` from vtcode.toml.
179    #[serde(default)]
180    pub tool_policy_overrides: BTreeMap<String, ToolPolicy>,
181}
182
183impl Default for SubagentSpec {
184    fn default() -> Self {
185        Self {
186            name: String::new(),
187            description: String::new(),
188            prompt: String::new(),
189            tools: None,
190            disallowed_tools: Vec::new(),
191            model: None,
192            color: None,
193            reasoning_effort: None,
194            permissions: AgentPermissionsConfig {
195                default: PermissionDefault::Ask,
196                allow: Vec::new(),
197                ask: Vec::new(),
198                auto: Vec::new(),
199                deny: Vec::new(),
200            },
201            skills: Vec::new(),
202            mcp_servers: Vec::new(),
203            hooks: None,
204            background: false,
205            mode: AgentMode::default(),
206            max_turns: None,
207            nickname_candidates: Vec::new(),
208            initial_prompt: None,
209            memory: None,
210            isolation: None,
211            aliases: Vec::new(),
212            source: SubagentSource::Builtin,
213            file_path: None,
214            warnings: Vec::new(),
215            tool_policy_overrides: BTreeMap::new(),
216        }
217    }
218}
219
220impl SubagentSpec {
221    /// Human-facing built-in name. Canonical IDs and custom agent names stay unchanged.
222    #[must_use]
223    pub fn display_name(&self) -> &str {
224        if self.source != SubagentSource::Builtin {
225            return &self.name;
226        }
227        match self.name.as_str() {
228            "auto" => "Autonomous",
229            "build" => "Build",
230            "duck" => "Ask",
231            "plan" => "Plan",
232            "coordinator" => "Coordinator",
233            _ => &self.name,
234        }
235    }
236
237    #[must_use]
238    pub const fn is_primary(&self) -> bool {
239        matches!(self.mode, AgentMode::Primary | AgentMode::All)
240    }
241
242    #[must_use]
243    pub const fn is_subagent(&self) -> bool {
244        matches!(self.mode, AgentMode::Subagent | AgentMode::All)
245    }
246
247    #[must_use]
248    pub fn is_read_only(&self) -> bool {
249        if !self.permissions_allows_mutation() {
250            return true;
251        }
252
253        let tools = self.tools.as_ref().map_or_else(Vec::new, Clone::clone);
254        let lower_tools = tools.iter().map(|tool| tool.to_ascii_lowercase()).collect::<Vec<_>>();
255        let lower_denied = self
256            .disallowed_tools
257            .iter()
258            .map(|tool| tool.to_ascii_lowercase())
259            .collect::<Vec<_>>();
260
261        let denies_writes = lower_denied.iter().any(|tool| is_mutating_tool_name(tool.as_str()));
262
263        if self.tools.is_some() {
264            let exposes_mutation = lower_tools.iter().any(|tool| is_mutating_tool_name(tool.as_str()));
265            !exposes_mutation
266        } else {
267            denies_writes
268        }
269    }
270
271    #[must_use]
272    fn permissions_allows_mutation(&self) -> bool {
273        if matches!(
274            self.permissions.default,
275            PermissionDefault::Ask | PermissionDefault::Allow | PermissionDefault::Auto
276        ) {
277            return true;
278        }
279
280        self.permissions
281            .allow
282            .iter()
283            .chain(self.permissions.auto.iter())
284            .map(|rule| rule.to_ascii_lowercase())
285            .any(|rule| is_mutating_tool_name(rule.as_str()))
286    }
287
288    #[must_use]
289    pub fn matches_name(&self, candidate: &str) -> bool {
290        self.name.eq_ignore_ascii_case(candidate)
291            || self.aliases.iter().any(|alias| alias.eq_ignore_ascii_case(candidate))
292    }
293}
294
295#[must_use]
296pub(crate) fn classify_agent_spec_field(field: &str) -> Option<AgentSpecFieldClass> {
297    match field.trim() {
298        "name" | "prompt" => Some(AgentSpecFieldClass::Shared),
299        "description" | "color" | "aliases" => Some(AgentSpecFieldClass::PrimaryMetadata),
300        "tools" | "disallowed_tools" | "disallowedTools" | "permissions" | "model" | "reasoning_effort" | "skills"
301        | "mcp_servers" | "mcpServers" | "hooks" | "memory" => Some(AgentSpecFieldClass::PrimaryRuntime),
302        "background"
303        | "max_turns"
304        | "maxTurns"
305        | "initial_prompt"
306        | "initialPrompt"
307        | "nickname_candidates"
308        | "isolation" => Some(AgentSpecFieldClass::SubagentOnly),
309        "mode" => Some(AgentSpecFieldClass::Availability),
310        _ => None,
311    }
312}
313
314#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
315#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
316pub struct BackgroundSubagentConfig {
317    #[serde(default = "default_background_subagents_enabled")]
318    pub enabled: bool,
319    #[serde(default)]
320    pub default_agent: Option<String>,
321    #[serde(default = "default_background_refresh_interval_ms")]
322    pub refresh_interval_ms: u64,
323    #[serde(default = "default_background_auto_restore")]
324    pub auto_restore: bool,
325    #[serde(default = "default_background_toggle_shortcut")]
326    toggle_shortcut: String,
327}
328
329impl Default for BackgroundSubagentConfig {
330    fn default() -> Self {
331        Self {
332            enabled: default_background_subagents_enabled(),
333            default_agent: None,
334            refresh_interval_ms: default_background_refresh_interval_ms(),
335            auto_restore: default_background_auto_restore(),
336            toggle_shortcut: default_background_toggle_shortcut(),
337        }
338    }
339}
340
341#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
342#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
343pub struct SubagentRuntimeLimits {
344    #[serde(default = "default_subagents_enabled")]
345    pub enabled: bool,
346    #[serde(default = "default_subagents_max_concurrent")]
347    pub max_concurrent: usize,
348    #[serde(default = "default_subagents_max_depth")]
349    pub max_depth: usize,
350    #[serde(default = "default_subagents_default_timeout_seconds")]
351    pub default_timeout_seconds: u64,
352    #[serde(default = "default_subagents_auto_delegate_read_only")]
353    pub auto_delegate_read_only: bool,
354    #[serde(default)]
355    pub background: BackgroundSubagentConfig,
356}
357
358impl Default for SubagentRuntimeLimits {
359    fn default() -> Self {
360        Self {
361            enabled: default_subagents_enabled(),
362            max_concurrent: default_subagents_max_concurrent(),
363            max_depth: default_subagents_max_depth(),
364            default_timeout_seconds: default_subagents_default_timeout_seconds(),
365            auto_delegate_read_only: default_subagents_auto_delegate_read_only(),
366            background: BackgroundSubagentConfig::default(),
367        }
368    }
369}
370
371#[derive(Debug, Clone, Default)]
372pub struct DiscoveredSubagents {
373    pub effective: Vec<SubagentSpec>,
374    pub shadowed: Vec<SubagentSpec>,
375}
376
377#[derive(Debug, Clone)]
378pub struct SubagentDiscoveryInput {
379    pub workspace_root: PathBuf,
380    pub cli_agents: Option<JsonValue>,
381    pub plugin_agent_files: Vec<(String, PathBuf)>,
382    pub include_user_agents: bool,
383}
384
385impl SubagentDiscoveryInput {
386    #[must_use]
387    pub fn new(workspace_root: PathBuf) -> Self {
388        Self {
389            workspace_root,
390            cli_agents: None,
391            plugin_agent_files: Vec::new(),
392            include_user_agents: true,
393        }
394    }
395}
396
397impl Default for SubagentDiscoveryInput {
398    fn default() -> Self {
399        Self::new(PathBuf::new())
400    }
401}
402
403const fn default_subagents_enabled() -> bool {
404    true
405}
406
407/// Hard ceiling for subagent concurrency. The configurable `max_concurrent` is
408/// clamped to this value at runtime so it can never be exceeded.
409pub const SUBAGENT_HARD_CONCURRENCY_LIMIT: usize = 5;
410
411const fn default_subagents_max_concurrent() -> usize {
412    3
413}
414
415const fn default_subagents_max_depth() -> usize {
416    1
417}
418
419const fn default_subagents_default_timeout_seconds() -> u64 {
420    300
421}
422
423const fn default_subagents_auto_delegate_read_only() -> bool {
424    true
425}
426
427const fn default_background_subagents_enabled() -> bool {
428    false
429}
430
431const fn default_background_refresh_interval_ms() -> u64 {
432    2_000
433}
434
435const fn default_background_auto_restore() -> bool {
436    false
437}
438
439fn default_background_toggle_shortcut() -> String {
440    "ctrl+b".to_string()
441}
442
443#[cfg(test)]
444mod tests;