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