Skip to main content

lean_ctx/
daemon_client.rs

1use anyhow::{Context, Result};
2use std::sync::OnceLock;
3use std::time::Duration;
4use tokio::io::{AsyncReadExt, AsyncWriteExt};
5use tokio::runtime::Runtime;
6
7use crate::daemon;
8use crate::ipc;
9
10static DELIVERY_RUNTIME: OnceLock<Result<Runtime, String>> = OnceLock::new();
11
12/// Cross-agent delivery lookups are an optional cache tier. They must never
13/// inherit the daemon client's normal control-plane timeout on an interactive
14/// read or shell path.
15const BEST_EFFORT_DELIVERY_IPC_TIMEOUT: Duration = Duration::from_millis(250);
16
17fn delivery_runtime() -> Result<&'static Runtime> {
18    match DELIVERY_RUNTIME.get_or_init(|| Runtime::new().map_err(|error| error.to_string())) {
19        Ok(runtime) => Ok(runtime),
20        Err(error) => Err(anyhow::anyhow!("initialize delivery IPC runtime: {error}")),
21    }
22}
23
24/// Safely run an async future on the delivery runtime from any thread context.
25/// When called from inside a tokio runtime (e.g. tool handler async pipeline /
26/// prefetch re-entry), spawns a scoped thread to avoid "Cannot start a runtime
27/// from within a runtime". When called from outside (CLI), blocks directly.
28fn delivery_block_on<F, O>(fut: F) -> Option<O>
29where
30    F: std::future::Future<Output = O> + Send,
31    O: Send,
32{
33    let rt = delivery_runtime().ok()?;
34    if tokio::runtime::Handle::try_current().is_ok() {
35        let mut result = None;
36        std::thread::scope(|s| {
37            s.spawn(|| {
38                result = Some(rt.block_on(fut));
39            });
40        });
41        result
42    } else {
43        Some(rt.block_on(fut))
44    }
45}
46
47/// Send an HTTP request to the daemon over the IPC channel.
48/// Returns the response body as a string.
49pub async fn daemon_request(method: &str, path: &str, body: &str) -> Result<String> {
50    use tokio::time::timeout;
51
52    const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
53    const IO_TIMEOUT: Duration = Duration::from_secs(10);
54
55    let addr = daemon::daemon_addr();
56    if !addr.is_listening() {
57        anyhow::bail!(
58            "Daemon endpoint not found at {}. Is the daemon running?",
59            addr.display()
60        );
61    }
62
63    let request = format_http_request(method, path, body);
64
65    #[cfg(unix)]
66    {
67        let mut stream = timeout(CONNECT_TIMEOUT, ipc::connect(&addr))
68            .await
69            .with_context(|| {
70                format!(
71                    "connect to daemon timed out ({}s)",
72                    CONNECT_TIMEOUT.as_secs()
73                )
74            })?
75            .with_context(|| format!("cannot connect to daemon at {}", addr.display()))?;
76
77        timeout(IO_TIMEOUT, stream.write_all(request.as_bytes()))
78            .await
79            .context("write to daemon timed out")?
80            .context("failed to write request to daemon")?;
81
82        let mut response_buf = Vec::with_capacity(4096);
83        timeout(IO_TIMEOUT, stream.read_to_end(&mut response_buf))
84            .await
85            .context("read from daemon timed out")?
86            .context("failed to read response from daemon")?;
87
88        parse_http_response(&response_buf)
89    }
90
91    #[cfg(windows)]
92    {
93        let mut stream = timeout(CONNECT_TIMEOUT, ipc::connect(&addr))
94            .await
95            .with_context(|| {
96                format!(
97                    "connect to daemon timed out ({}s)",
98                    CONNECT_TIMEOUT.as_secs()
99                )
100            })?
101            .with_context(|| format!("cannot connect to daemon at {}", addr.display()))?;
102
103        timeout(IO_TIMEOUT, stream.write_all(request.as_bytes()))
104            .await
105            .context("write to daemon timed out")?
106            .context("failed to write request to daemon")?;
107
108        let mut response_buf = Vec::with_capacity(4096);
109        timeout(IO_TIMEOUT, stream.read_to_end(&mut response_buf))
110            .await
111            .context("read from daemon timed out")?
112            .context("failed to read response from daemon")?;
113
114        parse_http_response(&response_buf)
115    }
116}
117
118/// Check if the daemon is reachable by hitting /health.
119pub async fn daemon_health_check() -> bool {
120    match daemon_request("GET", "/health", "").await {
121        Ok(body) => body.trim() == "ok",
122        Err(_) => false,
123    }
124}
125
126/// Call a tool on the daemon's REST API.
127pub async fn daemon_tool_call(name: &str, arguments: Option<&serde_json::Value>) -> Result<String> {
128    let body = serde_json::json!({
129        "name": name,
130        "arguments": arguments,
131    });
132    daemon_request("POST", "/v1/tools/call", &body.to_string()).await
133}
134
135fn format_http_request(method: &str, path: &str, body: &str) -> String {
136    if body.is_empty() {
137        format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
138    } else {
139        let content_length = body.len();
140        format!(
141            "{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}"
142        )
143    }
144}
145
146fn parse_http_response(raw: &[u8]) -> Result<String> {
147    let response_str = std::str::from_utf8(raw).context("daemon response is not valid UTF-8")?;
148
149    let Some(header_end) = response_str.find("\r\n\r\n") else {
150        anyhow::bail!("malformed HTTP response from daemon (no header boundary)");
151    };
152
153    let headers = &response_str[..header_end];
154    let body = &response_str[header_end + 4..];
155
156    let status_line = headers.lines().next().unwrap_or("");
157    let status_code = status_line
158        .split_whitespace()
159        .nth(1)
160        .and_then(|s| s.parse::<u16>().ok())
161        .unwrap_or(0);
162
163    if status_code >= 400 {
164        anyhow::bail!("daemon returned HTTP {status_code}: {body}");
165    }
166
167    Ok(body.to_string())
168}
169
170/// Attempt to connect to the daemon. Returns `None` if not running.
171pub async fn try_daemon_request(method: &str, path: &str, body: &str) -> Option<String> {
172    if !daemon::is_daemon_running() {
173        return None;
174    }
175    daemon_request(method, path, body).await.ok()
176}
177
178/// Tell a *running* daemon to drop its in-memory read cache (`SessionCache`).
179/// Returns `true` if a daemon was reached. Never auto-starts a daemon — if none
180/// is running there is no cache to flush. Force-rebuild CLI commands call this so
181/// `ctx_read` map/signatures stop serving pre-rebuild output from the daemon's
182/// long-lived cache, which CLI index rebuilds otherwise can't reach (#420).
183pub fn notify_cache_clear() -> bool {
184    if !daemon::is_daemon_running() {
185        return false;
186    }
187    let Ok(rt) = tokio::runtime::Runtime::new() else {
188        return false;
189    };
190    let body = serde_json::json!({
191        "name": "ctx_cache",
192        "arguments": { "action": "clear" },
193    });
194    rt.block_on(async {
195        try_daemon_request("POST", "/v1/tools/call", &body.to_string())
196            .await
197            .is_some()
198    })
199}
200
201/// Blocking helper for CLI commands: routes a tool call through the daemon.
202///
203/// Returns `None` if no daemon can serve the call (caller then renders the tool
204/// locally / standalone). Behaviour splits on caller identity:
205///
206/// - **Normal CLI invocation**: connects to a running daemon, and *auto-starts*
207///   one if none is listening (so the long-lived `LeanCtxServer` state — caches,
208///   indexes, detectors — is reused across commands).
209/// - **Shadow-mode hook child** (`LEAN_CTX_HOOK_CHILD` set): *connect-only*. It
210///   reuses an already-running daemon for full parity (the `ready` fast-path
211///   below routes straight through `/v1/tools/call` → `call_tool_guarded`, so the
212///   in-memory `LoopDetector`, correction-loop auto-degrade, bounce tracker and
213///   adaptive thresholds all fire on the daemon's long-lived state — #566), but
214///   it MUST NEVER auto-start a daemon. A hook fires once per intercepted
215///   read/grep as a fresh process; auto-starting from there would spawn daemons
216///   uncontrollably. With no live daemon it returns `None` and the caller falls
217///   back to the enriched standalone path (disk-backed learning sinks + Context
218///   IR from #550/#569).
219#[allow(clippy::needless_pass_by_value)]
220pub fn try_daemon_tool_call_blocking(
221    name: &str,
222    arguments: Option<serde_json::Value>,
223) -> Option<String> {
224    use std::time::Duration;
225
226    if std::env::var_os("__LEAN_CTX_NO_DAEMON").is_some() {
227        return None;
228    }
229
230    let rt = Runtime::new().ok()?;
231
232    let addr = daemon::daemon_addr();
233    let mut ready = addr.is_listening() && rt.block_on(async { daemon_health_check().await });
234
235    if !ready {
236        // Connect-only for shadow-mode hooks (#566): a hook child reaches a live
237        // daemon via the `ready` fast-path above (full detector parity), but when
238        // none is listening it must bail to the standalone fallback instead of
239        // auto-starting one. This guard MUST stay inside `if !ready` — hoisting it
240        // to the top of the function would also block hooks from reusing a running
241        // daemon, silently regressing loop/bounce/adaptive parity.
242        if crate::core::runtime_flags::hook_child_enabled() {
243            return None;
244        }
245
246        let lock = crate::core::startup_guard::try_acquire_lock(
247            "daemon-start",
248            Duration::from_millis(1200),
249            Duration::from_secs(5),
250        );
251
252        if let Some(g) = lock {
253            g.touch();
254            let mut did_start = false;
255
256            if !daemon::is_daemon_running() {
257                if daemon::start_daemon(&[]).is_ok() {
258                    did_start = true;
259                } else {
260                    return None;
261                }
262            }
263
264            for _ in 0..60 {
265                if addr.is_listening() && rt.block_on(async { daemon_health_check().await }) {
266                    ready = true;
267                    break;
268                }
269                std::thread::sleep(Duration::from_millis(50));
270            }
271
272            if ready && did_start && crate::core::protocol::meta_visible() {
273                eprintln!("\x1b[2m▸ daemon auto-started\x1b[0m");
274            }
275        } else {
276            for _ in 0..60 {
277                if addr.is_listening() && rt.block_on(async { daemon_health_check().await }) {
278                    ready = true;
279                    break;
280                }
281                std::thread::sleep(Duration::from_millis(50));
282            }
283        }
284    }
285
286    if !ready {
287        return None;
288    }
289
290    if let Some(out) = rt.block_on(async { daemon_tool_call(name, arguments.as_ref()).await.ok() })
291    {
292        return Some(out);
293    }
294
295    for _ in 0..5 {
296        std::thread::sleep(Duration::from_millis(50));
297        if let Some(out) =
298            rt.block_on(async { daemon_tool_call(name, arguments.as_ref()).await.ok() })
299        {
300            return Some(out);
301        }
302    }
303
304    None
305}
306
307fn unwrap_mcp_tool_text(body: &str) -> Option<String> {
308    let v: serde_json::Value = serde_json::from_str(body).ok()?;
309    let result = v.get("result")?;
310
311    if let Some(content) = result.get("content").and_then(|c| c.as_array()) {
312        let mut texts: Vec<String> = Vec::new();
313        for item in content {
314            if let Some(text) = item.get("text").and_then(|t| t.as_str())
315                && !text.is_empty()
316            {
317                texts.push(text.to_string());
318            }
319        }
320        if !texts.is_empty() {
321            return Some(texts.join("\n"));
322        }
323    }
324
325    if let Some(text) = result.get("text").and_then(|t| t.as_str()) {
326        return Some(text.to_string());
327    }
328
329    result.as_str().map(std::string::ToString::to_string)
330}
331
332/// Like `try_daemon_tool_call_blocking`, but unwraps MCP JSON responses to text for CLI output.
333pub fn try_daemon_tool_call_blocking_text(
334    name: &str,
335    arguments: Option<serde_json::Value>,
336) -> Option<String> {
337    let body = try_daemon_tool_call_blocking(name, arguments)?;
338    let trimmed = body.trim_start();
339    if !trimmed.starts_with('{') {
340        return Some(body);
341    }
342    Some(unwrap_mcp_tool_text(&body).unwrap_or(body))
343}
344
345/// Check the daemon's cross-agent delivery registry for a content hash.
346/// Returns `None` if daemon unreachable or no hit. Connect-only — never
347/// auto-starts a daemon (delivery is best-effort).
348pub fn try_delivery_check_blocking(
349    blake3: &[u8; 12],
350    mtime: u64,
351    path: &str,
352    requester_agent_id: Option<&str>,
353    requester_conversation_id: Option<&str>,
354) -> Option<crate::core::ocla::types::DeliveryRecord> {
355    if !daemon::is_daemon_running() {
356        return None;
357    }
358    let body = serde_json::json!({
359        "blake3": blake3,
360        "mtime": mtime,
361        "path": path,
362        "requester_agent_id": requester_agent_id,
363        "requester_conversation_id": requester_conversation_id,
364    });
365    let body_str = body.to_string();
366    let resp = delivery_block_on(async move {
367        tokio::time::timeout(
368            BEST_EFFORT_DELIVERY_IPC_TIMEOUT,
369            try_daemon_request("POST", "/ocla/v1/delivery/check", &body_str),
370        )
371        .await
372        .ok()
373        .flatten()
374    })??;
375    let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
376    if !v.get("hit")?.as_bool()? {
377        return None;
378    }
379    Some(crate::core::ocla::types::DeliveryRecord {
380        blake3: *blake3,
381        path: v.get("path")?.as_str()?.to_string(),
382        line_count: v.get("line_count")?.as_u64()? as u32,
383        token_count: v.get("token_count").and_then(serde_json::Value::as_u64)?,
384        agent_id: v.get("agent_id")?.as_str()?.to_string(),
385        conversation_id: v.get("conversation_id")?.as_str()?.to_string(),
386        read_at: v.get("read_at")?.as_u64()?,
387        mtime: v
388            .get("mtime")
389            .and_then(serde_json::Value::as_u64)
390            .unwrap_or(mtime),
391        fresh: v
392            .get("fresh")
393            .and_then(serde_json::Value::as_bool)
394            .unwrap_or(true),
395        relay_content: v
396            .get("relay_content")
397            .and_then(serde_json::Value::as_str)
398            .map(String::from),
399        relay_mode: v
400            .get("relay_mode")
401            .and_then(serde_json::Value::as_str)
402            .map(String::from),
403    })
404}
405
406/// Record a delivery in the daemon's cross-agent registry.
407/// Fire-and-forget: errors and slow daemon responses are intentionally dropped.
408pub fn try_delivery_record_blocking(entry: &crate::core::ocla::types::DeliveryEntry) {
409    if !daemon::is_daemon_running() {
410        return;
411    }
412    let Ok(body) = serde_json::to_string(entry) else {
413        return;
414    };
415    let Ok(rt) = delivery_runtime() else {
416        return;
417    };
418    drop(rt.spawn(async move {
419        let _ = tokio::time::timeout(
420            Duration::from_secs(3),
421            try_daemon_request("POST", "/ocla/v1/delivery/record", &body),
422        )
423        .await;
424    }));
425}
426
427/// Check the daemon's generalized cross-agent cache (all DeliveryKinds).
428/// Returns the cached entry on hit, None on miss or daemon unreachable.
429pub fn try_cache_check_blocking(
430    key: &crate::core::ocla::cache_types::CacheKey,
431    validator: &crate::core::ocla::cache_types::CacheValidator,
432    requester_agent_id: Option<&str>,
433    requester_conversation_id: Option<&str>,
434) -> Option<crate::core::ocla::cache_types::DeliveryEntryV2> {
435    if !daemon::is_daemon_running() {
436        return None;
437    }
438    let validator_str = match validator {
439        crate::core::ocla::cache_types::CacheValidator::Immutable => "immutable".into(),
440        crate::core::ocla::cache_types::CacheValidator::File { mtime_ns } => {
441            format!("file:{mtime_ns}")
442        }
443        crate::core::ocla::cache_types::CacheValidator::Directory { mtime_ns } => {
444            format!("directory:{mtime_ns}")
445        }
446    };
447    let body = serde_json::json!({
448        "key": key.0,
449        "validator": validator_str,
450        "requester_agent_id": requester_agent_id,
451        "requester_conversation_id": requester_conversation_id,
452    });
453    let body_str = body.to_string();
454    let resp = delivery_block_on(async move {
455        tokio::time::timeout(
456            BEST_EFFORT_DELIVERY_IPC_TIMEOUT,
457            try_daemon_request("POST", "/ocla/v1/cache/check", &body_str),
458        )
459        .await
460        .ok()
461        .flatten()
462    })??;
463    let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
464    if !v.get("hit")?.as_bool()? {
465        return None;
466    }
467    serde_json::from_value(v.get("entry")?.clone()).ok()
468}
469
470/// Record a generalized cache entry via daemon IPC. Fire-and-forget.
471pub fn try_cache_record_blocking(entry: &crate::core::ocla::cache_types::DeliveryEntryV2) {
472    if !daemon::is_daemon_running() {
473        return;
474    }
475    let Ok(body) = serde_json::to_string(entry) else {
476        return;
477    };
478    let Ok(rt) = delivery_runtime() else { return };
479    drop(rt.spawn(async move {
480        let _ = tokio::time::timeout(
481            Duration::from_secs(3),
482            try_daemon_request("POST", "/ocla/v1/cache/record", &body),
483        )
484        .await;
485    }));
486}
487
488#[cfg(test)]
489mod tests {
490    use super::delivery_runtime;
491
492    #[test]
493    fn delivery_runtime_is_shared() {
494        let first = delivery_runtime().expect("shared delivery runtime initializes");
495        let second = delivery_runtime().expect("shared delivery runtime remains available");
496        assert!(std::ptr::eq(first, second));
497    }
498}