Skip to main content

objectiveai_sdk/
process.rs

1//! Process-management helpers that pair with [`crate::lockfile`]'s owner
2//! lookups: given a pid (e.g. from [`crate::lockfile::owners`] /
3//! [`crate::lockfile::owners_in_tree`]), ask the OS to terminate it —
4//! plus the repo-wide [`no_window`] spawn hygiene.
5
6/// Windows `CREATE_NO_WINDOW`: spawn the child without a console
7/// window. Our services are windowless (daemon, laboratory host, db
8/// supervisor, the viewer shell), so every console-subsystem child
9/// they spawn — podman, postgres, plugins, tools, runners, the cli
10/// re-execing itself — otherwise allocates and FLASHES its own
11/// console at the user. Applied at every runtime spawn site in the
12/// repository; no-op off Windows.
13#[cfg(any(
14    feature = "http",
15    feature = "mcp",
16    feature = "cli-executor",
17    feature = "lockfile",
18    feature = "subprocess-reaper"
19))]
20pub fn no_window(command: &mut tokio::process::Command) {
21    #[cfg(windows)]
22    {
23        use std::os::windows::process::CommandExt;
24        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
25        command.creation_flags(CREATE_NO_WINDOW);
26    }
27    #[cfg(not(windows))]
28    {
29        let _ = command;
30    }
31}
32
33
34/// The one-line stdout readiness handshake every persistent server the
35/// daemon spawns (db / api / mcp / viewer / laboratory host) emits the
36/// moment it is serving: `{"type":"ready","address":...}`. The daemon —
37/// which holds the child's stdout pipe for its whole life (the children
38/// are OS-leashed to it) — reads lines until this parses, caches the
39/// address, and keeps draining. `address` is the server's client
40/// connect coordinate (`http://…` for api/mcp, `postgresql://…` for
41/// db) or `None` for servers with no listener (viewer, laboratory
42/// host — they dial out; the line is pure readiness).
43///
44/// This replaced the old lockfile-readiness scheme: servers no longer
45/// publish locks (the daemon is their sole spawner and owns their
46/// lifetime), so there is nothing on disk to discover. The daemon's
47/// OWN lock is the one survivor — short-lived CLI processes need a
48/// rendezvous outside any pipe to find an already-running daemon.
49#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
50#[serde(tag = "type", rename = "ready")]
51pub struct ServerReady {
52    pub address: Option<String>,
53}
54
55/// Print the readiness line to stdout and flush. UNCONDITIONAL by
56/// contract — never behind a suppress-output flag: the spawner blocks
57/// on this line, and the daemon's persistent drain makes any later
58/// stray writes harmless.
59pub fn print_ready(address: Option<&str>) {
60    use std::io::Write;
61    let line = serde_json::to_string(&ServerReady {
62        address: address.map(str::to_string),
63    })
64    .expect("ServerReady serializes");
65    let mut stdout = std::io::stdout().lock();
66    let _ = writeln!(stdout, "{line}");
67    let _ = stdout.flush();
68}
69
70/// Parse one stdout line as the readiness handshake. `None` for
71/// anything else (servers may print other lines; the reader skips
72/// them).
73pub fn parse_ready(line: &str) -> Option<ServerReady> {
74    serde_json::from_str(line.trim()).ok()
75}
76
77/// Send a terminate to `pid` — Unix `SIGTERM`, Windows `TerminateProcess`.
78/// Returns 1 if a live process with that pid was signalled, 0 otherwise
79/// (no such process, or the signal/open failed). Idempotent and
80/// best-effort: killing an already-dead pid is a 0, not an error.
81///
82/// Gated on the two features that carry the nix / windows-sys deps —
83/// the module itself exists for every subprocess-spawning feature
84/// (see the `no_window` gate).
85#[cfg(all(unix, any(feature = "lockfile", feature = "subprocess-reaper")))]
86pub fn kill_pid(pid: u32) -> usize {
87    // SAFETY: `kill(2)` with a valid signal number is sound — it only
88    // checks the target's existence and posts a signal, touching no
89    // memory. `SIGTERM` to a nonexistent pid returns -1 (ESRCH), which
90    // we map to 0.
91    let rc = unsafe { nix::libc::kill(pid as nix::libc::pid_t, nix::libc::SIGTERM) };
92    if rc == 0 { 1 } else { 0 }
93}
94
95#[cfg(all(windows, any(feature = "lockfile", feature = "subprocess-reaper")))]
96pub fn kill_pid(pid: u32) -> usize {
97    use windows_sys::Win32::Foundation::CloseHandle;
98    use windows_sys::Win32::System::Threading::{
99        OpenProcess, PROCESS_TERMINATE, TerminateProcess,
100    };
101    // SAFETY: `OpenProcess` returns null on failure (no such pid, or no
102    // rights) — we check before use. `TerminateProcess` and `CloseHandle`
103    // operate only on the handle we just opened; the handle is closed on
104    // every path.
105    unsafe {
106        let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
107        if handle.is_null() {
108            return 0;
109        }
110        let ok = TerminateProcess(handle, 1);
111        CloseHandle(handle);
112        if ok != 0 { 1 } else { 0 }
113    }
114}