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            root: super::env_root("QWEN_PROJECT_DIR"),
91        })
92    }
93
94    fn render_response(&self, verdict: Verdict) -> HookResponse {
95        if verdict.is_allowed() {
96            let reason = allow_reason(verdict);
97            // Qwen mirrors Claude Code's hookSpecificOutput envelope.
98            let body = json!({
99                "hookSpecificOutput": {
100                    "hookEventName": "PreToolUse",
101                    "permissionDecision": "allow",
102                    "permissionDecisionReason": reason,
103                }
104            });
105            HookResponse {
106                stdout: serde_json::to_string(&body).unwrap_or_default(),
107                exit_code: 0,
108            }
109        } else {
110            HookResponse {
111                stdout: String::new(),
112                exit_code: 0,
113            }
114        }
115    }
116
117    fn render_context(&self, context: &str) -> HookResponse {
118        // Qwen mirrors Claude Code's hookSpecificOutput envelope, including
119        // additionalContext (injects model-visible text, no permission decision).
120        let body = json!({
121            "hookSpecificOutput": {
122                "hookEventName": "PreToolUse",
123                "additionalContext": context,
124            }
125        });
126        HookResponse {
127            stdout: serde_json::to_string(&body).unwrap_or_default(),
128            exit_code: 0,
129        }
130    }
131}
132
133fn hook_entry(binary: &str) -> Value {
134    json!({
135        "matcher": "^Bash$",
136        "hooks": [{
137            "type": "command",
138            "command": binary,
139            "timeout": 60_000,
140        }]
141    })
142}
143
144fn has_safe_chains_hook(settings: &Value) -> bool {
145    settings
146        .get("hooks")
147        .and_then(|h| h.get("PreToolUse"))
148        .and_then(|arr| arr.as_array())
149        .is_some_and(|entries| {
150            entries.iter().any(|entry| {
151                entry
152                    .get("hooks")
153                    .and_then(|h| h.as_array())
154                    .is_some_and(|hooks| {
155                        hooks.iter().any(|hook| {
156                            hook.get("command")
157                                .and_then(|c| c.as_str())
158                                .is_some_and(|cmd| cmd.contains("safe-chains"))
159                        })
160                    })
161            })
162        })
163}
164
165fn add_hook(settings: &mut Value, binary: &str) {
166    if !settings.is_object() {
167        *settings = json!({});
168    }
169    let Some(obj) = settings.as_object_mut() else {
170        unreachable!("settings was just set to an object");
171    };
172    let hooks = obj
173        .entry("hooks")
174        .or_insert_with(|| json!({}))
175        .as_object_mut()
176        .expect("hooks key was created above as an object");
177    let pre_tool_use = hooks
178        .entry("PreToolUse")
179        .or_insert_with(|| json!([]))
180        .as_array_mut()
181        .expect("PreToolUse was created above as an array");
182    pre_tool_use.push(hook_entry(binary));
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::verdict::SafetyLevel;
189
190    fn target() -> QwenTarget {
191        QwenTarget
192    }
193
194    /// Verbatim shape from the Qwen Code hooks docs.
195    const QWEN_DOCS_SAMPLE: &str = r#"{
196        "session_id": "abc123",
197        "transcript_path": "/Users/me/.qwen/transcripts/abc.json",
198        "cwd": "/Users/me/project",
199        "hook_event_name": "PreToolUse",
200        "timestamp": "2026-05-06T12:00:00Z",
201        "permission_mode": "default",
202        "tool_name": "Bash",
203        "tool_input": {"command": "ls -la"},
204        "tool_use_id": "tu_123"
205    }"#;
206
207    #[test]
208    fn install_no_qwen_dir_skips() {
209        let dir = tempfile::tempdir().unwrap();
210        let outcome = target().install(dir.path()).unwrap();
211        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
212    }
213
214    #[test]
215    fn install_creates_settings_file() {
216        let dir = tempfile::tempdir().unwrap();
217        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
218        let outcome = target().install(dir.path()).unwrap();
219        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
220        let contents = std::fs::read_to_string(dir.path().join(".qwen/settings.json")).unwrap();
221        let settings: Value = serde_json::from_str(&contents).unwrap();
222        assert!(has_safe_chains_hook(&settings));
223    }
224
225    #[test]
226    fn install_uses_bash_matcher() {
227        let dir = tempfile::tempdir().unwrap();
228        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
229        target().install(dir.path()).unwrap();
230        let contents = std::fs::read_to_string(dir.path().join(".qwen/settings.json")).unwrap();
231        assert!(contents.contains("^Bash$"));
232        assert!(contents.contains("safe-chains hook qwen"));
233    }
234
235    #[test]
236    fn install_idempotent() {
237        let dir = tempfile::tempdir().unwrap();
238        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
239        target().install(dir.path()).unwrap();
240        let outcome = target().install(dir.path()).unwrap();
241        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
242    }
243
244    #[test]
245    fn parse_input_extracts_command() {
246        let parsed = QwenHookFormat.parse_input(QWEN_DOCS_SAMPLE).unwrap();
247        assert_eq!(parsed.command, "ls -la");
248        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
249    }
250
251    #[test]
252    fn parse_input_rejects_garbage() {
253        assert!(QwenHookFormat.parse_input("not json").is_err());
254        assert!(QwenHookFormat.parse_input("{}").is_err());
255    }
256
257    #[test]
258    fn render_response_emits_claude_shaped_envelope() {
259        let r = QwenHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
260        let v: Value = serde_json::from_str(&r.stdout).unwrap();
261        assert_eq!(
262            v.pointer("/hookSpecificOutput/permissionDecision")
263                .and_then(|d| d.as_str()),
264            Some("allow"),
265        );
266        assert_eq!(
267            v.pointer("/hookSpecificOutput/hookEventName")
268                .and_then(|d| d.as_str()),
269            Some("PreToolUse"),
270        );
271    }
272
273    #[test]
274    fn render_response_deny_emits_empty_body() {
275        let r = QwenHookFormat.render_response(Verdict::Denied);
276        assert_eq!(r.stdout, "");
277    }
278}