Skip to main content

safe_chains/targets/
qwen.rs

1use std::path::{Path, PathBuf};
2
3use serde::Deserialize;
4use serde_json::{Map, Value, json};
5
6use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target, allow_reason};
7use crate::verdict::Verdict;
8
9pub struct QwenTarget;
10
11impl Target for QwenTarget {
12    fn name(&self) -> &'static str {
13        "qwen"
14    }
15
16    fn display_name(&self) -> &'static str {
17        "Qwen Code"
18    }
19
20    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
21        vec![home.join(".qwen")]
22    }
23
24    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
25        let dir = home.join(".qwen");
26        if !dir.exists() {
27            return Ok(InstallOutcome::Skipped {
28                reason: format!(
29                    "~/.qwen not found at {} (Qwen Code not installed)",
30                    dir.display()
31                ),
32            });
33        }
34
35        let path = dir.join("settings.json");
36        let binary = "safe-chains hook qwen";
37
38        if path.exists() {
39            let contents = std::fs::read_to_string(&path)
40                .map_err(|e| format!("Could not read {}: {e}", path.display()))?;
41            let mut settings: Value = serde_json::from_str(&contents)
42                .map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
43
44            if has_safe_chains_hook(&settings) {
45                return Ok(InstallOutcome::AlreadyConfigured { path });
46            }
47
48            add_hook(&mut settings, binary);
49            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
50            std::fs::write(&path, format!("{output}\n"))
51                .map_err(|e| format!("Could not write {}: {e}", path.display()))?;
52            Ok(InstallOutcome::Installed { path })
53        } else {
54            let mut settings = Value::Object(Map::new());
55            add_hook(&mut settings, binary);
56            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
57            std::fs::write(&path, format!("{output}\n"))
58                .map_err(|e| format!("Could not write {}: {e}", path.display()))?;
59            Ok(InstallOutcome::Installed { path })
60        }
61    }
62
63    fn hook_format(&self) -> Option<&dyn HookFormat> {
64        Some(&QwenHookFormat)
65    }
66}
67
68struct QwenHookFormat;
69
70#[derive(Deserialize)]
71struct ToolInput {
72    command: String,
73}
74
75#[derive(Deserialize)]
76struct QwenHookEnvelope {
77    tool_input: ToolInput,
78    #[serde(default)]
79    cwd: Option<String>,
80}
81
82impl HookFormat for QwenHookFormat {
83    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
84        let envelope: QwenHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError {
85            message: e.to_string(),
86        })?;
87        Ok(HookInput {
88            command: envelope.tool_input.command,
89            cwd: envelope.cwd,
90        })
91    }
92
93    fn render_response(&self, verdict: Verdict) -> HookResponse {
94        if verdict.is_allowed() {
95            let reason = allow_reason(verdict);
96            // Qwen mirrors Claude Code's hookSpecificOutput envelope.
97            let body = json!({
98                "hookSpecificOutput": {
99                    "hookEventName": "PreToolUse",
100                    "permissionDecision": "allow",
101                    "permissionDecisionReason": reason,
102                }
103            });
104            HookResponse {
105                stdout: serde_json::to_string(&body).unwrap_or_default(),
106                exit_code: 0,
107            }
108        } else {
109            HookResponse {
110                stdout: String::new(),
111                exit_code: 0,
112            }
113        }
114    }
115
116    fn render_context(&self, context: &str) -> HookResponse {
117        // Qwen mirrors Claude Code's hookSpecificOutput envelope, including
118        // additionalContext (injects model-visible text, no permission decision).
119        let body = json!({
120            "hookSpecificOutput": {
121                "hookEventName": "PreToolUse",
122                "additionalContext": context,
123            }
124        });
125        HookResponse {
126            stdout: serde_json::to_string(&body).unwrap_or_default(),
127            exit_code: 0,
128        }
129    }
130}
131
132fn hook_entry(binary: &str) -> Value {
133    json!({
134        "matcher": "^Bash$",
135        "hooks": [{
136            "type": "command",
137            "command": binary,
138            "timeout": 60_000,
139        }]
140    })
141}
142
143fn has_safe_chains_hook(settings: &Value) -> bool {
144    settings
145        .get("hooks")
146        .and_then(|h| h.get("PreToolUse"))
147        .and_then(|arr| arr.as_array())
148        .is_some_and(|entries| {
149            entries.iter().any(|entry| {
150                entry
151                    .get("hooks")
152                    .and_then(|h| h.as_array())
153                    .is_some_and(|hooks| {
154                        hooks.iter().any(|hook| {
155                            hook.get("command")
156                                .and_then(|c| c.as_str())
157                                .is_some_and(|cmd| cmd.contains("safe-chains"))
158                        })
159                    })
160            })
161        })
162}
163
164fn add_hook(settings: &mut Value, binary: &str) {
165    if !settings.is_object() {
166        *settings = json!({});
167    }
168    let Some(obj) = settings.as_object_mut() else {
169        unreachable!("settings was just set to an object");
170    };
171    let hooks = obj
172        .entry("hooks")
173        .or_insert_with(|| json!({}))
174        .as_object_mut()
175        .expect("hooks key was created above as an object");
176    let pre_tool_use = hooks
177        .entry("PreToolUse")
178        .or_insert_with(|| json!([]))
179        .as_array_mut()
180        .expect("PreToolUse was created above as an array");
181    pre_tool_use.push(hook_entry(binary));
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use crate::verdict::SafetyLevel;
188
189    fn target() -> QwenTarget {
190        QwenTarget
191    }
192
193    /// Verbatim shape from the Qwen Code hooks docs.
194    const QWEN_DOCS_SAMPLE: &str = r#"{
195        "session_id": "abc123",
196        "transcript_path": "/Users/me/.qwen/transcripts/abc.json",
197        "cwd": "/Users/me/project",
198        "hook_event_name": "PreToolUse",
199        "timestamp": "2026-05-06T12:00:00Z",
200        "permission_mode": "default",
201        "tool_name": "Bash",
202        "tool_input": {"command": "ls -la"},
203        "tool_use_id": "tu_123"
204    }"#;
205
206    #[test]
207    fn install_no_qwen_dir_skips() {
208        let dir = tempfile::tempdir().unwrap();
209        let outcome = target().install(dir.path()).unwrap();
210        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
211    }
212
213    #[test]
214    fn install_creates_settings_file() {
215        let dir = tempfile::tempdir().unwrap();
216        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
217        let outcome = target().install(dir.path()).unwrap();
218        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
219        let contents = std::fs::read_to_string(dir.path().join(".qwen/settings.json")).unwrap();
220        let settings: Value = serde_json::from_str(&contents).unwrap();
221        assert!(has_safe_chains_hook(&settings));
222    }
223
224    #[test]
225    fn install_uses_bash_matcher() {
226        let dir = tempfile::tempdir().unwrap();
227        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
228        target().install(dir.path()).unwrap();
229        let contents = std::fs::read_to_string(dir.path().join(".qwen/settings.json")).unwrap();
230        assert!(contents.contains("^Bash$"));
231        assert!(contents.contains("safe-chains hook qwen"));
232    }
233
234    #[test]
235    fn install_idempotent() {
236        let dir = tempfile::tempdir().unwrap();
237        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
238        target().install(dir.path()).unwrap();
239        let outcome = target().install(dir.path()).unwrap();
240        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
241    }
242
243    #[test]
244    fn parse_input_extracts_command() {
245        let parsed = QwenHookFormat.parse_input(QWEN_DOCS_SAMPLE).unwrap();
246        assert_eq!(parsed.command, "ls -la");
247        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
248    }
249
250    #[test]
251    fn parse_input_rejects_garbage() {
252        assert!(QwenHookFormat.parse_input("not json").is_err());
253        assert!(QwenHookFormat.parse_input("{}").is_err());
254    }
255
256    #[test]
257    fn render_response_emits_claude_shaped_envelope() {
258        let r = QwenHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
259        let v: Value = serde_json::from_str(&r.stdout).unwrap();
260        assert_eq!(
261            v.pointer("/hookSpecificOutput/permissionDecision")
262                .and_then(|d| d.as_str()),
263            Some("allow"),
264        );
265        assert_eq!(
266            v.pointer("/hookSpecificOutput/hookEventName")
267                .and_then(|d| d.as_str()),
268            Some("PreToolUse"),
269        );
270    }
271
272    #[test]
273    fn render_response_deny_emits_empty_body() {
274        let r = QwenHookFormat.render_response(Verdict::Denied);
275        assert_eq!(r.stdout, "");
276    }
277}