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