openlatch-client 0.1.6

The open-source security layer for AI agents — client forwarder
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
/// Daemon lifecycle commands: start, stop, restart.
///
/// Provides OS-aware process management:
/// - Unix: `process_group(0)` for clean background spawning
/// - Windows: `CREATE_NO_WINDOW` to suppress console windows
///
/// All path references use `config::openlatch_dir()` per PLAT-02.
use std::process::Stdio;

use crate::cli::output::OutputConfig;
use crate::cli::StartArgs;
use crate::config;
use crate::error::{OlError, ERR_DAEMON_START_FAILED, ERR_INVALID_CONFIG};

/// Resolve and emit the observability-subsystem status line to daemon.log.
///
/// Called once per daemon start, right after `log_startup`. Records whether
/// telemetry + crash reports are active and which rule decided each — so
/// operators grepping daemon.log can confirm at a glance whether events and
/// panics will be sent upstream. Never logs the PostHog key or Sentry DSN.
pub(crate) fn log_observability_status_from_env() {
    let dir = config::openlatch_dir();

    let telemetry_consent = crate::telemetry::consent::resolve(&dir.join("telemetry.json"));
    let baked_key_present = crate::telemetry::network::key_is_present();
    let telemetry_enabled = telemetry_consent.enabled() && baked_key_present;
    let telemetry_decided_by = if !baked_key_present {
        "NoBakedKey".to_string()
    } else {
        format!("{:?}", telemetry_consent.decided_by)
    };

    #[cfg(feature = "crash-report")]
    let (crash_report_enabled, crash_report_decided_by) = {
        let resolved = crate::crash_report::current_state(&dir);
        (resolved.enabled(), format!("{:?}", resolved.decided_by))
    };
    #[cfg(not(feature = "crash-report"))]
    let (crash_report_enabled, crash_report_decided_by) = (false, "BuildExcluded".to_string());

    crate::logging::daemon_log::log_observability_status(
        telemetry_enabled,
        &telemetry_decided_by,
        crash_report_enabled,
        &crash_report_decided_by,
    );
}

/// Run the `openlatch start` command.
///
/// Starts the daemon in the background, or in foreground if `--foreground` is set.
/// Idempotent: if the daemon is already running, exits 0 with a message.
///
/// # Errors
///
/// Returns an error if the daemon fails to spawn.
pub fn run_start(args: &StartArgs, output: &OutputConfig) -> Result<(), OlError> {
    let cfg = config::Config::load(args.port, None, false)?;

    // Idempotency: check if daemon is already running
    if let Some(pid) = read_pid_file() {
        if is_process_alive(pid) {
            output.print_info(&format!("Daemon is already running (PID {pid})"));
            return Ok(());
        }
    }

    let token = load_or_generate_token()?;

    if args.foreground {
        run_daemon_foreground(cfg.port, &token)?;
    } else {
        let pid = spawn_daemon_background(cfg.port, &token)?;
        if !wait_for_health(cfg.port, 5) {
            return Err(OlError::new(
                ERR_DAEMON_START_FAILED,
                format!("Daemon spawned (PID {pid}) but health check failed within 5s"),
            )
            .with_suggestion("Check ~/.openlatch/logs/daemon.log for errors.")
            .with_docs("https://docs.openlatch.ai/errors/OL-1502"));
        }
        output.print_step(&format!("Daemon started on port {} (PID {pid})", cfg.port));
    }

    Ok(())
}

/// Run the `openlatch stop` command.
///
/// Sends a graceful shutdown request to the daemon via POST /shutdown.
/// Idempotent: if the daemon is not running, exits 0 with a message.
///
/// # Errors
///
/// Returns an error if the shutdown request fails.
pub fn run_stop(output: &OutputConfig) -> Result<(), OlError> {
    let Some(pid) = read_pid_file() else {
        output.print_info("Daemon is not running");
        return Ok(());
    };

    if !is_process_alive(pid) {
        output.print_info("Daemon is not running");
        // Clean up stale PID file
        let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.pid"));
        return Ok(());
    }

    // Load config to get the port
    let cfg = config::Config::load(None, None, false)?;

    // Prefer graceful shutdown via POST /shutdown endpoint (works cross-platform, DAEM-14)
    let token = load_or_generate_token().unwrap_or_default();
    if send_shutdown_request(cfg.port, &token) {
        // Wait for process to exit (poll PID file deletion, 5s timeout)
        let start = std::time::Instant::now();
        while start.elapsed() < std::time::Duration::from_secs(5) {
            if !is_process_alive(pid) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(200));
        }
    }

    // Clean up PID file if process is gone
    if !is_process_alive(pid) {
        let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.pid"));
        output.print_step("Daemon stopped");
        return Ok(());
    }

    // Graceful shutdown didn't work — force kill
    force_kill(pid);
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
    while std::time::Instant::now() < deadline && is_process_alive(pid) {
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    if is_process_alive(pid) {
        return Err(OlError::new(
            ERR_INVALID_CONFIG,
            format!("Failed to stop daemon (pid {pid}); process still running"),
        )
        .with_suggestion("Kill the process manually and remove ~/.openlatch/daemon.pid."));
    }

    let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.pid"));
    output.print_step("Daemon stopped");
    Ok(())
}

/// Run the `openlatch restart` command.
///
/// Stops the daemon, waits for it to exit, then starts it again.
/// Per Pitfall 4 from RESEARCH.md: waits for stop to complete before starting.
///
/// # Errors
///
/// Returns an error if start fails.
pub fn run_restart(output: &OutputConfig) -> Result<(), OlError> {
    // Stop — ignore "not running" case
    run_stop(output)?;

    // Wait until PID file is gone or health check fails before starting
    let timeout = std::time::Duration::from_secs(5);
    let start = std::time::Instant::now();
    let cfg = config::Config::load(None, None, false)?;

    while start.elapsed() < timeout {
        let pid_file_gone = read_pid_file().is_none();
        let health_down = !check_health(cfg.port);
        if pid_file_gone || health_down {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }

    let start_args = StartArgs {
        foreground: false,
        port: None,
    };
    run_start(&start_args, output)
}

/// Spawn the daemon as a detached background process.
///
/// Gets the path to the current executable and re-executes with `daemon start --foreground`.
///
/// Platform-specific detachment:
/// - Unix: `process_group(0)` creates a new process group (survives parent exit)
/// - Windows: `CREATE_NO_WINDOW` suppresses the console window
///
/// Writes PID to `config::openlatch_dir().join("daemon.pid")` per PLAT-02.
///
/// # Errors
///
/// Returns an error if the child process cannot be spawned or PID file cannot be written.
pub fn spawn_daemon_background(port: u16, token: &str) -> Result<u32, OlError> {
    let exe = std::env::current_exe().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot locate current executable: {e}"),
        )
    })?;

    #[cfg(unix)]
    let child = {
        use std::os::unix::process::CommandExt;
        std::process::Command::new(&exe)
            .args([
                "daemon",
                "start",
                "--foreground",
                "--port",
                &port.to_string(),
            ])
            .env("OPENLATCH_TOKEN", token)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .process_group(0)
            .spawn()
            .map_err(|e| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("Failed to spawn daemon process: {e}"),
                )
                .with_suggestion("Check that the openlatch binary is executable.")
            })?
    };

    #[cfg(windows)]
    let child = {
        use std::os::windows::process::CommandExt;
        // CREATE_NO_WINDOW: suppress console window for background daemon
        // CREATE_NEW_PROCESS_GROUP: detach from parent so daemon survives parent exit
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
        std::process::Command::new(&exe)
            .args([
                "daemon",
                "start",
                "--foreground",
                "--port",
                &port.to_string(),
            ])
            .env("OPENLATCH_TOKEN", token)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP)
            .spawn()
            .map_err(|e| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("Failed to spawn daemon process: {e}"),
                )
                .with_suggestion("Check that the openlatch binary is executable.")
            })?
    };

    let pid = child.id();

    // PID file is written by the child process in run_daemon_foreground(),
    // not here — writing it here causes the child's idempotency check to
    // see its own PID and exit immediately.

    Ok(pid)
}

/// Read the daemon PID from the PID file.
///
/// Returns `None` if the file doesn't exist or can't be parsed.
pub(crate) fn read_pid_file() -> Option<u32> {
    let pid_path = config::openlatch_dir().join("daemon.pid");
    let content = std::fs::read_to_string(&pid_path).ok()?;
    content.trim().parse::<u32>().ok()
}

/// Check whether a process with the given PID is alive.
///
/// Uses OS-appropriate process existence checks.
/// Per T-02-06: verifies the process exists, not just the PID file.
pub(crate) fn is_process_alive(pid: u32) -> bool {
    // PID 0 is kernel-reserved on every platform and never a valid daemon PID.
    // On Unix, `kill(0, 0)` would additionally target the caller's process group
    // rather than probe PID 0 — guard so stale-PID detection stays correct.
    if pid == 0 {
        return false;
    }

    #[cfg(unix)]
    {
        // send signal 0 — tests process existence without actually sending a signal
        let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
        result == 0
    }

    #[cfg(windows)]
    {
        // Use OpenProcess to check if the process exists
        let handle = unsafe {
            winapi::um::processthreadsapi::OpenProcess(
                winapi::um::winnt::PROCESS_QUERY_INFORMATION,
                0,
                pid,
            )
        };
        if handle.is_null() {
            return false;
        }
        let mut exit_code: u32 = 0;
        let alive = unsafe {
            winapi::um::processthreadsapi::GetExitCodeProcess(handle, &mut exit_code) != 0
                && exit_code == winapi::um::minwinbase::STILL_ACTIVE
        };
        unsafe { winapi::um::handleapi::CloseHandle(handle) };
        alive
    }

    // Fallback for non-unix, non-windows (should not happen in practice)
    #[cfg(not(any(unix, windows)))]
    {
        let _ = pid;
        false
    }
}

/// Send a graceful shutdown request to the daemon via POST /shutdown.
///
/// Returns true if the request was sent successfully.
pub(crate) fn send_shutdown_request(port: u16, token: &str) -> bool {
    let url = format!("http://127.0.0.1:{port}/shutdown");
    let client = reqwest::blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(2))
        .build();

    match client {
        Ok(c) => c
            .post(&url)
            .header("Authorization", format!("Bearer {token}"))
            .send()
            .map(|r| r.status().is_success() || r.status() == reqwest::StatusCode::GONE)
            .unwrap_or(false),
        Err(_) => false,
    }
}

/// Force-kill the daemon process as a last resort when graceful shutdown fails.
pub(crate) fn force_kill(pid: u32) {
    #[cfg(unix)]
    unsafe {
        libc::kill(pid as libc::pid_t, libc::SIGTERM);
    }

    #[cfg(windows)]
    {
        let _ = std::process::Command::new("taskkill")
            .args(["/F", "/T", "/PID", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

/// Wait for the daemon's /health endpoint to return 200.
///
/// Returns true if health check passed within the timeout, false otherwise.
pub(crate) fn wait_for_health(port: u16, timeout_secs: u64) -> bool {
    let url = format!("http://127.0.0.1:{port}/health");
    let start = std::time::Instant::now();
    let timeout = std::time::Duration::from_secs(timeout_secs);

    while start.elapsed() < timeout {
        if let Ok(resp) = reqwest::blocking::get(&url) {
            if resp.status().is_success() {
                return true;
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
    false
}

/// Check if the daemon's /health endpoint is reachable (non-blocking, single attempt).
pub(crate) fn check_health(port: u16) -> bool {
    let url = format!("http://127.0.0.1:{port}/health");
    reqwest::blocking::get(url)
        .map(|r| r.status().is_success())
        .unwrap_or(false)
}

/// Build the credential store chain (keyring -> env -> file) for the daemon
/// to hand to the cloud worker.
pub(crate) fn build_credential_store() -> std::sync::Arc<dyn crate::auth::CredentialStore> {
    let agent_id = config::Config::load(None, None, false)
        .ok()
        .and_then(|c| c.agent_id)
        .unwrap_or_default();
    let keyring = Box::new(crate::auth::KeyringCredentialStore::new());
    let file = Box::new(crate::auth::FileCredentialStore::new(
        config::openlatch_dir().join("credentials.enc"),
        agent_id,
    ));
    std::sync::Arc::new(crate::auth::FallbackCredentialStore::new(keyring, file))
}

/// Load the daemon token or generate a new one if missing.
fn load_or_generate_token() -> Result<String, OlError> {
    let ol_dir = config::openlatch_dir();
    config::ensure_token(&ol_dir)
}

/// Start the daemon in foreground mode (blocking call).
///
/// Creates a tokio runtime and runs the daemon server directly.
fn run_daemon_foreground(port: u16, token: &str) -> Result<(), OlError> {
    // D-11: self-heal old installs whose config.toml pre-dates the
    // agent_id field. Idempotent — if already present, reads and returns
    // the existing ID without touching the file.
    let config_path = config::openlatch_dir().join("config.toml");
    if config_path.exists() {
        let _ = config::ensure_agent_id(&config_path);
    }

    let mut cfg = config::Config::load(Some(port), None, true)?;
    cfg.foreground = true;

    let rt = tokio::runtime::Runtime::new().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Failed to create async runtime: {e}"),
        )
    })?;

    let token_owned = token.to_string();
    let pid = std::process::id();

    // Tag this process as the daemon in Sentry BEFORE any tokio work runs.
    // Reached via `daemon start --foreground` re-invoking the same binary,
    // so main()'s earlier `enrich_cli_scope` tagged us as "cli" — this
    // overwrites it so panics in daemon bootstrap carry the correct tag.
    #[cfg(feature = "crash-report")]
    crate::crash_report::enrich_daemon_scope(cfg.port, pid);

    rt.block_on(async move {
        use crate::daemon;
        use crate::envelope;
        use crate::logging;
        use crate::privacy;

        let _guard = logging::daemon_log::init_daemon_logging(&cfg.log_dir, cfg.foreground);

        if let Ok(deleted) = logging::cleanup_old_logs(&cfg.log_dir, cfg.retention_days) {
            if deleted > 0 {
                tracing::info!(deleted = deleted, "cleaned up old log files");
            }
        }

        privacy::init_filter(&cfg.extra_patterns);

        // Write PID file so status/stop can find us
        let pid_path = config::openlatch_dir().join("daemon.pid");
        if let Err(e) = std::fs::write(&pid_path, pid.to_string()) {
            tracing::warn!(error = %e, "failed to write PID file");
        }

        logging::daemon_log::log_startup(
            env!("CARGO_PKG_VERSION"),
            cfg.port,
            pid,
            envelope::os_string(),
            envelope::arch_string(),
        );
        log_observability_status_from_env();

        // Daemon foreground has no parent `OutputConfig` — construct a minimal
        // human-mode config so the header honors TTY color detection.
        let header_output = crate::cli::output::OutputConfig {
            format: crate::cli::output::OutputFormat::Human,
            verbose: false,
            debug: false,
            quiet: false,
            color: std::io::IsTerminal::is_terminal(&std::io::stderr()),
        };
        crate::cli::header::print(
            &header_output,
            &[
                &format!("listening 127.0.0.1:{}", cfg.port),
                &format!("pid {pid}"),
            ],
        );

        let credential_store = build_credential_store();
        match daemon::start_server(cfg.clone(), token_owned, Some(credential_store)).await {
            Ok((uptime_secs, events)) => {
                eprintln!(
                    "openlatch daemon stopped \u{2022} uptime {} \u{2022} {} events processed",
                    daemon::format_uptime(uptime_secs),
                    events
                );
            }
            Err(e) => {
                tracing::error!(error = %e, "daemon exited with error");
                eprintln!("Error: daemon exited unexpectedly: {e}");
            }
        }

        // Clean up PID file on exit
        let _ = std::fs::remove_file(&pid_path);
    });

    // Flush pending Sentry events before the process winds down. Covers
    // panics captured in the final few ms of the server loop where the
    // guard's Drop might otherwise race OS process teardown.
    #[cfg(feature = "crash-report")]
    crate::crash_report::flush(std::time::Duration::from_secs(2));

    Ok(())
}