Skip to main content

vtcode_config/subagents/
builtin.rs

1//! Built-in primary and subagent specifications.
2
3use std::collections::BTreeMap;
4use std::sync::LazyLock;
5
6use vtcode_commons::reasoning::ReasoningEffortLevel;
7
8use crate::constants::tools;
9use crate::constants::ui;
10use crate::core::permissions::{AgentPermissionsConfig, PermissionDefault};
11use crate::core::tools::ToolPolicy;
12
13use super::{AgentMode, SubagentSource, SubagentSpec};
14
15const BUILTIN_DEFAULT_AGENT: &str = r#"You are the default VT Code execution subagent.
16
17Work directly, keep context isolated from the parent session, and return concise summaries.
18Match the repository's local patterns, verify changes, and avoid unrelated edits.
19If a file is referenced, read it before answering; base claims about code on what you have read.
20Only make changes that are directly requested or clearly necessary. Keep solutions simple and focused.
21Do not add features, refactor code, or make improvements beyond what was asked.
22Verify your work by running the smallest relevant check before reporting completion."#;
23
24const BUILTIN_EXPLORER_AGENT: &str = r#"You are a fast read-only exploration subagent.
25
26Search the codebase, inspect relevant files, and return concise findings with file references.
27Do not modify files or take mutating actions.
28Read files before making claims about their contents.
29Use structural search and grep over shell exploration when possible.
30Return findings with file paths and line numbers for easy navigation."#;
31
32const BUILTIN_WORKER_AGENT: &str = r#"You are a write-capable worker subagent.
33
34Handle bounded implementation work, verify results, and return a concise outcome summary with
35any important risks or follow-up items.
36Read files before editing them or describing what they contain.
37Only make changes that are directly requested. Keep solutions simple and focused.
38Do not add features, refactor surrounding code, or make improvements beyond the scope.
39Verify your changes by running relevant tests or checks before reporting completion.
40If calls repeat without progress, re-plan instead of retrying identically."#;
41
42const BUILTIN_BUILD_PRIMARY_AGENT: &str = r#"You are the build agent.
43
44Understand the user's request, then use available tools to inspect context and make changes.
45Read files before editing. Search before guessing at code structure.
46Edit, write, and run commands directly when the request is clear.
47Keep changes focused on what was asked. Do not add unrelated features or refactors.
48When planning is needed, state the plan briefly before implementation. When the user only wants
49discussion or review, do not edit files.
50Report changed files, validation, and remaining risks clearly."#;
51
52const BUILTIN_AUTO_PRIMARY_AGENT: &str = r#"You are the auto agent.
53
54Work autonomously within the active permission policy, taking direct action when the request is clear.
55Inspect the relevant repository context before editing, keep changes focused, and verify with the
56narrowest useful checks before reporting completion.
57Pause for user input when the scope is ambiguous, risky, or outside the requested work."#;
58
59const BUILTIN_COORDINATOR_PRIMARY_AGENT: &str = r#"You are the coordinator agent.
60
61Define explicit matrix tasks, dependencies, resource capacities, timeouts, and verification commands.
62Delegate all shell execution, file changes, and verification to scheduler-owned matrix workers.
63Use matrix create to persist a specification, then start to freeze it and dispatch work.
64Delegate discovery to a read-only explorer before making repository claims, while the matrix is idle.
65During active execution, use matrix status and control actions; do not spawn independent workers.
66Resolve failed checks, permission denials, exhausted budgets, and unsafe retries with the user.
67Worker summaries are not verification evidence. Report success only after matrix final verification.
68Pause stops dispatch; cancel is terminal. Preserve sandbox, approvals, and existing budgets."#;
69
70const DISCUSSION_FIRST_GUIDANCE: &str = r#"Be discussion-first. Clarify scope, constraints, contradictions, and options before implementation.
71Resolve ordinary ambiguity from repository evidence when possible; ask the user directly only when material ambiguity is critical.
72Stop researching when existing evidence supports a decision."#;
73
74const BUILTIN_PLAN_AGENT_ROLE: &str = r#"You are a read-only planning agent.
75
76Use repository-grounded, read-only discovery to gather the minimum context needed to support a plan or design decision.
77Return findings, risks, and constraints clearly, with specific code references and file paths.
78Read relevant files before making claims about the codebase.
79Use structural search to find patterns across the repository.
80Use `web_fetch`/`web_search` only when external documentation is needed to ground a design decision; repository evidence stays primary.
81When ready, emit exactly one final <proposed_plan> block for review.
82Never write the plan file with shell or file-editing tools; the runtime persists the plan and tracker artifacts.
83When the user asks for implementation, present the plan and wait for explicit user approval before implementation instead of suggesting an immediate edit."#;
84
85const BUILTIN_DUCK_PRIMARY_AGENT_ROLE: &str = r#"You are the duck agent.
86
87Do not edit files; you are for rubber-ducking only.
88If the user asks for edits, suggest pressing Tab to switch to the Build agent for implementation."#;
89/// Cached built-in subagent specifications.
90///
91/// Built once on first access and reused for every subsequent discovery call.
92/// The constructors below (`builtin_primary_build_agent`, etc.) each allocate
93/// a `SubagentSpec` with a `BTreeMap` of policy overrides and a cloned prompt
94/// string; reconstructing all of them on every `discover_subagents` call is the
95/// expensive part, so the result is memoized here. Callers still receive an
96/// owned `Vec` (cloned from this cache) so they can mutate freely without
97/// touching the shared canonical specs.
98static BUILTIN_SUBAGENTS: LazyLock<Vec<SubagentSpec>> = LazyLock::new(builtin_subagents_inner);
99
100pub fn builtin_subagents() -> Vec<SubagentSpec> {
101    BUILTIN_SUBAGENTS.clone()
102}
103
104fn builtin_subagents_inner() -> Vec<SubagentSpec> {
105    vec![
106        builtin_primary_build_agent(),
107        builtin_primary_auto_agent(),
108        builtin_primary_coordinator_agent(),
109        builtin_primary_duck_agent(),
110        builtin_plan_agent(),
111        SubagentSpec {
112            name: "default".to_string(),
113            description: "Default inheriting subagent for general delegated work.".to_string(),
114            prompt: BUILTIN_DEFAULT_AGENT.to_string(),
115            tools: None,
116            disallowed_tools: Vec::new(),
117            model: Some("inherit".to_string()),
118            color: Some("blue".to_string()),
119            reasoning_effort: None,
120            permissions: mutating_agent_permissions(),
121            skills: Vec::new(),
122            mcp_servers: Vec::new(),
123            hooks: None,
124            background: false,
125            mode: AgentMode::Subagent,
126            max_turns: None,
127            nickname_candidates: vec!["default".to_string()],
128            initial_prompt: None,
129            memory: None,
130            isolation: None,
131            aliases: Vec::new(),
132            source: SubagentSource::Builtin,
133            file_path: None,
134            warnings: Vec::new(),
135            tool_policy_overrides: BTreeMap::new(),
136        },
137        SubagentSpec {
138            name: "explorer".to_string(),
139            description: "Read-only exploration specialist. Use proactively for code search, file discovery, and repository understanding.".to_string(),
140            prompt: BUILTIN_EXPLORER_AGENT.to_string(),
141            tools: Some(builtin_readonly_tool_ids()),
142            disallowed_tools: builtin_readonly_disallowed_tool_ids(),
143            model: Some("small".to_string()),
144            color: Some("cyan".to_string()),
145            reasoning_effort: Some(ReasoningEffortLevel::Low),
146            permissions: readonly_agent_permissions(),
147            skills: Vec::new(),
148            mcp_servers: Vec::new(),
149            hooks: None,
150            background: false,
151            mode: AgentMode::Subagent,
152            max_turns: None,
153            nickname_candidates: vec!["explore".to_string(), "search".to_string()],
154            initial_prompt: None,
155            memory: None,
156            isolation: None,
157            aliases: vec!["explore".to_string()],
158            source: SubagentSource::Builtin,
159            file_path: None,
160            warnings: Vec::new(),
161            tool_policy_overrides: BTreeMap::new(),
162        },
163        SubagentSpec {
164            name: "worker".to_string(),
165            description: "Write-capable execution subagent for bounded implementation or multi-step action.".to_string(),
166            prompt: BUILTIN_WORKER_AGENT.to_string(),
167            tools: None,
168            disallowed_tools: Vec::new(),
169            model: Some("inherit".to_string()),
170            color: Some("magenta".to_string()),
171            reasoning_effort: None,
172            permissions: mutating_agent_permissions(),
173            skills: Vec::new(),
174            mcp_servers: Vec::new(),
175            hooks: None,
176            background: false,
177            mode: AgentMode::Subagent,
178            max_turns: None,
179            nickname_candidates: vec!["general".to_string(), "worker".to_string()],
180            initial_prompt: None,
181            memory: None,
182            isolation: None,
183            aliases: vec!["general".to_string(), "general-purpose".to_string()],
184            source: SubagentSource::Builtin,
185            file_path: None,
186            warnings: Vec::new(),
187            tool_policy_overrides: BTreeMap::new(),
188        },
189    ]
190}
191
192pub fn builtin_primary_build_agent() -> SubagentSpec {
193    SubagentSpec {
194        name: "build".to_string(),
195        description: "Implement changes using configured permissions.".to_string(),
196        prompt: BUILTIN_BUILD_PRIMARY_AGENT.to_string(),
197        tools: None,
198        disallowed_tools: Vec::new(),
199        model: Some("inherit".to_string()),
200        color: Some(ui::AGENT_COLOR_BUILD.to_string()),
201        reasoning_effort: None,
202        permissions: mutating_agent_permissions(),
203        skills: Vec::new(),
204        mcp_servers: Vec::new(),
205        hooks: None,
206        background: false,
207        mode: AgentMode::Primary,
208        max_turns: None,
209        nickname_candidates: vec!["build".to_string(), "builder".to_string()],
210        initial_prompt: None,
211        memory: None,
212        isolation: None,
213        aliases: vec!["builder".to_string()],
214        source: SubagentSource::Builtin,
215        file_path: None,
216        warnings: Vec::new(),
217        tool_policy_overrides: {
218            let mut m = BTreeMap::new();
219            m.insert(tools::EXEC_COMMAND.to_string(), ToolPolicy::Allow);
220            m
221        },
222    }
223}
224
225pub fn builtin_primary_auto_agent() -> SubagentSpec {
226    SubagentSpec {
227        name: "auto".to_string(),
228        description: "Implement and verify autonomously. Uses automatic agent permissions; sandbox and explicit denies still apply.".to_string(),
229        prompt: BUILTIN_AUTO_PRIMARY_AGENT.to_string(),
230        tools: None,
231        disallowed_tools: Vec::new(),
232        model: Some("inherit".to_string()),
233        color: Some(ui::AGENT_COLOR_AUTO.to_string()),
234        reasoning_effort: None,
235        permissions: auto_agent_permissions(),
236        skills: Vec::new(),
237        mcp_servers: Vec::new(),
238        hooks: None,
239        background: false,
240        mode: AgentMode::Primary,
241        max_turns: None,
242        nickname_candidates: vec!["auto".to_string()],
243        initial_prompt: None,
244        memory: None,
245        isolation: None,
246        aliases: vec!["autonomous".to_string()],
247        source: SubagentSource::Builtin,
248        file_path: None,
249        warnings: Vec::new(),
250        tool_policy_overrides: {
251            let mut m = BTreeMap::new();
252            m.insert(tools::EXEC_COMMAND.to_string(), ToolPolicy::Allow);
253            m
254        },
255    }
256}
257
258/// Opt-in orchestration role; worker permissions remain inherited from the session.
259pub fn builtin_primary_coordinator_agent() -> SubagentSpec {
260    let mut spec = builtin_primary_build_agent();
261    spec.name = "coordinator".to_string();
262    spec.description = "Deterministic local matrix orchestration for the main session.".to_string();
263    spec.prompt = BUILTIN_COORDINATOR_PRIMARY_AGENT.to_string();
264    spec.tools = Some(
265        [
266            "matrix",
267            tools::REQUEST_USER_INPUT,
268            "agent",
269            tools::RECORD_DECISION,
270            tools::TASK_TRACKER,
271        ]
272        .into_iter()
273        .map(str::to_string)
274        .collect(),
275    );
276    spec.nickname_candidates = vec!["coordinator".to_string()];
277    spec.aliases.clear();
278    spec.tool_policy_overrides.clear();
279    spec
280}
281
282pub fn builtin_plan_agent() -> SubagentSpec {
283    SubagentSpec {
284        name: "plan".to_string(),
285        description: "Explore code and propose a plan before implementation.".to_string(),
286        prompt: format!("{DISCUSSION_FIRST_GUIDANCE}\n\n{BUILTIN_PLAN_AGENT_ROLE}"),
287        tools: Some(builtin_plan_tool_ids()),
288        disallowed_tools: builtin_readonly_disallowed_tool_ids(),
289        model: Some("inherit".to_string()),
290        color: Some(ui::AGENT_COLOR_PLAN.to_string()),
291        reasoning_effort: None,
292        permissions: plan_agent_permissions(),
293        skills: Vec::new(),
294        mcp_servers: Vec::new(),
295        hooks: None,
296        background: false,
297        mode: AgentMode::Primary,
298        max_turns: None,
299        nickname_candidates: vec!["plan".to_string(), "planner".to_string()],
300        initial_prompt: None,
301        memory: None,
302        isolation: None,
303        aliases: vec!["planner".to_string()],
304        source: SubagentSource::Builtin,
305        file_path: None,
306        warnings: Vec::new(),
307        tool_policy_overrides: BTreeMap::new(),
308    }
309}
310
311pub fn builtin_primary_duck_agent() -> SubagentSpec {
312    SubagentSpec {
313        name: "duck".to_string(),
314        description: "Discuss questions and explore code without changing files.".to_string(),
315        prompt: format!("{DISCUSSION_FIRST_GUIDANCE}\n\n{BUILTIN_DUCK_PRIMARY_AGENT_ROLE}"),
316        tools: Some(builtin_primary_readonly_tool_ids()),
317        disallowed_tools: builtin_readonly_disallowed_tool_ids(),
318        model: Some("inherit".to_string()),
319        color: Some(ui::AGENT_COLOR_DUCK.to_string()),
320        reasoning_effort: None,
321        permissions: readonly_interview_agent_permissions(),
322        skills: Vec::new(),
323        mcp_servers: Vec::new(),
324        hooks: None,
325        background: false,
326        mode: AgentMode::Primary,
327        max_turns: None,
328        nickname_candidates: vec!["duck".to_string()],
329        initial_prompt: None,
330        memory: None,
331        isolation: None,
332        aliases: vec!["ask".to_string()],
333        source: SubagentSource::Builtin,
334        file_path: None,
335        warnings: Vec::new(),
336        tool_policy_overrides: BTreeMap::new(),
337    }
338}
339
340fn builtin_readonly_tool_ids() -> Vec<String> {
341    // Allowlist only: entries restrict the snapshot catalog and can never add
342    // tools to it. `code_search` is the live read path; `exec_command` survives
343    // here for surfaces that keep it (read-only agents deny `bash`, so the
344    // wire shaper hides it for them). `read_file`/`list_files` are registered
345    // but model-hidden, so they take effect only if a surface ever exposes
346    // them (turn_912/913: the planning profile admits the read surface; this
347    // list keeps agents from re-hiding it). `grep_file` has no registration
348    // and is intentionally absent (see the harness audit ledger).
349    vec![
350        tools::CODE_SEARCH.to_string(),
351        tools::EXEC_COMMAND.to_string(),
352        tools::READ_FILE.to_string(),
353        tools::LIST_FILES.to_string(),
354    ]
355}
356
357/// Readonly tools for primary agents that interact with the user directly.
358/// Extends the base readonly set with `request_user_input` so plan/duck can
359/// ask clarifying questions.
360fn builtin_primary_readonly_tool_ids() -> Vec<String> {
361    let mut ids = builtin_readonly_tool_ids();
362    ids.push(tools::REQUEST_USER_INPUT.to_string());
363    ids.push(tools::RECORD_DECISION.to_string());
364    ids
365}
366
367/// Plan-agent tool set: the primary readonly set plus external research.
368/// Planning a change often needs to ground a design in public docs, and
369/// `curl`/`wget` are hard-blocked by command safety, so the plan agent needs
370/// the dedicated web tools rather than a shell workaround. `search_tools`
371/// stays out: MCP tools can mutate and are not part of the read-only plan
372/// surface.
373fn builtin_plan_tool_ids() -> Vec<String> {
374    let mut ids = builtin_primary_readonly_tool_ids();
375    ids.push(tools::WEB_FETCH.to_string());
376    ids.push(tools::WEB_SEARCH.to_string());
377    ids
378}
379
380fn builtin_readonly_disallowed_tool_ids() -> Vec<String> {
381    Vec::new()
382}
383
384pub(super) fn mutating_agent_permissions() -> AgentPermissionsConfig {
385    AgentPermissionsConfig::new(PermissionDefault::Ask)
386}
387
388fn auto_agent_permissions() -> AgentPermissionsConfig {
389    AgentPermissionsConfig::new(PermissionDefault::Auto)
390}
391
392pub(super) fn readonly_agent_permissions() -> AgentPermissionsConfig {
393    let mut permissions = AgentPermissionsConfig::new(PermissionDefault::Deny);
394    permissions.allow = vec!["read".to_string()];
395    permissions
396}
397
398/// Read-only agents that talk to the user (duck, plan) also list
399/// `request_user_input` and `record_decision` in their tool set. Allow both
400/// explicitly: the default-deny fallback otherwise rejects their semantic
401/// kind "other" and hides them from the wire catalog.
402pub(super) fn readonly_interview_agent_permissions() -> AgentPermissionsConfig {
403    let mut permissions = readonly_agent_permissions();
404    permissions.allow.push("request_user_input".to_string());
405    permissions.allow.push(tools::RECORD_DECISION.to_string());
406    permissions
407}
408
409/// Plan-agent permissions extend the read-only interview set with `bash` so
410/// `exec_command` stays on the wire and read-only shell inspection (`rg`,
411/// `cat`, `wc`, ...) works while planning, plus the web research kinds so
412/// `web_fetch`/`web_search` survive primary-agent wire shaping. This stays
413/// read-only in practice:
414/// selecting the plan agent always activates the planning workflow, whose
415/// dispatch gate (`ToolRegistry::is_planning_active_allowed` +
416/// `assess_plan_mode_read_only_bash_command`) hard-blocks every mutating
417/// command before execution — the bash permission only admits the tool, the
418/// planning gate keeps it read-only. Explorer/duck stay bash-denied via
419/// [`readonly_agent_permissions`]/[`readonly_interview_agent_permissions`].
420fn plan_agent_permissions() -> AgentPermissionsConfig {
421    let mut permissions = readonly_interview_agent_permissions();
422    permissions.allow.push("bash".to_string());
423    // Web research is read-only, but its advertised permission kinds are
424    // `WebFetch` and `Other` (not `Read`), so the default-deny readonly
425    // fallback would otherwise hide both tools from the wire catalog.
426    permissions.allow.push("webfetch".to_string());
427    permissions.allow.push(tools::WEB_SEARCH.to_string());
428    // `primary_agent_allows_tool` force-admits the tracker, but permission
429    // shaping still hides it when its advertised `Other` request hits the
430    // default-deny fallback. Planning is documented to keep checklist state.
431    permissions.allow.push(tools::TASK_TRACKER.to_string());
432    permissions
433}