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