1use std::path::PathBuf;
2use std::process::Stdio;
3use std::sync::Arc;
4use std::time::Duration;
5
6use anyhow::{Context, Result};
7use serde_json::Value;
8use tokio::io::{AsyncReadExt, AsyncWriteExt};
9use tokio::process::Command;
10use tokio::sync::Mutex;
11use tokio::time;
12
13use crate::config::{HookCommandConfig, HooksConfig};
14use crate::exec::events::{CompactionMode, CompactionTrigger};
15use crate::permissions::PermissionRequest;
16use crate::utils::dot_config::load_lifecycle_hook_approval;
17
18use crate::hooks::lifecycle::compiled::CompiledLifecycleHooks;
19use crate::hooks::lifecycle::interpret::{
20 HookCommandResult, interpret_permission_request, interpret_post_tool, interpret_pre_tool, interpret_session_end,
21 interpret_session_start, interpret_stop, interpret_user_prompt,
22};
23use crate::hooks::lifecycle::types::{
24 HookMessage, NotificationHookType, PermissionRequestHookOutcome, PostToolHookOutcome, PreCompactHookOutcome,
25 PreToolHookDecision, PreToolHookOutcome, SessionEndReason, SessionStartHookOutcome, SessionStartTrigger,
26 StopHookOutcome, UserPromptHookOutcome,
27};
28#[cfg(test)]
29use crate::hooks::lifecycle::utils::generate_session_id;
30use crate::hooks::lifecycle::utils::path_to_string;
31
32const DEFAULT_TIMEOUT_SECS: u64 = 60;
33
34const HOOK_POST_KILL_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
39
40mod process_guard;
41#[cfg(unix)]
42use process_guard::HookProcessGroupGuard;
43
44mod payloads;
45
46#[derive(Clone)]
47pub struct LifecycleHookEngine {
48 inner: Arc<LifecycleHookInner>,
49}
50
51impl LifecycleHookEngine {
52 #[cfg(test)]
57 pub fn new(workspace: PathBuf, config: &HooksConfig, trigger: SessionStartTrigger) -> Result<Option<Self>> {
58 Self::new_with_session(workspace, config, trigger, generate_session_id())
59 }
60
61 #[cfg(test)]
63 pub fn new_with_session(
64 workspace: PathBuf,
65 config: &HooksConfig,
66 trigger: SessionStartTrigger,
67 session_id: impl Into<String>,
68 ) -> Result<Option<Self>> {
69 Self::new_with_session_gated(workspace, config, trigger, session_id, false)
70 }
71
72 pub fn new_with_session_gated(
83 workspace: PathBuf,
84 config: &HooksConfig,
85 trigger: SessionStartTrigger,
86 session_id: impl Into<String>,
87 workspace_gated: bool,
88 ) -> Result<Option<Self>> {
89 if config.lifecycle.is_empty() {
90 return Ok(None);
91 }
92
93 let compiled = CompiledLifecycleHooks::from_config(&config.lifecycle)?;
94 if compiled.is_empty() {
95 return Ok(None);
96 }
97
98 let command_digest = commands_digest(&compiled);
99
100 Ok(Some(Self {
101 inner: Arc::new(LifecycleHookInner {
102 workspace,
103 session_id: session_id.into(),
104 trigger,
105 hooks: compiled,
106 workspace_gated,
107 command_digest,
108 state: Mutex::new(LifecycleHookState {
109 transcript_path: None,
110 approved_workspace_digest: None,
111 }),
112 }),
113 }))
114 }
115
116 pub async fn run_session_start(&self) -> Result<SessionStartHookOutcome> {
117 let mut messages = Vec::new();
118 let mut additional_context = Vec::new();
119
120 if self.inner.hooks.session_start.is_empty() {
121 return Ok(SessionStartHookOutcome { messages, additional_context });
122 }
123
124 let trigger_value = self.inner.trigger.as_str().to_owned();
125 let payload = self.build_session_start_payload().await?;
126
127 for group in &self.inner.hooks.session_start {
128 if !group.matcher.matches(&trigger_value) {
129 continue;
130 }
131
132 for command in &group.commands {
133 match self.execute_command("SessionStart", command, &payload).await {
134 Ok(result) => interpret_session_start(
135 command,
136 &result,
137 &mut messages,
138 &mut additional_context,
139 self.inner.hooks.quiet_success_output,
140 ),
141 Err(err) => messages
142 .push(HookMessage::error(format!("SessionStart hook `{}` failed: {err}", command.command))),
143 }
144 }
145 }
146
147 Ok(SessionStartHookOutcome { messages, additional_context })
148 }
149
150 pub async fn run_session_end(&self, turn_id: &str, reason: SessionEndReason) -> Result<Vec<HookMessage>> {
151 let mut messages = Vec::new();
152
153 if self.inner.hooks.session_end.is_empty() {
154 return Ok(messages);
155 }
156
157 let payload = self.build_session_end_payload(turn_id, reason).await?;
158 let reason_value = reason.as_str().to_owned();
159
160 for group in &self.inner.hooks.session_end {
161 if !group.matcher.matches(&reason_value) {
162 continue;
163 }
164
165 for command in &group.commands {
166 match self.execute_command("SessionEnd", command, &payload).await {
167 Ok(result) => {
168 interpret_session_end(command, &result, &mut messages, self.inner.hooks.quiet_success_output)
169 }
170 Err(err) => messages
171 .push(HookMessage::error(format!("SessionEnd hook `{}` failed: {err}", command.command))),
172 }
173 }
174 }
175
176 Ok(messages)
177 }
178
179 pub async fn run_subagent_start(
180 &self,
181 parent_session_id: &str,
182 child_thread_id: &str,
183 agent_name: &str,
184 display_label: &str,
185 background: bool,
186 status: &str,
187 transcript_path: Option<&std::path::Path>,
188 ) -> Result<Vec<HookMessage>> {
189 let mut messages = Vec::new();
190
191 if self.inner.hooks.subagent_start.is_empty() {
192 return Ok(messages);
193 }
194
195 let payload = self
196 .build_subagent_start_payload(
197 parent_session_id,
198 child_thread_id,
199 agent_name,
200 display_label,
201 background,
202 status,
203 transcript_path,
204 )
205 .await?;
206 let matcher_value = agent_name.to_owned();
207
208 for group in &self.inner.hooks.subagent_start {
209 if !group.matcher.matches(&matcher_value) {
210 continue;
211 }
212
213 for command in &group.commands {
214 match self.execute_command("SubagentStart", command, &payload).await {
215 Ok(result) => {
216 interpret_session_end(command, &result, &mut messages, self.inner.hooks.quiet_success_output)
217 }
218 Err(err) => messages
219 .push(HookMessage::error(format!("SubagentStart hook `{}` failed: {err}", command.command))),
220 }
221 }
222 }
223
224 Ok(messages)
225 }
226
227 pub async fn run_subagent_stop(
228 &self,
229 parent_session_id: &str,
230 child_thread_id: &str,
231 agent_name: &str,
232 display_label: &str,
233 background: bool,
234 status: &str,
235 transcript_path: Option<&std::path::Path>,
236 ) -> Result<Vec<HookMessage>> {
237 let mut messages = Vec::new();
238
239 if self.inner.hooks.subagent_stop.is_empty() {
240 return Ok(messages);
241 }
242
243 let payload = self
244 .build_subagent_stop_payload(
245 parent_session_id,
246 child_thread_id,
247 agent_name,
248 display_label,
249 background,
250 status,
251 transcript_path,
252 )
253 .await?;
254 let matcher_value = agent_name.to_owned();
255
256 for group in &self.inner.hooks.subagent_stop {
257 if !group.matcher.matches(&matcher_value) {
258 continue;
259 }
260
261 for command in &group.commands {
262 match self.execute_command("SubagentStop", command, &payload).await {
263 Ok(result) => {
264 interpret_session_end(command, &result, &mut messages, self.inner.hooks.quiet_success_output)
265 }
266 Err(err) => messages
267 .push(HookMessage::error(format!("SubagentStop hook `{}` failed: {err}", command.command))),
268 }
269 }
270 }
271
272 Ok(messages)
273 }
274
275 pub async fn run_user_prompt_submit(&self, turn_id: &str, prompt: &str) -> Result<UserPromptHookOutcome> {
277 let mut outcome = UserPromptHookOutcome::default();
278
279 if self.inner.hooks.user_prompt_submit.is_empty() {
280 return Ok(outcome);
281 }
282
283 let payload = self.build_user_prompt_payload(turn_id, prompt).await?;
284
285 for group in &self.inner.hooks.user_prompt_submit {
286 if !group.matcher.matches(prompt) {
287 continue;
288 }
289
290 for command in &group.commands {
291 match self.execute_command("UserPromptSubmit", command, &payload).await {
292 Ok(result) => {
293 interpret_user_prompt(command, &result, &mut outcome, self.inner.hooks.quiet_success_output);
294 if !outcome.allow_prompt {
295 return Ok(outcome);
296 }
297 }
298 Err(err) => outcome
299 .messages
300 .push(HookMessage::error(format!("UserPromptSubmit hook `{}` failed: {err}", command.command))),
301 }
302 }
303 }
304
305 Ok(outcome)
306 }
307
308 pub async fn run_permission_request(
310 &self,
311 tool_name: &str,
312 tool_input: Option<&Value>,
313 permission_request: &PermissionRequest,
314 permission_suggestions: &[Value],
315 ) -> Result<PermissionRequestHookOutcome> {
316 let mut outcome = PermissionRequestHookOutcome::default();
317
318 if self.inner.hooks.permission_request.is_empty() {
319 return Ok(outcome);
320 }
321
322 let payload = self
323 .build_permission_request_payload(tool_name, tool_input, permission_request, permission_suggestions)
324 .await?;
325
326 for group in &self.inner.hooks.permission_request {
327 if !group.matcher.matches(tool_name) {
328 continue;
329 }
330
331 for command in &group.commands {
332 match self.execute_command("PermissionRequest", command, &payload).await {
333 Ok(result) => {
334 interpret_permission_request(
335 command,
336 &result,
337 &mut outcome,
338 self.inner.hooks.quiet_success_output,
339 );
340 if outcome.decision.is_some() {
341 return Ok(outcome);
342 }
343 }
344 Err(err) => outcome.messages.push(HookMessage::error(format!(
345 "PermissionRequest hook `{}` failed: {err}",
346 command.command
347 ))),
348 }
349 }
350 }
351
352 Ok(outcome)
353 }
354
355 pub async fn run_pre_tool_use(
363 &self,
364 tool_name: &str,
365 tool_input: Option<&Value>,
366 tool_call_id: Option<&str>,
367 ) -> Result<PreToolHookOutcome> {
368 let mut outcome = PreToolHookOutcome::default();
369
370 if self.inner.hooks.pre_tool_use.is_empty() {
371 return Ok(outcome);
372 }
373
374 let mut payload = self.build_pre_tool_payload(tool_name, tool_input, tool_call_id).await?;
375
376 for group in &self.inner.hooks.pre_tool_use {
377 if !group.matcher.matches(tool_name) {
378 continue;
379 }
380
381 for command in &group.commands {
382 match self.execute_command("PreToolUse", command, &payload).await {
383 Ok(result) => {
384 interpret_pre_tool(command, &result, &mut outcome, self.inner.hooks.quiet_success_output);
385 if let Some(updated) = outcome.updated_input.take() {
386 outcome.updated_input = Some(updated.clone());
387 if let Some(payload_obj) = payload.as_object_mut() {
388 payload_obj.insert("tool_input".to_string(), updated);
389 }
390 }
391 match outcome.decision {
392 PreToolHookDecision::Allow | PreToolHookDecision::Deny => {
393 return Ok(outcome);
394 }
395 _ => {}
396 }
397 }
398 Err(err) => outcome
399 .messages
400 .push(HookMessage::error(format!("PreToolUse hook `{}` failed: {err}", command.command))),
401 }
402 }
403 }
404
405 Ok(outcome)
406 }
407
408 pub async fn run_post_tool_use(
410 &self,
411 tool_name: &str,
412 tool_input: Option<&Value>,
413 tool_output: &Value,
414 tool_call_id: Option<&str>,
415 ) -> Result<PostToolHookOutcome> {
416 let mut outcome = PostToolHookOutcome::default();
417
418 if self.inner.hooks.post_tool_use.is_empty() {
419 return Ok(outcome);
420 }
421
422 let payload = self
423 .build_post_tool_payload(tool_name, tool_input, tool_output, tool_call_id)
424 .await?;
425
426 for group in &self.inner.hooks.post_tool_use {
427 if !group.matcher.matches(tool_name) {
428 continue;
429 }
430
431 for command in &group.commands {
432 match self.execute_command("PostToolUse", command, &payload).await {
433 Ok(result) => {
434 interpret_post_tool(command, &result, &mut outcome, self.inner.hooks.quiet_success_output)
435 }
436 Err(err) => outcome
437 .messages
438 .push(HookMessage::error(format!("PostToolUse hook `{}` failed: {err}", command.command))),
439 }
440 }
441 }
442
443 Ok(outcome)
444 }
445
446 pub async fn run_pre_compact(
448 &self,
449 trigger: CompactionTrigger,
450 mode: CompactionMode,
451 original_message_count: usize,
452 compacted_message_count: usize,
453 history_artifact_path: Option<&str>,
454 ) -> Result<PreCompactHookOutcome> {
455 let mut outcome = PreCompactHookOutcome::default();
456
457 if self.inner.hooks.pre_compact.is_empty() {
458 return Ok(outcome);
459 }
460
461 let payload = self
462 .build_pre_compact_payload(
463 trigger,
464 mode,
465 original_message_count,
466 compacted_message_count,
467 history_artifact_path,
468 )
469 .await?;
470 let trigger_value = trigger.as_str().to_owned();
471
472 for group in &self.inner.hooks.pre_compact {
473 if !group.matcher.matches(&trigger_value) {
474 continue;
475 }
476
477 for command in &group.commands {
478 match self.execute_command("PreCompact", command, &payload).await {
479 Ok(result) => {
480 interpret_session_end(
481 command,
482 &result,
483 &mut outcome.messages,
484 self.inner.hooks.quiet_success_output,
485 );
486 }
487 Err(err) => outcome
488 .messages
489 .push(HookMessage::error(format!("PreCompact hook `{}` failed: {err}", command.command))),
490 }
491 }
492 }
493
494 Ok(outcome)
495 }
496
497 pub async fn run_notification(
499 &self,
500 notification_type: NotificationHookType,
501 title: &str,
502 message: &str,
503 ) -> Result<Vec<HookMessage>> {
504 let mut messages = Vec::new();
505
506 if self.inner.hooks.notification.is_empty() {
507 return Ok(messages);
508 }
509
510 let payload = self.build_notification_payload(notification_type, title, message).await?;
511 let matcher_value = notification_type.as_str().to_owned();
512
513 for group in &self.inner.hooks.notification {
514 if !group.matcher.matches(&matcher_value) {
515 continue;
516 }
517
518 for command in &group.commands {
519 match self.execute_command("Notification", command, &payload).await {
520 Ok(result) => {
521 interpret_session_end(command, &result, &mut messages, self.inner.hooks.quiet_success_output)
522 }
523 Err(err) => messages
524 .push(HookMessage::error(format!("Notification hook `{}` failed: {err}", command.command))),
525 }
526 }
527 }
528
529 Ok(messages)
530 }
531
532 pub async fn run_stop(&self, last_assistant_message: &str, stop_hook_active: bool) -> Result<StopHookOutcome> {
534 let mut outcome = StopHookOutcome::default();
535
536 if self.inner.hooks.stop.is_empty() {
537 return Ok(outcome);
538 }
539
540 let payload = self.build_stop_payload(last_assistant_message, stop_hook_active).await?;
541
542 for group in &self.inner.hooks.stop {
543 if !group.matcher.matches("stop") {
544 continue;
545 }
546
547 for command in &group.commands {
548 match self.execute_command("Stop", command, &payload).await {
549 Ok(result) => {
550 interpret_stop(command, &result, &mut outcome, self.inner.hooks.quiet_success_output);
551 if outcome.block_reason.is_some() {
552 return Ok(outcome);
553 }
554 }
555 Err(err) => outcome
556 .messages
557 .push(HookMessage::error(format!("Stop hook `{}` failed: {err}", command.command))),
558 }
559 }
560 }
561
562 Ok(outcome)
563 }
564
565 pub async fn update_transcript_path(&self, path: Option<PathBuf>) {
567 let mut state = self.inner.state.lock().await;
568 state.transcript_path = path;
569 }
570
571 pub async fn transcript_path(&self) -> Option<PathBuf> {
573 let state = self.inner.state.lock().await;
574 state.transcript_path.clone()
575 }
576
577 pub fn workspace_gated(&self) -> bool {
579 self.inner.workspace_gated
580 }
581
582 pub fn command_digest(&self) -> &str {
585 &self.inner.command_digest
586 }
587
588 pub fn command_previews(&self) -> Vec<LifecycleHookCommandPreview> {
591 let mut previews = Vec::new();
592 self.inner.hooks.for_each_command(|event, matcher, command| {
593 previews.push(LifecycleHookCommandPreview {
594 event,
595 matcher: matcher.map(str::to_string),
596 command: command.command.clone(),
597 timeout_seconds: command.timeout_seconds,
598 });
599 });
600 previews
601 }
602
603 pub async fn approve_workspace_hooks(&self) {
606 let mut state = self.inner.state.lock().await;
607 state.approved_workspace_digest = Some(self.inner.command_digest.clone());
608 }
609
610 pub async fn workspace_hooks_need_approval(&self) -> bool {
614 if !self.inner.workspace_gated {
615 return false;
616 }
617 let state = self.inner.state.lock().await;
618 state.approved_workspace_digest.as_deref() != Some(self.inner.command_digest.as_str())
619 }
620
621 async fn workspace_approval_granted(&self) -> bool {
625 if !self.inner.workspace_gated {
626 return true;
627 }
628 let state = self.inner.state.lock().await;
629 state.approved_workspace_digest.as_deref() == Some(self.inner.command_digest.as_str())
630 }
631
632 async fn execute_command(
633 &self,
634 event_name: &str,
635 command: &HookCommandConfig,
636 payload: &Value,
637 ) -> Result<HookCommandResult> {
638 if !self.workspace_approval_granted().await {
639 return Err(anyhow::anyhow!(
640 "skipped: the workspace configuration defines lifecycle hooks that are not approved for this workspace. \
641 Approve workspace lifecycle hooks at session start to enable `{}` (event: {event_name}).",
642 command.command
643 ));
644 }
645
646 let mut process = Command::new("sh");
647 process.arg("-c").arg(&command.command);
648 process.current_dir(&self.inner.workspace);
649 process.stdin(Stdio::piped());
650 process.stdout(Stdio::piped());
651 process.stderr(Stdio::piped());
652 process.kill_on_drop(true);
653 #[cfg(unix)]
656 process.process_group(0);
657
658 let workspace_str = self.inner.workspace.to_string_lossy().into_owned();
659 process.env("VT_PROJECT_DIR", &workspace_str);
660 process.env("CLAUDE_PROJECT_DIR", &workspace_str);
661 process.env("VT_SESSION_ID", &self.inner.session_id);
662 process.env("CLAUDE_SESSION_ID", &self.inner.session_id);
663 process.env("VT_HOOK_EVENT", event_name);
664
665 if let Some(transcript_path) = self.current_transcript_path().await {
666 process.env("VT_TRANSCRIPT_PATH", &transcript_path);
667 process.env("CLAUDE_TRANSCRIPT_PATH", &transcript_path);
668 }
669
670 let mut child = process
671 .spawn()
672 .with_context(|| format!("failed to spawn lifecycle hook `{}`", command.command))?;
673 #[cfg(unix)]
674 let mut group_guard = HookProcessGroupGuard::new(child.id());
675
676 if let Some(mut stdin) = child.stdin.take() {
677 let mut payload_bytes =
678 serde_json::to_vec(payload).context("failed to serialize lifecycle hook payload")?;
679 payload_bytes.push(b'\n');
680 stdin
681 .write_all(&payload_bytes)
682 .await
683 .context("failed to write lifecycle hook payload")?;
684 stdin.shutdown().await.context("failed to close lifecycle hook stdin")?;
685 }
686
687 let mut stdout_pipe = child.stdout.take().context("lifecycle hook missing stdout pipe")?;
688 let mut stderr_pipe = child.stderr.take().context("lifecycle hook missing stderr pipe")?;
689
690 let stdout_task = tokio::spawn(async move {
691 let mut buffer = Vec::new();
692 stdout_pipe.read_to_end(&mut buffer).await.map(|_| buffer)
693 });
694 let stderr_task = tokio::spawn(async move {
695 let mut buffer = Vec::new();
696 stderr_pipe.read_to_end(&mut buffer).await.map(|_| buffer)
697 });
698
699 let timeout_secs = command.timeout_seconds.unwrap_or(DEFAULT_TIMEOUT_SECS).max(1);
700 let wait_result = time::timeout(Duration::from_secs(timeout_secs), child.wait()).await;
701
702 let (exit_code, timed_out) = match wait_result {
703 Ok(status_res) => {
704 let status = status_res.context("failed to wait for lifecycle hook")?;
705 #[cfg(unix)]
706 group_guard.disarm();
707 (status.code(), false)
708 }
709 Err(_) => {
710 #[cfg(unix)]
711 group_guard.kill();
712 #[cfg(not(unix))]
713 let _ = child.start_kill();
714 let _ = child.wait().await;
715 (None, true)
716 }
717 };
718
719 let stdout_bytes = if timed_out {
723 match time::timeout(HOOK_POST_KILL_DRAIN_TIMEOUT, stdout_task).await {
724 Ok(result) => result.unwrap_or_else(|_| Ok(Vec::new())).unwrap_or_default(),
725 Err(_) => Vec::new(),
726 }
727 } else {
728 stdout_task.await.unwrap_or_else(|_| Ok(Vec::new())).unwrap_or_default()
729 };
730 let stderr_bytes = if timed_out {
731 match time::timeout(HOOK_POST_KILL_DRAIN_TIMEOUT, stderr_task).await {
732 Ok(result) => result.unwrap_or_else(|_| Ok(Vec::new())).unwrap_or_default(),
733 Err(_) => Vec::new(),
734 }
735 } else {
736 stderr_task.await.unwrap_or_else(|_| Ok(Vec::new())).unwrap_or_default()
737 };
738
739 Ok(HookCommandResult {
740 exit_code,
741 stdout: String::from_utf8_lossy(&stdout_bytes).into_owned(),
742 stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
743 timed_out,
744 timeout_seconds: timeout_secs,
745 })
746 }
747
748 async fn current_transcript_path(&self) -> Option<String> {
749 let state = self.inner.state.lock().await;
750 state.transcript_path.as_ref().and_then(|path| path_to_string(path))
751 }
752}
753
754struct LifecycleHookInner {
755 workspace: PathBuf,
756 session_id: String,
757 trigger: SessionStartTrigger,
758 hooks: CompiledLifecycleHooks,
759 workspace_gated: bool,
760 command_digest: String,
761 state: Mutex<LifecycleHookState>,
762}
763
764struct LifecycleHookState {
765 transcript_path: Option<PathBuf>,
766 approved_workspace_digest: Option<String>,
767}
768
769#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
773pub struct LifecycleHookCommandPreview {
774 pub event: &'static str,
776 pub matcher: Option<String>,
778 pub command: String,
780 pub timeout_seconds: Option<u64>,
782}
783
784mod approval;
785use approval::commands_digest;
786pub use approval::{carry_or_restore_workspace_hook_approval, restore_workspace_hook_approval};