agent_hub_runtime/core/
skill_deployment.rs1use std::path::{Path, PathBuf};
2
3use super::{
4 error::{AppError, TargetConflictDetail},
5 scenario_service::{deployment_target, is_skill_path_within_root, replace_policy},
6 skill_metadata,
7 skill_store::{SkillStore, SkillTargetRecord},
8 sync_engine, tool_adapters, tool_service,
9};
10
11#[derive(Debug, Clone, Copy)]
18pub enum DeployIntent<'a> {
19 Managed,
21 AdoptExisting(&'a Path),
23}
24
25pub(crate) fn detach_source_refs_from_adoption_target(
42 store: &SkillStore,
43 target: &Path,
44) -> Result<(), AppError> {
45 let target_str = target.to_string_lossy().into_owned();
46 let target_canonical = if std::fs::symlink_metadata(target)
55 .map(|meta| meta.file_type().is_symlink())
56 .unwrap_or(false)
57 {
58 None
59 } else {
60 std::fs::canonicalize(target).ok()
61 };
62 for skill in store.get_all_skills().map_err(AppError::db)? {
63 let Some(source_ref) = skill.source_ref.as_deref() else {
64 continue;
65 };
66 if source_ref == skill.central_path {
68 continue;
69 }
70 let points_at_target = source_ref == target_str
71 || target_canonical.as_ref().is_some_and(|canonical| {
72 std::fs::canonicalize(source_ref).is_ok_and(|source| &source == canonical)
73 });
74 if points_at_target {
75 store
76 .update_skill_source_ref(&skill.id, &skill.central_path)
77 .map_err(AppError::db)?;
78 log::info!(
79 "adoption: re-pointed source_ref of skill '{}' at its central copy; \
80 the adopted agent directory is now a deployment, not a source (#425)",
81 skill.name
82 );
83 }
84 }
85 Ok(())
86}
87
88pub fn sync_single_skill_to_tool(
90 store: &SkillStore,
91 skill_id: &str,
92 tool: &str,
93 intent: DeployIntent<'_>,
94 force: bool,
95) -> Result<(), AppError> {
96 let adapter = tool_adapters::find_adapter_with_store(store, tool)
97 .ok_or_else(|| AppError::not_found(format!("Unknown tool: {}", tool)))?;
98
99 if !adapter.can_deploy() {
100 return Err(AppError::not_found(format!(
101 "{} is not installed",
102 adapter.display_name
103 )));
104 }
105
106 if tool_service::get_disabled_tools(store).contains(&tool.to_string()) {
107 return Err(AppError::invalid_input(format!(
108 "{} is disabled",
109 adapter.display_name
110 )));
111 }
112
113 let skill = store
114 .get_skill_by_id(skill_id)
115 .map_err(AppError::db)?
116 .ok_or_else(|| AppError::not_found("Skill not found"))?;
117
118 let source = PathBuf::from(&skill.central_path);
119 let existing_targets = store
120 .get_targets_for_skill(skill_id)
121 .map_err(AppError::db)?;
122 let target = match intent {
123 DeployIntent::AdoptExisting(path) => {
124 let root = adapter.skills_dir();
125 if !is_skill_path_within_root(path, &root) {
126 return Err(AppError::invalid_input(
127 "Skill path is outside the agent skills directory",
128 ));
129 }
130 path.to_path_buf()
131 }
132 DeployIntent::Managed => deployment_target(
133 &adapter,
134 &sync_engine::target_dir_name(&source, &skill.name),
135 skill_id,
136 &existing_targets,
137 ),
138 };
139 let preference = crate::core::deployment_preferences::Preference::load(
140 store,
141 crate::core::deployment_preferences::Scope::Global,
142 )?;
143 let recorded_mode = match intent {
144 DeployIntent::AdoptExisting(_) => None,
145 DeployIntent::Managed => existing_targets
146 .iter()
147 .find(|existing| {
148 existing.tool == tool && std::path::Path::new(&existing.target_path) == target
149 })
150 .map(|existing| existing.mode.clone()),
151 };
152 let mode = preference.for_target(recorded_mode.as_deref());
153 let policy = match intent {
154 DeployIntent::AdoptExisting(_) => sync_engine::ReplacePolicy::UserConfirmed,
155 DeployIntent::Managed => replace_policy(recorded_mode.as_deref(), force),
156 };
157 if matches!(policy, sync_engine::ReplacePolicy::UserConfirmed) {
158 detach_source_refs_from_adoption_target(store, &target)?;
163 }
164 let actual_mode = sync_engine::sync_skill(&source, &target, mode, policy).map_err(|e| {
165 if let Some(refused) = e.downcast_ref::<sync_engine::ReplaceRefused>() {
166 AppError::target_conflict(
167 refused.to_string(),
168 vec![TargetConflictDetail {
169 path: refused.target.to_string_lossy().to_string(),
170 reason: refused.reason.to_string(),
171 is_skill: skill_metadata::is_valid_skill_dir(&refused.target),
172 }],
173 )
174 } else {
175 AppError::io(e)
176 }
177 })?;
178
179 let now = chrono::Utc::now().timestamp_millis();
180 let target_record = SkillTargetRecord {
181 id: uuid::Uuid::new_v4().to_string(),
182 skill_id: skill_id.to_string(),
183 tool: tool.to_string(),
184 target_path: target.to_string_lossy().to_string(),
185 mode: actual_mode.as_str().to_string(),
186 status: "ok".to_string(),
187 synced_at: Some(now),
188 last_error: None,
189 source_hash: skill.content_hash.clone(),
190 };
191
192 store.insert_target(&target_record).map_err(AppError::db)?;
193 Ok(())
194}
195
196#[cfg(test)]
197mod tests;