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    /// as a session-scoped in-memory overlay: overrides never persist to disk,
180    /// are replaced on every agent (re)selection (including session setup), and
181    /// can never lift an explicit persisted Deny.
182    #[serde(default)]
183    pub tool_policy_overrides: BTreeMap<String, ToolPolicy>,
184}
185
186impl Default for SubagentSpec {
187    fn default() -> Self {
188        Self {
189            name: String::new(),
190            description: String::new(),
191            prompt: String::new(),
192            tools: None,
193            disallowed_tools: Vec::new(),
194            model: None,
195            color: None,
196            reasoning_effort: None,
197            permissions: AgentPermissionsConfig {
198                default: PermissionDefault::Ask,
199                allow: Vec::new(),
200                ask: Vec::new(),
201                auto: Vec::new(),
202                deny: Vec::new(),
203            },
204            skills: Vec::new(),
205            mcp_servers: Vec::new(),
206            hooks: None,
207            background: false,
208            mode: AgentMode::default(),
209            max_turns: None,
210            nickname_candidates: Vec::new(),
211            initial_prompt: None,
212            memory: None,
213            isolation: None,
214            aliases: Vec::new(),
215            source: SubagentSource::Builtin,
216            file_path: None,
217            warnings: Vec::new(),
218            tool_policy_overrides: BTreeMap::new(),
219        }
220    }
221}
222
223impl SubagentSpec {
224    /// Human-facing built-in name. Canonical IDs and custom agent names stay unchanged.
225    #[must_use]
226    pub fn display_name(&self) -> &str {
227        if self.source != SubagentSource::Builtin {
228            return &self.name;
229        }
230        match self.name.as_str() {
231            "auto" => "Autonomous",
232            "build" => "Build",
233            "duck" => "Ask",
234            "plan" => "Plan",
235            "coordinator" => "Coordinator",
236            _ => &self.name,
237        }
238    }
239
240    #[must_use]
241    pub const fn is_primary(&self) -> bool {
242        matches!(self.mode, AgentMode::Primary | AgentMode::All)
243    }
244
245    #[must_use]
246    pub const fn is_subagent(&self) -> bool {
247        matches!(self.mode, AgentMode::Subagent | AgentMode::All)
248    }
249
250    #[must_use]
251    pub fn is_read_only(&self) -> bool {
252        if !self.permissions_allows_mutation() {
253            return true;
254        }
255
256        let tools = self.tools.as_ref().map_or_else(Vec::new, Clone::clone);
257        let lower_tools = tools.iter().map(|tool| tool.to_ascii_lowercase()).collect::<Vec<_>>();
258        let lower_denied = self
259            .disallowed_tools
260            .iter()
261            .map(|tool| tool.to_ascii_lowercase())
262            .collect::<Vec<_>>();
263
264        let denies_writes = lower_denied.iter().any(|tool| is_mutating_tool_name(tool.as_str()));
265
266        if self.tools.is_some() {
267            let exposes_mutation = lower_tools.iter().any(|tool| is_mutating_tool_name(tool.as_str()));
268            !exposes_mutation
269        } else {
270            denies_writes
271        }
272    }
273
274    #[must_use]
275    fn permissions_allows_mutation(&self) -> bool {
276        if matches!(
277            self.permissions.default,
278            PermissionDefault::Ask | PermissionDefault::Allow | PermissionDefault::Auto
279        ) {
280            return true;
281        }
282
283        self.permissions
284            .allow
285            .iter()
286            .chain(self.permissions.auto.iter())
287            .map(|rule| rule.to_ascii_lowercase())
288            .any(|rule| is_mutating_tool_name(rule.as_str()))
289    }
290
291    #[must_use]
292    pub fn matches_name(&self, candidate: &str) -> bool {
293        self.name.eq_ignore_ascii_case(candidate)
294            || self.aliases.iter().any(|alias| alias.eq_ignore_ascii_case(candidate))
295    }
296}
297
298#[must_use]
299pub(crate) fn classify_agent_spec_field(field: &str) -> Option<AgentSpecFieldClass> {
300    match field.trim() {
301        "name" | "prompt" => Some(AgentSpecFieldClass::Shared),
302        "description" | "color" | "aliases" => Some(AgentSpecFieldClass::PrimaryMetadata),
303        "tools" | "disallowed_tools" | "disallowedTools" | "permissions" | "model" | "reasoning_effort" | "skills"
304        | "mcp_servers" | "mcpServers" | "hooks" | "memory" => Some(AgentSpecFieldClass::PrimaryRuntime),
305        "background"
306        | "max_turns"
307        | "maxTurns"
308        | "initial_prompt"
309        | "initialPrompt"
310        | "nickname_candidates"
311        | "isolation" => Some(AgentSpecFieldClass::SubagentOnly),
312        "mode" => Some(AgentSpecFieldClass::Availability),
313        _ => None,
314    }
315}
316
317#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
318#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
319pub struct BackgroundSubagentConfig {
320    #[serde(default = "default_background_subagents_enabled")]
321    pub enabled: bool,
322    #[serde(default)]
323    pub default_agent: Option<String>,
324    #[serde(default = "default_background_refresh_interval_ms")]
325    pub refresh_interval_ms: u64,
326    #[serde(default = "default_background_auto_restore")]
327    pub auto_restore: bool,
328    #[serde(default = "default_background_toggle_shortcut")]
329    toggle_shortcut: String,
330}
331
332impl Default for BackgroundSubagentConfig {
333    fn default() -> Self {
334        Self {
335            enabled: default_background_subagents_enabled(),
336            default_agent: None,
337            refresh_interval_ms: default_background_refresh_interval_ms(),
338            auto_restore: default_background_auto_restore(),
339            toggle_shortcut: default_background_toggle_shortcut(),
340        }
341    }
342}
343
344#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
345#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
346pub struct SubagentRuntimeLimits {
347    #[serde(default = "default_subagents_enabled")]
348    pub enabled: bool,
349    #[serde(default = "default_subagents_max_concurrent")]
350    pub max_concurrent: usize,
351    #[serde(default = "default_subagents_max_depth")]
352    pub max_depth: usize,
353    #[serde(default = "default_subagents_default_timeout_seconds")]
354    pub default_timeout_seconds: u64,
355    #[serde(default = "default_subagents_auto_delegate_read_only")]
356    pub auto_delegate_read_only: bool,
357    #[serde(default)]
358    pub background: BackgroundSubagentConfig,
359}
360
361impl Default for SubagentRuntimeLimits {
362    fn default() -> Self {
363        Self {
364            enabled: default_subagents_enabled(),
365            max_concurrent: default_subagents_max_concurrent(),
366            max_depth: default_subagents_max_depth(),
367            default_timeout_seconds: default_subagents_default_timeout_seconds(),
368            auto_delegate_read_only: default_subagents_auto_delegate_read_only(),
369            background: BackgroundSubagentConfig::default(),
370        }
371    }
372}
373
374#[derive(Debug, Clone, Default)]
375pub struct DiscoveredSubagents {
376    pub effective: Vec<SubagentSpec>,
377    pub shadowed: Vec<SubagentSpec>,
378}
379
380#[derive(Debug, Clone)]
381pub struct SubagentDiscoveryInput {
382    pub workspace_root: PathBuf,
383    pub cli_agents: Option<JsonValue>,
384    pub plugin_agent_files: Vec<(String, PathBuf)>,
385    pub include_user_agents: bool,
386}
387
388impl SubagentDiscoveryInput {
389    #[must_use]
390    pub fn new(workspace_root: PathBuf) -> Self {
391        Self {
392            workspace_root,
393            cli_agents: None,
394            plugin_agent_files: Vec::new(),
395            include_user_agents: true,
396        }
397    }
398}
399
400impl Default for SubagentDiscoveryInput {
401    fn default() -> Self {
402        Self::new(PathBuf::new())
403    }
404}
405
406const fn default_subagents_enabled() -> bool {
407    true
408}
409
410/// Hard ceiling for subagent concurrency. The configurable `max_concurrent` is
411/// clamped to this value at runtime so it can never be exceeded.
412pub const SUBAGENT_HARD_CONCURRENCY_LIMIT: usize = 5;
413
414const fn default_subagents_max_concurrent() -> usize {
415    3
416}
417
418const fn default_subagents_max_depth() -> usize {
419    1
420}
421
422const fn default_subagents_default_timeout_seconds() -> u64 {
423    300
424}
425
426const fn default_subagents_auto_delegate_read_only() -> bool {
427    true
428}
429
430const fn default_background_subagents_enabled() -> bool {
431    false
432}
433
434const fn default_background_refresh_interval_ms() -> u64 {
435    2_000
436}
437
438const fn default_background_auto_restore() -> bool {
439    false
440}
441
442fn default_background_toggle_shortcut() -> String {
443    "ctrl+b".to_string()
444}
445
446#[cfg(test)]
447mod tests;