1use std::net::SocketAddr;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use anyhow::{Context, Result, anyhow};
6use axum::{
7 Router,
8 extract::Json,
9 extract::Query,
10 extract::State,
11 http::{Request, StatusCode, header},
12 middleware::{self, Next},
13 response::sse::{Event as SseEvent, KeepAlive, Sse},
14 response::{IntoResponse, Response},
15 routing::get,
16};
17use futures::Stream;
18use rmcp::transport::{StreamableHttpServerConfig, StreamableHttpService};
19use serde::Deserialize;
20use serde_json::Value;
21use tokio::sync::broadcast;
22use tokio::time::{Duration, Instant};
23
24use crate::core::context_os::ContextOsMetrics;
25use crate::engine::ContextEngine;
26use crate::tools::LeanCtxServer;
27
28pub mod context_views;
29pub mod roi_webhook;
30pub mod savings_ingest;
31pub mod savings_summary;
32pub mod team;
33pub mod team_billing;
34
35use std::pin::Pin;
37
38pub(crate) struct SseDisconnectGuard<I> {
39 pub(crate) inner: Pin<Box<dyn Stream<Item = I> + Send>>,
40 pub(crate) metrics: Arc<ContextOsMetrics>,
41}
42
43impl<I> Stream for SseDisconnectGuard<I> {
44 type Item = I;
45
46 fn poll_next(
47 mut self: Pin<&mut Self>,
48 cx: &mut std::task::Context<'_>,
49 ) -> std::task::Poll<Option<Self::Item>> {
50 self.inner.as_mut().poll_next(cx)
51 }
52}
53
54impl<I> Drop for SseDisconnectGuard<I> {
55 fn drop(&mut self) {
56 self.metrics.record_sse_disconnect();
57 }
58}
59
60const MAX_ID_LEN: usize = 64;
61
62fn sanitize_id(raw: &str) -> String {
63 let trimmed = raw.trim();
64 if trimmed.is_empty() {
65 return "default".to_string();
66 }
67 let cleaned: String = trimmed
68 .chars()
69 .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_' || *c == '.')
70 .take(MAX_ID_LEN)
71 .collect();
72 if cleaned.is_empty() {
73 "default".to_string()
74 } else {
75 cleaned
76 }
77}
78
79#[derive(Clone, Debug)]
80pub struct HttpServerConfig {
81 pub host: String,
82 pub port: u16,
83 pub project_root: PathBuf,
84 pub auth_token: Option<String>,
85 pub stateful_mode: bool,
86 pub json_response: bool,
87 pub disable_host_check: bool,
88 pub allowed_hosts: Vec<String>,
89 pub max_body_bytes: usize,
90 pub max_concurrency: usize,
91 pub max_rps: u32,
92 pub rate_burst: u32,
93 pub request_timeout_ms: u64,
94}
95
96impl Default for HttpServerConfig {
97 fn default() -> Self {
98 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
99 Self {
100 host: "127.0.0.1".to_string(),
101 port: 8080,
102 project_root,
103 auth_token: None,
104 stateful_mode: false,
105 json_response: true,
106 disable_host_check: false,
107 allowed_hosts: Vec::new(),
108 max_body_bytes: 2 * 1024 * 1024,
109 max_concurrency: 32,
110 max_rps: 50,
111 rate_burst: 100,
112 request_timeout_ms: 30_000,
113 }
114 }
115}
116
117impl HttpServerConfig {
118 pub fn validate(&self) -> Result<()> {
119 let host = self.host.trim().to_lowercase();
120 let is_loopback = host == "127.0.0.1" || host == "localhost" || host == "::1";
121 if !is_loopback && self.auth_token.as_deref().unwrap_or("").is_empty() {
122 return Err(anyhow!(
123 "Refusing to bind to host='{host}' without auth. Provide --auth-token (or bind to 127.0.0.1)."
124 ));
125 }
126 Ok(())
127 }
128
129 pub fn effective_auth_token(&self) -> Option<String> {
130 if let Some(ref token) = self.auth_token
131 && !token.is_empty()
132 {
133 return Some(token.clone());
134 }
135 let host = self.host.trim().to_lowercase();
136 let is_loopback = host == "127.0.0.1" || host == "localhost" || host == "::1";
137 if is_loopback {
138 let auto_token = crate::core::session_token::generate_token();
139 eprintln!(
140 "[lean-ctx] Auto-generated auth token for loopback: {auto_token}\n\
141 Pass as Bearer token or set --auth-token explicitly."
142 );
143 Some(auto_token)
144 } else {
145 None
146 }
147 }
148
149 fn mcp_http_config(&self) -> StreamableHttpServerConfig {
150 let mut cfg = StreamableHttpServerConfig::default()
151 .with_stateful_mode(self.stateful_mode)
152 .with_json_response(self.json_response);
153
154 if self.disable_host_check {
155 tracing::warn!(
156 "⚠ --disable-host-check is active: DNS rebinding protection is OFF. \
157 Do NOT use this in production or on non-loopback interfaces."
158 );
159 cfg = cfg.disable_allowed_hosts();
160 return cfg;
161 }
162
163 if !self.allowed_hosts.is_empty() {
164 cfg = cfg.with_allowed_hosts(self.allowed_hosts.clone());
165 return cfg;
166 }
167
168 let host = self.host.trim();
170 if host == "127.0.0.1" || host == "localhost" || host == "::1" {
171 cfg.allowed_hosts.push(host.to_string());
172 }
173
174 cfg
175 }
176}
177
178#[derive(Clone)]
179struct AppState {
180 token: Option<String>,
181 concurrency: Arc<tokio::sync::Semaphore>,
182 rate: Arc<RateLimiter>,
183 project_root: String,
184 timeout: Duration,
185 server: LeanCtxServer,
186}
187
188#[derive(Debug)]
189struct RateLimiter {
190 max_rps: f64,
191 burst: f64,
192 state: tokio::sync::Mutex<RateState>,
193}
194
195#[derive(Debug, Clone, Copy)]
196struct RateState {
197 tokens: f64,
198 last: Instant,
199}
200
201impl RateLimiter {
202 fn new(max_rps: u32, burst: u32) -> Self {
203 let now = Instant::now();
204 Self {
205 max_rps: (max_rps.max(1)) as f64,
206 burst: (burst.max(1)) as f64,
207 state: tokio::sync::Mutex::new(RateState {
208 tokens: (burst.max(1)) as f64,
209 last: now,
210 }),
211 }
212 }
213
214 async fn allow(&self) -> bool {
215 let mut s = self.state.lock().await;
216 let now = Instant::now();
217 let elapsed = now.saturating_duration_since(s.last);
218 let refill = elapsed.as_secs_f64() * self.max_rps;
219 s.tokens = (s.tokens + refill).min(self.burst);
220 s.last = now;
221 if s.tokens >= 1.0 {
222 s.tokens -= 1.0;
223 true
224 } else {
225 false
226 }
227 }
228}
229
230async fn auth_middleware(
231 State(state): State<AppState>,
232 req: Request<axum::body::Body>,
233 next: Next,
234) -> Response {
235 if state.token.is_none() {
236 return next.run(req).await;
237 }
238
239 if req.uri().path() == "/health" {
240 return next.run(req).await;
241 }
242
243 let expected = state.token.as_deref().unwrap_or("");
244 let Some(h) = req.headers().get(header::AUTHORIZATION) else {
245 return json_error(
246 StatusCode::UNAUTHORIZED,
247 "unauthorized",
248 "missing Authorization header",
249 );
250 };
251 let Ok(s) = h.to_str() else {
252 return json_error(
253 StatusCode::UNAUTHORIZED,
254 "unauthorized",
255 "malformed Authorization header",
256 );
257 };
258 let Some(token) = s
259 .strip_prefix("Bearer ")
260 .or_else(|| s.strip_prefix("bearer "))
261 else {
262 return json_error(
263 StatusCode::UNAUTHORIZED,
264 "unauthorized",
265 "Authorization must use the Bearer scheme",
266 );
267 };
268 if !constant_time_eq(token.as_bytes(), expected.as_bytes()) {
269 return json_error(
270 StatusCode::UNAUTHORIZED,
271 "unauthorized",
272 "invalid bearer token",
273 );
274 }
275
276 next.run(req).await
277}
278
279pub(crate) fn json_error(status: StatusCode, error_code: &str, message: &str) -> Response {
285 (
286 status,
287 Json(serde_json::json!({ "error": message, "error_code": error_code })),
288 )
289 .into_response()
290}
291
292fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
293 use subtle::ConstantTimeEq;
294 if a.len() != b.len() {
295 return false;
296 }
297 bool::from(a.ct_eq(b))
298}
299
300async fn rate_limit_middleware(
301 State(state): State<AppState>,
302 req: Request<axum::body::Body>,
303 next: Next,
304) -> Response {
305 if !state.rate.allow().await {
306 return StatusCode::TOO_MANY_REQUESTS.into_response();
307 }
308 next.run(req).await
309}
310
311async fn concurrency_middleware(
312 State(state): State<AppState>,
313 req: Request<axum::body::Body>,
314 next: Next,
315) -> Response {
316 let Ok(permit) = state.concurrency.clone().try_acquire_owned() else {
317 return StatusCode::TOO_MANY_REQUESTS.into_response();
318 };
319 let resp = next.run(req).await;
320 drop(permit);
321 resp
322}
323
324async fn health() -> impl IntoResponse {
325 (StatusCode::OK, "ok\n")
326}
327
328async fn v1_shutdown() -> impl IntoResponse {
329 tokio::spawn(async {
330 tokio::time::sleep(Duration::from_millis(100)).await;
331 std::process::exit(0);
332 });
333 (StatusCode::OK, "shutting down\n")
334}
335
336#[derive(Debug, Deserialize)]
337#[serde(rename_all = "camelCase")]
338struct ToolCallBody {
339 name: String,
340 #[serde(default)]
341 arguments: Option<Value>,
342 #[serde(default)]
343 _workspace_id: Option<String>,
344 #[serde(default)]
345 _channel_id: Option<String>,
346}
347
348#[derive(Debug, Deserialize)]
349#[serde(rename_all = "camelCase")]
350struct EventsQuery {
351 #[serde(default)]
352 workspace_id: Option<String>,
353 #[serde(default)]
354 channel_id: Option<String>,
355 #[serde(default)]
356 since: Option<i64>,
357 #[serde(default)]
358 limit: Option<usize>,
359 #[serde(default)]
362 kind: Option<String>,
363}
364
365async fn v1_manifest(State(state): State<AppState>) -> impl IntoResponse {
366 let _ = state;
367 let v = crate::core::mcp_manifest::manifest_value();
368 (StatusCode::OK, Json(v))
369}
370
371async fn v1_capabilities(State(state): State<AppState>) -> impl IntoResponse {
375 let _ = state;
376 (
377 StatusCode::OK,
378 Json(crate::core::server_capabilities::capabilities_value()),
379 )
380}
381
382async fn v1_openapi(State(state): State<AppState>) -> impl IntoResponse {
385 let _ = state;
386 (StatusCode::OK, Json(crate::core::openapi::openapi_value()))
387}
388
389#[derive(Debug, Deserialize)]
390#[serde(rename_all = "camelCase")]
391struct ToolsQuery {
392 #[serde(default)]
393 offset: Option<usize>,
394 #[serde(default)]
395 limit: Option<usize>,
396}
397
398async fn v1_tools(State(state): State<AppState>, Query(q): Query<ToolsQuery>) -> impl IntoResponse {
399 let _ = state;
400 let v = crate::core::mcp_manifest::manifest_value();
401 let tools = v
402 .get("tools")
403 .and_then(|t| t.get("granular"))
404 .cloned()
405 .unwrap_or(Value::Array(vec![]));
406
407 let all = tools.as_array().cloned().unwrap_or_default();
408 let total = all.len();
409 let offset = q.offset.unwrap_or(0).min(total);
410 let limit = q.limit.unwrap_or(200).min(500);
411 let page = all.into_iter().skip(offset).take(limit).collect::<Vec<_>>();
412
413 (
414 StatusCode::OK,
415 Json(serde_json::json!({
416 "tools": page,
417 "total": total,
418 "offset": offset,
419 "limit": limit,
420 })),
421 )
422}
423
424async fn v1_tool_call(
425 State(state): State<AppState>,
426 Json(body): Json<ToolCallBody>,
427) -> impl IntoResponse {
428 let engine = ContextEngine::from_server(state.server.clone());
429 match tokio::time::timeout(
430 state.timeout,
431 engine.call_tool_value(&body.name, body.arguments),
432 )
433 .await
434 {
435 Ok(Ok(v)) => (StatusCode::OK, Json(serde_json::json!({ "result": v }))).into_response(),
436 Ok(Err(e)) => {
437 tracing::warn!("tool call error: {e}");
438 json_error(
439 StatusCode::BAD_REQUEST,
440 "tool_error",
441 "tool execution failed",
442 )
443 }
444 Err(_) => json_error(
445 StatusCode::GATEWAY_TIMEOUT,
446 "request_timeout",
447 "tool call timed out",
448 ),
449 }
450}
451
452async fn v1_events(
453 State(state): State<AppState>,
454 Query(q): Query<EventsQuery>,
455) -> Sse<impl Stream<Item = Result<SseEvent, std::convert::Infallible>>> {
456 use crate::core::context_os::{ContextEventV1, RedactionLevel, redact_event_payload};
457
458 let ws = sanitize_id(&q.workspace_id.unwrap_or_else(|| "default".to_string()));
459 let ch = sanitize_id(&q.channel_id.unwrap_or_else(|| "default".to_string()));
460 let _ = &state.project_root;
461 let since = q.since.unwrap_or(0);
462 let limit = q.limit.unwrap_or(200).min(1000);
463 let redaction = RedactionLevel::RefsOnly;
464
465 let kind_filter: Option<Vec<String>> = q
466 .kind
467 .as_deref()
468 .map(|k| k.split(',').map(|s| s.trim().to_string()).collect());
469
470 let rt = crate::core::context_os::runtime();
471 let replay = rt.bus.read(&ws, &ch, since, limit);
472
473 let replay = if let Some(ref kinds) = kind_filter {
474 replay
475 .into_iter()
476 .filter(|ev| kinds.contains(&ev.kind))
477 .collect()
478 } else {
479 replay
480 };
481
482 let rx = if let Some(ref kinds) = kind_filter {
483 let kind_refs: Vec<&str> = kinds.iter().map(String::as_str).collect();
484 let filter = crate::core::context_os::TopicFilter::kinds(&kind_refs);
485 if let Some(sub) = rt.bus.subscribe_filtered(&ws, &ch, filter) {
486 crate::core::context_os::SubscriptionKind::Filtered(sub)
487 } else {
488 tracing::warn!("SSE subscriber limit reached for {ws}/{ch}");
489 let (_, rx) = broadcast::channel::<ContextEventV1>(1);
490 crate::core::context_os::SubscriptionKind::Unfiltered(rx)
491 }
492 } else if let Some(sub) = rt.bus.subscribe(&ws, &ch) {
493 crate::core::context_os::SubscriptionKind::Unfiltered(sub)
494 } else {
495 tracing::warn!("SSE subscriber limit reached for {ws}/{ch}");
496 let (_, rx) = broadcast::channel::<ContextEventV1>(1);
497 crate::core::context_os::SubscriptionKind::Unfiltered(rx)
498 };
499
500 rt.metrics.record_sse_connect();
501 rt.metrics.record_events_replayed(replay.len() as u64);
502 rt.metrics.record_workspace_active(&ws);
503
504 let bus = rt.bus.clone();
505 let metrics = rt.metrics.clone();
506 let pending: std::collections::VecDeque<ContextEventV1> = replay.into();
507
508 let stream = futures::stream::unfold(
509 (
510 pending,
511 rx,
512 ws.clone(),
513 ch.clone(),
514 since,
515 redaction,
516 bus,
517 metrics,
518 ),
519 |(mut pending, mut rx, ws, ch, mut last_id, redaction, bus, metrics)| async move {
520 if let Some(mut ev) = pending.pop_front() {
521 last_id = ev.id;
522 redact_event_payload(&mut ev, redaction);
523 let data = serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string());
524 let evt = SseEvent::default()
525 .id(ev.id.to_string())
526 .event(ev.kind)
527 .data(data);
528 return Some((
529 Ok(evt),
530 (pending, rx, ws, ch, last_id, redaction, bus, metrics),
531 ));
532 }
533
534 loop {
535 match rx.recv().await {
536 Ok(mut ev) if ev.id > last_id => {
537 last_id = ev.id;
538 redact_event_payload(&mut ev, redaction);
539 let data = serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string());
540 let evt = SseEvent::default()
541 .id(ev.id.to_string())
542 .event(ev.kind)
543 .data(data);
544 return Some((
545 Ok(evt),
546 (pending, rx, ws, ch, last_id, redaction, bus, metrics),
547 ));
548 }
549 Ok(_) => {}
550 Err(broadcast::error::RecvError::Closed) => return None,
551 Err(broadcast::error::RecvError::Lagged(skipped)) => {
552 let missed = bus.read(&ws, &ch, last_id, skipped as usize);
553 metrics.record_events_replayed(missed.len() as u64);
554 for ev in missed {
555 last_id = last_id.max(ev.id);
556 pending.push_back(ev);
557 }
558 }
559 }
560 }
561 },
562 );
563
564 let metrics_ref = rt.metrics.clone();
565 let guarded = SseDisconnectGuard {
566 inner: Box::pin(stream),
567 metrics: metrics_ref,
568 };
569
570 Sse::new(guarded).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
571}
572
573#[derive(Debug, Deserialize)]
574struct AuditEventsQuery {
575 #[serde(default = "default_audit_limit")]
576 limit: usize,
577}
578
579fn default_audit_limit() -> usize {
580 100
581}
582
583async fn v1_audit_events(Query(q): Query<AuditEventsQuery>) -> impl IntoResponse {
584 let capped = q.limit.min(1000);
585 let boundary_events = crate::core::memory_boundary::load_audit_events(capped);
586 let trail_events = crate::core::audit_trail::load_recent(capped);
587
588 Json(serde_json::json!({
589 "cross_project_events": boundary_events,
590 "audit_trail": trail_events,
591 }))
592}
593
594async fn v1_metrics(State(_state): State<AppState>) -> impl IntoResponse {
595 let rt = crate::core::context_os::runtime();
596 let snap = rt.metrics.snapshot();
597 (
598 StatusCode::OK,
599 Json(serde_json::to_value(snap).unwrap_or_default()),
600 )
601}
602
603const MAX_HANDOFF_PAYLOAD_BYTES: usize = 1_000_000;
604const MAX_HANDOFF_FILES: usize = 50;
605
606async fn v1_a2a_handoff(
607 State(state): State<AppState>,
608 Json(body): Json<Value>,
609) -> impl IntoResponse {
610 let envelope = match crate::core::a2a_transport::parse_envelope(
611 &serde_json::to_string(&body).unwrap_or_default(),
612 ) {
613 Ok(env) => env,
614 Err(e) => {
615 tracing::warn!("a2a handoff parse error: {e}");
616 return (
617 StatusCode::BAD_REQUEST,
618 Json(serde_json::json!({"error": "invalid_envelope"})),
619 );
620 }
621 };
622
623 if envelope.payload_json.len() > MAX_HANDOFF_PAYLOAD_BYTES {
624 tracing::warn!(
625 "a2a handoff payload too large: {} bytes (limit {MAX_HANDOFF_PAYLOAD_BYTES})",
626 envelope.payload_json.len()
627 );
628 return (
629 StatusCode::PAYLOAD_TOO_LARGE,
630 Json(serde_json::json!({"error": "payload_too_large"})),
631 );
632 }
633
634 let rt = crate::core::context_os::runtime();
635 rt.bus.append(
636 &state.project_root,
637 "a2a",
638 &crate::core::context_os::ContextEventKindV1::SessionMutated,
639 Some(&envelope.sender.agent_id),
640 serde_json::json!({
641 "type": "handoff_received",
642 "content_type": format!("{:?}", envelope.content_type),
643 "sender": envelope.sender.agent_id,
644 "payload_size": envelope.payload_json.len(),
645 }),
646 );
647
648 match envelope.content_type {
649 crate::core::a2a_transport::TransportContentType::ContextPackage => {
650 let dir = std::path::Path::new(&state.project_root)
651 .join(".lean-ctx")
652 .join("handoffs")
653 .join("packages");
654 let _ = std::fs::create_dir_all(&dir);
655 evict_oldest_files(&dir, MAX_HANDOFF_FILES);
656 let out = dir.join(format!(
657 "ctx-{}.{}",
658 chrono::Utc::now().format("%Y%m%d_%H%M%S"),
659 crate::core::contracts::PACKAGE_EXTENSION
660 ));
661 if let Err(e) = std::fs::write(&out, &envelope.payload_json) {
662 tracing::error!("a2a handoff write failed: {e}");
663 return (
664 StatusCode::INTERNAL_SERVER_ERROR,
665 Json(serde_json::json!({"error": "write_failed"})),
666 );
667 }
668 (
669 StatusCode::OK,
670 Json(serde_json::json!({
671 "status": "received",
672 "content_type": "context_package",
673 })),
674 )
675 }
676 crate::core::a2a_transport::TransportContentType::HandoffBundle => {
677 let bundle =
683 match crate::core::handoff_transfer_bundle::parse_bundle_v1(&envelope.payload_json)
684 {
685 Ok(b) => b,
686 Err(e) => {
687 tracing::warn!("a2a handoff rejected: not a valid bundle: {e}");
688 return (
689 StatusCode::BAD_REQUEST,
690 Json(serde_json::json!({"error": "invalid_bundle"})),
691 );
692 }
693 };
694 let signature =
695 match crate::core::handoff_transfer_bundle::check_bundle_signature(&bundle) {
696 crate::core::handoff_transfer_bundle::BundleSignatureStatus::Invalid(
697 reason,
698 ) => {
699 tracing::warn!("a2a handoff rejected: signature invalid: {reason}");
700 crate::core::audit_trail::record(
701 crate::core::audit_trail::AuditEntryData {
702 agent_id: envelope.sender.agent_id.clone(),
703 tool: "http:/v1/a2a/handoff".to_string(),
704 action: Some("import_signature_invalid".to_string()),
705 input_hash: String::new(),
706 output_tokens: 0,
707 role: crate::core::roles::active_role_name(),
708 event_type:
709 crate::core::audit_trail::AuditEventType::SecurityViolation,
710 },
711 );
712 return (
713 StatusCode::BAD_REQUEST,
714 Json(serde_json::json!({"error": "invalid_signature"})),
715 );
716 }
717 crate::core::handoff_transfer_bundle::BundleSignatureStatus::Verified(
718 signer,
719 ) => {
720 serde_json::json!({"status": "verified", "signer": signer})
721 }
722 crate::core::handoff_transfer_bundle::BundleSignatureStatus::Unsigned => {
723 serde_json::json!({"status": "unsigned"})
724 }
725 };
726
727 let dir = std::path::Path::new(&state.project_root)
728 .join(".lean-ctx")
729 .join("handoffs");
730 let _ = std::fs::create_dir_all(&dir);
731 evict_oldest_files(&dir, MAX_HANDOFF_FILES);
732 let out = dir.join(format!(
733 "received-{}.json",
734 chrono::Utc::now().format("%Y%m%d_%H%M%S")
735 ));
736 if let Err(e) = std::fs::write(&out, &envelope.payload_json) {
737 tracing::error!("a2a handoff write failed: {e}");
738 return (
739 StatusCode::INTERNAL_SERVER_ERROR,
740 Json(serde_json::json!({"error": "write_failed"})),
741 );
742 }
743 (
744 StatusCode::OK,
745 Json(serde_json::json!({
746 "status": "received",
747 "content_type": "handoff_bundle",
748 "signature": signature,
749 })),
750 )
751 }
752 _ => (
753 StatusCode::OK,
754 Json(serde_json::json!({
755 "status": "received",
756 "content_type": format!("{:?}", envelope.content_type),
757 })),
758 ),
759 }
760}
761
762fn evict_oldest_files(dir: &std::path::Path, max_files: usize) {
763 let Ok(entries) = std::fs::read_dir(dir) else {
764 return;
765 };
766 let mut files: Vec<(std::time::SystemTime, std::path::PathBuf)> = entries
767 .filter_map(|e| {
768 let e = e.ok()?;
769 let meta = e.metadata().ok()?;
770 if meta.is_file() {
771 Some((meta.modified().unwrap_or(std::time::UNIX_EPOCH), e.path()))
772 } else {
773 None
774 }
775 })
776 .collect();
777
778 if files.len() < max_files {
779 return;
780 }
781 files.sort_by_key(|(mtime, _)| *mtime);
782 let to_remove = files.len().saturating_sub(max_files.saturating_sub(1));
783 for (_, path) in files.into_iter().take(to_remove) {
784 let _ = std::fs::remove_file(path);
785 }
786}
787
788async fn a2a_jsonrpc(Json(body): Json<Value>) -> impl IntoResponse {
789 let req: crate::core::a2a::a2a_compat::JsonRpcRequest = match serde_json::from_value(body) {
790 Ok(r) => r,
791 Err(e) => {
792 tracing::debug!("a2a JSON-RPC parse error: {e}");
793 return (
794 StatusCode::BAD_REQUEST,
795 Json(serde_json::json!({
796 "jsonrpc": "2.0",
797 "id": null,
798 "error": {"code": -32700, "message": "invalid request"}
799 })),
800 );
801 }
802 };
803 let resp = crate::core::a2a::a2a_compat::handle_a2a_jsonrpc(&req);
804 let json = serde_json::to_value(resp).unwrap_or_default();
805 (StatusCode::OK, Json(json))
806}
807
808async fn v1_a2a_agent_card(State(state): State<AppState>) -> impl IntoResponse {
809 let card = crate::core::a2a::agent_card::build_agent_card(&state.project_root);
810 (
811 StatusCode::OK,
812 [(header::CONTENT_TYPE, "application/json")],
813 Json(card),
814 )
815}
816
817async fn mcp_server_card() -> impl IntoResponse {
818 let card = serde_json::json!({
819 "name": "lean-ctx",
820 "version": env!("CARGO_PKG_VERSION"),
821 "description": "Context Infrastructure Layer — compression, caching, governance for AI agents",
822 "capabilities": {
823 "tools": true,
824 "resources": false,
825 "prompts": false,
826 "sampling": false
827 },
828 "tool_categories": [
829 {"name": "file_operations", "tools": ["ctx_read", "ctx_search", "ctx_tree", "ctx_edit"], "avg_token_cost": 150},
830 {"name": "session_management", "tools": ["ctx_session", "ctx_compress", "ctx_dedup", "ctx_preload"], "avg_token_cost": 80},
831 {"name": "intelligence", "tools": ["ctx_knowledge", "ctx_semantic_search", "ctx_graph", "ctx_overview"], "avg_token_cost": 200},
832 {"name": "agent_ops", "tools": ["ctx_agent", "ctx_handoff", "ctx_task", "ctx_share"], "avg_token_cost": 120}
833 ],
834 "features": {
835 "compression": "deterministic AST-based, 40-70% token reduction",
836 "caching": "session-scoped with zstd, re-reads ~13 tokens",
837 "audit_trail": "SHA-256 chained JSONL",
838 "rbac": "5 built-in roles with capability-based access",
839 "sandboxing": "Level 0 (subprocess) + Level 1 (OS-level)",
840 "secret_detection": "8 regex patterns + custom"
841 },
842 "security": {
843 "path_jail": true,
844 "rate_limiting": true,
845 "budget_tracking": true,
846 "signed_handoffs": true,
847 "timing_safe_auth": true
848 }
849 });
850 Json(card)
851}
852
853async fn v1_agents_register(
854 State(state): State<AppState>,
855 Json(body): Json<Value>,
856) -> impl IntoResponse {
857 let agent_type = body
858 .get("agent_type")
859 .and_then(|v| v.as_str())
860 .unwrap_or("unknown");
861 let role = body.get("role").and_then(|v| v.as_str());
862 let project_root = body
863 .get("project_root")
864 .and_then(|v| v.as_str())
865 .unwrap_or(&state.project_root);
866
867 let mut registry = crate::core::agents::AgentRegistry::load_or_create();
868 let agent_id = registry.register(agent_type, role, project_root);
869 let _ = registry.save();
870
871 Json(serde_json::json!({
872 "agent_id": agent_id,
873 "status": "registered"
874 }))
875}
876
877async fn v1_agents_heartbeat(Json(body): Json<Value>) -> impl IntoResponse {
878 let agent_id = body.get("agent_id").and_then(|v| v.as_str()).unwrap_or("");
879 let mut registry = crate::core::agents::AgentRegistry::load_or_create();
880 registry.update_heartbeat(agent_id);
881 let _ = registry.save();
882 Json(serde_json::json!({"status": "ok"}))
883}
884
885async fn v1_agents_list() -> impl IntoResponse {
886 let registry = crate::core::agents::AgentRegistry::load_or_create();
887 let active = registry.list_active(None);
888 Json(serde_json::json!({
889 "agents": active.iter().map(|a| serde_json::json!({
890 "agent_id": a.agent_id,
891 "agent_type": a.agent_type,
892 "role": a.role,
893 "status": a.status.to_string(),
894 "last_active": a.last_active.to_rfc3339(),
895 })).collect::<Vec<_>>()
896 }))
897}
898
899async fn v1_agents_deregister(Json(body): Json<Value>) -> impl IntoResponse {
900 let agent_id = body.get("agent_id").and_then(|v| v.as_str()).unwrap_or("");
901 let mut registry = crate::core::agents::AgentRegistry::load_or_create();
902 registry.set_status(
903 agent_id,
904 crate::core::agents::AgentStatus::Finished,
905 Some("deregistered via API"),
906 );
907 let _ = registry.save();
908 Json(serde_json::json!({"status": "deregistered"}))
909}
910
911async fn v1_agents_events_sse()
912-> Sse<impl Stream<Item = Result<SseEvent, std::convert::Infallible>>> {
913 let stream = futures::stream::unfold(0usize, |last_count| async move {
914 loop {
915 tokio::time::sleep(Duration::from_secs(5)).await;
916 let registry = crate::core::agents::AgentRegistry::load_or_create();
917 let active = registry.list_active(None);
918 let count = active.len();
919 if count != last_count {
920 let data = serde_json::json!({
921 "type": "agents_changed",
922 "active_count": count,
923 "agents": active.iter().map(|a| &a.agent_id).collect::<Vec<_>>(),
924 });
925 return Some((
926 Ok::<_, std::convert::Infallible>(SseEvent::default().data(data.to_string())),
927 count,
928 ));
929 }
930 }
931 });
932
933 Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
934}
935
936fn build_app_router(cfg: &HttpServerConfig) -> Router {
937 let project_root = cfg.project_root.to_string_lossy().to_string();
938 let service_project_root = project_root.clone();
939 let service_factory = move || -> Result<LeanCtxServer, std::io::Error> {
940 Ok(LeanCtxServer::new_shared_with_context(
941 &service_project_root,
942 "default",
943 "default",
944 ))
945 };
946 let mcp_http = StreamableHttpService::new(
947 service_factory,
948 Arc::new(
949 rmcp::transport::streamable_http_server::session::local::LocalSessionManager::default(),
950 ),
951 cfg.mcp_http_config(),
952 );
953
954 let rest_server = LeanCtxServer::new_shared_with_context(&project_root, "default", "default");
955
956 let state = AppState {
957 token: cfg.effective_auth_token(),
958 concurrency: Arc::new(tokio::sync::Semaphore::new(cfg.max_concurrency.max(1))),
959 rate: Arc::new(RateLimiter::new(cfg.max_rps, cfg.rate_burst)),
960 project_root,
961 timeout: Duration::from_millis(cfg.request_timeout_ms.max(1)),
962 server: rest_server,
963 };
964
965 Router::new()
966 .route("/health", get(health))
967 .route("/v1/shutdown", axum::routing::post(v1_shutdown))
968 .route("/v1/manifest", get(v1_manifest))
969 .route("/v1/capabilities", get(v1_capabilities))
970 .route("/v1/openapi.json", get(v1_openapi))
971 .route("/v1/tools", get(v1_tools))
972 .route("/v1/tools/call", axum::routing::post(v1_tool_call))
973 .route("/v1/events", get(v1_events))
974 .route(
975 "/v1/context/summary",
976 get(context_views::v1_context_summary),
977 )
978 .route("/v1/events/search", get(context_views::v1_events_search))
979 .route("/v1/events/lineage", get(context_views::v1_event_lineage))
980 .route("/v1/metrics", get(v1_metrics))
981 .route("/v1/audit/events", get(v1_audit_events))
982 .route("/v1/a2a/handoff", axum::routing::post(v1_a2a_handoff))
983 .route("/v1/a2a/agent-card", get(v1_a2a_agent_card))
984 .route("/.well-known/agent.json", get(v1_a2a_agent_card))
985 .route("/.well-known/mcp-server.json", get(mcp_server_card))
986 .route("/a2a", axum::routing::post(a2a_jsonrpc))
987 .route(
988 "/v1/agents/register",
989 axum::routing::post(v1_agents_register),
990 )
991 .route(
992 "/v1/agents/heartbeat",
993 axum::routing::post(v1_agents_heartbeat),
994 )
995 .route("/v1/agents/list", get(v1_agents_list))
996 .route(
997 "/v1/agents/deregister",
998 axum::routing::post(v1_agents_deregister),
999 )
1000 .route("/v1/agents/events", get(v1_agents_events_sse))
1001 .fallback_service(mcp_http)
1002 .layer(axum::extract::DefaultBodyLimit::max(cfg.max_body_bytes))
1003 .layer(middleware::from_fn_with_state(
1004 state.clone(),
1005 rate_limit_middleware,
1006 ))
1007 .layer(middleware::from_fn_with_state(
1008 state.clone(),
1009 concurrency_middleware,
1010 ))
1011 .layer(middleware::from_fn_with_state(
1012 state.clone(),
1013 auth_middleware,
1014 ))
1015 .with_state(state)
1016}
1017
1018pub async fn serve(cfg: HttpServerConfig) -> Result<()> {
1019 crate::core::protocol::set_mcp_context(true);
1020 cfg.validate()?;
1021
1022 crate::core::plugins::PluginManager::init();
1023 crate::core::savings_autopush::spawn_if_enabled();
1024
1025 let warm_root = cfg.project_root.to_string_lossy().to_string();
1034 if !warm_root.is_empty() {
1035 crate::core::index_orchestrator::ensure_all_background(&warm_root);
1036 }
1037
1038 let addr: SocketAddr = format!("{}:{}", cfg.host, cfg.port)
1039 .parse()
1040 .context("invalid host/port")?;
1041
1042 let app = build_app_router(&cfg);
1043
1044 let listener = tokio::net::TcpListener::bind(addr)
1045 .await
1046 .with_context(|| format!("bind {addr}"))?;
1047
1048 tracing::info!(
1049 "lean-ctx Streamable HTTP server listening on http://{addr} (project_root={})",
1050 cfg.project_root.display()
1051 );
1052
1053 axum::serve(listener, app)
1054 .with_graceful_shutdown(async move {
1055 let _ = tokio::signal::ctrl_c().await;
1056 })
1057 .await
1058 .context("http server")?;
1059
1060 fire_session_end();
1061 Ok(())
1062}
1063
1064pub(crate) fn fire_session_end() {
1068 if crate::core::plugins::PluginManager::has_listener("on_session_end") {
1069 let _ = crate::core::plugins::PluginManager::fire_hook(
1070 &crate::core::plugins::executor::HookPoint::OnSessionEnd,
1071 );
1072 }
1073}
1074
1075#[cfg(windows)]
1076impl axum::serve::Listener for crate::ipc::NamedPipeListener {
1077 type Io = tokio::net::windows::named_pipe::NamedPipeServer;
1078 type Addr = String;
1079
1080 async fn accept(&mut self) -> (Self::Io, Self::Addr) {
1081 loop {
1082 match self.accept_pipe().await {
1083 Ok(pipe) => return (pipe, self.name().to_string()),
1084 Err(e) => {
1085 tracing::error!("named pipe accept error: {e}");
1086 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1087 }
1088 }
1089 }
1090 }
1091
1092 fn local_addr(&self) -> std::io::Result<Self::Addr> {
1093 Ok(self.name().to_string())
1094 }
1095}
1096
1097pub async fn serve_ipc(cfg: HttpServerConfig, addr: crate::ipc::DaemonAddr) -> Result<()> {
1100 cfg.validate()?;
1101
1102 crate::core::plugins::PluginManager::init();
1103 crate::core::savings_autopush::spawn_if_enabled();
1104
1105 match addr {
1106 #[cfg(unix)]
1107 crate::ipc::DaemonAddr::Unix(ref path) => {
1108 let app = build_app_router(&cfg);
1109 let listener = crate::ipc::bind_listener(&addr)?;
1110
1111 tracing::info!(
1112 "lean-ctx daemon listening on {} (project_root={})",
1113 path.display(),
1114 cfg.project_root.display()
1115 );
1116
1117 axum::serve(listener, app.into_make_service())
1118 .with_graceful_shutdown(async move {
1119 let _ = tokio::signal::ctrl_c().await;
1120 })
1121 .await
1122 .context("ipc server")?;
1123 Ok(())
1124 }
1125 #[cfg(windows)]
1126 crate::ipc::DaemonAddr::NamedPipe(ref name) => {
1127 let app = build_app_router(&cfg);
1128 let listener = crate::ipc::bind_listener(&addr)?;
1129
1130 tracing::info!(
1131 "lean-ctx daemon listening on {} (project_root={})",
1132 name,
1133 cfg.project_root.display()
1134 );
1135
1136 axum::serve(listener, app.into_make_service())
1137 .with_graceful_shutdown(async move {
1138 let _ = tokio::signal::ctrl_c().await;
1139 })
1140 .await
1141 .context("ipc server")?;
1142 Ok(())
1143 }
1144 }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149 use super::*;
1150 use axum::body::Body;
1151 use axum::http::Request;
1152 use futures::StreamExt;
1153 use rmcp::transport::{StreamableHttpServerConfig, StreamableHttpService};
1154 use serde_json::json;
1155 use tower::ServiceExt;
1156
1157 async fn read_first_sse_message(body: Body) -> String {
1158 let mut stream = body.into_data_stream();
1159 let mut buf: Vec<u8> = Vec::new();
1160 for _ in 0..32 {
1161 let next = tokio::time::timeout(Duration::from_secs(2), stream.next()).await;
1162 let Ok(Some(Ok(bytes))) = next else {
1163 break;
1164 };
1165 buf.extend_from_slice(&bytes);
1166 if buf.windows(2).any(|w| w == b"\n\n") {
1167 break;
1168 }
1169 }
1170 String::from_utf8_lossy(&buf).to_string()
1171 }
1172
1173 #[tokio::test]
1174 async fn auth_token_blocks_requests_without_bearer_header() {
1175 let dir = tempfile::tempdir().expect("tempdir");
1176 let root_str = dir.path().to_string_lossy().to_string();
1177 let service_project_root = root_str.clone();
1178 let service_factory = move || -> Result<LeanCtxServer, std::io::Error> {
1179 Ok(LeanCtxServer::new_shared_with_context(
1180 &service_project_root,
1181 "default",
1182 "default",
1183 ))
1184 };
1185 let cfg = StreamableHttpServerConfig::default()
1186 .with_stateful_mode(false)
1187 .with_json_response(true);
1188
1189 let mcp_http = StreamableHttpService::new(
1190 service_factory,
1191 Arc::new(
1192 rmcp::transport::streamable_http_server::session::local::LocalSessionManager::default(),
1193 ),
1194 cfg,
1195 );
1196
1197 let state = AppState {
1198 token: Some("secret".to_string()),
1199 concurrency: Arc::new(tokio::sync::Semaphore::new(4)),
1200 rate: Arc::new(RateLimiter::new(50, 100)),
1201 project_root: root_str.clone(),
1202 timeout: Duration::from_secs(30),
1203 server: LeanCtxServer::new_shared_with_context(&root_str, "default", "default"),
1204 };
1205
1206 let app = Router::new()
1207 .fallback_service(mcp_http)
1208 .layer(middleware::from_fn_with_state(
1209 state.clone(),
1210 auth_middleware,
1211 ))
1212 .with_state(state);
1213
1214 let body = json!({
1215 "jsonrpc": "2.0",
1216 "id": 1,
1217 "method": "tools/list",
1218 "params": {}
1219 })
1220 .to_string();
1221
1222 let req = Request::builder()
1223 .method("POST")
1224 .uri("/")
1225 .header("Host", "localhost")
1226 .header("Accept", "application/json, text/event-stream")
1227 .header("Content-Type", "application/json")
1228 .body(Body::from(body))
1229 .expect("request");
1230
1231 let resp = app.clone().oneshot(req).await.expect("resp");
1232 assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
1233 }
1234
1235 #[tokio::test]
1236 async fn mcp_service_factory_isolates_per_client_state() {
1237 let dir = tempfile::tempdir().expect("tempdir");
1238 let root_str = dir.path().to_string_lossy().to_string();
1239
1240 let service_project_root = root_str.clone();
1242 let service_factory = move || -> Result<LeanCtxServer, std::convert::Infallible> {
1243 Ok(LeanCtxServer::new_shared_with_context(
1244 &service_project_root,
1245 "default",
1246 "default",
1247 ))
1248 };
1249
1250 let s1 = service_factory().expect("server 1");
1251 let s2 = service_factory().expect("server 2");
1252
1253 *s1.client_name.write().await = "client-a".to_string();
1256 *s2.client_name.write().await = "client-b".to_string();
1257
1258 let a = s1.client_name.read().await.clone();
1259 let b = s2.client_name.read().await.clone();
1260 assert_eq!(a, "client-a");
1261 assert_eq!(b, "client-b");
1262 }
1263
1264 #[tokio::test]
1265 async fn rate_limit_returns_429_when_exhausted() {
1266 let state = AppState {
1267 token: None,
1268 concurrency: Arc::new(tokio::sync::Semaphore::new(16)),
1269 rate: Arc::new(RateLimiter::new(1, 1)),
1270 project_root: ".".to_string(),
1271 timeout: Duration::from_secs(30),
1272 server: LeanCtxServer::new_shared_with_context(".", "default", "default"),
1273 };
1274
1275 let app = Router::new()
1276 .route("/limited", get(|| async { (StatusCode::OK, "ok\n") }))
1277 .layer(middleware::from_fn_with_state(
1278 state.clone(),
1279 rate_limit_middleware,
1280 ))
1281 .with_state(state);
1282
1283 let req1 = Request::builder()
1284 .method("GET")
1285 .uri("/limited")
1286 .header("Host", "localhost")
1287 .body(Body::empty())
1288 .expect("req1");
1289 let resp1 = app.clone().oneshot(req1).await.expect("resp1");
1290 assert_eq!(resp1.status(), StatusCode::OK);
1291
1292 let req2 = Request::builder()
1293 .method("GET")
1294 .uri("/limited")
1295 .header("Host", "localhost")
1296 .body(Body::empty())
1297 .expect("req2");
1298 let resp2 = app.clone().oneshot(req2).await.expect("resp2");
1299 assert_eq!(resp2.status(), StatusCode::TOO_MANY_REQUESTS);
1300 }
1301
1302 #[tokio::test]
1303 async fn audit_events_endpoint_returns_json() {
1304 let dir = tempfile::tempdir().expect("tempdir");
1305 let root_str = dir.path().to_string_lossy().to_string();
1306
1307 let state = AppState {
1308 token: None,
1309 concurrency: Arc::new(tokio::sync::Semaphore::new(16)),
1310 rate: Arc::new(RateLimiter::new(50, 100)),
1311 project_root: root_str.clone(),
1312 timeout: Duration::from_secs(30),
1313 server: LeanCtxServer::new_shared_with_context(&root_str, "default", "default"),
1314 };
1315
1316 let app = Router::new()
1317 .route("/v1/audit/events", get(v1_audit_events))
1318 .with_state(state);
1319
1320 let req = Request::builder()
1321 .method("GET")
1322 .uri("/v1/audit/events?limit=10")
1323 .header("Host", "localhost")
1324 .body(Body::empty())
1325 .unwrap();
1326
1327 let resp = app.oneshot(req).await.unwrap();
1328 assert_eq!(resp.status(), StatusCode::OK);
1329
1330 let body = axum::body::to_bytes(resp.into_body(), 1_000_000)
1331 .await
1332 .unwrap();
1333 let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
1334 assert!(json.get("cross_project_events").unwrap().is_array());
1335 assert!(json.get("audit_trail").unwrap().is_array());
1336 }
1337
1338 #[tokio::test]
1339 async fn capabilities_endpoint_returns_contract() {
1340 let dir = tempfile::tempdir().expect("tempdir");
1341 let root_str = dir.path().to_string_lossy().to_string();
1342
1343 let state = AppState {
1344 token: None,
1345 concurrency: Arc::new(tokio::sync::Semaphore::new(16)),
1346 rate: Arc::new(RateLimiter::new(50, 100)),
1347 project_root: root_str.clone(),
1348 timeout: Duration::from_secs(30),
1349 server: LeanCtxServer::new_shared_with_context(&root_str, "default", "default"),
1350 };
1351
1352 let app = Router::new()
1353 .route("/v1/capabilities", get(v1_capabilities))
1354 .with_state(state);
1355
1356 let req = Request::builder()
1357 .method("GET")
1358 .uri("/v1/capabilities")
1359 .header("Host", "localhost")
1360 .body(Body::empty())
1361 .unwrap();
1362
1363 let resp = app.oneshot(req).await.unwrap();
1364 assert_eq!(resp.status(), StatusCode::OK);
1365
1366 let body = axum::body::to_bytes(resp.into_body(), 1_000_000)
1367 .await
1368 .unwrap();
1369 let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
1370 assert_eq!(json["contract_version"], json!(1));
1371 assert!(json["tools"]["total"].as_u64().unwrap() > 0);
1372 assert!(json["features"]["compression"].as_bool().unwrap());
1373 assert!(json["contracts"].is_object());
1374 }
1375
1376 #[tokio::test]
1377 async fn openapi_endpoint_returns_spec() {
1378 let dir = tempfile::tempdir().expect("tempdir");
1379 let root_str = dir.path().to_string_lossy().to_string();
1380
1381 let state = AppState {
1382 token: None,
1383 concurrency: Arc::new(tokio::sync::Semaphore::new(16)),
1384 rate: Arc::new(RateLimiter::new(50, 100)),
1385 project_root: root_str.clone(),
1386 timeout: Duration::from_secs(30),
1387 server: LeanCtxServer::new_shared_with_context(&root_str, "default", "default"),
1388 };
1389
1390 let app = Router::new()
1391 .route("/v1/openapi.json", get(v1_openapi))
1392 .with_state(state);
1393
1394 let req = Request::builder()
1395 .method("GET")
1396 .uri("/v1/openapi.json")
1397 .header("Host", "localhost")
1398 .body(Body::empty())
1399 .unwrap();
1400
1401 let resp = app.oneshot(req).await.unwrap();
1402 assert_eq!(resp.status(), StatusCode::OK);
1403
1404 let body = axum::body::to_bytes(resp.into_body(), 1_000_000)
1405 .await
1406 .unwrap();
1407 let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
1408 assert_eq!(json["openapi"], json!("3.0.3"));
1409 assert!(json["paths"]["/v1/capabilities"]["get"].is_object());
1410 assert!(json["paths"]["/v1/openapi.json"]["get"].is_object());
1411 }
1412
1413 #[tokio::test]
1414 async fn events_endpoint_replays_tool_call_event() {
1415 use crate::core::context_os::{self, ContextEventKindV1};
1416
1417 let dir = tempfile::tempdir().expect("tempdir");
1418 std::fs::create_dir_all(dir.path().join(".git")).expect("git marker");
1419 std::fs::write(dir.path().join("a.txt"), "ok").expect("file");
1420 let root_str = dir.path().to_string_lossy().to_string();
1421
1422 let state = AppState {
1423 token: None,
1424 concurrency: Arc::new(tokio::sync::Semaphore::new(16)),
1425 rate: Arc::new(RateLimiter::new(50, 100)),
1426 project_root: root_str.clone(),
1427 timeout: Duration::from_secs(30),
1428 server: LeanCtxServer::new_shared_with_context(&root_str, "default", "default"),
1429 };
1430
1431 let app = Router::new()
1432 .route("/v1/events", get(v1_events))
1433 .with_state(state);
1434
1435 let rt = context_os::runtime();
1437 rt.bus.append(
1438 "ws1",
1439 "ch1",
1440 &ContextEventKindV1::ToolCallRecorded,
1441 Some("test-agent"),
1442 json!({"tool": "ctx_session", "action": "status"}),
1443 );
1444
1445 let req = Request::builder()
1446 .method("GET")
1447 .uri("/v1/events?workspaceId=ws1&channelId=ch1&since=0&limit=1")
1448 .header("Host", "localhost")
1449 .header("Accept", "text/event-stream")
1450 .body(Body::empty())
1451 .expect("req");
1452 let resp = app.clone().oneshot(req).await.expect("events");
1453 assert_eq!(resp.status(), StatusCode::OK);
1454
1455 let msg = read_first_sse_message(resp.into_body()).await;
1456 assert!(msg.contains("event: tool_call_recorded"), "msg={msg:?}");
1457 assert!(msg.contains("\"ws1\""), "msg={msg:?}");
1458 assert!(msg.contains("\"ch1\""), "msg={msg:?}");
1459 }
1460}