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