1use std::path::Path;
4
5use crate::config::constants::prompt_budget as prompt_budget_constants;
6use crate::config::types::ShellPromptProfile;
7use crate::llm::providers::gemini::wire::Content;
8use crate::prompts::context::PromptContext;
9use crate::prompts::guidelines::{generate_tool_guidelines_for_profile, render_shell_profile_guidance};
10use crate::prompts::output_styles::OutputStyleApplier;
11use crate::prompts::render::render_environment_addenda;
12use crate::prompts::resources::{SystemPromptLayers, apply_system_prompt_layers, resolve_system_prompt_layers};
13use crate::prompts::static_prompts::static_profile_prompt;
14use crate::prompts::system_prompt_cache::PROMPT_CACHE;
15use crate::skills::render::render_prompt_skills_section;
16use tracing::warn;
17
18use super::cache::{cache_key_for_identity, prompt_context_digest};
19use super::constants::{PROMPT_IDENTITY_NAME, PROMPT_INTRO, PROMPT_TITLE, STRUCTURED_REASONING_INSTRUCTIONS};
20use super::tokens::estimate_token_count;
21use super::types::{PromptSection, SectionKind, SystemPromptConfig, SystemPromptReport};
22
23use crate::prompts::static_prompts::agent_identity_label;
24
25pub async fn compose_system_instruction_text(
27 project_root: &Path,
28 vtcode_config: Option<&crate::config::VTCodeConfig>,
29 prompt_context: Option<&PromptContext>,
30) -> String {
31 compose_system_instruction_with_report(project_root, vtcode_config, prompt_context)
32 .await
33 .0
34}
35
36pub async fn compose_system_instruction_with_report(
41 project_root: &Path,
42 vtcode_config: Option<&crate::config::VTCodeConfig>,
43 prompt_context: Option<&PromptContext>,
44) -> (String, SystemPromptReport) {
45 let (prompt, report, _) =
46 compose_system_instruction_with_identity(project_root, vtcode_config, prompt_context).await;
47 (prompt, report)
48}
49
50pub async fn compose_runtime_base_instruction_with_report(
53 project_root: &Path,
54 vtcode_config: Option<&crate::config::VTCodeConfig>,
55 prompt_context: Option<&PromptContext>,
56) -> (String, SystemPromptReport) {
57 let layers = resolve_system_prompt_layers(project_root).await;
58 let sections = build_prompt_sections_with_layers_option(vtcode_config, prompt_context, &layers, false);
59 let (max_tokens, warn_enabled, trim_enabled) = system_prompt_budget_settings(vtcode_config);
60 apply_token_budget(sections, max_tokens, warn_enabled, trim_enabled, applied_layer_token_estimate(&layers))
61}
62
63async fn compose_system_instruction_with_identity(
66 project_root: &Path,
67 vtcode_config: Option<&crate::config::VTCodeConfig>,
68 prompt_context: Option<&PromptContext>,
69) -> (String, SystemPromptReport, u64) {
70 let layers = resolve_system_prompt_layers(project_root).await;
71 let sections = build_prompt_sections_with_layers(vtcode_config, prompt_context, &layers);
72 let instruction_digest = stable_prompt_sections_digest(§ions);
73 let (max_tokens, warn_enabled, trim_enabled) = system_prompt_budget_settings(vtcode_config);
74 let (prompt, report) =
75 apply_token_budget(sections, max_tokens, warn_enabled, trim_enabled, applied_layer_token_estimate(&layers));
76 (prompt, report, instruction_digest)
77}
78
79pub async fn measure_system_prompt_size(
86 project_root: &Path,
87 vtcode_config: &crate::config::VTCodeConfig,
88) -> SystemPromptReport {
89 let layers = resolve_system_prompt_layers(project_root).await;
90 let sections = build_prompt_sections_with_layers(Some(vtcode_config), None, &layers);
91 let text = join_prompt_sections(§ions);
92 let token_estimate = estimate_token_count(&text);
93 SystemPromptReport {
94 token_estimate,
95 over_budget: token_estimate > vtcode_config.agent.max_system_prompt_tokens,
96 trimmed_sections: Vec::new(),
97 layer_token_estimate: applied_layer_token_estimate(&layers),
98 }
99}
100
101fn applied_layer_token_estimate(layers: &SystemPromptLayers) -> u64 {
105 estimate_token_count(&layers.applied_text())
106}
107
108fn system_prompt_budget_settings(vtcode_config: Option<&crate::config::VTCodeConfig>) -> (u64, bool, bool) {
112 vtcode_config.map_or((prompt_budget_constants::DEFAULT_MAX_SYSTEM_PROMPT_TOKENS, true, true), |cfg| {
113 (
114 cfg.agent.max_system_prompt_tokens,
115 cfg.agent.system_prompt_budget_warning,
116 cfg.agent.trim_system_prompt,
117 )
118 })
119}
120
121pub(super) fn build_prompt_sections_with_layers(
126 vtcode_config: Option<&crate::config::VTCodeConfig>,
127 prompt_context: Option<&PromptContext>,
128 resolved_layers: &SystemPromptLayers,
129) -> Vec<PromptSection> {
130 build_prompt_sections_with_layers_option(vtcode_config, prompt_context, resolved_layers, true)
131}
132
133pub(super) fn build_prompt_sections_with_layers_option(
134 vtcode_config: Option<&crate::config::VTCodeConfig>,
135 prompt_context: Option<&PromptContext>,
136 resolved_layers: &SystemPromptLayers,
137 include_tool_guidance: bool,
138) -> Vec<PromptSection> {
139 let prompt_mode = vtcode_config.map(|c| c.agent.system_prompt_mode).unwrap_or_default();
140 let static_base_prompt = static_profile_prompt(prompt_mode);
141 let mut base_prompt = apply_system_prompt_layers(static_base_prompt, resolved_layers);
142 crate::prompts::runtime_guidance::ensure_runtime_guidance(&mut base_prompt);
143
144 tracing::trace!(
145 mode = ?prompt_mode,
146 base_tokens = estimate_token_count(&base_prompt),
147 "Selected system prompt mode"
148 );
149
150 if let Some(cfg) = vtcode_config {
153 let agent_label = agent_identity_label(&cfg.default_primary_agent);
154 base_prompt = apply_agent_identity(&base_prompt, &agent_label);
155 apply_coordinator_role_guidance(&mut base_prompt, cfg.default_primary_agent == "coordinator");
156 }
157
158 let mut sections = vec![PromptSection { kind: SectionKind::BaseContract, text: base_prompt }];
159
160 if should_include_structured_reasoning(vtcode_config) {
161 sections.push(PromptSection {
162 kind: SectionKind::StructuredReasoning,
163 text: STRUCTURED_REASONING_INSTRUCTIONS.to_string(),
164 });
165 }
166
167 let shell_profile = vtcode_config
168 .map(|cfg| cfg.agent.shell_prompt_profile)
169 .unwrap_or(ShellPromptProfile::Auto)
170 .resolve_for_current_platform();
171 sections.push(PromptSection {
172 kind: SectionKind::ShellProfile,
173 text: render_shell_profile_guidance(shell_profile),
174 });
175
176 if let Some(ctx) = prompt_context {
177 if let Some(skills_section) = render_prompt_skills_section(&ctx.available_skill_metadata) {
183 sections.push(PromptSection { kind: SectionKind::Skills, text: skills_section });
184 }
185 if include_tool_guidance {
188 let guidelines =
189 generate_tool_guidelines_for_profile(&ctx.available_tools, ctx.capability_level, shell_profile, true);
190 if !guidelines.is_empty() {
191 sections.push(PromptSection {
192 kind: SectionKind::ToolGuidelines,
193 text: guidelines.trim_start_matches('\n').to_string(),
194 });
195 }
196 }
197 }
198
199 if let Some(environment_section) = render_environment_addenda(vtcode_config, prompt_context) {
200 sections.push(PromptSection {
201 kind: SectionKind::EnvironmentAddenda,
202 text: environment_section,
203 });
204 }
205
206 sections
207}
208
209pub(super) fn join_prompt_sections(sections: &[PromptSection]) -> String {
217 let capacity = sections.iter().map(|section| section.text.len() + 2).sum();
218 let mut joined = String::with_capacity(capacity);
219 for (index, section) in sections.iter().enumerate() {
220 if index > 0 {
221 joined.push_str("\n\n");
222 }
223 joined.push_str(section.text.trim());
224 }
225 joined
226}
227
228pub(super) fn apply_token_budget(
238 mut sections: Vec<PromptSection>,
239 max_tokens: u64,
240 warn_enabled: bool,
241 trim_enabled: bool,
242 layer_token_estimate: u64,
243) -> (String, SystemPromptReport) {
244 let mut text = join_prompt_sections(§ions);
245 let mut token_estimate = estimate_token_count(&text);
246 let mut trimmed_sections: Vec<&'static str> = Vec::new();
247
248 if token_estimate > max_tokens {
249 if trim_enabled {
250 while token_estimate > max_tokens {
251 let drop_index = sections
252 .iter()
253 .enumerate()
254 .filter_map(|(index, section)| section.kind.trim_priority().map(|priority| (priority, index)))
255 .min_by_key(|(priority, _)| *priority)
256 .map(|(_, index)| index);
257 let Some(drop_index) = drop_index else {
258 break;
259 };
260 let dropped = sections.remove(drop_index);
261 trimmed_sections.push(dropped.kind.name());
262 text = join_prompt_sections(§ions);
263 token_estimate = estimate_token_count(&text);
264 }
265
266 if !trimmed_sections.is_empty() {
267 tracing::warn!(
268 token_estimate,
269 max_system_prompt_tokens = max_tokens,
270 layer_token_estimate,
271 dropped_sections = ?trimmed_sections,
272 "Trimmed system prompt sections to satisfy token budget"
273 );
274 }
275 } else if warn_enabled {
276 tracing::warn!(
277 token_estimate,
278 max_system_prompt_tokens = max_tokens,
279 layer_token_estimate,
280 "System prompt exceeds configured token budget"
281 );
282 }
283 }
284
285 let report = SystemPromptReport {
286 token_estimate,
287 over_budget: token_estimate > max_tokens,
288 trimmed_sections,
289 layer_token_estimate,
290 };
291 (text, report)
292}
293
294pub(super) fn stable_prompt_sections_digest(sections: &[PromptSection]) -> u64 {
296 let stable_sections = sections
297 .iter()
298 .filter(|section| section.kind.is_cache_stable())
299 .map(|section| (section.kind.name(), section.text.as_str()))
300 .collect::<Vec<_>>();
301 crate::core::agent::hash_utils::hash_value(&stable_sections)
302}
303
304pub fn apply_coordinator_role_guidance(prompt: &mut String, coordinator_active: bool) {
306 use crate::prompts::sections::{SectionBoundaryMode, find_prompt_section_bounds};
307
308 const ORDINARY_DELEGATION: &str = crate::prompts::runtime_guidance::DELEGATION_RULE;
309 const COORDINATOR_DELEGATION: &str = "- As coordinator, delegate execution and verification to scheduler-owned matrix workers; keep decisions in the main thread.";
310
311 if !coordinator_active && !prompt.contains("## Coordinator Role") && !prompt.contains(COORDINATOR_DELEGATION) {
312 return;
313 }
314
315 let coordinator_role =
316 format!("## Coordinator Role\n{}\n", vtcode_config::subagents::builtin_primary_coordinator_agent().prompt);
317 if coordinator_active
318 && prompt.matches("## Coordinator Role").count() == 1
319 && prompt.contains(COORDINATOR_DELEGATION)
320 && let Some((start, end)) =
321 find_prompt_section_bounds(prompt, "## Coordinator Role", SectionBoundaryMode::BracketOrMarkdown)
322 && prompt
323 .get(start..end)
324 .is_some_and(|section| section.trim() == coordinator_role.trim())
325 {
326 return;
327 }
328
329 while let Some((start, end)) =
330 find_prompt_section_bounds(prompt, "## Coordinator Role", SectionBoundaryMode::BracketOrMarkdown)
331 {
332 prompt.replace_range(start..end, "");
333 }
334 let (previous, current) = if coordinator_active {
335 (ORDINARY_DELEGATION, COORDINATOR_DELEGATION)
336 } else {
337 (COORDINATOR_DELEGATION, ORDINARY_DELEGATION)
338 };
339 *prompt = prompt.replace(previous, current);
340 if coordinator_active {
341 prompt.push_str("\n\n");
342 prompt.push_str(&coordinator_role);
343 }
344}
345
346pub(super) fn apply_agent_identity(prompt: &str, agent_label: &str) -> String {
350 let mut result = prompt.to_string();
351 let old_title = PROMPT_TITLE;
352 let labeled_title = old_title.replacen(PROMPT_IDENTITY_NAME, agent_label, 1);
353 let old_intro = PROMPT_INTRO;
354
355 let title_found = if let Some(pos) = result.find(old_title) {
356 result.replace_range(pos..pos + old_title.len(), &labeled_title);
357 true
358 } else {
359 warn!("Could not find prompt title '{}' to apply agent identity", old_title);
360 false
361 };
362
363 let intro_found = if let Some(pos) = result.find(old_intro) {
364 let labeled_intro = old_intro.replacen(PROMPT_IDENTITY_NAME, agent_label, 1);
365 result.replace_range(pos..pos + old_intro.len(), &labeled_intro);
366 true
367 } else {
368 warn!("Could not find prompt intro '{}' to apply agent identity", old_intro);
369 false
370 };
371
372 if !title_found || !intro_found {
373 warn!(
374 agent_label = %agent_label,
375 title_replaced = title_found,
376 intro_replaced = intro_found,
377 "agent identity partially applied"
378 );
379 }
380
381 result
382}
383
384pub(super) fn should_include_structured_reasoning(vtcode_config: Option<&crate::config::VTCodeConfig>) -> bool {
387 vtcode_config.is_some_and(|cfg| cfg.agent.should_include_structured_reasoning_tags())
388}
389
390pub async fn generate_system_instruction_with_config(
395 config: &SystemPromptConfig,
396 project_root: &Path,
397 vtcode_config: Option<&crate::config::VTCodeConfig>,
398) -> Content {
399 let (content, _report) =
400 generate_system_instruction_with_config_and_report(config, project_root, vtcode_config).await;
401 content
402}
403
404pub async fn generate_system_instruction_with_config_and_report(
408 _config: &SystemPromptConfig,
409 project_root: &Path,
410 vtcode_config: Option<&crate::config::VTCodeConfig>,
411) -> (Content, SystemPromptReport) {
412 generate_system_instruction_with_context_and_report(_config, project_root, vtcode_config, None).await
413}
414
415pub async fn generate_system_instruction_with_context_and_report(
421 _config: &SystemPromptConfig,
422 project_root: &Path,
423 vtcode_config: Option<&crate::config::VTCodeConfig>,
424 prompt_context: Option<&PromptContext>,
425) -> (Content, SystemPromptReport) {
426 let (built_instruction, built_report, instruction_digest) =
427 compose_system_instruction_with_identity(project_root, vtcode_config, prompt_context).await;
428 let cache_key = cache_key_for_identity(
429 project_root,
430 vtcode_config,
431 instruction_digest,
432 prompt_context_digest(prompt_context),
433 0,
434 );
435 let (instruction, report) = match PROMPT_CACHE.get(&cache_key) {
436 Some(cached) => cached,
437 None => {
438 let built = (built_instruction, built_report);
439 PROMPT_CACHE.insert(cache_key, built.clone());
440 built
441 }
442 };
443
444 let styled_instruction = apply_output_style(instruction, vtcode_config, project_root).await;
446 (Content::system_text(styled_instruction), report)
447}
448
449pub async fn apply_output_style(
451 instruction: String,
452 vtcode_config: Option<&crate::config::VTCodeConfig>,
453 project_root: &Path,
454) -> String {
455 if let Some(config) = vtcode_config {
456 let output_style_applier = OutputStyleApplier::new();
457 if let Err(e) = output_style_applier.load_styles_from_config(config, project_root).await {
458 tracing::warn!("Failed to load output styles: {}", e);
459 instruction } else {
461 output_style_applier
462 .apply_style(&config.output_style.active_style, &instruction, config)
463 .await
464 }
465 } else {
466 instruction }
468}