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, remove_prompt_section_after,
7    trim_trailing_newlines,
8};
9use crate::tools::registry::tool_groups;
10
11const TOOL_EXEC_COMMAND: &str = tools::EXEC_COMMAND;
12const TOOL_WRITE_STDIN: &str = tools::WRITE_STDIN;
13const TOOL_CODE_SEARCH: &str = tools::CODE_SEARCH;
14const TOOL_READ_FILE: &str = tools::READ_FILE;
15const TOOL_LIST_FILES: &str = tools::LIST_FILES;
16const TOOL_GREP_FILE: &str = tools::GREP_FILE;
17const TOOL_APPLY_PATCH: &str = tools::APPLY_PATCH;
18const TOOL_REQUEST_USER_INPUT: &str = tools::REQUEST_USER_INPUT;
19const TOOL_ASK_SESSION: &str = tools::ASK_SESSION;
20const TOOL_TASK_TRACKER: &str = tools::TASK_TRACKER;
21const TOOL_COMPUTER_USE: &str = tools::COMPUTER_USE;
22const 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.";
23const 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.";
24const 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.";
25const 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.";
26const COMPUTER_USE_GUIDANCE: &str = "- `computer_use`: when the user asks to see, screenshot, or operate the isolated browser preview, call it with one screen-sized browser task instead of exploring code or shelling around; each turn asks approval before acting and reports only a redacted summary. Never for local files, shells, or secrets entry. For external pages, local servers, or desktop apps instead, use the shell (headless browser for pages; native tools for desktop): v1 is preview-only, with no network access.";
27
28const TOOL_START_PLANNING: &str = tools::START_PLANNING;
29
30const OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE: &str = "- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.";
31
32/// The single home of `start_planning` guidance, shared by the Minimal and
33/// Default Active Tools. The tool itself asks the user before entering
34/// planning (`require_confirmation`), except under full-auto or
35/// skip-confirmations, so the model calls it rather than proposing it in prose.
36const 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.";
37
38/// Planning-workflow `task_tracker` rules that the tracker schema cannot
39/// carry.
40///
41/// The call shapes (list/update/bulk, index vs. index_path vs. items), the
42/// planning index rule, and "update as work progresses" all live in the tool
43/// description and parameter schema, which reach the model with the tool
44/// definitions. Only the tracker-to-verification relation is left, and it
45/// applies equally at every density, so one constant serves both the Minimal
46/// planning addendum and the Default planning Active Tools.
47const PLANNING_TASK_TRACKER_LINE: &str = "- `task_tracker`: keep blockers and verification open. `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 `request_user_input` threshold rule, shared by the
59/// Minimal planning addendum and the planning Active Tools.
60/// The `request_user_input` threshold for the planning workflow.
61///
62/// Planning mode already states this threshold in
63/// `PLANNING_WORKFLOW_INTERVIEW_POLICY_LINE` ("only for a critical blocker
64/// where proceeding could cause materially different, unsafe, or irreversible
65/// work"), which the planning notice always renders. This line therefore
66/// carries only the part the notice does not: that the blocker must survive
67/// repository exploration.
68const REQUEST_USER_INPUT_LINE: &str = "- Use `request_user_input` only for a blocker that repository exploration did not resolve. Set `multi_select: true` for independent checkbox answers; omit it for one radio-button answer.";
69
70/// Read-only capability line shared by the capability-level and
71/// tool-fallback arms of `capability_mode_line`.
72const CAPABILITY_READ_ONLY_LINE: &str =
73    "- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.";
74
75/// Policy line 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. 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    computer_use: 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            computer_use: false,
150        };
151        for tool in available_tools {
152            match tool.as_str() {
153                TOOL_EXEC_COMMAND => presence.exec = true,
154                TOOL_WRITE_STDIN => presence.write_stdin = true,
155                TOOL_CODE_SEARCH => presence.code_search = true,
156                "web_search" => presence.web_search = true,
157                TOOL_READ_FILE => presence.read_file = true,
158                TOOL_GREP_FILE => presence.grep_file = true,
159                TOOL_LIST_FILES => presence.list_files = true,
160                TOOL_APPLY_PATCH => presence.apply_patch = true,
161                TOOL_REQUEST_USER_INPUT => presence.request_user_input = true,
162                TOOL_TASK_TRACKER => presence.task_tracker = true,
163                TOOL_START_PLANNING => presence.start_planning = true,
164                "matrix" => presence.matrix = true,
165                TOOL_ASK_SESSION => presence.session_messaging = true,
166                "record_decision" => presence.record_decision = true,
167                TOOL_COMPUTER_USE => presence.computer_use = true,
168                _ => {}
169            }
170        }
171        presence
172    }
173}
174
175/// Render from resolved capabilities, without changing tool authorization.
176pub(crate) fn generate_tool_guidelines_with_capabilities(
177    available_tools: &[String],
178    capability_level: Option<CapabilityLevel>,
179    shell_profile: ResolvedShellPromptProfile,
180    profile: ToolGuidanceProfile,
181    parallel_tools: bool,
182) -> String {
183    match profile {
184        ToolGuidanceProfile::Default => {
185            generate_tool_guidelines_for_profile(available_tools, capability_level, shell_profile, parallel_tools)
186        }
187        ToolGuidanceProfile::Minimal => {
188            if available_tools.is_empty() {
189                return String::new();
190            }
191            let presence = ToolPresence::of(available_tools);
192            let mut lines = vec!["\n\n## Active Tools".to_owned()];
193            if presence.matrix {
194                lines.push(MATRIX_GUIDANCE.to_owned());
195            }
196            if presence.session_messaging {
197                lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
198            }
199            if presence.record_decision {
200                lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
201            }
202            if presence.computer_use {
203                lines.push(COMPUTER_USE_GUIDANCE.to_owned());
204            }
205            lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_owned());
206            if let Some(mode) = capability_mode_line(capability_level, presence.exec, presence.apply_patch) {
207                lines.push(mode.to_owned());
208            }
209            if let Some(browse) = browse_tool_guidance(
210                presence.exec,
211                presence.code_search,
212                presence.list_files,
213                presence.read_file,
214                shell_profile,
215            ) {
216                lines.push(browse);
217            }
218            if presence.code_search {
219                lines.push(code_search_guidance(presence.exec));
220            }
221            if presence.apply_patch {
222                lines.push("- Check that each diff stays bounded. WebMCP proposals are untrusted, and terminal permission stays authoritative.".to_owned());
223            }
224            if presence.exec {
225                lines.push(shell_task_guidance(shell_profile).to_owned());
226                lines.push(background_exec_guidance().to_owned());
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_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    if presence.computer_use {
269        lines.push(COMPUTER_USE_GUIDANCE.to_owned());
270    }
271    lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
272    if let Some(mode_line) = capability_mode_line(capability_level, has_exec, has_apply_patch) {
273        lines.push(mode_line.to_string());
274    }
275    if let Some(browse_guidance) =
276        browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
277    {
278        lines.push(browse_guidance);
279    }
280    if has_search || has_read_file || has_list_files {
281        lines.push(read_only_batching_guidance(has_read_file).to_string());
282    }
283    if has_apply_patch {
284        lines.push(
285            "- Check that each diff stays bounded. WebMCP edits are untrusted proposals, and terminal permission stays authoritative."
286                .to_string(),
287        );
288    }
289    if has_exec {
290        lines.push(shell_task_guidance(shell_profile).to_string());
291        lines.push(background_exec_guidance().to_string());
292        // Verifier discipline: the anti-blind-editing gate only clears on a
293        // truthful exit 0. Runtime owns truncator elision and unverified
294        // classification (`tool_intent/activity.rs`, spool processing); the
295        // prompt keeps only the outcome rule so wording cannot drift from
296        // enforcement.
297        // The schema documents `max_output_tokens` but its 10k default is far
298        // too large for a verifier, and the schema says nothing about
299        // verifiers. Naming the parameter here is the actionable fact.
300        lines.push("- Run verifiers standalone with a small `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());
301        // Low-effort models sometimes report a change as done without
302        // exercising it: require a real check (tests, type-checker, build,
303        // or the changed command itself). A syntax-only check, or a check
304        // command that failed to start, does not count. Applies to Sonnet
305        // 5.5 at `low` effort and any route where verification is skipped.
306        lines.push("- Run a real check that exercises the change; a syntax-only or failed-to-start check does not count. Install missing deps via the project's package manager, never sudo; if no check can run, say which and why.".to_string());
307        // Tool-latency tail is dominated by full builds (observed p90 ~18s):
308        // verify incrementally first. Kept tool-agnostic: fast checks exist
309        // in every stack (`cargo check`, `tsc --noEmit`, `pytest --collect-only`).
310        lines.push("- Run fast checks before full builds.".to_string());
311    }
312    // Tool-failure diagnosis, waiting on returned `next_wait_args` instead of
313    // polling, the safeguard rule, the verification outcome rule (report
314    // completion only after a check you ran), and spool paging with
315    // per-result preview bounds each have one home in Runtime
316    // Guidance, which every profile includes; do not restate them here.
317    //
318    // The `write_stdin` and `code_search` contracts (session-id handling and
319    // filter shape) live in those tools' own descriptions, which the model
320    // receives with the tool definitions; restating them here only
321    // duplicates the schema.
322    if has_search {
323        lines.push(code_search_guidance(has_exec));
324    }
325    if has_apply_patch || has_exec {
326        lines.push(
327            "- Build and Auto share tools and safety gates; Auto changes confirmation behavior only after explicit approval or full-auto policy."
328                .to_string(),
329        );
330    }
331    if (has_search || has_exec) && parallel_tools {
332        lines.push(PARALLEL_TOOLS_LINE.to_string());
333    }
334    if has_start_planning {
335        lines.push(START_PLANNING_GUIDANCE_LINE.to_string());
336    }
337
338    if lines.is_empty() {
339        return String::new();
340    }
341
342    if presence.record_decision {
343        lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
344    }
345    format!("\n\n## Active Tools\n{}", lines.join("\n"))
346}
347
348pub fn append_runtime_tool_prompt_sections_for_profile(
349    prompt: &mut String,
350    tool_snapshot: &SessionToolCatalogSnapshot,
351    include_catalog_metadata: bool,
352    shell_profile: ResolvedShellPromptProfile,
353) {
354    let names = snapshot_tool_names(tool_snapshot);
355    append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile, 0);
356}
357
358/// Select documentation density using the active route and session budgets.
359pub fn append_runtime_tool_prompt_sections_for_model(
360    prompt: &mut String,
361    tool_snapshot: &SessionToolCatalogSnapshot,
362    include_catalog_metadata: bool,
363    shell_profile: ResolvedShellPromptProfile,
364    provider: &dyn crate::llm::provider::LLMProvider,
365    model: &str,
366    config: Option<&crate::config::VTCodeConfig>,
367) {
368    append_runtime_tool_prompt_sections_for_model_after(
369        prompt,
370        tool_snapshot,
371        include_catalog_metadata,
372        shell_profile,
373        provider,
374        model,
375        config,
376        0,
377    );
378}
379
380/// Append runtime tool guidance while preserving all existing prompt content.
381///
382/// Call this with a fresh base prompt that does not contain generated tool
383/// guidance. The existing prefix may include user-authored section headings.
384pub fn append_fresh_runtime_tool_prompt_sections_for_model(
385    prompt: &mut String,
386    tool_snapshot: &SessionToolCatalogSnapshot,
387    include_catalog_metadata: bool,
388    shell_profile: ResolvedShellPromptProfile,
389    provider: &dyn crate::llm::provider::LLMProvider,
390    model: &str,
391    config: Option<&crate::config::VTCodeConfig>,
392) {
393    let boundary = prompt.len();
394    append_runtime_tool_prompt_sections_for_model_after(
395        prompt,
396        tool_snapshot,
397        include_catalog_metadata,
398        shell_profile,
399        provider,
400        model,
401        config,
402        boundary,
403    );
404}
405
406fn append_runtime_tool_prompt_sections_for_model_after(
407    prompt: &mut String,
408    tool_snapshot: &SessionToolCatalogSnapshot,
409    include_catalog_metadata: bool,
410    shell_profile: ResolvedShellPromptProfile,
411    provider: &dyn crate::llm::provider::LLMProvider,
412    model: &str,
413    config: Option<&crate::config::VTCodeConfig>,
414    boundary: usize,
415) {
416    let names = snapshot_tool_names(tool_snapshot);
417    let default_guidance = append_runtime_tool_sections_with_names(
418        prompt,
419        tool_snapshot,
420        names,
421        include_catalog_metadata,
422        shell_profile,
423        boundary,
424    );
425    let pricing = crate::config::models::model_catalog_entry(provider.name(), model).map(|entry| entry.pricing);
426    let profile = ToolGuidanceProfile::resolve(
427        crate::compaction::effective_context_budget(config, provider, model),
428        vtcode_commons::estimate_tokens(prompt),
429        config.map_or(0, |cfg| cfg.agent.max_system_prompt_tokens as usize),
430        pricing.and_then(|price| price.input),
431        config.and_then(|cfg| cfg.agent.harness.max_budget_usd),
432    );
433    let parallel_tools = provider.supports_parallel_tool_config(model);
434    // The planning mode section owns the output contract at every density.
435    // Default planning tool guidance contains no parallel-call hint.
436    if tool_snapshot.planning_active && profile == ToolGuidanceProfile::Default {
437        return;
438    }
439    remove_prompt_section_after(prompt, boundary, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
440    let presence = ToolPresence::of(names);
441    let capability_level = Some(infer_capability_level_from_presence(&presence));
442    let mut guidance = match profile {
443        ToolGuidanceProfile::Default => {
444            let mut guidance = default_guidance;
445            if let (Some(original), Some(effective)) = (
446                capability_mode_line(None, presence.exec, presence.apply_patch),
447                capability_mode_line(capability_level, presence.exec, presence.apply_patch),
448            ) && original != effective
449                && let Some(start) = guidance.find(original)
450            {
451                guidance.replace_range(start..start + original.len(), effective);
452            }
453            if !parallel_tools && let Some(start) = guidance.find(PARALLEL_TOOLS_LINE) {
454                guidance.replace_range(start.saturating_sub(1)..start + PARALLEL_TOOLS_LINE.len(), "");
455            }
456            guidance
457        }
458        ToolGuidanceProfile::Minimal => {
459            generate_tool_guidelines_with_capabilities(names, capability_level, shell_profile, profile, parallel_tools)
460        }
461    };
462    if tool_snapshot.planning_active {
463        append_minimal_planning_addendum(&mut guidance, &presence);
464    }
465    append_prompt_block(prompt, guidance.trim_start_matches('\n'));
466}
467
468/// Replace the runtime tool sections with guidance built from `names`, plus
469/// optional catalog metadata. Return the Default guidance so model-aware
470/// callers can reuse it after measuring the assembled prompt.
471fn append_runtime_tool_sections_with_names(
472    prompt: &mut String,
473    tool_snapshot: &SessionToolCatalogSnapshot,
474    names: &[String],
475    include_catalog_metadata: bool,
476    shell_profile: ResolvedShellPromptProfile,
477    boundary: usize,
478) -> String {
479    remove_prompt_section_after(prompt, boundary, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
480    remove_prompt_section_after(prompt, boundary, "[Runtime Tool Catalog]", SectionBoundaryMode::BracketOrMarkdown);
481    if boundary == 0 {
482        trim_trailing_newlines(prompt);
483    }
484
485    let guidelines = generate_runtime_tool_guidelines_for_profile(names, tool_snapshot.planning_active, shell_profile);
486    if !guidelines.is_empty() {
487        append_prompt_block(prompt, guidelines.trim_start_matches('\n'));
488    }
489
490    if include_catalog_metadata && tool_snapshot.snapshot.is_some() {
491        let active_tools = if tool_snapshot.active_tool_names.is_empty() {
492            "none".to_string()
493        } else {
494            tool_snapshot.active_tool_names.join(", ")
495        };
496        // One payload line: this block is machine diagnostics for the
497        // prompt/catalog alignment guard, not model guidance, so it must not
498        // spend prompt lines. The guard parses `key: value` pairs separated
499        // by `;`, so the format stays machine-readable.
500        let catalog_metadata = format!(
501            "[Runtime Tool Catalog]\n- version: {}; epoch: {}; catalog_tools: {}; available_tools: {}; currently_available_tools: {}; request_user_input_enabled: {}",
502            tool_snapshot.version,
503            tool_snapshot.epoch,
504            tool_snapshot.catalog_tools(),
505            tool_snapshot.available_tools(),
506            active_tools,
507            tool_snapshot.request_user_input_enabled,
508        );
509        append_prompt_block(prompt, &catalog_metadata);
510    }
511    guidelines
512}
513
514/// Compact tool reminders; the planning mode section retains the canonical
515/// research, step-quality, output, and persistence contract at every density.
516fn append_minimal_planning_addendum(guidance: &mut String, presence: &ToolPresence) {
517    guidance.push_str("\n- Planning is read-only.");
518    let mut read_tools = Vec::with_capacity(4);
519    if presence.read_file {
520        read_tools.push(TOOL_READ_FILE);
521    }
522    if presence.grep_file {
523        read_tools.push(TOOL_GREP_FILE);
524    }
525    if presence.code_search {
526        read_tools.push(TOOL_CODE_SEARCH);
527    }
528    if presence.list_files {
529        read_tools.push(TOOL_LIST_FILES);
530    }
531    guidance.push_str("\n- Keep inspections small: ");
532    if !read_tools.is_empty() {
533        guidance.push_str(&format!("prefer `{}` over `exec_command` shell reads; ", read_tools.join("`/`")));
534    }
535    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`.");
536    if presence.task_tracker {
537        guidance.push('\n');
538        guidance.push_str(PLANNING_TASK_TRACKER_LINE);
539    }
540    if presence.request_user_input {
541        guidance.push('\n');
542        guidance.push_str(REQUEST_USER_INPUT_LINE);
543    }
544}
545
546/// Append a compact summary of tools omitted from a client-local wire payload.
547///
548/// The listing is bounded like the `## Skills` routing section: at most
549/// `DEFERRED_TOOLS_MAX_GROUPS` groups are named and the rest collapse into one
550/// overflow line, so MCP-heavy sessions cannot bloat every request. Group
551/// descriptions are server-provided and unbounded, so each line is truncated
552/// to `DEFERRED_TOOLS_MAX_DESC_CHARS` characters.
553pub fn append_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
554    remove_prompt_section(prompt, "[Deferred Tools]", SectionBoundaryMode::BracketOrMarkdown);
555    append_fresh_deferred_tools_prompt_section(prompt, tools);
556}
557
558/// Append deferred-tool guidance to a fresh runtime prompt without removing
559/// user-authored sections with the same heading.
560pub fn append_fresh_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
561    let mut groups: Vec<_> = tool_groups(tools)
562        .into_iter()
563        .filter(|group| group.deferred_count > 0)
564        .collect();
565    let overflow = groups.len().saturating_sub(DEFERRED_TOOLS_MAX_GROUPS);
566    groups.truncate(DEFERRED_TOOLS_MAX_GROUPS);
567
568    let mut lines: Vec<String> = groups
569        .into_iter()
570        .map(|group| {
571            let description = truncate_deferred_description(group.description.as_deref().unwrap_or_default());
572            format!("- {} ({} tools): {}", group.name, group.deferred_count, description)
573        })
574        .collect();
575    if overflow > 0 {
576        lines.push(format!("(+{overflow} more deferred groups available — use `search_tools` to find them)"));
577    }
578
579    let unnamespaced_deferred = tools
580        .iter()
581        .filter(|tool| tool.namespace.is_none() && tool.defer_loading == Some(true))
582        .count();
583    if unnamespaced_deferred > 0 {
584        lines.push(format!("- {unnamespaced_deferred} additional deferred tools"));
585    }
586
587    if lines.is_empty() {
588        return;
589    }
590
591    let section = format!(
592        "[Deferred Tools]\n{}\nUse `search_tools` to find a deferred capability. Selected definitions become available in the next request segment.",
593        lines.join("\n")
594    );
595    append_prompt_block(prompt, &section);
596}
597
598/// Maximum deferred-tool groups named in the `[Deferred Tools]` prompt
599/// section before the rest collapse into one overflow line.
600const DEFERRED_TOOLS_MAX_GROUPS: usize = 8;
601/// Maximum characters of a group description in the section. Mirrors the
602/// `## Skills` line truncation: server-provided text must not bloat the prompt.
603const DEFERRED_TOOLS_MAX_DESC_CHARS: usize = 120;
604
605fn truncate_deferred_description(description: &str) -> String {
606    // Single pass: visit at most `MAX + 1` chars. The old form ran
607    // `chars().count()` over the whole string, then `chars().take()` again.
608    let mut chars = description.chars();
609    let truncated: String = chars.by_ref().take(DEFERRED_TOOLS_MAX_DESC_CHARS).collect();
610    if chars.next().is_none() {
611        return description.to_string();
612    }
613    format!("{}...", truncated.trim_end())
614}
615
616fn generate_runtime_tool_guidelines_for_profile(
617    available_tools: &[String],
618    planning_active: bool,
619    shell_profile: ResolvedShellPromptProfile,
620) -> String {
621    if !planning_active {
622        // Measurement parity: this Default-density build feeds the prompt size
623        // that `ToolGuidanceProfile::resolve` reads, so it keeps shipping the
624        // parallel-call hint unconditionally like the static composition path.
625        return generate_tool_guidelines_for_profile(available_tools, None, shell_profile, true);
626    }
627
628    let presence = ToolPresence::of(available_tools);
629    let has_exec = presence.exec;
630    let has_search = presence.code_search;
631    let has_read_file = presence.read_file;
632    let has_list_files = presence.list_files;
633    let has_request_user_input = presence.request_user_input;
634    let has_task_tracker = presence.task_tracker;
635
636    let mut lines = vec!["- Planning workflow active: stay within the read-safe tool list.".to_string()];
637    if presence.web_search {
638        lines.push(WEB_SEARCH_GUIDANCE.to_owned());
639    }
640    lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
641    if let Some(browse_guidance) =
642        browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
643    {
644        lines.push(browse_guidance);
645    }
646    if has_exec {
647        lines.push("- In Planning workflow, use `exec_command` only for read-only verification.".to_string());
648    }
649    if has_search {
650        lines.push(code_search_guidance(has_exec));
651    }
652    if has_task_tracker {
653        // The tracker call shapes (list/update/bulk, index vs. index_path vs.
654        // items, and "omit unused fields") are documented by the tool
655        // description, which reaches the model with the tool definitions.
656        // This line keeps only the planning-only facts the schema does not
657        // carry.
658        lines.push(PLANNING_TASK_TRACKER_LINE.to_string());
659    }
660    if has_request_user_input {
661        lines.push(REQUEST_USER_INPUT_LINE.to_string());
662    }
663    if has_search || has_exec {
664        lines.push("- If calls repeat without progress, tighten the plan instead of retrying identically.".to_string());
665    }
666    if presence.record_decision {
667        lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
668    }
669
670    format!("\n\n## Active Tools\n{}", lines.join("\n"))
671}
672
673fn snapshot_tool_names(tool_snapshot: &SessionToolCatalogSnapshot) -> &[String] {
674    &tool_snapshot.active_tool_names
675}
676
677fn browse_tool_guidance(
678    has_exec: bool,
679    has_search: bool,
680    has_list_files: bool,
681    has_read_file: bool,
682    shell_profile: ResolvedShellPromptProfile,
683) -> Option<String> {
684    if has_exec {
685        return Some(shell_browse_guidance(shell_profile, has_search));
686    }
687
688    if !(has_search || has_list_files || has_read_file) {
689        return None;
690    }
691
692    Some("- Use available read-only repository tools for browsing; do not modify files.".to_string())
693}
694
695pub(crate) fn render_shell_profile_guidance(shell_profile: ResolvedShellPromptProfile) -> String {
696    let profile_lines = match shell_profile {
697        ResolvedShellPromptProfile::UnixLike => {
698            "- Active shell profile: `unix_like`.\n- On macOS, write BSD-compatible flags for BSD tools. VT Code does not rewrite GNU flags for macOS BSD tools.\n- Commands run under the user's login shell, which may be zsh: avoid bash-only syntax such as `${PIPESTATUS[...]}` (it expands empty outside bash); rely on the harness-reported exit status instead of capturing codes through pipes."
699        }
700        ResolvedShellPromptProfile::PowerShell => {
701            "- Active shell profile: `powershell`.\n- On native Windows, use WSL when you need Unix-like workflows or Unix command examples."
702        }
703    };
704    format!("## Shell Profile\n{profile_lines}\n{SHELL_PROFILE_POLICY_SUFFIX}")
705}
706
707fn shell_browse_guidance(shell_profile: ResolvedShellPromptProfile, has_search: bool) -> String {
708    // Sessions show `exec_command` + `rg` crowding out `code_search`
709    // (observed 654 exec vs 15 code_search in one run): `rg` scans text
710    // while `code_search` resolves definitions and exact usages, so route
711    // code search to the dedicated tool whenever it is available.
712    const SEARCH_PREFERENCE_UNIX: &str = " Prefer `code_search` over `rg`/`grep` for code.";
713    const SEARCH_PREFERENCE_POWERSHELL: &str = " Prefer `code_search` over `Select-String` for code.";
714    match shell_profile {
715        ResolvedShellPromptProfile::UnixLike => {
716            let mut line = String::from("- Browse the repository with `exec_command.cmd`.");
717            if has_search {
718                line.push_str(SEARCH_PREFERENCE_UNIX);
719            }
720            line
721        }
722        ResolvedShellPromptProfile::PowerShell => {
723            let mut line = "- Browse the repository with `exec_command.cmd`.".to_string();
724            if has_search {
725                line.push_str(SEARCH_PREFERENCE_POWERSHELL);
726            }
727            line
728        }
729    }
730}
731
732fn shell_task_guidance(shell_profile: ResolvedShellPromptProfile) -> &'static str {
733    match shell_profile {
734        ResolvedShellPromptProfile::UnixLike => {
735            "- 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`)."
736        }
737        ResolvedShellPromptProfile::PowerShell => {
738            "- Use native PowerShell syntax in `exec_command.cmd` for shell-only tasks."
739        }
740    }
741}
742
743fn background_exec_guidance() -> &'static str {
744    // `background`, the three-process cap, `session_id`, `monitor_filter`, and
745    // `monitor_digest` are all documented by the `exec_command` schema, which
746    // reaches the model with the tool definitions, and the runtime rejects an
747    // over-limit background start with an actionable error. The only fact the
748    // schema cannot state is *when* to reach for it.
749    "- For long-lived commands, start them in the background rather than blocking a turn."
750}
751
752fn read_only_batching_guidance(has_read_file: bool) -> &'static str {
753    if has_read_file {
754        "- 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."
755    } else {
756        "- Batch independent read-only calls; order dependent reads, and serialize mutations."
757    }
758}
759
760fn code_search_guidance(has_exec: bool) -> String {
761    // The schema owns the query contract ("Literal code or path query",
762    // smart-case) and the filter names. What it cannot state is that `|`
763    // separates alternatives, that a truncated or unavailable result needs a
764    // different query rather than a retry, and that the runtime coerces a
765    // JSON-encoded array or integer. The runtime also emits per-call hints
766    // when it truncates or drops a result category, so this line carries the
767    // standing rule rather than repeating them.
768    const BASE: &str = "- `code_search` queries are literal and smart-case; `|` separates alternatives. On a truncated or unavailable result, change the query instead of retrying it. Do not JSON-encode arrays or integers as strings.";
769    if has_exec {
770        format!("{BASE} Use `exec_command` or a skill for syntax patterns.")
771    } else {
772        BASE.to_string()
773    }
774}
775
776fn capability_mode_line(
777    capability_level: Option<CapabilityLevel>,
778    has_exec: bool,
779    has_file: bool,
780) -> Option<&'static str> {
781    match capability_level {
782        Some(CapabilityLevel::Basic) => {
783            Some("- Capabilities: limited. Ask the user to enable more capabilities if file work is required.")
784        }
785        Some(CapabilityLevel::FileReading | CapabilityLevel::FileListing) => Some(CAPABILITY_READ_ONLY_LINE),
786        _ if !has_exec && !has_file => Some(CAPABILITY_READ_ONLY_LINE),
787        _ => None,
788    }
789}
790
791/// Infer capability level from available tools.
792pub(crate) fn infer_capability_level(available_tools: &[String]) -> CapabilityLevel {
793    infer_capability_level_from_presence(&ToolPresence::of(available_tools))
794}
795
796fn infer_capability_level_from_presence(presence: &ToolPresence) -> CapabilityLevel {
797    if presence.code_search {
798        CapabilityLevel::CodeSearch
799    } else if presence.apply_patch {
800        CapabilityLevel::Editing
801    } else if presence.exec {
802        CapabilityLevel::Bash
803    } else if presence.list_files {
804        CapabilityLevel::FileListing
805    } else if presence.read_file {
806        CapabilityLevel::FileReading
807    } else {
808        CapabilityLevel::Basic
809    }
810}
811
812#[cfg(test)]
813mod tests;