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