reliary-agent 0.4.2

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

fn ok(msg: &str) { println!("  {} {}", "\x1b[32m✓\x1b[0m", msg); }

// Embed gate.js at compile time

/// Atomic write: write to tmp, sync, rename. Prevents partial write corruption.
fn atomic_write(path: &str, content: &str) -> bool {
    let tmp = format!("{}.tmp.{}", path, std::process::id());
    std::fs::write(&tmp, content).is_ok() && std::fs::rename(&tmp, path).is_ok()
}
const EMBEDDED_GATE_JS: &str = include_str!("../../../pi/gate.js");

fn ask_yes_no(prompt: &str, default: bool) -> bool {
    let def_str = if default { "[Y/n]" } else { "[y/N]" };
    print!("{} {}: ", prompt, def_str);
    let _ = io::stdout().flush();

    let mut input = String::new();
    if io::stdin().read_line(&mut input).is_ok() {
        let input = input.trim().to_lowercase();
        if input.is_empty() {
            return default;
        }
        return input == "y" || input == "yes";
    }
    default
}

fn home_dir() -> Option<PathBuf> {
    dirs::home_dir()
}

fn get_data_dir() -> Option<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        dirs::data_local_dir()
    }
    #[cfg(not(target_os = "windows"))]
    {
        home_dir().map(|h| h.join(".local/share"))
    }
}

pub fn run() {
    println!("\nReliary Setup");
    println!("-------------");

    let mut configured_agents = 0;

    // 1. Pi Agent
    let pi_bin = home_dir().map(|h| h.join(".local/bin/pi")).unwrap_or_else(|| PathBuf::from("pi"));
    let has_pi = pi_bin.exists() || Command::new("pi").arg("--version").output().is_ok();
    
    if has_pi {
        if ask_yes_no("Found Pi Agent. Install Reliary extension?", true) {
            if let Some(data_dir) = get_data_dir() {
                let target_dir = data_dir.join("reliary");
                if fs::create_dir_all(&target_dir).is_ok() {
                    let target_path = target_dir.join("gate.js");
                    let content = EMBEDDED_GATE_JS.as_bytes();
                    let tmp = format!("{}.tmp.{}", target_path.display(), std::process::id());
                    if std::fs::write(&tmp, content).is_ok()
                        && std::fs::rename(&tmp, &target_path).is_ok()
                    {
                        let pi_cmd = if pi_bin.exists() { pi_bin.to_str().unwrap_or("pi") } else { "pi" };
                        let status = Command::new(pi_cmd)
                            .args(["install", target_path.to_str().unwrap_or("/dev/null")])
                            .output();
                        
                        if let Ok(output) = status {
                            if output.status.success() {
                                ok("Installed gate.js");
                                configured_agents += 1;
                            } else {
                                println!("  {} Failed to run `pi install`\n", "\x1b[31m✗\x1b[0m");
                            }
                        } else {
                            println!("  {} Failed to run `pi install`\n", "\x1b[31m✗\x1b[0m");
                        }
                    } else {
                        println!("  {} Failed to write gate.js\n", "\x1b[31m✗\x1b[0m");
                    }
                } else {
                    println!("  {} Failed to create directory {:?}\n", "\x1b[31m✗\x1b[0m", target_dir);
                }
            } else {
                println!("  {} Could not determine data directory\n", "\x1b[31m✗\x1b[0m");
            }
        } else {
            println!("  {} Skipped\n", "\x1b[33m-\x1b[0m");
        }
    }

    // 2. Claude Code
    if let Some(home) = home_dir() {
        let claude_cfg = home.join(".claude.json");
        if claude_cfg.exists() {
            if ask_yes_no("Found Claude Code config. Add Reliary MCP server?", true) {
                    if inject_mcp_server(&claude_cfg, "reliary") {
                        ok("Updated ~/.claude.json");
                        configured_agents += 1;
                    } else {
                        println!("  {} Failed to update ~/.claude.json\n", "\x1b[31m✗\x1b[0m");
                    }
            } else {
                println!("  {} Skipped\n", "\x1b[33m-\x1b[0m");
            }
        }
    }

    // 3. OpenCode
    if let Some(home) = home_dir() {
        let opencode_cfg = if cfg!(target_os = "windows") {
            dirs::config_dir().map(|d| d.join("opencode").join("opencode.json"))
        } else if cfg!(target_os = "macos") {
            Some(home.join("Library/Application Support/opencode/opencode.json"))
        } else {
            Some(home.join(".config/opencode/opencode.json"))
        };

        if let Some(cfg_path) = opencode_cfg {
            if cfg_path.exists() {
                if ask_yes_no("Found OpenCode config. Add Reliary MCP server?", true) {
                    if inject_mcp_server(&cfg_path, "reliary") {
                        ok("Updated opencode.json");
                        configured_agents += 1;
                    } else {
                        println!("  {} Failed to update opencode.json\n", "\x1b[31m✗\x1b[0m");
                    }
                } else {
                    println!("  {} Skipped\n", "\x1b[33m-\x1b[0m");
                }
            }
        }
    }
    
    // 4. Cline
    if let Some(home) = home_dir() {
        let cline_cfg = if cfg!(target_os = "windows") {
            dirs::data_dir().map(|d| d.join("Code").join("User").join("globalStorage").join("rooveterinery.cline").join("cline_mcp_settings.json"))
        } else if cfg!(target_os = "macos") {
            Some(home.join("Library/Application Support/Code/User/globalStorage/rooveterinery.cline/cline_mcp_settings.json"))
        } else {
            Some(home.join(".config/Code/User/globalStorage/rooveterinery.cline/cline_mcp_settings.json"))
        };

        if let Some(cfg_path) = cline_cfg {
            if cfg_path.exists() {
                if ask_yes_no("Found Cline config. Add Reliary MCP server?", true) {
                    if inject_mcp_server(&cfg_path, "reliary") {
                        ok("Updated cline MCP settings");
                        configured_agents += 1;
                    } else {
                        println!("  {} Failed to update cline_mcp_settings.json\n", "\x1b[31m✗\x1b[0m");
                    }
                } else {
                    println!("  {} Skipped\n", "\x1b[33m-\x1b[0m");
                }
            }
        }
    }

    if configured_agents == 0 {
        println!("No agents were configured.\n");
    }

    // 5. Daemon
    if ask_yes_no("Do you want to install the Reliary daemon to run on boot?\n(Enables cross-session memory, dead code removal, faster search)", true) {
        if install_daemon() {
            ok("Daemon installed and started");
        } else {
            println!("  {} Failed to install daemon\n", "\x1b[31m✗\x1b[0m");
        }
    } else {
        println!("  {} Skipped\n", "\x1b[33m-\x1b[0m");
    }

    println!("\n  {} Setup complete! Your agents are now connected.", "\x1b[32m✓\x1b[0m");
}

fn inject_mcp_server(cfg_path: &PathBuf, server_name: &str) -> bool {
    let content = match fs::read_to_string(cfg_path) {
        Ok(c) => c,
        Err(_) => return false,
    };
    
    let mut v: Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(_) => return false,
    };

    if let Some(obj) = v.as_object_mut() {
        let mcp_servers = obj.entry("mcpServers").or_insert(serde_json::json!({}));
        if let Some(servers) = mcp_servers.as_object_mut() {
            let exe_path = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("reliary-agent"));
            let exe_str = exe_path.to_string_lossy().to_string();
            
            servers.insert(server_name.to_string(), serde_json::json!({
                "command": exe_str,
                "args": ["mcp"]
            }));
            
            if let Ok(new_content) = serde_json::to_string_pretty(&v) {
                return atomic_write(&cfg_path.to_string_lossy(), &new_content);
            }
        }
    }
    false
}

fn install_daemon() -> bool {
    let exe_path = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("reliary-agent"));
    let exe_str = exe_path.to_string_lossy().to_string();

    #[cfg(target_os = "linux")]
    {
        if let Some(home) = home_dir() {
            let service_dir = home.join(".config/systemd/user");
            if fs::create_dir_all(&service_dir).is_err() { return false; }
            
            let service_path = service_dir.join("reliary-daemon.service");
            let service_content = format!(
                "[Unit]\nDescription=Reliary Agent Daemon\n\n[Service]\nExecStart={} daemon\nRestart=always\n\n[Install]\nWantedBy=default.target\n",
                exe_str
            );
            
            if !atomic_write(&service_path.to_string_lossy(), &service_content) { return false; }
            
            let _ = Command::new("systemctl").args(["--user", "daemon-reload"]).status();
            let enable = Command::new("systemctl").args(["--user", "enable", "--now", "reliary-daemon.service"]).status();
            return enable.is_ok() && enable.unwrap_or_default().success();
        }
        false
    }
    #[cfg(target_os = "macos")]
    {
        if let Some(home) = home_dir() {
            let plist_dir = home.join("Library/LaunchAgents");
            if fs::create_dir_all(&plist_dir).is_err() { return false; }
            
            let plist_path = plist_dir.join("com.reliary.daemon.plist");
            let plist_content = format!(
                r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.reliary.daemon</string>
    <key>ProgramArguments</key>
    <array>
        <string>{}</string>
        <string>daemon</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
</dict>
</plist>
"#, exe_str
            );
            
            if !atomic_write(&plist_path.to_string_lossy(), &plist_content) { return false; }
            
            let _ = Command::new("launchctl").args(["unload", "-w", plist_path.to_str().unwrap_or("")]).status();
            let load = Command::new("launchctl").args(["load", "-w", plist_path.to_str().unwrap_or("")]).status();
            return load.is_ok() && load.unwrap_or_default().success();
        }
        false
    }
    #[cfg(target_os = "windows")]
    {
        if let Some(roaming) = dirs::config_dir() {
            let startup_dir = roaming.join("Microsoft/Windows/Start Menu/Programs/Startup");
            if fs::create_dir_all(&startup_dir).is_err() { return false; }
            
            let vbs_path = startup_dir.join("reliary-daemon.vbs");
            let vbs_content = format!(
                "Set WshShell = CreateObject(\"WScript.Shell\")\nWshShell.Run chr(34) & \"{}\" & chr(34) & \" daemon\", 0\nSet WshShell = Nothing\n",
                exe_str
            );
            
            if atomic_write(&vbs_path.to_string_lossy(), &vbs_content) {
                // Try to start it right now too
                let _ = Command::new("wscript").arg(vbs_path.to_str().unwrap_or("")).status();
                return true;
            }
        }
        false
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        println!("Platform not supported for auto-start daemon.");
        false
    }
}

pub fn uninstall() {
    println!("\nReliary Uninstall");
    println!("-----------------");

    let mut removed_agents = 0;

    // 1. Pi Agent
    let pi_bin = home_dir().map(|h| h.join(".local/bin/pi")).unwrap_or_else(|| PathBuf::from("pi"));
    let has_pi = pi_bin.exists() || Command::new("pi").arg("--version").output().is_ok();
    
    if has_pi {
        println!("Removing Pi Agent extension...");
        if let Some(data_dir) = get_data_dir() {
            let target_dir = data_dir.join("reliary");
            let target_path = target_dir.join("gate.js");
            
            if target_path.exists() {
                let pi_cmd = if pi_bin.exists() { pi_bin.to_str().unwrap_or("pi") } else { "pi" };
                let _ = Command::new(pi_cmd)
                    .args(["uninstall", target_path.to_str().unwrap_or("/dev/null")])
                    .status();
                
                let _ = fs::remove_file(&target_path);
                
                // Attempt to remove directory if empty
                if let Ok(entries) = fs::read_dir(&target_dir) {
                    if entries.count() == 0 {
                        let _ = fs::remove_dir(&target_dir);
                    }
                }
                
                ok("Removed gate.js");
                removed_agents += 1;
            } else {
                println!("- gate.js not found\n");
            }
        }
    }

    // 2. Claude Code
    println!("Removing MCP integrations...");
    if let Some(home) = home_dir() {
        let claude_cfg = home.join(".claude.json");
        if claude_cfg.exists() && remove_mcp_server(&claude_cfg, "reliary") {
            ok("Removed Reliary from Claude Code");
            removed_agents += 1;
        }
    }

    // 3. OpenCode
    if let Some(home) = home_dir() {
        let opencode_cfg = if cfg!(target_os = "windows") {
            dirs::config_dir().map(|d| d.join("opencode").join("opencode.json"))
        } else if cfg!(target_os = "macos") {
            Some(home.join("Library/Application Support/opencode/opencode.json"))
        } else {
            Some(home.join(".config/opencode/opencode.json"))
        };

        if let Some(cfg_path) = opencode_cfg {
            if cfg_path.exists() && remove_mcp_server(&cfg_path, "reliary") {
                ok("Removed Reliary from OpenCode");
                removed_agents += 1;
            }
        }
    }
    
    // 4. Cline
    if let Some(home) = home_dir() {
        let cline_cfg = if cfg!(target_os = "windows") {
            dirs::data_dir().map(|d| d.join("Code").join("User").join("globalStorage").join("rooveterinery.cline").join("cline_mcp_settings.json"))
        } else if cfg!(target_os = "macos") {
            Some(home.join("Library/Application Support/Code/User/globalStorage/rooveterinery.cline/cline_mcp_settings.json"))
        } else {
            Some(home.join(".config/Code/User/globalStorage/rooveterinery.cline/cline_mcp_settings.json"))
        };

        if let Some(cfg_path) = cline_cfg {
            if cfg_path.exists() && remove_mcp_server(&cfg_path, "reliary") {
                ok("Removed Reliary from Cline");
                removed_agents += 1;
            }
        }
    }

    if removed_agents == 0 {
        println!("- No MCP integrations found or modified");
    }
    println!();

    // 5. Daemon
    println!("Stopping and removing background daemon...");
    if uninstall_daemon() {
        ok("Daemon service removed");
    } else {
        println!("- Daemon service not found or could not be removed\n");
    }

    // 6. Config
    if ask_yes_no("Do you want to delete global configuration files? (~/.reliary)", false) {
        if let Some(home) = home_dir() {
            let config_dir = home.join(".reliary");
            if config_dir.exists() {
                if fs::remove_dir_all(&config_dir).is_ok() {
                    ok("Deleted ~/.reliary");
                } else {
                    println!("✗ Failed to delete ~/.reliary\n");
                }
            } else {
                println!("- ~/.reliary not found\n");
            }
        }
    } else {
        println!("- Skipped\n");
    }

    println!("Uninstall complete. You can now safely run `cargo uninstall reliary-agent`.");
}

fn remove_mcp_server(cfg_path: &PathBuf, server_name: &str) -> bool {
    let content = match fs::read_to_string(cfg_path) {
        Ok(c) => c,
        Err(_) => return false,
    };
    
    let mut v: Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(_) => return false,
    };

    if let Some(obj) = v.as_object_mut() {
        if let Some(mcp_servers) = obj.get_mut("mcpServers").and_then(|m| m.as_object_mut()) {
            if mcp_servers.remove(server_name).is_some() {
                if let Ok(new_content) = serde_json::to_string_pretty(&v) {
                    return atomic_write(&cfg_path.to_string_lossy(), &new_content);
                }
            }
        }
    }
    false
}

fn uninstall_daemon() -> bool {
    let mut removed = false;

    #[cfg(target_os = "linux")]
    {
        if let Some(home) = home_dir() {
            let service_path = home.join(".config/systemd/user/reliary-daemon.service");
            if service_path.exists() {
                let _ = Command::new("systemctl").args(["--user", "disable", "--now", "reliary-daemon.service"]).status();
                if fs::remove_file(&service_path).is_ok() {
                    removed = true;
                }
                let _ = Command::new("systemctl").args(["--user", "daemon-reload"]).status();
            }
        }
    }
    #[cfg(target_os = "macos")]
    {
        if let Some(home) = home_dir() {
            let plist_path = home.join("Library/LaunchAgents/com.reliary.daemon.plist");
            if plist_path.exists() {
                let _ = Command::new("launchctl").args(["unload", "-w", plist_path.to_str().unwrap_or("")]).status();
                if fs::remove_file(&plist_path).is_ok() {
                    removed = true;
                }
            }
        }
    }
    #[cfg(target_os = "windows")]
    {
        if let Some(roaming) = dirs::config_dir() {
            let vbs_path = roaming.join("Microsoft/Windows/Start Menu/Programs/Startup/reliary-daemon.vbs");
            if vbs_path.exists() {
                let _ = Command::new("taskkill").args(["/F", "/IM", "reliary-agent.exe"]).status();
                if fs::remove_file(&vbs_path).is_ok() {
                    removed = true;
                }
            }
        }
    }
    
    removed
}