Skip to main content

vtcode_core/prompts/system/
compose.rs

1//! System-instruction composition, budget trimming, and identity substitution.
2
3use 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
25/// Compose the base system instruction plus compact tool/skill/environment addenda.
26pub 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
36/// Compose the system instruction and return the token-budget report
37/// alongside it. See [`SystemPromptReport`] and `SectionKind::trim_priority`
38/// for the budget/trim behavior driven by `agent.max_system_prompt_tokens`,
39/// `agent.system_prompt_budget_warning`, and `agent.trim_system_prompt`.
40pub 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
50/// Compose a runtime base without provisional tool guidance. The live catalog
51/// is appended after the caller has added its workspace and runtime context.
52pub 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
63/// Compose a prompt and retain the stable instruction digest used by local and
64/// provider-facing prompt caches.
65async 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(&sections);
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
79/// Measure the system prompt size without applying budget trimming or warnings.
80///
81/// This is used at startup to warn about potential token budget overruns
82/// before the first request is made. Unlike [`compose_system_instruction_with_report`],
83/// this function does not apply `agent.trim_system_prompt` and does not emit
84/// budget-exceeded warnings.
85pub 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(&sections);
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
101/// Token estimate of the user/workspace prompt-layer text spliced into the
102/// composed prompt. Measured on the exact applied layer text so the figure
103/// tracks what the model sees, modulo separators and later identity substitutions.
104fn applied_layer_token_estimate(layers: &SystemPromptLayers) -> u64 {
105    estimate_token_count(&layers.applied_text())
106}
107
108/// Resolve the effective `(max_system_prompt_tokens, budget_warning_enabled,
109/// trim_enabled)` settings, falling back to the `AgentConfig` defaults when
110/// no config is available.
111fn 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
121/// Build the ordered prompt sections. Each section's text is stored exactly
122/// as the legacy single-string builder would have appended it; the joiner
123/// trims section edges, so only the inter-section newlines differ from the
124/// legacy builder.
125pub(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    // Apply agent identity based on the default primary agent configuration.
151    // This combines "VT Code" with the active agent mode so the LLM knows its role.
152    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        // Prompt-caching discipline: static content first, dynamic last.
178        // `Skills` is session-stable routing metadata while `ToolGuidelines`
179        // derives from the live tool catalog (planning toggles, MCP refreshes),
180        // so skills must precede tool guidelines. Otherwise every catalog
181        // change would invalidate the cached skills section that follows it.
182        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        // Static prompts ship the parallel-call hint unconditionally; only the
186        // runtime per-turn path re-resolves it against the provider.
187        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
209/// Join ordered prompt sections the way the legacy single-string builder
210/// did: the first section, then each subsequent section separated by a blank
211/// line.
212///
213/// Each section is trimmed first. Section sources carry their own leading or
214/// trailing newlines, and joining those verbatim produced two blank lines
215/// between some sections, which cost prompt lines without carrying meaning.
216pub(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
228/// Enforce the configured system-prompt token budget against the composed
229/// sections.
230///
231/// When under budget, sections are joined and returned unchanged. When over
232/// budget and `trim_enabled` is false, the full untrimmed text is still used
233/// but a warning is logged (gated on `warn_enabled`). When over budget and
234/// `trim_enabled` is true, whole sections are dropped in
235/// [`SectionKind::trim_priority`] order (lowest first), re-measuring after
236/// each drop, until the prompt fits or only untrimmable sections remain.
237pub(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(&sections);
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(&sections);
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
294/// Hash only the explicitly stable prompt sections.
295pub(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
304/// Align cached base guidance with the selected role, including switches away from the coordinator.
305pub 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
346/// Apply agent identity to the system prompt by replacing the title and intro lines.
347/// This combines the "VT Code" identity with the active agent mode so the LLM
348/// knows its role (e.g., "VT Code (Build mode)" or "VT Code (Auto mode)").
349pub(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
384/// Structured reasoning tags are opt-in (`agent.include_structured_reasoning_tags`)
385/// in every prompt mode; without a config there is nothing to opt in.
386pub(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
390/// Generate the stable base system instruction with configuration-aware sections.
391///
392/// Note: This function maintains backward compatibility by not accepting prompt_context.
393/// For enhanced prompts with dynamic guidelines, call `compose_system_instruction_text` directly.
394pub 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
404/// Same as [`generate_system_instruction_with_config`] but also returns the
405/// [`SystemPromptReport`] for the composed prompt, whether served from cache
406/// or freshly built.
407pub 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
415/// Generate a system instruction using a context-aware cache identity.
416///
417/// Context-free and context-aware prompts intentionally use different cache
418/// keys. This prevents a prompt assembled with workspace tools or skill
419/// metadata from being returned to a caller that requested the static prompt.
420pub 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    // Apply output style if configured
445    let styled_instruction = apply_output_style(instruction, vtcode_config, project_root).await;
446    (Content::system_text(styled_instruction), report)
447}
448
449/// Apply output style to a generated system instruction
450pub 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 // Return original if loading fails
460        } else {
461            output_style_applier
462                .apply_style(&config.output_style.active_style, &instruction, config)
463                .await
464        }
465    } else {
466        instruction // Return original if no config
467    }
468}