Skip to main content

lean_ctx/
daemon_client.rs

1use anyhow::{Context, Result};
2use tokio::io::{AsyncReadExt, AsyncWriteExt};
3
4use crate::daemon;
5use crate::ipc;
6
7/// Send an HTTP request to the daemon over the IPC channel.
8/// Returns the response body as a string.
9pub async fn daemon_request(method: &str, path: &str, body: &str) -> Result<String> {
10    use std::time::Duration;
11    use tokio::time::timeout;
12
13    const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
14    const IO_TIMEOUT: Duration = Duration::from_secs(10);
15
16    let addr = daemon::daemon_addr();
17    if !addr.is_listening() {
18        anyhow::bail!(
19            "Daemon endpoint not found at {}. Is the daemon running?",
20            addr.display()
21        );
22    }
23
24    let request = format_http_request(method, path, body);
25
26    #[cfg(unix)]
27    {
28        let mut stream = timeout(CONNECT_TIMEOUT, ipc::connect(&addr))
29            .await
30            .with_context(|| {
31                format!(
32                    "connect to daemon timed out ({}s)",
33                    CONNECT_TIMEOUT.as_secs()
34                )
35            })?
36            .with_context(|| format!("cannot connect to daemon at {}", addr.display()))?;
37
38        timeout(IO_TIMEOUT, stream.write_all(request.as_bytes()))
39            .await
40            .context("write to daemon timed out")?
41            .context("failed to write request to daemon")?;
42
43        let mut response_buf = Vec::with_capacity(4096);
44        timeout(IO_TIMEOUT, stream.read_to_end(&mut response_buf))
45            .await
46            .context("read from daemon timed out")?
47            .context("failed to read response from daemon")?;
48
49        parse_http_response(&response_buf)
50    }
51
52    #[cfg(windows)]
53    {
54        let mut stream = timeout(CONNECT_TIMEOUT, ipc::connect(&addr))
55            .await
56            .with_context(|| {
57                format!(
58                    "connect to daemon timed out ({}s)",
59                    CONNECT_TIMEOUT.as_secs()
60                )
61            })?
62            .with_context(|| format!("cannot connect to daemon at {}", addr.display()))?;
63
64        timeout(IO_TIMEOUT, stream.write_all(request.as_bytes()))
65            .await
66            .context("write to daemon timed out")?
67            .context("failed to write request to daemon")?;
68
69        let mut response_buf = Vec::with_capacity(4096);
70        timeout(IO_TIMEOUT, stream.read_to_end(&mut response_buf))
71            .await
72            .context("read from daemon timed out")?
73            .context("failed to read response from daemon")?;
74
75        parse_http_response(&response_buf)
76    }
77}
78
79/// Check if the daemon is reachable by hitting /health.
80pub async fn daemon_health_check() -> bool {
81    match daemon_request("GET", "/health", "").await {
82        Ok(body) => body.trim() == "ok",
83        Err(_) => false,
84    }
85}
86
87/// Call a tool on the daemon's REST API.
88pub async fn daemon_tool_call(name: &str, arguments: Option<&serde_json::Value>) -> Result<String> {
89    let body = serde_json::json!({
90        "name": name,
91        "arguments": arguments,
92    });
93    daemon_request("POST", "/v1/tools/call", &body.to_string()).await
94}
95
96fn format_http_request(method: &str, path: &str, body: &str) -> String {
97    if body.is_empty() {
98        format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
99    } else {
100        let content_length = body.len();
101        format!(
102            "{method} {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {content_length}\r\nConnection: close\r\n\r\n{body}"
103        )
104    }
105}
106
107fn parse_http_response(raw: &[u8]) -> Result<String> {
108    let response_str = std::str::from_utf8(raw).context("daemon response is not valid UTF-8")?;
109
110    let Some(header_end) = response_str.find("\r\n\r\n") else {
111        anyhow::bail!("malformed HTTP response from daemon (no header boundary)");
112    };
113
114    let headers = &response_str[..header_end];
115    let body = &response_str[header_end + 4..];
116
117    let status_line = headers.lines().next().unwrap_or("");
118    let status_code = status_line
119        .split_whitespace()
120        .nth(1)
121        .and_then(|s| s.parse::<u16>().ok())
122        .unwrap_or(0);
123
124    if status_code >= 400 {
125        anyhow::bail!("daemon returned HTTP {status_code}: {body}");
126    }
127
128    Ok(body.to_string())
129}
130
131/// Attempt to connect to the daemon. Returns `None` if not running.
132pub async fn try_daemon_request(method: &str, path: &str, body: &str) -> Option<String> {
133    if !daemon::is_daemon_running() {
134        return None;
135    }
136    daemon_request(method, path, body).await.ok()
137}
138
139/// Tell a *running* daemon to drop its in-memory read cache (`SessionCache`).
140/// Returns `true` if a daemon was reached. Never auto-starts a daemon — if none
141/// is running there is no cache to flush. Force-rebuild CLI commands call this so
142/// `ctx_read` map/signatures stop serving pre-rebuild output from the daemon's
143/// long-lived cache, which CLI index rebuilds otherwise can't reach (#420).
144pub fn notify_cache_clear() -> bool {
145    if !daemon::is_daemon_running() {
146        return false;
147    }
148    let Ok(rt) = tokio::runtime::Runtime::new() else {
149        return false;
150    };
151    let body = serde_json::json!({
152        "name": "ctx_cache",
153        "arguments": { "action": "clear" },
154    });
155    rt.block_on(async {
156        try_daemon_request("POST", "/v1/tools/call", &body.to_string())
157            .await
158            .is_some()
159    })
160}
161
162/// Blocking helper for CLI commands: routes a tool call through the daemon.
163///
164/// Returns `None` if no daemon can serve the call (caller then renders the tool
165/// locally / standalone). Behaviour splits on caller identity:
166///
167/// - **Normal CLI invocation**: connects to a running daemon, and *auto-starts*
168///   one if none is listening (so the long-lived `LeanCtxServer` state — caches,
169///   indexes, detectors — is reused across commands).
170/// - **Shadow-mode hook child** (`LEAN_CTX_HOOK_CHILD` set): *connect-only*. It
171///   reuses an already-running daemon for full parity (the `ready` fast-path
172///   below routes straight through `/v1/tools/call` → `call_tool_guarded`, so the
173///   in-memory `LoopDetector`, correction-loop auto-degrade, bounce tracker and
174///   adaptive thresholds all fire on the daemon's long-lived state — #566), but
175///   it MUST NEVER auto-start a daemon. A hook fires once per intercepted
176///   read/grep as a fresh process; auto-starting from there would spawn daemons
177///   uncontrollably. With no live daemon it returns `None` and the caller falls
178///   back to the enriched standalone path (disk-backed learning sinks + Context
179///   IR from #550/#569).
180#[allow(clippy::needless_pass_by_value)]
181pub fn try_daemon_tool_call_blocking(
182    name: &str,
183    arguments: Option<serde_json::Value>,
184) -> Option<String> {
185    use std::time::Duration;
186
187    let rt = tokio::runtime::Runtime::new().ok()?;
188
189    let addr = daemon::daemon_addr();
190    let mut ready = addr.is_listening() && rt.block_on(async { daemon_health_check().await });
191
192    if !ready {
193        // Connect-only for shadow-mode hooks (#566): a hook child reaches a live
194        // daemon via the `ready` fast-path above (full detector parity), but when
195        // none is listening it must bail to the standalone fallback instead of
196        // auto-starting one. This guard MUST stay inside `if !ready` — hoisting it
197        // to the top of the function would also block hooks from reusing a running
198        // daemon, silently regressing loop/bounce/adaptive parity.
199        if crate::core::runtime_flags::hook_child_enabled() {
200            return None;
201        }
202
203        let lock = crate::core::startup_guard::try_acquire_lock(
204            "daemon-start",
205            Duration::from_millis(1200),
206            Duration::from_secs(5),
207        );
208
209        if let Some(g) = lock {
210            g.touch();
211            let mut did_start = false;
212
213            if !daemon::is_daemon_running() {
214                if daemon::start_daemon(&[]).is_ok() {
215                    did_start = true;
216                } else {
217                    return None;
218                }
219            }
220
221            for _ in 0..60 {
222                if addr.is_listening() && rt.block_on(async { daemon_health_check().await }) {
223                    ready = true;
224                    break;
225                }
226                std::thread::sleep(Duration::from_millis(50));
227            }
228
229            if ready && did_start && crate::core::protocol::meta_visible() {
230                eprintln!("\x1b[2m▸ daemon auto-started\x1b[0m");
231            }
232        } else {
233            for _ in 0..60 {
234                if addr.is_listening() && rt.block_on(async { daemon_health_check().await }) {
235                    ready = true;
236                    break;
237                }
238                std::thread::sleep(Duration::from_millis(50));
239            }
240        }
241    }
242
243    if !ready {
244        return None;
245    }
246
247    if let Some(out) = rt.block_on(async { daemon_tool_call(name, arguments.as_ref()).await.ok() })
248    {
249        return Some(out);
250    }
251
252    for _ in 0..5 {
253        std::thread::sleep(Duration::from_millis(50));
254        if let Some(out) =
255            rt.block_on(async { daemon_tool_call(name, arguments.as_ref()).await.ok() })
256        {
257            return Some(out);
258        }
259    }
260
261    None
262}
263
264fn unwrap_mcp_tool_text(body: &str) -> Option<String> {
265    let v: serde_json::Value = serde_json::from_str(body).ok()?;
266    let result = v.get("result")?;
267
268    if let Some(content) = result.get("content").and_then(|c| c.as_array()) {
269        let mut texts: Vec<String> = Vec::new();
270        for item in content {
271            if let Some(text) = item.get("text").and_then(|t| t.as_str())
272                && !text.is_empty()
273            {
274                texts.push(text.to_string());
275            }
276        }
277        if !texts.is_empty() {
278            return Some(texts.join("\n"));
279        }
280    }
281
282    if let Some(text) = result.get("text").and_then(|t| t.as_str()) {
283        return Some(text.to_string());
284    }
285
286    result.as_str().map(std::string::ToString::to_string)
287}
288
289/// Like `try_daemon_tool_call_blocking`, but unwraps MCP JSON responses to text for CLI output.
290pub fn try_daemon_tool_call_blocking_text(
291    name: &str,
292    arguments: Option<serde_json::Value>,
293) -> Option<String> {
294    let body = try_daemon_tool_call_blocking(name, arguments)?;
295    let trimmed = body.trim_start();
296    if !trimmed.starts_with('{') {
297        return Some(body);
298    }
299    Some(unwrap_mcp_tool_text(&body).unwrap_or(body))
300}