Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat: MCP tool registry, granular permissions, PC control tools (Agent v2)

PurpleDoubleD78f702637fa7
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index da46f76c..d2175411 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -421,6 +421,25 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
+dependencies = [
+ "crossbeam-utils",
+]
+
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
@@ -693,6 +712,12 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+[[package]]
+name = "either"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
+
[[package]]
name = "embed-resource"
version = "3.0.8"
@@ -1306,12 +1331,29 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+[[package]]
+name = "hermit-abi"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
+
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hostname"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "windows-link 0.2.1",
+]
+
[[package]]
name = "html5ever"
version = "0.29.1"
@@ -1862,7 +1904,10 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08"
dependencies = [
+ "bitflags 2.11.0",
"libc",
+ "plain",
+ "redox_syscall 0.7.3",
]
[[package]]
@@ -1879,15 +1924,19 @@ checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"
[[package]]
name = "locally-uncensored"
-version = "2.2.0"
+version = "2.2.1"
dependencies = [
"base64 0.22.1",
"dirs",
"futures-util",
+ "glob",
+ "hostname",
+ "num_cpus",
"regex",
"reqwest 0.12.28",
"serde",
"serde_json",
+ "sysinfo",
"tauri",
"tauri-build",
"tauri-plugin-shell",
@@ -1896,6 +1945,8 @@ dependencies = [
"tokio-util",
"url",
"urlencoding",
+ "walkdir",
+ "whoami",
]
[[package]]
@@ -2093,6 +2144,15 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
+[[package]]
+name = "ntapi"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
+dependencies = [
+ "winapi",
+]
+
[[package]]
name = "num-conv"
version = "0.2.1"
@@ -2108,6 +2168,16 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "num_cpus"
+version = "1.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
+dependencies = [
+ "hermit-abi",
+ "libc",
+]
+
[[package]]
name = "num_enum"
version = "0.7.6"
@@ -2374,7 +2444,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
- "redox_syscall",
+ "redox_syscall 0.5.18",
"smallvec",
"windows-link 0.2.1",
]
@@ -2596,6 +2666,12 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
+[[package]]
+name = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
[[package]]
name = "plist"
version = "1.8.0"
@@ -2866,6 +2942,26 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+[[package]]
+name = "rayon"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -2875,6 +2971,15 @@ dependencies = [
"bitflags 2.11.0",
]
+[[package]]
+name = "redox_syscall"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce70a74e890531977d37e532c34d45e9055d2409ed08ddba14529471ed0be16"
+dependencies = [
+ "bitflags 2.11.0",
+]
+
[[package]]
name = "redox_users"
version = "0.5.2"
@@ -3538,7 +3643,7 @@ dependencies = [
"objc2-foundation",
"objc2-quartz-core",
"raw-window-handle",
- "redox_syscall",
+ "redox_syscall 0.5.18",
"tracing",
"wasm-bindgen",
"web-sys",
@@ -3691,6 +3796,20 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "sysinfo"
+version = "0.33.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fc858248ea01b66f19d8e8a6d55f41deaf91e9d495246fd01368d99935c6c01"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+ "memchr",
+ "ntapi",
+ "rayon",
+ "windows 0.57.0",
+]
+
[[package]]
name = "system-configuration"
version = "0.7.0"
@@ -3757,7 +3876,7 @@ dependencies = [
"tao-macros",
"unicode-segmentation",
"url",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
"windows-version",
"x11-dl",
@@ -3829,7 +3948,7 @@ dependencies = [
"webkit2gtk",
"webview2-com",
"window-vibrancy",
- "windows",
+ "windows 0.61.3",
]
[[package]]
@@ -3955,7 +4074,7 @@ dependencies = [
"url",
"webkit2gtk",
"webview2-com",
- "windows",
+ "windows 0.61.3",
]
[[package]]
@@ -3980,7 +4099,7 @@ dependencies = [
"url",
"webkit2gtk",
"webview2-com",
- "windows",
+ "windows 0.61.3",
"wry",
]
@@ -4625,6 +4744,12 @@ dependencies = [
"wit-bindgen",
]
+[[package]]
+name = "wasite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
+
[[package]]
name = "wasm-bindgen"
version = "0.2.115"
@@ -4814,10 +4939,10 @@ checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
dependencies = [
"webview2-com-macros",
"webview2-com-sys",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
- "windows-implement",
- "windows-interface",
+ "windows-implement 0.60.2",
+ "windows-interface 0.59.3",
]
[[package]]
@@ -4838,10 +4963,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
dependencies = [
"thiserror 2.0.18",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
]
+[[package]]
+name = "whoami"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d"
+dependencies = [
+ "libredox",
+ "wasite",
+ "web-sys",
+]
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -4888,6 +5024,16 @@ dependencies = [
"windows-version",
]
+[[package]]
+name = "windows"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143"
+dependencies = [
+ "windows-core 0.57.0",
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows"
version = "0.61.3"
@@ -4910,14 +5056,26 @@ dependencies = [
"windows-core 0.61.2",
]
+[[package]]
+name = "windows-core"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d"
+dependencies = [
+ "windows-implement 0.57.0",
+ "windows-interface 0.57.0",
+ "windows-result 0.1.2",
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
- "windows-implement",
- "windows-interface",
+ "windows-implement 0.60.2",
+ "windows-interface 0.59.3",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
@@ -4929,8 +5087,8 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
- "windows-implement",
- "windows-interface",
+ "windows-implement 0.60.2",
+ "windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
@@ -4947,6 +5105,17 @@ dependencies = [
"windows-threading",
]
+[[package]]
+name = "windows-implement"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "windows-implement"
version = "0.60.2"
@@ -4958,6 +5127,17 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "windows-interface"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -5002,6 +5182,15 @@ dependencies = [
"windows-strings 0.5.1",
]
+[[package]]
+name = "windows-result"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-result"
version = "0.3.4"
@@ -5453,7 +5642,7 @@ dependencies = [
"webkit2gtk",
"webkit2gtk-sys",
"webview2-com",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
"windows-version",
"x11-dl",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index a25c4bae..c50af57f 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -17,6 +17,12 @@ tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", features = ["stream", "blocking", "json"] }
dirs = "6"
regex = "1"
+glob = "0.3"
+sysinfo = "0.33"
+walkdir = "2"
+hostname = "0.4"
+whoami = "1"
+num_cpus = "1"
base64 = "0.22"
tempfile = "3"
futures-util = "0.3"
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rs
index 5e415866..cc324f05 100644
--- a/src-tauri/src/commands/agent.rs
+++ b/src-tauri/src/commands/agent.rs
@@ -17,16 +17,13 @@ fn agent_workspace() -> PathBuf {
dirs::home_dir().unwrap_or_default().join("agent-workspace")
}
-fn validate_path(path: &str) -> Result<PathBuf, String> {
- if path.contains("..") {
- return Err("Path traversal not allowed".to_string());
+fn resolve_agent_path(path: &str) -> PathBuf {
+ let p = std::path::Path::new(path);
+ if p.is_absolute() {
+ p.to_path_buf()
+ } else {
+ agent_workspace().join(path)
}
- let workspace = agent_workspace();
- let full = workspace.join(path);
- if !full.starts_with(&workspace) {
- return Err("Path outside workspace".to_string());
- }
- Ok(full)
}
#[tauri::command]
@@ -105,9 +102,9 @@ pub fn execute_code(
#[tauri::command]
pub fn file_read(path: String) -> Result<serde_json::Value, String> {
- let full_path = validate_path(&path)?;
+ let full_path = resolve_agent_path(&path);
if !full_path.exists() {
- return Err(format!("File not found: {}", path));
+ return Err(format!("File not found: {}", full_path.display()));
}
let content = fs::read_to_string(&full_path)
.map_err(|e| format!("Read error: {}", e))?;
@@ -116,7 +113,7 @@ pub fn file_read(path: String) -> Result<serde_json::Value, String> {
#[tauri::command]
pub fn file_write(path: String, content: String) -> Result<serde_json::Value, String> {
- let full_path = validate_path(&path)?;
+ let full_path = resolve_agent_path(&path);
if let Some(parent) = full_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", e))?;
}
diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rs
new file mode 100644
index 00000000..c2bf1e9a
--- /dev/null
+++ b/src-tauri/src/commands/filesystem.rs
@@ -0,0 +1,205 @@
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::time::UNIX_EPOCH;
+
+use base64::Engine;
+use glob::glob as glob_match;
+use regex::Regex;
+use walkdir::WalkDir;
+
+/// Resolve path — supports absolute and relative (relative to home/agent-workspace)
+fn resolve_path(path: &str) -> PathBuf {
+ let p = Path::new(path);
+ if p.is_absolute() {
+ p.to_path_buf()
+ } else {
+ dirs::home_dir()
+ .unwrap_or_default()
+ .join("agent-workspace")
+ .join(path)
+ }
+}
+
+fn file_meta(path: &Path) -> serde_json::Value {
+ let meta = fs::metadata(path);
+ let (size, modified, is_dir) = match meta {
+ Ok(m) => (
+ m.len(),
+ m.modified()
+ .ok()
+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
+ .map(|d| d.as_secs())
+ .unwrap_or(0),
+ m.is_dir(),
+ ),
+ Err(_) => (0, 0, false),
+ };
+ serde_json::json!({
+ "name": path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(),
+ "path": path.to_string_lossy(),
+ "size": size,
+ "isDir": is_dir,
+ "modified": modified,
+ })
+}
+
+#[tauri::command]
+pub fn fs_read(path: String) -> Result<serde_json::Value, String> {
+ let full = resolve_path(&path);
+ if !full.exists() {
+ return Err(format!("File not found: {}", full.display()));
+ }
+
+ // Try text first, fall back to base64 for binary
+ match fs::read_to_string(&full) {
+ Ok(content) => Ok(serde_json::json!({ "content": content, "encoding": "utf8" })),
+ Err(_) => {
+ let bytes = fs::read(&full).map_err(|e| format!("Read error: {}", e))?;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
+ Ok(serde_json::json!({ "content": b64, "encoding": "base64" }))
+ }
+ }
+}
+
+#[tauri::command]
+pub fn fs_write(path: String, content: String) -> Result<serde_json::Value, String> {
+ let full = resolve_path(&path);
+ if let Some(parent) = full.parent() {
+ fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", e))?;
+ }
+ fs::write(&full, &content).map_err(|e| format!("Write error: {}", e))?;
+ Ok(serde_json::json!({ "status": "saved", "path": full.to_string_lossy() }))
+}
+
+#[tauri::command]
+pub fn fs_list(
+ path: String,
+ recursive: Option<bool>,
+ pattern: Option<String>,
+) -> Result<serde_json::Value, String> {
+ let dir = resolve_path(&path);
+ if !dir.is_dir() {
+ return Err(format!("Not a directory: {}", dir.display()));
+ }
+
+ let mut entries: Vec<serde_json::Value> = Vec::new();
+ let max_entries = 500;
+
+ if let Some(ref pat) = pattern {
+ // Glob pattern relative to dir
+ let glob_pattern = dir.join(pat).to_string_lossy().to_string();
+ if let Ok(paths) = glob_match(&glob_pattern) {
+ for entry in paths.flatten() {
+ if entries.len() >= max_entries {
+ break;
+ }
+ entries.push(file_meta(&entry));
+ }
+ }
+ } else if recursive.unwrap_or(false) {
+ for entry in WalkDir::new(&dir).max_depth(5).into_iter().filter_map(|e| e.ok()) {
+ if entries.len() >= max_entries {
+ break;
+ }
+ entries.push(file_meta(entry.path()));
+ }
+ } else {
+ let read_dir = fs::read_dir(&dir).map_err(|e| format!("Read dir: {}", e))?;
+ for entry in read_dir.flatten() {
+ if entries.len() >= max_entries {
+ break;
+ }
+ entries.push(file_meta(&entry.path()));
+ }
+ }
+
+ Ok(serde_json::json!({ "entries": entries, "count": entries.len() }))
+}
+
+#[tauri::command]
+pub fn fs_search(
+ path: String,
+ pattern: String,
+ max_results: Option<u32>,
+) -> Result<serde_json::Value, String> {
+ let dir = resolve_path(&path);
+ if !dir.is_dir() {
+ return Err(format!("Not a directory: {}", dir.display()));
+ }
+
+ let re = Regex::new(&pattern).map_err(|e| format!("Invalid regex: {}", e))?;
+ let max = max_results.unwrap_or(50) as usize;
+ let mut results: Vec<serde_json::Value> = Vec::new();
+
+ for entry in WalkDir::new(&dir).max_depth(8).into_iter().filter_map(|e| e.ok()) {
+ if results.len() >= max {
+ break;
+ }
+ let p = entry.path();
+ if !p.is_file() {
+ continue;
+ }
+
+ // Skip binary / large files
+ let meta = fs::metadata(p);
+ if let Ok(m) = &meta {
+ if m.len() > 1_000_000 {
+ continue;
+ }
+ }
+
+ if let Ok(content) = fs::read_to_string(p) {
+ let mut matches: Vec<serde_json::Value> = Vec::new();
+ for (line_num, line) in content.lines().enumerate() {
+ if re.is_match(line) {
+ matches.push(serde_json::json!({
+ "line": line_num + 1,
+ "text": if line.len() > 200 { &line[..200] } else { line },
+ }));
+ if matches.len() >= 10 {
+ break;
+ }
+ }
+ }
+ if !matches.is_empty() {
+ results.push(serde_json::json!({
+ "file": p.to_string_lossy(),
+ "matches": matches,
+ }));
+ }
+ }
+ }
+
+ Ok(serde_json::json!({ "results": results, "count": results.len() }))
+}
+
+#[tauri::command]
+pub fn fs_info(path: String) -> Result<serde_json::Value, String> {
+ let full = resolve_path(&path);
+ if !full.exists() {
+ return Err(format!("Path not found: {}", full.display()));
+ }
+ let meta = fs::metadata(&full).map_err(|e| format!("Metadata error: {}", e))?;
+ let modified = meta
+ .modified()
+ .ok()
+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ let created = meta
+ .created()
+ .ok()
+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+
+ Ok(serde_json::json!({
+ "path": full.to_string_lossy(),
+ "size": meta.len(),
+ "isDir": meta.is_dir(),
+ "isFile": meta.is_file(),
+ "modified": modified,
+ "created": created,
+ "readonly": meta.permissions().readonly(),
+ }))
+}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index ce7b9bbe..b54807b1 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -1,7 +1,10 @@
pub mod agent;
pub mod download;
+pub mod filesystem;
pub mod install;
pub mod process;
pub mod proxy;
pub mod search;
+pub mod shell;
+pub mod system;
pub mod whisper;
diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rs
new file mode 100644
index 00000000..58544c6c
--- /dev/null
+++ b/src-tauri/src/commands/shell.rs
@@ -0,0 +1,98 @@
+use std::io::Read;
+use std::process::{Command, Stdio};
+
+#[cfg(target_os = "windows")]
+use std::os::windows::process::CommandExt;
+
+#[cfg(target_os = "windows")]
+const CREATE_NO_WINDOW: u32 = 0x08000000;
+
+#[tauri::command]
+pub fn shell_execute(
+ command: String,
+ args: Option<Vec<String>>,
+ cwd: Option<String>,
+ timeout: Option<u64>,
+ shell: Option<String>,
+) -> Result<serde_json::Value, String> {
+ let timeout_ms = timeout.unwrap_or(120_000);
+ let shell_bin = shell.unwrap_or_else(|| {
+ if cfg!(target_os = "windows") {
+ "powershell".to_string()
+ } else {
+ "bash".to_string()
+ }
+ });
+
+ let mut cmd = Command::new(&shell_bin);
+
+ // Build shell command
+ if cfg!(target_os = "windows") && shell_bin.to_lowercase().contains("powershell") {
+ cmd.arg("-NoProfile").arg("-NonInteractive").arg("-Command").arg(&command);
+ } else if cfg!(target_os = "windows") && shell_bin.to_lowercase().contains("cmd") {
+ cmd.arg("/C").arg(&command);
+ } else {
+ cmd.arg("-c").arg(&command);
+ }
+
+ // Append extra args
+ if let Some(extra_args) = args {
+ for a in extra_args {
+ cmd.arg(&a);
+ }
+ }
+
+ // Working directory
+ if let Some(ref dir) = cwd {
+ let path = std::path::Path::new(dir);
+ if path.is_dir() {
+ cmd.current_dir(path);
+ }
+ }
+
+ cmd.stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let mut child = cmd.spawn().map_err(|e| format!("Spawn shell: {}", e))?;
+
+ let start = std::time::Instant::now();
+ let timeout_dur = std::time::Duration::from_millis(timeout_ms);
+
+ loop {
+ match child.try_wait() {
+ Ok(Some(status)) => {
+ let mut stdout_str = String::new();
+ let mut stderr_str = String::new();
+ if let Some(mut stdout) = child.stdout.take() {
+ let _ = stdout.read_to_string(&mut stdout_str);
+ }
+ if let Some(mut stderr) = child.stderr.take() {
+ let _ = stderr.read_to_string(&mut stderr_str);
+ }
+ return Ok(serde_json::json!({
+ "stdout": stdout_str,
+ "stderr": stderr_str,
+ "exitCode": status.code().unwrap_or(-1),
+ "timedOut": false,
+ }));
+ }
+ Ok(None) => {
+ if start.elapsed() > timeout_dur {
+ let _ = child.kill();
+ return Ok(serde_json::json!({
+ "stdout": "",
+ "stderr": format!("Execution timed out after {}ms", timeout_ms),
+ "exitCode": -1,
+ "timedOut": true,
+ }));
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+ Err(e) => return Err(format!("Wait error: {}", e)),
+ }
+ }
+}
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
new file mode 100644
index 00000000..6aa93e4c
--- /dev/null
+++ b/src-tauri/src/commands/system.rs
@@ -0,0 +1,97 @@
+use base64::Engine;
+use sysinfo::System;
+
+#[cfg(target_os = "windows")]
+use std::os::windows::process::CommandExt;
+
+#[tauri::command]
+pub fn system_info() -> Result<serde_json::Value, String> {
+ Ok(serde_json::json!({
+ "os": std::env::consts::OS,
+ "arch": std::env::consts::ARCH,
+ "hostname": hostname::get()
+ .map(|h| h.to_string_lossy().to_string())
+ .unwrap_or_default(),
+ "username": whoami::username(),
+ "totalMemory": System::new_all().total_memory(),
+ "cpuCount": num_cpus::get(),
+ }))
+}
+
+#[tauri::command]
+pub fn process_list() -> Result<serde_json::Value, String> {
+ let mut sys = System::new_all();
+ sys.refresh_all();
+
+ let mut processes: Vec<serde_json::Value> = sys
+ .processes()
+ .values()
+ .map(|p| {
+ serde_json::json!({
+ "name": p.name().to_string_lossy(),
+ "pid": p.pid().as_u32(),
+ "memory": p.memory(),
+ "cpu": p.cpu_usage(),
+ })
+ })
+ .collect();
+
+ // Sort by memory desc, limit to top 50
+ processes.sort_by(|a, b| {
+ b.get("memory")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0)
+ .cmp(
+ &a.get("memory")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0),
+ )
+ });
+ processes.truncate(50);
+
+ Ok(serde_json::json!({ "processes": processes, "count": processes.len() }))
+}
+
+#[tauri::command]
+pub fn screenshot() -> Result<serde_json::Value, String> {
+ // Use PowerShell to capture screen on Windows
+ #[cfg(target_os = "windows")]
+ {
+ let tmp = std::env::temp_dir().join("lu-screenshot.png");
+ let ps_script = format!(
+ r#"
+ Add-Type -AssemblyName System.Windows.Forms
+ Add-Type -AssemblyName System.Drawing
+ $screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
+ $bitmap = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height)
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
+ $graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size)
+ $bitmap.Save('{}')
+ $graphics.Dispose()
+ $bitmap.Dispose()
+ "#,
+ tmp.to_string_lossy().replace('\\', "\\\\")
+ );
+
+ let output = std::process::Command::new("powershell")
+ .args(["-NoProfile", "-NonInteractive", "-Command", &ps_script])
+ .creation_flags(0x08000000) // CREATE_NO_WINDOW
+ .output()
+ .map_err(|e| format!("Screenshot failed: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("Screenshot failed: {}", stderr));
+ }
+
+ let bytes = std::fs::read(&tmp).map_err(|e| format!("Read screenshot: {}", e))?;
+ let _ = std::fs::remove_file(&tmp);
+ let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
+ Ok(serde_json::json!({ "image": b64, "format": "png", "encoding": "base64" }))
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ {
+ Err("Screenshot not implemented for this platform yet".to_string())
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 89c463ff..b9a484e8 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -33,10 +33,22 @@ fn main() {
// Whisper STT
commands::whisper::whisper_status,
commands::whisper::transcribe,
- // Agent tools
+ // Agent tools (legacy)
commands::agent::execute_code,
commands::agent::file_read,
commands::agent::file_write,
+ // Shell
+ commands::shell::shell_execute,
+ // Filesystem
+ commands::filesystem::fs_read,
+ commands::filesystem::fs_write,
+ commands::filesystem::fs_list,
+ commands::filesystem::fs_search,
+ commands::filesystem::fs_info,
+ // System
+ commands::system::system_info,
+ commands::system::process_list,
+ commands::system::screenshot,
// Downloads
commands::download::download_model,
commands::download::download_progress,
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 42d57faf..ce6fe3c2 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -19,7 +19,8 @@
"resizable": true,
"fullscreen": false,
"visible": false,
- "decorations": false
+ "decorations": false,
+ "transparent": true
}
],
"security": {
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 621fce6b..080fcdaf 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -129,6 +129,16 @@ export async function backendCall<T = any>(
ollama_search: { path: "/ollama-search" },
fetch_external: { path: "/local-api/proxy-download" },
fetch_external_bytes: { path: "/local-api/proxy-download" },
+ // Agent tools (Phase 1 — new commands)
+ shell_execute: { path: "/local-api/shell-execute", method: "POST" },
+ fs_read: { path: "/local-api/fs-read", method: "POST" },
+ fs_write: { path: "/local-api/fs-write", method: "POST" },
+ fs_list: { path: "/local-api/fs-list", method: "POST" },
+ fs_search: { path: "/local-api/fs-search", method: "POST" },
+ fs_info: { path: "/local-api/fs-info", method: "POST" },
+ system_info: { path: "/local-api/system-info" },
+ process_list: { path: "/local-api/process-list" },
+ screenshot: { path: "/local-api/screenshot" },
};
const endpoint = endpointMap[command];
diff --git a/src/api/hermes-tool-calling.ts b/src/api/hermes-tool-calling.ts
index dcaae16b..5cd28766 100644
--- a/src/api/hermes-tool-calling.ts
+++ b/src/api/hermes-tool-calling.ts
@@ -12,15 +12,18 @@
import type { AgentToolDef } from '../types/agent-mode'
+// Generic tool shape accepted by the prompt builder
+type ToolLike = { name: string; description: string; parameters?: any; inputSchema?: any }
+
// ── Build System Prompt with Tool Definitions ───────────────────
-export function buildHermesToolPrompt(tools: AgentToolDef[]): string {
+export function buildHermesToolPrompt(tools: (AgentToolDef | ToolLike)[]): string {
const toolDefs = tools.map((t) => JSON.stringify({
type: 'function',
function: {
name: t.name,
description: t.description,
- parameters: t.parameters,
+ parameters: (t as any).inputSchema || (t as any).parameters,
},
})).join('\n')
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
new file mode 100644
index 00000000..ffccaafd
--- /dev/null
+++ b/src/api/mcp/builtin-tools.ts
@@ -0,0 +1,447 @@
+// Built-in tool definitions + executors — replaces hardcoded AGENT_TOOL_DEFS
+
+import type { MCPToolDefinition } from './types'
+import type { ToolRegistry } from './tool-registry'
+import { backendCall, fetchExternal } from '../backend'
+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
+import { WorkflowEngine } from '../../lib/workflow-engine'
+import type { StepResult } from '../../types/agent-workflows'
+
+// ── Tool Definitions ────────────────────────────────────────────
+
+const BUILTIN_TOOLS: MCPToolDefinition[] = [
+ // Web
+ {
+ name: 'web_search',
+ description: 'Search the web for current information. Returns titles, URLs, and short snippets. Use web_fetch on promising URLs to read full content.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'The search query string' },
+ maxResults: { type: 'number', description: 'Maximum results to return (default: 5)' },
+ },
+ required: ['query'],
+ },
+ category: 'web',
+ source: 'builtin',
+ },
+ {
+ name: 'web_fetch',
+ description: 'Fetch a web page URL and return its text content. Use AFTER web_search to read the full content. Returns cleaned text, not HTML.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: { type: 'string', description: 'The URL to fetch' },
+ maxLength: { type: 'number', description: 'Maximum characters to return (default: 4000)' },
+ },
+ required: ['url'],
+ },
+ category: 'web',
+ source: 'builtin',
+ },
+
+ // Filesystem
+ {
+ name: 'file_read',
+ description: 'Read the contents of any file on the system. Supports absolute paths and relative paths (relative to agent workspace).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Path to the file (absolute or relative)' },
+ },
+ required: ['path'],
+ },
+ category: 'filesystem',
+ source: 'builtin',
+ },
+ {
+ name: 'file_write',
+ description: 'Write content to any file. Creates the file if it does not exist, overwrites if it does. Creates parent directories automatically.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Path to the file (absolute or relative)' },
+ content: { type: 'string', description: 'The content to write' },
+ },
+ required: ['path', 'content'],
+ },
+ category: 'filesystem',
+ source: 'builtin',
+ },
+ {
+ name: 'file_list',
+ description: 'List files and directories at a path. Supports recursive listing and glob patterns.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Directory path to list' },
+ recursive: { type: 'boolean', description: 'Whether to list recursively (default: false)' },
+ pattern: { type: 'string', description: 'Glob pattern to filter results (e.g. "*.ts", "**/*.py")' },
+ },
+ required: ['path'],
+ },
+ category: 'filesystem',
+ source: 'builtin',
+ },
+ {
+ name: 'file_search',
+ description: 'Search file contents using regex patterns. Returns matching files with line numbers and context.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Directory to search in' },
+ pattern: { type: 'string', description: 'Regex pattern to search for' },
+ maxResults: { type: 'number', description: 'Maximum files to return (default: 50)' },
+ },
+ required: ['path', 'pattern'],
+ },
+ category: 'filesystem',
+ source: 'builtin',
+ },
+
+ // Terminal
+ {
+ name: 'shell_execute',
+ description: 'Execute a shell command on the system. Supports PowerShell (Windows), bash (Linux/Mac). Returns stdout, stderr, and exit code.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ command: { type: 'string', description: 'The command to execute' },
+ cwd: { type: 'string', description: 'Working directory (optional)' },
+ timeout: { type: 'number', description: 'Timeout in milliseconds (default: 120000)' },
+ shell: { type: 'string', description: 'Shell to use: "powershell", "cmd", "bash" (default: auto)' },
+ },
+ required: ['command'],
+ },
+ category: 'terminal',
+ source: 'builtin',
+ },
+ {
+ name: 'code_execute',
+ description: 'Execute Python code. Returns stdout, stderr, and exit code.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ code: { type: 'string', description: 'The Python code to execute' },
+ language: { type: 'string', description: 'Programming language: "python" or "shell"', enum: ['python', 'shell'] },
+ },
+ required: ['code'],
+ },
+ category: 'terminal',
+ source: 'builtin',
+ },
+
+ // System
+ {
+ name: 'system_info',
+ description: 'Get system information: OS, architecture, hostname, username, RAM, CPU count.',
+ inputSchema: { type: 'object', properties: {}, required: [] },
+ category: 'system',
+ source: 'builtin',
+ },
+ {
+ name: 'process_list',
+ description: 'List running processes sorted by memory usage. Returns top 50 processes with name, PID, memory, and CPU usage.',
+ inputSchema: { type: 'object', properties: {}, required: [] },
+ category: 'system',
+ source: 'builtin',
+ },
+
+ // Desktop
+ {
+ name: 'screenshot',
+ description: 'Take a screenshot of the primary screen. Returns base64-encoded PNG image.',
+ inputSchema: { type: 'object', properties: {}, required: [] },
+ category: 'desktop',
+ source: 'builtin',
+ },
+
+ // Image
+ {
+ name: 'image_generate',
+ description: 'Generate an image from a text description using the local ComfyUI image generation pipeline.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ prompt: { type: 'string', description: 'Text description of the image to generate' },
+ negativePrompt: { type: 'string', description: 'Things to avoid in the generated image' },
+ },
+ required: ['prompt'],
+ },
+ category: 'image',
+ source: 'builtin',
+ },
+
+ // Workflow
+ {
+ name: 'run_workflow',
+ description: 'Run a saved agent workflow by name. Available workflows: Research Topic, Summarize URL, Code Review, and any custom workflows.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Name of the workflow to run' },
+ input: { type: 'string', description: 'Initial input to provide to the workflow' },
+ },
+ required: ['name'],
+ },
+ category: 'workflow',
+ source: 'builtin',
+ },
+]
+
+// ── Executors ────────────────────────────────────────────────────
+
+async function executeWebSearch(args: Record<string, any>): Promise<string> {
+ const { useSettingsStore } = await import('../../stores/settingsStore')
+ const searchSettings = useSettingsStore.getState().settings
+ const data = await backendCall('web_search', {
+ query: args.query,
+ count: args.maxResults || 5,
+ provider: searchSettings.searchProvider || 'auto',
+ braveApiKey: searchSettings.braveApiKey || '',
+ tavilyApiKey: searchSettings.tavilyApiKey || '',
+ })
+ if (Array.isArray(data.results)) {
+ return data.results
+ .map((r: any, i: number) => `${i + 1}. ${r.title}\n ${r.url}\n ${r.snippet}`)
+ .join('\n\n')
+ }
+ return JSON.stringify(data)
+}
+
+async function executeWebFetch(args: Record<string, any>): Promise<string> {
+ const url = args.url
+ const maxLength = args.maxLength || 4000
+ if (!url) return 'Error: No URL provided'
+
+ const html = await fetchExternal(url)
+ const text = htmlToText(html)
+ if (text.length > maxLength) {
+ return text.substring(0, maxLength) + '\n\n[...truncated]'
+ }
+ return text || 'Error: Page returned empty content'
+}
+
+async function executeFileRead(args: Record<string, any>): Promise<string> {
+ const data = await backendCall('fs_read', { path: args.path })
+ return data.content || ''
+}
+
+async function executeFileWrite(args: Record<string, any>): Promise<string> {
+ const data = await backendCall('fs_write', { path: args.path, content: args.content })
+ return data.status === 'saved' ? `File saved: ${data.path}` : JSON.stringify(data)
+}
+
+async function executeFileList(args: Record<string, any>): Promise<string> {
+ const data = await backendCall('fs_list', {
+ path: args.path,
+ recursive: args.recursive || false,
+ pattern: args.pattern || null,
+ })
+ if (Array.isArray(data.entries)) {
+ return data.entries
+ .map((e: any) => `${e.isDir ? '[DIR]' : ''} ${e.name} (${formatBytes(e.size)}) ${e.path}`)
+ .join('\n')
+ }
+ return JSON.stringify(data)
+}
+
+async function executeFileSearch(args: Record<string, any>): Promise<string> {
+ const data = await backendCall('fs_search', {
+ path: args.path,
+ pattern: args.pattern,
+ max_results: args.maxResults || 50,
+ })
+ if (Array.isArray(data.results)) {
+ return data.results
+ .map((r: any) => {
+ const matches = r.matches?.map((m: any) => ` L${m.line}: ${m.text}`).join('\n') || ''
+ return `${r.file}\n${matches}`
+ })
+ .join('\n\n')
+ }
+ return JSON.stringify(data)
+}
+
+async function executeShellExecute(args: Record<string, any>): Promise<string> {
+ const data = await backendCall('shell_execute', {
+ command: args.command,
+ args: args.args || null,
+ cwd: args.cwd || null,
+ timeout: args.timeout || 120000,
+ shell: args.shell || null,
+ })
+ return `Exit code: ${data.exitCode ?? 0}\nStdout:\n${data.stdout || ''}\nStderr:\n${data.stderr || ''}`
+}
+
+async function executeCodeExecute(args: Record<string, any>): Promise<string> {
+ const data = await backendCall('execute_code', { code: args.code, timeout: 30000 })
+ return `Exit code: ${data.exitCode ?? 0}\nStdout:\n${data.stdout || ''}\nStderr:\n${data.stderr || ''}`
+}
+
+async function executeSystemInfo(): Promise<string> {
+ const data = await backendCall('system_info', {})
+ return Object.entries(data).map(([k, v]) => `${k}: ${v}`).join('\n')
+}
+
+async function executeProcessList(): Promise<string> {
+ const data = await backendCall('process_list', {})
+ if (Array.isArray(data.processes)) {
+ return data.processes
+ .slice(0, 30)
+ .map((p: any) => `${p.name} (PID: ${p.pid}) — ${formatBytes(p.memory)} RAM, ${p.cpu?.toFixed(1)}% CPU`)
+ .join('\n')
+ }
+ return JSON.stringify(data)
+}
+
+async function executeScreenshot(): Promise<string> {
+ const data = await backendCall('screenshot', {})
+ if (data.image) {
+ return `[Screenshot captured: base64 PNG, ${Math.round(data.image.length / 1024)}KB]`
+ }
+ return JSON.stringify(data)
+}
+
+async function executeImageGenerate(args: Record<string, any>): Promise<string> {
+ const prompt = args.prompt || args.description || ''
+ if (!prompt) return 'Error: No prompt provided for image generation.'
+ try {
+ const { buildDynamicWorkflow } = await import('../dynamic-workflow')
+ const { submitWorkflow, getHistory, classifyModel, getImageModels } = await import('../comfyui')
+ const models = await getImageModels()
+ if (models.length === 0) return 'Error: No image models available in ComfyUI.'
+ const model = models[0]
+ const workflow = await buildDynamicWorkflow({
+ prompt, negativePrompt: '', model: model.name,
+ sampler: 'euler', scheduler: 'normal', steps: 20, cfgScale: 7,
+ width: 1024, height: 1024, seed: -1, batchSize: 1,
+ }, classifyModel(model.name))
+ const promptId = await submitWorkflow(workflow)
+ for (let i = 0; i < 300; i++) {
+ await new Promise(r => setTimeout(r, 1000))
+ const history = await getHistory(promptId)
+ if (history?.status?.completed) {
+ const outputs = history.outputs ?? {}
+ for (const nodeId of Object.keys(outputs)) {
+ const files = [...(outputs[nodeId].images ?? []), ...(outputs[nodeId].gifs ?? [])]
+ if (files.length > 0) return `Image generated: ${files[0].filename} (prompt: "${prompt}")`
+ }
+ return 'Generation completed but no output produced.'
+ }
+ if (history?.status?.status_str === 'error') return `Generation failed: ${history.status.messages?.[0]?.[1]?.message || 'Unknown error'}`
+ }
+ return 'Generation timed out after 5 minutes.'
+ } catch (err) {
+ return `Generation failed: ${err instanceof Error ? err.message : String(err)}`
+ }
+}
+
+let _workflowDepth = 0
+
+async function executeRunWorkflow(args: Record<string, any>): Promise<string> {
+ const workflowName = args.name
+ if (!workflowName) return 'Error: No workflow name provided'
+ if (_workflowDepth >= 5) return 'Error: Maximum workflow nesting depth (5) exceeded'
+
+ const store = useAgentWorkflowStore.getState()
+ const workflow = store.workflows.find(w => w.name.toLowerCase() === workflowName.toLowerCase())
+ if (!workflow) {
+ const available = store.workflows.map(w => w.name).join(', ')
+ return `Error: Workflow "${workflowName}" not found. Available: ${available}`
+ }
+
+ const results: StepResult[] = []
+ let finalOutput = ''
+ const callbacks = {
+ onStepStart: () => {},
+ onStepComplete: (_idx: number, result: StepResult) => { results.push(result) },
+ onStepError: () => {},
+ onWaitingForInput: () => {},
+ onComplete: () => {
+ const lastOutput = results.filter(r => r.output).pop()
+ finalOutput = lastOutput?.output || 'Workflow completed with no output.'
+ },
+ onError: (error: string) => { finalOutput = `Workflow error: ${error}` },
+ }
+
+ const initialVars = args.input ? { user_input: args.input, last_output: args.input } : {}
+ _workflowDepth++
+ try {
+ const engine = new WorkflowEngine(workflow, 'tool-execution', callbacks, initialVars, _workflowDepth)
+ await engine.run()
+ } finally {
+ _workflowDepth--
+ }
+ return finalOutput
+}
+
+// ── Helpers ─────────────────────────────────────────────────────
+
+function formatBytes(bytes: number): string {
+ if (bytes === 0) return '0 B'
+ const k = 1024
+ const sizes = ['B', 'KB', 'MB', 'GB']
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
+ return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`
+}
+
+function htmlToText(html: string): string {
+ if (typeof DOMParser !== 'undefined') {
+ const parser = new DOMParser()
+ const doc = parser.parseFromString(html, 'text/html')
+ doc.querySelectorAll('script, style, nav, header, footer, .nav, .header, .footer, .sidebar, .menu, .ad, .advertisement, [role="navigation"], [role="banner"]').forEach(el => el.remove())
+ const main = doc.querySelector('main, article, [role="main"], .content, .article, .post, #content, #main')
+ const target = main || doc.body
+ if (!target) return ''
+ let text = ''
+ const walker = document.createTreeWalker(target, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT)
+ let node: Node | null = walker.nextNode()
+ while (node) {
+ if (node.nodeType === Node.TEXT_NODE) {
+ const t = node.textContent?.trim()
+ if (t) text += t + ' '
+ } else if (node.nodeType === Node.ELEMENT_NODE) {
+ const tag = (node as Element).tagName.toLowerCase()
+ if (['p', 'div', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'tr'].includes(tag)) text += '\n'
+ if (['h1', 'h2', 'h3'].includes(tag)) text += '# '
+ }
+ node = walker.nextNode()
+ }
+ return text.replace(/\n{3,}/g, '\n\n').replace(/ {2,}/g, ' ').trim()
+ }
+ return html
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
+ .replace(/<[^>]+>/g, ' ')
+ .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, ' ')
+ .replace(/\s{2,}/g, ' ')
+ .trim()
+}
+
+// ── Registration ────────────────────────────────────────────────
+
+const EXECUTOR_MAP: Record<string, (args: Record<string, any>) => Promise<string>> = {
+ web_search: executeWebSearch,
+ web_fetch: executeWebFetch,
+ file_read: executeFileRead,
+ file_write: executeFileWrite,
+ file_list: executeFileList,
+ file_search: executeFileSearch,
+ shell_execute: executeShellExecute,
+ code_execute: executeCodeExecute,
+ system_info: executeSystemInfo,
+ process_list: executeProcessList,
+ screenshot: executeScreenshot,
+ image_generate: executeImageGenerate,
+ run_workflow: executeRunWorkflow,
+}
+
+export function registerBuiltinTools(registry: ToolRegistry) {
+ for (const tool of BUILTIN_TOOLS) {
+ const executor = EXECUTOR_MAP[tool.name]
+ if (executor) {
+ registry.registerBuiltin(tool, executor)
+ }
+ }
+}
diff --git a/src/api/mcp/external-client.ts b/src/api/mcp/external-client.ts
new file mode 100644
index 00000000..2bfd90ca
--- /dev/null
+++ b/src/api/mcp/external-client.ts
@@ -0,0 +1,183 @@
+/**
+ * MCP External Client — connects to external MCP servers via stdio JSON-RPC.
+ *
+ * Uses @tauri-apps/plugin-shell to spawn server processes
+ * and communicate via stdin/stdout JSON-RPC 2.0.
+ */
+
+import type { MCPToolDefinition, MCPServerConfig } from './types'
+
+// JSON-RPC message types
+interface JsonRpcRequest {
+ jsonrpc: '2.0'
+ id: number
+ method: string
+ params?: any
+}
+
+interface JsonRpcResponse {
+ jsonrpc: '2.0'
+ id: number
+ result?: any
+ error?: { code: number; message: string; data?: any }
+}
+
+export class MCPExternalClient {
+ private process: any = null
+ private requestId = 0
+ private pendingRequests = new Map<number, {
+ resolve: (value: any) => void
+ reject: (error: Error) => void
+ }>()
+ private outputBuffer = ''
+ private connected = false
+
+ constructor(private config: MCPServerConfig) {}
+
+ async connect(): Promise<MCPToolDefinition[]> {
+ try {
+ // Dynamic import for Tauri shell plugin — only available in .exe builds
+ // @ts-ignore — module may not exist in dev mode
+ const shellModule = await import(/* @vite-ignore */ '@tauri-apps/plugin-shell')
+ const { Command } = shellModule
+
+ this.process = Command.create(this.config.command, this.config.args, {
+ env: this.config.env,
+ })
+
+ // Handle stdout — parse JSON-RPC responses
+ this.process.stdout.on('data', (data: string) => {
+ this.outputBuffer += data
+ this.processBuffer()
+ })
+
+ this.process.stderr.on('data', (data: string) => {
+ console.warn(`[MCP:${this.config.name}] stderr:`, data)
+ })
+
+ this.process.on('close', () => {
+ this.connected = false
+ this.rejectAllPending('Server process exited')
+ })
+
+ await this.process.spawn()
+ this.connected = true
+
+ // Initialize the MCP connection
+ await this.sendRequest('initialize', {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'locally-uncensored', version: '2.3.0' },
+ })
+
+ // Discover tools
+ const toolsResult = await this.sendRequest('tools/list', {})
+ const tools: MCPToolDefinition[] = (toolsResult.tools || []).map((t: any) => ({
+ name: t.name,
+ description: t.description || '',
+ inputSchema: t.inputSchema || { type: 'object', properties: {}, required: [] },
+ category: 'workflow' as const, // External tools default to workflow category
+ source: 'external' as const,
+ serverId: this.config.id,
+ }))
+
+ return tools
+ } catch (err) {
+ this.connected = false
+ throw new Error(`Failed to connect to MCP server "${this.config.name}": ${err instanceof Error ? err.message : String(err)}`)
+ }
+ }
+
+ async callTool(name: string, args: Record<string, any>): Promise<string> {
+ if (!this.connected) throw new Error('Not connected')
+
+ const result = await this.sendRequest('tools/call', { name, arguments: args })
+
+ // MCP returns content array
+ if (Array.isArray(result.content)) {
+ return result.content
+ .map((c: any) => {
+ if (c.type === 'text') return c.text
+ if (c.type === 'image') return `[Image: ${c.mimeType}]`
+ return JSON.stringify(c)
+ })
+ .join('\n')
+ }
+ return JSON.stringify(result)
+ }
+
+ async disconnect() {
+ this.connected = false
+ this.rejectAllPending('Disconnecting')
+ if (this.process) {
+ try {
+ await this.process.kill()
+ } catch {
+ // Process may already be dead
+ }
+ this.process = null
+ }
+ }
+
+ isConnected() {
+ return this.connected
+ }
+
+ // ── Private ─────────────────────────────────────────────────
+
+ private sendRequest(method: string, params?: any): Promise<any> {
+ return new Promise((resolve, reject) => {
+ const id = ++this.requestId
+ const request: JsonRpcRequest = {
+ jsonrpc: '2.0',
+ id,
+ method,
+ params,
+ }
+
+ this.pendingRequests.set(id, { resolve, reject })
+
+ const msg = JSON.stringify(request) + '\n'
+ this.process.stdin.write(msg)
+
+ // Timeout after 30 seconds
+ setTimeout(() => {
+ if (this.pendingRequests.has(id)) {
+ this.pendingRequests.delete(id)
+ reject(new Error(`Request ${method} timed out`))
+ }
+ }, 30000)
+ })
+ }
+
+ private processBuffer() {
+ const lines = this.outputBuffer.split('\n')
+ this.outputBuffer = lines.pop() || ''
+
+ for (const line of lines) {
+ const trimmed = line.trim()
+ if (!trimmed) continue
+ try {
+ const response: JsonRpcResponse = JSON.parse(trimmed)
+ const pending = this.pendingRequests.get(response.id)
+ if (pending) {
+ this.pendingRequests.delete(response.id)
+ if (response.error) {
+ pending.reject(new Error(response.error.message))
+ } else {
+ pending.resolve(response.result)
+ }
+ }
+ } catch {
+ // Not JSON — might be a notification, ignore
+ }
+ }
+ }
+
+ private rejectAllPending(reason: string) {
+ for (const [id, { reject }] of this.pendingRequests) {
+ reject(new Error(reason))
+ this.pendingRequests.delete(id)
+ }
+ }
+}
diff --git a/src/api/mcp/index.ts b/src/api/mcp/index.ts
new file mode 100644
index 00000000..a5d0870e
--- /dev/null
+++ b/src/api/mcp/index.ts
@@ -0,0 +1,12 @@
+// MCP Tool System — entry point
+
+export { toolRegistry, ToolRegistry } from './tool-registry'
+export { registerBuiltinTools } from './builtin-tools'
+export type { MCPToolDefinition, ToolCategory, PermissionLevel, PermissionMap, MCPServerConfig } from './types'
+export { DEFAULT_PERMISSIONS } from './types'
+
+// Initialize: register all built-in tools on import
+import { toolRegistry } from './tool-registry'
+import { registerBuiltinTools } from './builtin-tools'
+
+registerBuiltinTools(toolRegistry)
diff --git a/src/api/mcp/tool-registry.ts b/src/api/mcp/tool-registry.ts
new file mode 100644
index 00000000..ff16e02e
--- /dev/null
+++ b/src/api/mcp/tool-registry.ts
@@ -0,0 +1,108 @@
+// Dynamic Tool Registry — MCP-shaped, replaces hardcoded AGENT_TOOL_DEFS
+
+import type { MCPToolDefinition, PermissionMap, PermissionLevel } from './types'
+import type { OllamaTool } from '../../types/agent-mode'
+import type { ToolDefinition } from '../providers/types'
+
+type ToolExecutor = (args: Record<string, any>) => Promise<string>
+
+interface RegisteredTool {
+ definition: MCPToolDefinition
+ executor: ToolExecutor
+}
+
+export class ToolRegistry {
+ private tools = new Map<string, RegisteredTool>()
+
+ // ── Registration ──────────────────────────────────────────────
+
+ registerBuiltin(tool: MCPToolDefinition, executor: ToolExecutor) {
+ this.tools.set(tool.name, { definition: tool, executor })
+ }
+
+ registerExternal(serverId: string, tools: MCPToolDefinition[], executor: ToolExecutor) {
+ for (const tool of tools) {
+ this.tools.set(tool.name, {
+ definition: { ...tool, source: 'external', serverId },
+ executor,
+ })
+ }
+ }
+
+ unregisterServer(serverId: string) {
+ for (const [name, entry] of this.tools) {
+ if (entry.definition.serverId === serverId) {
+ this.tools.delete(name)
+ }
+ }
+ }
+
+ // ── Query ─────────────────────────────────────────────────────
+
+ getAll(): MCPToolDefinition[] {
+ return Array.from(this.tools.values()).map(t => t.definition)
+ }
+
+ getAvailableTools(permissions: PermissionMap): MCPToolDefinition[] {
+ return this.getAll().filter(t => permissions[t.category] !== 'blocked')
+ }
+
+ getToolByName(name: string): MCPToolDefinition | undefined {
+ return this.tools.get(name)?.definition
+ }
+
+ getPermissionLevel(toolName: string, permissions: PermissionMap): PermissionLevel {
+ const tool = this.tools.get(toolName)?.definition
+ if (!tool) return 'confirm'
+ return permissions[tool.category]
+ }
+
+ // ── Execution ─────────────────────────────────────────────────
+
+ async execute(name: string, args: Record<string, any>): Promise<string> {
+ const entry = this.tools.get(name)
+ if (!entry) return `Error: Unknown tool "${name}"`
+ try {
+ return await entry.executor(args)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ return `Error: ${message}`
+ }
+ }
+
+ // ── Format Conversion ─────────────────────────────────────────
+
+ toOllamaTools(permissions: PermissionMap): OllamaTool[] {
+ return this.getAvailableTools(permissions).map(t => ({
+ type: 'function' as const,
+ function: {
+ name: t.name,
+ description: t.description,
+ parameters: t.inputSchema,
+ },
+ }))
+ }
+
+ toOpenAITools(permissions: PermissionMap): ToolDefinition[] {
+ return this.getAvailableTools(permissions).map(t => ({
+ type: 'function' as const,
+ function: {
+ name: t.name,
+ description: t.description,
+ parameters: t.inputSchema,
+ },
+ }))
+ }
+
+ toHermesToolDefs(permissions: PermissionMap): { name: string; description: string; parameters: any }[] {
+ return this.getAvailableTools(permissions).map(t => ({
+ name: t.name,
+ description: t.description,
+ parameters: t.inputSchema,
+ }))
+ }
+}
+
+// ── Singleton ────────────────────────────────────────────────────
+
+export const toolRegistry = new ToolRegistry()
diff --git a/src/api/mcp/types.ts b/src/api/mcp/types.ts
new file mode 100644
index 00000000..20a3d78f
--- /dev/null
+++ b/src/api/mcp/types.ts
@@ -0,0 +1,43 @@
+// MCP-shaped tool definitions and permission types
+
+export type ToolCategory = 'filesystem' | 'terminal' | 'desktop' | 'web' | 'system' | 'image' | 'video' | 'workflow'
+
+export type PermissionLevel = 'blocked' | 'confirm' | 'auto'
+
+export type PermissionMap = Record<ToolCategory, PermissionLevel>
+
+export const DEFAULT_PERMISSIONS: PermissionMap = {
+ filesystem: 'confirm',
+ terminal: 'confirm',
+ desktop: 'confirm',
+ web: 'auto',
+ system: 'auto',
+ image: 'confirm',
+ workflow: 'confirm',
+}
+
+export interface MCPToolDefinition {
+ name: string
+ description: string
+ inputSchema: {
+ type: 'object'
+ properties: Record<string, {
+ type: string
+ description: string
+ enum?: string[]
+ }>
+ required: string[]
+ }
+ category: ToolCategory
+ source: 'builtin' | 'external'
+ serverId?: string // for external MCP server tools
+}
+
+export interface MCPServerConfig {
+ id: string
+ name: string
+ command: string
+ args: string[]
+ env?: Record<string, string>
+ enabled: boolean
+}
diff --git a/src/api/tool-registry.ts b/src/api/tool-registry.ts
index 19bef4eb..106c70e3 100644
--- a/src/api/tool-registry.ts
+++ b/src/api/tool-registry.ts
@@ -1,285 +1,41 @@
-import type { AgentToolDef, OllamaTool } from '../types/agent-mode'
-import { executeTool } from './agents'
-import { fetchExternal } from './backend'
-import type { ToolName } from '../types/agents'
-import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
-import { WorkflowEngine } from '../lib/workflow-engine'
-import type { StepResult } from '../types/agent-workflows'
+/**
+ * Compatibility shim — delegates to new MCP tool registry.
+ * Existing imports from this file continue to work.
+ */
-// ── Tool Definitions ──────────────────────────────────────────────
+import { toolRegistry, DEFAULT_PERMISSIONS } from './mcp'
+import type { AgentToolDef, OllamaTool } from '../types/agent-mode'
-export const AGENT_TOOL_DEFS: AgentToolDef[] = [
- {
- name: 'web_search',
- description: 'Search the web for current information. Returns titles, URLs, and short snippets. Use web_fetch on promising URLs to read full content.',
- parameters: {
- type: 'object',
- properties: {
- query: { type: 'string', description: 'The search query string' },
- maxResults: { type: 'number', description: 'Maximum results to return (default: 5)' },
- },
- required: ['query'],
- },
- permission: 'auto',
- },
- {
- name: 'web_fetch',
- description: 'Fetch a web page URL and return its text content. Use this AFTER web_search to read the full content of a result. Returns cleaned text, not HTML.',
- parameters: {
- type: 'object',
- properties: {
- url: { type: 'string', description: 'The URL to fetch' },
- maxLength: { type: 'number', description: 'Maximum characters to return (default: 4000)' },
- },
- required: ['url'],
- },
- permission: 'auto',
- },
- {
- name: 'file_read',
- description: 'Read the contents of a file from the local filesystem within the agent workspace.',
- parameters: {
- type: 'object',
- properties: {
- path: { type: 'string', description: 'Path to the file to read' },
- },
- required: ['path'],
- },
- permission: 'auto',
- },
- {
- name: 'file_write',
- description: 'Write content to a file. Creates the file if it does not exist, overwrites if it does.',
- parameters: {
- type: 'object',
- properties: {
- path: { type: 'string', description: 'Path to the file to write' },
- content: { type: 'string', description: 'The content to write' },
- },
- required: ['path', 'content'],
- },
- permission: 'confirm',
- },
- {
- name: 'code_execute',
- description: 'Execute code in a sandboxed environment. Supports Python and shell commands. Returns stdout, stderr, and exit code.',
- parameters: {
- type: 'object',
- properties: {
- code: { type: 'string', description: 'The code to execute' },
- language: { type: 'string', description: 'Programming language: "python" or "shell"', enum: ['python', 'shell'] },
- },
- required: ['code'],
- },
- permission: 'confirm',
- },
- {
- name: 'image_generate',
- description: 'Generate an image from a text description using the local ComfyUI image generation pipeline.',
- parameters: {
- type: 'object',
- properties: {
- prompt: { type: 'string', description: 'Text description of the image to generate' },
- negativePrompt: { type: 'string', description: 'Things to avoid in the generated image' },
- },
- required: ['prompt'],
- },
- permission: 'confirm',
- },
- {
- name: 'run_workflow',
- description: 'Run a saved agent workflow by name. Available workflows: Research Topic, Summarize URL, Code Review, and any custom workflows.',
- parameters: {
- type: 'object',
- properties: {
- name: { type: 'string', description: 'Name of the workflow to run (e.g. "Research Topic", "Summarize URL", "Code Review")' },
- input: { type: 'string', description: 'Initial input to provide to the workflow (e.g. a topic, URL, or file path)' },
- },
- required: ['name'],
- },
- permission: 'confirm',
- },
-]
+// ── Legacy exports (delegate to new registry) ─────────────────
-// ── Convert to Ollama Format ──────────────────────────────────────
+/** @deprecated Use toolRegistry.getAll() */
+export const AGENT_TOOL_DEFS: AgentToolDef[] = toolRegistry.getAll().map((t) => ({
+ name: t.name,
+ description: t.description,
+ parameters: t.inputSchema,
+ permission: DEFAULT_PERMISSIONS[t.category] === 'auto' ? 'auto' as const : 'confirm' as const,
+}))
+/** @deprecated Use toolRegistry.toOllamaTools(permissions) */
export function getOllamaTools(): OllamaTool[] {
- return AGENT_TOOL_DEFS.map((tool) => ({
- type: 'function' as const,
- function: {
- name: tool.name,
- description: tool.description,
- parameters: tool.parameters,
- },
- }))
+ return toolRegistry.toOllamaTools(DEFAULT_PERMISSIONS)
}
-// ── Lookup Helpers ────────────────────────────────────────────────
-
+/** @deprecated Use toolRegistry.getToolByName(name) */
export function getToolByName(name: string): AgentToolDef | undefined {
return AGENT_TOOL_DEFS.find((t) => t.name === name)
}
+/** @deprecated Use toolRegistry.getPermissionLevel(name, permissions) */
export function getToolPermission(name: string): 'auto' | 'confirm' {
- const tool = getToolByName(name)
- return tool?.permission ?? 'confirm'
+ const level = toolRegistry.getPermissionLevel(name, DEFAULT_PERMISSIONS)
+ return level === 'auto' ? 'auto' : 'confirm'
}
-// ── Execute Tool (wraps errors as string results — never throws) ─
-
+/** @deprecated Use toolRegistry.execute(name, args) */
export async function executeAgentTool(
name: string,
args: Record<string, any>
): Promise<string> {
- try {
- // Handle web_fetch separately (not in legacy agents.ts)
- if (name === 'web_fetch') {
- return await executeWebFetch(args.url, args.maxLength)
- }
-
- // Handle run_workflow
- if (name === 'run_workflow') {
- return await executeRunWorkflow(args.name, args.input)
- }
-
- // Reuse the existing executeTool from agents.ts for other tools
- return await executeTool(name as ToolName, args)
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err)
- return `Error: ${message}`
- }
-}
-
-// ── web_fetch: Fetch URL → Extract Text → Return ────────────────
-
-async function executeWebFetch(url: string, maxLength: number = 4000): Promise<string> {
- if (!url) return 'Error: No URL provided'
-
- try {
- // Fetch the page content
- const html = await fetchExternal(url)
-
- // Convert HTML to readable text
- const text = htmlToText(html)
-
- // Truncate if needed
- if (text.length > maxLength) {
- return text.substring(0, maxLength) + '\n\n[...truncated]'
- }
-
- return text || 'Error: Page returned empty content'
- } catch (err) {
- return `Error fetching ${url}: ${err instanceof Error ? err.message : String(err)}`
- }
-}
-
-/**
- * Convert HTML to clean readable text.
- * Strips tags, decodes entities, preserves structure.
- */
-function htmlToText(html: string): string {
- // Use DOMParser if available (browser environment)
- if (typeof DOMParser !== 'undefined') {
- const parser = new DOMParser()
- const doc = parser.parseFromString(html, 'text/html')
-
- // Remove script, style, nav, header, footer elements
- const removeSelectors = 'script, style, nav, header, footer, .nav, .header, .footer, .sidebar, .menu, .ad, .advertisement, [role="navigation"], [role="banner"]'
- doc.querySelectorAll(removeSelectors).forEach(el => el.remove())
-
- // Try to find main content area
- const main = doc.querySelector('main, article, [role="main"], .content, .article, .post, #content, #main')
- const target = main || doc.body
-
- if (!target) return ''
-
- // Get text content with basic formatting
- let text = ''
- const walker = document.createTreeWalker(target, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT)
- let node: Node | null = walker.nextNode()
-
- while (node) {
- if (node.nodeType === Node.TEXT_NODE) {
- const t = node.textContent?.trim()
- if (t) text += t + ' '
- } else if (node.nodeType === Node.ELEMENT_NODE) {
- const tag = (node as Element).tagName.toLowerCase()
- if (['p', 'div', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'tr'].includes(tag)) {
- text += '\n'
- }
- if (['h1', 'h2', 'h3'].includes(tag)) {
- text += '# '
- }
- }
- node = walker.nextNode()
- }
-
- // Clean up whitespace
- return text
- .replace(/\n{3,}/g, '\n\n')
- .replace(/ {2,}/g, ' ')
- .trim()
- }
-
- // Fallback: simple regex-based HTML stripping
- return html
- .replace(/<script[\s\S]*?<\/script>/gi, '')
- .replace(/<style[\s\S]*?<\/style>/gi, '')
- .replace(/<[^>]+>/g, ' ')
- .replace(/&amp;/g, '&')
- .replace(/&lt;/g, '<')
- .replace(/&gt;/g, '>')
- .replace(/&quot;/g, '"')
- .replace(/&#39;/g, "'")
- .replace(/&nbsp;/g, ' ')
- .replace(/\s{2,}/g, ' ')
- .trim()
-}
-
-// ── run_workflow: Execute a workflow by name ────────────────────
-
-let _workflowDepth = 0
-
-async function executeRunWorkflow(workflowName: string, input?: string): Promise<string> {
- if (!workflowName) return 'Error: No workflow name provided'
-
- if (_workflowDepth >= 5) {
- return 'Error: Maximum workflow nesting depth (5) exceeded'
- }
-
- const store = useAgentWorkflowStore.getState()
- const workflow = store.workflows.find(
- w => w.name.toLowerCase() === workflowName.toLowerCase()
- )
-
- if (!workflow) {
- const available = store.workflows.map(w => w.name).join(', ')
- return `Error: Workflow "${workflowName}" not found. Available: ${available}`
- }
-
- // Run the workflow with a simple callback collector
- const results: StepResult[] = []
- let finalOutput = ''
-
- const callbacks = {
- onStepStart: () => {},
- onStepComplete: (_idx: number, result: StepResult) => { results.push(result) },
- onStepError: () => {},
- onWaitingForInput: () => {},
- onComplete: () => {
- const lastOutput = results.filter(r => r.output).pop()
- finalOutput = lastOutput?.output || 'Workflow completed with no output.'
- },
- onError: (error: string) => { finalOutput = `Workflow error: ${error}` },
- }
-
- const initialVars = input ? { user_input: input, last_output: input } : {}
- _workflowDepth++
- try {
- const engine = new WorkflowEngine(workflow, 'tool-execution', callbacks, initialVars, _workflowDepth)
- await engine.run()
- } finally {
- _workflowDepth--
- }
- return finalOutput
+ return toolRegistry.execute(name, args)
}
diff --git a/src/components/chat/AgentModeToggle.tsx b/src/components/chat/AgentModeToggle.tsx
index 3fc845b9..e3e2079d 100644
--- a/src/components/chat/AgentModeToggle.tsx
+++ b/src/components/chat/AgentModeToggle.tsx
@@ -1,40 +1,80 @@
import { useState } from 'react'
+import { motion } from 'framer-motion'
+import { MessageSquarePlus } from 'lucide-react'
import { ToggleSwitch } from '../ui/ToggleSwitch'
+import { Modal } from '../ui/Modal'
import { useAgentModeStore } from '../../stores/agentModeStore'
import { useChatStore } from '../../stores/chatStore'
import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
import { isAgentCompatible } from '../../lib/model-compatibility'
import { FEATURE_FLAGS } from '../../lib/constants'
import { AgentTutorial } from './AgentTutorial'
export function AgentModeToggle() {
const [showTutorial, setShowTutorial] = useState(false)
+ const [showNewChatModal, setShowNewChatModal] = useState(false)
+ const [neverShowChecked, setNeverShowChecked] = useState(false)
const activeConversationId = useChatStore((s) => s.activeConversationId)
+ const conversations = useChatStore((s) => s.conversations)
+ const createConversation = useChatStore((s) => s.createConversation)
const activeModel = useModelStore((s) => s.activeModel)
- const { agentModeActive, toggleAgentMode, tutorialCompleted } = useAgentModeStore()
+ const { agentModeActive, toggleAgentMode, tutorialCompleted, newChatHintDismissed } = useAgentModeStore()
if (!FEATURE_FLAGS.AGENT_MODE || !activeConversationId) return null
const isActive = agentModeActive[activeConversationId] ?? false
const isCompatible = activeModel ? isAgentCompatible(activeModel) : false
+ const conversation = conversations.find((c) => c.id === activeConversationId)
+ const hasMessages = (conversation?.messages?.length ?? 0) > 0
+
+ const createNewAgentChat = () => {
+ if (!activeModel) return
+ const persona = useSettingsStore.getState().getActivePersona()
+ const newId = createConversation(activeModel, persona?.systemPrompt || '')
+ if (!tutorialCompleted) {
+ useAgentModeStore.getState().setTutorialCompleted()
+ }
+ useAgentModeStore.getState().toggleAgentMode(newId)
+ }
+
const handleToggle = () => {
if (!isCompatible) return
+
+ // Chat has messages and agent is off → redirect
+ if (hasMessages && !isActive) {
+ // "Never show again" was checked previously → skip modal, just create
+ if (newChatHintDismissed) {
+ createNewAgentChat()
+ return
+ }
+ setShowNewChatModal(true)
+ return
+ }
+
+ // First time → show tutorial
if (!isActive && !tutorialCompleted) {
setShowTutorial(true)
return
}
- if (activeConversationId) {
- toggleAgentMode(activeConversationId)
- }
+
+ toggleAgentMode(activeConversationId)
}
const handleTutorialComplete = () => {
setShowTutorial(false)
useAgentModeStore.getState().setTutorialCompleted()
- if (activeConversationId) {
- toggleAgentMode(activeConversationId)
+ toggleAgentMode(activeConversationId)
+ }
+
+ const handleNewAgentChat = () => {
+ if (neverShowChecked) {
+ useAgentModeStore.getState().setNewChatHintDismissed(true)
}
+ createNewAgentChat()
+ setShowNewChatModal(false)
+ setNeverShowChecked(false)
}
return (
@@ -46,6 +86,61 @@ export function AgentModeToggle() {
size="sm"
/>
+ {/* New Chat Required Modal */}
+ <Modal open={showNewChatModal} onClose={() => { setShowNewChatModal(false); setNeverShowChecked(false) }} title="">
+ <div className="space-y-4">
+ <motion.div
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.2 }}
+ className="text-center space-y-3"
+ >
+ <div className="flex justify-center">
+ <div
+ className="w-3 h-3 rounded-full bg-amber-500 shadow-lg"
+ style={{ boxShadow: '0 0 20px 4px rgba(245, 158, 11, 0.4)' }}
+ />
+ </div>
+
+ <h3 className="text-base font-semibold text-white">New Chat Required</h3>
+ <p className="text-[0.75rem] text-gray-400 leading-relaxed">
+ Agent Mode needs to be active from the start of a conversation to work properly. Start a new chat with Agent Mode enabled.
+ </p>
+ </motion.div>
+
+ {/* Never show again */}
+ <label className="flex items-center justify-center gap-2 cursor-pointer group">
+ <input
+ type="checkbox"
+ checked={neverShowChecked}
+ onChange={(e) => setNeverShowChecked(e.target.checked)}
+ className="w-3.5 h-3.5 rounded border-white/20 bg-white/5 text-green-500 focus:ring-green-500/30 focus:ring-offset-0 cursor-pointer"
+ />
+ <span className="text-[0.65rem] text-gray-500 group-hover:text-gray-400 transition-colors select-none">
+ Don't show this again
+ </span>
+ </label>
+
+ {/* Actions */}
+ <div className="flex items-center justify-between pt-1">
+ <button
+ onClick={() => { setShowNewChatModal(false); setNeverShowChecked(false) }}
+ className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-[0.7rem] text-gray-400 hover:text-white hover:bg-white/10 transition-colors"
+ >
+ Cancel
+ </button>
+
+ <button
+ onClick={handleNewAgentChat}
+ className="flex items-center gap-1.5 px-4 py-1.5 rounded-lg text-[0.7rem] font-medium bg-green-500/15 border border-green-500/30 text-green-300 hover:bg-green-500/25 transition-colors"
+ >
+ <MessageSquarePlus size={14} />
+ New Agent Chat
+ </button>
+ </div>
+ </div>
+ </Modal>
+
{showTutorial && (
<AgentTutorial
open={showTutorial}
diff --git a/src/components/chat/AgentTutorial.tsx b/src/components/chat/AgentTutorial.tsx
index 113b76e9..c4ad1706 100644
--- a/src/components/chat/AgentTutorial.tsx
+++ b/src/components/chat/AgentTutorial.tsx
@@ -120,6 +120,21 @@ export function AgentTutorial({ open, onClose, onComplete }: Props) {
</motion.div>
</AnimatePresence>
+ {/* Don't show again — visible on last step */}
+ {isLast && (
+ <label className="flex items-center justify-center gap-2 cursor-pointer group">
+ <input
+ type="checkbox"
+ checked={true}
+ disabled
+ className="w-3.5 h-3.5 rounded border-white/20 bg-white/5 text-green-500 focus:ring-green-500/30 focus:ring-offset-0 opacity-50"
+ />
+ <span className="text-[0.65rem] text-gray-500 select-none">
+ Don't show this again
+ </span>
+ </label>
+ )}
+
{/* Navigation */}
<div className="flex items-center justify-between pt-2">
<button
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index bb05172b..d59d134e 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -14,12 +14,13 @@ import { ErrorBoundary } from '../ui/ErrorBoundary'
import { useSettingsStore } from '../../stores/settingsStore'
import { FEATURE_FLAGS } from '../../lib/constants'
import { isAgentCompatible } from '../../lib/model-compatibility'
-import { FileText, Bot, User, ChevronDown, Download, GitCompareArrows } from 'lucide-react'
+import { FileText, Bot, User, ChevronDown, Download } from 'lucide-react'
import { TokenCounter } from './TokenCounter'
import { MemoryDebugToggle } from './MemoryDebugPanel'
import { ABCompare } from './ABCompare'
import { useCompareStore } from '../../stores/compareStore'
import { exportConversation } from '../../lib/chat-export'
+import { PermissionOverrideBar } from './PermissionOverrideBar'
export function ChatView() {
const { sendMessage, stopGeneration, isGenerating, isLoadingModel, regenerateMessage, editAndResend, pendingApproval, approveToolCall, rejectToolCall } = useChat()
@@ -44,7 +45,6 @@ export function ChatView() {
activeConversationId ? s.agentModeActive[activeConversationId] ?? false : false
)
const isComparing = useCompareStore((s) => s.isComparing)
- const setComparing = useCompareStore((s) => s.setComparing)
// A/B Compare mode takes over the entire view
if (isComparing) {
@@ -183,16 +183,6 @@ export function ChatView() {
)}
</button>
- {/* A/B Compare */}
- <button
- onClick={() => setComparing(true)}
- className="flex items-center gap-1.5 px-3 py-1 rounded-full border border-gray-300 dark:border-white/15 hover:border-gray-400 dark:hover:border-white/25 text-gray-500 dark:text-gray-400 transition-colors text-xs"
- title="A/B Compare — test two models side by side"
- >
- <GitCompareArrows size={13} />
- <span className="font-medium">A/B</span>
- </button>
-
{/* Agent Mode (Beta) */}
{FEATURE_FLAGS.AGENT_MODE && (
<div className={
@@ -213,6 +203,9 @@ export function ChatView() {
)}
</div>
+ {/* Permission Override Bar — shown when agent mode is active */}
+ {isAgentActive && <PermissionOverrideBar />}
+
<MessageList
isGenerating={isGenerating}
isLoadingModel={isLoadingModel}
diff --git a/src/components/chat/PermissionOverrideBar.tsx b/src/components/chat/PermissionOverrideBar.tsx
new file mode 100644
index 00000000..df2b11d8
--- /dev/null
+++ b/src/components/chat/PermissionOverrideBar.tsx
@@ -0,0 +1,69 @@
+import { usePermissionStore } from '../../stores/permissionStore'
+import { useChatStore } from '../../stores/chatStore'
+import type { ToolCategory, PermissionLevel } from '../../api/mcp/types'
+import { FolderOpen, Terminal, Monitor, Globe, Cpu, Image, GitBranch } from 'lucide-react'
+
+const CATEGORY_META: Record<ToolCategory, { icon: typeof Globe; short: string }> = {
+ web: { icon: Globe, short: 'Web' },
+ system: { icon: Cpu, short: 'Sys' },
+ filesystem: { icon: FolderOpen, short: 'Files' },
+ terminal: { icon: Terminal, short: 'Shell' },
+ desktop: { icon: Monitor, short: 'Screen' },
+ image: { icon: Image, short: 'Image' },
+ workflow: { icon: GitBranch, short: 'Flow' },
+}
+
+const LEVEL_COLORS: Record<PermissionLevel, string> = {
+ blocked: 'bg-red-500/10 border-red-500/30 text-red-400',
+ confirm: 'bg-amber-500/10 border-amber-500/30 text-amber-400',
+ auto: 'bg-green-500/10 border-green-500/30 text-green-400',
+}
+
+const NEXT_LEVEL: Record<PermissionLevel, PermissionLevel> = {
+ blocked: 'confirm',
+ confirm: 'auto',
+ auto: 'blocked',
+}
+
+export function PermissionOverrideBar() {
+ const activeConversationId = useChatStore((s) => s.activeConversationId)
+ const { getEffectivePermissions, setConversationOverride, clearConversationOverrides, conversationOverrides } = usePermissionStore()
+
+ if (!activeConversationId) return null
+
+ const permissions = getEffectivePermissions(activeConversationId)
+ const hasOverrides = !!conversationOverrides[activeConversationId]
+
+ const handleClick = (category: ToolCategory) => {
+ const current = permissions[category]
+ setConversationOverride(activeConversationId, category, NEXT_LEVEL[current])
+ }
+
+ return (
+ <div className="flex items-center gap-1 px-2 py-0.5 flex-wrap">
+ {(Object.keys(CATEGORY_META) as ToolCategory[]).map((cat) => {
+ const { icon: Icon, short } = CATEGORY_META[cat]
+ const level = permissions[cat]
+ return (
+ <button
+ key={cat}
+ onClick={() => handleClick(cat)}
+ className={`flex items-center gap-1 px-1.5 py-0.5 rounded border text-[0.5rem] font-medium transition-all ${LEVEL_COLORS[level]}`}
+ title={`${short}: ${level} — click to cycle`}
+ >
+ <Icon size={9} />
+ <span>{short}</span>
+ </button>
+ )
+ })}
+ {hasOverrides && (
+ <button
+ onClick={() => clearConversationOverrides(activeConversationId)}
+ className="text-[0.5rem] text-gray-600 hover:text-gray-400 transition-colors ml-1"
+ >
+ reset
+ </button>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
index e8219fce..5a11ed5d 100644
--- a/src/components/chat/ToolCallBlock.tsx
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { ChevronDown, Search, Globe, FileText, FileEdit, Terminal, Image, Loader2, Check, X, Clock, AlertCircle } from 'lucide-react'
+import { ChevronDown, Search, Globe, FileText, FileEdit, Terminal, Image, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch } from 'lucide-react'
import type { AgentToolCall } from '../../types/agent-mode'
interface Props {
@@ -14,8 +14,15 @@ const TOOL_ICONS: Record<string, typeof Search> = {
web_fetch: Globe,
file_read: FileText,
file_write: FileEdit,
+ file_list: FolderOpen,
+ file_search: Search,
code_execute: Terminal,
+ shell_execute: Terminal,
+ system_info: Cpu,
+ process_list: Cpu,
+ screenshot: Monitor,
image_generate: Image,
+ run_workflow: GitBranch,
}
const TOOL_COLORS: Record<string, string> = {
@@ -23,8 +30,15 @@ const TOOL_COLORS: Record<string, string> = {
web_fetch: 'text-cyan-400',
file_read: 'text-gray-400',
file_write: 'text-amber-400',
+ file_list: 'text-gray-400',
+ file_search: 'text-gray-400',
code_execute: 'text-green-400',
+ shell_execute: 'text-green-400',
+ system_info: 'text-purple-400',
+ process_list: 'text-purple-400',
+ screenshot: 'text-pink-400',
image_generate: 'text-purple-400',
+ run_workflow: 'text-amber-400',
}
const STATUS_ICONS = {
@@ -46,7 +60,7 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
return (
<div className="mb-1">
- {/* Inline tool call line — no box, just text */}
+ {/* Inline tool call line */}
<button
onClick={() => setOpen(!open)}
className="flex items-center gap-1.5 py-0.5 text-left hover:opacity-80 transition-opacity w-full"
@@ -83,14 +97,14 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
>
<div className="pl-5 pb-2 space-y-1.5">
{/* Arguments */}
- <pre className="text-[0.62rem] leading-relaxed text-gray-500 bg-black/[0.02] dark:bg-white/[0.02] rounded px-2 py-1 overflow-x-auto">
+ <pre className="text-[0.62rem] leading-relaxed text-gray-500 bg-black/[0.02] dark:bg-white/[0.02] rounded px-2 py-1 overflow-x-auto scrollbar-thin">
{JSON.stringify(toolCall.args, null, 2)}
</pre>
- {/* Result */}
+ {/* Result — full content, scrollable */}
{toolCall.result && (
- <pre className="text-[0.62rem] leading-relaxed text-gray-400 bg-black/[0.02] dark:bg-white/[0.02] rounded px-2 py-1 overflow-x-auto max-h-[150px]">
- {toolCall.result.length > 500 ? toolCall.result.slice(0, 500) + '\n...' : toolCall.result}
+ <pre className="text-[0.62rem] leading-relaxed text-gray-400 bg-black/[0.02] dark:bg-white/[0.02] rounded px-2 py-1 overflow-auto scrollbar-thin max-h-[300px]">
+ {toolCall.result}
</pre>
)}
diff --git a/src/components/settings/MCPServerSettings.tsx b/src/components/settings/MCPServerSettings.tsx
new file mode 100644
index 00000000..c4a603b2
--- /dev/null
+++ b/src/components/settings/MCPServerSettings.tsx
@@ -0,0 +1,221 @@
+import { useState } from 'react'
+import { v4 as uuid } from 'uuid'
+import { Plus, Trash2, Power, PowerOff, ChevronDown } from 'lucide-react'
+import { useMCPStore } from '../../stores/mcpStore'
+import { toolRegistry } from '../../api/mcp'
+import type { MCPServerConfig } from '../../api/mcp/types'
+
+// Active client instances (lazy-loaded to avoid Tauri import in dev mode)
+const clients = new Map<string, any>()
+
+export function MCPServerSettings() {
+ const { servers, connectedServers, serverTools, addServer, removeServer, setConnected, setServerTools, clearServerTools } = useMCPStore()
+ const [showAddForm, setShowAddForm] = useState(false)
+ const [connecting, setConnecting] = useState<string | null>(null)
+ const [error, setError] = useState<string | null>(null)
+
+ // Add form state
+ const [formName, setFormName] = useState('')
+ const [formCommand, setFormCommand] = useState('')
+ const [formArgs, setFormArgs] = useState('')
+
+ const handleAdd = () => {
+ if (!formName.trim() || !formCommand.trim()) return
+ const server: MCPServerConfig = {
+ id: uuid(),
+ name: formName.trim(),
+ command: formCommand.trim(),
+ args: formArgs.trim() ? formArgs.trim().split(' ') : [],
+ enabled: true,
+ }
+ addServer(server)
+ setFormName('')
+ setFormCommand('')
+ setFormArgs('')
+ setShowAddForm(false)
+ }
+
+ const handleConnect = async (server: MCPServerConfig) => {
+ setConnecting(server.id)
+ setError(null)
+ try {
+ const { MCPExternalClient } = await import('../../api/mcp/external-client')
+ const client = new MCPExternalClient(server)
+ const tools = await client.connect()
+ clients.set(server.id, client)
+ setConnected(server.id, true)
+ setServerTools(server.id, tools)
+ // Register tools with the global registry
+ toolRegistry.registerExternal(
+ server.id,
+ tools,
+ async (args) => {
+ const toolName = args.__toolName || ''
+ delete args.__toolName
+ return client.callTool(toolName, args)
+ }
+ )
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err))
+ } finally {
+ setConnecting(null)
+ }
+ }
+
+ const handleDisconnect = async (id: string) => {
+ const client = clients.get(id)
+ if (client) {
+ await client.disconnect()
+ clients.delete(id)
+ }
+ toolRegistry.unregisterServer(id)
+ setConnected(id, false)
+ clearServerTools(id)
+ }
+
+ const handleRemove = async (id: string) => {
+ await handleDisconnect(id)
+ removeServer(id)
+ }
+
+ return (
+ <div className="space-y-3">
+ <p className="text-[0.6rem] text-gray-500">
+ Connect external MCP servers to extend Agent capabilities with community tools.
+ </p>
+
+ {/* Server List */}
+ {servers.map((server) => {
+ const isConnected = connectedServers.includes(server.id)
+ const tools = serverTools[server.id] || []
+ const isLoading = connecting === server.id
+
+ return (
+ <div
+ key={server.id}
+ className={`px-3 py-2 rounded-lg border transition-colors ${
+ isConnected
+ ? 'bg-green-500/[0.03] border-green-500/20'
+ : 'bg-white/[0.02] border-white/[0.06]'
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ {/* Status dot */}
+ <div className={`w-1.5 h-1.5 rounded-full shrink-0 ${
+ isConnected ? 'bg-green-500' : 'bg-gray-600'
+ }`} />
+
+ {/* Name + command */}
+ <div className="flex-1 min-w-0">
+ <p className="text-[0.7rem] text-gray-300 font-medium">{server.name}</p>
+ <p className="text-[0.55rem] text-gray-600 font-mono truncate">
+ {server.command} {server.args.join(' ')}
+ </p>
+ </div>
+
+ {/* Tools count */}
+ {isConnected && tools.length > 0 && (
+ <span className="text-[0.55rem] text-green-400 font-medium">
+ {tools.length} tools
+ </span>
+ )}
+
+ {/* Connect/Disconnect */}
+ <button
+ onClick={() => isConnected ? handleDisconnect(server.id) : handleConnect(server)}
+ disabled={isLoading}
+ className={`p-1 rounded transition-colors ${
+ isConnected
+ ? 'text-green-400 hover:text-red-400 hover:bg-red-500/10'
+ : 'text-gray-500 hover:text-green-400 hover:bg-green-500/10'
+ }`}
+ title={isConnected ? 'Disconnect' : 'Connect'}
+ >
+ {isLoading ? (
+ <div className="w-3 h-3 border border-gray-400 border-t-transparent rounded-full animate-spin" />
+ ) : isConnected ? (
+ <PowerOff size={12} />
+ ) : (
+ <Power size={12} />
+ )}
+ </button>
+
+ {/* Remove */}
+ <button
+ onClick={() => handleRemove(server.id)}
+ className="p-1 rounded text-gray-600 hover:text-red-400 hover:bg-red-500/10 transition-colors"
+ title="Remove server"
+ >
+ <Trash2 size={11} />
+ </button>
+ </div>
+
+ {/* Expanded tool list */}
+ {isConnected && tools.length > 0 && (
+ <div className="mt-1.5 pt-1.5 border-t border-white/5 space-y-0.5">
+ {tools.map((t) => (
+ <div key={t.name} className="flex items-center gap-1.5">
+ <span className="text-[0.55rem] text-gray-500 font-mono">{t.name}</span>
+ <span className="text-[0.5rem] text-gray-600 truncate">{t.description}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+ })}
+
+ {/* Error */}
+ {error && (
+ <p className="text-[0.6rem] text-red-400 px-2">{error}</p>
+ )}
+
+ {/* Add Server Form */}
+ {showAddForm ? (
+ <div className="space-y-2 p-3 rounded-lg border border-white/10 bg-white/[0.02]">
+ <input
+ value={formName}
+ onChange={(e) => setFormName(e.target.value)}
+ placeholder="Server name"
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:border-white/20 outline-none"
+ />
+ <input
+ value={formCommand}
+ onChange={(e) => setFormCommand(e.target.value)}
+ placeholder="Command (e.g. npx, python)"
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 font-mono focus:border-white/20 outline-none"
+ />
+ <input
+ value={formArgs}
+ onChange={(e) => setFormArgs(e.target.value)}
+ placeholder="Args (e.g. -y @modelcontextprotocol/server-filesystem /path)"
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 font-mono focus:border-white/20 outline-none"
+ />
+ <div className="flex gap-1.5">
+ <button
+ onClick={handleAdd}
+ disabled={!formName.trim() || !formCommand.trim()}
+ className="px-3 py-1 rounded text-[0.6rem] font-medium bg-green-500/15 border border-green-500/30 text-green-300 hover:bg-green-500/25 disabled:opacity-40 transition-colors"
+ >
+ Add Server
+ </button>
+ <button
+ onClick={() => setShowAddForm(false)}
+ className="px-3 py-1 rounded text-[0.6rem] text-gray-500 hover:text-gray-300 transition-colors"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <button
+ onClick={() => setShowAddForm(true)}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[0.65rem] text-gray-500 hover:text-gray-300 hover:bg-white/5 border border-dashed border-white/10 hover:border-white/20 transition-all w-full justify-center"
+ >
+ <Plus size={12} />
+ Add MCP Server
+ </button>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/settings/PermissionSettings.tsx b/src/components/settings/PermissionSettings.tsx
new file mode 100644
index 00000000..afd6d352
--- /dev/null
+++ b/src/components/settings/PermissionSettings.tsx
@@ -0,0 +1,111 @@
+import { usePermissionStore } from '../../stores/permissionStore'
+import type { ToolCategory, PermissionLevel } from '../../api/mcp/types'
+import { FolderOpen, Terminal, Monitor, Globe, Cpu, Image, GitBranch, Lock } from 'lucide-react'
+
+// Categories that are not yet fully implemented
+const LOCKED_CATEGORIES = new Set<ToolCategory>(['image'])
+
+const CATEGORIES: {
+ key: ToolCategory
+ label: string
+ description: string
+ icon: typeof FolderOpen
+ risk: 'low' | 'medium' | 'high'
+}[] = [
+ { key: 'web', label: 'Web Access', description: 'Search & fetch web pages', icon: Globe, risk: 'low' },
+ { key: 'system', label: 'System Info', description: 'OS info, process list', icon: Cpu, risk: 'low' },
+ { key: 'filesystem', label: 'Filesystem', description: 'Read, write, search files anywhere', icon: FolderOpen, risk: 'medium' },
+ { key: 'image', label: 'Image Generation', description: 'Generate images via ComfyUI', icon: Image, risk: 'medium' },
+ { key: 'workflow', label: 'Workflows', description: 'Execute saved agent workflows', icon: GitBranch, risk: 'medium' },
+ { key: 'terminal', label: 'Terminal / Shell', description: 'Execute commands, run code', icon: Terminal, risk: 'high' },
+ { key: 'desktop', label: 'Desktop Control', description: 'Screenshots, screen interaction', icon: Monitor, risk: 'high' },
+]
+
+const RISK_COLORS = {
+ low: 'bg-green-500',
+ medium: 'bg-amber-500',
+ high: 'bg-red-500',
+}
+
+const LEVEL_OPTIONS: { value: PermissionLevel; label: string }[] = [
+ { value: 'blocked', label: 'Blocked' },
+ { value: 'confirm', label: 'Ask First' },
+ { value: 'auto', label: 'Auto' },
+]
+
+export function PermissionSettings() {
+ const { globalPermissions, setGlobalPermission, resetToDefaults } = usePermissionStore()
+
+ return (
+ <div className="space-y-2">
+ <p className="text-[0.6rem] text-gray-500 mb-3">
+ Control what the Agent can access. Per-category permissions apply to all tools in that category.
+ </p>
+
+ {CATEGORIES.map(({ key, label, description, icon: Icon, risk }) => {
+ const isLocked = LOCKED_CATEGORIES.has(key)
+
+ return (
+ <div
+ key={key}
+ className={`flex items-center gap-3 px-3 py-2 rounded-lg border transition-colors ${
+ isLocked
+ ? 'bg-white/[0.01] border-white/[0.04] opacity-50'
+ : 'bg-white/[0.02] border-white/[0.06] hover:border-white/10'
+ }`}
+ >
+ {/* Risk dot */}
+ <div className={`w-1.5 h-1.5 rounded-full ${RISK_COLORS[risk]} shrink-0`} />
+
+ {/* Icon */}
+ <Icon size={14} className="text-gray-500 shrink-0" />
+
+ {/* Label + Description */}
+ <div className="flex-1 min-w-0">
+ <p className="text-[0.7rem] text-gray-300 font-medium">{label}</p>
+ <p className="text-[0.55rem] text-gray-600 truncate">{description}</p>
+ </div>
+
+ {/* Locked badge or Permission Level Selector */}
+ {isLocked ? (
+ <div className="flex items-center gap-1 shrink-0">
+ <Lock size={10} className="text-gray-600" />
+ <span className="text-[0.55rem] text-gray-600 font-medium">Coming Soon</span>
+ </div>
+ ) : (
+ <div className="flex gap-0.5 shrink-0">
+ {LEVEL_OPTIONS.map(({ value, label: lvlLabel }) => {
+ const isActive = globalPermissions[key] === value
+ return (
+ <button
+ key={value}
+ onClick={() => setGlobalPermission(key, value)}
+ className={`px-2 py-0.5 rounded text-[0.55rem] font-medium transition-all ${
+ isActive
+ ? value === 'blocked'
+ ? 'bg-red-500/15 text-red-400 border border-red-500/30'
+ : value === 'confirm'
+ ? 'bg-amber-500/15 text-amber-400 border border-amber-500/30'
+ : 'bg-green-500/15 text-green-400 border border-green-500/30'
+ : 'text-gray-600 hover:text-gray-400 border border-transparent'
+ }`}
+ >
+ {lvlLabel}
+ </button>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ )
+ })}
+
+ <button
+ onClick={resetToDefaults}
+ className="text-[0.6rem] text-gray-500 hover:text-gray-300 transition-colors mt-2"
+ >
+ Reset to defaults
+ </button>
+ </div>
+ )
+}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 78fb5b04..7bdabbbc 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -9,10 +9,11 @@ import { useVoiceStore } from '../../stores/voiceStore'
import { checkWhisperAvailable } from '../../api/voice'
import { useAgentModeStore } from '../../stores/agentModeStore'
import { FEATURE_FLAGS } from '../../lib/constants'
-import { AGENT_TOOL_DEFS } from '../../api/tool-registry'
import { getRecommendedAgentModels } from '../../lib/model-compatibility'
import { MemorySettings } from './MemorySettings'
import { ProviderSettings } from './ProviderConfig'
+import { PermissionSettings } from './PermissionSettings'
+import { MCPServerSettings } from './MCPServerSettings'
import { WorkflowList } from '../agents/WorkflowList'
import { WorkflowBuilder } from '../agents/WorkflowBuilder'
import { useUpdateStore } from '../../stores/updateStore'
@@ -228,35 +229,9 @@ export function SettingsPage() {
{/* ── Agent Mode ─────────────────────────────── */}
{FEATURE_FLAGS.AGENT_MODE && (
- <Section title="Agent Mode (Beta)">
- <div className="flex items-center justify-between">
- <span className="text-[0.7rem] text-gray-500">Sandbox</span>
- <div className="flex gap-1">
- {(['restricted', 'full'] as const).map(level => (
- <button
- key={level}
- onClick={() => useAgentModeStore.getState().setSandboxLevel(level)}
- className={`px-2 py-0.5 rounded text-[0.6rem] transition-colors ${
- useAgentModeStore.getState().sandboxLevel === level ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300'
- }`}
- >
- {level === 'restricted' ? 'Restricted' : 'Full Access'}
- </button>
- ))}
- </div>
- </div>
- <div className="space-y-0.5">
- <span className="text-[0.6rem] text-gray-500">Tools</span>
- {AGENT_TOOL_DEFS.map((tool) => (
- <div key={tool.name} className="flex items-center justify-between py-0.5">
- <span className="text-[0.65rem] text-gray-400 font-mono">{tool.name}</span>
- <span className={`text-[0.55rem] ${tool.permission === 'auto' ? 'text-green-500' : 'text-amber-400'}`}>
- {tool.permission === 'auto' ? 'auto' : 'approval'}
- </span>
- </div>
- ))}
- </div>
- <div className="space-y-0.5">
+ <Section title="Agent Permissions">
+ <PermissionSettings />
+ <div className="space-y-0.5 mt-3 pt-3 border-t border-white/5">
<span className="text-[0.6rem] text-gray-500">Recommended Models</span>
{getRecommendedAgentModels().map((m) => (
<div key={m.name} className="flex items-center gap-1.5 py-0.5">
@@ -282,6 +257,13 @@ export function SettingsPage() {
</Section>
)}
+ {/* ── MCP Servers ─────────────────────────────── */}
+ {FEATURE_FLAGS.AGENT_MODE && (
+ <Section title="MCP Servers">
+ <MCPServerSettings />
+ </Section>
+ )}
+
{/* ── Search Provider ────────────────────────── */}
{FEATURE_FLAGS.AGENT_MODE && (
<Section title="Search Provider">
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index c6ba8b76..3c87389d 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -9,7 +9,10 @@ import { useRAGStore } from '../stores/ragStore'
import { useVoiceStore } from '../stores/voiceStore'
import { retrieveContext } from '../api/rag'
import { speakStreaming, isSpeechSynthesisSupported, getVoicesAsync } from '../api/voice'
-import { getOllamaTools, getToolPermission, executeAgentTool, AGENT_TOOL_DEFS } from '../api/tool-registry'
+import { toolRegistry } from '../api/mcp'
+import { usePermissionStore } from '../stores/permissionStore'
+// Legacy compat imports (still used by some callers)
+import { getToolPermission, executeAgentTool, AGENT_TOOL_DEFS } from '../api/tool-registry'
import { getToolCallingStrategy, type ToolCallingStrategy } from '../lib/model-compatibility'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'
@@ -269,9 +272,13 @@ export function useAgentChat() {
// Memory injection is non-critical
}
+ // Get effective permissions for this conversation
+ const permissions = usePermissionStore.getState().getEffectivePermissions(convId!)
+
// Build agent system prompt
+ const hermesToolDefs = toolRegistry.toHermesToolDefs(permissions)
const agentSystemPrompt = strategy === 'hermes_xml'
- ? buildHermesToolPrompt(AGENT_TOOL_DEFS) + (systemPrompt ? `\n\n${systemPrompt}` : '')
+ ? buildHermesToolPrompt(hermesToolDefs) + (systemPrompt ? `\n\n${systemPrompt}` : '')
: buildAgentSystemPrompt(systemPrompt)
// Build messages array
@@ -332,7 +339,7 @@ export function useAgentChat() {
if (strategy === 'native') {
// ── Native tool calling (works with Ollama, OpenAI, Anthropic) ──
- const tools: ToolDefinition[] = getOllamaTools()
+ const tools: ToolDefinition[] = toolRegistry.toOpenAITools(permissions)
const turn = await provider.chatWithTools(modelToUse, agentMessages, tools, chatOptions)
toolCalls = turn.toolCalls
@@ -383,8 +390,9 @@ export function useAgentChat() {
timestamp: Date.now(),
}
- // Check permission
- const permission = getToolPermission(tc.function.name)
+ // Check permission via new registry
+ const permLevel = toolRegistry.getPermissionLevel(tc.function.name, permissions)
+ const permission = permLevel === 'auto' ? 'auto' : 'confirm'
if (permission === 'confirm') {
agentToolCall.status = 'pending_approval'
@@ -449,7 +457,7 @@ export function useAgentChat() {
// Execute the tool
const startTime = Date.now()
- const result = await executeAgentTool(tc.function.name, tc.function.arguments)
+ const result = await toolRegistry.execute(tc.function.name, tc.function.arguments)
const duration = Date.now() - startTime
// Update block with result
diff --git a/src/lib/model-compatibility.ts b/src/lib/model-compatibility.ts
index b1b59b9b..1c2e1a7e 100644
--- a/src/lib/model-compatibility.ts
+++ b/src/lib/model-compatibility.ts
@@ -76,13 +76,16 @@ export interface RecommendedModel {
export function getRecommendedAgentModels(): RecommendedModel[] {
return [
- { name: 'hermes3:8b', label: 'Hermes 3 8B', reason: 'Uncensored + native tool calling. THE agent model.', hot: true, provider: 'ollama' },
- { name: 'hermes3:70b', label: 'Hermes 3 70B', reason: 'Maximum power uncensored agent. Needs 48GB+.', hot: true, provider: 'ollama' },
+ // Local — HOT picks
+ { name: 'qwen3.5:35b-a3b', label: 'Qwen 3.5 35B MoE', reason: '35B brain, 3B active. Best agentic + 256K context. SWE-bench leader.', hot: true, provider: 'ollama' },
{ name: 'gemma4:26b', label: 'Gemma 4 26B MoE', reason: '26B brain, runs like 4B. Native tools + vision. Apache 2.0.', hot: true, provider: 'ollama' },
- { name: 'qwen3-coder:30b', label: 'Qwen3-Coder 30B MoE', reason: '30B brain, 3B active. Built for code + agentic workflows. 256K context.', hot: true, provider: 'ollama' },
- { name: 'qwen2.5:7b', label: 'Qwen 2.5 7B', reason: 'Fast, reliable tool calling', provider: 'ollama' },
- { name: 'llama3.1:8b', label: 'Llama 3.1 8B', reason: 'Proven tool calling all-rounder', provider: 'ollama' },
- { name: 'openai::gpt-4o', label: 'GPT-4o', reason: 'Cloud: powerful tool calling', provider: 'openai' },
- { name: 'anthropic::claude-sonnet-4-20250514', label: 'Claude Sonnet 4', reason: 'Cloud: fast + smart', provider: 'anthropic' },
+ { name: 'qwen3-coder:30b', label: 'Qwen3-Coder 30B MoE', reason: 'Built for code + agentic workflows. 256K context.', hot: true, provider: 'ollama' },
+ { name: 'hermes3:8b', label: 'Hermes 3 8B', reason: 'Uncensored + native tool calling. Best small agent.', hot: true, provider: 'ollama' },
+ // Local — solid picks
+ { name: 'deepseek-v3.2', label: 'DeepSeek V3.2', reason: 'Frontier reasoning + tool use. Open-source.', provider: 'ollama' },
+ { name: 'glm4.7', label: 'GLM 4.7', reason: 'Strong coding, reasoning, agentic execution.', provider: 'ollama' },
+ // Cloud
+ { name: 'anthropic::claude-opus-4-20250514', label: 'Claude Opus 4', reason: 'Cloud: most capable agent model.', provider: 'anthropic' },
+ { name: 'anthropic::claude-sonnet-4-20250514', label: 'Claude Sonnet 4', reason: 'Cloud: fast + smart tool calling.', provider: 'anthropic' },
]
}
diff --git a/src/stores/agentModeStore.ts b/src/stores/agentModeStore.ts
index 2ca5d4cb..1813e488 100644
--- a/src/stores/agentModeStore.ts
+++ b/src/stores/agentModeStore.ts
@@ -9,12 +9,14 @@ interface AgentModeState {
// Settings
sandboxLevel: SandboxLevel
tutorialCompleted: boolean
+ newChatHintDismissed: boolean
// Actions
toggleAgentMode: (conversationId: string) => void
setAgentModeActive: (conversationId: string, active: boolean) => void
setSandboxLevel: (level: SandboxLevel) => void
setTutorialCompleted: () => void
+ setNewChatHintDismissed: (dismissed: boolean) => void
isActive: (conversationId: string) => boolean
}
@@ -24,6 +26,7 @@ export const useAgentModeStore = create<AgentModeState>()(
agentModeActive: {},
sandboxLevel: 'restricted',
tutorialCompleted: false,
+ newChatHintDismissed: false,
toggleAgentMode: (conversationId) =>
set((state) => ({
@@ -45,6 +48,8 @@ export const useAgentModeStore = create<AgentModeState>()(
setTutorialCompleted: () => set({ tutorialCompleted: true }),
+ setNewChatHintDismissed: (dismissed) => set({ newChatHintDismissed: dismissed }),
+
isActive: (conversationId) => {
return get().agentModeActive[conversationId] ?? false
},
diff --git a/src/stores/mcpStore.ts b/src/stores/mcpStore.ts
new file mode 100644
index 00000000..2cf092a1
--- /dev/null
+++ b/src/stores/mcpStore.ts
@@ -0,0 +1,68 @@
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import type { MCPServerConfig, MCPToolDefinition } from '../api/mcp/types'
+
+interface MCPState {
+ servers: MCPServerConfig[]
+ connectedServers: string[]
+ serverTools: Record<string, MCPToolDefinition[]>
+
+ // CRUD
+ addServer: (server: MCPServerConfig) => void
+ updateServer: (id: string, updates: Partial<MCPServerConfig>) => void
+ removeServer: (id: string) => void
+
+ // Connection state
+ setConnected: (id: string, connected: boolean) => void
+ setServerTools: (id: string, tools: MCPToolDefinition[]) => void
+ clearServerTools: (id: string) => void
+}
+
+export const useMCPStore = create<MCPState>()(
+ persist(
+ (set) => ({
+ servers: [],
+ connectedServers: [],
+ serverTools: {},
+
+ addServer: (server) =>
+ set((state) => ({ servers: [...state.servers, server] })),
+
+ updateServer: (id, updates) =>
+ set((state) => ({
+ servers: state.servers.map((s) => (s.id === id ? { ...s, ...updates } : s)),
+ })),
+
+ removeServer: (id) =>
+ set((state) => ({
+ servers: state.servers.filter((s) => s.id !== id),
+ connectedServers: state.connectedServers.filter((s) => s !== id),
+ serverTools: Object.fromEntries(
+ Object.entries(state.serverTools).filter(([k]) => k !== id)
+ ),
+ })),
+
+ setConnected: (id, connected) =>
+ set((state) => ({
+ connectedServers: connected
+ ? [...state.connectedServers.filter((s) => s !== id), id]
+ : state.connectedServers.filter((s) => s !== id),
+ })),
+
+ setServerTools: (id, tools) =>
+ set((state) => ({ serverTools: { ...state.serverTools, [id]: tools } })),
+
+ clearServerTools: (id) =>
+ set((state) => {
+ const { [id]: _, ...rest } = state.serverTools
+ return { serverTools: rest }
+ }),
+ }),
+ {
+ name: 'locally-uncensored-mcp-servers',
+ partialize: (state) => ({
+ servers: state.servers,
+ }),
+ }
+ )
+)
diff --git a/src/stores/permissionStore.ts b/src/stores/permissionStore.ts
new file mode 100644
index 00000000..9bdd3985
--- /dev/null
+++ b/src/stores/permissionStore.ts
@@ -0,0 +1,61 @@
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import type { PermissionMap, PermissionLevel, ToolCategory } from '../api/mcp/types'
+import { DEFAULT_PERMISSIONS } from '../api/mcp/types'
+
+interface PermissionState {
+ globalPermissions: PermissionMap
+ conversationOverrides: Record<string, Partial<PermissionMap>>
+
+ // Getters
+ getEffectivePermissions: (conversationId?: string) => PermissionMap
+
+ // Setters
+ setGlobalPermission: (category: ToolCategory, level: PermissionLevel) => void
+ setConversationOverride: (convId: string, category: ToolCategory, level: PermissionLevel) => void
+ clearConversationOverrides: (convId: string) => void
+ resetToDefaults: () => void
+}
+
+export const usePermissionStore = create<PermissionState>()(
+ persist(
+ (set, get) => ({
+ globalPermissions: { ...DEFAULT_PERMISSIONS },
+ conversationOverrides: {},
+
+ getEffectivePermissions: (conversationId?) => {
+ const global = get().globalPermissions
+ if (!conversationId) return global
+ const overrides = get().conversationOverrides[conversationId]
+ if (!overrides) return global
+ return { ...global, ...overrides }
+ },
+
+ setGlobalPermission: (category, level) =>
+ set((state) => ({
+ globalPermissions: { ...state.globalPermissions, [category]: level },
+ })),
+
+ setConversationOverride: (convId, category, level) =>
+ set((state) => ({
+ conversationOverrides: {
+ ...state.conversationOverrides,
+ [convId]: {
+ ...(state.conversationOverrides[convId] || {}),
+ [category]: level,
+ },
+ },
+ })),
+
+ clearConversationOverrides: (convId) =>
+ set((state) => {
+ const { [convId]: _, ...rest } = state.conversationOverrides
+ return { conversationOverrides: rest }
+ }),
+
+ resetToDefaults: () =>
+ set({ globalPermissions: { ...DEFAULT_PERMISSIONS }, conversationOverrides: {} }),
+ }),
+ { name: 'locally-uncensored-permissions' }
+ )
+)
diff --git a/vite.config.ts b/vite.config.ts
index f639a9f7..d71dafbe 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -814,6 +814,243 @@ function comfyLauncher(): Plugin {
})
})
+ // --- New Agent Tool Endpoints (Phase 1) ---
+
+ // API: Shell execute
+ server.middlewares.use('/local-api/shell-execute', (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
+ let body = ''
+ req.on('data', (c: any) => { body += c })
+ req.on('end', () => {
+ try {
+ const { command, cwd, timeout: timeoutMs, shell: shellType } = JSON.parse(body)
+ if (!command) {
+ res.writeHead(400, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Missing command' }))
+ return
+ }
+
+ const shellBin = shellType || (process.platform === 'win32' ? 'powershell' : 'bash')
+ const shellArgs: string[] = []
+ if (shellBin.includes('powershell')) {
+ shellArgs.push('-NoProfile', '-NonInteractive', '-Command', command)
+ } else if (shellBin.includes('cmd')) {
+ shellArgs.push('/C', command)
+ } else {
+ shellArgs.push('-c', command)
+ }
+
+ const limit = timeoutMs || 120000
+ let stdout = ''
+ let stderr = ''
+ let killed = false
+
+ const proc = spawn(shellBin, shellArgs, {
+ cwd: cwd || undefined,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ shell: false,
+ })
+
+ const timer = setTimeout(() => {
+ killed = true
+ try { proc.kill('SIGKILL') } catch { /* dead */ }
+ }, limit)
+
+ proc.stdout?.on('data', (d: Buffer) => { stdout += d.toString() })
+ proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString() })
+
+ proc.on('exit', (exitCode) => {
+ clearTimeout(timer)
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({
+ stdout, stderr,
+ exitCode: killed ? -1 : (exitCode ?? 1),
+ timedOut: killed,
+ }))
+ })
+
+ proc.on('error', (err: Error) => {
+ clearTimeout(timer)
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ stdout: '', stderr: err.message, exitCode: 1, timedOut: false }))
+ })
+ } catch (err) {
+ res.writeHead(400, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: String(err) }))
+ }
+ })
+ })
+
+ // API: FS read (unsandboxed)
+ server.middlewares.use('/local-api/fs-read', (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
+ let body = ''
+ req.on('data', (c: any) => { body += c })
+ req.on('end', () => {
+ try {
+ const { path: filePath } = JSON.parse(body)
+ const os = require('os')
+ const fs = require('fs')
+ const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), 'agent-workspace', filePath)
+ const content = fs.readFileSync(resolved, 'utf8')
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ content, encoding: 'utf8' }))
+ } catch (err) {
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: String(err) }))
+ }
+ })
+ })
+
+ // API: FS write (unsandboxed)
+ server.middlewares.use('/local-api/fs-write', (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
+ let body = ''
+ req.on('data', (c: any) => { body += c })
+ req.on('end', () => {
+ try {
+ const { path: filePath, content } = JSON.parse(body)
+ const os = require('os')
+ const fs = require('fs')
+ const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), 'agent-workspace', filePath)
+ const parentDir = resolve(resolved, '..')
+ if (!existsSync(parentDir)) mkdirSync(parentDir, { recursive: true })
+ fs.writeFileSync(resolved, content, 'utf8')
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ status: 'saved', path: resolved }))
+ } catch (err) {
+ res.writeHead(400, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: String(err) }))
+ }
+ })
+ })
+
+ // API: FS list
+ server.middlewares.use('/local-api/fs-list', (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
+ let body = ''
+ req.on('data', (c: any) => { body += c })
+ req.on('end', () => {
+ try {
+ const { path: dirPath, recursive } = JSON.parse(body)
+ const os = require('os')
+ const fs = require('fs')
+ const resolved = require('path').isAbsolute(dirPath) ? dirPath : join(os.homedir(), 'agent-workspace', dirPath)
+ const entries: any[] = []
+ const items = fs.readdirSync(resolved, { withFileTypes: true })
+ for (const item of items.slice(0, 500)) {
+ const fullPath = join(resolved, item.name)
+ try {
+ const stat = fs.statSync(fullPath)
+ entries.push({ name: item.name, path: fullPath, size: stat.size, isDir: item.isDirectory(), modified: Math.floor(stat.mtimeMs / 1000) })
+ } catch { /* skip */ }
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ entries, count: entries.length }))
+ } catch (err) {
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ entries: [], count: 0, error: String(err) }))
+ }
+ })
+ })
+
+ // API: FS search (grep-like)
+ server.middlewares.use('/local-api/fs-search', (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
+ let body = ''
+ req.on('data', (c: any) => { body += c })
+ req.on('end', () => {
+ try {
+ const { path: dirPath, pattern, max_results } = JSON.parse(body)
+ const os = require('os')
+ const fs = require('fs')
+ const resolved = require('path').isAbsolute(dirPath) ? dirPath : join(os.homedir(), 'agent-workspace', dirPath)
+ const re = new RegExp(pattern)
+ const results: any[] = []
+ const max = max_results || 50
+
+ function walkDir(dir: string, depth: number) {
+ if (depth > 5 || results.length >= max) return
+ try {
+ for (const item of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = join(dir, item.name)
+ if (item.isDirectory() && !item.name.startsWith('.') && item.name !== 'node_modules') {
+ walkDir(full, depth + 1)
+ } else if (item.isFile()) {
+ try {
+ const stat = fs.statSync(full)
+ if (stat.size > 1000000) continue
+ const content = fs.readFileSync(full, 'utf8')
+ const matches: any[] = []
+ content.split('\n').forEach((line: string, i: number) => {
+ if (re.test(line) && matches.length < 10) {
+ matches.push({ line: i + 1, text: line.slice(0, 200) })
+ }
+ })
+ if (matches.length > 0) results.push({ file: full, matches })
+ } catch { /* skip binary */ }
+ }
+ }
+ } catch { /* permission denied */ }
+ }
+ walkDir(resolved, 0)
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ results, count: results.length }))
+ } catch (err) {
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ results: [], count: 0, error: String(err) }))
+ }
+ })
+ })
+
+ // API: FS info
+ server.middlewares.use('/local-api/fs-info', (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
+ let body = ''
+ req.on('data', (c: any) => { body += c })
+ req.on('end', () => {
+ try {
+ const { path: filePath } = JSON.parse(body)
+ const os = require('os')
+ const fs = require('fs')
+ const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), 'agent-workspace', filePath)
+ const stat = fs.statSync(resolved)
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({
+ path: resolved, size: stat.size, isDir: stat.isDirectory(), isFile: stat.isFile(),
+ modified: Math.floor(stat.mtimeMs / 1000), created: Math.floor(stat.birthtimeMs / 1000),
+ readonly: false,
+ }))
+ } catch (err) {
+ res.writeHead(400, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: String(err) }))
+ }
+ })
+ })
+
+ // API: System info
+ server.middlewares.use('/local-api/system-info', (_req, res) => {
+ const os = require('os')
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({
+ os: process.platform, arch: process.arch, hostname: os.hostname(),
+ username: os.userInfo().username, totalMemory: os.totalmem(), cpuCount: os.cpus().length,
+ }))
+ })
+
+ // API: Process list
+ server.middlewares.use('/local-api/process-list', (_req, res) => {
+ // Simple stub — full process list needs native code
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ processes: [], count: 0, note: 'Full process list available in Tauri build only' }))
+ })
+
+ // API: Screenshot
+ server.middlewares.use('/local-api/screenshot', (_req, res) => {
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Screenshot available in Tauri build only' }))
+ })
+
// --- SearXNG availability check ---
let searxngAvailable = false
const checkSearXNG = () => {