claude_code_agent/fs_events.rs
1//! Typed filesystem events from `FileChanged` / `CwdChanged` / `DirectoryAdded` hooks.
2//!
3//! Register a hook, then decode its payload:
4//!
5//! ```rust,no_run
6//! use claude_code_agent::HookRegistry;
7//! use claude_code_agent::fs_events::FsEvent;
8//! use claude_code_agent::protocol::{HookEventKind, HookOutput};
9//!
10//! let mut hooks = HookRegistry::new();
11//! hooks.on(HookEventKind::CwdChanged, None, |payload| async move {
12//! match FsEvent::from_payload(&payload) {
13//! Some(FsEvent::CwdChanged { new_cwd, .. }) => {
14//! // Watch the new project's sources; FileChanged hooks fire for them.
15//! HookOutput::watch_paths(HookEventKind::CwdChanged, vec![format!("{new_cwd}/src")])
16//! }
17//! _ => HookOutput::allow(),
18//! }
19//! });
20//! ```
21//!
22//! Limitation (verified against 2.1.328): the CLI delivers `CwdChanged` and
23//! `FileChanged` to shell hooks declared in settings (`SessionOptions::settings`)
24//! but not to SDK hook callbacks. Use `FsEvent::from_payload` on the JSON a
25//! settings hook receives, or on payloads from a CLI version that forwards them.
26//!
27//! Source: binary hook input schemas (`FileChanged`: `file_path`, event;
28//! `CwdChanged`: `old_cwd`, `new_cwd`; `DirectoryAdded`: directory)
29use crate::protocol::{HookEventKind, HookEventPayload};
30
31/// A filesystem hook event, decoded from its payload.
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum FsEvent {
35 /// `event`: "change" | "add" | "unlink"
36 FileChanged {
37 /// The changed file (`file_path`).
38 path: String,
39 /// What happened to it.
40 event: String,
41 },
42 /// The working directory changed.
43 CwdChanged {
44 /// Previous working directory.
45 old_cwd: String,
46 /// New working directory.
47 new_cwd: String,
48 },
49 /// A directory was added (`DirectoryAdded`).
50 DirectoryAdded {
51 /// The added directory.
52 directory: String,
53 },
54}
55
56impl FsEvent {
57 /// Decode a hook payload; `None` for other events or missing fields.
58 #[must_use]
59 pub fn from_payload(p: &HookEventPayload) -> Option<Self> {
60 let extra = |k: &str| p.extra.get(k).and_then(|v| v.as_str()).map(str::to_owned);
61 match p.hook_event_name {
62 HookEventKind::FileChanged => Some(Self::FileChanged {
63 path: p.file_path.clone()?,
64 event: p.event.clone()?,
65 }),
66 HookEventKind::CwdChanged => Some(Self::CwdChanged {
67 old_cwd: extra("old_cwd")?,
68 new_cwd: extra("new_cwd")?,
69 }),
70 HookEventKind::DirectoryAdded => Some(Self::DirectoryAdded { directory: extra("directory")? }),
71 _ => None,
72 }
73 }
74}