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