localgpt 0.1.3

A local device focused AI assistant with persistent markdown memory, autonomous heartbeat tasks, and semantic search. Single binary, no runtime dependencies.
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
use anyhow::Result;
use clap::{Args, Subcommand};
use std::fs;
use std::path::PathBuf;

#[cfg(unix)]
use daemonize::Daemonize;

use localgpt::concurrency::TurnGate;
use localgpt::config::Config;
use localgpt::heartbeat::HeartbeatRunner;
use localgpt::memory::MemoryManager;
use localgpt::server::Server;

/// Synchronously stop the daemon (for use before Tokio runtime starts)
pub fn stop_sync() -> Result<()> {
    let pid_file = get_pid_file()?;

    if !pid_file.exists() {
        println!("Daemon is not running");
        return Ok(());
    }

    let pid = fs::read_to_string(&pid_file)?.trim().to_string();

    if !is_process_running(&pid) {
        println!("Daemon is not running (stale PID file)");
        fs::remove_file(&pid_file)?;
        return Ok(());
    }

    println!("Stopping daemon (PID: {})...", pid);

    // Send SIGTERM
    #[cfg(unix)]
    {
        use std::process::Command;
        Command::new("kill").args(["-TERM", &pid]).status()?;
    }

    #[cfg(windows)]
    {
        use std::process::Command;
        Command::new("taskkill").args(["/PID", &pid]).status()?;
    }

    // Wait for process to stop (up to 5 seconds)
    for _ in 0..50 {
        if !is_process_running(&pid) {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    if is_process_running(&pid) {
        anyhow::bail!("Failed to stop daemon (PID: {})", pid);
    }

    println!("Daemon stopped");
    fs::remove_file(&pid_file).ok();

    Ok(())
}

/// Fork and daemonize BEFORE starting the Tokio runtime.
/// This avoids the macOS fork-safety issue with ObjC/Swift runtime.
#[cfg(unix)]
pub fn daemonize_and_run(agent_id: &str) -> Result<()> {
    let config = Config::load()?;

    // Check if already running
    let pid_file = get_pid_file()?;
    if pid_file.exists() {
        let pid = fs::read_to_string(&pid_file)?;
        if is_process_running(&pid) {
            anyhow::bail!("Daemon already running (PID: {})", pid.trim());
        }
        fs::remove_file(&pid_file)?;
    }

    let log_file = get_log_file(config.logging.retention_days)?;

    // Print startup info before daemonizing
    println!(
        "Starting LocalGPT daemon in background (agent: {})...",
        agent_id
    );
    println!("  PID file: {}", pid_file.display());
    println!("  Log file: {}", log_file.display());
    if config.server.enabled {
        println!(
            "  Server: http://{}:{}",
            config.server.bind, config.server.port
        );
    }
    println!("\nUse 'localgpt daemon status' to check status");
    println!("Use 'localgpt daemon stop' to stop\n");

    // Fork BEFORE starting Tokio
    // Use append mode to preserve previous logs within the same day
    let stdout = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_file)?;
    let stderr = stdout.try_clone()?;

    let daemonize = Daemonize::new()
        .pid_file(&pid_file)
        .working_directory(std::env::current_dir()?)
        .stdout(stdout)
        .stderr(stderr);

    match daemonize.start() {
        Ok(_) => {
            // Now in the child process - safe to start Tokio
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()?
                .block_on(run_daemon_server(config, agent_id))
        }
        Err(e) => anyhow::bail!("Failed to daemonize: {}", e),
    }
}

/// Run the daemon server (called after fork in background mode)
async fn run_daemon_server(config: Config, agent_id: &str) -> Result<()> {
    // Initialize logging in the daemon process
    // Disable ANSI colors since we're writing to a file
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::new("info"))
        .with_ansi(false)
        .init();

    let memory = MemoryManager::new_with_full_config(&config.memory, Some(&config), agent_id)?;
    let _watcher = memory.start_watcher()?;

    println!("Daemon started successfully");

    run_daemon_services(&config, agent_id).await?;

    println!("\nShutting down...");
    let pid_file = get_pid_file()?;
    fs::remove_file(&pid_file).ok();

    Ok(())
}

/// Run daemon services (server and/or heartbeat)
async fn run_daemon_services(config: &Config, agent_id: &str) -> Result<()> {
    // Create shared turn gate for heartbeat + HTTP concurrency control
    let turn_gate = TurnGate::new();

    // Spawn heartbeat in background if enabled
    let heartbeat_handle = if config.heartbeat.enabled {
        let heartbeat_config = config.clone();
        let heartbeat_agent_id = agent_id.to_string();
        let heartbeat_gate = turn_gate.clone();
        println!(
            "  Heartbeat: enabled (interval: {})",
            config.heartbeat.interval
        );
        Some(tokio::spawn(async move {
            match HeartbeatRunner::new_with_gate(
                &heartbeat_config,
                &heartbeat_agent_id,
                Some(heartbeat_gate),
            ) {
                Ok(runner) => {
                    if let Err(e) = runner.run().await {
                        tracing::error!("Heartbeat runner error: {}", e);
                    }
                }
                Err(e) => {
                    tracing::error!("Failed to create heartbeat runner: {}", e);
                }
            }
        }))
    } else {
        None
    };

    // Spawn Telegram bot in background if configured
    let telegram_handle = if config.telegram.as_ref().is_some_and(|t| t.enabled) {
        let tg_config = config.clone();
        let tg_gate = turn_gate.clone();
        println!("  Telegram: enabled");
        Some(tokio::spawn(async move {
            if let Err(e) = localgpt::server::telegram::run_telegram_bot(&tg_config, tg_gate).await
            {
                tracing::error!("Telegram bot error: {}", e);
            }
        }))
    } else {
        None
    };

    // Run server or wait for shutdown
    if config.server.enabled {
        println!(
            "  Server: http://{}:{}",
            config.server.bind, config.server.port
        );
        let server = Server::new_with_gate(config, turn_gate)?;
        server.run().await?;
    } else if heartbeat_handle.is_some() {
        // Server not enabled but heartbeat is - wait for Ctrl+C
        println!("  Server: disabled");
        tokio::signal::ctrl_c().await?;
    } else {
        println!("  Neither server nor heartbeat is enabled. Use Ctrl+C to stop.");
        tokio::signal::ctrl_c().await?;
    }

    // Abort background tasks on shutdown
    if let Some(handle) = heartbeat_handle {
        handle.abort();
    }
    if let Some(handle) = telegram_handle {
        handle.abort();
    }

    Ok(())
}

#[derive(Args)]
pub struct DaemonArgs {
    #[command(subcommand)]
    pub command: DaemonCommands,
}

#[derive(Subcommand)]
pub enum DaemonCommands {
    /// Start the daemon
    Start {
        /// Run in foreground (don't daemonize)
        #[arg(short, long)]
        foreground: bool,
    },

    /// Stop the daemon
    Stop,

    /// Restart the daemon (stop then start)
    Restart {
        /// Run in foreground (don't daemonize)
        #[arg(short, long)]
        foreground: bool,
    },

    /// Show daemon status
    Status,

    /// Run heartbeat once (for testing)
    Heartbeat,
}

pub async fn run(args: DaemonArgs, agent_id: &str) -> Result<()> {
    match args.command {
        DaemonCommands::Start { foreground } => start_daemon(foreground, agent_id).await,
        DaemonCommands::Stop => stop_daemon().await,
        DaemonCommands::Restart { foreground } => restart_daemon(foreground, agent_id).await,
        DaemonCommands::Status => show_status().await,
        DaemonCommands::Heartbeat => run_heartbeat_once(agent_id).await,
    }
}

async fn start_daemon(foreground: bool, agent_id: &str) -> Result<()> {
    let config = Config::load()?;

    // Check if already running
    let pid_file = get_pid_file()?;
    if pid_file.exists() {
        let pid = fs::read_to_string(&pid_file)?;
        if is_process_running(&pid) {
            anyhow::bail!("Daemon already running (PID: {})", pid.trim());
        }
        fs::remove_file(&pid_file)?;
    }

    // Background mode on Unix is handled by daemonize_and_run() before Tokio starts
    // This function only handles foreground mode and non-Unix platforms
    #[cfg(unix)]
    if !foreground {
        // This shouldn't be reached - background mode is handled in main()
        anyhow::bail!("Background mode should be handled before Tokio starts");
    }

    #[cfg(not(unix))]
    if !foreground {
        println!(
            "Note: Background daemonization not supported on this platform. Running in foreground."
        );
    }

    println!(
        "Starting LocalGPT daemon in foreground (agent: {})...",
        agent_id
    );

    // Write PID file for foreground mode
    fs::write(&pid_file, std::process::id().to_string())?;

    // Initialize components
    let memory = MemoryManager::new_with_full_config(&config.memory, Some(&config), agent_id)?;
    let _watcher = memory.start_watcher()?;

    println!("Daemon started successfully");

    run_daemon_services(&config, agent_id).await?;

    println!("\nShutting down...");
    fs::remove_file(&pid_file).ok();

    Ok(())
}

async fn stop_daemon() -> Result<()> {
    let pid_file = get_pid_file()?;

    if !pid_file.exists() {
        println!("Daemon is not running");
        return Ok(());
    }

    let pid = fs::read_to_string(&pid_file)?.trim().to_string();

    if !is_process_running(&pid) {
        println!("Daemon is not running (stale PID file)");
        fs::remove_file(&pid_file)?;
        return Ok(());
    }

    // Send SIGTERM
    #[cfg(unix)]
    {
        use std::process::Command;
        Command::new("kill").args(["-TERM", &pid]).status()?;
    }

    #[cfg(windows)]
    {
        use std::process::Command;
        Command::new("taskkill").args(["/PID", &pid]).status()?;
    }

    println!("Sent stop signal to daemon (PID: {})", pid);
    fs::remove_file(&pid_file)?;

    Ok(())
}

async fn restart_daemon(foreground: bool, agent_id: &str) -> Result<()> {
    // Stop the daemon if running
    let pid_file = get_pid_file()?;
    if pid_file.exists() {
        let pid = fs::read_to_string(&pid_file)?.trim().to_string();
        if is_process_running(&pid) {
            println!("Stopping daemon (PID: {})...", pid);

            #[cfg(unix)]
            {
                use std::process::Command;
                Command::new("kill").args(["-TERM", &pid]).status()?;
            }

            #[cfg(windows)]
            {
                use std::process::Command;
                Command::new("taskkill").args(["/PID", &pid]).status()?;
            }

            // Wait for process to stop (up to 5 seconds)
            for _ in 0..50 {
                if !is_process_running(&pid) {
                    break;
                }
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
            }

            if is_process_running(&pid) {
                anyhow::bail!("Failed to stop daemon (PID: {})", pid);
            }

            println!("Daemon stopped");
        }
        fs::remove_file(&pid_file).ok();
    }

    // For background mode on Unix, we need to exit and let main() handle daemonization
    #[cfg(unix)]
    if !foreground {
        println!("\nTo start daemon in background, run: localgpt daemon start");
        println!("(Background restart requires re-running the command due to fork requirements)");
        return Ok(());
    }

    // Start in foreground mode
    println!();
    start_daemon(foreground, agent_id).await
}

async fn show_status() -> Result<()> {
    let config = Config::load()?;
    let pid_file = get_pid_file()?;

    let running = if pid_file.exists() {
        let pid = fs::read_to_string(&pid_file)?;
        is_process_running(&pid)
    } else {
        false
    };

    println!("LocalGPT Daemon Status");
    println!("----------------------");
    println!("Running: {}", if running { "yes" } else { "no" });

    if running {
        let pid = fs::read_to_string(&pid_file)?;
        println!("PID: {}", pid.trim());
    }

    println!("\nConfiguration:");
    println!("  Heartbeat enabled: {}", config.heartbeat.enabled);
    if config.heartbeat.enabled {
        println!("  Heartbeat interval: {}", config.heartbeat.interval);
    }
    println!("  Server enabled: {}", config.server.enabled);
    if config.server.enabled {
        println!(
            "  Server address: http://{}:{}",
            config.server.bind, config.server.port
        );
    }

    Ok(())
}

async fn run_heartbeat_once(agent_id: &str) -> Result<()> {
    let config = Config::load()?;
    let runner = HeartbeatRunner::new_with_agent(&config, agent_id)?;

    println!("Running heartbeat (agent: {})...", agent_id);
    let result = runner.run_once().await?;

    if result == "HEARTBEAT_OK" {
        println!("Heartbeat completed: No tasks needed attention");
    } else {
        println!("Heartbeat response:\n{}", result);
    }

    Ok(())
}

fn get_pid_file() -> Result<PathBuf> {
    // Put PID file in state dir (~/.localgpt/), not workspace
    let state_dir = localgpt::agent::get_state_dir()?;
    Ok(state_dir.join("daemon.pid"))
}

fn get_log_file(retention_days: u32) -> Result<PathBuf> {
    let state_dir = localgpt::agent::get_state_dir()?;
    let logs_dir = state_dir.join("logs");
    fs::create_dir_all(&logs_dir)?;

    // Prune old logs only if retention_days > 0
    if retention_days > 0 {
        prune_old_logs(&logs_dir, retention_days as i64);
    }

    // Use date-based log files (like OpenClaw)
    let date = chrono::Local::now().format("%Y-%m-%d");
    Ok(logs_dir.join(format!("localgpt-{}.log", date)))
}

/// Prune log files older than `keep_days` days
fn prune_old_logs(logs_dir: &std::path::Path, keep_days: i64) {
    let cutoff = chrono::Local::now() - chrono::Duration::days(keep_days);
    let cutoff_date = cutoff.format("%Y-%m-%d").to_string();

    if let Ok(entries) = fs::read_dir(logs_dir) {
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();

            // Match localgpt-YYYY-MM-DD.log pattern
            if name_str.starts_with("localgpt-")
                && name_str.ends_with(".log")
                && let Some(date_part) = name_str
                    .strip_prefix("localgpt-")
                    .and_then(|s| s.strip_suffix(".log"))
                && date_part < cutoff_date.as_str()
            {
                let _ = fs::remove_file(entry.path());
            }
        }
    }
}

fn is_process_running(pid: &str) -> bool {
    let pid = pid.trim();

    #[cfg(unix)]
    {
        use std::process::Command;
        Command::new("kill")
            .args(["-0", pid])
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }

    #[cfg(windows)]
    {
        use std::process::Command;
        Command::new("tasklist")
            .args(["/FI", &format!("PID eq {}", pid)])
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).contains(pid))
            .unwrap_or(false)
    }
}