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 shell_tool_name(&self) -> &'static str {
26        QwenHookFormat::SHELL_TOOL
27    }
28
29    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
30        vec![home.join(".qwen")]
31    }
32
33    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
34        let dir = home.join(".qwen");
35        if !dir.exists() {
36            return Ok(InstallOutcome::Skipped { reason: format!("~/.qwen not found at {} (Qwen Code not installed)", dir.display()) });
37        }
38
39        let path = dir.join("settings.json");
40        let binary = "safe-chains hook qwen";
41
42        if path.exists() {
43            let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
44            let mut settings: Value = serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
45
46            if has_safe_chains_hook(&settings) {
47                if !migrate_legacy_entries(&mut settings) {
48                    return Ok(InstallOutcome::AlreadyConfigured { path });
49                }
50                let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
51                std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
52                return Ok(InstallOutcome::Installed { path });
53            }
54
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")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
58            Ok(InstallOutcome::Installed { path })
59        } else {
60            let mut settings = Value::Object(Map::new());
61            add_hook(&mut settings, binary)?;
62            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
63            std::fs::write(&path, format!("{output}\n")).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
75impl QwenHookFormat {
76    /// The runtime tool id Qwen puts in `tool_name`. `Bash` is accepted as a matcher alias only; the
77    /// payload carries this id (hooks docs, "Tool hooks receive the runtime tool id in `tool_name`").
78    const SHELL_TOOL: &'static str = "run_shell_command";
79}
80
81#[derive(Deserialize)]
82struct ToolInput {
83    command: String,
84    /// Where the command runs (`ShellToolParams.directory` in qwen-code v0.25.3).
85    #[serde(default)]
86    directory: Option<String>,
87}
88
89#[derive(Deserialize)]
90struct QwenHookEnvelope {
91    /// Optional so a harness that omits it still works; when present and naming another tool we
92    /// abstain (see parse_input).
93    #[serde(default)]
94    tool_name: Option<String>,
95    tool_input: ToolInput,
96    #[serde(default)]
97    cwd: Option<String>,
98}
99
100impl HookFormat for QwenHookFormat {
101    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
102        let envelope: QwenHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
103        // Self-filter on the tool: the hook can be delivered for a non-shell call by a
104        // hand-edited matcher, and deciding on one grants or vetoes a tool never analysed.
105        if let Some(name) = &envelope.tool_name
106            && name != QwenHookFormat::SHELL_TOOL
107            && name != "Bash"
108        {
109            return Err(ParseError { message: format!("not a shell tool: {name}") });
110        }
111        let (cwd, cwd_declared) = super::declared_cwd(envelope.cwd, envelope.tool_input.directory.as_deref());
112        Ok(HookInput {
113            command: envelope.tool_input.command,
114            cwd,
115            cwd_declared,
116            root: super::env_root("QWEN_PROJECT_DIR"),
117            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
118            session_id: None,
119            permission_mode: None,
120        })
121    }
122
123    fn decision_pointer(&self) -> &'static str {
124        "/hookSpecificOutput/permissionDecision" // mirrors Claude's nesting
125    }
126
127    fn render_response(&self, verdict: Verdict) -> HookResponse {
128        if verdict.is_allowed() {
129            let reason = allow_reason(verdict);
130            // Qwen mirrors Claude Code's hookSpecificOutput envelope.
131            let body = json!({
132                "hookSpecificOutput": {
133                    "hookEventName": "PreToolUse",
134                    "permissionDecision": "allow",
135                    "permissionDecisionReason": reason,
136                }
137            });
138            HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
139        } else {
140            HookResponse { stdout: String::new(), exit_code: 0 }
141        }
142    }
143
144    fn render_context(&self, context: &str) -> HookResponse {
145        // Qwen mirrors Claude Code's hookSpecificOutput envelope, including
146        // additionalContext (injects model-visible text, no permission decision).
147        let body = json!({
148            "hookSpecificOutput": {
149                "hookEventName": "PreToolUse",
150                "additionalContext": context,
151            }
152        });
153        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
154    }
155}
156
157fn hook_entry(binary: &str) -> Value {
158    json!({
159        "matcher": "^run_shell_command$",
160        "hooks": [{
161            "type": "command",
162            "command": binary,
163            "timeout": 60,
164        }]
165    })
166}
167
168fn has_safe_chains_hook(settings: &Value) -> bool {
169    settings
170        .get("hooks")
171        .and_then(|h| h.get("PreToolUse"))
172        .and_then(|arr| arr.as_array())
173        .is_some_and(|entries| {
174            entries
175                .iter()
176                .any(|entry| entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| hooks.iter().any(is_our_hook)))
177        })
178}
179
180const LEGACY_MATCHER: &str = "^Bash$";
181const LEGACY_TIMEOUT: u64 = 60_000;
182
183fn is_our_hook(hook: &Value) -> bool {
184    hook.get("command").and_then(Value::as_str).is_some_and(|cmd| cmd.contains("safe-chains"))
185}
186
187fn migrate_legacy_entries(settings: &mut Value) -> bool {
188    let Some(entries) = settings.pointer_mut("/hooks/PreToolUse").and_then(Value::as_array_mut) else {
189        return false;
190    };
191    let mut changed = false;
192    for entry in entries.iter_mut() {
193        let ours = entry.get("hooks").and_then(Value::as_array).is_some_and(|hooks| hooks.iter().any(is_our_hook));
194        if !ours {
195            continue;
196        }
197        if entry.get("matcher").and_then(Value::as_str) == Some(LEGACY_MATCHER) {
198            entry["matcher"] = json!("^run_shell_command$");
199            changed = true;
200        }
201        let Some(hooks) = entry.get_mut("hooks").and_then(Value::as_array_mut) else {
202            continue;
203        };
204        for hook in hooks.iter_mut().filter(|h| is_our_hook(h)) {
205            if hook.get("timeout").and_then(Value::as_u64) == Some(LEGACY_TIMEOUT) {
206                hook["timeout"] = json!(60);
207                changed = true;
208            }
209        }
210    }
211    changed
212}
213
214fn add_hook(settings: &mut Value, binary: &str) -> Result<(), String> {
215    super::append_hook_entry(settings, "hooks", "PreToolUse", hook_entry(binary))
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::verdict::SafetyLevel;
222
223    fn target() -> QwenTarget {
224        QwenTarget
225    }
226
227    /// Verbatim shape from the Qwen Code hooks docs.
228    const QWEN_DOCS_SAMPLE: &str = r#"{
229        "session_id": "abc123",
230        "transcript_path": "/Users/me/.qwen/transcripts/abc.json",
231        "cwd": "/Users/me/project",
232        "hook_event_name": "PreToolUse",
233        "timestamp": "2026-05-06T12:00:00Z",
234        "permission_mode": "default",
235        "tool_name": "run_shell_command",
236        "tool_input": {"command": "ls -la"},
237        "tool_use_id": "tu_123"
238    }"#;
239
240    #[test]
241    fn install_no_qwen_dir_skips() {
242        let dir = tempfile::tempdir().unwrap();
243        let outcome = target().install(dir.path()).unwrap();
244        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
245    }
246
247    #[test]
248    fn install_creates_settings_file() {
249        let dir = tempfile::tempdir().unwrap();
250        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
251        let outcome = target().install(dir.path()).unwrap();
252        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
253        let contents = std::fs::read_to_string(dir.path().join(".qwen/settings.json")).unwrap();
254        let settings: Value = serde_json::from_str(&contents).unwrap();
255        assert!(has_safe_chains_hook(&settings));
256    }
257
258    #[test]
259    fn install_uses_runtime_id_matcher() {
260        let dir = tempfile::tempdir().unwrap();
261        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
262        target().install(dir.path()).unwrap();
263        let contents = std::fs::read_to_string(dir.path().join(".qwen/settings.json")).unwrap();
264        assert!(contents.contains("^run_shell_command$"));
265        assert!(contents.contains("safe-chains hook qwen"));
266    }
267
268    #[test]
269    fn install_idempotent() {
270        let dir = tempfile::tempdir().unwrap();
271        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
272        target().install(dir.path()).unwrap();
273        let outcome = target().install(dir.path()).unwrap();
274        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
275    }
276
277    #[test]
278    fn install_migrates_the_old_bash_matcher_without_duplicating() {
279        let dir = tempfile::tempdir().unwrap();
280        std::fs::create_dir(dir.path().join(".qwen")).unwrap();
281        let old = r#"{"hooks":{"PreToolUse":[
282            {"matcher":"^Bash$","hooks":[{"type":"command","command":"safe-chains hook qwen","timeout":60000}]},
283            {"matcher":"^Bash$","hooks":[{"type":"command","command":"my-own-hook","timeout":60000}]}
284        ]}}"#;
285        let path = dir.path().join(".qwen/settings.json");
286        std::fs::write(&path, old).unwrap();
287
288        let outcome = target().install(dir.path()).unwrap();
289        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
290        let settings: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
291        let entries = settings.pointer("/hooks/PreToolUse").and_then(Value::as_array).unwrap();
292        assert_eq!(entries.len(), 2);
293        assert_eq!(entries[0], hook_entry("safe-chains hook qwen"));
294        assert_eq!(entries[1].get("matcher").and_then(Value::as_str), Some("^Bash$"));
295        assert_eq!(entries[1].pointer("/hooks/0/timeout").and_then(Value::as_u64), Some(60000));
296
297        let again = target().install(dir.path()).unwrap();
298        assert!(matches!(again, InstallOutcome::AlreadyConfigured { .. }));
299    }
300
301    #[test]
302    fn parse_input_extracts_command() {
303        let parsed = QwenHookFormat.parse_input(QWEN_DOCS_SAMPLE).unwrap();
304        assert_eq!(parsed.command, "ls -la");
305        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
306    }
307
308    /// Qwen sends the runtime tool id in `tool_name`; `Bash` is only a matcher alias. Refusing the real
309    /// name made the hook abstain on every command.
310    #[test]
311    fn parse_input_accepts_runtime_shell_id_and_the_alias() {
312        for name in ["run_shell_command", "Bash"] {
313            let json = format!(r#"{{"tool_name":"{name}","tool_input":{{"command":"ls"}}}}"#);
314            assert_eq!(QwenHookFormat.parse_input(&json).unwrap().command, "ls");
315        }
316        let other = r#"{"tool_name":"write_file","tool_input":{"command":"ls"}}"#;
317        assert!(QwenHookFormat.parse_input(other).is_err());
318    }
319
320    #[test]
321    fn install_timeout_is_in_seconds() {
322        let hook = hook_entry("safe-chains hook qwen");
323        assert_eq!(hook.pointer("/hooks/0/timeout").and_then(Value::as_u64), Some(60));
324    }
325
326    #[test]
327    fn parse_input_rejects_garbage() {
328        assert!(QwenHookFormat.parse_input("not json").is_err());
329        assert!(QwenHookFormat.parse_input("{}").is_err());
330    }
331
332    #[test]
333    fn render_response_emits_claude_shaped_envelope() {
334        let r = QwenHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
335        let v: Value = serde_json::from_str(&r.stdout).unwrap();
336        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("allow"),);
337        assert_eq!(v.pointer("/hookSpecificOutput/hookEventName").and_then(|d| d.as_str()), Some("PreToolUse"),);
338    }
339
340    #[test]
341    fn render_response_deny_emits_empty_body() {
342        let r = QwenHookFormat.render_response(Verdict::Denied);
343        assert_eq!(r.stdout, "");
344    }
345}