Skip to main content

lean_ctx_cli/http_server/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! HTTP server combining Streamable-HTTP MCP transport, REST APIs, and
3//! optional local HTTP surfaces.
4//!
5//! # Pillar mapping
6//!
7//! - **Engine:** HTTP MCP transport, Context OS event bus (SSE), A2A handoffs,
8//!   agent registry, capabilities/manifest/openapi endpoints.
9
10use std::net::SocketAddr;
11use std::sync::Arc;
12
13use anyhow::{Context, Result};
14use axum::{
15    Router,
16    extract::Json,
17    extract::Query,
18    extract::State,
19    http::{Request, StatusCode, header},
20    middleware::{self, Next},
21    response::sse::{Event as SseEvent, KeepAlive, Sse},
22    response::{IntoResponse, Response},
23    routing::get,
24};
25use futures::Stream;
26use rmcp::transport::StreamableHttpService;
27use serde::Deserialize;
28use serde_json::Value;
29use tokio::sync::broadcast;
30use tokio::time::{Duration, Instant};
31
32use lean_ctx::core::a2a::relay::RelayPeerTableV1;
33use lean_ctx::core::context_os::ContextOsMetrics;
34use lean_ctx_server::engine::ContextEngine;
35use lean_ctx_server::tools::LeanCtxServer;
36
37mod config;
38mod discovery;
39mod handlers;
40mod local_service;
41mod oauth;
42mod relay_rate;
43mod relay_replay;
44mod relay_replay_async;
45#[cfg(test)]
46mod relay_tls_tests;
47mod remote_replay;
48mod scoped_delivery;
49mod task_control;
50#[cfg(test)]
51mod task_control_tests;
52#[cfg(test)]
53mod work_graph_delivery_tests;
54#[allow(clippy::wildcard_imports)]
55use handlers::*;
56
57pub mod kernel_api;
58
59pub use config::HttpServerConfig;
60use config::sanitize_id;
61pub use relay_rate::{RelayQuota, RelayQuotaConfig};
62
63/// Wrapper stream that calls `record_sse_disconnect` on drop.
64use std::pin::Pin;
65
66pub(crate) struct SseDisconnectGuard<I> {
67    pub(crate) inner: Pin<Box<dyn Stream<Item = I> + Send>>,
68    pub(crate) metrics: Arc<ContextOsMetrics>,
69}
70
71impl<I> Stream for SseDisconnectGuard<I> {
72    type Item = I;
73
74    fn poll_next(
75        mut self: Pin<&mut Self>,
76        cx: &mut std::task::Context<'_>,
77    ) -> std::task::Poll<Option<Self::Item>> {
78        self.inner.as_mut().poll_next(cx)
79    }
80}
81
82impl<I> Drop for SseDisconnectGuard<I> {
83    fn drop(&mut self) {
84        self.metrics.record_sse_disconnect();
85    }
86}
87
88type RequestConcurrencyLease = Arc<tokio::sync::OwnedSemaphorePermit>;
89
90#[derive(Clone)]
91struct AppState {
92    token: Option<String>,
93    a2a_signing_key: Option<String>,
94    a2a_recipient_id: Option<String>,
95    a2a_tenant_id: Option<String>,
96    a2a_project_id: Option<String>,
97    a2a_peers: Arc<RelayPeerTableV1>,
98    relay_quotas: Option<Arc<tokio::sync::Mutex<relay_rate::RelayQuotaState>>>,
99    /// Configured Ed25519 peer trust and capability grants. Sender-provided
100    /// capability claims are never authority; only this policy is.
101    a2a_task_authority: Arc<lean_ctx::core::a2a::task::TaskAuthorityConfigV1>,
102    concurrency: Arc<tokio::sync::Semaphore>,
103    rate: Arc<RateLimiter>,
104    remote_replays: Arc<remote_replay::RemoteReplayGuard>,
105    project_root: String,
106    timeout: Duration,
107    server: LeanCtxServer,
108    /// Serving the local daemon socket: a tool call may name its project.
109    local_ipc: bool,
110    project_servers: Arc<ProjectServers>,
111    /// The OAuth authorization server (`serve --oauth`); TCP only.
112    oauth: Option<Arc<oauth::OAuthState>>,
113}
114
115/// One server per project a CLI call named, so a call from project B never
116/// runs in the session of project A (a CLI `knowledge recall` in B answered
117/// with A's facts, 24.10.). Bounded: past [`ProjectServers::KEPT`] projects
118/// the oldest servers are dropped and rebuilt on their next call.
119struct ProjectServers {
120    servers: tokio::sync::Mutex<Vec<(std::path::PathBuf, LeanCtxServer)>>,
121    factory: Box<dyn Fn(&str) -> LeanCtxServer + Send + Sync>,
122}
123
124impl ProjectServers {
125    const KEPT: usize = 32;
126
127    /// For a test state: no server built yet, each named project gets a
128    /// plain server.
129    #[cfg(test)]
130    pub(crate) fn for_tests() -> Arc<Self> {
131        Arc::new(Self {
132            servers: tokio::sync::Mutex::new(Vec::new()),
133            factory: Box::new(|root| {
134                LeanCtxServer::new_shared_with_context(root, "default", "default")
135            }),
136        })
137    }
138
139    /// The server for `root`, or why `root` may not be served: it must be an
140    /// existing directory, not a broad root (home, `/`), and inside the
141    /// Workspace when one confines this machine (#2120).
142    async fn for_root(
143        &self,
144        root: &str,
145        default_root: &str,
146        default: &LeanCtxServer,
147    ) -> Result<LeanCtxServer, &'static str> {
148        let root = std::path::Path::new(root)
149            .canonicalize()
150            .map_err(|_| "project root unavailable")?;
151        // A canonical filesystem root has no parent: `/`, and on Windows the
152        // verbatim drive root `\\?\C:\`, which `is_broad_or_unsafe_root`
153        // does not spell out.
154        if !root.is_dir()
155            || root.parent().is_none()
156            || lean_ctx::core::pathutil::is_broad_or_unsafe_root(&root)
157        {
158            return Err("project root is not a project");
159        }
160        if !lean_ctx::core::workspace_authority::root_authorized(&root) {
161            return Err("project root is outside the workspace");
162        }
163        if std::path::Path::new(default_root)
164            .canonicalize()
165            .ok()
166            .as_deref()
167            == Some(root.as_path())
168        {
169            return Ok(default.clone());
170        }
171        let mut servers = self.servers.lock().await;
172        if let Some((_, server)) = servers.iter().find(|(known, _)| *known == root) {
173            return Ok(server.clone());
174        }
175        if servers.len() >= Self::KEPT {
176            servers.remove(0);
177        }
178        let server = (self.factory)(&root.to_string_lossy());
179        servers.push((root, server.clone()));
180        Ok(server)
181    }
182}
183
184#[derive(Debug)]
185struct RateLimiter {
186    max_rps: f64,
187    burst: f64,
188    state: tokio::sync::Mutex<RateState>,
189}
190
191#[derive(Debug, Clone, Copy)]
192struct RateState {
193    tokens: f64,
194    last: Instant,
195}
196
197impl RateLimiter {
198    fn new(max_rps: u32, burst: u32) -> Self {
199        let now = Instant::now();
200        Self {
201            max_rps: (max_rps.max(1)) as f64,
202            burst: (burst.max(1)) as f64,
203            state: tokio::sync::Mutex::new(RateState {
204                tokens: (burst.max(1)) as f64,
205                last: now,
206            }),
207        }
208    }
209
210    async fn allow(&self) -> bool {
211        let mut s = self.state.lock().await;
212        let now = Instant::now();
213        let elapsed = now.saturating_duration_since(s.last);
214        let refill = elapsed.as_secs_f64() * self.max_rps;
215        s.tokens = (s.tokens + refill).min(self.burst);
216        s.last = now;
217        if s.tokens >= 1.0 {
218            s.tokens -= 1.0;
219            true
220        } else {
221            false
222        }
223    }
224}
225
226async fn auth_middleware(
227    State(state): State<AppState>,
228    mut req: Request<axum::body::Body>,
229    next: Next,
230) -> Response {
231    if state.token.is_none() {
232        return next.run(req).await;
233    }
234
235    let path = req.uri().path().to_string();
236    // Relay deliveries authenticate against their selected peer channel; the
237    // general server bearer must not become a second singleton authority.
238    if path == "/a2a/deliver" && !state.a2a_peers.peers.is_empty() {
239        return next.run(req).await;
240    }
241
242    if path == "/health" {
243        return next.run(req).await;
244    }
245
246    // OAuth discovery, registration, consent and token endpoints are how a
247    // client without a token gets one.
248    if state.oauth.is_some() && oauth::is_public_path(&path) {
249        return next.run(req).await;
250    }
251
252    let expected = state.token.as_deref().unwrap_or("");
253    let Some(h) = req.headers().get(header::AUTHORIZATION) else {
254        return unauthorized(&state, "missing Authorization header", None);
255    };
256    let Ok(s) = h.to_str() else {
257        return unauthorized(&state, "malformed Authorization header", None);
258    };
259    let Some(token) = s
260        .strip_prefix("Bearer ")
261        .or_else(|| s.strip_prefix("bearer "))
262    else {
263        return unauthorized(&state, "Authorization must use the Bearer scheme", None);
264    };
265    let kind = if constant_time_eq(token.as_bytes(), expected.as_bytes()) {
266        oauth::AuthKind::Owner
267    } else if let Some(client_id) = state
268        .oauth
269        .as_deref()
270        .and_then(|o| o.verify_access(token, oauth::unix_now()))
271    {
272        if !oauth::oauth_may_call(req.method(), &path) {
273            return json_error(
274                StatusCode::FORBIDDEN,
275                "insufficient_scope",
276                "an OAuth client may not call this route; it needs the instance token",
277            );
278        }
279        oauth::AuthKind::OAuth { client_id }
280    } else {
281        return unauthorized(&state, "invalid bearer token", Some("invalid_token"));
282    };
283    req.extensions_mut().insert(kind);
284
285    next.run(req).await
286}
287
288/// A 401; with OAuth on it points the client at the protected resource
289/// metadata (MCP authorization, RFC 9728 §5.1).
290fn unauthorized(state: &AppState, message: &str, error: Option<&str>) -> Response {
291    let mut resp = json_error(StatusCode::UNAUTHORIZED, "unauthorized", message);
292    if let Some(oauth) = state.oauth.as_deref()
293        && let Ok(value) = axum::http::HeaderValue::from_str(&oauth.challenge(error))
294    {
295        resp.headers_mut().insert(header::WWW_AUTHENTICATE, value);
296    }
297    resp
298}
299
300/// Structured REST error envelope: `{ "error": <human message>, "error_code": <stable code> }`.
301///
302/// `error_code` is the stable, machine-readable string SDKs switch on; `error` carries the
303/// human-facing message. Used for every REST (non-A2A) error so clients branch on a code
304/// instead of parsing prose. The A2A JSON-RPC surface keeps its own `-32xxx` envelope.
305pub(crate) fn json_error(status: StatusCode, error_code: &str, message: &str) -> Response {
306    (
307        status,
308        Json(serde_json::json!({ "error": message, "error_code": error_code })),
309    )
310        .into_response()
311}
312
313fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
314    use subtle::ConstantTimeEq;
315    if a.len() != b.len() {
316        return false;
317    }
318    bool::from(a.ct_eq(b))
319}
320
321async fn rate_limit_middleware(
322    State(state): State<AppState>,
323    req: Request<axum::body::Body>,
324    next: Next,
325) -> Response {
326    if is_diagnostic_path(req.uri().path()) {
327        return next.run(req).await;
328    }
329    if !state.rate.allow().await {
330        lean_ctx::core::request_ledger::refused();
331        return StatusCode::TOO_MANY_REQUESTS.into_response();
332    }
333    next.run(req).await
334}
335
336/// Health routes answer from counters, never from the work queue: they must
337/// stay reachable exactly when every request slot is taken (#2197).
338fn is_diagnostic_path(path: &str) -> bool {
339    matches!(path, "/health" | "/v1/health")
340}
341
342async fn concurrency_middleware(
343    State(state): State<AppState>,
344    mut req: Request<axum::body::Body>,
345    next: Next,
346) -> Response {
347    if is_diagnostic_path(req.uri().path()) {
348        return next.run(req).await;
349    }
350    let Ok(permit) = state.concurrency.clone().try_acquire_owned() else {
351        lean_ctx::core::request_ledger::refused();
352        return StatusCode::TOO_MANY_REQUESTS.into_response();
353    };
354    let permit = Arc::new(permit);
355    req.extensions_mut().insert(permit.clone());
356    let resp = next.run(req).await;
357    drop(permit);
358    resp
359}
360
361async fn health() -> impl IntoResponse {
362    (StatusCode::OK, "ok\n")
363}
364
365/// `GET /v1/health`: liveness plus the request ledger (#2197) — counters,
366/// the oldest pending request's method, stage and age, and the last tool
367/// completion. Method names only; no arguments, paths or content.
368async fn v1_health() -> impl IntoResponse {
369    let snapshot = lean_ctx::core::request_ledger::snapshot()
370        .with_ages(lean_ctx::core::request_ledger::epoch_ms());
371    Json(serde_json::json!({ "status": "ok", "requests": snapshot }))
372}
373
374/// Persist queued observations and remove the published request snapshot
375/// (#2196, #2197). Blocking work, so it runs off the async workers.
376async fn finish_serving() {
377    let _ = tokio::task::spawn_blocking(|| {
378        lean_ctx::core::request_ledger::finish_serving(Duration::from_secs(5));
379    })
380    .await;
381}
382
383async fn v1_shutdown() -> impl IntoResponse {
384    tokio::spawn(async {
385        tokio::time::sleep(Duration::from_millis(100)).await;
386        // `process::exit` runs no destructors or exit hooks.
387        finish_serving().await;
388        std::process::exit(0);
389    });
390    (StatusCode::OK, "shutting down\n")
391}
392
393#[derive(Debug, Deserialize)]
394#[serde(rename_all = "camelCase")]
395struct IndexEnsureBody {
396    root: String,
397    #[serde(default)]
398    extra_roots: Vec<String>,
399}
400
401/// Daemon-side index delegation (#460). A thin-client session POSTs the repo it
402/// needs warmed and the daemon — the single long-lived indexer — builds it once
403/// in the background (deduped per root). Every other session for the same root
404/// then load-shares the on-disk result via the `graph-idx`/`bm25-idx`
405/// cross-process locks instead of running its own scan, so N concurrent sessions
406/// cost ~one index pass machine-wide instead of N. Returns immediately; the
407/// build runs in the orchestrator's own worker thread.
408async fn v1_index_ensure(Json(body): Json<IndexEnsureBody>) -> impl IntoResponse {
409    if body.root.trim().is_empty() {
410        return (StatusCode::BAD_REQUEST, "root is required\n");
411    }
412    let root = body.root;
413    // Under a Workspace this daemon indexes only its roots (#2120).
414    if !lean_ctx::core::workspace_authority::root_authorized(std::path::Path::new(&root)) {
415        return (
416            StatusCode::FORBIDDEN,
417            "root is outside this server's Workspace\n",
418        );
419    }
420    let extra: Vec<String> = body
421        .extra_roots
422        .into_iter()
423        .filter(|extra| {
424            lean_ctx::core::workspace_authority::root_authorized(std::path::Path::new(extra))
425        })
426        .collect();
427    tokio::task::spawn_blocking(move || {
428        lean_ctx::core::index_orchestrator::ensure_all_background(&root);
429        if !extra.is_empty() {
430            lean_ctx::core::index_orchestrator::ensure_extra_roots_background(&root, &extra);
431        }
432    });
433    (StatusCode::OK, "{\"status\":\"ok\"}\n")
434}
435
436#[derive(Debug, Deserialize)]
437#[serde(rename_all = "camelCase")]
438struct ToolCallBody {
439    name: String,
440    #[serde(default)]
441    arguments: Option<Value>,
442    /// The project the calling CLI process resolved (`--root`,
443    /// `LEAN_CTX_PROJECT_ROOT`, its working directory). Honoured only on the
444    /// local daemon socket: the call then runs in that project's own server,
445    /// never in the session of whichever project the daemon served last.
446    #[serde(default)]
447    project_root: Option<String>,
448    /// The calling session's `LEAN_CTX_RIGHTS_FILE` (process-v1 §9). Honoured
449    /// only on the local daemon socket: the call runs under that session's
450    /// rights, never under the daemon's own environment.
451    #[serde(default)]
452    rights_file: Option<String>,
453    #[serde(default)]
454    _workspace_id: Option<String>,
455    #[serde(default)]
456    _channel_id: Option<String>,
457}
458
459#[derive(Debug, Deserialize)]
460#[serde(rename_all = "camelCase")]
461struct EventsQuery {
462    #[serde(default)]
463    workspace_id: Option<String>,
464    #[serde(default)]
465    channel_id: Option<String>,
466    #[serde(default)]
467    since: Option<i64>,
468    #[serde(default)]
469    limit: Option<usize>,
470    /// Comma-separated event kind filter (e.g. `tool_call,session_start`).
471    /// When set, only matching events are delivered via SSE.
472    #[serde(default)]
473    kind: Option<String>,
474    /// Agent identity used for directed-event visibility. Without an identity,
475    /// SSE exposes broadcast events only.
476    #[serde(default)]
477    agent_id: Option<String>,
478}
479
480async fn v1_manifest(State(state): State<AppState>) -> impl IntoResponse {
481    let _ = state;
482    let v = lean_ctx::core::mcp_manifest::manifest_value();
483    (StatusCode::OK, Json(v))
484}
485
486/// `GET /v1/capabilities` — discovery document describing what this instance
487/// supports (presets, tools, read modes, features, extensions, contract
488/// versions). See `docs/contracts/capabilities-contract-v1.md`.
489async fn v1_capabilities(State(state): State<AppState>) -> impl IntoResponse {
490    let _ = state;
491    (
492        StatusCode::OK,
493        Json(lean_ctx::core::server_capabilities::capabilities_value()),
494    )
495}
496
497/// `GET /v1/openapi.json` — OpenAPI 3.0 document for the public `/v1` surface,
498/// generated from the in-code endpoint inventory (`core::openapi`).
499async fn v1_openapi(State(state): State<AppState>) -> impl IntoResponse {
500    let _ = state;
501    (
502        StatusCode::OK,
503        Json(lean_ctx::core::openapi::openapi_value()),
504    )
505}
506
507#[derive(Debug, Deserialize)]
508#[serde(rename_all = "camelCase")]
509struct ToolsQuery {
510    #[serde(default)]
511    offset: Option<usize>,
512    #[serde(default)]
513    limit: Option<usize>,
514}
515
516async fn v1_tools(State(state): State<AppState>, Query(q): Query<ToolsQuery>) -> impl IntoResponse {
517    let _ = state;
518    let v = lean_ctx::core::mcp_manifest::manifest_value();
519    let tools = v
520        .get("tools")
521        .and_then(|t| t.get("granular"))
522        .cloned()
523        .unwrap_or(Value::Array(vec![]));
524
525    let all = tools.as_array().cloned().unwrap_or_default();
526    let total = all.len();
527    let offset = q.offset.unwrap_or(0).min(total);
528    let limit = q.limit.unwrap_or(200).min(500);
529    let page = all.into_iter().skip(offset).take(limit).collect::<Vec<_>>();
530
531    (
532        StatusCode::OK,
533        Json(serde_json::json!({
534            "tools": page,
535            "total": total,
536            "offset": offset,
537            "limit": limit,
538        })),
539    )
540}
541
542async fn v1_tool_call(
543    State(state): State<AppState>,
544    Json(body): Json<ToolCallBody>,
545) -> impl IntoResponse {
546    let server = match body.project_root.as_deref() {
547        None => state.server.clone(),
548        // Only the local socket's own user may pick a directory on this host.
549        Some(_) if !state.local_ipc => {
550            return json_error(
551                StatusCode::BAD_REQUEST,
552                "project_root_refused",
553                "only the local daemon socket names a project root",
554            )
555            .into_response();
556        }
557        Some(root) => match state
558            .project_servers
559            .for_root(root, &state.project_root, &state.server)
560            .await
561        {
562            Ok(server) => server,
563            Err(reason) => {
564                return json_error(StatusCode::BAD_REQUEST, "project_root_invalid", reason)
565                    .into_response();
566            }
567        },
568    };
569    if body.rights_file.is_some() && !state.local_ipc {
570        return json_error(
571            StatusCode::BAD_REQUEST,
572            "rights_file_refused",
573            "only the local daemon socket names a session's rights file",
574        )
575        .into_response();
576    }
577    // Every forwarded call runs under the sender's rights; without a rights
578    // file the sender has no session profile (the Instance's rules apply).
579    let rights = lean_ctx::core::session_rights::from_file_arg(body.rights_file.as_deref());
580    let engine = ContextEngine::from_server(server);
581    match tokio::time::timeout(
582        state.timeout,
583        engine.call_tool_value_with_rights(&body.name, body.arguments, rights),
584    )
585    .await
586    {
587        Ok(Ok(v)) => (StatusCode::OK, Json(serde_json::json!({ "result": v }))).into_response(),
588        Ok(Err(_)) => {
589            // The error carries the tool's message, which can echo content
590            // the release point withheld from the reply (AP10-R4).
591            tracing::warn!("tool call error (tool_error)");
592            json_error(
593                StatusCode::BAD_REQUEST,
594                "tool_error",
595                "tool execution failed",
596            )
597        }
598        Err(_) => json_error(
599            StatusCode::GATEWAY_TIMEOUT,
600            "request_timeout",
601            "tool call timed out",
602        ),
603    }
604}
605
606async fn v1_events(
607    State(state): State<AppState>,
608    Query(q): Query<EventsQuery>,
609) -> Sse<impl Stream<Item = Result<SseEvent, std::convert::Infallible>>> {
610    use lean_ctx::core::context_os::{ContextEventV1, RedactionLevel, redact_event_payload};
611
612    let ws = sanitize_id(&q.workspace_id.unwrap_or_else(|| "default".to_string()));
613    let ch = sanitize_id(&q.channel_id.unwrap_or_else(|| "default".to_string()));
614    let _ = &state.project_root;
615    let since = q.since.unwrap_or(0);
616    let limit = q.limit.unwrap_or(200).min(1000);
617    let redaction = RedactionLevel::RefsOnly;
618
619    let kind_filter: Option<Vec<String>> = q.kind.as_deref().map(|k| {
620        k.split(',')
621            .map(|s| s.trim().to_string())
622            .filter(|s| !s.is_empty())
623            .collect()
624    });
625    let agent_id = q
626        .agent_id
627        .as_deref()
628        .map(str::trim)
629        .filter(|id| !id.is_empty())
630        .map(str::to_string);
631    let event_filter = lean_ctx::core::context_os::TopicFilter {
632        kinds: kind_filter.as_ref().map(|kinds| {
633            kinds
634                .iter()
635                .map(|kind| lean_ctx::core::context_os::ContextEventKindV1::parse(kind))
636                .collect()
637        }),
638        agent_id: agent_id.clone(),
639        include_directed: agent_id.is_some(),
640        ..Default::default()
641    };
642
643    let rt = lean_ctx::core::context_os::runtime();
644    let replay = rt.bus.read(&ws, &ch, since, limit);
645    let replay: Vec<_> = replay
646        .into_iter()
647        .filter(|event| event_filter.matches(event))
648        .collect();
649
650    let rx = if let Some(sub) = rt.bus.subscribe_filtered(&ws, &ch, event_filter.clone()) {
651        lean_ctx::core::context_os::SubscriptionKind::Filtered(sub)
652    } else {
653        tracing::warn!("SSE subscriber limit reached for {ws}/{ch}");
654        let (_, rx) = broadcast::channel::<ContextEventV1>(1);
655        lean_ctx::core::context_os::SubscriptionKind::Unfiltered(rx)
656    };
657
658    rt.metrics.record_sse_connect();
659    rt.metrics.record_events_replayed(replay.len() as u64);
660    rt.metrics.record_workspace_active(&ws);
661
662    let bus = rt.bus.clone();
663    let metrics = rt.metrics.clone();
664    let pending: std::collections::VecDeque<ContextEventV1> = replay.into();
665
666    let stream = futures::stream::unfold(
667        (
668            pending,
669            rx,
670            event_filter,
671            ws.clone(),
672            ch.clone(),
673            since,
674            redaction,
675            bus,
676            metrics,
677        ),
678        |(mut pending, mut rx, event_filter, ws, ch, mut last_id, redaction, bus, metrics)| async move {
679            if let Some(mut ev) = pending.pop_front() {
680                last_id = ev.id;
681                redact_event_payload(&mut ev, redaction);
682                let data = serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string());
683                let evt = SseEvent::default()
684                    .id(ev.id.to_string())
685                    .event(ev.kind)
686                    .data(data);
687                return Some((
688                    Ok(evt),
689                    (
690                        pending,
691                        rx,
692                        event_filter,
693                        ws,
694                        ch,
695                        last_id,
696                        redaction,
697                        bus,
698                        metrics,
699                    ),
700                ));
701            }
702
703            loop {
704                match rx.recv().await {
705                    Ok(mut ev) if ev.id > last_id => {
706                        last_id = ev.id;
707                        if !event_filter.matches(&ev) {
708                            continue;
709                        }
710                        redact_event_payload(&mut ev, redaction);
711                        let data = serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string());
712                        let evt = SseEvent::default()
713                            .id(ev.id.to_string())
714                            .event(ev.kind)
715                            .data(data);
716                        return Some((
717                            Ok(evt),
718                            (
719                                pending,
720                                rx,
721                                event_filter,
722                                ws,
723                                ch,
724                                last_id,
725                                redaction,
726                                bus,
727                                metrics,
728                            ),
729                        ));
730                    }
731                    Ok(_) => {}
732                    Err(broadcast::error::RecvError::Closed) => return None,
733                    Err(broadcast::error::RecvError::Lagged(skipped)) => {
734                        let missed = bus.read(&ws, &ch, last_id, skipped as usize);
735                        metrics.record_events_replayed(missed.len() as u64);
736                        for ev in missed {
737                            last_id = last_id.max(ev.id);
738                            if event_filter.matches(&ev) {
739                                pending.push_back(ev);
740                            }
741                        }
742                    }
743                }
744            }
745        },
746    );
747
748    let metrics_ref = rt.metrics.clone();
749    let guarded = SseDisconnectGuard {
750        inner: Box::pin(stream),
751        metrics: metrics_ref,
752    };
753
754    Sse::new(guarded).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
755}
756
757#[derive(Debug, Deserialize)]
758struct AuditEventsQuery {
759    #[serde(default = "default_audit_limit")]
760    limit: usize,
761}
762
763fn default_audit_limit() -> usize {
764    100
765}
766
767async fn v1_audit_events(Query(q): Query<AuditEventsQuery>) -> impl IntoResponse {
768    let capped = q.limit.min(1000);
769    let boundary_events = lean_ctx::core::memory_boundary::load_audit_events(capped);
770    let trail_events = lean_ctx::core::audit_trail::load_recent(capped);
771
772    Json(serde_json::json!({
773        "cross_project_events": boundary_events,
774        "audit_trail": trail_events,
775    }))
776}
777
778#[derive(Deserialize)]
779struct ContextSummaryQuery {
780    #[serde(default)]
781    workspace_id: Option<String>,
782    #[serde(default)]
783    limit: Option<usize>,
784}
785
786async fn v1_context_summary(
787    State(state): State<AppState>,
788    Query(q): Query<ContextSummaryQuery>,
789) -> impl IntoResponse {
790    let ws = sanitize_id(&q.workspace_id.unwrap_or_else(|| "default".to_string()));
791    let limit = q.limit.unwrap_or(100).min(1000);
792    let rt = lean_ctx::core::context_os::runtime();
793    let events = rt.bus.read(&ws, "default", 0, limit);
794    let mut counts_by_kind = serde_json::Map::new();
795    for ev in &events {
796        let counter = counts_by_kind
797            .entry(ev.kind.clone())
798            .or_insert(serde_json::Value::from(0u64));
799        if let Some(n) = counter.as_u64() {
800            *counter = serde_json::Value::from(n + 1);
801        }
802    }
803    Json(serde_json::json!({
804        "workspaceId": ws,
805        "channelId": "default",
806        "projectRoot": state.project_root,
807        "totalEvents": events.len(),
808        "eventCountsByKind": counts_by_kind,
809        "limit": limit,
810    }))
811}
812
813#[derive(Deserialize)]
814struct EventsSearchQuery {
815    #[serde(default)]
816    q: Option<String>,
817    #[serde(default)]
818    limit: Option<usize>,
819}
820
821async fn v1_events_search(Query(q): Query<EventsSearchQuery>) -> impl IntoResponse {
822    let query = q.q.unwrap_or_default();
823    let limit = q.limit.unwrap_or(50).min(500);
824    let rt = lean_ctx::core::context_os::runtime();
825    let all_events = rt.bus.read("default", "default", 0, limit * 10);
826    let results: Vec<serde_json::Value> = all_events
827        .into_iter()
828        .filter(|ev| {
829            let payload = serde_json::to_string(ev).unwrap_or_default();
830            query.is_empty() || payload.contains(&query)
831        })
832        .take(limit)
833        .map(|ev| serde_json::to_value(&ev).unwrap_or_default())
834        .collect();
835    Json(serde_json::json!({
836        "query": query,
837        "results": results,
838        "count": results.len(),
839    }))
840}
841
842#[derive(Deserialize)]
843struct EventLineageQuery {
844    #[serde(default)]
845    id: Option<i64>,
846    #[serde(default)]
847    depth: Option<usize>,
848}
849
850async fn v1_events_lineage(Query(q): Query<EventLineageQuery>) -> impl IntoResponse {
851    let event_id = q.id.unwrap_or(0);
852    let depth = q.depth.unwrap_or(10).min(100);
853    let rt = lean_ctx::core::context_os::runtime();
854    let events = rt.bus.read("default", "default", 0, depth);
855    let chain: Vec<serde_json::Value> = events
856        .into_iter()
857        .filter(|ev| ev.id >= event_id)
858        .take(depth)
859        .map(|ev| serde_json::to_value(&ev).unwrap_or_default())
860        .collect();
861    Json(serde_json::json!({
862        "eventId": event_id,
863        "depth": depth,
864        "chain": chain,
865    }))
866}
867
868async fn v1_metrics(State(_state): State<AppState>) -> impl IntoResponse {
869    let rt = lean_ctx::core::context_os::runtime();
870    let snap = rt.metrics.snapshot();
871    (
872        StatusCode::OK,
873        Json(serde_json::to_value(snap).unwrap_or_default()),
874    )
875}
876
877async fn a2a_jsonrpc(State(state): State<AppState>, Json(body): Json<Value>) -> impl IntoResponse {
878    let req: lean_ctx::core::a2a::a2a_compat::JsonRpcRequest = match serde_json::from_value(body) {
879        Ok(r) => r,
880        Err(e) => {
881            tracing::debug!("a2a JSON-RPC parse error: {e}");
882            return (
883                StatusCode::BAD_REQUEST,
884                Json(serde_json::json!({
885                    "jsonrpc": "2.0",
886                    "id": null,
887                    "error": {"code": -32700, "message": "invalid request"}
888                })),
889            );
890        }
891    };
892    let resp = match lean_ctx::core::a2a::task::TaskStore::scoped_path(&state.project_root) {
893        Ok(path) => lean_ctx::core::a2a::a2a_compat::handle_a2a_jsonrpc_at_path(&req, &path),
894        Err(error) => {
895            tracing::warn!("A2A project scope error: {error}");
896            lean_ctx::core::a2a::a2a_compat::JsonRpcResponse::server_error(
897                req.id.clone(),
898                "task storage unavailable",
899            )
900        }
901    };
902    let json = serde_json::to_value(resp).unwrap_or_default();
903    (StatusCode::OK, Json(json))
904}
905
906async fn v1_a2a_agent_card(State(state): State<AppState>) -> impl IntoResponse {
907    let card = lean_ctx::core::a2a::agent_card::build_agent_card(
908        &state.project_root,
909        state.token.is_some(),
910    );
911    (
912        StatusCode::OK,
913        [(header::CONTENT_TYPE, "application/json")],
914        Json(card),
915    )
916}
917
918async fn v1_agents_register(State(state): State<AppState>, Json(body): Json<Value>) -> Response {
919    let agent_type = body
920        .get("agent_type")
921        .and_then(|v| v.as_str())
922        .unwrap_or("unknown");
923    let role = body.get("role").and_then(|v| v.as_str());
924    let project_root = body
925        .get("project_root")
926        .and_then(|v| v.as_str())
927        .unwrap_or(&state.project_root);
928
929    match lean_ctx::core::agents::AgentRegistry::mutate_locked(|registry| {
930        registry.register(agent_type, role, project_root, None)
931    }) {
932        Ok((_, agent_id)) => (
933            StatusCode::CREATED,
934            Json(serde_json::json!({
935                "agent_id": agent_id,
936                "status": "registered"
937            })),
938        )
939            .into_response(),
940        Err(error) => {
941            tracing::warn!(%error, "lean-ctx: agent registration failed");
942            (
943                StatusCode::SERVICE_UNAVAILABLE,
944                Json(serde_json::json!({"error": "agent registry unavailable"})),
945            )
946                .into_response()
947        }
948    }
949}
950
951async fn v1_agents_heartbeat(Json(body): Json<Value>) -> Response {
952    let agent_id = body.get("agent_id").and_then(|v| v.as_str()).unwrap_or("");
953    match lean_ctx::core::agents::AgentRegistry::mutate_locked(|registry| {
954        registry.update_heartbeat(agent_id)
955    })
956    .and_then(|(_, result)| result)
957    {
958        Ok(()) => (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))).into_response(),
959        Err(error) => {
960            tracing::warn!(%error, agent_id, "lean-ctx: rejected agent heartbeat");
961            let (status, message) = if error.starts_with("agent presence '") {
962                (StatusCode::NOT_FOUND, "unknown agent id")
963            } else {
964                (
965                    StatusCode::SERVICE_UNAVAILABLE,
966                    "agent registry unavailable",
967                )
968            };
969            (
970                status,
971                Json(serde_json::json!({
972                    "error": message,
973                    "status": "rejected"
974                })),
975            )
976                .into_response()
977        }
978    }
979}
980
981async fn v1_agents_list() -> impl IntoResponse {
982    let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
983    let active = registry.list_active(None);
984    Json(serde_json::json!({
985        "agents": active.iter().map(|a| serde_json::json!({
986            "agent_id": a.agent_id,
987            "agent_type": a.agent_type,
988            "role": a.role,
989            "status": a.status.to_string(),
990            "last_active": a.last_active.to_rfc3339(),
991        })).collect::<Vec<_>>()
992    }))
993}
994
995async fn v1_agents_deregister(Json(body): Json<Value>) -> Response {
996    let agent_id = body.get("agent_id").and_then(|v| v.as_str()).unwrap_or("");
997    match lean_ctx::core::agents::AgentRegistry::mutate_locked(|registry| {
998        registry.set_status(
999            agent_id,
1000            lean_ctx::core::agents::AgentStatus::Finished,
1001            Some("deregistered via API"),
1002        )
1003    })
1004    .and_then(|(_, result)| result)
1005    {
1006        Ok(()) => (
1007            StatusCode::OK,
1008            Json(serde_json::json!({"status": "deregistered"})),
1009        )
1010            .into_response(),
1011        Err(error) => {
1012            tracing::warn!(%error, agent_id, "lean-ctx: rejected agent deregistration");
1013            let (status, message) = if error.starts_with("agent presence '") {
1014                (StatusCode::NOT_FOUND, "unknown agent id")
1015            } else {
1016                (
1017                    StatusCode::SERVICE_UNAVAILABLE,
1018                    "agent registry unavailable",
1019                )
1020            };
1021            (
1022                status,
1023                Json(serde_json::json!({
1024                    "error": message,
1025                    "status": "rejected"
1026                })),
1027            )
1028                .into_response()
1029        }
1030    }
1031}
1032
1033async fn v1_agents_events_sse()
1034-> Sse<impl Stream<Item = Result<SseEvent, std::convert::Infallible>>> {
1035    let stream = futures::stream::unfold(0usize, |last_count| async move {
1036        loop {
1037            tokio::time::sleep(Duration::from_secs(5)).await;
1038            let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
1039            let active = registry.list_active(None);
1040            let count = active.len();
1041            if count != last_count {
1042                let data = serde_json::json!({
1043                    "type": "agents_changed",
1044                    "active_count": count,
1045                    "agents": active.iter().map(|a| &a.agent_id).collect::<Vec<_>>(),
1046                });
1047                return Some((
1048                    Ok::<_, std::convert::Infallible>(SseEvent::default().data(data.to_string())),
1049                    count,
1050                ));
1051            }
1052        }
1053    });
1054
1055    Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
1056}
1057
1058fn build_app_router(
1059    cfg: &HttpServerConfig,
1060    receipt_authority: Option<Arc<lean_ctx::core::execution_ledger::host::HostReceiptAuthority>>,
1061) -> Router {
1062    build_app_router_with_auth(cfg, true, receipt_authority)
1063}
1064
1065#[cfg(test)]
1066pub(crate) fn build_delivery_test_router(cfg: &HttpServerConfig) -> Router {
1067    build_app_router_with_auth(cfg, false, None)
1068}
1069
1070fn build_app_router_with_auth(
1071    cfg: &HttpServerConfig,
1072    require_auth: bool,
1073    receipt_authority: Option<Arc<lean_ctx::core::execution_ledger::host::HostReceiptAuthority>>,
1074) -> Router {
1075    build_router(cfg, require_auth, false, receipt_authority)
1076}
1077
1078/// The router of the local daemon socket: tool calls may name their project.
1079pub(crate) fn build_ipc_router(
1080    cfg: &HttpServerConfig,
1081    receipt_authority: Option<Arc<lean_ctx::core::execution_ledger::host::HostReceiptAuthority>>,
1082) -> Router {
1083    build_router(cfg, false, true, receipt_authority)
1084}
1085
1086fn build_router(
1087    cfg: &HttpServerConfig,
1088    require_auth: bool,
1089    local_ipc: bool,
1090    receipt_authority: Option<Arc<lean_ctx::core::execution_ledger::host::HostReceiptAuthority>>,
1091) -> Router {
1092    let project_root = cfg.project_root.to_string_lossy().to_string();
1093    let service_project_root = project_root.clone();
1094    let project_authority = receipt_authority.clone();
1095    let project_factory = move |root: &str| {
1096        let mut server = LeanCtxServer::new_shared_with_context(root, "default", "default");
1097        server
1098            .native_receipt_authority
1099            .clone_from(&project_authority);
1100        server
1101    };
1102    // REST and Streamable HTTP share the same startup authority snapshot.
1103    let server_factory = move || {
1104        let mut server =
1105            LeanCtxServer::new_shared_with_context(&service_project_root, "default", "default");
1106        server
1107            .native_receipt_authority
1108            .clone_from(&receipt_authority);
1109        server
1110    };
1111    let rest_server = server_factory();
1112    let service_factory = move || -> Result<LeanCtxServer, std::io::Error> { Ok(server_factory()) };
1113    let mcp_http = StreamableHttpService::new(
1114        service_factory,
1115        Arc::new(
1116            rmcp::transport::streamable_http_server::session::local::LocalSessionManager::default(),
1117        ),
1118        cfg.mcp_http_config(),
1119    );
1120
1121    let token = if require_auth {
1122        cfg.effective_auth_token()
1123    } else {
1124        None
1125    };
1126    let oauth_state = match (token.as_deref(), cfg.oauth_enabled()) {
1127        (Some(owner), true) => match cfg.oauth_issuer_url() {
1128            Ok(Some(issuer)) => {
1129                let dir = cfg.oauth_state_dir.clone().or_else(|| {
1130                    lean_ctx::core::data_dir::lean_ctx_data_dir()
1131                        .ok()
1132                        .map(|dir| dir.join("oauth"))
1133                });
1134                let store = dir.map(|dir| oauth::OAuthState::store_path(&dir, &issuer));
1135                // An explicit --auth-token is fingerprinted: rotating it ends
1136                // every grant approved with the old one. The loopback token
1137                // generated per start keeps the grants across restarts.
1138                let explicit = cfg.auth_token.as_deref().is_some_and(|t| !t.is_empty());
1139                Some(Arc::new(oauth::OAuthState::open(
1140                    issuer,
1141                    owner.to_string(),
1142                    store,
1143                    explicit,
1144                )))
1145            }
1146            Ok(None) => None,
1147            Err(error) => {
1148                tracing::error!("OAuth not served: {error}");
1149                None
1150            }
1151        },
1152        _ => None,
1153    };
1154    let oauth_routes = match &oauth_state {
1155        Some(state) => oauth::router(state.clone()),
1156        None => Router::new(),
1157    };
1158    let state = AppState {
1159        token,
1160        a2a_signing_key: cfg.a2a_signing_key.clone(),
1161        a2a_recipient_id: cfg.a2a_recipient_id.clone(),
1162        a2a_tenant_id: cfg.a2a_tenant_id.clone(),
1163        a2a_project_id: cfg.a2a_project_id.clone(),
1164        a2a_peers: Arc::new(cfg.a2a_peers.clone()),
1165        relay_quotas: match cfg.relay_quota_state() {
1166            Ok(state) => state.map(|state| Arc::new(tokio::sync::Mutex::new(state))),
1167            Err(error) => {
1168                tracing::error!("relay quota configuration rejected: {error}");
1169                None
1170            }
1171        },
1172        a2a_task_authority: Arc::new(cfg.a2a_task_authority.clone()),
1173        concurrency: Arc::new(tokio::sync::Semaphore::new(cfg.max_concurrency.max(1))),
1174        rate: Arc::new(RateLimiter::new(cfg.max_rps, cfg.rate_burst)),
1175        remote_replays: Arc::new(remote_replay::RemoteReplayGuard::new(
1176            &project_root,
1177            handlers::REMOTE_REPLAY_RETENTION_SECONDS,
1178        )),
1179        project_root,
1180        timeout: Duration::from_millis(cfg.request_timeout_ms.max(1)),
1181        server: rest_server,
1182        local_ipc,
1183        project_servers: Arc::new(ProjectServers {
1184            servers: tokio::sync::Mutex::new(Vec::new()),
1185            factory: Box::new(project_factory),
1186        }),
1187        oauth: oauth_state,
1188    };
1189
1190    let ocla = match (
1191        state.token.as_ref(),
1192        state.a2a_tenant_id.as_deref(),
1193        state.a2a_project_id.as_deref(),
1194    ) {
1195        (Some(_), Some(tenant_id), Some(project_id)) => {
1196            match lean_ctx::core::a2a::dlq::DlqScope::new(tenant_id, project_id) {
1197                Ok(scope) => lean_ctx::core::ocla::wire_api::ocla_router_with_dlq(scope),
1198                Err(_) => lean_ctx::core::ocla::wire_api::ocla_router(),
1199            }
1200        }
1201        _ => lean_ctx::core::ocla::wire_api::ocla_router(),
1202    };
1203
1204    // Local Service v1 (Local Read routes, live events): the daemon socket
1205    // only — its 0600 mode is the guard; a TCP server never serves them.
1206    let local_routes = if local_ipc {
1207        local_service::router()
1208    } else {
1209        Router::new()
1210    };
1211
1212    Router::new()
1213        .route("/health", get(health))
1214        .route("/v1/health", get(v1_health))
1215        .route(
1216            "/ocla/v1/delivery/scoped",
1217            axum::routing::post(scoped_delivery::execute),
1218        )
1219        .route("/v1/shutdown", axum::routing::post(v1_shutdown))
1220        .route("/v1/index/ensure", axum::routing::post(v1_index_ensure))
1221        .route("/v1/manifest", get(v1_manifest))
1222        .route("/v1/capabilities", get(v1_capabilities))
1223        .route("/v1/openapi.json", get(v1_openapi))
1224        .route("/v1/cache/stats", get(v1_cache_stats))
1225        .route("/v1/tools", get(v1_tools))
1226        .route("/v1/tools/call", axum::routing::post(v1_tool_call))
1227        .route("/v1/events", get(v1_events))
1228        .route("/v1/metrics", get(v1_metrics))
1229        .route("/v1/context/summary", get(v1_context_summary))
1230        .route("/v1/events/search", get(v1_events_search))
1231        .route("/v1/events/lineage", get(v1_events_lineage))
1232        .route("/v1/audit/events", get(v1_audit_events))
1233        .route("/v1/a2a/handoff", axum::routing::post(v1_a2a_handoff))
1234        .route("/a2a/deliver", axum::routing::post(handlers::a2a_deliver))
1235        .route("/v1/a2a/agent-card", get(v1_a2a_agent_card))
1236        .route("/.well-known/agent.json", get(v1_a2a_agent_card))
1237        .route(
1238            "/.well-known/mcp-server.json",
1239            get(discovery::mcp_server_card),
1240        )
1241        .route("/a2a", axum::routing::post(a2a_jsonrpc))
1242        .route(
1243            "/v1/agents/register",
1244            axum::routing::post(v1_agents_register),
1245        )
1246        .route(
1247            "/v1/agents/heartbeat",
1248            axum::routing::post(v1_agents_heartbeat),
1249        )
1250        .route("/v1/agents/list", get(v1_agents_list))
1251        .route(
1252            "/v1/agents/deregister",
1253            axum::routing::post(v1_agents_deregister),
1254        )
1255        .route("/v1/agents/events", get(v1_agents_events_sse))
1256        .route("/v1/kernel/dashboard", get(kernel_api::dashboard))
1257        .route("/v1/kernel/etpao", get(kernel_api::etpao))
1258        .route("/v1/kernel/config", get(kernel_api::get_config))
1259        .route(
1260            "/v1/kernel/config",
1261            axum::routing::post(kernel_api::set_config),
1262        )
1263        .route("/v1/kernel/evidence", get(kernel_api::evidence))
1264        .route("/v1/kernel/health", get(kernel_api::health))
1265        .route("/v1/kernel/report", get(kernel_api::report))
1266        .route(
1267            "/v1/kernel/reset",
1268            axum::routing::post(kernel_api::reset_state),
1269        )
1270        .merge(ocla.with_state(()))
1271        .merge(local_routes)
1272        .merge(oauth_routes)
1273        .fallback_service(mcp_http)
1274        .layer(axum::extract::DefaultBodyLimit::max(cfg.max_body_bytes))
1275        .layer(middleware::from_fn_with_state(
1276            state.clone(),
1277            rate_limit_middleware,
1278        ))
1279        .layer(middleware::from_fn_with_state(
1280            state.clone(),
1281            concurrency_middleware,
1282        ))
1283        .layer(middleware::from_fn_with_state(
1284            state.clone(),
1285            auth_middleware,
1286        ))
1287        .with_state(state)
1288}
1289
1290pub async fn serve(cfg: HttpServerConfig) -> Result<()> {
1291    lean_ctx::core::protocol::set_mcp_context(true);
1292    cfg.validate()?;
1293    let receipt_authority =
1294        lean_ctx_server::server::native_receipts::load_configured_host_authority()
1295            .map_err(anyhow::Error::msg)?;
1296    // Observations never block dispatch; the request ledger publishes for
1297    // `lean-ctx doctor` and `/v1/health` (#2196, #2197).
1298    lean_ctx::core::request_ledger::start_serving("http");
1299    // Apply the `LEAN_CTX_KERNEL_*` switches once, so kernel health
1300    // (`/v1/kernel/health`) reports the configuration this server runs with.
1301    lean_ctx::core::context_kernel::startup::initialize();
1302
1303    // Surface any path-jail relaxation inherited from the launch env or config,
1304    // so a loosened boundary is never silent (GH security audit, finding 3).
1305    lean_ctx::core::pathjail::warn_if_relaxed();
1306
1307    // OAuth exposed without TLS, or a public consent page guarded only by
1308    // the generated token, is never silent (ux16 review).
1309    for warning in cfg.oauth_exposure_warnings() {
1310        tracing::warn!("{warning}");
1311        eprintln!("[lean-ctx] WARNING: {warning}");
1312    }
1313
1314    // Pre-warm the project indices in the background for this long-lived HTTP
1315    // server. The stdio path deliberately stays lazy — short-lived respawns must
1316    // not each pay a full graph + BM25 scan (#453) — but `serve` is a single,
1317    // persistent process: one background build gives the first heavy/search tool
1318    // call a warm index instead of racing a cold scan of a large project root
1319    // against the per-request timeout (the SDK-conformance regression, GL #395).
1320    // The build is deduped per root and idle CPU settles flat once it completes
1321    // (the memory guard backs off), so #453 idle hygiene is preserved.
1322    let warm_root = cfg.project_root.to_string_lossy().to_string();
1323    // Under a Workspace only one of its roots is warmed (#2120).
1324    if !warm_root.is_empty()
1325        && lean_ctx::core::workspace_authority::root_authorized(std::path::Path::new(&warm_root))
1326    {
1327        lean_ctx::core::index_orchestrator::ensure_all_background(&warm_root);
1328    }
1329
1330    let addr: SocketAddr = format!("{}:{}", cfg.host, cfg.port)
1331        .parse()
1332        .context("invalid host/port")?;
1333
1334    let app = build_app_router(&cfg, receipt_authority);
1335
1336    let listener = tokio::net::TcpListener::bind(addr)
1337        .await
1338        .with_context(|| format!("bind {addr}"))?;
1339
1340    tracing::info!(
1341        "lean-ctx Streamable HTTP server listening on http://{addr} (project_root={})",
1342        cfg.project_root.display()
1343    );
1344
1345    let served = axum::serve(listener, app)
1346        .with_graceful_shutdown(async move {
1347            let _ = tokio::signal::ctrl_c().await;
1348        })
1349        .await
1350        .context("http server");
1351    finish_serving().await;
1352    served
1353}
1354
1355/// Serve the daemon over a platform-independent IPC channel (UDS on Unix,
1356/// Named Pipes on Windows).
1357pub async fn serve_ipc(cfg: HttpServerConfig, addr: lean_ctx::ipc::DaemonAddr) -> Result<()> {
1358    cfg.validate()?;
1359    let receipt_authority =
1360        lean_ctx_server::server::native_receipts::load_configured_host_authority()
1361            .map_err(anyhow::Error::msg)?;
1362    // Observations never block dispatch; the request ledger publishes for
1363    // `lean-ctx doctor` (#2196, #2197).
1364    lean_ctx::core::request_ledger::start_serving("daemon");
1365    lean_ctx::core::context_kernel::startup::initialize();
1366
1367    lean_ctx::core::telemetry_send::spawn_daemon_telemetry();
1368    lean_ctx::core::context_admission::receipt_store::retention::maintain_at_startup();
1369    // One Cloud scheduler per machine (the daemon is the singleton).
1370    lean_ctx_cloud::scheduler::spawn(&lean_ctx::core::config::Config::load().cloud);
1371    // One Cloud bus relay per machine, beside the scheduler.
1372    lean_ctx_cloud::bus::spawn();
1373
1374    match addr {
1375        #[cfg(unix)]
1376        lean_ctx::ipc::DaemonAddr::Unix(ref path) => {
1377            let app = build_ipc_router(&cfg, receipt_authority);
1378            let listener = lean_ctx::ipc::bind_listener(&addr)?;
1379
1380            tracing::info!(
1381                "lean-ctx daemon listening on {} (project_root={})",
1382                path.display(),
1383                cfg.project_root.display()
1384            );
1385
1386            let served = axum::serve(listener, app.into_make_service())
1387                .with_graceful_shutdown(async move {
1388                    let _ = tokio::signal::ctrl_c().await;
1389                })
1390                .await
1391                .context("ipc server");
1392            finish_serving().await;
1393            served
1394        }
1395        #[cfg(windows)]
1396        lean_ctx::ipc::DaemonAddr::NamedPipe(ref name) => {
1397            let app = build_ipc_router(&cfg, receipt_authority);
1398            let listener = lean_ctx::ipc::bind_listener(&addr)?;
1399
1400            tracing::info!(
1401                "lean-ctx daemon listening on {} (project_root={})",
1402                name,
1403                cfg.project_root.display()
1404            );
1405
1406            let served = axum::serve(listener, app.into_make_service())
1407                .with_graceful_shutdown(async move {
1408                    let _ = tokio::signal::ctrl_c().await;
1409                })
1410                .await
1411                .context("ipc server");
1412            finish_serving().await;
1413            served
1414        }
1415    }
1416}
1417
1418#[cfg(test)]
1419mod cancellation_tests;
1420
1421#[cfg(test)]
1422mod native_receipt_tests;
1423
1424#[cfg(test)]
1425#[path = "main_http_tests.rs"]
1426mod tests;