Skip to main content

vtcode_config/
hooks.rs

1use anyhow::{Context, Result, ensure};
2use regex::Regex;
3use serde::{Deserialize, Serialize};
4
5/// Top-level configuration for automation hooks and lifecycle events
6#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
7#[derive(Debug, Clone, Deserialize, Serialize, Default)]
8pub struct HooksConfig {
9    /// Configuration for lifecycle-based shell command execution
10    #[serde(default)]
11    pub lifecycle: LifecycleHooksConfig,
12}
13
14/// Configuration for hooks triggered during distinct agent lifecycle events.
15/// Each event supports a list of groups with optional matchers.
16#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
17#[derive(Debug, Clone, Deserialize, Serialize, Default)]
18pub struct LifecycleHooksConfig {
19    /// Commands to run immediately when an agent session begins
20    #[serde(default)]
21    pub session_start: Vec<HookGroupConfig>,
22
23    /// Commands to run when an agent session ends
24    #[serde(default)]
25    pub session_end: Vec<HookGroupConfig>,
26
27    /// Commands to run when the user submits a prompt (pre-processing)
28    #[serde(default)]
29    pub user_prompt_submit: Vec<HookGroupConfig>,
30
31    /// Commands to run immediately before a tool is executed
32    #[serde(default)]
33    pub pre_tool_use: Vec<HookGroupConfig>,
34
35    /// Commands to run immediately after a tool returns its output
36    #[serde(default)]
37    pub post_tool_use: Vec<HookGroupConfig>,
38
39    /// Commands to run when the agent indicates task completion (pre-exit)
40    #[serde(default)]
41    pub task_completion: Vec<HookGroupConfig>,
42
43    /// Commands to run after a task is finalized and session is closed
44    #[serde(default)]
45    pub task_completed: Vec<HookGroupConfig>,
46}
47
48impl LifecycleHooksConfig {
49    pub fn is_empty(&self) -> bool {
50        self.session_start.is_empty()
51            && self.session_end.is_empty()
52            && self.user_prompt_submit.is_empty()
53            && self.pre_tool_use.is_empty()
54            && self.post_tool_use.is_empty()
55            && self.task_completion.is_empty()
56            && self.task_completed.is_empty()
57    }
58}
59
60/// A group of hooks sharing a common execution matcher
61#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
62#[derive(Debug, Clone, Deserialize, Serialize, Default)]
63pub struct HookGroupConfig {
64    /// Optional regex matcher to filter when this group runs.
65    /// Matched against context strings (e.g. tool name, project path).
66    #[serde(default)]
67    pub matcher: Option<String>,
68
69    /// List of hook commands to execute sequentially in this group
70    #[serde(default)]
71    pub hooks: Vec<HookCommandConfig>,
72}
73
74#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
75#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
76#[serde(rename_all = "snake_case")]
77#[derive(Default)]
78pub enum HookCommandKind {
79    #[default]
80    Command,
81}
82
83/// Configuration for a single shell command hook
84#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
85#[derive(Debug, Clone, Deserialize, Serialize, Default)]
86pub struct HookCommandConfig {
87    /// Type of hook command (currently only 'command' is supported)
88    #[serde(default)]
89    #[serde(rename = "type")]
90    pub kind: HookCommandKind,
91
92    /// The shell command string to execute
93    #[serde(default)]
94    pub command: String,
95
96    /// Optional execution timeout in seconds
97    #[serde(default)]
98    pub timeout_seconds: Option<u64>,
99}
100
101impl HooksConfig {
102    pub fn validate(&self) -> Result<()> {
103        self.lifecycle
104            .validate()
105            .context("Invalid lifecycle hooks configuration")
106    }
107}
108
109impl LifecycleHooksConfig {
110    pub fn validate(&self) -> Result<()> {
111        validate_groups(&self.session_start, "session_start")?;
112        validate_groups(&self.session_end, "session_end")?;
113        validate_groups(&self.user_prompt_submit, "user_prompt_submit")?;
114        validate_groups(&self.pre_tool_use, "pre_tool_use")?;
115        validate_groups(&self.post_tool_use, "post_tool_use")?;
116        validate_groups(&self.task_completion, "task_completion")?;
117        validate_groups(&self.task_completed, "task_completed")?;
118        Ok(())
119    }
120}
121
122fn validate_groups(groups: &[HookGroupConfig], context_name: &str) -> Result<()> {
123    for (index, group) in groups.iter().enumerate() {
124        if let Some(pattern) = group.matcher.as_ref() {
125            validate_matcher(pattern).with_context(|| {
126                format!("Invalid matcher in hooks.{context_name}[{index}] -> matcher")
127            })?;
128        }
129
130        ensure!(
131            !group.hooks.is_empty(),
132            "hooks.{context_name}[{index}] must define at least one hook command"
133        );
134
135        for (hook_index, hook) in group.hooks.iter().enumerate() {
136            ensure!(
137                matches!(hook.kind, HookCommandKind::Command),
138                "hooks.{context_name}[{index}].hooks[{hook_index}] has unsupported type"
139            );
140
141            ensure!(
142                !hook.command.trim().is_empty(),
143                "hooks.{context_name}[{index}].hooks[{hook_index}] must specify a command"
144            );
145
146            if let Some(timeout) = hook.timeout_seconds {
147                ensure!(
148                    timeout > 0,
149                    "hooks.{context_name}[{index}].hooks[{hook_index}].timeout_seconds must be positive"
150                );
151            }
152        }
153    }
154
155    Ok(())
156}
157
158fn validate_matcher(pattern: &str) -> Result<()> {
159    let trimmed = pattern.trim();
160    if trimmed.is_empty() || trimmed == "*" {
161        return Ok(());
162    }
163
164    let regex_pattern = format!("^(?:{})$", trimmed);
165    Regex::new(&regex_pattern)
166        .with_context(|| format!("failed to compile lifecycle hook matcher: {pattern}"))?;
167    Ok(())
168}