x0x 0.19.47

Agent-to-agent gossip network for AI systems — no winners, no losers, just cooperation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Daemon lifecycle CLI commands.

use anyhow::{Context, Result};
use std::path::Path;
use std::time::Duration;

use crate::cli::DaemonClient;

/// `x0x start` — spawn x0xd as a background process.
pub async fn start(name: Option<&str>, config: Option<&Path>, foreground: bool) -> Result<()> {
    // Find x0xd binary: same directory as x0x, then PATH.
    let x0xd_path = find_x0xd()?;

    // Check if the target instance is already running.
    let format = crate::cli::OutputFormat::Text;
    if let Some(base_url) = discovered_base_url(name)? {
        let client = DaemonClient::new(name, Some(&base_url), format)?;
        if client.ensure_running().await.is_ok() {
            println!("Daemon already running at {}", client.base_url());
            return Ok(());
        }
    }

    let mut cmd = std::process::Command::new(&x0xd_path);
    if let Some(n) = name {
        cmd.arg("--name").arg(n);
    }
    if let Some(c) = config {
        cmd.arg("--config").arg(c);
    }

    if foreground {
        // Replace current process with x0xd.
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;
            let err = cmd.exec();
            anyhow::bail!("failed to exec x0xd: {err}");
        }
        #[cfg(not(unix))]
        {
            let status = cmd.status().context("failed to run x0xd")?;
            if !status.success() {
                anyhow::bail!("x0xd exited with {status}");
            }
            return Ok(());
        }
    }

    // Background: spawn and wait for health.
    cmd.stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());

    let _child = cmd.spawn().context("failed to spawn x0xd")?;

    // Poll health for up to 5 seconds.
    for _ in 0..50 {
        tokio::time::sleep(Duration::from_millis(100)).await;
        let Some(base_url) = discovered_base_url(name)? else {
            continue;
        };
        let client = DaemonClient::new(name, Some(&base_url), format)?;
        if client.ensure_running().await.is_ok() {
            println!("Daemon started at {}", client.base_url());
            return Ok(());
        }
    }

    let fallback_url =
        discovered_base_url(name)?.unwrap_or_else(|| String::from("http://127.0.0.1:12700"));
    println!("Daemon spawned but not yet reachable at {fallback_url}");
    Ok(())
}

/// `x0x stop` — POST /shutdown
pub async fn stop(client: &DaemonClient) -> Result<()> {
    client.ensure_running().await?;
    match client.post_empty("/shutdown").await {
        Ok(_) => println!("Daemon shutting down."),
        Err(e) => {
            // Connection reset is expected when the server shuts down.
            let msg = format!("{e:#}");
            if msg.contains("connection") || msg.contains("reset") || msg.contains("closed") {
                println!("Daemon shutting down.");
            } else {
                return Err(e);
            }
        }
    }
    Ok(())
}

/// `x0x doctor` — run diagnostics against the daemon.
pub async fn doctor(client: &DaemonClient) -> Result<()> {
    println!("Running diagnostics...\n");

    // 1. Health check.
    print!("Health check: ");
    match client.ensure_running().await {
        Ok(()) => println!("OK"),
        Err(e) => {
            println!("FAIL — {e}");
            return Ok(());
        }
    }

    // 2. Agent identity.
    print!("Agent identity: ");
    match client.get("/agent").await {
        Ok(val) => {
            let agent_id = val
                .get("agent_id")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            println!("{agent_id}");
        }
        Err(e) => println!("FAIL — {e}"),
    }

    // 3. Network status.
    print!("Network: ");
    match client.get("/status").await {
        Ok(val) => {
            let peers = val.get("peers").and_then(|v| v.as_u64()).unwrap_or(0);
            let connectivity = val
                .get("status")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            println!("{peers} peers, {connectivity}");
        }
        Err(e) => println!("FAIL — {e}"),
    }

    // 4. Contacts.
    print!("Contacts: ");
    match client.get("/contacts").await {
        Ok(val) => {
            let count = val
                .get("contacts")
                .and_then(|v| v.as_array())
                .map(|a| a.len())
                .unwrap_or(0);
            println!("{count} contacts");
        }
        Err(e) => println!("FAIL — {e}"),
    }

    println!("\nDiagnostics complete.");
    Ok(())
}

/// `x0x instances` — list running daemon instances.
pub async fn instances() -> Result<()> {
    let data_dir = dirs::data_dir().context("cannot determine data directory")?;

    let mut found = Vec::new();

    // Check default instance.
    let default_port = data_dir.join("x0x").join("api.port");
    if default_port.exists() {
        found.push(("(default)".to_string(), default_port));
    }

    // Check named instances.
    if let Ok(entries) = std::fs::read_dir(&data_dir) {
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if let Some(instance) = name_str.strip_prefix("x0x-") {
                let port_file = entry.path().join("api.port");
                if port_file.exists() {
                    found.push((instance.to_string(), port_file));
                }
            }
        }
    }

    if found.is_empty() {
        println!("No running instances found.");
        return Ok(());
    }

    let name_width = found.iter().map(|(n, _)| n.len()).max().unwrap_or(4).max(4);
    println!("{:<name_width$}  {:<21}  {:<10}", "NAME", "API", "STATUS");

    let http_client = reqwest::Client::builder()
        .timeout(Duration::from_secs(2))
        .build()?;

    for (name, port_file) in &found {
        let addr = std::fs::read_to_string(port_file)
            .unwrap_or_default()
            .trim()
            .to_string();
        let status = if !addr.is_empty() {
            match http_client
                .get(format!("http://{addr}/health"))
                .send()
                .await
            {
                Ok(r) if r.status().is_success() => "running",
                _ => "stale",
            }
        } else {
            "stale"
        };
        println!("{:<name_width$}  {:<21}  {:<10}", name, addr, status);
    }

    Ok(())
}

/// `x0x autostart` — configure daemon to start on boot.
pub async fn autostart(name: Option<&str>) -> Result<()> {
    let x0xd_path = find_x0xd()?;
    let x0xd = x0xd_path.to_string_lossy();

    #[cfg(target_os = "linux")]
    {
        let mut args = Vec::new();
        if let Some(n) = name {
            args.push("--name".to_string());
            args.push(n.to_string());
        }
        let args_str = args.join(" ");
        let unit_dir = dirs::config_dir()
            .context("cannot determine config directory")?
            .join("systemd/user");
        std::fs::create_dir_all(&unit_dir)?;

        let unit_path = unit_dir.join("x0xd.service");
        let unit = format!(
            "[Unit]\n\
             Description=x0x Agent Daemon\n\
             After=network-online.target\n\
             Wants=network-online.target\n\
             \n\
             [Service]\n\
             Type=simple\n\
             ExecStart={x0xd} {args_str}\n\
             Restart=always\n\
             RestartSec=5\n\
             \n\
             [Install]\n\
             WantedBy=default.target\n"
        );
        std::fs::write(&unit_path, unit)?;

        let status = std::process::Command::new("systemctl")
            .args(["--user", "daemon-reload"])
            .status()
            .context("systemctl daemon-reload failed")?;
        if !status.success() {
            anyhow::bail!("systemctl daemon-reload failed");
        }

        let status = std::process::Command::new("systemctl")
            .args(["--user", "enable", "x0xd"])
            .status()
            .context("systemctl enable failed")?;
        if !status.success() {
            anyhow::bail!("systemctl enable failed");
        }

        println!("Autostart enabled (systemd user service)");
        println!("  systemctl --user start x0xd");
        println!("  systemctl --user status x0xd");
        println!("  systemctl --user stop x0xd");
    }

    #[cfg(target_os = "macos")]
    {
        let plist_dir = dirs::home_dir()
            .context("cannot determine home directory")?
            .join("Library/LaunchAgents");
        std::fs::create_dir_all(&plist_dir)?;

        let plist_path = plist_dir.join("com.saorsalabs.x0xd.plist");
        let mut prog_args = format!("        <string>{x0xd}</string>\n");
        if let Some(n) = name {
            prog_args.push_str(&format!(
                "        <string>--name</string>\n        <string>{n}</string>\n"
            ));
        }

        let data_dir = if let Some(n) = name {
            dirs::data_dir()
                .context("cannot determine data directory")?
                .join(format!("x0x-{n}"))
        } else {
            dirs::data_dir()
                .context("cannot determine data directory")?
                .join("x0x")
        };
        std::fs::create_dir_all(&data_dir)?;
        let log_path = data_dir.join("x0xd.log");

        let plist = format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
             <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
             <plist version=\"1.0\">\n\
             <dict>\n\
                 <key>Label</key>\n\
                 <string>com.saorsalabs.x0xd</string>\n\
                 <key>ProgramArguments</key>\n\
                 <array>\n\
             {prog_args}\
                 </array>\n\
                 <key>RunAtLoad</key>\n\
                 <true/>\n\
                 <key>KeepAlive</key>\n\
                 <true/>\n\
                 <key>StandardOutPath</key>\n\
                 <string>{}</string>\n\
                 <key>StandardErrorPath</key>\n\
                 <string>{}</string>\n\
             </dict>\n\
             </plist>\n",
            log_path.display(),
            log_path.display()
        );
        std::fs::write(&plist_path, plist)?;

        // Unload any existing agent first (ignore errors if not loaded).
        let _ = std::process::Command::new("launchctl")
            .args(["unload", &plist_path.to_string_lossy()])
            .output();

        // Load the agent so it starts now and on boot.
        let status = std::process::Command::new("launchctl")
            .args(["load", &plist_path.to_string_lossy()])
            .status()
            .context("failed to run launchctl load")?;
        if !status.success() {
            anyhow::bail!("launchctl load failed (exit {})", status);
        }

        println!("Autostart enabled (launchd agent)");
        println!("  Plist:  {}", plist_path.display());
        println!("  Status: launchctl list | grep x0xd");
        println!("  Remove: x0x autostart --remove");
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        println!("Autostart not supported on this platform.");
        println!("Run x0xd manually or configure your OS service manager.");
    }

    Ok(())
}

/// `x0x autostart --remove` — remove autostart configuration.
pub async fn autostart_remove() -> Result<()> {
    #[cfg(target_os = "linux")]
    {
        let _ = std::process::Command::new("systemctl")
            .args(["--user", "disable", "x0xd"])
            .status();
        let unit_path = dirs::config_dir()
            .context("cannot determine config directory")?
            .join("systemd/user/x0xd.service");
        if unit_path.exists() {
            std::fs::remove_file(&unit_path)?;
        }
        let _ = std::process::Command::new("systemctl")
            .args(["--user", "daemon-reload"])
            .status();
        println!("Autostart removed (systemd)");
    }

    #[cfg(target_os = "macos")]
    {
        let plist_path = dirs::home_dir()
            .context("cannot determine home directory")?
            .join("Library/LaunchAgents/com.saorsalabs.x0xd.plist");
        if plist_path.exists() {
            let _ = std::process::Command::new("launchctl")
                .args(["unload", &plist_path.to_string_lossy()])
                .status();
            std::fs::remove_file(&plist_path)?;
        }
        println!("Autostart removed (launchd)");
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    println!("Autostart not supported on this platform.");

    Ok(())
}

fn discovered_base_url(name: Option<&str>) -> Result<Option<String>> {
    let port_file = port_file_path(name)?;
    if !port_file.exists() {
        return Ok(None);
    }

    let addr = std::fs::read_to_string(&port_file)
        .context("failed to read port file")?
        .trim()
        .to_string();
    if addr.is_empty() {
        return Ok(None);
    }

    Ok(Some(format!("http://{addr}")))
}

fn port_file_path(name: Option<&str>) -> Result<std::path::PathBuf> {
    let data_dir = dirs::data_dir().context("cannot determine data directory")?;
    let dir_name = match name {
        Some(instance) => format!("x0x-{instance}"),
        None => "x0x".to_string(),
    };
    Ok(data_dir.join(dir_name).join("api.port"))
}

/// Find the x0xd binary.
fn find_x0xd() -> Result<std::path::PathBuf> {
    // Same directory as x0x binary.
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            let candidate = dir.join("x0xd");
            if candidate.exists() {
                return Ok(candidate);
            }
        }
    }

    // Search PATH.
    if let Ok(path) = which::which("x0xd") {
        return Ok(path);
    }

    anyhow::bail!("x0xd not found. Install it or ensure it's in the same directory as x0x.")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn port_file_path_default() {
        let path = port_file_path(None).unwrap();
        let path_str = path.to_string_lossy();
        assert!(path_str.contains("x0x"), "should contain x0x: {path_str}");
        assert!(
            path_str.ends_with("api.port"),
            "should end with api.port: {path_str}"
        );
    }

    #[test]
    fn port_file_path_named() {
        let path = port_file_path(Some("test-instance")).unwrap();
        let path_str = path.to_string_lossy();
        assert!(
            path_str.contains("x0x-test-instance"),
            "should contain instance name: {path_str}"
        );
        assert!(
            path_str.ends_with("api.port"),
            "should end with api.port: {path_str}"
        );
    }

    #[test]
    fn discovered_base_url_returns_none_for_missing_file() {
        let result = discovered_base_url(Some("nonexistent-instance-xyz-12345")).unwrap();
        assert!(
            result.is_none(),
            "should return None for nonexistent instance"
        );
    }

    #[test]
    fn find_x0xd_returns_error_when_not_found() {
        // Temporarily change PATH to something that doesn't have x0xd
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = find_x0xd();
        }));
        // Should not panic — just return an error
        assert!(result.is_ok());
    }

    /// Start a mock axum server that returns the given JSON for any request.
    #[allow(dead_code)]
    async fn start_mock_server(
        response_json: serde_json::Value,
    ) -> (String, tokio::sync::oneshot::Sender<()>) {
        use std::sync::Arc;

        let json = Arc::new(response_json);
        let app = axum::Router::new().fallback(move |_req: axum::extract::Request| {
            let json = Arc::clone(&json);
            async move {
                let body = serde_json::to_vec(&*json).unwrap();
                axum::response::Response::builder()
                    .status(200)
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(body))
                    .unwrap()
            }
        });

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (tx, rx) = tokio::sync::oneshot::channel::<()>();

        tokio::spawn(async move {
            axum::serve(listener, app.into_make_service())
                .with_graceful_shutdown(async {
                    rx.await.ok();
                })
                .await
                .ok();
        });

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        (format!("http://{}", addr), tx)
    }

    #[tokio::test]
    async fn stop_sends_shutdown_request() {
        let mock_resp = serde_json::json!({"ok": true});
        let (url, _shutdown) = start_mock_server(mock_resp).await;
        let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();
        let result = stop(&client).await;
        assert!(result.is_ok(), "stop should succeed: {:?}", result);
    }

    #[tokio::test]
    async fn doctor_runs_all_checks() {
        let mock_resp = serde_json::json!({
            "agent_id": "abc123",
            "peers": 5,
            "status": "connected",
            "contacts": [{"agent_id": "xyz"}]
        });
        let (url, _shutdown) = start_mock_server(mock_resp).await;
        let client = DaemonClient::new(None, Some(&url), crate::cli::OutputFormat::Json).unwrap();
        let result = doctor(&client).await;
        assert!(result.is_ok(), "doctor should succeed: {:?}", result);
    }

    #[tokio::test]
    async fn instances_returns_empty_when_no_port_files() {
        // In a test environment without port files, instances should return empty
        let result = instances().await;
        assert!(result.is_ok(), "instances should not fail: {:?}", result);
    }

    #[tokio::test]
    async fn autostart_remove_does_not_panic() {
        // Should not panic even without autostart configured
        let result = autostart_remove().await;
        assert!(
            result.is_ok(),
            "autostart_remove should not fail: {:?}",
            result
        );
    }
}