agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use serde::Serialize;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Instant;
use tauri::{AppHandle, State};

use crate::core::error::AppError;
use crate::core::scenario_service;
use crate::core::scenario_service::sync_scenario_skills;
use crate::core::skill_store::SkillStore;
use crate::core::sync_engine;
use crate::core::timing::should_log_first_or_slow;
use crate::core::tool_adapters::{self, CustomToolDef, ToolCategory};
use crate::core::tool_service::{
    self, get_custom_tool_paths, get_custom_tool_project_paths, get_custom_tools,
    get_disabled_tools, get_tool_order, normalize_project_relative_skills_dir_input,
    normalize_skills_dir_input, set_custom_tool_paths, set_custom_tool_project_paths,
    set_custom_tools, set_disabled_tools, set_tool_order, ToolInfo,
};

#[derive(Debug, Serialize)]
pub struct ToolInfoDto {
    pub key: String,
    pub display_name: String,
    pub installed: bool,
    pub skills_dir: String,
    pub enabled: bool,
    pub is_custom: bool,
    pub has_path_override: bool,
    pub project_relative_skills_dir: Option<String>,
    pub has_project_path_override: bool,
    pub category: ToolCategory,
}

/// Sync active scenario skills to a single tool.
fn sync_active_scenario_to_tool(store: &SkillStore, tool_key: &str) {
    scenario_service::sync_active_scenario_to_tool(store, tool_key)
}

/// Remove all synced skill files and target records for a given tool.
fn unsync_all_for_tool(store: &SkillStore, tool_key: &str) {
    let targets = store.get_all_targets().unwrap_or_default();
    for target in targets.iter().filter(|t| t.tool == tool_key) {
        // Tools can share one skills directory; another tool's live
        // deployment at this exact path is not ours to remove.
        let still_referenced = targets
            .iter()
            .any(|other| other.tool != tool_key && other.target_path == target.target_path);
        if !still_referenced {
            sync_engine::remove_recorded_target_or_warn(
                &PathBuf::from(&target.target_path),
                &target.mode,
            );
        }
        store.delete_target(&target.skill_id, tool_key).ok();
    }
}

fn reconcile_tool_sync_after_path_change(store: &SkillStore, tool_key: &str) {
    // Remove existing synced artifacts/records (old path), then re-sync to current adapter path.
    unsync_all_for_tool(store, tool_key);
    let disabled = get_disabled_tools(store);
    if !disabled.contains(&tool_key.to_string()) {
        sync_active_scenario_to_tool(store, tool_key);
    }
}

static GET_TOOL_STATUS_FIRST_CALL: AtomicBool = AtomicBool::new(true);

#[tauri::command]
pub async fn get_tool_status(
    store: State<'_, Arc<SkillStore>>,
) -> Result<Vec<ToolInfoDto>, AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || {
        let start = Instant::now();
        let infos = tool_service::list_tool_info(&store);
        let count = infos.len();
        let result: Vec<ToolInfoDto> = infos
            .into_iter()
            .map(|info: ToolInfo| ToolInfoDto {
                key: info.key,
                display_name: info.display_name,
                installed: info.installed,
                skills_dir: info.skills_dir,
                enabled: info.enabled,
                is_custom: info.is_custom,
                has_path_override: info.has_path_override,
                project_relative_skills_dir: info.project_relative_skills_dir,
                has_project_path_override: info.has_project_path_override,
                category: info.category,
            })
            .collect();
        let elapsed_ms = start.elapsed().as_millis();
        if should_log_first_or_slow(&GET_TOOL_STATUS_FIRST_CALL, elapsed_ms, 100) {
            log::info!("get_tool_status: {count} tools in {elapsed_ms} ms");
        }
        Ok(result)
    })
    .await?
}

fn refresh_tray_menu_best_effort(app: &AppHandle) {
    if let Err(err) = crate::refresh_tray_menu(app) {
        log::warn!("Failed to refresh tray menu after tool mutation: {err}");
    }
}

#[tauri::command]
pub async fn set_tool_enabled(
    app: AppHandle,
    key: String,
    enabled: bool,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    let result = tauri::async_runtime::spawn_blocking(move || {
        set_tool_enabled_internal(&store, &key, enabled)
    })
    .await?;
    if result.is_ok() {
        refresh_tray_menu_best_effort(&app);
    }
    result
}

/// Shared GUI/CLI implementation for the global agent toggle.
pub fn set_tool_enabled_internal(
    store: &SkillStore,
    key: &str,
    enabled: bool,
) -> Result<(), AppError> {
    if tool_adapters::find_adapter_with_store(store, key).is_none() {
        return Err(AppError::not_found(format!("Unknown agent: {key}")));
    }

    let mut disabled = get_disabled_tools(store);
    if enabled {
        disabled.retain(|item| item != key);
        set_disabled_tools(store, &disabled)?;
        sync_active_scenario_to_tool(store, key);
        Ok(())
    } else {
        if !disabled.iter().any(|item| item == key) {
            disabled.push(key.to_string());
        }
        unsync_all_for_tool(store, key);
        set_disabled_tools(store, &disabled)
    }
}

#[tauri::command]
pub async fn set_all_tools_enabled(
    app: AppHandle,
    enabled: bool,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    let result = tauri::async_runtime::spawn_blocking(move || {
        if enabled {
            set_disabled_tools(&store, &[])?;
            // Re-sync active scenario skills to all (now-enabled) installed tools
            if let Ok(Some(active_id)) = store.get_active_scenario_id() {
                // Enabling the tools succeeded either way; a target we may not
                // replace is reported, not fatal (#363).
                match sync_scenario_skills(&store, &active_id, false) {
                    Ok(refusals) => {
                        for refusal in refusals {
                            log::warn!("enable-all-tools sync skipped a target: {refusal}");
                        }
                    }
                    Err(e) => log::warn!("enable-all-tools sync failed: {e}"),
                }
            }
            Ok(())
        } else {
            let adapters = tool_adapters::all_tool_adapters(&store);
            let all_keys: Vec<String> = adapters.iter().map(|a| a.key.clone()).collect();
            for adapter in &adapters {
                unsync_all_for_tool(&store, &adapter.key);
            }
            set_disabled_tools(&store, &all_keys)
        }
    })
    .await?;
    if result.is_ok() {
        refresh_tray_menu_best_effort(&app);
    }
    result
}

#[tauri::command]
pub async fn get_tool_order_cmd(
    store: State<'_, Arc<SkillStore>>,
) -> Result<Vec<String>, AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || Ok(get_tool_order(&store))).await?
}

#[tauri::command]
pub async fn set_tool_order_cmd(
    order: Vec<String>,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || set_tool_order(&store, &order)).await?
}

/// Whether a built-in adapter claims this key. Resolution consults built-ins
/// before custom tools, so a key that answers `true` here must have its
/// overrides written to the side maps, never onto a custom tool definition.
fn is_builtin_key(key: &str) -> bool {
    tool_adapters::default_tool_adapters()
        .iter()
        .any(|a| a.key == key)
}

/// Store side of [`set_custom_tool_path`], separated so the write can be
/// tested against a real store without a Tauri runtime.
pub(crate) fn apply_tool_skills_dir(
    store: &SkillStore,
    key: &str,
    path: &str,
) -> Result<(), AppError> {
    let key = key.trim().to_string();
    let path = normalize_skills_dir_input(path)?;
    if key.is_empty() || path.is_empty() {
        return Err(AppError::invalid_input("Key and path are required"));
    }

    let old_adapter = tool_adapters::find_adapter_with_store(store, &key)
        .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
    let old_skills_dir = old_adapter.skills_dir();

    // Resolution prefers a built-in over a custom tool of the same key
    // (`find_adapter_with_store`), so the write has to agree. A custom agent
    // whose key later became a built-in one otherwise stores the new path on a
    // definition nothing reads, and the save reports success while the
    // displayed path never moves (#378).
    let mut customs = get_custom_tools(store);
    match customs.iter_mut().find(|c| c.key == key) {
        Some(custom) if !is_builtin_key(&key) => {
            custom.skills_dir = path;
            set_custom_tools(store, &customs)?;
        }
        _ => {
            let mut paths = get_custom_tool_paths(store);
            paths.insert(key.clone(), path);
            set_custom_tool_paths(store, &paths)?;
        }
    }

    let new_adapter = tool_adapters::find_adapter_with_store(store, &key)
        .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
    if old_skills_dir != new_adapter.skills_dir() {
        reconcile_tool_sync_after_path_change(store, &key);
    }
    Ok(())
}

#[tauri::command]
pub async fn set_custom_tool_path(
    key: String,
    path: String,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || apply_tool_skills_dir(&store, &key, &path)).await?
}

#[tauri::command]
pub async fn reset_custom_tool_path(
    key: String,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || {
        let old_adapter = tool_adapters::find_adapter_with_store(&store, &key)
            .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
        let old_skills_dir = old_adapter.skills_dir();

        let mut paths = get_custom_tool_paths(&store);
        paths.remove(&key);
        set_custom_tool_paths(&store, &paths)?;

        let new_adapter = tool_adapters::find_adapter_with_store(&store, &key)
            .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
        if old_skills_dir != new_adapter.skills_dir() {
            reconcile_tool_sync_after_path_change(&store, &key);
        }
        Ok(())
    })
    .await?
}

/// Store side of [`set_custom_tool_project_path`], separated so the write can
/// be tested against a real store without a Tauri runtime.
pub(crate) fn apply_tool_project_skills_dir(
    store: &SkillStore,
    key: &str,
    project_relative_skills_dir: Option<&str>,
) -> Result<(), AppError> {
    let key = key.trim().to_string();
    if key.is_empty() {
        return Err(AppError::invalid_input("Key is required"));
    }
    let normalized = normalize_project_relative_skills_dir_input(
        project_relative_skills_dir.unwrap_or_default(),
    )?;

    // Built-in tools keep overrides in a side map keyed by tool key. Resolve
    // the built-in default project path (no store overrides) to validate the
    // key and to detect no-op edits: an empty value, or one equal to the
    // default, removes the override and restores the default.
    //
    // Checked before custom tools, matching how resolution reads them back
    // (#378) — see `apply_tool_skills_dir`.
    let default_project_path = match tool_adapters::default_tool_adapters()
        .into_iter()
        .find(|a| a.key == key)
        .map(|a| a.project_relative_skills_dir().to_string())
    {
        Some(default_project_path) => default_project_path,
        // Custom tools store the project path on their definition; clearing it
        // (None) drops project-workspace support for that agent.
        None => {
            let mut customs = get_custom_tools(store);
            let custom = customs
                .iter_mut()
                .find(|c| c.key == key)
                .ok_or_else(|| AppError::not_found(format!("Unknown tool: {key}")))?;
            custom.project_relative_skills_dir = normalized;
            return set_custom_tools(store, &customs);
        }
    };
    let mut project_paths = get_custom_tool_project_paths(store);
    match normalized {
        Some(path) if path != default_project_path => {
            project_paths.insert(key, path);
        }
        _ => {
            project_paths.remove(&key);
        }
    }
    set_custom_tool_project_paths(store, &project_paths)
}

#[tauri::command]
pub async fn set_custom_tool_project_path(
    key: String,
    project_relative_skills_dir: Option<String>,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || {
        apply_tool_project_skills_dir(&store, &key, project_relative_skills_dir.as_deref())
    })
    .await?
}

#[tauri::command]
pub async fn reset_custom_tool_project_path(
    key: String,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || {
        let key = key.trim().to_string();
        if key.is_empty() {
            return Err(AppError::invalid_input("Key is required"));
        }
        if tool_adapters::find_adapter_with_store(&store, &key).is_none() {
            return Err(AppError::not_found(format!("Unknown tool: {key}")));
        }
        let mut project_paths = get_custom_tool_project_paths(&store);
        if project_paths.remove(&key).is_some() {
            set_custom_tool_project_paths(&store, &project_paths)?;
        }
        Ok(())
    })
    .await?
}

#[tauri::command]
pub async fn add_custom_tool(
    key: String,
    display_name: String,
    skills_dir: String,
    project_relative_skills_dir: Option<String>,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || {
        add_custom_tool_internal(
            &store,
            &key,
            &display_name,
            &skills_dir,
            project_relative_skills_dir.as_deref(),
        )
    })
    .await?
}

/// Shared by the app and the CLI (`agents add-custom`, #501).
pub fn add_custom_tool_internal(
    store: &SkillStore,
    key: &str,
    display_name: &str,
    skills_dir: &str,
    project_relative_skills_dir: Option<&str>,
) -> Result<(), AppError> {
    let key = key.trim().to_string();
    let display_name = display_name.trim().to_string();
    let skills_dir = normalize_skills_dir_input(skills_dir)?;
    let project_relative_skills_dir = normalize_project_relative_skills_dir_input(
        project_relative_skills_dir.unwrap_or_default(),
    )?;
    if key.is_empty() || display_name.is_empty() || skills_dir.is_empty() {
        return Err(AppError::invalid_input(
            "Agent key, name and skills path are required",
        ));
    }

    // Validate key uniqueness
    let all = tool_adapters::all_tool_adapters(store);
    if all.iter().any(|a| a.key == key) {
        return Err(AppError::invalid_input(format!(
            "Agent key \"{key}\" already exists"
        )));
    }
    let mut customs = get_custom_tools(store);
    customs.push(CustomToolDef {
        key: key.clone(),
        display_name,
        skills_dir,
        project_relative_skills_dir,
        category: Default::default(),
    });
    set_custom_tools(store, &customs)?;
    reconcile_tool_sync_after_path_change(store, &key);
    Ok(())
}

#[tauri::command]
pub async fn remove_custom_tool(
    key: String,
    store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
    let store = store.inner().clone();
    tauri::async_runtime::spawn_blocking(move || {
        // Remove synced targets for this tool
        unsync_all_for_tool(&store, &key);
        // Remove from custom_tools list
        let mut customs = get_custom_tools(&store);
        customs.retain(|c| c.key != key);
        set_custom_tools(&store, &customs)?;
        // Remove any stale override for this key.
        let mut custom_paths = get_custom_tool_paths(&store);
        custom_paths.remove(&key);
        set_custom_tool_paths(&store, &custom_paths)?;
        // Also remove from disabled_tools if present
        let mut disabled = get_disabled_tools(&store);
        disabled.retain(|k| k != &key);
        set_disabled_tools(&store, &disabled)
    })
    .await?
}

pub fn migrate_legacy_tool_keys(store: &SkillStore) -> Result<(), AppError> {
    tool_service::migrate_legacy_tool_keys(store)
}

#[cfg(test)]
mod tests;