Skip to main content

vtcode_core/primary_agent/
mod.rs

1use std::collections::BTreeMap;
2use std::error::Error;
3use std::fmt;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use vtcode_config::constants::{defaults::DEFAULT_PRIMARY_AGENT_NAME, tools};
8use vtcode_config::core::permissions::AgentPermissionsConfig;
9use vtcode_config::core::tools::ToolPolicy;
10use vtcode_config::{
11    DiscoveredSubagents, HookGroupConfig, HooksConfig, SubagentMcpServer, SubagentMemoryScope, SubagentSource,
12    SubagentSpec, builtin_primary_build_agent,
13};
14
15use crate::config::{ReasoningEffortLevel, VTCodeConfig};
16use crate::llm::provider::ToolDefinition;
17use crate::permissions::{PermissionRequest, ResolvedPermissionDecision, evaluate_effective_permissions};
18use crate::prompts::PromptContext;
19use crate::subagents::{ResolvedAgentRuntimeView, inline_mcp_provider};
20use tracing::warn;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ActivePrimaryAgentSpecIdentity {
24    pub name: String,
25    pub source: SubagentSource,
26    pub file_path: Option<PathBuf>,
27}
28
29#[derive(Debug, Clone, PartialEq)]
30pub struct ActivePrimaryAgent {
31    pub identity: ActivePrimaryAgentSpecIdentity,
32    pub display_name: String,
33    pub description: String,
34    pub color: Option<String>,
35    pub aliases: Vec<String>,
36    pub instructions: String,
37    pub tools: Option<Vec<String>>,
38    pub disallowed_tools: Vec<String>,
39    pub permissions: AgentPermissionsConfig,
40    pub model: Option<String>,
41    pub reasoning_effort: Option<ReasoningEffortLevel>,
42    pub hooks: Option<HooksConfig>,
43    pub skills: Vec<String>,
44    pub mcp_servers: Vec<SubagentMcpServer>,
45    pub memory: Option<SubagentMemoryScope>,
46    pub tool_policy_overrides: BTreeMap<String, ToolPolicy>,
47}
48
49impl ActivePrimaryAgent {
50    #[must_use]
51    pub fn from_spec(spec: &SubagentSpec) -> Self {
52        Self::from_runtime_view(&ResolvedAgentRuntimeView::from_spec(spec))
53    }
54
55    #[must_use]
56    pub fn from_runtime_view(runtime: &ResolvedAgentRuntimeView) -> Self {
57        Self {
58            identity: ActivePrimaryAgentSpecIdentity {
59                name: runtime.canonical_name.clone(),
60                source: runtime.source.clone(),
61                file_path: runtime.file_path.clone(),
62            },
63            display_name: runtime.display_name.clone(),
64            description: runtime.description.clone(),
65            color: runtime.color.clone(),
66            aliases: runtime.aliases.clone(),
67            instructions: runtime.instructions.clone(),
68            tools: runtime.tools.clone(),
69            disallowed_tools: runtime.disallowed_tools.clone(),
70            permissions: runtime.permissions.clone(),
71            model: runtime.model.clone(),
72            reasoning_effort: runtime.reasoning_effort,
73            hooks: runtime.hooks.clone(),
74            skills: runtime.skills.clone(),
75            mcp_servers: runtime.mcp_servers.clone(),
76            memory: runtime.memory,
77            tool_policy_overrides: runtime.tool_policy_overrides.clone(),
78        }
79    }
80
81    /// Canonical primary agent name (the active session "mode").
82    #[must_use]
83    pub fn name(&self) -> &str {
84        &self.identity.name
85    }
86
87    /// Whether this agent contributes lifecycle hooks that originate from
88    /// workspace-controlled content (project agent-spec files inside the
89    /// repository). Such hooks must be gated behind the workspace lifecycle
90    /// hook approval just like hooks declared in a workspace `vtcode.toml`.
91    #[must_use]
92    pub fn contributes_workspace_controlled_hooks(&self) -> bool {
93        self.hooks.is_some()
94            && matches!(
95                self.identity.source,
96                SubagentSource::ProjectVtcode | SubagentSource::ProjectClaude | SubagentSource::ProjectCodex
97            )
98    }
99}
100
101#[derive(Debug, Clone, PartialEq)]
102pub struct ActivePrimaryAgentState {
103    active: ActivePrimaryAgent,
104}
105
106impl Default for ActivePrimaryAgentState {
107    fn default() -> Self {
108        Self {
109            active: ActivePrimaryAgent::from_spec(&builtin_primary_build_agent()),
110        }
111    }
112}
113
114impl ActivePrimaryAgentState {
115    #[must_use]
116    pub const fn active(&self) -> &ActivePrimaryAgent {
117        &self.active
118    }
119
120    #[must_use]
121    pub fn from_discovery(discovered: &DiscoveredSubagents) -> Self {
122        Self::from_specs(&discovered.effective)
123    }
124
125    #[must_use]
126    pub fn from_specs(specs: &[SubagentSpec]) -> Self {
127        Self::from_specs_with_default(specs, DEFAULT_PRIMARY_AGENT_NAME)
128    }
129
130    #[must_use]
131    pub fn from_specs_with_default(specs: &[SubagentSpec], requested_default: &str) -> Self {
132        let requested = if requested_default.trim().is_empty() {
133            DEFAULT_PRIMARY_AGENT_NAME
134        } else {
135            requested_default.trim()
136        };
137        let active = match resolve_primary_agent(specs, requested) {
138            Ok(active) => active,
139            Err(_) => {
140                if let Some(requested_name) = fallback_notice(requested) {
141                    warn!(
142                        requested = %requested_name,
143                        fallback = %DEFAULT_PRIMARY_AGENT_NAME,
144                        "Primary agent '{}' was not discovered; falling back to the built-in '{}' agent. \
145                         Set default_primary_agent to a discovered agent or add a matching primary agent.",
146                        requested_name,
147                        DEFAULT_PRIMARY_AGENT_NAME,
148                    );
149                }
150                ActivePrimaryAgent::from_spec(&builtin_primary_build_agent())
151            }
152        };
153        Self { active }
154    }
155
156    pub fn reset_to_default_from_specs(&mut self, specs: &[SubagentSpec]) -> &ActivePrimaryAgent {
157        self.active = Self::from_specs(specs).active;
158        &self.active
159    }
160
161    /// Restore a previously captured active-agent snapshot. Runloop prompt
162    /// boundaries use this to keep a write-capable Build handoff intact when
163    /// unrelated queued UI input attempts to switch modes mid-turn.
164    pub fn restore_snapshot(&mut self, snapshot: ActivePrimaryAgent) -> &ActivePrimaryAgent {
165        self.active = snapshot;
166        &self.active
167    }
168
169    pub fn select_from_discovery(
170        &mut self,
171        discovered: &DiscoveredSubagents,
172        requested: &str,
173    ) -> PrimaryAgentResolutionResult<&ActivePrimaryAgent> {
174        self.select_from_specs(&discovered.effective, requested)
175    }
176
177    pub fn select_from_specs(
178        &mut self,
179        specs: &[SubagentSpec],
180        requested: &str,
181    ) -> PrimaryAgentResolutionResult<&ActivePrimaryAgent> {
182        let active = resolve_primary_agent(specs, requested)?;
183        self.active = active;
184        Ok(&self.active)
185    }
186}
187
188pub type PrimaryAgentResolutionResult<T> = Result<T, PrimaryAgentResolutionError>;
189
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub enum PrimaryAgentResolutionError {
192    UnknownAgent { requested: String },
193}
194
195impl fmt::Display for PrimaryAgentResolutionError {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        match self {
198            Self::UnknownAgent { requested } => write!(f, "Unknown primary agent {requested}"),
199        }
200    }
201}
202
203impl Error for PrimaryAgentResolutionError {}
204
205pub fn resolve_discovered_primary_agent(
206    discovered: &DiscoveredSubagents,
207    requested: &str,
208) -> PrimaryAgentResolutionResult<ActivePrimaryAgent> {
209    resolve_primary_agent(&discovered.effective, requested)
210}
211
212pub fn resolve_primary_agent(
213    specs: &[SubagentSpec],
214    requested: &str,
215) -> PrimaryAgentResolutionResult<ActivePrimaryAgent> {
216    specs
217        .iter()
218        .find(|spec| spec.is_primary() && spec.name.eq_ignore_ascii_case(requested))
219        .or_else(|| specs.iter().find(|spec| spec.is_primary() && spec.matches_name(requested)))
220        .map(ActivePrimaryAgent::from_spec)
221        .ok_or_else(|| PrimaryAgentResolutionError::UnknownAgent { requested: requested.to_string() })
222}
223
224/// Returns `true` for cleanup-only child-agent tools that must remain
225/// available regardless of the active primary agent's tool policy.
226///
227/// NOTE: after `wait_agent`/`close_agent` were folded into the unified
228/// `agent` tool (action='wait'/'close'), `LIFECYCLE_CLEANUP_TOOLS` no longer
229/// matches any name that is actually *emitted* to the model — the emitted
230/// name is always `tools::AGENT` ("agent"). This carve-out therefore only
231/// takes effect if a caller passes one of the legacy granular names
232/// (`wait_agent`/`close_agent`) directly rather than the folded name.
233/// Expressing true per-action granularity at runtime (allow cleanup actions
234/// on the folded `agent` tool while denying `spawn`) requires
235/// execution-time action gating, the same mechanism used for
236/// `mcp:connect`/`mcp:disconnect` (see `action_qualified_policy_name` in
237/// `tool_intent.rs`), and is deferred — see
238/// `apply_primary_agent_tool_policy`'s doc comment for the specific gap.
239fn is_subagent_cleanup_tool(tool_name: &str) -> bool {
240    tools::LIFECYCLE_CLEANUP_TOOLS
241        .iter()
242        .any(|cleanup| cleanup.eq_ignore_ascii_case(tool_name))
243}
244
245/// Returns the configured agent name that should be surfaced to the operator
246/// when the resolver cannot find it and falls back to the built-in `build`
247/// agent, or `None` when the fallback is expected and should stay silent.
248///
249/// A fallback is expected (and therefore silent) when the operator asked for
250/// the default `build` agent — whether explicitly or because no
251/// `default_primary_agent` was configured — since the built-in `build` agent
252/// *is* the canonical build. Any other requested name that misses discovery is
253/// a configuration mismatch the operator should hear about.
254///
255/// Extracted as a pure predicate so the decision is unit-testable without a
256/// tracing subscriber.
257fn fallback_notice(requested_default: &str) -> Option<&str> {
258    let requested = requested_default.trim();
259    if requested.is_empty() || requested.eq_ignore_ascii_case(DEFAULT_PRIMARY_AGENT_NAME) {
260        None
261    } else {
262        Some(requested)
263    }
264}
265
266#[must_use]
267pub fn primary_agent_allows_tool(agent: &ActivePrimaryAgent, tool_name: &str) -> bool {
268    let tool_name = tool_name.trim();
269
270    // Cleanup tools stay available so restricted agents can still join or
271    // close already-running child work.
272    if is_subagent_cleanup_tool(tool_name) {
273        return true;
274    }
275
276    // The task tracker stays available so restricted primaries (including
277    // custom `auto` agents with an explicit `tools:` list) can still report
278    // progress. Planning/interview tools stay author-curated: unlike the
279    // tracker they change the session mode, so an explicit omission must
280    // keep working.
281    if tool_name.eq_ignore_ascii_case(tools::TASK_TRACKER) {
282        return true;
283    }
284
285    let allow_list_allows = agent
286        .tools
287        .as_ref()
288        .is_none_or(|tools| tools.iter().any(|allowed| allowed.trim().eq_ignore_ascii_case(tool_name)));
289    if !allow_list_allows {
290        return false;
291    }
292
293    !agent
294        .disallowed_tools
295        .iter()
296        .any(|denied| denied.trim().eq_ignore_ascii_case(tool_name))
297}
298
299/// Filters the emitted tool list down to those `primary_agent_allows_tool`
300/// permits for `agent`.
301///
302/// KNOWN LIMITATION: filtering is by each tool's canonical
303/// `function_name()`, and matching only trims and ignores ASCII case — it
304/// does not alias-resolve. For multi-action tools that fold several legacy
305/// actions into one emitted name (e.g. `agent` folding
306/// spawn/wait/close/send_input/resume, or `mcp` folding connect/disconnect),
307/// a granular allow/deny entry such as `"spawn_agent"` in
308/// `disallowed_tools`/`tools` has no effect on the folded `agent` tool: the
309/// whole tool is either present or absent based on whether `"agent"` itself
310/// is allowed. Expressing "allow cleanup (wait/close) but deny spawn"
311/// therefore cannot be done here; it requires execution-time action gating —
312/// the same action-qualified mechanism already used to keep `mcp:connect`/
313/// `mcp:disconnect` HITL-gated separately from bare `mcp` (see
314/// `action_qualified_policy_name` in `tool_intent.rs`) — applied per-action
315/// at the point the subagent tool call is dispatched. That is deferred.
316#[must_use]
317pub fn apply_primary_agent_tool_policy(
318    tools: Option<Arc<Vec<ToolDefinition>>>,
319    agent: &ActivePrimaryAgent,
320) -> Option<Arc<Vec<ToolDefinition>>> {
321    let tools = tools?;
322    let Some(first_rejected) = tools
323        .iter()
324        .position(|tool| !primary_agent_allows_tool(agent, tool.function_name()))
325    else {
326        return (!tools.is_empty()).then_some(tools);
327    };
328    let filtered = tools
329        .iter()
330        .take(first_rejected)
331        .chain(
332            tools
333                .iter()
334                .skip(first_rejected + 1)
335                .filter(|tool| primary_agent_allows_tool(agent, tool.function_name())),
336        )
337        .cloned()
338        .collect::<Vec<_>>();
339
340    (!filtered.is_empty()).then(|| Arc::new(filtered))
341}
342
343#[must_use]
344pub fn build_primary_agent_runtime_config(parent: &VTCodeConfig, agent: &ActivePrimaryAgent) -> VTCodeConfig {
345    let mut config = parent.clone();
346    // "inherit" (and empty) are sentinels meaning "use the parent's model" — mirrors
347    // resolve_subagent_model's handling in subagents/model.rs. Built-in primary agents
348    // (e.g. "auto", "build") default their `model` field to "inherit", so without this
349    // check every plain `exec` run would clobber a real, explicitly configured model
350    // (via --model or [agent].default_model) with the literal string "inherit", which
351    // then fails ModelId parsing entirely.
352    if let Some(model) = agent.model.as_ref() {
353        let trimmed = model.trim();
354        if !trimmed.is_empty() && !trimmed.eq_ignore_ascii_case("inherit") {
355            config.agent.default_model = model.clone();
356        }
357    }
358    if let Some(reasoning_effort) = agent.reasoning_effort {
359        config.agent.reasoning_effort = reasoning_effort;
360    }
361    merge_primary_mcp_servers(&mut config, agent.mcp_servers.as_slice());
362    config
363}
364
365#[must_use]
366pub fn build_primary_agent_hook_config(global: &HooksConfig, agent: &ActivePrimaryAgent) -> HooksConfig {
367    let mut config = global.clone();
368    merge_active_primary_hooks(&mut config, agent.hooks.as_ref());
369    config
370}
371
372pub fn apply_primary_agent_prompt_context(context: &mut PromptContext, agent: &ActivePrimaryAgent) {
373    context.replace_available_skills_with_named(agent.skills.as_slice());
374}
375
376#[must_use]
377pub fn active_primary_agent_permissions(agent: &ActivePrimaryAgent) -> &AgentPermissionsConfig {
378    &agent.permissions
379}
380
381pub fn evaluate_active_primary_agent_permissions(
382    config: &VTCodeConfig,
383    agent: &ActivePrimaryAgent,
384    workspace_root: &std::path::Path,
385    current_dir: &std::path::Path,
386    request: &PermissionRequest,
387) -> ResolvedPermissionDecision {
388    evaluate_effective_permissions(
389        &config.permissions,
390        active_primary_agent_permissions(agent),
391        workspace_root,
392        current_dir,
393        request,
394    )
395}
396
397fn merge_primary_mcp_servers(config: &mut VTCodeConfig, servers: &[SubagentMcpServer]) {
398    for server in servers {
399        match server {
400            SubagentMcpServer::Named(_) => {}
401            SubagentMcpServer::Inline(definition) => {
402                for (name, value) in definition {
403                    if config.mcp.providers.iter().any(|provider| provider.name == *name) {
404                        continue;
405                    }
406                    if let Some(provider) = inline_mcp_provider(name, value) {
407                        config.mcp.providers.push(provider);
408                    }
409                }
410            }
411        }
412    }
413}
414
415fn merge_active_primary_hooks(config: &mut HooksConfig, hooks: Option<&HooksConfig>) {
416    let Some(hooks) = hooks else {
417        return;
418    };
419
420    config.lifecycle.quiet_success_output |= hooks.lifecycle.quiet_success_output;
421    append_hook_groups(&mut config.lifecycle.session_start, &hooks.lifecycle.session_start);
422    append_hook_groups(&mut config.lifecycle.session_end, &hooks.lifecycle.session_end);
423    append_hook_groups(&mut config.lifecycle.subagent_start, &hooks.lifecycle.subagent_start);
424    append_hook_groups(&mut config.lifecycle.subagent_stop, &hooks.lifecycle.subagent_stop);
425    append_hook_groups(&mut config.lifecycle.user_prompt_submit, &hooks.lifecycle.user_prompt_submit);
426    append_hook_groups(&mut config.lifecycle.pre_tool_use, &hooks.lifecycle.pre_tool_use);
427    append_hook_groups(&mut config.lifecycle.post_tool_use, &hooks.lifecycle.post_tool_use);
428    append_hook_groups(&mut config.lifecycle.permission_request, &hooks.lifecycle.permission_request);
429    append_hook_groups(&mut config.lifecycle.pre_compact, &hooks.lifecycle.pre_compact);
430    append_hook_groups(&mut config.lifecycle.stop, &hooks.lifecycle.stop);
431    append_hook_groups(&mut config.lifecycle.notification, &hooks.lifecycle.notification);
432}
433
434fn append_hook_groups(target: &mut Vec<HookGroupConfig>, source: &[HookGroupConfig]) {
435    target.extend(source.iter().cloned());
436}
437
438#[cfg(test)]
439mod tests;