Skip to main content

vtcode_config/core/agent/
mod.rs

1use crate::constants::{defaults, execution, llm_generation, prompt_budget, tool_limits};
2use crate::models::{ModelId, Provider};
3use crate::types::{
4    ReasoningEffortLevel, ShellPromptProfile, SystemPromptMode, ToolDocumentationMode, UiSurfacePreference,
5    VerbosityLevel,
6};
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9
10const DEFAULT_CHECKPOINTS_ENABLED: bool = true;
11const DEFAULT_MAX_SNAPSHOTS: usize = 50;
12const DEFAULT_MAX_AGE_DAYS: u64 = 30;
13
14mod approval;
15mod circuit_breaker;
16mod codex_app_server;
17mod harness;
18mod memory;
19mod onboarding;
20mod open_responses;
21mod prompt_suggestions;
22mod small_model;
23mod vibe_coding;
24
25pub use approval::{AsyncApprovalConfig, ConfidenceEscalationConfig, SkepticPanelConfig};
26pub use circuit_breaker::CircuitBreakerConfig;
27pub use codex_app_server::AgentCodexAppServerConfig;
28pub use harness::{
29    AgentHarnessConfig, InspectionConfig, InspectionMode, ToolResultClearingConfig, TrackerContinuationConfig,
30    VerificationAutoRecoveryConfig,
31};
32pub use memory::{MemoriesConfig, PersistentMemoryConfig};
33pub use onboarding::AgentOnboardingConfig;
34pub use open_responses::OpenResponsesConfig;
35pub use prompt_suggestions::AgentPromptSuggestionsConfig;
36pub use small_model::AgentSmallModelConfig;
37pub use vibe_coding::AgentVibeCodingConfig;
38
39/// Agent-wide configuration
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41#[derive(Debug, Clone, Deserialize, Serialize)]
42pub struct AgentConfig {
43    /// Active provider for single-agent runs.
44    #[serde(default = "default_provider")]
45    pub provider: String,
46
47    /// Environment variable that stores the API key for the active provider
48    #[serde(default = "default_api_key_env")]
49    pub api_key_env: String,
50
51    /// Default model for new conversations.
52    #[serde(default = "default_model")]
53    pub default_model: String,
54
55    /// UI theme identifier controlling ANSI styling
56    #[serde(default = "default_theme")]
57    pub theme: String,
58
59    /// System prompt mode controlling prompt verbosity and token overhead.
60    /// Options target lean base prompts: minimal (~500 tokens), lightweight (~750 tokens),
61    /// default and specialized (~900 tokens) before dynamic runtime addenda.
62    #[serde(default)]
63    pub system_prompt_mode: SystemPromptMode,
64
65    /// Soft token budget for the fully composed system prompt (character-based
66    /// estimate, ~4 chars/token). Includes workspace instructions, guidelines,
67    /// and runtime addenda on top of the base prompt.
68    #[serde(default = "default_max_system_prompt_tokens")]
69    pub max_system_prompt_tokens: u64,
70
71    /// Warn when the composed system prompt exceeds `max_system_prompt_tokens`.
72    #[serde(default = "default_system_prompt_budget_warning")]
73    pub system_prompt_budget_warning: bool,
74
75    /// Trim low-priority advisory system prompt sections when over budget.
76    /// Base, shell-safety, and active-tool contracts are never trimmed.
77    #[serde(default = "default_trim_system_prompt")]
78    pub trim_system_prompt: bool,
79
80    /// Tool documentation mode controlling token overhead for tool definitions
81    /// Options: minimal, progressive (default, ~1.8k tokens for the builtin catalog), full
82    /// Progressive: complete tool and parameter descriptions; only unusually long tails are trimmed at a sentence boundary (recommended)
83    /// Minimal: first sentence of each tool description and no parameter descriptions (power users)
84    /// Full: every tool and parameter description sent unmodified
85    #[serde(default)]
86    pub tool_documentation_mode: ToolDocumentationMode,
87
88    /// Shell syntax profile used in model-facing command examples.
89    /// This controls prompt wording only; command policy remains in the runtime.
90    /// Values: auto, unix_like, powershell.
91    #[serde(default)]
92    pub shell_prompt_profile: ShellPromptProfile,
93
94    /// Enable split tool results for massive token savings (Phase 4)
95    /// When enabled, tools return dual-channel output:
96    /// - llm_content: Concise summary sent to LLM (token-optimized, 53-95% reduction)
97    /// - ui_content: Rich output displayed to user (full details preserved)
98    ///   Applies to: exec_command, code_search, apply_patch, and retained internal helpers
99    ///   Default: true (opt-out for compatibility), recommended for production use
100    #[serde(default = "default_enable_split_tool_results")]
101    pub enable_split_tool_results: bool,
102
103    /// Enable TODO planning helper mode for structured task management
104    #[serde(default = "default_todo_planning_mode")]
105    pub todo_planning_mode: bool,
106
107    /// Preferred rendering surface for the interactive chat UI (inline by default; auto, alternate, inline)
108    #[serde(default)]
109    pub ui_surface: UiSurfacePreference,
110
111    /// Maximum number of conversation turns before auto-termination
112    #[serde(default = "default_max_conversation_turns")]
113    pub max_conversation_turns: usize,
114
115    /// Maximum consecutive idle turns (no tool calls, no meaningful response) before
116    /// the agent runner treats the session as stalled and aborts the loop.
117    #[serde(default = "default_idle_turn_limit")]
118    pub idle_turn_limit: usize,
119
120    /// Reasoning depth for capable models (none to max).
121    #[serde(default = "default_reasoning_effort")]
122    pub reasoning_effort: ReasoningEffortLevel,
123    /// Permit a lower supported effort with an explicit harness diagnostic.
124    #[serde(default)]
125    pub allow_reasoning_effort_downgrade: bool,
126
127    /// Output verbosity for supported models (low to high). Options: "low", "medium", "high".
128    #[serde(default = "default_verbosity")]
129    pub verbosity: VerbosityLevel,
130
131    /// Sampling temperature (0.0 precise to 1.0 creative).
132    #[serde(default = "default_temperature")]
133    pub temperature: f32,
134
135    /// Temperature for prompt refinement (0.0-1.0).
136    #[serde(default = "default_refine_temperature")]
137    pub refine_temperature: f32,
138
139    /// Enable an extra self-review pass to refine final responses
140    #[serde(default = "default_enable_self_review")]
141    pub enable_self_review: bool,
142
143    /// Maximum number of self-review passes
144    #[serde(default = "default_max_review_passes")]
145    pub max_review_passes: usize,
146
147    /// Enable prompt refinement pass before sending to LLM
148    #[serde(default = "default_refine_prompts_enabled")]
149    pub refine_prompts_enabled: bool,
150
151    /// Max refinement passes for prompt writing
152    #[serde(default = "default_refine_max_passes")]
153    pub refine_prompts_max_passes: usize,
154
155    /// Optional model override for the refiner (empty = auto pick efficient sibling)
156    #[serde(default)]
157    pub refine_prompts_model: String,
158
159    /// Small/lightweight model configuration for efficient operations
160    /// Used for tasks like large file reads, parsing, git history, conversation summarization
161    /// Measure quality, token cost, and latency before choosing a different route.
162    #[serde(default)]
163    pub small_model: AgentSmallModelConfig,
164
165    /// Inline prompt suggestion configuration for the chat composer
166    #[serde(default)]
167    pub prompt_suggestions: AgentPromptSuggestionsConfig,
168
169    /// Session onboarding and welcome message configuration
170    #[serde(default)]
171    pub onboarding: AgentOnboardingConfig,
172
173    /// Deprecated and ignored: kept so existing configs still parse. Instruction loading,
174    /// including welcome-screen highlights, uses `instruction_max_bytes`.
175    #[serde(default = "default_project_doc_max_bytes")]
176    pub project_doc_max_bytes: usize,
177
178    /// Additional filenames to check when AGENTS.md is absent at a directory level.
179    #[serde(default)]
180    pub project_doc_fallback_filenames: Vec<String>,
181
182    /// Maximum bytes of instruction content to load from AGENTS.md/CLAUDE.md hierarchy
183    #[serde(default = "default_instruction_max_bytes", alias = "rule_doc_max_bytes")]
184    pub instruction_max_bytes: usize,
185
186    /// Additional instruction files or globs to merge into the hierarchy
187    #[serde(default, alias = "instruction_paths", alias = "instructions")]
188    pub instruction_files: Vec<String>,
189
190    /// Instruction files or globs to exclude from AGENTS.md and rules discovery
191    #[serde(default)]
192    pub instruction_excludes: Vec<String>,
193
194    /// Maximum recursive `@path` import depth for instruction and rule files
195    #[serde(default = "default_instruction_import_max_depth")]
196    pub instruction_import_max_depth: usize,
197
198    /// Durable per-repository memory for main sessions
199    #[serde(default)]
200    pub persistent_memory: PersistentMemoryConfig,
201
202    /// Provider/key identities captured from interactive configuration flows
203    ///
204    /// Note: Actual API keys are stored securely in the configured credential
205    /// backend (OS keyring when available, otherwise encrypted file storage).
206    /// Keys use `<provider>/<environment-variable>` identity keys and this
207    /// field only tracks which identities have keys stored (for UI/migration purposes).
208    /// The keys themselves are NOT serialized to the config file for security.
209    #[serde(default, skip_serializing)]
210    pub custom_api_keys: BTreeMap<String, String>,
211
212    /// Preferred storage backend for credentials (OAuth tokens, API keys, etc.)
213    ///
214    /// - `keyring`: Use OS-specific secure storage (macOS Keychain, Windows Credential
215    ///   Manager, Linux Secret Service), with encrypted-file fallback when unavailable.
216    /// - `file`: Use AES-256-GCM encrypted file with machine-derived key
217    /// - `auto`: Try keyring first, fall back to file if unavailable
218    #[serde(default)]
219    pub credential_storage_mode: crate::auth::AuthCredentialsStoreMode,
220
221    /// Checkpointing configuration for automatic turn snapshots
222    #[serde(default)]
223    pub checkpointing: AgentCheckpointingConfig,
224
225    /// Vibe coding configuration for lazy or vague request support
226    #[serde(default)]
227    pub vibe_coding: AgentVibeCodingConfig,
228
229    /// Maximum number of retries for agent task execution (default: 2)
230    /// When an agent task fails due to retryable errors (timeout, network, 503, etc.),
231    /// it will be retried up to this many times with exponential backoff
232    #[serde(default = "default_max_task_retries")]
233    pub max_task_retries: u32,
234
235    /// Harness configuration for turn-level budgets, telemetry, and execution limits
236    #[serde(default)]
237    pub harness: AgentHarnessConfig,
238
239    /// Experimental Codex app-server sidecar configuration.
240    #[serde(default)]
241    pub codex_app_server: AgentCodexAppServerConfig,
242
243    /// Include current date/time in system prompt for temporal awareness
244    /// Helps LLM understand context for time-sensitive tasks (default: true)
245    #[serde(default = "default_include_temporal_context")]
246    pub include_temporal_context: bool,
247
248    /// Use UTC instead of local time for temporal context in system prompts
249    #[serde(default)]
250    pub temporal_context_use_utc: bool,
251
252    /// Include current working directory in system prompt (default: true)
253    #[serde(default = "default_include_working_directory")]
254    pub include_working_directory: bool,
255
256    /// Controls inclusion of the structured reasoning tag instructions block.
257    ///
258    /// Behavior:
259    /// - `Some(true)`: always include structured reasoning instructions.
260    /// - `Some(false)`: never include structured reasoning instructions.
261    /// - `None` (default): omit structured reasoning instructions in every prompt mode.
262    ///
263    /// Models with native reasoning do not need visible reasoning tags, so the
264    /// block is opt-in for users who want tag-based reasoning guidance.
265    #[serde(default)]
266    pub include_structured_reasoning_tags: Option<bool>,
267
268    /// Custom instructions provided by the user via configuration to guide agent behavior
269    #[serde(default)]
270    pub user_instructions: Option<String>,
271
272    /// Require user confirmation before executing a plan generated in planning workflow
273    /// When true, exiting planning workflow shows the implementation blueprint and
274    /// requires explicit user approval before enabling edit tools.
275    #[serde(default = "default_require_plan_confirmation")]
276    pub require_plan_confirmation: bool,
277
278    /// Circuit breaker configuration for resilient tool execution
279    /// Controls when the agent should pause and ask for user guidance due to repeated failures
280    #[serde(default)]
281    pub circuit_breaker: CircuitBreakerConfig,
282
283    /// Open Responses specification compliance configuration
284    /// Enables vendor-neutral LLM API format for interoperable workflows
285    #[serde(default)]
286    pub open_responses: OpenResponsesConfig,
287}
288
289#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
290#[cfg_attr(feature = "schema", schemars(rename_all = "snake_case"))]
291#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
292#[serde(rename_all = "snake_case")]
293pub enum ContinuationPolicy {
294    Off,
295    ExecOnly,
296    #[default]
297    All,
298}
299
300impl ContinuationPolicy {
301    pub fn as_str(&self) -> &'static str {
302        match self {
303            Self::Off => "off",
304            Self::ExecOnly => "exec_only",
305            Self::All => "all",
306        }
307    }
308
309    fn parse(value: &str) -> Option<Self> {
310        let normalized = value.trim();
311        if normalized.eq_ignore_ascii_case("off") {
312            Some(Self::Off)
313        } else if normalized.eq_ignore_ascii_case("exec_only") || normalized.eq_ignore_ascii_case("exec-only") {
314            Some(Self::ExecOnly)
315        } else if normalized.eq_ignore_ascii_case("all") {
316            Some(Self::All)
317        } else {
318            None
319        }
320    }
321}
322
323impl<'de> Deserialize<'de> for ContinuationPolicy {
324    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
325    where
326        D: serde::Deserializer<'de>,
327    {
328        let raw = String::deserialize(deserializer)?;
329        Ok(Self::parse(&raw).unwrap_or_default())
330    }
331}
332
333/// When to trigger a context reset — starting a clean session from external
334/// artifacts only, discarding conversation history to clear noise and bad
335/// assumptions. This is distinct from compaction, which preserves
336/// conversational continuity within the same task/agent loop.
337///
338/// Following the context engineering pattern: "Context reset uses external
339/// artifacts (files from note-taking, git logs, test results, task lists) as
340/// startup material to open a clean new context/session. It does not preserve
341/// the full conversation history, and can clear noise and bad assumptions so
342/// that a new agent can reorient itself."
343#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
344#[cfg_attr(feature = "schema", schemars(rename_all = "snake_case"))]
345#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
346#[serde(rename_all = "snake_case")]
347pub enum ContextResetMode {
348    /// Never reset — always carry forward conversation history (current behavior).
349    #[default]
350    Off,
351    /// Reset when the progress monitor detects a stall (no forward progress for
352    /// `context_reset_stall_threshold` consecutive turns).
353    OnStall,
354    /// Reset after every automatic compaction, so the post-compaction session
355    /// starts from artifacts only rather than the compacted summary.
356    OnCompaction,
357}
358
359impl ContextResetMode {
360    pub fn as_str(&self) -> &'static str {
361        match self {
362            Self::Off => "off",
363            Self::OnStall => "on_stall",
364            Self::OnCompaction => "on_compaction",
365        }
366    }
367
368    fn parse(value: &str) -> Option<Self> {
369        let normalized = value.trim();
370        if normalized.eq_ignore_ascii_case("off") {
371            Some(Self::Off)
372        } else if normalized.eq_ignore_ascii_case("on_stall") || normalized.eq_ignore_ascii_case("on-stall") {
373            Some(Self::OnStall)
374        } else if normalized.eq_ignore_ascii_case("on_compaction") || normalized.eq_ignore_ascii_case("on-compaction") {
375            Some(Self::OnCompaction)
376        } else {
377            None
378        }
379    }
380}
381
382impl<'de> Deserialize<'de> for ContextResetMode {
383    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
384    where
385        D: serde::Deserializer<'de>,
386    {
387        let raw = String::deserialize(deserializer)?;
388        Ok(Self::parse(&raw).unwrap_or_default())
389    }
390}
391
392#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
393#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
394#[serde(rename_all = "snake_case")]
395pub enum HarnessOrchestrationMode {
396    #[default]
397    PlanBuildEvaluate,
398    Single,
399}
400
401impl HarnessOrchestrationMode {
402    pub fn as_str(&self) -> &'static str {
403        match self {
404            Self::Single => "single",
405            Self::PlanBuildEvaluate => "plan_build_evaluate",
406        }
407    }
408
409    fn parse(value: &str) -> Option<Self> {
410        let normalized = value.trim();
411        if normalized.eq_ignore_ascii_case("single") {
412            Some(Self::Single)
413        } else if normalized.eq_ignore_ascii_case("plan_build_evaluate")
414            || normalized.eq_ignore_ascii_case("plan-build-evaluate")
415            || normalized.eq_ignore_ascii_case("planner_generator_evaluator")
416            || normalized.eq_ignore_ascii_case("planner-generator-evaluator")
417        {
418            Some(Self::PlanBuildEvaluate)
419        } else {
420            None
421        }
422    }
423}
424
425impl<'de> Deserialize<'de> for HarnessOrchestrationMode {
426    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
427    where
428        D: serde::Deserializer<'de>,
429    {
430        let raw = String::deserialize(deserializer)?;
431        Ok(Self::parse(&raw).unwrap_or_default())
432    }
433}
434
435impl Default for AgentConfig {
436    fn default() -> Self {
437        Self {
438            provider: default_provider(),
439            api_key_env: default_api_key_env(),
440            default_model: default_model(),
441            theme: default_theme(),
442            system_prompt_mode: SystemPromptMode::default(),
443            max_system_prompt_tokens: default_max_system_prompt_tokens(),
444            system_prompt_budget_warning: default_system_prompt_budget_warning(),
445            trim_system_prompt: default_trim_system_prompt(),
446            tool_documentation_mode: ToolDocumentationMode::default(),
447            shell_prompt_profile: ShellPromptProfile::default(),
448            enable_split_tool_results: default_enable_split_tool_results(),
449            todo_planning_mode: default_todo_planning_mode(),
450            ui_surface: UiSurfacePreference::default(),
451            max_conversation_turns: default_max_conversation_turns(),
452            idle_turn_limit: default_idle_turn_limit(),
453            reasoning_effort: default_reasoning_effort(),
454            allow_reasoning_effort_downgrade: false,
455            verbosity: default_verbosity(),
456            temperature: default_temperature(),
457            refine_temperature: default_refine_temperature(),
458            enable_self_review: default_enable_self_review(),
459            max_review_passes: default_max_review_passes(),
460            refine_prompts_enabled: default_refine_prompts_enabled(),
461            refine_prompts_max_passes: default_refine_max_passes(),
462            refine_prompts_model: String::new(),
463            small_model: AgentSmallModelConfig::default(),
464            prompt_suggestions: AgentPromptSuggestionsConfig::default(),
465            onboarding: AgentOnboardingConfig::default(),
466            project_doc_max_bytes: default_project_doc_max_bytes(),
467            project_doc_fallback_filenames: Vec::new(),
468            instruction_max_bytes: default_instruction_max_bytes(),
469            instruction_files: Vec::new(),
470            instruction_excludes: Vec::new(),
471            instruction_import_max_depth: default_instruction_import_max_depth(),
472            persistent_memory: PersistentMemoryConfig::default(),
473            custom_api_keys: BTreeMap::new(),
474            credential_storage_mode: crate::auth::AuthCredentialsStoreMode::default(),
475            checkpointing: AgentCheckpointingConfig::default(),
476            vibe_coding: AgentVibeCodingConfig::default(),
477            max_task_retries: default_max_task_retries(),
478            harness: AgentHarnessConfig::default(),
479            codex_app_server: AgentCodexAppServerConfig::default(),
480            include_temporal_context: default_include_temporal_context(),
481            temporal_context_use_utc: false, // Default to local time
482            include_working_directory: default_include_working_directory(),
483            include_structured_reasoning_tags: None,
484            user_instructions: None,
485            require_plan_confirmation: default_require_plan_confirmation(),
486            circuit_breaker: CircuitBreakerConfig::default(),
487            open_responses: OpenResponsesConfig::default(),
488        }
489    }
490}
491
492/// Reject an agent-tier sampling temperature outside the unit range.
493/// NaN fails the range check, so unrepresentable TOML floats cannot slip through.
494fn validate_unit_temperature(name: &str, value: f32) -> Result<(), String> {
495    if !(0.0..=1.0).contains(&value) {
496        return Err(format!("{name} must be between 0.0 and 1.0, got {value}"));
497    }
498    Ok(())
499}
500
501impl AgentConfig {
502    /// Determine whether structured reasoning tag instructions should be included.
503    pub fn should_include_structured_reasoning_tags(&self) -> bool {
504        self.include_structured_reasoning_tags.unwrap_or(false)
505    }
506
507    /// Validate LLM generation parameters
508    pub(crate) fn validate_llm_params(&self) -> Result<(), String> {
509        // Agent-tier sampling temperatures share the unit range; custom
510        // providers allow 0.0-2.0 and validate separately.
511        validate_unit_temperature("temperature", self.temperature)?;
512        validate_unit_temperature("refine_temperature", self.refine_temperature)?;
513        validate_unit_temperature("small_model.temperature", self.small_model.temperature)?;
514        validate_unit_temperature("prompt_suggestions.temperature", self.prompt_suggestions.temperature)?;
515
516        if self.instruction_import_max_depth == 0 {
517            return Err("instruction_import_max_depth must be greater than 0".to_string());
518        }
519
520        if !(0.0..=1.0).contains(&self.harness.budget_warning_threshold) {
521            return Err(format!(
522                "harness.budget_warning_threshold must be between 0.0 and 1.0, got {}",
523                self.harness.budget_warning_threshold
524            ));
525        }
526
527        self.persistent_memory.validate()?;
528        self.harness.tool_result_clearing.validate()?;
529
530        Ok(())
531    }
532}
533
534// Optimized: Use inline defaults with constants to reduce function call overhead
535#[inline]
536fn default_provider() -> String {
537    defaults::DEFAULT_PROVIDER.into()
538}
539
540#[inline]
541fn default_api_key_env() -> String {
542    defaults::DEFAULT_API_KEY_ENV.into()
543}
544
545fn default_model() -> String {
546    // Resolve the SOTA flagship at runtime so struct defaults never go stale;
547    // the curated constant remains as the fallback (and the anti-rot tripwire
548    // in `model_id::table::tests` keeps the two in lockstep).
549    ModelId::latest_flagship(Provider::Anthropic)
550        .map(|model| model.as_str().into_owned())
551        .unwrap_or_else(|| defaults::DEFAULT_MODEL.into())
552}
553
554#[inline]
555fn default_theme() -> String {
556    defaults::DEFAULT_THEME.into()
557}
558
559#[inline]
560const fn default_todo_planning_mode() -> bool {
561    true
562}
563
564#[inline]
565const fn default_enable_split_tool_results() -> bool {
566    true // Default: enabled for production use (84% token savings)
567}
568
569#[inline]
570const fn default_max_conversation_turns() -> usize {
571    tool_limits::DEFAULT_MAX_CONVERSATION_TURNS
572}
573
574#[inline]
575const fn default_idle_turn_limit() -> usize {
576    execution::IDLE_TURN_LIMIT
577}
578
579#[inline]
580fn default_reasoning_effort() -> ReasoningEffortLevel {
581    ReasoningEffortLevel::None
582}
583
584#[inline]
585fn default_verbosity() -> VerbosityLevel {
586    VerbosityLevel::default()
587}
588
589#[inline]
590const fn default_temperature() -> f32 {
591    llm_generation::DEFAULT_TEMPERATURE
592}
593
594#[inline]
595const fn default_refine_temperature() -> f32 {
596    llm_generation::DEFAULT_REFINE_TEMPERATURE
597}
598
599#[inline]
600const fn default_enable_self_review() -> bool {
601    false
602}
603
604#[inline]
605const fn default_max_review_passes() -> usize {
606    1
607}
608
609#[inline]
610const fn default_refine_prompts_enabled() -> bool {
611    false
612}
613
614#[inline]
615const fn default_refine_max_passes() -> usize {
616    1
617}
618
619#[inline]
620const fn default_max_system_prompt_tokens() -> u64 {
621    prompt_budget::DEFAULT_MAX_SYSTEM_PROMPT_TOKENS
622}
623
624#[inline]
625const fn default_system_prompt_budget_warning() -> bool {
626    true
627}
628
629#[inline]
630const fn default_trim_system_prompt() -> bool {
631    true
632}
633
634#[inline]
635const fn default_project_doc_max_bytes() -> usize {
636    prompt_budget::DEFAULT_MAX_BYTES
637}
638
639#[inline]
640const fn default_instruction_max_bytes() -> usize {
641    prompt_budget::DEFAULT_MAX_BYTES
642}
643
644#[inline]
645const fn default_instruction_import_max_depth() -> usize {
646    5
647}
648
649#[inline]
650const fn default_max_task_retries() -> u32 {
651    2 // Retry twice on transient failures
652}
653
654#[inline]
655const fn default_include_temporal_context() -> bool {
656    true // Enable by default - minimal overhead (~20 tokens)
657}
658
659#[inline]
660const fn default_include_working_directory() -> bool {
661    true // Enable by default - minimal overhead (~10 tokens)
662}
663
664#[inline]
665const fn default_require_plan_confirmation() -> bool {
666    true // Default: require confirmation (HITL pattern)
667}
668
669#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
670#[derive(Debug, Clone, Deserialize, Serialize)]
671pub struct AgentCheckpointingConfig {
672    /// Enable automatic checkpoints after each successful turn
673    #[serde(default = "default_checkpointing_enabled")]
674    pub enabled: bool,
675
676    /// Optional custom directory for storing checkpoints (relative to workspace or absolute)
677    #[serde(default)]
678    pub storage_dir: Option<String>,
679
680    /// Maximum number of checkpoints to retain on disk
681    #[serde(default = "default_checkpointing_max_snapshots")]
682    pub max_snapshots: usize,
683
684    /// Maximum age in days before checkpoints are removed automatically (None disables)
685    #[serde(default = "default_checkpointing_max_age_days")]
686    pub max_age_days: Option<u64>,
687}
688
689impl Default for AgentCheckpointingConfig {
690    fn default() -> Self {
691        Self {
692            enabled: default_checkpointing_enabled(),
693            storage_dir: None,
694            max_snapshots: default_checkpointing_max_snapshots(),
695            max_age_days: default_checkpointing_max_age_days(),
696        }
697    }
698}
699
700#[inline]
701const fn default_checkpointing_enabled() -> bool {
702    DEFAULT_CHECKPOINTS_ENABLED
703}
704
705#[inline]
706const fn default_checkpointing_max_snapshots() -> usize {
707    DEFAULT_MAX_SNAPSHOTS
708}
709
710#[inline]
711const fn default_checkpointing_max_age_days() -> Option<u64> {
712    Some(DEFAULT_MAX_AGE_DAYS)
713}
714
715#[cfg(test)]
716mod tests;