Skip to main content

agent_hub_runtime/commands/
tools.rs

1use serde::Serialize;
2use std::path::PathBuf;
3use std::sync::atomic::AtomicBool;
4use std::sync::Arc;
5use std::time::Instant;
6use tauri::{AppHandle, State};
7
8use crate::core::error::AppError;
9use crate::core::scenario_service;
10use crate::core::scenario_service::sync_scenario_skills;
11use crate::core::skill_store::SkillStore;
12use crate::core::sync_engine;
13use crate::core::timing::should_log_first_or_slow;
14use crate::core::tool_adapters::{self, CustomToolDef, ToolCategory};
15use crate::core::tool_service::{
16    self, get_custom_tool_paths, get_custom_tool_project_paths, get_custom_tools,
17    get_disabled_tools, get_tool_order, normalize_project_relative_skills_dir_input,
18    normalize_skills_dir_input, set_custom_tool_paths, set_custom_tool_project_paths,
19    set_custom_tools, set_disabled_tools, set_tool_order, ToolInfo,
20};
21
22#[derive(Debug, Serialize)]
23pub struct ToolInfoDto {
24    pub key: String,
25    pub display_name: String,
26    pub installed: bool,
27    pub skills_dir: String,
28    pub enabled: bool,
29    pub is_custom: bool,
30    pub has_path_override: bool,
31    pub project_relative_skills_dir: Option<String>,
32    pub has_project_path_override: bool,
33    pub category: ToolCategory,
34}
35
36/// Sync active scenario skills to a single tool.
37fn sync_active_scenario_to_tool(store: &SkillStore, tool_key: &str) {
38    scenario_service::sync_active_scenario_to_tool(store, tool_key)
39}
40
41/// Remove all synced skill files and target records for a given tool.
42fn unsync_all_for_tool(store: &SkillStore, tool_key: &str) {
43    let targets = store.get_all_targets().unwrap_or_default();
44    for target in targets.iter().filter(|t| t.tool == tool_key) {
45        // Tools can share one skills directory; another tool's live
46        // deployment at this exact path is not ours to remove.
47        let still_referenced = targets
48            .iter()
49            .any(|other| other.tool != tool_key && other.target_path == target.target_path);
50        if !still_referenced {
51            sync_engine::remove_recorded_target_or_warn(
52                &PathBuf::from(&target.target_path),
53                &target.mode,
54            );
55        }
56        store.delete_target(&target.skill_id, tool_key).ok();
57    }
58}
59
60fn reconcile_tool_sync_after_path_change(store: &SkillStore, tool_key: &str) {
61    // Remove existing synced artifacts/records (old path), then re-sync to current adapter path.
62    unsync_all_for_tool(store, tool_key);
63    let disabled = get_disabled_tools(store);
64    if !disabled.contains(&tool_key.to_string()) {
65        sync_active_scenario_to_tool(store, tool_key);
66    }
67}
68
69static GET_TOOL_STATUS_FIRST_CALL: AtomicBool = AtomicBool::new(true);
70
71#[tauri::command]
72pub async fn get_tool_status(
73    store: State<'_, Arc<SkillStore>>,
74) -> Result<Vec<ToolInfoDto>, AppError> {
75    let store = store.inner().clone();
76    tauri::async_runtime::spawn_blocking(move || {
77        let start = Instant::now();
78        let infos = tool_service::list_tool_info(&store);
79        let count = infos.len();
80        let result: Vec<ToolInfoDto> = infos
81            .into_iter()
82            .map(|info: ToolInfo| ToolInfoDto {
83                key: info.key,
84                display_name: info.display_name,
85                installed: info.installed,
86                skills_dir: info.skills_dir,
87                enabled: info.enabled,
88                is_custom: info.is_custom,
89                has_path_override: info.has_path_override,
90                project_relative_skills_dir: info.project_relative_skills_dir,
91                has_project_path_override: info.has_project_path_override,
92                category: info.category,
93            })
94            .collect();
95        let elapsed_ms = start.elapsed().as_millis();
96        if should_log_first_or_slow(&GET_TOOL_STATUS_FIRST_CALL, elapsed_ms, 100) {
97            log::info!("get_tool_status: {count} tools in {elapsed_ms} ms");
98        }
99        Ok(result)
100    })
101    .await?
102}
103
104fn refresh_tray_menu_best_effort(app: &AppHandle) {
105    if let Err(err) = crate::refresh_tray_menu(app) {
106        log::warn!("Failed to refresh tray menu after tool mutation: {err}");
107    }
108}
109
110#[tauri::command]
111pub async fn set_tool_enabled(
112    app: AppHandle,
113    key: String,
114    enabled: bool,
115    store: State<'_, Arc<SkillStore>>,
116) -> Result<(), AppError> {
117    let store = store.inner().clone();
118    let result = tauri::async_runtime::spawn_blocking(move || {
119        set_tool_enabled_internal(&store, &key, enabled)
120    })
121    .await?;
122    if result.is_ok() {
123        refresh_tray_menu_best_effort(&app);
124    }
125    result
126}
127
128/// Shared GUI/CLI implementation for the global agent toggle.
129pub fn set_tool_enabled_internal(
130    store: &SkillStore,
131    key: &str,
132    enabled: bool,
133) -> Result<(), AppError> {
134    if tool_adapters::find_adapter_with_store(store, key).is_none() {
135        return Err(AppError::not_found(format!("Unknown agent: {key}")));
136    }
137
138    let mut disabled = get_disabled_tools(store);
139    if enabled {
140        disabled.retain(|item| item != key);
141        set_disabled_tools(store, &disabled)?;
142        sync_active_scenario_to_tool(store, key);
143        Ok(())
144    } else {
145        if !disabled.iter().any(|item| item == key) {
146            disabled.push(key.to_string());
147        }
148        unsync_all_for_tool(store, key);
149        set_disabled_tools(store, &disabled)
150    }
151}
152
153#[tauri::command]
154pub async fn set_all_tools_enabled(
155    app: AppHandle,
156    enabled: bool,
157    store: State<'_, Arc<SkillStore>>,
158) -> Result<(), AppError> {
159    let store = store.inner().clone();
160    let result = tauri::async_runtime::spawn_blocking(move || {
161        if enabled {
162            set_disabled_tools(&store, &[])?;
163            // Re-sync active scenario skills to all (now-enabled) installed tools
164            if let Ok(Some(active_id)) = store.get_active_scenario_id() {
165                // Enabling the tools succeeded either way; a target we may not
166                // replace is reported, not fatal (#363).
167                match sync_scenario_skills(&store, &active_id, false) {
168                    Ok(refusals) => {
169                        for refusal in refusals {
170                            log::warn!("enable-all-tools sync skipped a target: {refusal}");
171                        }
172                    }
173                    Err(e) => log::warn!("enable-all-tools sync failed: {e}"),
174                }
175            }
176            Ok(())
177        } else {
178            let adapters = tool_adapters::all_tool_adapters(&store);
179            let all_keys: Vec<String> = adapters.iter().map(|a| a.key.clone()).collect();
180            for adapter in &adapters {
181                unsync_all_for_tool(&store, &adapter.key);
182            }
183            set_disabled_tools(&store, &all_keys)
184        }
185    })
186    .await?;
187    if result.is_ok() {
188        refresh_tray_menu_best_effort(&app);
189    }
190    result
191}
192
193#[tauri::command]
194pub async fn get_tool_order_cmd(
195    store: State<'_, Arc<SkillStore>>,
196) -> Result<Vec<String>, AppError> {
197    let store = store.inner().clone();
198    tauri::async_runtime::spawn_blocking(move || Ok(get_tool_order(&store))).await?
199}
200
201#[tauri::command]
202pub async fn set_tool_order_cmd(
203    order: Vec<String>,
204    store: State<'_, Arc<SkillStore>>,
205) -> Result<(), AppError> {
206    let store = store.inner().clone();
207    tauri::async_runtime::spawn_blocking(move || set_tool_order(&store, &order)).await?
208}
209
210/// Whether a built-in adapter claims this key. Resolution consults built-ins
211/// before custom tools, so a key that answers `true` here must have its
212/// overrides written to the side maps, never onto a custom tool definition.
213fn is_builtin_key(key: &str) -> bool {
214    tool_adapters::default_tool_adapters()
215        .iter()
216        .any(|a| a.key == key)
217}
218
219/// Store side of [`set_custom_tool_path`], separated so the write can be
220/// tested against a real store without a Tauri runtime.
221pub(crate) fn apply_tool_skills_dir(
222    store: &SkillStore,
223    key: &str,
224    path: &str,
225) -> Result<(), AppError> {
226    let key = key.trim().to_string();
227    let path = normalize_skills_dir_input(path)?;
228    if key.is_empty() || path.is_empty() {
229        return Err(AppError::invalid_input("Key and path are required"));
230    }
231
232    let old_adapter = tool_adapters::find_adapter_with_store(store, &key)
233        .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
234    let old_skills_dir = old_adapter.skills_dir();
235
236    // Resolution prefers a built-in over a custom tool of the same key
237    // (`find_adapter_with_store`), so the write has to agree. A custom agent
238    // whose key later became a built-in one otherwise stores the new path on a
239    // definition nothing reads, and the save reports success while the
240    // displayed path never moves (#378).
241    let mut customs = get_custom_tools(store);
242    match customs.iter_mut().find(|c| c.key == key) {
243        Some(custom) if !is_builtin_key(&key) => {
244            custom.skills_dir = path;
245            set_custom_tools(store, &customs)?;
246        }
247        _ => {
248            let mut paths = get_custom_tool_paths(store);
249            paths.insert(key.clone(), path);
250            set_custom_tool_paths(store, &paths)?;
251        }
252    }
253
254    let new_adapter = tool_adapters::find_adapter_with_store(store, &key)
255        .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
256    if old_skills_dir != new_adapter.skills_dir() {
257        reconcile_tool_sync_after_path_change(store, &key);
258    }
259    Ok(())
260}
261
262#[tauri::command]
263pub async fn set_custom_tool_path(
264    key: String,
265    path: String,
266    store: State<'_, Arc<SkillStore>>,
267) -> Result<(), AppError> {
268    let store = store.inner().clone();
269    tauri::async_runtime::spawn_blocking(move || apply_tool_skills_dir(&store, &key, &path)).await?
270}
271
272#[tauri::command]
273pub async fn reset_custom_tool_path(
274    key: String,
275    store: State<'_, Arc<SkillStore>>,
276) -> Result<(), AppError> {
277    let store = store.inner().clone();
278    tauri::async_runtime::spawn_blocking(move || {
279        let old_adapter = tool_adapters::find_adapter_with_store(&store, &key)
280            .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
281        let old_skills_dir = old_adapter.skills_dir();
282
283        let mut paths = get_custom_tool_paths(&store);
284        paths.remove(&key);
285        set_custom_tool_paths(&store, &paths)?;
286
287        let new_adapter = tool_adapters::find_adapter_with_store(&store, &key)
288            .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
289        if old_skills_dir != new_adapter.skills_dir() {
290            reconcile_tool_sync_after_path_change(&store, &key);
291        }
292        Ok(())
293    })
294    .await?
295}
296
297/// Store side of [`set_custom_tool_project_path`], separated so the write can
298/// be tested against a real store without a Tauri runtime.
299pub(crate) fn apply_tool_project_skills_dir(
300    store: &SkillStore,
301    key: &str,
302    project_relative_skills_dir: Option<&str>,
303) -> Result<(), AppError> {
304    let key = key.trim().to_string();
305    if key.is_empty() {
306        return Err(AppError::invalid_input("Key is required"));
307    }
308    let normalized = normalize_project_relative_skills_dir_input(
309        project_relative_skills_dir.unwrap_or_default(),
310    )?;
311
312    // Built-in tools keep overrides in a side map keyed by tool key. Resolve
313    // the built-in default project path (no store overrides) to validate the
314    // key and to detect no-op edits: an empty value, or one equal to the
315    // default, removes the override and restores the default.
316    //
317    // Checked before custom tools, matching how resolution reads them back
318    // (#378) — see `apply_tool_skills_dir`.
319    let default_project_path = match tool_adapters::default_tool_adapters()
320        .into_iter()
321        .find(|a| a.key == key)
322        .map(|a| a.project_relative_skills_dir().to_string())
323    {
324        Some(default_project_path) => default_project_path,
325        // Custom tools store the project path on their definition; clearing it
326        // (None) drops project-workspace support for that agent.
327        None => {
328            let mut customs = get_custom_tools(store);
329            let custom = customs
330                .iter_mut()
331                .find(|c| c.key == key)
332                .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
333            custom.project_relative_skills_dir = normalized;
334            return set_custom_tools(store, &customs);
335        }
336    };
337    let mut project_paths = get_custom_tool_project_paths(store);
338    match normalized {
339        Some(path) if path != default_project_path => {
340            project_paths.insert(key, path);
341        }
342        _ => {
343            project_paths.remove(&key);
344        }
345    }
346    set_custom_tool_project_paths(store, &project_paths)
347}
348
349#[tauri::command]
350pub async fn set_custom_tool_project_path(
351    key: String,
352    project_relative_skills_dir: Option<String>,
353    store: State<'_, Arc<SkillStore>>,
354) -> Result<(), AppError> {
355    let store = store.inner().clone();
356    tauri::async_runtime::spawn_blocking(move || {
357        apply_tool_project_skills_dir(&store, &key, project_relative_skills_dir.as_deref())
358    })
359    .await?
360}
361
362#[tauri::command]
363pub async fn reset_custom_tool_project_path(
364    key: String,
365    store: State<'_, Arc<SkillStore>>,
366) -> Result<(), AppError> {
367    let store = store.inner().clone();
368    tauri::async_runtime::spawn_blocking(move || {
369        let key = key.trim().to_string();
370        if key.is_empty() {
371            return Err(AppError::invalid_input("Key is required"));
372        }
373        if tool_adapters::find_adapter_with_store(&store, &key).is_none() {
374            return Err(AppError::not_found(format!("Unknown tool: {key}")));
375        }
376        let mut project_paths = get_custom_tool_project_paths(&store);
377        if project_paths.remove(&key).is_some() {
378            set_custom_tool_project_paths(&store, &project_paths)?;
379        }
380        Ok(())
381    })
382    .await?
383}
384
385#[tauri::command]
386pub async fn add_custom_tool(
387    key: String,
388    display_name: String,
389    skills_dir: String,
390    project_relative_skills_dir: Option<String>,
391    store: State<'_, Arc<SkillStore>>,
392) -> Result<(), AppError> {
393    let store = store.inner().clone();
394    tauri::async_runtime::spawn_blocking(move || {
395        add_custom_tool_internal(
396            &store,
397            &key,
398            &display_name,
399            &skills_dir,
400            project_relative_skills_dir.as_deref(),
401        )
402    })
403    .await?
404}
405
406/// Shared by the app and the CLI (`agents add-custom`, #501).
407pub fn add_custom_tool_internal(
408    store: &SkillStore,
409    key: &str,
410    display_name: &str,
411    skills_dir: &str,
412    project_relative_skills_dir: Option<&str>,
413) -> Result<(), AppError> {
414    let key = key.trim().to_string();
415    let display_name = display_name.trim().to_string();
416    let skills_dir = normalize_skills_dir_input(skills_dir)?;
417    let project_relative_skills_dir = normalize_project_relative_skills_dir_input(
418        project_relative_skills_dir.unwrap_or_default(),
419    )?;
420    if key.is_empty() || display_name.is_empty() || skills_dir.is_empty() {
421        return Err(AppError::invalid_input(
422            "Agent key, name and skills path are required",
423        ));
424    }
425
426    // Validate key uniqueness
427    let all = tool_adapters::all_tool_adapters(store);
428    if all.iter().any(|a| a.key == key) {
429        return Err(AppError::invalid_input(format!(
430            "Agent key \"{key}\" already exists"
431        )));
432    }
433    let mut customs = get_custom_tools(store);
434    customs.push(CustomToolDef {
435        key: key.clone(),
436        display_name,
437        skills_dir,
438        project_relative_skills_dir,
439        category: Default::default(),
440    });
441    set_custom_tools(store, &customs)?;
442    reconcile_tool_sync_after_path_change(store, &key);
443    Ok(())
444}
445
446#[tauri::command]
447pub async fn remove_custom_tool(
448    key: String,
449    store: State<'_, Arc<SkillStore>>,
450) -> Result<(), AppError> {
451    let store = store.inner().clone();
452    tauri::async_runtime::spawn_blocking(move || {
453        // Remove synced targets for this tool
454        unsync_all_for_tool(&store, &key);
455        // Remove from custom_tools list
456        let mut customs = get_custom_tools(&store);
457        customs.retain(|c| c.key != key);
458        set_custom_tools(&store, &customs)?;
459        // Remove any stale override for this key.
460        let mut custom_paths = get_custom_tool_paths(&store);
461        custom_paths.remove(&key);
462        set_custom_tool_paths(&store, &custom_paths)?;
463        // Also remove from disabled_tools if present
464        let mut disabled = get_disabled_tools(&store);
465        disabled.retain(|k| k != &key);
466        set_disabled_tools(&store, &disabled)
467    })
468    .await?
469}
470
471pub fn migrate_legacy_tool_keys(store: &SkillStore) -> Result<(), AppError> {
472    tool_service::migrate_legacy_tool_keys(store)
473}
474
475#[cfg(test)]
476mod tests;