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 const SHELL_TOOL: &'static str = "run_shell_command";
79}
80
81#[derive(Deserialize)]
82struct ToolInput {
83 command: String,
84}
85
86#[derive(Deserialize)]
87struct QwenHookEnvelope {
88 #[serde(default)]
91 tool_name: Option<String>,
92 tool_input: ToolInput,
93 #[serde(default)]
94 cwd: Option<String>,
95}
96
97impl HookFormat for QwenHookFormat {
98 fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
99 let envelope: QwenHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
100 if let Some(name) = &envelope.tool_name
103 && name != QwenHookFormat::SHELL_TOOL
104 && name != "Bash"
105 {
106 return Err(ParseError { message: format!("not a shell tool: {name}") });
107 }
108 Ok(HookInput {
109 command: envelope.tool_input.command,
110 cwd: envelope.cwd,
111 root: super::env_root("QWEN_PROJECT_DIR"),
112 session_id: None,
114 permission_mode: None,
115 })
116 }
117
118 fn decision_pointer(&self) -> &'static str {
119 "/hookSpecificOutput/permissionDecision" }
121
122 fn render_response(&self, verdict: Verdict) -> HookResponse {
123 if verdict.is_allowed() {
124 let reason = allow_reason(verdict);
125 let body = json!({
127 "hookSpecificOutput": {
128 "hookEventName": "PreToolUse",
129 "permissionDecision": "allow",
130 "permissionDecisionReason": reason,
131 }
132 });
133 HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
134 } else {
135 HookResponse { stdout: String::new(), exit_code: 0 }
136 }
137 }
138
139 fn render_context(&self, context: &str) -> HookResponse {
140 let body = json!({
143 "hookSpecificOutput": {
144 "hookEventName": "PreToolUse",
145 "additionalContext": context,
146 }
147 });
148 HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
149 }
150}
151
152fn hook_entry(binary: &str) -> Value {
153 json!({
154 "matcher": "^run_shell_command$",
155 "hooks": [{
156 "type": "command",
157 "command": binary,
158 "timeout": 60,
159 }]
160 })
161}
162
163fn has_safe_chains_hook(settings: &Value) -> bool {
164 settings
165 .get("hooks")
166 .and_then(|h| h.get("PreToolUse"))
167 .and_then(|arr| arr.as_array())
168 .is_some_and(|entries| {
169 entries
170 .iter()
171 .any(|entry| entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| hooks.iter().any(is_our_hook)))
172 })
173}
174
175const LEGACY_MATCHER: &str = "^Bash$";
176const LEGACY_TIMEOUT: u64 = 60_000;
177
178fn is_our_hook(hook: &Value) -> bool {
179 hook.get("command").and_then(Value::as_str).is_some_and(|cmd| cmd.contains("safe-chains"))
180}
181
182fn migrate_legacy_entries(settings: &mut Value) -> bool {
183 let Some(entries) = settings.pointer_mut("/hooks/PreToolUse").and_then(Value::as_array_mut) else {
184 return false;
185 };
186 let mut changed = false;
187 for entry in entries.iter_mut() {
188 let ours = entry.get("hooks").and_then(Value::as_array).is_some_and(|hooks| hooks.iter().any(is_our_hook));
189 if !ours {
190 continue;
191 }
192 if entry.get("matcher").and_then(Value::as_str) == Some(LEGACY_MATCHER) {
193 entry["matcher"] = json!("^run_shell_command$");
194 changed = true;
195 }
196 let Some(hooks) = entry.get_mut("hooks").and_then(Value::as_array_mut) else {
197 continue;
198 };
199 for hook in hooks.iter_mut().filter(|h| is_our_hook(h)) {
200 if hook.get("timeout").and_then(Value::as_u64) == Some(LEGACY_TIMEOUT) {
201 hook["timeout"] = json!(60);
202 changed = true;
203 }
204 }
205 }
206 changed
207}
208
209fn add_hook(settings: &mut Value, binary: &str) -> Result<(), String> {
210 super::append_hook_entry(settings, "hooks", "PreToolUse", hook_entry(binary))
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216 use crate::verdict::SafetyLevel;
217
218 fn target() -> QwenTarget {
219 QwenTarget
220 }
221
222 const QWEN_DOCS_SAMPLE: &str = r#"{
224 "session_id": "abc123",
225 "transcript_path": "/Users/me/.qwen/transcripts/abc.json",
226 "cwd": "/Users/me/project",
227 "hook_event_name": "PreToolUse",
228 "timestamp": "2026-05-06T12:00:00Z",
229 "permission_mode": "default",
230 "tool_name": "run_shell_command",
231 "tool_input": {"command": "ls -la"},
232 "tool_use_id": "tu_123"
233 }"#;
234
235 #[test]
236 fn install_no_qwen_dir_skips() {
237 let dir = tempfile::tempdir().unwrap();
238 let outcome = target().install(dir.path()).unwrap();
239 assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
240 }
241
242 #[test]
243 fn install_creates_settings_file() {
244 let dir = tempfile::tempdir().unwrap();
245 std::fs::create_dir(dir.path().join(".qwen")).unwrap();
246 let outcome = target().install(dir.path()).unwrap();
247 assert!(matches!(outcome, InstallOutcome::Installed { .. }));
248 let contents = std::fs::read_to_string(dir.path().join(".qwen/settings.json")).unwrap();
249 let settings: Value = serde_json::from_str(&contents).unwrap();
250 assert!(has_safe_chains_hook(&settings));
251 }
252
253 #[test]
254 fn install_uses_runtime_id_matcher() {
255 let dir = tempfile::tempdir().unwrap();
256 std::fs::create_dir(dir.path().join(".qwen")).unwrap();
257 target().install(dir.path()).unwrap();
258 let contents = std::fs::read_to_string(dir.path().join(".qwen/settings.json")).unwrap();
259 assert!(contents.contains("^run_shell_command$"));
260 assert!(contents.contains("safe-chains hook qwen"));
261 }
262
263 #[test]
264 fn install_idempotent() {
265 let dir = tempfile::tempdir().unwrap();
266 std::fs::create_dir(dir.path().join(".qwen")).unwrap();
267 target().install(dir.path()).unwrap();
268 let outcome = target().install(dir.path()).unwrap();
269 assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
270 }
271
272 #[test]
273 fn install_migrates_the_old_bash_matcher_without_duplicating() {
274 let dir = tempfile::tempdir().unwrap();
275 std::fs::create_dir(dir.path().join(".qwen")).unwrap();
276 let old = r#"{"hooks":{"PreToolUse":[
277 {"matcher":"^Bash$","hooks":[{"type":"command","command":"safe-chains hook qwen","timeout":60000}]},
278 {"matcher":"^Bash$","hooks":[{"type":"command","command":"my-own-hook","timeout":60000}]}
279 ]}}"#;
280 let path = dir.path().join(".qwen/settings.json");
281 std::fs::write(&path, old).unwrap();
282
283 let outcome = target().install(dir.path()).unwrap();
284 assert!(matches!(outcome, InstallOutcome::Installed { .. }));
285 let settings: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
286 let entries = settings.pointer("/hooks/PreToolUse").and_then(Value::as_array).unwrap();
287 assert_eq!(entries.len(), 2);
288 assert_eq!(entries[0], hook_entry("safe-chains hook qwen"));
289 assert_eq!(entries[1].get("matcher").and_then(Value::as_str), Some("^Bash$"));
290 assert_eq!(entries[1].pointer("/hooks/0/timeout").and_then(Value::as_u64), Some(60000));
291
292 let again = target().install(dir.path()).unwrap();
293 assert!(matches!(again, InstallOutcome::AlreadyConfigured { .. }));
294 }
295
296 #[test]
297 fn parse_input_extracts_command() {
298 let parsed = QwenHookFormat.parse_input(QWEN_DOCS_SAMPLE).unwrap();
299 assert_eq!(parsed.command, "ls -la");
300 assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
301 }
302
303 #[test]
306 fn parse_input_accepts_runtime_shell_id_and_the_alias() {
307 for name in ["run_shell_command", "Bash"] {
308 let json = format!(r#"{{"tool_name":"{name}","tool_input":{{"command":"ls"}}}}"#);
309 assert_eq!(QwenHookFormat.parse_input(&json).unwrap().command, "ls");
310 }
311 let other = r#"{"tool_name":"write_file","tool_input":{"command":"ls"}}"#;
312 assert!(QwenHookFormat.parse_input(other).is_err());
313 }
314
315 #[test]
316 fn install_timeout_is_in_seconds() {
317 let hook = hook_entry("safe-chains hook qwen");
318 assert_eq!(hook.pointer("/hooks/0/timeout").and_then(Value::as_u64), Some(60));
319 }
320
321 #[test]
322 fn parse_input_rejects_garbage() {
323 assert!(QwenHookFormat.parse_input("not json").is_err());
324 assert!(QwenHookFormat.parse_input("{}").is_err());
325 }
326
327 #[test]
328 fn render_response_emits_claude_shaped_envelope() {
329 let r = QwenHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
330 let v: Value = serde_json::from_str(&r.stdout).unwrap();
331 assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("allow"),);
332 assert_eq!(v.pointer("/hookSpecificOutput/hookEventName").and_then(|d| d.as_str()), Some("PreToolUse"),);
333 }
334
335 #[test]
336 fn render_response_deny_emits_empty_body() {
337 let r = QwenHookFormat.render_response(Verdict::Denied);
338 assert_eq!(r.stdout, "");
339 }
340}