Skip to main content

lean_ctx/
server_client.rs

1use crate::config;
2use crate::models::{
3    ProjectContext, ProjectResolutionRequest, ProjectResolutionResponse, ServerConnection,
4    TelemetryIngestRequest, ToolCallRequest, ToolCallResponse, ToolListResponse,
5};
6use anyhow::{anyhow, Context, Result};
7use serde::de::DeserializeOwned;
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11pub struct ServerClient {
12    connection: ServerConnection,
13}
14
15impl ServerClient {
16    pub fn load() -> Result<Self> {
17        let connection = config::load_connection()?.ok_or_else(|| {
18            anyhow!("No server connection saved. Run `nebu-ctx connect --endpoint <url> --token <token>`.")
19        })?;
20        Ok(Self { connection })
21    }
22
23    pub fn new(connection: ServerConnection) -> Self {
24        Self { connection }
25    }
26
27    pub fn endpoint(&self) -> &str {
28        &self.connection.endpoint
29    }
30
31    pub fn health(&self) -> Result<Value> {
32        self.get_json("/health")
33    }
34
35    pub fn manifest(&self) -> Result<Value> {
36        self.get_json("/v1/manifest")
37    }
38
39    pub fn list_tools(&self) -> Result<ToolListResponse> {
40        self.get_json("/v1/tools")
41    }
42
43    pub fn resolve_project(
44        &self,
45        project_context: &ProjectContext,
46    ) -> Result<ProjectResolutionResponse> {
47        self.post_json(
48            "/v1/projects/resolve",
49            &ProjectResolutionRequest {
50                fingerprint: project_context.fingerprint.clone(),
51                suggested_slug: Some(project_context.project_slug.clone()),
52                checkout_binding: Some(project_context.checkout_binding.clone()),
53                project_metadata: project_context.project_metadata.clone(),
54            },
55        )
56    }
57
58    pub fn call_tool(
59        &self,
60        tool_name: &str,
61        arguments: Map<String, Value>,
62        project_context: &ProjectContext,
63    ) -> Result<Value> {
64        let response: ToolCallResponse = self.post_json(
65            "/v1/tools/call",
66            &ToolCallRequest {
67                name: tool_name.to_string(),
68                arguments,
69                project_id: None,
70                project_slug: Some(project_context.project_slug.clone()),
71                repository_fingerprint: Some(project_context.fingerprint.clone()),
72                checkout_binding: Some(project_context.checkout_binding.clone()),
73                project_metadata: project_context.project_metadata.clone(),
74            },
75        )?;
76
77        Ok(response.result)
78    }
79
80    /// Posts a single tool-call telemetry event to the server for dashboard aggregation.
81    /// Only token counts and metadata are sent; no raw content.
82    pub fn ingest_telemetry(&self, request: &TelemetryIngestRequest) -> Result<()> {
83        let _: serde_json::Value = self.post_json("/v1/telemetry/ingest", request)?;
84        Ok(())
85    }
86
87    /// Syncs the full project code index (files, symbols, call edges) to the server.
88    /// Returns the number of files, symbols, and edges successfully synced.
89    pub fn sync_index(&self, request: &IndexSyncPayload) -> Result<serde_json::Value> {
90        self.post_json("/v1/index/sync", request)
91    }
92
93    fn get_json<T>(&self, path: &str) -> Result<T>
94    where
95        T: DeserializeOwned,
96    {
97        let response = ureq::get(&self.url(path))
98            .header(
99                "Authorization",
100                &format!("Bearer {}", self.connection.token.trim()),
101            )
102            .call()
103            .map_err(|error| anyhow!("Request to {} failed: {}", self.url(path), error))?;
104        Self::read_json(response)
105    }
106
107    fn post_json<TResponse, TRequest>(&self, path: &str, request: &TRequest) -> Result<TResponse>
108    where
109        TResponse: DeserializeOwned,
110        TRequest: Serialize,
111    {
112        let body = serde_json::to_vec(request).context("failed to serialize request")?;
113        let response = ureq::post(&self.url(path))
114            .header(
115                "Authorization",
116                &format!("Bearer {}", self.connection.token.trim()),
117            )
118            .header("Content-Type", "application/json")
119            .send(body.as_slice())
120            .map_err(|error| anyhow!("Request to {} failed: {}", self.url(path), error))?;
121        Self::read_json(response)
122    }
123
124    /// Deserializes a JSON response body into a target type.
125    fn read_json<T>(response: ureq::http::Response<ureq::Body>) -> Result<T>
126    where
127        T: DeserializeOwned,
128    {
129        let mut body = response.into_body();
130        let payload = body.read_to_string().context("failed to read response body")?;
131        serde_json::from_str(&payload).context("failed to parse server response")
132    }
133
134    /// Combines the normalized endpoint and a relative API path.
135    fn url(&self, path: &str) -> String {
136        format!("{}{}", self.connection.endpoint.trim_end_matches('/'), path)
137    }
138}
139
140/// Payload for syncing a project's code index to the server.
141#[derive(Debug, Serialize, Deserialize)]
142pub struct IndexSyncPayload {
143    pub project_id: String,
144    pub files: Vec<IndexSyncFile>,
145    pub symbols: Vec<IndexSyncSymbol>,
146    pub edges: Vec<IndexSyncEdge>,
147}
148
149/// A single file entry in the index sync payload.
150#[derive(Debug, Serialize, Deserialize)]
151pub struct IndexSyncFile {
152    pub path: String,
153    pub hash: String,
154    pub language: String,
155    pub line_count: usize,
156    pub token_count: usize,
157    pub exports: Vec<String>,
158    pub summary: String,
159}
160
161/// A single symbol entry in the index sync payload.
162#[derive(Debug, Serialize, Deserialize)]
163pub struct IndexSyncSymbol {
164    pub file_path: String,
165    pub name: String,
166    pub kind: String,
167    pub start_line: usize,
168    pub end_line: usize,
169    pub is_exported: bool,
170}
171
172/// A single call edge in the index sync payload.
173#[derive(Debug, Serialize, Deserialize)]
174pub struct IndexSyncEdge {
175    pub from_symbol: String,
176    pub to_symbol: String,
177    pub kind: String,
178}
179
180/// Posts every current, high-confidence fact from local `knowledge.json` to the
181/// server-backed `ctx_knowledge` store. Called after auto-consolidation and from
182/// `handle_stop()` to keep PostgreSQL in sync with the local session outcome.
183/// Silently returns if the server is not configured or any call fails.
184pub fn post_knowledge_to_server(project_root: &str) {
185    let Ok(client) = ServerClient::load() else {
186        return;
187    };
188    let ctx = crate::git_context::discover_project_context(std::path::Path::new(project_root));
189    let knowledge = crate::core::knowledge::ProjectKnowledge::load_or_create(project_root);
190
191    for fact in knowledge
192        .facts
193        .iter()
194        .filter(|f| f.is_current() && f.confidence >= 0.7)
195    {
196        let mut args = Map::new();
197        args.insert("action".to_string(), Value::String("remember".to_string()));
198        args.insert("category".to_string(), Value::String(fact.category.clone()));
199        args.insert("key".to_string(), Value::String(fact.key.clone()));
200        args.insert("value".to_string(), Value::String(fact.value.clone()));
201        args.insert(
202            "confidence".to_string(),
203            serde_json::json!(fact.confidence),
204        );
205        let _ = client.call_tool("ctx_knowledge", args, &ctx);
206    }
207}
208
209/// Posts a session summary to `ctx_brain` when a session is saved.
210/// Silently returns if the server is not configured.
211pub fn post_session_to_brain(session: &crate::core::session::SessionState) {
212    let Ok(client) = ServerClient::load() else {
213        return;
214    };
215    let current_dir = std::env::current_dir().unwrap_or_default();
216    let ctx = crate::git_context::discover_project_context(&current_dir);
217
218    let task = session
219        .task
220        .as_ref()
221        .map(|t| t.description.as_str())
222        .unwrap_or("(no task)");
223    let summary = format!(
224        "session={} task=\"{}\" calls={} tokens_saved={} decisions={} findings={}",
225        session.id,
226        task,
227        session.stats.total_tool_calls,
228        session.stats.total_tokens_saved,
229        session.decisions.len(),
230        session.findings.len(),
231    );
232    let key = format!("session-{}", session.id);
233
234    let mut args = Map::new();
235    args.insert("action".to_string(), Value::String("store".to_string()));
236    args.insert("key".to_string(), Value::String(key));
237    args.insert("value".to_string(), Value::String(summary));
238    let _ = client.call_tool("ctx_brain", args, &ctx);
239}