1use crate::config::constants::tools;
2use crate::config::types::{CapabilityLevel, ResolvedShellPromptProfile};
3use crate::core::agent::harness_kernel::SessionToolCatalogSnapshot;
4use crate::llm::provider::ToolDefinition;
5use crate::prompts::sections::{
6 SectionBoundaryMode, append_prompt_block, remove_prompt_section, remove_prompt_section_after,
7 trim_trailing_newlines,
8};
9use crate::tools::registry::tool_groups;
10
11const TOOL_EXEC_COMMAND: &str = tools::EXEC_COMMAND;
12const TOOL_WRITE_STDIN: &str = tools::WRITE_STDIN;
13const TOOL_CODE_SEARCH: &str = tools::CODE_SEARCH;
14const TOOL_READ_FILE: &str = tools::READ_FILE;
15const TOOL_LIST_FILES: &str = tools::LIST_FILES;
16const TOOL_GREP_FILE: &str = tools::GREP_FILE;
17const TOOL_APPLY_PATCH: &str = tools::APPLY_PATCH;
18const TOOL_REQUEST_USER_INPUT: &str = tools::REQUEST_USER_INPUT;
19const TOOL_ASK_SESSION: &str = tools::ASK_SESSION;
20const TOOL_TASK_TRACKER: &str = tools::TASK_TRACKER;
21const TOOL_COMPUTER_USE: &str = tools::COMPUTER_USE;
22const PUBLIC_DECISION_GUIDANCE: &str = "- Use optional `record_decision` for consequential choices, rejected approaches, or recovery changes. Give concise public rationale; ordinary reads and commands need no record.";
23const MATRIX_GUIDANCE: &str = "- `matrix`: create persists explicit tasks, checks, resources, and timeouts; start freezes the spec. The coordinator delegates execution and verification to scheduler-owned workers; discovery is idle-only. Replay restores admission before discovery; resume reconciles owned cleanup. status is a projection; pause stops dispatch; user cancel is terminal. Internal failures require reconciliation, not cancellation. Workers retain effective permissions and sandbox gates. Read leases require read-only workers. Report identity is runtime-owned; final success needs durable declared checks for the current generation, never summaries or child completion. Source and declared input changes, including submodule state, invalidate checks. Automatic retry requires replay_safe, confirmed cleanup, and at most one interrupted/timeout retry; other failures need a coordinator decision.";
24const SESSION_MESSAGING_GUIDANCE: &str = "- Peer sessions: `list_sessions` discovers live CLI sessions in this workspace; `ask_session` sends one a question and its `answer_session` reply arrives as a notice on a later turn. Delivery needs the peer running.";
25const WEB_SEARCH_GUIDANCE: &str = "- web_search uses keyless DuckDuckGo; web_fetch needs separate approval. For `antiban_blocked` or `retryable: false`, do not retry; wait `retry_after_ms` for `cooldown`; retry `network_error`/`upstream_error` once. For GitHub queries prefer `gh search`/`gh api` via exec_command when available.";
26const COMPUTER_USE_GUIDANCE: &str = "- `computer_use`: when the user asks to see, screenshot, or operate the isolated browser preview, call it with one screen-sized browser task instead of exploring code or shelling around; each turn asks approval before acting and reports only a redacted summary. Never for local files, shells, or secrets entry. For external pages, local servers, or desktop apps instead, use the shell (headless browser for pages; native tools for desktop): v1 is preview-only, with no network access.";
27
28const TOOL_START_PLANNING: &str = tools::START_PLANNING;
29
30const OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE: &str = "- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.";
31
32const START_PLANNING_GUIDANCE_LINE: &str = "- For demanding, ambiguous, or multi-phase tasks, call `start_planning`; it asks the user before entering the read-only Planning workflow unless the session runs in full-auto or skips confirmations. Skip it for straightforward changes.";
37
38const PLANNING_TASK_TRACKER_LINE: &str = "- `task_tracker`: keep blockers and verification open. `scope_review` checks cannot satisfy functional `verify` checks.";
48
49const MINIMAL_CONTEXT_TOKEN_CEILING: usize = 32_000;
52
53const PARALLEL_TOOLS_LINE: &str = "- Run independent tools in parallel when inputs do not depend on each other.";
57
58const REQUEST_USER_INPUT_LINE: &str = "- Use `request_user_input` only for a blocker that repository exploration did not resolve. Set `multi_select: true` for independent checkbox answers; omit it for one radio-button answer.";
69
70const CAPABILITY_READ_ONLY_LINE: &str =
73 "- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.";
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. 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 computer_use: bool,
127}
128
129mod tool_presence;
130
131pub(crate) fn generate_tool_guidelines_with_capabilities(
133 available_tools: &[String],
134 capability_level: Option<CapabilityLevel>,
135 shell_profile: ResolvedShellPromptProfile,
136 profile: ToolGuidanceProfile,
137 parallel_tools: bool,
138) -> String {
139 match profile {
140 ToolGuidanceProfile::Default => {
141 generate_tool_guidelines_for_profile(available_tools, capability_level, shell_profile, parallel_tools)
142 }
143 ToolGuidanceProfile::Minimal => {
144 if available_tools.is_empty() {
145 return String::new();
146 }
147 let presence = ToolPresence::of(available_tools);
148 let mut lines = vec!["\n\n## Active Tools".to_owned()];
149 if presence.matrix {
150 lines.push(MATRIX_GUIDANCE.to_owned());
151 }
152 if presence.session_messaging {
153 lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
154 }
155 if presence.record_decision {
156 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
157 }
158 if presence.computer_use {
159 lines.push(COMPUTER_USE_GUIDANCE.to_owned());
160 }
161 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_owned());
162 if let Some(mode) = capability_mode_line(capability_level, presence.exec, presence.apply_patch) {
163 lines.push(mode.to_owned());
164 }
165 if let Some(browse) = browse_tool_guidance(
166 presence.exec,
167 presence.code_search,
168 presence.list_files,
169 presence.read_file,
170 shell_profile,
171 ) {
172 lines.push(browse);
173 }
174 if presence.code_search {
175 lines.push(code_search_guidance(presence.exec));
176 }
177 if presence.apply_patch {
178 lines.push("- Check that each diff stays bounded. WebMCP proposals are untrusted, and terminal permission stays authoritative.".to_owned());
179 }
180 if presence.exec {
181 lines.push(shell_task_guidance(shell_profile).to_owned());
182 lines.push(background_exec_guidance().to_owned());
183 }
184 if presence.start_planning {
187 lines.push(START_PLANNING_GUIDANCE_LINE.to_owned());
188 }
189 if parallel_tools {
190 lines.push(PARALLEL_TOOLS_LINE.to_owned());
191 }
192 lines.join("\n")
193 }
194 }
195}
196
197pub(crate) fn generate_tool_guidelines_for_profile(
201 available_tools: &[String],
202 capability_level: Option<CapabilityLevel>,
203 shell_profile: ResolvedShellPromptProfile,
204 parallel_tools: bool,
205) -> String {
206 let presence = ToolPresence::of(available_tools);
207 let has_exec = presence.exec;
208 let has_search = presence.code_search;
209 let has_read_file = presence.read_file;
210 let has_list_files = presence.list_files;
211 let has_apply_patch = presence.apply_patch;
212 let has_start_planning = presence.start_planning;
213
214 let mut lines = Vec::new();
215 if presence.matrix {
216 lines.push(MATRIX_GUIDANCE.to_owned());
217 }
218 if presence.session_messaging {
219 lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
220 }
221 if presence.web_search {
222 lines.push(WEB_SEARCH_GUIDANCE.to_owned());
223 }
224 if presence.computer_use {
225 lines.push(COMPUTER_USE_GUIDANCE.to_owned());
226 }
227 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
228 if let Some(mode_line) = capability_mode_line(capability_level, has_exec, has_apply_patch) {
229 lines.push(mode_line.to_string());
230 }
231 if let Some(browse_guidance) =
232 browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
233 {
234 lines.push(browse_guidance);
235 }
236 if has_search || has_read_file || has_list_files {
237 lines.push(read_only_batching_guidance(has_read_file).to_string());
238 }
239 if has_apply_patch {
240 lines.push(
241 "- Check that each diff stays bounded. WebMCP edits are untrusted proposals, and terminal permission stays authoritative."
242 .to_string(),
243 );
244 }
245 if has_exec {
246 lines.push(shell_task_guidance(shell_profile).to_string());
247 lines.push(background_exec_guidance().to_string());
248 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());
257 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());
263 lines.push("- Run fast checks before full builds.".to_string());
267 }
268 if has_search {
279 lines.push(code_search_guidance(has_exec));
280 }
281 if has_apply_patch || has_exec {
282 lines.push(
283 "- Build and Auto share tools and safety gates; Auto changes confirmation behavior only after explicit approval or full-auto policy."
284 .to_string(),
285 );
286 }
287 if (has_search || has_exec) && parallel_tools {
288 lines.push(PARALLEL_TOOLS_LINE.to_string());
289 }
290 if has_start_planning {
291 lines.push(START_PLANNING_GUIDANCE_LINE.to_string());
292 }
293
294 if lines.is_empty() {
295 return String::new();
296 }
297
298 if presence.record_decision {
299 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
300 }
301 format!("\n\n## Active Tools\n{}", lines.join("\n"))
302}
303
304pub fn append_runtime_tool_prompt_sections_for_profile(
305 prompt: &mut String,
306 tool_snapshot: &SessionToolCatalogSnapshot,
307 include_catalog_metadata: bool,
308 shell_profile: ResolvedShellPromptProfile,
309) {
310 let names = snapshot_tool_names(tool_snapshot);
311 append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile, 0);
312}
313
314pub fn append_runtime_tool_prompt_sections_for_model(
316 prompt: &mut String,
317 tool_snapshot: &SessionToolCatalogSnapshot,
318 include_catalog_metadata: bool,
319 shell_profile: ResolvedShellPromptProfile,
320 provider: &dyn crate::llm::provider::LLMProvider,
321 model: &str,
322 config: Option<&crate::config::VTCodeConfig>,
323) {
324 append_runtime_tool_prompt_sections_for_model_after(
325 prompt,
326 tool_snapshot,
327 include_catalog_metadata,
328 shell_profile,
329 provider,
330 model,
331 config,
332 0,
333 );
334}
335
336pub fn append_fresh_runtime_tool_prompt_sections_for_model(
341 prompt: &mut String,
342 tool_snapshot: &SessionToolCatalogSnapshot,
343 include_catalog_metadata: bool,
344 shell_profile: ResolvedShellPromptProfile,
345 provider: &dyn crate::llm::provider::LLMProvider,
346 model: &str,
347 config: Option<&crate::config::VTCodeConfig>,
348) {
349 let boundary = prompt.len();
350 append_runtime_tool_prompt_sections_for_model_after(
351 prompt,
352 tool_snapshot,
353 include_catalog_metadata,
354 shell_profile,
355 provider,
356 model,
357 config,
358 boundary,
359 );
360}
361
362fn append_runtime_tool_prompt_sections_for_model_after(
363 prompt: &mut String,
364 tool_snapshot: &SessionToolCatalogSnapshot,
365 include_catalog_metadata: bool,
366 shell_profile: ResolvedShellPromptProfile,
367 provider: &dyn crate::llm::provider::LLMProvider,
368 model: &str,
369 config: Option<&crate::config::VTCodeConfig>,
370 boundary: usize,
371) {
372 let names = snapshot_tool_names(tool_snapshot);
373 let default_guidance = append_runtime_tool_sections_with_names(
374 prompt,
375 tool_snapshot,
376 names,
377 include_catalog_metadata,
378 shell_profile,
379 boundary,
380 );
381 let pricing = crate::config::models::model_catalog_entry(provider.name(), model).map(|entry| entry.pricing);
382 let profile = ToolGuidanceProfile::resolve(
383 crate::compaction::effective_context_budget(config, provider, model),
384 vtcode_commons::estimate_tokens(prompt),
385 config.map_or(0, |cfg| cfg.agent.max_system_prompt_tokens as usize),
386 pricing.and_then(|price| price.input),
387 config.and_then(|cfg| cfg.agent.harness.max_budget_usd),
388 );
389 let parallel_tools = provider.supports_parallel_tool_config(model);
390 if tool_snapshot.planning_active && profile == ToolGuidanceProfile::Default {
393 return;
394 }
395 remove_prompt_section_after(prompt, boundary, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
396 let presence = ToolPresence::of(names);
397 let capability_level = Some(infer_capability_level_from_presence(&presence));
398 let mut guidance = match profile {
399 ToolGuidanceProfile::Default => {
400 let mut guidance = default_guidance;
401 if let (Some(original), Some(effective)) = (
402 capability_mode_line(None, presence.exec, presence.apply_patch),
403 capability_mode_line(capability_level, presence.exec, presence.apply_patch),
404 ) && original != effective
405 && let Some(start) = guidance.find(original)
406 {
407 guidance.replace_range(start..start + original.len(), effective);
408 }
409 if !parallel_tools && let Some(start) = guidance.find(PARALLEL_TOOLS_LINE) {
410 guidance.replace_range(start.saturating_sub(1)..start + PARALLEL_TOOLS_LINE.len(), "");
411 }
412 guidance
413 }
414 ToolGuidanceProfile::Minimal => {
415 generate_tool_guidelines_with_capabilities(names, capability_level, shell_profile, profile, parallel_tools)
416 }
417 };
418 if tool_snapshot.planning_active {
419 append_minimal_planning_addendum(&mut guidance, &presence);
420 }
421 append_prompt_block(prompt, guidance.trim_start_matches('\n'));
422}
423
424fn append_runtime_tool_sections_with_names(
428 prompt: &mut String,
429 tool_snapshot: &SessionToolCatalogSnapshot,
430 names: &[String],
431 include_catalog_metadata: bool,
432 shell_profile: ResolvedShellPromptProfile,
433 boundary: usize,
434) -> String {
435 remove_prompt_section_after(prompt, boundary, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
436 remove_prompt_section_after(prompt, boundary, "[Runtime Tool Catalog]", SectionBoundaryMode::BracketOrMarkdown);
437 if boundary == 0 {
438 trim_trailing_newlines(prompt);
439 }
440
441 let guidelines = generate_runtime_tool_guidelines_for_profile(names, tool_snapshot.planning_active, shell_profile);
442 if !guidelines.is_empty() {
443 append_prompt_block(prompt, guidelines.trim_start_matches('\n'));
444 }
445
446 if include_catalog_metadata && tool_snapshot.snapshot.is_some() {
447 let active_tools = if tool_snapshot.active_tool_names.is_empty() {
448 "none".to_string()
449 } else {
450 tool_snapshot.active_tool_names.join(", ")
451 };
452 let catalog_metadata = format!(
457 "[Runtime Tool Catalog]\n- version: {}; epoch: {}; catalog_tools: {}; available_tools: {}; currently_available_tools: {}; request_user_input_enabled: {}",
458 tool_snapshot.version,
459 tool_snapshot.epoch,
460 tool_snapshot.catalog_tools(),
461 tool_snapshot.available_tools(),
462 active_tools,
463 tool_snapshot.request_user_input_enabled,
464 );
465 append_prompt_block(prompt, &catalog_metadata);
466 }
467 guidelines
468}
469
470fn append_minimal_planning_addendum(guidance: &mut String, presence: &ToolPresence) {
473 guidance.push_str("\n- Planning is read-only.");
474 let mut read_tools = Vec::with_capacity(4);
475 if presence.read_file {
476 read_tools.push(TOOL_READ_FILE);
477 }
478 if presence.grep_file {
479 read_tools.push(TOOL_GREP_FILE);
480 }
481 if presence.code_search {
482 read_tools.push(TOOL_CODE_SEARCH);
483 }
484 if presence.list_files {
485 read_tools.push(TOOL_LIST_FILES);
486 }
487 guidance.push_str("\n- Keep inspections small: ");
488 if !read_tools.is_empty() {
489 guidance.push_str(&format!("prefer `{}` over `exec_command` shell reads; ", read_tools.join("`/`")));
490 }
491 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`.");
492 if presence.task_tracker {
493 guidance.push('\n');
494 guidance.push_str(PLANNING_TASK_TRACKER_LINE);
495 }
496 if presence.request_user_input {
497 guidance.push('\n');
498 guidance.push_str(REQUEST_USER_INPUT_LINE);
499 }
500}
501
502pub fn append_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
510 remove_prompt_section(prompt, "[Deferred Tools]", SectionBoundaryMode::BracketOrMarkdown);
511 append_fresh_deferred_tools_prompt_section(prompt, tools);
512}
513
514pub fn append_fresh_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
517 let mut groups: Vec<_> = tool_groups(tools)
518 .into_iter()
519 .filter(|group| group.deferred_count > 0)
520 .collect();
521 let overflow = groups.len().saturating_sub(DEFERRED_TOOLS_MAX_GROUPS);
522 groups.truncate(DEFERRED_TOOLS_MAX_GROUPS);
523
524 let mut lines: Vec<String> = groups
525 .into_iter()
526 .map(|group| {
527 let description = truncate_deferred_description(group.description.as_deref().unwrap_or_default());
528 format!("- {} ({} tools): {}", group.name, group.deferred_count, description)
529 })
530 .collect();
531 if overflow > 0 {
532 lines.push(format!("(+{overflow} more deferred groups available — use `search_tools` to find them)"));
533 }
534
535 let unnamespaced_deferred = tools
536 .iter()
537 .filter(|tool| tool.namespace.is_none() && tool.defer_loading == Some(true))
538 .count();
539 if unnamespaced_deferred > 0 {
540 lines.push(format!("- {unnamespaced_deferred} additional deferred tools"));
541 }
542
543 if lines.is_empty() {
544 return;
545 }
546
547 let section = format!(
548 "[Deferred Tools]\n{}\nUse `search_tools` to find a deferred capability. Selected definitions become available in the next request segment.",
549 lines.join("\n")
550 );
551 append_prompt_block(prompt, §ion);
552}
553
554const DEFERRED_TOOLS_MAX_GROUPS: usize = 8;
557const DEFERRED_TOOLS_MAX_DESC_CHARS: usize = 120;
560
561fn truncate_deferred_description(description: &str) -> String {
562 let mut chars = description.chars();
565 let truncated: String = chars.by_ref().take(DEFERRED_TOOLS_MAX_DESC_CHARS).collect();
566 if chars.next().is_none() {
567 return description.to_string();
568 }
569 format!("{}...", truncated.trim_end())
570}
571
572fn generate_runtime_tool_guidelines_for_profile(
573 available_tools: &[String],
574 planning_active: bool,
575 shell_profile: ResolvedShellPromptProfile,
576) -> String {
577 if !planning_active {
578 return generate_tool_guidelines_for_profile(available_tools, None, shell_profile, true);
582 }
583
584 let presence = ToolPresence::of(available_tools);
585 let has_exec = presence.exec;
586 let has_search = presence.code_search;
587 let has_read_file = presence.read_file;
588 let has_list_files = presence.list_files;
589 let has_request_user_input = presence.request_user_input;
590 let has_task_tracker = presence.task_tracker;
591
592 let mut lines = vec!["- Planning workflow active: stay within the read-safe tool list.".to_string()];
593 if presence.web_search {
594 lines.push(WEB_SEARCH_GUIDANCE.to_owned());
595 }
596 lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
597 if let Some(browse_guidance) =
598 browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
599 {
600 lines.push(browse_guidance);
601 }
602 if has_exec {
603 lines.push("- In Planning workflow, use `exec_command` only for read-only verification.".to_string());
604 }
605 if has_search {
606 lines.push(code_search_guidance(has_exec));
607 }
608 if has_task_tracker {
609 lines.push(PLANNING_TASK_TRACKER_LINE.to_string());
615 }
616 if has_request_user_input {
617 lines.push(REQUEST_USER_INPUT_LINE.to_string());
618 }
619 if has_search || has_exec {
620 lines.push("- If calls repeat without progress, tighten the plan instead of retrying identically.".to_string());
621 }
622 if presence.record_decision {
623 lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
624 }
625
626 format!("\n\n## Active Tools\n{}", lines.join("\n"))
627}
628
629fn snapshot_tool_names(tool_snapshot: &SessionToolCatalogSnapshot) -> &[String] {
630 &tool_snapshot.active_tool_names
631}
632
633fn browse_tool_guidance(
634 has_exec: bool,
635 has_search: bool,
636 has_list_files: bool,
637 has_read_file: bool,
638 shell_profile: ResolvedShellPromptProfile,
639) -> Option<String> {
640 if has_exec {
641 return Some(shell_browse_guidance(shell_profile, has_search));
642 }
643
644 if !(has_search || has_list_files || has_read_file) {
645 return None;
646 }
647
648 Some("- Use available read-only repository tools for browsing; do not modify files.".to_string())
649}
650
651pub(crate) fn render_shell_profile_guidance(shell_profile: ResolvedShellPromptProfile) -> String {
652 let profile_lines = match shell_profile {
653 ResolvedShellPromptProfile::UnixLike => {
654 "- 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."
655 }
656 ResolvedShellPromptProfile::PowerShell => {
657 "- Active shell profile: `powershell`.\n- On native Windows, use WSL when you need Unix-like workflows or Unix command examples."
658 }
659 };
660 format!("## Shell Profile\n{profile_lines}\n{SHELL_PROFILE_POLICY_SUFFIX}")
661}
662
663fn shell_browse_guidance(shell_profile: ResolvedShellPromptProfile, has_search: bool) -> String {
664 const SEARCH_PREFERENCE_UNIX: &str = " Prefer `code_search` over `rg`/`grep` for code.";
669 const SEARCH_PREFERENCE_POWERSHELL: &str = " Prefer `code_search` over `Select-String` for code.";
670 match shell_profile {
671 ResolvedShellPromptProfile::UnixLike => {
672 let mut line = String::from("- Browse the repository with `exec_command.cmd`.");
673 if has_search {
674 line.push_str(SEARCH_PREFERENCE_UNIX);
675 }
676 line
677 }
678 ResolvedShellPromptProfile::PowerShell => {
679 let mut line = "- Browse the repository with `exec_command.cmd`.".to_string();
680 if has_search {
681 line.push_str(SEARCH_PREFERENCE_POWERSHELL);
682 }
683 line
684 }
685 }
686}
687
688fn shell_task_guidance(shell_profile: ResolvedShellPromptProfile) -> &'static str {
689 match shell_profile {
690 ResolvedShellPromptProfile::UnixLike => {
691 "- 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`)."
692 }
693 ResolvedShellPromptProfile::PowerShell => {
694 "- Use native PowerShell syntax in `exec_command.cmd` for shell-only tasks."
695 }
696 }
697}
698
699fn background_exec_guidance() -> &'static str {
700 "- For long-lived commands, start them in the background rather than blocking a turn."
706}
707
708fn read_only_batching_guidance(has_read_file: bool) -> &'static str {
709 if has_read_file {
710 "- 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."
711 } else {
712 "- Batch independent read-only calls; order dependent reads, and serialize mutations."
713 }
714}
715
716fn code_search_guidance(has_exec: bool) -> String {
717 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.";
725 if has_exec {
726 format!("{BASE} Use `exec_command` or a skill for syntax patterns.")
727 } else {
728 BASE.to_string()
729 }
730}
731
732fn capability_mode_line(
733 capability_level: Option<CapabilityLevel>,
734 has_exec: bool,
735 has_file: bool,
736) -> Option<&'static str> {
737 match capability_level {
738 Some(CapabilityLevel::Basic) => {
739 Some("- Capabilities: limited. Ask the user to enable more capabilities if file work is required.")
740 }
741 Some(CapabilityLevel::FileReading | CapabilityLevel::FileListing) => Some(CAPABILITY_READ_ONLY_LINE),
742 _ if !has_exec && !has_file => Some(CAPABILITY_READ_ONLY_LINE),
743 _ => None,
744 }
745}
746
747pub(crate) fn infer_capability_level(available_tools: &[String]) -> CapabilityLevel {
749 infer_capability_level_from_presence(&ToolPresence::of(available_tools))
750}
751
752fn infer_capability_level_from_presence(presence: &ToolPresence) -> CapabilityLevel {
753 if presence.code_search {
754 CapabilityLevel::CodeSearch
755 } else if presence.apply_patch {
756 CapabilityLevel::Editing
757 } else if presence.exec {
758 CapabilityLevel::Bash
759 } else if presence.list_files {
760 CapabilityLevel::FileListing
761 } else if presence.read_file {
762 CapabilityLevel::FileReading
763 } else {
764 CapabilityLevel::Basic
765 }
766}
767
768#[cfg(test)]
769mod tests;