1use crate::config::constants::tools;
2use crate::config::types::{CapabilityLevel, ResolvedShellPromptProfile};
3use crate::core::agent::harness_kernel::SessionToolCatalogSnapshot;
4use crate::llm::provider::ToolDefinition;
5use crate::prompts::sections::{
6 SectionBoundaryMode, append_prompt_block, remove_prompt_section, trim_trailing_newlines,
7};
8use crate::tools::registry::tool_groups;
9
10const TOOL_EXEC_COMMAND: &str = tools::EXEC_COMMAND;
11const TOOL_WRITE_STDIN: &str = tools::WRITE_STDIN;
12const TOOL_CODE_SEARCH: &str = tools::CODE_SEARCH;
13const TOOL_READ_FILE: &str = tools::READ_FILE;
14const TOOL_LIST_FILES: &str = tools::LIST_FILES;
15const TOOL_GREP_FILE: &str = tools::GREP_FILE;
16const TOOL_APPLY_PATCH: &str = tools::APPLY_PATCH;
17const TOOL_REQUEST_USER_INPUT: &str = tools::REQUEST_USER_INPUT;
18const TOOL_ASK_SESSION: &str = tools::ASK_SESSION;
19const TOOL_TASK_TRACKER: &str = tools::TASK_TRACKER;
20const PUBLIC_DECISION_GUIDANCE: &str = "- Use optional `record_decision` for consequential choices, rejected approaches, or recovery changes. Give concise public rationale; ordinary reads and commands need no record.";
21const MATRIX_GUIDANCE: &str = "- `matrix`: create persists explicit tasks, checks, resources, and timeouts; start freezes the spec. The coordinator delegates execution and verification to scheduler-owned workers; discovery is idle-only. Replay restores admission before discovery; resume reconciles owned cleanup. status is a projection; pause stops dispatch; user cancel is terminal. Internal failures require reconciliation, not cancellation. Workers retain effective permissions and sandbox gates. Read leases require read-only workers. Report identity is runtime-owned; final success needs durable declared checks for the current generation, never summaries or child completion. Source and declared input changes, including submodule state, invalidate checks. Automatic retry requires replay_safe, confirmed cleanup, and at most one interrupted/timeout retry; other failures need a coordinator decision.";
22const SESSION_MESSAGING_GUIDANCE: &str = "- Peer sessions: `list_sessions` discovers live CLI sessions in this workspace; `ask_session` sends one a question and its `answer_session` reply arrives as a notice on a later turn. Delivery needs the peer running.";
23const WEB_SEARCH_GUIDANCE: &str = "- web_search uses keyless DuckDuckGo; web_fetch needs separate approval. For `antiban_blocked` or `retryable: false`, do not retry; wait `retry_after_ms` for `cooldown`; retry `network_error`/`upstream_error` once. For GitHub queries prefer `gh search`/`gh api` via exec_command when available.";
24const TOOL_START_PLANNING: &str = tools::START_PLANNING;
25
26const OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE: &str = "- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.";
27
28const CROSS_TURN_RESUME_HINT_CLAUSE: &str =
33 "; a turn-start `Exec session resume:` hint carries the live ids when a prior turn ended mid-run.";
34
35const START_PLANNING_GUIDANCE_LINE: &str = "- For demanding, ambiguous, or multi-phase tasks, call `start_planning`; it asks the user before entering the read-only Planning workflow unless the session runs in full-auto or skips confirmations. Skip it for straightforward changes.";
40
41const PLANNING_TASK_TRACKER_COMPACT_LINE: &str = "- `task_tracker`: list {\"action\":\"list\"}; updates use positive index/index_path or items, never conflicting fields; index 0 is invalid while planning. Keep blockers and verification open. `scope_review` checks cannot satisfy functional `verify` checks.";
46const PLANNING_TASK_TRACKER_INDEX_LINE: &str = "- `task_tracker`: list {\"action\":\"list\"}; update {\"action\":\"update\",\"index\":1,\"status\":\"in_progress\"}; bulk {\"action\":\"update\",\"items\":[\"[x] Done\",\"[ ] Remaining\"]}. Use positive flat indices or hierarchical index_path (index 0 is invalid while planning), or items for full checklist replacement. Omit unused fields; never combine index, index_path, and items. `scope_review` checks cannot satisfy functional `verify` checks.";
47
48const MINIMAL_CONTEXT_TOKEN_CEILING: usize = 32_000;
51
52const PARALLEL_TOOLS_LINE: &str = "- Run independent tools in parallel when inputs do not depend on each other.";
56
57const CODE_SEARCH_FILTER_LINE: &str = "- `code_search`: omit unused filters; no empty values (`path: \"\"`).";
60
61const REQUEST_USER_INPUT_LINE: &str =
64 "- Use `request_user_input` only for material blockers remaining after repository exploration.";
65
66const CAPABILITY_READ_ONLY_LINE: &str =
69 "- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.";
70
71const WRITE_STDIN_RECOVERY_CLAUSE: &str = "; if missing, recover prior output";
74
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.\n- VT Code does not translate GNU-to-BSD, BSD-to-GNU, Unix-to-PowerShell, or PowerShell-to-Unix command flags.";
78
79#[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
109struct ToolPresence {
112 exec: bool,
113 write_stdin: bool,
114 code_search: bool,
115 web_search: bool,
116 read_file: bool,
117 grep_file: bool,
118 list_files: bool,
119 apply_patch: bool,
120 request_user_input: bool,
121 task_tracker: bool,
122 start_planning: bool,
123 matrix: bool,
124 record_decision: bool,
125 session_messaging: bool,
126}
127
128impl ToolPresence {
129 fn of(available_tools: &[String]) -> Self {
130 let mut presence = Self {
134 exec: false,
135 write_stdin: false,
136 code_search: false,
137 web_search: false,
138 read_file: false,
139 grep_file: false,
140 list_files: false,
141 apply_patch: false,
142 request_user_input: false,
143 task_tracker: false,
144 start_planning: false,
145 matrix: false,
146 record_decision: false,
147 session_messaging: false,
148 };
149 for tool in available_tools {
150 match tool.as_str() {
151 TOOL_EXEC_COMMAND => presence.exec = true,
152 TOOL_WRITE_STDIN => presence.write_stdin = true,
153 TOOL_CODE_SEARCH => presence.code_search = true,
154 "web_search" => presence.web_search = true,
155 TOOL_READ_FILE => presence.read_file = true,
156 TOOL_GREP_FILE => presence.grep_file = true,
157 TOOL_LIST_FILES => presence.list_files = true,
158 TOOL_APPLY_PATCH => presence.apply_patch = true,
159 TOOL_REQUEST_USER_INPUT => presence.request_user_input = true,
160 TOOL_TASK_TRACKER => presence.task_tracker = true,
161 TOOL_START_PLANNING => presence.start_planning = true,
162 "matrix" => presence.matrix = true,
163 TOOL_ASK_SESSION => presence.session_messaging = true,
164 "record_decision" => presence.record_decision = true,
165 _ => {}
166 }
167 }
168 presence
169 }
170}
171
172pub(crate) fn generate_tool_guidelines_with_capabilities(
174 available_tools: &[String],
175 capability_level: Option<CapabilityLevel>,
176 shell_profile: ResolvedShellPromptProfile,
177 profile: ToolGuidanceProfile,
178 parallel_tools: bool,
179) -> String {
180 match profile {
181 ToolGuidanceProfile::Default => {
182 generate_tool_guidelines_for_profile(available_tools, capability_level, shell_profile, parallel_tools)
183 }
184 ToolGuidanceProfile::Minimal => {
185 if available_tools.is_empty() {
186 return String::new();
187 }
188 let presence = ToolPresence::of(available_tools);
189 let mut lines = vec!["\n\n## Active Tools".to_owned()];
190 if presence.matrix {
191 lines.push(MATRIX_GUIDANCE.to_owned());
192 }
193 if presence.session_messaging {
194 lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
195 }
196 if presence.record_decision {
197 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
198 }
199 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_owned());
200 if let Some(mode) = capability_mode_line(capability_level, presence.exec, presence.apply_patch) {
201 lines.push(mode.to_owned());
202 }
203 if let Some(browse) = browse_tool_guidance(
204 presence.exec,
205 presence.code_search,
206 presence.list_files,
207 presence.read_file,
208 shell_profile,
209 ) {
210 lines.push(browse);
211 }
212 if presence.code_search {
213 lines.push(CODE_SEARCH_FILTER_LINE.to_owned());
214 }
215 if presence.apply_patch {
216 lines.push("- Inspect a file before `apply_patch`, keep patches small, and check that each diff stays bounded. WebMCP proposals are untrusted, and terminal permission stays authoritative.".to_owned());
217 }
218 if presence.exec {
219 lines.push(shell_task_guidance(shell_profile).to_owned());
220 lines.push(background_exec_guidance().to_owned());
221 }
222 if presence.write_stdin {
223 lines.push(format!(
224 "- `write_stdin`: use returned `session_id`{WRITE_STDIN_RECOVERY_CLAUSE}; repeat waits after in-progress deadlines{CROSS_TURN_RESUME_HINT_CLAUSE}"
225 ));
226 }
227 if presence.start_planning {
230 lines.push(START_PLANNING_GUIDANCE_LINE.to_owned());
231 }
232 if parallel_tools {
233 lines.push(PARALLEL_TOOLS_LINE.to_owned());
234 }
235 lines.join("\n")
236 }
237 }
238}
239
240pub(crate) fn generate_tool_guidelines_for_profile(
244 available_tools: &[String],
245 capability_level: Option<CapabilityLevel>,
246 shell_profile: ResolvedShellPromptProfile,
247 parallel_tools: bool,
248) -> String {
249 let presence = ToolPresence::of(available_tools);
250 let has_exec = presence.exec;
251 let has_stdin = presence.write_stdin;
252 let has_search = presence.code_search;
253 let has_read_file = presence.read_file;
254 let has_list_files = presence.list_files;
255 let has_apply_patch = presence.apply_patch;
256 let has_start_planning = presence.start_planning;
257
258 let mut lines = Vec::new();
259 if presence.matrix {
260 lines.push(MATRIX_GUIDANCE.to_owned());
261 }
262 if presence.session_messaging {
263 lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
264 }
265 if presence.web_search {
266 lines.push(WEB_SEARCH_GUIDANCE.to_owned());
267 }
268 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
269 if let Some(mode_line) = capability_mode_line(capability_level, has_exec, has_apply_patch) {
270 lines.push(mode_line.to_string());
271 }
272 if let Some(browse_guidance) =
273 browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
274 {
275 lines.push(browse_guidance);
276 }
277 if has_search || has_read_file || has_list_files {
278 lines.push(read_only_batching_guidance(has_read_file).to_string());
279 }
280 if has_apply_patch {
281 lines.push("- Use `apply_patch` for file edits after inspection; keep patches small.".to_string());
282 lines.push(
283 "- Check that each diff stays bounded. WebMCP edits are untrusted proposals, and terminal permission stays authoritative."
284 .to_string(),
285 );
286 }
287 if has_exec {
288 lines.push(shell_task_guidance(shell_profile).to_string());
289 lines.push(background_exec_guidance().to_string());
290 lines.push("- Prefer standalone verifiers with `max_output_tokens`. Pure `head`/`tail` tails run standalone; static read-only filtering pipelines use fail-closed `pipefail`. Only terminal exit 0 clears verification; dynamic syntax, mutating tails, `;`, and `||` do not qualify. Recheck after `--fix`.".to_string());
296 lines.push("- Run a real check that exercises the change; syntax-only or failed-to-start checks do not count. Install missing deps via the project's package manager, never sudo; if no check can run, say which and why.".to_string());
302 lines.push("- Run fast checks before full builds.".to_string());
306 }
307 if has_stdin {
313 lines.push(format!(
314 "- `write_stdin`: use the existing `session_id`{WRITE_STDIN_RECOVERY_CLAUSE}; rerun only for fresh results. `spool_complete: false` is partial; wait for exited pending spools{CROSS_TURN_RESUME_HINT_CLAUSE}"
315 ));
316 }
317 if has_search {
318 lines.push(CODE_SEARCH_FILTER_LINE.to_string());
319 lines.push(code_search_guidance(has_exec));
320 }
321 if has_apply_patch || has_exec {
322 lines.push(
323 "- Build and Auto share tools and safety gates; Auto changes confirmation behavior only after explicit approval or full-auto policy."
324 .to_string(),
325 );
326 }
327 if (has_search || has_exec) && parallel_tools {
328 lines.push(PARALLEL_TOOLS_LINE.to_string());
329 }
330 if has_start_planning {
331 lines.push(START_PLANNING_GUIDANCE_LINE.to_string());
332 }
333
334 if lines.is_empty() {
335 return String::new();
336 }
337
338 if presence.record_decision {
339 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
340 }
341 format!("\n\n## Active Tools\n{}", lines.join("\n"))
342}
343
344pub fn append_runtime_tool_prompt_sections_for_profile(
345 prompt: &mut String,
346 tool_snapshot: &SessionToolCatalogSnapshot,
347 include_catalog_metadata: bool,
348 shell_profile: ResolvedShellPromptProfile,
349) {
350 let names = snapshot_tool_names(tool_snapshot);
351 append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile);
352}
353
354pub fn append_runtime_tool_prompt_sections_for_model(
356 prompt: &mut String,
357 tool_snapshot: &SessionToolCatalogSnapshot,
358 include_catalog_metadata: bool,
359 shell_profile: ResolvedShellPromptProfile,
360 provider: &dyn crate::llm::provider::LLMProvider,
361 model: &str,
362 config: Option<&crate::config::VTCodeConfig>,
363) {
364 let names = snapshot_tool_names(tool_snapshot);
365 let default_guidance =
366 append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile);
367 let pricing = crate::config::models::model_catalog_entry(provider.name(), model).map(|entry| entry.pricing);
368 let profile = ToolGuidanceProfile::resolve(
369 crate::compaction::effective_context_budget(config, provider, model),
370 vtcode_commons::estimate_tokens(prompt),
371 config.map_or(0, |cfg| cfg.agent.max_system_prompt_tokens as usize),
372 pricing.and_then(|price| price.input),
373 config.and_then(|cfg| cfg.agent.harness.max_budget_usd),
374 );
375 let parallel_tools = provider.supports_parallel_tool_config(model);
376 if tool_snapshot.planning_active && profile == ToolGuidanceProfile::Default {
379 return;
380 }
381 remove_prompt_section(prompt, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
382 let presence = ToolPresence::of(names);
383 let capability_level = Some(infer_capability_level_from_presence(&presence));
384 let mut guidance = match profile {
385 ToolGuidanceProfile::Default => {
386 let mut guidance = default_guidance;
387 if let (Some(original), Some(effective)) = (
388 capability_mode_line(None, presence.exec, presence.apply_patch),
389 capability_mode_line(capability_level, presence.exec, presence.apply_patch),
390 ) && original != effective
391 && let Some(start) = guidance.find(original)
392 {
393 guidance.replace_range(start..start + original.len(), effective);
394 }
395 if !parallel_tools && let Some(start) = guidance.find(PARALLEL_TOOLS_LINE) {
396 guidance.replace_range(start.saturating_sub(1)..start + PARALLEL_TOOLS_LINE.len(), "");
397 }
398 guidance
399 }
400 ToolGuidanceProfile::Minimal => {
401 generate_tool_guidelines_with_capabilities(names, capability_level, shell_profile, profile, parallel_tools)
402 }
403 };
404 if tool_snapshot.planning_active {
405 append_minimal_planning_addendum(&mut guidance, &presence);
406 }
407 append_prompt_block(prompt, guidance.trim_start_matches('\n'));
408}
409
410fn append_runtime_tool_sections_with_names(
414 prompt: &mut String,
415 tool_snapshot: &SessionToolCatalogSnapshot,
416 names: &[String],
417 include_catalog_metadata: bool,
418 shell_profile: ResolvedShellPromptProfile,
419) -> String {
420 remove_prompt_section(prompt, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
421 remove_prompt_section(prompt, "[Runtime Tool Catalog]", SectionBoundaryMode::BracketOrMarkdown);
422 trim_trailing_newlines(prompt);
423
424 let guidelines = generate_runtime_tool_guidelines_for_profile(names, tool_snapshot.planning_active, shell_profile);
425 if !guidelines.is_empty() {
426 append_prompt_block(prompt, guidelines.trim_start_matches('\n'));
427 }
428
429 if include_catalog_metadata && tool_snapshot.snapshot.is_some() {
430 let active_tools = if tool_snapshot.active_tool_names.is_empty() {
431 "none".to_string()
432 } else {
433 tool_snapshot.active_tool_names.join(", ")
434 };
435 let catalog_metadata = format!(
436 "[Runtime Tool Catalog]\n- version: {}\n- epoch: {}\n- catalog_tools: {}\n- available_tools: {}\n- currently_available_tools: {}\n- request_user_input_enabled: {}",
437 tool_snapshot.version,
438 tool_snapshot.epoch,
439 tool_snapshot.catalog_tools(),
440 tool_snapshot.available_tools(),
441 active_tools,
442 tool_snapshot.request_user_input_enabled,
443 );
444 append_prompt_block(prompt, &catalog_metadata);
445 }
446 guidelines
447}
448
449fn append_minimal_planning_addendum(guidance: &mut String, presence: &ToolPresence) {
452 guidance.push_str("\n- Planning is read-only.");
453 let mut read_tools = Vec::with_capacity(4);
454 if presence.read_file {
455 read_tools.push(TOOL_READ_FILE);
456 }
457 if presence.grep_file {
458 read_tools.push(TOOL_GREP_FILE);
459 }
460 if presence.code_search {
461 read_tools.push(TOOL_CODE_SEARCH);
462 }
463 if presence.list_files {
464 read_tools.push(TOOL_LIST_FILES);
465 }
466 guidance.push_str("\n- Keep inspections small: ");
467 if !read_tools.is_empty() {
468 guidance.push_str(&format!("prefer `{}` over `exec_command` shell reads; ", read_tools.join("`/`")));
469 }
470 guidance.push_str("keep `max_output_tokens` small, avoid batching multiple large inspections in parallel; start git history with `git log --oneline` before targeted `git show --stat`.");
471 if presence.task_tracker {
472 guidance.push('\n');
473 guidance.push_str(PLANNING_TASK_TRACKER_COMPACT_LINE);
474 }
475 if presence.request_user_input {
476 guidance.push('\n');
477 guidance.push_str(REQUEST_USER_INPUT_LINE);
478 }
479}
480
481pub fn append_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
489 remove_prompt_section(prompt, "[Deferred Tools]", SectionBoundaryMode::BracketOrMarkdown);
490
491 let mut groups: Vec<_> = tool_groups(tools)
492 .into_iter()
493 .filter(|group| group.deferred_count > 0)
494 .collect();
495 let overflow = groups.len().saturating_sub(DEFERRED_TOOLS_MAX_GROUPS);
496 groups.truncate(DEFERRED_TOOLS_MAX_GROUPS);
497
498 let mut lines: Vec<String> = groups
499 .into_iter()
500 .map(|group| {
501 let description = truncate_deferred_description(group.description.as_deref().unwrap_or_default());
502 format!("- {} ({} tools): {}", group.name, group.deferred_count, description)
503 })
504 .collect();
505 if overflow > 0 {
506 lines.push(format!("(+{overflow} more deferred groups available — use `search_tools` to find them)"));
507 }
508
509 let unnamespaced_deferred = tools
510 .iter()
511 .filter(|tool| tool.namespace.is_none() && tool.defer_loading == Some(true))
512 .count();
513 if unnamespaced_deferred > 0 {
514 lines.push(format!("- {unnamespaced_deferred} additional deferred tools"));
515 }
516
517 if lines.is_empty() {
518 return;
519 }
520
521 let section = format!(
522 "[Deferred Tools]\n{}\nUse `search_tools` to find a deferred capability. Selected definitions become available in the next request segment.",
523 lines.join("\n")
524 );
525 append_prompt_block(prompt, §ion);
526}
527
528const DEFERRED_TOOLS_MAX_GROUPS: usize = 8;
531const DEFERRED_TOOLS_MAX_DESC_CHARS: usize = 120;
534
535fn truncate_deferred_description(description: &str) -> String {
536 let mut chars = description.chars();
539 let truncated: String = chars.by_ref().take(DEFERRED_TOOLS_MAX_DESC_CHARS).collect();
540 if chars.next().is_none() {
541 return description.to_string();
542 }
543 format!("{}...", truncated.trim_end())
544}
545
546fn generate_runtime_tool_guidelines_for_profile(
547 available_tools: &[String],
548 planning_active: bool,
549 shell_profile: ResolvedShellPromptProfile,
550) -> String {
551 if !planning_active {
552 return generate_tool_guidelines_for_profile(available_tools, None, shell_profile, true);
556 }
557
558 let presence = ToolPresence::of(available_tools);
559 let has_exec = presence.exec;
560 let has_search = presence.code_search;
561 let has_read_file = presence.read_file;
562 let has_list_files = presence.list_files;
563 let has_request_user_input = presence.request_user_input;
564 let has_task_tracker = presence.task_tracker;
565
566 let mut lines = vec!["- Planning workflow active: stay within the read-safe tool list.".to_string()];
567 if presence.web_search {
568 lines.push(WEB_SEARCH_GUIDANCE.to_owned());
569 }
570 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
571 if let Some(browse_guidance) =
572 browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
573 {
574 lines.push(browse_guidance);
575 }
576 if has_exec {
577 lines.push("- In Planning workflow, use `exec_command` only for read-only verification.".to_string());
578 }
579 if has_search {
580 lines.push(CODE_SEARCH_FILTER_LINE.to_string());
581 }
582 if has_task_tracker {
583 lines.push("- Keep `task_tracker` updated as you refine the plan. Indexed updates return totals and the changed item; use action=list for the full checklist.".to_string());
584 lines.push("- Keep blockers and verification open in `task_tracker` until resolved.".to_string());
585 lines.push(PLANNING_TASK_TRACKER_INDEX_LINE.to_string());
586 }
587 if has_request_user_input {
588 lines.push(REQUEST_USER_INPUT_LINE.to_string());
589 }
590 if has_search || has_exec {
591 lines.push("- If calls repeat without progress, tighten the plan instead of retrying identically.".to_string());
592 }
593 if presence.record_decision {
594 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
595 }
596
597 format!("\n\n## Active Tools\n{}", lines.join("\n"))
598}
599
600fn snapshot_tool_names(tool_snapshot: &SessionToolCatalogSnapshot) -> &[String] {
601 &tool_snapshot.active_tool_names
602}
603
604fn browse_tool_guidance(
605 has_exec: bool,
606 has_search: bool,
607 has_list_files: bool,
608 has_read_file: bool,
609 shell_profile: ResolvedShellPromptProfile,
610) -> Option<String> {
611 if has_exec {
612 return Some(shell_browse_guidance(shell_profile, has_search));
613 }
614
615 if !(has_search || has_list_files || has_read_file) {
616 return None;
617 }
618
619 Some("- Use available read-only repository tools for browsing; do not modify files.".to_string())
620}
621
622pub(crate) fn render_shell_profile_guidance(shell_profile: ResolvedShellPromptProfile) -> String {
623 let profile_lines = match shell_profile {
624 ResolvedShellPromptProfile::UnixLike => {
625 "- Active shell profile: `unix_like`. Use Unix-like command syntax in `exec_command.cmd`, for example `ls`, `rg`, `find`, `cat`, `sed`, and `awk`.\n- On macOS, write BSD-compatible flags for BSD tools. VT Code does not rewrite GNU flags for macOS BSD tools."
626 }
627 ResolvedShellPromptProfile::PowerShell => {
628 "- Active shell profile: `powershell`. Use native PowerShell syntax in `exec_command.cmd`, for example `Get-ChildItem`, `Select-String`, `Get-Content`, and `Where-Object`.\n- On native Windows, use WSL when you need Unix-like workflows or Unix command examples."
629 }
630 };
631 format!("## Shell Profile\n{profile_lines}\n{SHELL_PROFILE_POLICY_SUFFIX}")
632}
633
634fn shell_browse_guidance(shell_profile: ResolvedShellPromptProfile, has_search: bool) -> String {
635 const SEARCH_PREFERENCE_UNIX: &str = " Prefer `code_search` over `rg`/`grep` for code.";
640 const SEARCH_PREFERENCE_POWERSHELL: &str = " Prefer `code_search` over `Select-String` for code.";
641 match shell_profile {
642 ResolvedShellPromptProfile::UnixLike => {
643 let mut line = String::from("- Use `exec_command.cmd` with `ls`, ");
644 if !has_search {
645 line.push_str("`rg`, ");
646 }
647 line.push_str("`find`, `cat`, `sed`, and `awk` for repository browsing.");
648 if has_search {
649 line.push_str(SEARCH_PREFERENCE_UNIX);
650 }
651 line
652 }
653 ResolvedShellPromptProfile::PowerShell => {
654 let mut line = "- Use `exec_command.cmd` with native PowerShell commands such as `Get-ChildItem`, `Select-String`, `Get-Content`, and `Where-Object` for repository browsing.".to_string();
655 if has_search {
656 line.push_str(SEARCH_PREFERENCE_POWERSHELL);
657 }
658 line
659 }
660 }
661}
662
663fn shell_task_guidance(shell_profile: ResolvedShellPromptProfile) -> &'static str {
664 match shell_profile {
665 ResolvedShellPromptProfile::UnixLike => {
666 "- Use `exec_command.cmd` for build tools, test tools, `git diff -- <path>`, and shell-only tasks. In one-shot `exec_command` calls, do not use `!!`, `!$`, `!ssh`, or `fc`; write full command arguments explicitly from conversation or tool results. Interactive shells: review-safe history expansion (Bash `histverify`, zsh `HIST_VERIFY`)."
667 }
668 ResolvedShellPromptProfile::PowerShell => {
669 "- Use `exec_command.cmd` for build tools, test tools, `git diff -- <path>`, and shell-only tasks using native PowerShell syntax."
670 }
671 }
672}
673
674fn background_exec_guidance() -> &'static str {
675 "- For long-lived commands, set `background: true` on `exec_command`; it returns a bounded preview plus a stable `session_id` and wait arguments. At most three live background processes are retained per runtime, with no automatic eviction; `write_stdin` drives the session lifecycle."
676}
677
678fn read_only_batching_guidance(has_read_file: bool) -> &'static str {
679 if has_read_file {
680 "- Batch independent read-only calls; use bounded `read_file` ranges, order dependencies, serialize mutations; narrow the range on `line_truncated`; prefer wider windows and reuse evidence over overlapping slices."
681 } else {
682 "- Batch independent read-only calls; order dependent reads, and serialize mutations."
683 }
684}
685
686fn code_search_guidance(has_exec: bool) -> String {
687 const BASE: &str = "- Advanced `code_search` takes `query`; filters `path`, `file_types`, `result_types`, `max_results`; results: definitions, exact syntactic usages. Queries use literal smart-case and `|`-separated literals; truncated: narrow; unavailable: do not retry identical, drop `file_types`/broaden `path`. Example: `{\"query\":\"TurnLoop\",\"path\":\"src\",\"result_types\":[\"definition\"]}`. Do not JSON-encode arrays or integers as strings. Prefer `code_search` over `rg` on `.vtcode/context/tool_outputs/`.";
688 if has_exec {
689 format!("{BASE} Use `exec_command` or a skill for syntax patterns.")
690 } else {
691 BASE.to_string()
692 }
693}
694
695fn capability_mode_line(
696 capability_level: Option<CapabilityLevel>,
697 has_exec: bool,
698 has_file: bool,
699) -> Option<&'static str> {
700 match capability_level {
701 Some(CapabilityLevel::Basic) => {
702 Some("- Capabilities: limited. Ask the user to enable more capabilities if file work is required.")
703 }
704 Some(CapabilityLevel::FileReading | CapabilityLevel::FileListing) => Some(CAPABILITY_READ_ONLY_LINE),
705 _ if !has_exec && !has_file => Some(CAPABILITY_READ_ONLY_LINE),
706 _ => None,
707 }
708}
709
710pub(crate) fn infer_capability_level(available_tools: &[String]) -> CapabilityLevel {
712 infer_capability_level_from_presence(&ToolPresence::of(available_tools))
713}
714
715fn infer_capability_level_from_presence(presence: &ToolPresence) -> CapabilityLevel {
716 if presence.code_search {
717 CapabilityLevel::CodeSearch
718 } else if presence.apply_patch {
719 CapabilityLevel::Editing
720 } else if presence.exec {
721 CapabilityLevel::Bash
722 } else if presence.list_files {
723 CapabilityLevel::FileListing
724 } else if presence.read_file {
725 CapabilityLevel::FileReading
726 } else {
727 CapabilityLevel::Basic
728 }
729}
730
731#[cfg(test)]
732mod tests;