use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::Value;
use super::cchooks::{hook_is_portable, remove_hook_groups, render_hook_group};
use super::confedit::{json_edit, json_obj_at, json_prune_obj, json_remove, remove_file_idem, write_file_idem};
use super::mcpjson::{self, RemoteShape, ServerShape};
use super::report;
use super::skillsdir;
use super::{AgentBackend, BackendState};
use crate::components::{HookBinding, MarkdownDoc};
use crate::doctor::{CheckStatus, DoctorCheck, DoctorReport};
use crate::error::{Error, IoContext, Result};
use crate::host::{Capabilities, Desired, Outcome, Plugin, Scope, Source};
pub(crate) struct QwenCodeBackend;
const SHAPE: ServerShape = ServerShape::plain().with_remote(RemoteShape::HttpUrlKeyed);
impl AgentBackend for QwenCodeBackend {
fn id(&self) -> &'static str {
"qwen-code"
}
fn detect(&self) -> bool {
which::which("qwen").is_ok() || user_qwen_base().is_ok_and(|b| b.is_dir())
}
fn capabilities(&self) -> Capabilities {
Capabilities {
plugins: false,
mcp: true,
hooks: true,
commands: true,
agents: true,
skills: true,
instructions: false,
scopes: &["user", "project"],
}
}
fn probe(&self, plugin: &Plugin, scope: &Scope, source: &Source) -> Result<BackendState> {
let comp = plugin.components(source)?.with_client(self.id());
let base = qwen_dir(scope)?;
let settings = settings_file(scope)?;
let mcp = mcpjson::probe_surface(&settings, &["mcpServers"], &comp.mcp_servers, SHAPE)?;
let hooks = report::probe_json_entries(&settings, &hook_entries(&comp.hooks))?;
let cmd_root = base.join("commands").join(plugin.name);
let commands = report::probe_files(
&comp.commands.iter().map(|doc| (cmd_root.join(command_rel(doc)), doc.raw.clone())).collect::<Vec<_>>(),
|_, _| true,
)?;
let agent_root = base.join("agents");
let agents = report::probe_files(
&comp
.agents
.iter()
.map(|doc| (agent_root.join(agent_file(plugin.name, doc)), render_agent(plugin.name, doc).into_bytes()))
.collect::<Vec<_>>(),
|_, _| true,
)?;
let skills = skillsdir::probe(&base.join("skills"), plugin, &comp.skills)?;
Ok(report::compose([mcp, hooks, commands, agents, skills].into_iter().flatten()))
}
fn reconcile(&self, plugin: &Plugin, desired: &Desired, scope: &Scope) -> Result<Outcome> {
let comp = plugin.components(&desired.source)?.with_client(self.id());
let base = qwen_dir(scope)?;
let settings = settings_file(scope)?;
let mut changed = false;
changed |= mcpjson::reconcile(&settings, &["mcpServers"], &comp.mcp_servers, SHAPE)? != Outcome::NoOp;
changed |= reconcile_hooks(&settings, &comp.hooks)?;
let cmd_root = base.join("commands").join(plugin.name);
for doc in &comp.commands {
changed |= write_file_idem(&cmd_root.join(command_rel(doc)), &doc.raw)?;
}
let agent_root = base.join("agents");
for doc in &comp.agents {
changed |= write_file_idem(&agent_root.join(agent_file(plugin.name, doc)), render_agent(plugin.name, doc).as_bytes())?;
}
changed |= skillsdir::reconcile(&base.join("skills"), plugin, &comp.skills)?;
Ok(if changed { Outcome::Installed } else { Outcome::NoOp })
}
fn remove(&self, plugin: &Plugin, scope: &Scope, source: &Source) -> Result<Outcome> {
let comp = plugin.components(source)?.with_client(self.id());
let base = qwen_dir(scope)?;
let settings = settings_file(scope)?;
let mut changed = false;
changed |= mcpjson::remove(&settings, &["mcpServers"], &comp.mcp_servers, SHAPE)? != Outcome::NoOp;
changed |= remove_hooks(&settings, &comp.hooks)?;
let cmd_root = base.join("commands").join(plugin.name);
if cmd_root.exists() {
fs::remove_dir_all(&cmd_root).io_ctx(|| format!("removing {}", cmd_root.display()))?;
changed = true;
}
let agent_root = base.join("agents");
for doc in &comp.agents {
changed |= remove_file_idem(&agent_root.join(agent_file(plugin.name, doc)))?;
}
changed |= skillsdir::remove(&base.join("skills"), plugin, &comp.skills)?;
Ok(if changed { Outcome::Removed } else { Outcome::NoOp })
}
fn report(&self, plugin: &Plugin, source: &Source) -> DoctorReport {
DoctorReport::from_checks(report_checks(self, plugin, source))
}
}
fn user_qwen_base() -> Result<PathBuf> {
if let Some(dir) = std::env::var_os("QWEN_HOME").filter(|v| !v.is_empty()) {
return Ok(PathBuf::from(dir));
}
dirs::home_dir()
.map(|h| h.join(".qwen"))
.ok_or_else(|| Error::Tree("no home directory (HOME unset) and QWEN_HOME unset; cannot locate ~/.qwen".into()))
}
fn qwen_dir(scope: &Scope) -> Result<PathBuf> {
match scope {
Scope::User => user_qwen_base(),
Scope::Project { path } => Ok(path.join(".qwen")),
}
}
fn settings_file(scope: &Scope) -> Result<PathBuf> {
Ok(qwen_dir(scope)?.join("settings.json"))
}
fn map_event(cc_event: &str) -> Option<&'static str> {
match cc_event {
"PreToolUse" => Some("PreToolUse"),
"PostToolUse" => Some("PostToolUse"),
"UserPromptSubmit" => Some("UserPromptSubmit"),
"SessionStart" => Some("SessionStart"),
"SessionEnd" => Some("SessionEnd"),
"Stop" => Some("Stop"),
"SubagentStart" => Some("SubagentStart"),
"SubagentStop" => Some("SubagentStop"),
"PreCompact" => Some("PreCompact"),
"Notification" => Some("Notification"),
_ => None,
}
}
fn hook_entries(hooks: &[HookBinding]) -> Vec<(Vec<String>, Value)> {
hooks
.iter()
.filter(|h| hook_is_portable(h))
.filter_map(|h| map_event(&h.event).map(|event| (vec!["hooks".to_string(), event.to_string()], render_hook_group(h))))
.collect()
}
fn reconcile_hooks(settings: &Path, hooks: &[HookBinding]) -> Result<bool> {
let writable: Vec<(&'static str, &HookBinding)> =
hooks.iter().filter(|h| hook_is_portable(h)).filter_map(|h| map_event(&h.event).map(|event| (event, h))).collect();
if writable.is_empty() {
return Ok(false);
}
json_edit(settings, |root| {
let events = json_obj_at(root, &["hooks"]);
for (event, hook) in &writable {
let group = render_hook_group(hook);
let entry = events.entry((*event).to_string()).or_insert_with(|| Value::Array(Vec::new()));
if let Value::Array(list) = entry
&& !list.iter().any(|g| g == &group)
{
list.push(group);
}
}
Ok(())
})
}
fn remove_hooks(settings: &Path, hooks: &[HookBinding]) -> Result<bool> {
if !settings.exists() {
return Ok(false);
}
let ours: BTreeSet<&str> =
hooks.iter().filter(|h| hook_is_portable(h) && map_event(&h.event).is_some()).map(|h| h.command.as_str()).collect();
json_remove(settings, |root| {
json_prune_obj(root, &["hooks"], |events| {
remove_hook_groups(events, &ours);
Ok(())
})
.map(|_| ())
})
}
fn command_rel(doc: &MarkdownDoc) -> String {
doc.rel.strip_prefix("commands/").unwrap_or(&doc.rel).to_string()
}
fn agent_file(plugin: &str, doc: &MarkdownDoc) -> String {
format!("{plugin}-{}.md", flat_stem(&doc.rel, "agents/"))
}
fn flat_stem(rel: &str, prefix: &str) -> String {
let stripped = rel.strip_prefix(prefix).unwrap_or(rel);
let stem = stripped.strip_suffix(".md").unwrap_or(stripped);
stem.replace(['/', '\\'], "-")
}
fn render_agent(plugin: &str, doc: &MarkdownDoc) -> String {
let name = doc.frontmatter.get("name").and_then(Value::as_str).unwrap_or(doc.name.as_str());
let mut out = String::from("---\n");
out.push_str("name: ");
out.push_str(&Value::String(format!("{plugin}-{name}")).to_string());
out.push('\n');
if let Some(desc) = doc.frontmatter.get("description").and_then(Value::as_str) {
out.push_str("description: ");
out.push_str(&Value::String(desc.to_string()).to_string());
out.push('\n');
}
out.push_str("---\n\n");
out.push_str(doc.body.trim());
out.push('\n');
out
}
fn report_checks(backend: &QwenCodeBackend, plugin: &Plugin, source: &Source) -> Vec<DoctorCheck> {
let mut checks = Vec::new();
checks.push(if backend.detect() {
DoctorCheck { name: "qwen-code detected", status: CheckStatus::Ok("`qwen` on PATH or ~/.qwen present".into()) }
} else {
DoctorCheck {
name: "qwen-code detected",
status: CheckStatus::Fail {
problem: "qwen-code CLI not detected".into(),
fix: "install it with `npm install -g @qwen-code/qwen-code`".into(),
},
}
});
let base = match qwen_dir(&Scope::User) {
Ok(base) => base,
Err(e) => {
checks.push(DoctorCheck { name: "settings file", status: CheckStatus::Warn(e.to_string()) });
return checks;
}
};
let settings = match settings_file(&Scope::User) {
Ok(settings) => settings,
Err(e) => {
checks.push(DoctorCheck { name: "settings file", status: CheckStatus::Warn(e.to_string()) });
return checks;
}
};
let root = report::read_json_config(&mut checks, "settings file", &settings);
let Some(comp) = report::components(&mut checks, plugin, source).map(|c| c.with_client(backend.id())) else {
return checks;
};
checks.push(report::check_mcp_registered(
&comp.mcp_servers,
root.as_ref(),
&["mcpServers"],
"not in settings.json",
"run the host's `setup`",
));
checks.push(report::check_mcp_command(&comp.mcp_servers));
checks.push(check_commands_present(&comp.commands, &base.join("commands").join(plugin.name)));
checks.push(check_agents_present(&comp.agents, &base.join("agents"), plugin.name));
checks
}
fn check_commands_present(commands: &[MarkdownDoc], cmd_root: &Path) -> DoctorCheck {
let name = "translated commands present";
if commands.is_empty() {
return DoctorCheck { name, status: CheckStatus::Ok("no commands to translate".into()) };
}
let missing: Vec<String> = commands.iter().map(command_rel).filter(|rel| !cmd_root.join(rel).exists()).collect();
if missing.is_empty() {
DoctorCheck { name, status: CheckStatus::Ok(format!("{} command file(s) present", commands.len())) }
} else {
DoctorCheck {
name,
status: CheckStatus::Fail {
problem: format!("command file(s) missing: {}", missing.join(", ")),
fix: "run the host's `setup`".into(),
},
}
}
}
fn check_agents_present(agents: &[MarkdownDoc], agent_root: &Path, plugin: &str) -> DoctorCheck {
let name = "translated agents present";
if agents.is_empty() {
return DoctorCheck { name, status: CheckStatus::Ok("no agents to translate".into()) };
}
let missing: Vec<String> = agents.iter().map(|d| agent_file(plugin, d)).filter(|f| !agent_root.join(f).exists()).collect();
if missing.is_empty() {
DoctorCheck { name, status: CheckStatus::Ok(format!("{} agent file(s) present", agents.len())) }
} else {
DoctorCheck {
name,
status: CheckStatus::Fail {
problem: format!("agent file(s) missing: {}", missing.join(", ")),
fix: "run the host's `setup`".into(),
},
}
}
}
#[cfg(test)]
#[path = "../../tests/unit/qwen_code.rs"]
mod qwen_code_tests;