Skip to main content

ward/
input.rs

1use serde::Deserialize;
2use serde_json::Value;
3
4#[derive(Deserialize)]
5pub struct HookInput {
6    pub session_id: Option<String>,
7    pub hook_event_name: String,
8    pub tool_name: Option<String>,
9    pub tool_input: Option<Value>,
10    pub tool_response: Option<Value>,
11    pub cwd: Option<String>,
12    pub permission_mode: Option<String>,
13    #[serde(flatten)]
14    pub extra: Value,
15}
16
17impl HookInput {
18    /// Extract the file path from tool_input (present in Edit/Write payloads)
19    pub fn file_path(&self) -> Option<&str> {
20        self.tool_input
21            .as_ref()
22            .and_then(|input| input.get("file_path"))
23            .and_then(|v| v.as_str())
24    }
25
26    /// Extract all scannable text from the hook input
27    pub fn extract_text(&self) -> String {
28        let mut parts = Vec::new();
29
30        match self.hook_event_name.as_str() {
31            "UserPromptSubmit" => {
32                // Claude Code sends the prompt in the "prompt" field
33                if let Some(prompt) = self.extra.get("prompt") {
34                    collect_strings(prompt, &mut parts);
35                }
36                // Also check "content" for compatibility with test fixtures
37                if let Some(content) = self.extra.get("content") {
38                    collect_strings(content, &mut parts);
39                }
40            }
41            "PreToolUse" => {
42                if let Some(input) = &self.tool_input {
43                    collect_strings(input, &mut parts);
44                }
45            }
46            "PostToolUse" => {
47                // Scan only the tool's output; its input was already scanned at PreToolUse
48                if let Some(response) = &self.tool_response {
49                    collect_strings(response, &mut parts);
50                }
51            }
52            _ => {}
53        }
54
55        parts.join("\n")
56    }
57}
58
59fn collect_strings(value: &Value, out: &mut Vec<String>) {
60    match value {
61        Value::String(s) => out.push(s.clone()),
62        Value::Object(map) => {
63            for v in map.values() {
64                collect_strings(v, out);
65            }
66        }
67        Value::Array(arr) => {
68            for v in arr {
69                collect_strings(v, out);
70            }
71        }
72        _ => {}
73    }
74}