Skip to main content

vtcode_core/prompts/guidelines/
mod.rs

1use crate::config::constants::tools;
2use crate::config::types::{CapabilityLevel, ResolvedShellPromptProfile};
3use crate::core::agent::harness_kernel::SessionToolCatalogSnapshot;
4use crate::llm::provider::ToolDefinition;
5use crate::prompts::sections::{
6    SectionBoundaryMode, append_prompt_block, remove_prompt_section, trim_trailing_newlines,
7};
8use crate::tools::registry::tool_groups;
9
10const TOOL_EXEC_COMMAND: &str = tools::EXEC_COMMAND;
11const TOOL_WRITE_STDIN: &str = tools::WRITE_STDIN;
12const TOOL_CODE_SEARCH: &str = tools::CODE_SEARCH;
13const TOOL_READ_FILE: &str = tools::READ_FILE;
14const TOOL_LIST_FILES: &str = tools::LIST_FILES;
15const TOOL_GREP_FILE: &str = tools::GREP_FILE;
16const TOOL_APPLY_PATCH: &str = tools::APPLY_PATCH;
17const TOOL_REQUEST_USER_INPUT: &str = tools::REQUEST_USER_INPUT;
18const TOOL_ASK_SESSION: &str = tools::ASK_SESSION;
19const TOOL_TASK_TRACKER: &str = tools::TASK_TRACKER;
20const PUBLIC_DECISION_GUIDANCE: &str = "- Use optional `record_decision` for consequential choices, rejected approaches, or recovery changes. Give concise public rationale; ordinary reads and commands need no record.";
21const MATRIX_GUIDANCE: &str = "- `matrix`: create persists explicit tasks, checks, resources, and timeouts; start freezes the spec. The coordinator delegates execution and verification to scheduler-owned workers; discovery is idle-only. Replay restores admission before discovery; resume reconciles owned cleanup. status is a projection; pause stops dispatch; user cancel is terminal. Internal failures require reconciliation, not cancellation. Workers retain effective permissions and sandbox gates. Read leases require read-only workers. Report identity is runtime-owned; final success needs durable declared checks for the current generation, never summaries or child completion. Source and declared input changes, including submodule state, invalidate checks. Automatic retry requires replay_safe, confirmed cleanup, and at most one interrupted/timeout retry; other failures need a coordinator decision.";
22const SESSION_MESSAGING_GUIDANCE: &str = "- Peer sessions: `list_sessions` discovers live CLI sessions in this workspace; `ask_session` sends one a question and its `answer_session` reply arrives as a notice on a later turn. Delivery needs the peer running.";
23const WEB_SEARCH_GUIDANCE: &str = "- web_search uses keyless DuckDuckGo; web_fetch needs separate approval. For `antiban_blocked` or `retryable: false`, do not retry; wait `retry_after_ms` for `cooldown`; retry `network_error`/`upstream_error` once. For GitHub queries prefer `gh search`/`gh api` via exec_command when available.";
24
25const TOOL_START_PLANNING: &str = tools::START_PLANNING;
26
27const OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE: &str = "- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.";
28
29/// Shared cross-turn resume pointer (invariant #22). The hint body itself stays
30/// transient via `append_transient_turn_notes`; tool guidance only advertises
31/// that a turn-start `Exec session resume:` note carries the live ids so a
32/// resumed or compacted session needs zero identity reconstruction.
33const CROSS_TURN_RESUME_HINT_CLAUSE: &str =
34    "; a turn-start `Exec session resume:` hint carries the live ids when a prior turn ended mid-run.";
35
36/// The single home of `start_planning` guidance, shared by the Minimal and
37/// Default Active Tools. The tool itself asks the user before entering
38/// planning (`require_confirmation`), except under full-auto or
39/// skip-confirmations, so the model calls it rather than proposing it in prose.
40const START_PLANNING_GUIDANCE_LINE: &str = "- For demanding, ambiguous, or multi-phase tasks, call `start_planning`; it asks the user before entering the read-only Planning workflow unless the session runs in full-auto or skips confirmations. Skip it for straightforward changes.";
41
42/// Planning-workflow `task_tracker` index rules. While planning, the tracker
43/// routes to the plan sidecar, which rejects index 0 (`index_path components
44/// must be >= 1`); checklist-level `index: 0` completion exists only outside
45/// planning, so neither line advertises it.
46const PLANNING_TASK_TRACKER_COMPACT_LINE: &str = "- `task_tracker`: list {\"action\":\"list\"}; updates use positive index/index_path or items, never conflicting fields; index 0 is invalid while planning. Keep blockers and verification open. `scope_review` checks cannot satisfy functional `verify` checks.";
47const PLANNING_TASK_TRACKER_INDEX_LINE: &str = "- `task_tracker`: list {\"action\":\"list\"}; update {\"action\":\"update\",\"index\":1,\"status\":\"in_progress\"}; bulk {\"action\":\"update\",\"items\":[\"[x] Done\",\"[ ] Remaining\"]}. Use positive flat indices or hierarchical index_path (index 0 is invalid while planning), or items for full checklist replacement. Omit unused fields; never combine index, index_path, and items. `scope_review` checks cannot satisfy functional `verify` checks.";
48
49/// Context-token ceiling at or below which Active Tools documentation
50/// resolves to the Minimal density.
51const MINIMAL_CONTEXT_TOKEN_CEILING: usize = 32_000;
52
53/// The single home of the parallel-call hint, shared by the Minimal and
54/// Default Active Tools; emitted only when the provider keeps parallel tool
55/// configuration enabled.
56const PARALLEL_TOOLS_LINE: &str = "- Run independent tools in parallel when inputs do not depend on each other.";
57
58/// The single home of the `code_search` filter hygiene rule, shared by the
59/// Minimal, Default, and planning Active Tools variants.
60const CODE_SEARCH_FILTER_LINE: &str = "- `code_search`: omit unused filters; no empty values (`path: \"\"`).";
61
62/// The single home of the `request_user_input` threshold rule, shared by the
63/// Minimal planning addendum and the planning Active Tools.
64const REQUEST_USER_INPUT_LINE: &str =
65    "- Use `request_user_input` only for material blockers remaining after repository exploration.";
66
67/// Read-only capability line shared by the capability-level and
68/// tool-fallback arms of `capability_mode_line`.
69const CAPABILITY_READ_ONLY_LINE: &str =
70    "- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.";
71
72/// Shared `write_stdin` recovery clause; each profile adds its own
73/// rerun/wait policy around it.
74const WRITE_STDIN_RECOVERY_CLAUSE: &str = "; if missing, recover prior output";
75
76/// Policy lines shared by both shell profiles: the profile governs syntax
77/// examples only, and VT Code never translates flags across shells.
78const SHELL_PROFILE_POLICY_SUFFIX: &str = "- The shell profile controls prompt examples and expected command syntax only; command policy, sandboxing, and approvals remain separate runtime checks.\n- VT Code does not translate GNU-to-BSD, BSD-to-GNU, Unix-to-PowerShell, or PowerShell-to-Unix command flags.";
79
80/// Documentation density is independent of the tools a session may execute.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub(crate) enum ToolGuidanceProfile {
83    Minimal,
84    Default,
85}
86
87impl ToolGuidanceProfile {
88    #[must_use]
89    pub(crate) fn resolve(
90        context_tokens: usize,
91        default_prompt_tokens: usize,
92        max_prompt_tokens: usize,
93        input_usd_per_token: Option<f64>,
94        max_budget_usd: Option<f64>,
95    ) -> Self {
96        let exceeds_cost = input_usd_per_token.zip(max_budget_usd).is_some_and(|(price, budget)| {
97            price.is_finite() && price >= 0.0 && budget.is_finite() && default_prompt_tokens as f64 * price > budget
98        });
99        if (context_tokens > 0 && context_tokens <= MINIMAL_CONTEXT_TOKEN_CEILING)
100            || (max_prompt_tokens > 0 && default_prompt_tokens > max_prompt_tokens)
101            || exceeds_cost
102        {
103            Self::Minimal
104        } else {
105            Self::Default
106        }
107    }
108}
109
110/// Which guidance-gating tools a session exposes, computed once per build so
111/// every Active Tools variant branches on the same membership policy.
112struct ToolPresence {
113    exec: bool,
114    write_stdin: bool,
115    code_search: bool,
116    web_search: bool,
117    read_file: bool,
118    grep_file: bool,
119    list_files: bool,
120    apply_patch: bool,
121    request_user_input: bool,
122    task_tracker: bool,
123    start_planning: bool,
124    matrix: bool,
125    record_decision: bool,
126    session_messaging: bool,
127}
128
129impl ToolPresence {
130    fn of(available_tools: &[String]) -> Self {
131        // Single pass over the tool list: the old form ran one linear
132        // `any()` scan per flag (10 scans per call, up to 4 calls per
133        // model-aware prompt build). Same membership policy, one walk.
134        let mut presence = Self {
135            exec: false,
136            write_stdin: false,
137            code_search: false,
138            web_search: false,
139            read_file: false,
140            grep_file: false,
141            list_files: false,
142            apply_patch: false,
143            request_user_input: false,
144            task_tracker: false,
145            start_planning: false,
146            matrix: false,
147            record_decision: false,
148            session_messaging: false,
149        };
150        for tool in available_tools {
151            match tool.as_str() {
152                TOOL_EXEC_COMMAND => presence.exec = true,
153                TOOL_WRITE_STDIN => presence.write_stdin = true,
154                TOOL_CODE_SEARCH => presence.code_search = true,
155                "web_search" => presence.web_search = true,
156                TOOL_READ_FILE => presence.read_file = true,
157                TOOL_GREP_FILE => presence.grep_file = true,
158                TOOL_LIST_FILES => presence.list_files = true,
159                TOOL_APPLY_PATCH => presence.apply_patch = true,
160                TOOL_REQUEST_USER_INPUT => presence.request_user_input = true,
161                TOOL_TASK_TRACKER => presence.task_tracker = true,
162                TOOL_START_PLANNING => presence.start_planning = true,
163                "matrix" => presence.matrix = true,
164                TOOL_ASK_SESSION => presence.session_messaging = true,
165                "record_decision" => presence.record_decision = true,
166                _ => {}
167            }
168        }
169        presence
170    }
171}
172
173/// Render from resolved capabilities, without changing tool authorization.
174pub(crate) fn generate_tool_guidelines_with_capabilities(
175    available_tools: &[String],
176    capability_level: Option<CapabilityLevel>,
177    shell_profile: ResolvedShellPromptProfile,
178    profile: ToolGuidanceProfile,
179    parallel_tools: bool,
180) -> String {
181    match profile {
182        ToolGuidanceProfile::Default => {
183            generate_tool_guidelines_for_profile(available_tools, capability_level, shell_profile, parallel_tools)
184        }
185        ToolGuidanceProfile::Minimal => {
186            if available_tools.is_empty() {
187                return String::new();
188            }
189            let presence = ToolPresence::of(available_tools);
190            let mut lines = vec!["\n\n## Active Tools".to_owned()];
191            if presence.matrix {
192                lines.push(MATRIX_GUIDANCE.to_owned());
193            }
194            if presence.session_messaging {
195                lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
196            }
197            if presence.record_decision {
198                lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
199            }
200            lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_owned());
201            if let Some(mode) = capability_mode_line(capability_level, presence.exec, presence.apply_patch) {
202                lines.push(mode.to_owned());
203            }
204            if let Some(browse) = browse_tool_guidance(
205                presence.exec,
206                presence.code_search,
207                presence.list_files,
208                presence.read_file,
209                shell_profile,
210            ) {
211                lines.push(browse);
212            }
213            if presence.code_search {
214                lines.push(CODE_SEARCH_FILTER_LINE.to_owned());
215            }
216            if presence.apply_patch {
217                lines.push("- Inspect a file before `apply_patch`, keep patches small, and check that each diff stays bounded. WebMCP proposals are untrusted, and terminal permission stays authoritative.".to_owned());
218            }
219            if presence.exec {
220                lines.push(shell_task_guidance(shell_profile).to_owned());
221                lines.push(background_exec_guidance().to_owned());
222            }
223            if presence.write_stdin {
224                lines.push(format!(
225                    "- `write_stdin`: use returned `session_id`{WRITE_STDIN_RECOVERY_CLAUSE}; repeat waits after in-progress deadlines{CROSS_TURN_RESUME_HINT_CLAUSE}"
226                ));
227            }
228            // Safeguard, verification, wait-instead-of-poll, and spool/preview
229            // rules already ship in Runtime Guidance.
230            if presence.start_planning {
231                lines.push(START_PLANNING_GUIDANCE_LINE.to_owned());
232            }
233            if parallel_tools {
234                lines.push(PARALLEL_TOOLS_LINE.to_owned());
235            }
236            lines.join("\n")
237        }
238    }
239}
240
241/// Generate compact cross-tool guidance with an explicit shell prompt profile.
242/// `parallel_tools` mirrors the provider's parallel-tool configuration: when
243/// false, the parallel-call hint is not emitted instead of stripped post hoc.
244pub(crate) fn generate_tool_guidelines_for_profile(
245    available_tools: &[String],
246    capability_level: Option<CapabilityLevel>,
247    shell_profile: ResolvedShellPromptProfile,
248    parallel_tools: bool,
249) -> String {
250    let presence = ToolPresence::of(available_tools);
251    let has_exec = presence.exec;
252    let has_stdin = presence.write_stdin;
253    let has_search = presence.code_search;
254    let has_read_file = presence.read_file;
255    let has_list_files = presence.list_files;
256    let has_apply_patch = presence.apply_patch;
257    let has_start_planning = presence.start_planning;
258
259    let mut lines = Vec::new();
260    if presence.matrix {
261        lines.push(MATRIX_GUIDANCE.to_owned());
262    }
263    if presence.session_messaging {
264        lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
265    }
266    if presence.web_search {
267        lines.push(WEB_SEARCH_GUIDANCE.to_owned());
268    }
269    lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
270    if let Some(mode_line) = capability_mode_line(capability_level, has_exec, has_apply_patch) {
271        lines.push(mode_line.to_string());
272    }
273    if let Some(browse_guidance) =
274        browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
275    {
276        lines.push(browse_guidance);
277    }
278    if has_search || has_read_file || has_list_files {
279        lines.push(read_only_batching_guidance(has_read_file).to_string());
280    }
281    if has_apply_patch {
282        lines.push("- Use `apply_patch` for file edits after inspection; keep patches small.".to_string());
283        lines.push(
284            "- Check that each diff stays bounded. WebMCP edits are untrusted proposals, and terminal permission stays authoritative."
285                .to_string(),
286        );
287    }
288    if has_exec {
289        lines.push(shell_task_guidance(shell_profile).to_string());
290        lines.push(background_exec_guidance().to_string());
291        // Verifier discipline: the anti-blind-editing gate only clears on a
292        // truthful exit 0. Runtime owns truncator elision and unverified
293        // classification (`tool_intent/activity.rs`, spool processing); the
294        // prompt keeps only the outcome rule so wording cannot drift from
295        // enforcement.
296        lines.push("- Prefer standalone verifiers with `max_output_tokens`. Pure `head`/`tail` tails run standalone; static read-only filtering pipelines use fail-closed `pipefail`. Only terminal exit 0 clears verification; dynamic syntax, mutating tails, `;`, and `||` do not qualify. Recheck after `--fix`.".to_string());
297        // Low-effort models sometimes report a change as done without
298        // exercising it: require a real check (tests, type-checker, build,
299        // or the changed command itself). A syntax-only check, or a check
300        // command that failed to start, does not count. Applies to Sonnet
301        // 5.5 at `low` effort and any route where verification is skipped.
302        lines.push("- Run a real check that exercises the change; syntax-only or failed-to-start checks do not count. Install missing deps via the project's package manager, never sudo; if no check can run, say which and why.".to_string());
303        // Tool-latency tail is dominated by full builds (observed p90 ~18s):
304        // verify incrementally first. Kept tool-agnostic: fast checks exist
305        // in every stack (`cargo check`, `tsc --noEmit`, `pytest --collect-only`).
306        lines.push("- Run fast checks before full builds.".to_string());
307    }
308    // Tool-failure diagnosis, waiting on returned `next_wait_args` instead of
309    // polling, the safeguard rule, the verification outcome rule (report
310    // completion only after a check you ran), and spool paging with
311    // per-result preview bounds each have one home in Runtime
312    // Guidance, which every profile includes; do not restate them here.
313    if has_stdin {
314        lines.push(format!(
315            "- `write_stdin`: use the existing `session_id`{WRITE_STDIN_RECOVERY_CLAUSE}; rerun only for fresh results. `spool_complete: false` is partial; wait for exited pending spools{CROSS_TURN_RESUME_HINT_CLAUSE}"
316        ));
317    }
318    if has_search {
319        lines.push(CODE_SEARCH_FILTER_LINE.to_string());
320        lines.push(code_search_guidance(has_exec));
321    }
322    if has_apply_patch || has_exec {
323        lines.push(
324            "- Build and Auto share tools and safety gates; Auto changes confirmation behavior only after explicit approval or full-auto policy."
325                .to_string(),
326        );
327    }
328    if (has_search || has_exec) && parallel_tools {
329        lines.push(PARALLEL_TOOLS_LINE.to_string());
330    }
331    if has_start_planning {
332        lines.push(START_PLANNING_GUIDANCE_LINE.to_string());
333    }
334
335    if lines.is_empty() {
336        return String::new();
337    }
338
339    if presence.record_decision {
340        lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
341    }
342    format!("\n\n## Active Tools\n{}", lines.join("\n"))
343}
344
345pub fn append_runtime_tool_prompt_sections_for_profile(
346    prompt: &mut String,
347    tool_snapshot: &SessionToolCatalogSnapshot,
348    include_catalog_metadata: bool,
349    shell_profile: ResolvedShellPromptProfile,
350) {
351    let names = snapshot_tool_names(tool_snapshot);
352    append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile);
353}
354
355/// Select documentation density using the active route and session budgets.
356pub fn append_runtime_tool_prompt_sections_for_model(
357    prompt: &mut String,
358    tool_snapshot: &SessionToolCatalogSnapshot,
359    include_catalog_metadata: bool,
360    shell_profile: ResolvedShellPromptProfile,
361    provider: &dyn crate::llm::provider::LLMProvider,
362    model: &str,
363    config: Option<&crate::config::VTCodeConfig>,
364) {
365    let names = snapshot_tool_names(tool_snapshot);
366    let default_guidance =
367        append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile);
368    let pricing = crate::config::models::model_catalog_entry(provider.name(), model).map(|entry| entry.pricing);
369    let profile = ToolGuidanceProfile::resolve(
370        crate::compaction::effective_context_budget(config, provider, model),
371        vtcode_commons::estimate_tokens(prompt),
372        config.map_or(0, |cfg| cfg.agent.max_system_prompt_tokens as usize),
373        pricing.and_then(|price| price.input),
374        config.and_then(|cfg| cfg.agent.harness.max_budget_usd),
375    );
376    let parallel_tools = provider.supports_parallel_tool_config(model);
377    // The planning mode section owns the output contract at every density.
378    // Default planning tool guidance contains no parallel-call hint.
379    if tool_snapshot.planning_active && profile == ToolGuidanceProfile::Default {
380        return;
381    }
382    remove_prompt_section(prompt, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
383    let presence = ToolPresence::of(names);
384    let capability_level = Some(infer_capability_level_from_presence(&presence));
385    let mut guidance = match profile {
386        ToolGuidanceProfile::Default => {
387            let mut guidance = default_guidance;
388            if let (Some(original), Some(effective)) = (
389                capability_mode_line(None, presence.exec, presence.apply_patch),
390                capability_mode_line(capability_level, presence.exec, presence.apply_patch),
391            ) && original != effective
392                && let Some(start) = guidance.find(original)
393            {
394                guidance.replace_range(start..start + original.len(), effective);
395            }
396            if !parallel_tools && let Some(start) = guidance.find(PARALLEL_TOOLS_LINE) {
397                guidance.replace_range(start.saturating_sub(1)..start + PARALLEL_TOOLS_LINE.len(), "");
398            }
399            guidance
400        }
401        ToolGuidanceProfile::Minimal => {
402            generate_tool_guidelines_with_capabilities(names, capability_level, shell_profile, profile, parallel_tools)
403        }
404    };
405    if tool_snapshot.planning_active {
406        append_minimal_planning_addendum(&mut guidance, &presence);
407    }
408    append_prompt_block(prompt, guidance.trim_start_matches('\n'));
409}
410
411/// Replace the runtime tool sections with guidance built from `names`, plus
412/// optional catalog metadata. Return the Default guidance so model-aware
413/// callers can reuse it after measuring the assembled prompt.
414fn append_runtime_tool_sections_with_names(
415    prompt: &mut String,
416    tool_snapshot: &SessionToolCatalogSnapshot,
417    names: &[String],
418    include_catalog_metadata: bool,
419    shell_profile: ResolvedShellPromptProfile,
420) -> String {
421    remove_prompt_section(prompt, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
422    remove_prompt_section(prompt, "[Runtime Tool Catalog]", SectionBoundaryMode::BracketOrMarkdown);
423    trim_trailing_newlines(prompt);
424
425    let guidelines = generate_runtime_tool_guidelines_for_profile(names, tool_snapshot.planning_active, shell_profile);
426    if !guidelines.is_empty() {
427        append_prompt_block(prompt, guidelines.trim_start_matches('\n'));
428    }
429
430    if include_catalog_metadata && tool_snapshot.snapshot.is_some() {
431        let active_tools = if tool_snapshot.active_tool_names.is_empty() {
432            "none".to_string()
433        } else {
434            tool_snapshot.active_tool_names.join(", ")
435        };
436        let catalog_metadata = format!(
437            "[Runtime Tool Catalog]\n- version: {}\n- epoch: {}\n- catalog_tools: {}\n- available_tools: {}\n- currently_available_tools: {}\n- request_user_input_enabled: {}",
438            tool_snapshot.version,
439            tool_snapshot.epoch,
440            tool_snapshot.catalog_tools(),
441            tool_snapshot.available_tools(),
442            active_tools,
443            tool_snapshot.request_user_input_enabled,
444        );
445        append_prompt_block(prompt, &catalog_metadata);
446    }
447    guidelines
448}
449
450/// Compact tool reminders; the planning mode section retains the canonical
451/// research, step-quality, output, and persistence contract at every density.
452fn append_minimal_planning_addendum(guidance: &mut String, presence: &ToolPresence) {
453    guidance.push_str("\n- Planning is read-only.");
454    let mut read_tools = Vec::with_capacity(4);
455    if presence.read_file {
456        read_tools.push(TOOL_READ_FILE);
457    }
458    if presence.grep_file {
459        read_tools.push(TOOL_GREP_FILE);
460    }
461    if presence.code_search {
462        read_tools.push(TOOL_CODE_SEARCH);
463    }
464    if presence.list_files {
465        read_tools.push(TOOL_LIST_FILES);
466    }
467    guidance.push_str("\n- Keep inspections small: ");
468    if !read_tools.is_empty() {
469        guidance.push_str(&format!("prefer `{}` over `exec_command` shell reads; ", read_tools.join("`/`")));
470    }
471    guidance.push_str("keep `max_output_tokens` small, avoid batching multiple large inspections in parallel; start git history with `git log --oneline` before targeted `git show --stat`.");
472    if presence.task_tracker {
473        guidance.push('\n');
474        guidance.push_str(PLANNING_TASK_TRACKER_COMPACT_LINE);
475    }
476    if presence.request_user_input {
477        guidance.push('\n');
478        guidance.push_str(REQUEST_USER_INPUT_LINE);
479    }
480}
481
482/// Append a compact summary of tools omitted from a client-local wire payload.
483///
484/// The listing is bounded like the `## Skills` routing section: at most
485/// `DEFERRED_TOOLS_MAX_GROUPS` groups are named and the rest collapse into one
486/// overflow line, so MCP-heavy sessions cannot bloat every request. Group
487/// descriptions are server-provided and unbounded, so each line is truncated
488/// to `DEFERRED_TOOLS_MAX_DESC_CHARS` characters.
489pub fn append_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
490    remove_prompt_section(prompt, "[Deferred Tools]", SectionBoundaryMode::BracketOrMarkdown);
491
492    let mut groups: Vec<_> = tool_groups(tools)
493        .into_iter()
494        .filter(|group| group.deferred_count > 0)
495        .collect();
496    let overflow = groups.len().saturating_sub(DEFERRED_TOOLS_MAX_GROUPS);
497    groups.truncate(DEFERRED_TOOLS_MAX_GROUPS);
498
499    let mut lines: Vec<String> = groups
500        .into_iter()
501        .map(|group| {
502            let description = truncate_deferred_description(group.description.as_deref().unwrap_or_default());
503            format!("- {} ({} tools): {}", group.name, group.deferred_count, description)
504        })
505        .collect();
506    if overflow > 0 {
507        lines.push(format!("(+{overflow} more deferred groups available — use `search_tools` to find them)"));
508    }
509
510    let unnamespaced_deferred = tools
511        .iter()
512        .filter(|tool| tool.namespace.is_none() && tool.defer_loading == Some(true))
513        .count();
514    if unnamespaced_deferred > 0 {
515        lines.push(format!("- {unnamespaced_deferred} additional deferred tools"));
516    }
517
518    if lines.is_empty() {
519        return;
520    }
521
522    let section = format!(
523        "[Deferred Tools]\n{}\nUse `search_tools` to find a deferred capability. Selected definitions become available in the next request segment.",
524        lines.join("\n")
525    );
526    append_prompt_block(prompt, &section);
527}
528
529/// Maximum deferred-tool groups named in the `[Deferred Tools]` prompt
530/// section before the rest collapse into one overflow line.
531const DEFERRED_TOOLS_MAX_GROUPS: usize = 8;
532/// Maximum characters of a group description in the section. Mirrors the
533/// `## Skills` line truncation: server-provided text must not bloat the prompt.
534const DEFERRED_TOOLS_MAX_DESC_CHARS: usize = 120;
535
536fn truncate_deferred_description(description: &str) -> String {
537    // Single pass: visit at most `MAX + 1` chars. The old form ran
538    // `chars().count()` over the whole string, then `chars().take()` again.
539    let mut chars = description.chars();
540    let truncated: String = chars.by_ref().take(DEFERRED_TOOLS_MAX_DESC_CHARS).collect();
541    if chars.next().is_none() {
542        return description.to_string();
543    }
544    format!("{}...", truncated.trim_end())
545}
546
547fn generate_runtime_tool_guidelines_for_profile(
548    available_tools: &[String],
549    planning_active: bool,
550    shell_profile: ResolvedShellPromptProfile,
551) -> String {
552    if !planning_active {
553        // Measurement parity: this Default-density build feeds the prompt size
554        // that `ToolGuidanceProfile::resolve` reads, so it keeps shipping the
555        // parallel-call hint unconditionally like the static composition path.
556        return generate_tool_guidelines_for_profile(available_tools, None, shell_profile, true);
557    }
558
559    let presence = ToolPresence::of(available_tools);
560    let has_exec = presence.exec;
561    let has_search = presence.code_search;
562    let has_read_file = presence.read_file;
563    let has_list_files = presence.list_files;
564    let has_request_user_input = presence.request_user_input;
565    let has_task_tracker = presence.task_tracker;
566
567    let mut lines = vec!["- Planning workflow active: stay within the read-safe tool list.".to_string()];
568    if presence.web_search {
569        lines.push(WEB_SEARCH_GUIDANCE.to_owned());
570    }
571    lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
572    if let Some(browse_guidance) =
573        browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
574    {
575        lines.push(browse_guidance);
576    }
577    if has_exec {
578        lines.push("- In Planning workflow, use `exec_command` only for read-only verification.".to_string());
579    }
580    if has_search {
581        lines.push(CODE_SEARCH_FILTER_LINE.to_string());
582    }
583    if has_task_tracker {
584        lines.push("- Keep `task_tracker` updated as you refine the plan. Indexed updates return totals and the changed item; use action=list for the full checklist.".to_string());
585        lines.push("- Keep blockers and verification open in `task_tracker` until resolved.".to_string());
586        lines.push(PLANNING_TASK_TRACKER_INDEX_LINE.to_string());
587    }
588    if has_request_user_input {
589        lines.push(REQUEST_USER_INPUT_LINE.to_string());
590    }
591    if has_search || has_exec {
592        lines.push("- If calls repeat without progress, tighten the plan instead of retrying identically.".to_string());
593    }
594    if presence.record_decision {
595        lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
596    }
597
598    format!("\n\n## Active Tools\n{}", lines.join("\n"))
599}
600
601fn snapshot_tool_names(tool_snapshot: &SessionToolCatalogSnapshot) -> &[String] {
602    &tool_snapshot.active_tool_names
603}
604
605fn browse_tool_guidance(
606    has_exec: bool,
607    has_search: bool,
608    has_list_files: bool,
609    has_read_file: bool,
610    shell_profile: ResolvedShellPromptProfile,
611) -> Option<String> {
612    if has_exec {
613        return Some(shell_browse_guidance(shell_profile, has_search));
614    }
615
616    if !(has_search || has_list_files || has_read_file) {
617        return None;
618    }
619
620    Some("- Use available read-only repository tools for browsing; do not modify files.".to_string())
621}
622
623pub(crate) fn render_shell_profile_guidance(shell_profile: ResolvedShellPromptProfile) -> String {
624    let profile_lines = match shell_profile {
625        ResolvedShellPromptProfile::UnixLike => {
626            "- Active shell profile: `unix_like`. Use Unix-like command syntax in `exec_command.cmd`, for example `ls`, `rg`, `find`, `cat`, `sed`, and `awk`.\n- On macOS, write BSD-compatible flags for BSD tools. VT Code does not rewrite GNU flags for macOS BSD tools."
627        }
628        ResolvedShellPromptProfile::PowerShell => {
629            "- Active shell profile: `powershell`. Use native PowerShell syntax in `exec_command.cmd`, for example `Get-ChildItem`, `Select-String`, `Get-Content`, and `Where-Object`.\n- On native Windows, use WSL when you need Unix-like workflows or Unix command examples."
630        }
631    };
632    format!("## Shell Profile\n{profile_lines}\n{SHELL_PROFILE_POLICY_SUFFIX}")
633}
634
635fn shell_browse_guidance(shell_profile: ResolvedShellPromptProfile, has_search: bool) -> String {
636    // Sessions show `exec_command` + `rg` crowding out `code_search`
637    // (observed 654 exec vs 15 code_search in one run): `rg` scans text
638    // while `code_search` resolves definitions and exact usages, so route
639    // code search to the dedicated tool whenever it is available.
640    const SEARCH_PREFERENCE_UNIX: &str = " Prefer `code_search` over `rg`/`grep` for code.";
641    const SEARCH_PREFERENCE_POWERSHELL: &str = " Prefer `code_search` over `Select-String` for code.";
642    match shell_profile {
643        ResolvedShellPromptProfile::UnixLike => {
644            let mut line = String::from("- Use `exec_command.cmd` with `ls`, ");
645            if !has_search {
646                line.push_str("`rg`, ");
647            }
648            line.push_str("`find`, `cat`, `sed`, and `awk` for repository browsing.");
649            if has_search {
650                line.push_str(SEARCH_PREFERENCE_UNIX);
651            }
652            line
653        }
654        ResolvedShellPromptProfile::PowerShell => {
655            let mut line = "- Use `exec_command.cmd` with native PowerShell commands such as `Get-ChildItem`, `Select-String`, `Get-Content`, and `Where-Object` for repository browsing.".to_string();
656            if has_search {
657                line.push_str(SEARCH_PREFERENCE_POWERSHELL);
658            }
659            line
660        }
661    }
662}
663
664fn shell_task_guidance(shell_profile: ResolvedShellPromptProfile) -> &'static str {
665    match shell_profile {
666        ResolvedShellPromptProfile::UnixLike => {
667            "- Use `exec_command.cmd` for build tools, test tools, `git diff -- <path>`, and shell-only tasks. In one-shot `exec_command` calls, do not use `!!`, `!$`, `!ssh`, or `fc`; write full command arguments explicitly from conversation or tool results. Interactive shells: review-safe history expansion (Bash `histverify`, zsh `HIST_VERIFY`)."
668        }
669        ResolvedShellPromptProfile::PowerShell => {
670            "- Use `exec_command.cmd` for build tools, test tools, `git diff -- <path>`, and shell-only tasks using native PowerShell syntax."
671        }
672    }
673}
674
675fn background_exec_guidance() -> &'static str {
676    "- For long-lived commands, set `background: true` on `exec_command`; it returns a bounded preview plus a stable `session_id` and wait arguments. At most three live background processes are retained per runtime, with no automatic eviction; `write_stdin` drives the session lifecycle. For pipe runs, `monitor_filter` collects matches into a bounded `monitor_digest`; quiet commands skip full-output polls."
677}
678
679fn read_only_batching_guidance(has_read_file: bool) -> &'static str {
680    if has_read_file {
681        "- Batch independent read-only calls; use bounded `read_file` ranges, order dependencies, serialize mutations; narrow the range on `line_truncated`; prefer wider windows and reuse evidence over overlapping slices."
682    } else {
683        "- Batch independent read-only calls; order dependent reads, and serialize mutations."
684    }
685}
686
687fn code_search_guidance(has_exec: bool) -> String {
688    const BASE: &str = "- Advanced `code_search` takes `query`; filters `path`, `file_types`, `result_types`, `max_results`; results: definitions, exact syntactic usages. Queries use literal smart-case and `|`-separated literals; truncated: narrow; unavailable: do not retry identical, drop `file_types`/broaden `path`. Example: `{\"query\":\"TurnLoop\",\"path\":\"src\",\"result_types\":[\"definition\"]}`. Do not JSON-encode arrays or integers as strings. Prefer `code_search` over `rg` on `.vtcode/context/tool_outputs/`.";
689    if has_exec {
690        format!("{BASE} Use `exec_command` or a skill for syntax patterns.")
691    } else {
692        BASE.to_string()
693    }
694}
695
696fn capability_mode_line(
697    capability_level: Option<CapabilityLevel>,
698    has_exec: bool,
699    has_file: bool,
700) -> Option<&'static str> {
701    match capability_level {
702        Some(CapabilityLevel::Basic) => {
703            Some("- Capabilities: limited. Ask the user to enable more capabilities if file work is required.")
704        }
705        Some(CapabilityLevel::FileReading | CapabilityLevel::FileListing) => Some(CAPABILITY_READ_ONLY_LINE),
706        _ if !has_exec && !has_file => Some(CAPABILITY_READ_ONLY_LINE),
707        _ => None,
708    }
709}
710
711/// Infer capability level from available tools.
712pub(crate) fn infer_capability_level(available_tools: &[String]) -> CapabilityLevel {
713    infer_capability_level_from_presence(&ToolPresence::of(available_tools))
714}
715
716fn infer_capability_level_from_presence(presence: &ToolPresence) -> CapabilityLevel {
717    if presence.code_search {
718        CapabilityLevel::CodeSearch
719    } else if presence.apply_patch {
720        CapabilityLevel::Editing
721    } else if presence.exec {
722        CapabilityLevel::Bash
723    } else if presence.list_files {
724        CapabilityLevel::FileListing
725    } else if presence.read_file {
726        CapabilityLevel::FileReading
727    } else {
728        CapabilityLevel::Basic
729    }
730}
731
732#[cfg(test)]
733mod tests;