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 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.";
22const 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.";
23const 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.";
24const 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.";
25
26const TOOL_START_PLANNING: &str = tools::START_PLANNING;
27
28const OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE: &str = "- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.";
29
30const 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.";
35
36const PLANNING_TASK_TRACKER_LINE: &str = "- `task_tracker`: keep blockers and verification open. `scope_review` checks cannot satisfy functional `verify` checks.";
46
47const MINIMAL_CONTEXT_TOKEN_CEILING: usize = 32_000;
50
51const PARALLEL_TOOLS_LINE: &str = "- Run independent tools in parallel when inputs do not depend on each other.";
55
56const REQUEST_USER_INPUT_LINE: &str =
67 "- Use `request_user_input` only for a blocker that repository exploration did not resolve.";
68
69const CAPABILITY_READ_ONLY_LINE: &str =
72 "- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.";
73
74const 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.";
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub(crate) enum ToolGuidanceProfile {
81 Minimal,
82 Default,
83}
84
85impl ToolGuidanceProfile {
86 #[must_use]
87 pub(crate) fn resolve(
88 context_tokens: usize,
89 default_prompt_tokens: usize,
90 max_prompt_tokens: usize,
91 input_usd_per_token: Option<f64>,
92 max_budget_usd: Option<f64>,
93 ) -> Self {
94 let exceeds_cost = input_usd_per_token.zip(max_budget_usd).is_some_and(|(price, budget)| {
95 price.is_finite() && price >= 0.0 && budget.is_finite() && default_prompt_tokens as f64 * price > budget
96 });
97 if (context_tokens > 0 && context_tokens <= MINIMAL_CONTEXT_TOKEN_CEILING)
98 || (max_prompt_tokens > 0 && default_prompt_tokens > max_prompt_tokens)
99 || exceeds_cost
100 {
101 Self::Minimal
102 } else {
103 Self::Default
104 }
105 }
106}
107
108struct ToolPresence {
111 exec: bool,
112 write_stdin: bool,
113 code_search: bool,
114 web_search: bool,
115 read_file: bool,
116 grep_file: bool,
117 list_files: bool,
118 apply_patch: bool,
119 request_user_input: bool,
120 task_tracker: bool,
121 start_planning: bool,
122 matrix: bool,
123 record_decision: bool,
124 session_messaging: bool,
125}
126
127impl ToolPresence {
128 fn of(available_tools: &[String]) -> Self {
129 let mut presence = Self {
133 exec: false,
134 write_stdin: false,
135 code_search: false,
136 web_search: false,
137 read_file: false,
138 grep_file: false,
139 list_files: false,
140 apply_patch: false,
141 request_user_input: false,
142 task_tracker: false,
143 start_planning: false,
144 matrix: false,
145 record_decision: false,
146 session_messaging: false,
147 };
148 for tool in available_tools {
149 match tool.as_str() {
150 TOOL_EXEC_COMMAND => presence.exec = true,
151 TOOL_WRITE_STDIN => presence.write_stdin = true,
152 TOOL_CODE_SEARCH => presence.code_search = true,
153 "web_search" => presence.web_search = true,
154 TOOL_READ_FILE => presence.read_file = true,
155 TOOL_GREP_FILE => presence.grep_file = true,
156 TOOL_LIST_FILES => presence.list_files = true,
157 TOOL_APPLY_PATCH => presence.apply_patch = true,
158 TOOL_REQUEST_USER_INPUT => presence.request_user_input = true,
159 TOOL_TASK_TRACKER => presence.task_tracker = true,
160 TOOL_START_PLANNING => presence.start_planning = true,
161 "matrix" => presence.matrix = true,
162 TOOL_ASK_SESSION => presence.session_messaging = true,
163 "record_decision" => presence.record_decision = true,
164 _ => {}
165 }
166 }
167 presence
168 }
169}
170
171pub(crate) fn generate_tool_guidelines_with_capabilities(
173 available_tools: &[String],
174 capability_level: Option<CapabilityLevel>,
175 shell_profile: ResolvedShellPromptProfile,
176 profile: ToolGuidanceProfile,
177 parallel_tools: bool,
178) -> String {
179 match profile {
180 ToolGuidanceProfile::Default => {
181 generate_tool_guidelines_for_profile(available_tools, capability_level, shell_profile, parallel_tools)
182 }
183 ToolGuidanceProfile::Minimal => {
184 if available_tools.is_empty() {
185 return String::new();
186 }
187 let presence = ToolPresence::of(available_tools);
188 let mut lines = vec!["\n\n## Active Tools".to_owned()];
189 if presence.matrix {
190 lines.push(MATRIX_GUIDANCE.to_owned());
191 }
192 if presence.session_messaging {
193 lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
194 }
195 if presence.record_decision {
196 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
197 }
198 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_owned());
199 if let Some(mode) = capability_mode_line(capability_level, presence.exec, presence.apply_patch) {
200 lines.push(mode.to_owned());
201 }
202 if let Some(browse) = browse_tool_guidance(
203 presence.exec,
204 presence.code_search,
205 presence.list_files,
206 presence.read_file,
207 shell_profile,
208 ) {
209 lines.push(browse);
210 }
211 if presence.code_search {
212 lines.push(code_search_guidance(presence.exec));
213 }
214 if presence.apply_patch {
215 lines.push("- Check that each diff stays bounded. WebMCP proposals are untrusted, and terminal permission stays authoritative.".to_owned());
216 }
217 if presence.exec {
218 lines.push(shell_task_guidance(shell_profile).to_owned());
219 lines.push(background_exec_guidance().to_owned());
220 }
221 if presence.start_planning {
224 lines.push(START_PLANNING_GUIDANCE_LINE.to_owned());
225 }
226 if parallel_tools {
227 lines.push(PARALLEL_TOOLS_LINE.to_owned());
228 }
229 lines.join("\n")
230 }
231 }
232}
233
234pub(crate) fn generate_tool_guidelines_for_profile(
238 available_tools: &[String],
239 capability_level: Option<CapabilityLevel>,
240 shell_profile: ResolvedShellPromptProfile,
241 parallel_tools: bool,
242) -> String {
243 let presence = ToolPresence::of(available_tools);
244 let has_exec = presence.exec;
245 let has_search = presence.code_search;
246 let has_read_file = presence.read_file;
247 let has_list_files = presence.list_files;
248 let has_apply_patch = presence.apply_patch;
249 let has_start_planning = presence.start_planning;
250
251 let mut lines = Vec::new();
252 if presence.matrix {
253 lines.push(MATRIX_GUIDANCE.to_owned());
254 }
255 if presence.session_messaging {
256 lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
257 }
258 if presence.web_search {
259 lines.push(WEB_SEARCH_GUIDANCE.to_owned());
260 }
261 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
262 if let Some(mode_line) = capability_mode_line(capability_level, has_exec, has_apply_patch) {
263 lines.push(mode_line.to_string());
264 }
265 if let Some(browse_guidance) =
266 browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
267 {
268 lines.push(browse_guidance);
269 }
270 if has_search || has_read_file || has_list_files {
271 lines.push(read_only_batching_guidance(has_read_file).to_string());
272 }
273 if has_apply_patch {
274 lines.push(
275 "- Check that each diff stays bounded. WebMCP edits are untrusted proposals, and terminal permission stays authoritative."
276 .to_string(),
277 );
278 }
279 if has_exec {
280 lines.push(shell_task_guidance(shell_profile).to_string());
281 lines.push(background_exec_guidance().to_string());
282 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());
291 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());
297 lines.push("- Run fast checks before full builds.".to_string());
301 }
302 if has_search {
313 lines.push(code_search_guidance(has_exec));
314 }
315 if has_apply_patch || has_exec {
316 lines.push(
317 "- Build and Auto share tools and safety gates; Auto changes confirmation behavior only after explicit approval or full-auto policy."
318 .to_string(),
319 );
320 }
321 if (has_search || has_exec) && parallel_tools {
322 lines.push(PARALLEL_TOOLS_LINE.to_string());
323 }
324 if has_start_planning {
325 lines.push(START_PLANNING_GUIDANCE_LINE.to_string());
326 }
327
328 if lines.is_empty() {
329 return String::new();
330 }
331
332 if presence.record_decision {
333 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
334 }
335 format!("\n\n## Active Tools\n{}", lines.join("\n"))
336}
337
338pub fn append_runtime_tool_prompt_sections_for_profile(
339 prompt: &mut String,
340 tool_snapshot: &SessionToolCatalogSnapshot,
341 include_catalog_metadata: bool,
342 shell_profile: ResolvedShellPromptProfile,
343) {
344 let names = snapshot_tool_names(tool_snapshot);
345 append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile, 0);
346}
347
348pub fn append_runtime_tool_prompt_sections_for_model(
350 prompt: &mut String,
351 tool_snapshot: &SessionToolCatalogSnapshot,
352 include_catalog_metadata: bool,
353 shell_profile: ResolvedShellPromptProfile,
354 provider: &dyn crate::llm::provider::LLMProvider,
355 model: &str,
356 config: Option<&crate::config::VTCodeConfig>,
357) {
358 append_runtime_tool_prompt_sections_for_model_after(
359 prompt,
360 tool_snapshot,
361 include_catalog_metadata,
362 shell_profile,
363 provider,
364 model,
365 config,
366 0,
367 );
368}
369
370pub fn append_fresh_runtime_tool_prompt_sections_for_model(
375 prompt: &mut String,
376 tool_snapshot: &SessionToolCatalogSnapshot,
377 include_catalog_metadata: bool,
378 shell_profile: ResolvedShellPromptProfile,
379 provider: &dyn crate::llm::provider::LLMProvider,
380 model: &str,
381 config: Option<&crate::config::VTCodeConfig>,
382) {
383 let boundary = prompt.len();
384 append_runtime_tool_prompt_sections_for_model_after(
385 prompt,
386 tool_snapshot,
387 include_catalog_metadata,
388 shell_profile,
389 provider,
390 model,
391 config,
392 boundary,
393 );
394}
395
396fn append_runtime_tool_prompt_sections_for_model_after(
397 prompt: &mut String,
398 tool_snapshot: &SessionToolCatalogSnapshot,
399 include_catalog_metadata: bool,
400 shell_profile: ResolvedShellPromptProfile,
401 provider: &dyn crate::llm::provider::LLMProvider,
402 model: &str,
403 config: Option<&crate::config::VTCodeConfig>,
404 boundary: usize,
405) {
406 let names = snapshot_tool_names(tool_snapshot);
407 let default_guidance = append_runtime_tool_sections_with_names(
408 prompt,
409 tool_snapshot,
410 names,
411 include_catalog_metadata,
412 shell_profile,
413 boundary,
414 );
415 let pricing = crate::config::models::model_catalog_entry(provider.name(), model).map(|entry| entry.pricing);
416 let profile = ToolGuidanceProfile::resolve(
417 crate::compaction::effective_context_budget(config, provider, model),
418 vtcode_commons::estimate_tokens(prompt),
419 config.map_or(0, |cfg| cfg.agent.max_system_prompt_tokens as usize),
420 pricing.and_then(|price| price.input),
421 config.and_then(|cfg| cfg.agent.harness.max_budget_usd),
422 );
423 let parallel_tools = provider.supports_parallel_tool_config(model);
424 if tool_snapshot.planning_active && profile == ToolGuidanceProfile::Default {
427 return;
428 }
429 remove_prompt_section_after(prompt, boundary, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
430 let presence = ToolPresence::of(names);
431 let capability_level = Some(infer_capability_level_from_presence(&presence));
432 let mut guidance = match profile {
433 ToolGuidanceProfile::Default => {
434 let mut guidance = default_guidance;
435 if let (Some(original), Some(effective)) = (
436 capability_mode_line(None, presence.exec, presence.apply_patch),
437 capability_mode_line(capability_level, presence.exec, presence.apply_patch),
438 ) && original != effective
439 && let Some(start) = guidance.find(original)
440 {
441 guidance.replace_range(start..start + original.len(), effective);
442 }
443 if !parallel_tools && let Some(start) = guidance.find(PARALLEL_TOOLS_LINE) {
444 guidance.replace_range(start.saturating_sub(1)..start + PARALLEL_TOOLS_LINE.len(), "");
445 }
446 guidance
447 }
448 ToolGuidanceProfile::Minimal => {
449 generate_tool_guidelines_with_capabilities(names, capability_level, shell_profile, profile, parallel_tools)
450 }
451 };
452 if tool_snapshot.planning_active {
453 append_minimal_planning_addendum(&mut guidance, &presence);
454 }
455 append_prompt_block(prompt, guidance.trim_start_matches('\n'));
456}
457
458fn append_runtime_tool_sections_with_names(
462 prompt: &mut String,
463 tool_snapshot: &SessionToolCatalogSnapshot,
464 names: &[String],
465 include_catalog_metadata: bool,
466 shell_profile: ResolvedShellPromptProfile,
467 boundary: usize,
468) -> String {
469 remove_prompt_section_after(prompt, boundary, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
470 remove_prompt_section_after(prompt, boundary, "[Runtime Tool Catalog]", SectionBoundaryMode::BracketOrMarkdown);
471 if boundary == 0 {
472 trim_trailing_newlines(prompt);
473 }
474
475 let guidelines = generate_runtime_tool_guidelines_for_profile(names, tool_snapshot.planning_active, shell_profile);
476 if !guidelines.is_empty() {
477 append_prompt_block(prompt, guidelines.trim_start_matches('\n'));
478 }
479
480 if include_catalog_metadata && tool_snapshot.snapshot.is_some() {
481 let active_tools = if tool_snapshot.active_tool_names.is_empty() {
482 "none".to_string()
483 } else {
484 tool_snapshot.active_tool_names.join(", ")
485 };
486 let catalog_metadata = format!(
491 "[Runtime Tool Catalog]\n- version: {}; epoch: {}; catalog_tools: {}; available_tools: {}; currently_available_tools: {}; request_user_input_enabled: {}",
492 tool_snapshot.version,
493 tool_snapshot.epoch,
494 tool_snapshot.catalog_tools(),
495 tool_snapshot.available_tools(),
496 active_tools,
497 tool_snapshot.request_user_input_enabled,
498 );
499 append_prompt_block(prompt, &catalog_metadata);
500 }
501 guidelines
502}
503
504fn append_minimal_planning_addendum(guidance: &mut String, presence: &ToolPresence) {
507 guidance.push_str("\n- Planning is read-only.");
508 let mut read_tools = Vec::with_capacity(4);
509 if presence.read_file {
510 read_tools.push(TOOL_READ_FILE);
511 }
512 if presence.grep_file {
513 read_tools.push(TOOL_GREP_FILE);
514 }
515 if presence.code_search {
516 read_tools.push(TOOL_CODE_SEARCH);
517 }
518 if presence.list_files {
519 read_tools.push(TOOL_LIST_FILES);
520 }
521 guidance.push_str("\n- Keep inspections small: ");
522 if !read_tools.is_empty() {
523 guidance.push_str(&format!("prefer `{}` over `exec_command` shell reads; ", read_tools.join("`/`")));
524 }
525 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`.");
526 if presence.task_tracker {
527 guidance.push('\n');
528 guidance.push_str(PLANNING_TASK_TRACKER_LINE);
529 }
530 if presence.request_user_input {
531 guidance.push('\n');
532 guidance.push_str(REQUEST_USER_INPUT_LINE);
533 }
534}
535
536pub fn append_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
544 remove_prompt_section(prompt, "[Deferred Tools]", SectionBoundaryMode::BracketOrMarkdown);
545 append_fresh_deferred_tools_prompt_section(prompt, tools);
546}
547
548pub fn append_fresh_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
551 let mut groups: Vec<_> = tool_groups(tools)
552 .into_iter()
553 .filter(|group| group.deferred_count > 0)
554 .collect();
555 let overflow = groups.len().saturating_sub(DEFERRED_TOOLS_MAX_GROUPS);
556 groups.truncate(DEFERRED_TOOLS_MAX_GROUPS);
557
558 let mut lines: Vec<String> = groups
559 .into_iter()
560 .map(|group| {
561 let description = truncate_deferred_description(group.description.as_deref().unwrap_or_default());
562 format!("- {} ({} tools): {}", group.name, group.deferred_count, description)
563 })
564 .collect();
565 if overflow > 0 {
566 lines.push(format!("(+{overflow} more deferred groups available — use `search_tools` to find them)"));
567 }
568
569 let unnamespaced_deferred = tools
570 .iter()
571 .filter(|tool| tool.namespace.is_none() && tool.defer_loading == Some(true))
572 .count();
573 if unnamespaced_deferred > 0 {
574 lines.push(format!("- {unnamespaced_deferred} additional deferred tools"));
575 }
576
577 if lines.is_empty() {
578 return;
579 }
580
581 let section = format!(
582 "[Deferred Tools]\n{}\nUse `search_tools` to find a deferred capability. Selected definitions become available in the next request segment.",
583 lines.join("\n")
584 );
585 append_prompt_block(prompt, §ion);
586}
587
588const DEFERRED_TOOLS_MAX_GROUPS: usize = 8;
591const DEFERRED_TOOLS_MAX_DESC_CHARS: usize = 120;
594
595fn truncate_deferred_description(description: &str) -> String {
596 let mut chars = description.chars();
599 let truncated: String = chars.by_ref().take(DEFERRED_TOOLS_MAX_DESC_CHARS).collect();
600 if chars.next().is_none() {
601 return description.to_string();
602 }
603 format!("{}...", truncated.trim_end())
604}
605
606fn generate_runtime_tool_guidelines_for_profile(
607 available_tools: &[String],
608 planning_active: bool,
609 shell_profile: ResolvedShellPromptProfile,
610) -> String {
611 if !planning_active {
612 return generate_tool_guidelines_for_profile(available_tools, None, shell_profile, true);
616 }
617
618 let presence = ToolPresence::of(available_tools);
619 let has_exec = presence.exec;
620 let has_search = presence.code_search;
621 let has_read_file = presence.read_file;
622 let has_list_files = presence.list_files;
623 let has_request_user_input = presence.request_user_input;
624 let has_task_tracker = presence.task_tracker;
625
626 let mut lines = vec!["- Planning workflow active: stay within the read-safe tool list.".to_string()];
627 if presence.web_search {
628 lines.push(WEB_SEARCH_GUIDANCE.to_owned());
629 }
630 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
631 if let Some(browse_guidance) =
632 browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
633 {
634 lines.push(browse_guidance);
635 }
636 if has_exec {
637 lines.push("- In Planning workflow, use `exec_command` only for read-only verification.".to_string());
638 }
639 if has_search {
640 lines.push(code_search_guidance(has_exec));
641 }
642 if has_task_tracker {
643 lines.push(PLANNING_TASK_TRACKER_LINE.to_string());
649 }
650 if has_request_user_input {
651 lines.push(REQUEST_USER_INPUT_LINE.to_string());
652 }
653 if has_search || has_exec {
654 lines.push("- If calls repeat without progress, tighten the plan instead of retrying identically.".to_string());
655 }
656 if presence.record_decision {
657 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
658 }
659
660 format!("\n\n## Active Tools\n{}", lines.join("\n"))
661}
662
663fn snapshot_tool_names(tool_snapshot: &SessionToolCatalogSnapshot) -> &[String] {
664 &tool_snapshot.active_tool_names
665}
666
667fn browse_tool_guidance(
668 has_exec: bool,
669 has_search: bool,
670 has_list_files: bool,
671 has_read_file: bool,
672 shell_profile: ResolvedShellPromptProfile,
673) -> Option<String> {
674 if has_exec {
675 return Some(shell_browse_guidance(shell_profile, has_search));
676 }
677
678 if !(has_search || has_list_files || has_read_file) {
679 return None;
680 }
681
682 Some("- Use available read-only repository tools for browsing; do not modify files.".to_string())
683}
684
685pub(crate) fn render_shell_profile_guidance(shell_profile: ResolvedShellPromptProfile) -> String {
686 let profile_lines = match shell_profile {
687 ResolvedShellPromptProfile::UnixLike => {
688 "- 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."
689 }
690 ResolvedShellPromptProfile::PowerShell => {
691 "- Active shell profile: `powershell`.\n- On native Windows, use WSL when you need Unix-like workflows or Unix command examples."
692 }
693 };
694 format!("## Shell Profile\n{profile_lines}\n{SHELL_PROFILE_POLICY_SUFFIX}")
695}
696
697fn shell_browse_guidance(shell_profile: ResolvedShellPromptProfile, has_search: bool) -> String {
698 const SEARCH_PREFERENCE_UNIX: &str = " Prefer `code_search` over `rg`/`grep` for code.";
703 const SEARCH_PREFERENCE_POWERSHELL: &str = " Prefer `code_search` over `Select-String` for code.";
704 match shell_profile {
705 ResolvedShellPromptProfile::UnixLike => {
706 let mut line = String::from("- Browse the repository with `exec_command.cmd`.");
707 if has_search {
708 line.push_str(SEARCH_PREFERENCE_UNIX);
709 }
710 line
711 }
712 ResolvedShellPromptProfile::PowerShell => {
713 let mut line = "- Browse the repository with `exec_command.cmd`.".to_string();
714 if has_search {
715 line.push_str(SEARCH_PREFERENCE_POWERSHELL);
716 }
717 line
718 }
719 }
720}
721
722fn shell_task_guidance(shell_profile: ResolvedShellPromptProfile) -> &'static str {
723 match shell_profile {
724 ResolvedShellPromptProfile::UnixLike => {
725 "- 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`)."
726 }
727 ResolvedShellPromptProfile::PowerShell => {
728 "- Use native PowerShell syntax in `exec_command.cmd` for shell-only tasks."
729 }
730 }
731}
732
733fn background_exec_guidance() -> &'static str {
734 "- For long-lived commands, start them in the background rather than blocking a turn."
740}
741
742fn read_only_batching_guidance(has_read_file: bool) -> &'static str {
743 if has_read_file {
744 "- 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."
745 } else {
746 "- Batch independent read-only calls; order dependent reads, and serialize mutations."
747 }
748}
749
750fn code_search_guidance(has_exec: bool) -> String {
751 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.";
759 if has_exec {
760 format!("{BASE} Use `exec_command` or a skill for syntax patterns.")
761 } else {
762 BASE.to_string()
763 }
764}
765
766fn capability_mode_line(
767 capability_level: Option<CapabilityLevel>,
768 has_exec: bool,
769 has_file: bool,
770) -> Option<&'static str> {
771 match capability_level {
772 Some(CapabilityLevel::Basic) => {
773 Some("- Capabilities: limited. Ask the user to enable more capabilities if file work is required.")
774 }
775 Some(CapabilityLevel::FileReading | CapabilityLevel::FileListing) => Some(CAPABILITY_READ_ONLY_LINE),
776 _ if !has_exec && !has_file => Some(CAPABILITY_READ_ONLY_LINE),
777 _ => None,
778 }
779}
780
781pub(crate) fn infer_capability_level(available_tools: &[String]) -> CapabilityLevel {
783 infer_capability_level_from_presence(&ToolPresence::of(available_tools))
784}
785
786fn infer_capability_level_from_presence(presence: &ToolPresence) -> CapabilityLevel {
787 if presence.code_search {
788 CapabilityLevel::CodeSearch
789 } else if presence.apply_patch {
790 CapabilityLevel::Editing
791 } else if presence.exec {
792 CapabilityLevel::Bash
793 } else if presence.list_files {
794 CapabilityLevel::FileListing
795 } else if presence.read_file {
796 CapabilityLevel::FileReading
797 } else {
798 CapabilityLevel::Basic
799 }
800}
801
802#[cfg(test)]
803mod tests;