lspz 0.11.7

AI-friendly LSP compression proxy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! AgentPool — multi-language LSP session management for AI agents.

use std::collections::HashMap;

use super::AgentHandle;

/// A pool of LSP sessions managed by language identifier.
///
/// Sessions are lazily spawned on the first query for a given language.
/// All operations delegate to [`AgentHandle`] instances internally.
pub struct AgentPool {
    handles: HashMap<String, AgentHandle>,
    backends: HashMap<String, BackendConfig>,
    compression: bool,
}

struct BackendConfig {
    backend: String,
    workspace_root: Option<String>,
}

impl std::fmt::Debug for AgentPool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AgentPool")
            .field("languages", &self.backends.keys().collect::<Vec<_>>())
            .field("active_handles", &self.handles.len())
            .field("compression", &self.compression)
            .finish()
    }
}

impl AgentPool {
    /// Create a new [`AgentPoolBuilder`].
    pub fn builder() -> AgentPoolBuilder {
        AgentPoolBuilder::default()
    }

    async fn handle_for(&mut self, language: &str) -> Result<&mut AgentHandle, anyhow::Error> {
        if !self.handles.contains_key(language) {
            let cfg = self.backends.get(language).ok_or_else(|| {
                anyhow::anyhow!("no backend registered for language '{language}'")
            })?;
            let mut builder = AgentHandle::builder()
                .backend(&cfg.backend)
                .language(language)
                .enable_compression(self.compression);
            if let Some(root) = &cfg.workspace_root {
                builder = builder.workspace_root(root);
            }
            let handle = builder.start().await?;
            tracing::info!(language, "LSP handle created via pool");
            self.handles.insert(language.to_owned(), handle);
        }
        Ok(self.handles.get_mut(language).unwrap())
    }

    /// Insert a pre-constructed [`AgentHandle`] for testing.
    #[allow(dead_code)]
    pub fn insert_handle(&mut self, language: &str, handle: AgentHandle) {
        self.backends
            .entry(language.to_owned())
            .or_insert_with(|| BackendConfig {
                backend: String::new(),
                workspace_root: None,
            });
        self.handles.insert(language.to_owned(), handle);
    }

    // ── Query methods (delegation to AgentHandle) ─────────────────────

    /// Get diagnostics for a file using the specified language's LSP server.
    pub async fn get_diagnostics(
        &mut self,
        uri: &str,
        language: &str,
    ) -> Result<String, anyhow::Error> {
        self.handle_for(language).await?.get_diagnostics(uri).await
    }

    /// Get completions at a cursor position.
    pub async fn get_completions(
        &mut self,
        uri: &str,
        language: &str,
        line: u32,
        character: u32,
    ) -> Result<String, anyhow::Error> {
        self.handle_for(language)
            .await?
            .get_completions(uri, line, character)
            .await
    }

    /// Get document symbols using the specified language's LSP server.
    pub async fn get_symbols(
        &mut self,
        uri: &str,
        language: &str,
    ) -> Result<String, anyhow::Error> {
        self.handle_for(language).await?.get_symbols(uri).await
    }

    // ── Refactoring operations ──────────────────────────────────────────

    /// Rename a symbol.
    pub async fn rename(
        &mut self,
        uri: &str,
        language: &str,
        line: u32,
        character: u32,
        new_name: &str,
    ) -> Result<String, anyhow::Error> {
        self.handle_for(language)
            .await?
            .rename(uri, line, character, new_name)
            .await
    }

    /// Get code actions.
    pub async fn code_action(
        &mut self,
        uri: &str,
        language: &str,
        line: u32,
        character: u32,
        diagnostics: Option<Vec<serde_json::Value>>,
        only: Option<Vec<String>>,
    ) -> Result<String, anyhow::Error> {
        self.handle_for(language)
            .await?
            .code_action(uri, line, character, diagnostics, only)
            .await
    }

    /// Format a file.
    pub async fn formatting(
        &mut self,
        uri: &str,
        language: &str,
        options: Option<serde_json::Value>,
    ) -> Result<String, anyhow::Error> {
        self.handle_for(language)
            .await?
            .formatting(uri, options)
            .await
    }

    // ── Raw request ──────────────────────────────────────────────────

    /// Send a raw LSP request and return the response as a JSON string.
    pub async fn send_raw(
        &mut self,
        language: &str,
        method: &str,
        params: serde_json::Value,
    ) -> Result<String, anyhow::Error> {
        self.handle_for(language)
            .await?
            .send_raw(method, params)
            .await
    }

    // ── Compression helpers ─────────────────────────────────────────

    /// Expand compressed diagnostics back to standard LSP format.
    pub fn inflate(compressed_json: &str) -> Result<String, anyhow::Error> {
        AgentHandle::inflate(compressed_json)
    }

    /// Compress standard diagnostics into compact format.
    pub fn compress(raw_json: &str) -> Result<String, anyhow::Error> {
        AgentHandle::compress(raw_json)
    }

    // ── File sync notifications ──────────────────────────────────────

    /// Notify the LSP server that a file's content has changed.
    pub async fn notify_change(
        &mut self,
        uri: &str,
        language: &str,
        content: &str,
    ) -> Result<(), anyhow::Error> {
        self.handle_for(language)
            .await?
            .notify_change(uri, content)
            .await
    }

    /// Notify the LSP server that a file has been closed.
    pub async fn notify_close(&mut self, uri: &str, language: &str) -> Result<(), anyhow::Error> {
        self.handle_for(language).await?.notify_close(uri).await
    }

    /// Notify the LSP server that a file has been saved.
    pub async fn notify_save(&mut self, uri: &str, language: &str) -> Result<(), anyhow::Error> {
        self.handle_for(language).await?.notify_save(uri).await
    }

    // ── Shutdown ─────────────────────────────────────────────────────

    /// Shut down all LSP server sessions.
    pub async fn shutdown_all(self) -> Result<(), anyhow::Error> {
        for (language, handle) in self.handles {
            if let Err(e) = handle.shutdown().await {
                tracing::warn!(language, error = %e, "Failed to shutdown handle");
            }
        }
        Ok(())
    }
}

/// Builder for [`AgentPool`].
#[derive(Default)]
pub struct AgentPoolBuilder {
    backends: Vec<(String, String)>,
    workspace_root: Option<String>,
    compression: bool,
}

impl AgentPoolBuilder {
    /// Register an LSP backend for a language identifier.
    pub fn register(mut self, language: impl Into<String>, backend: impl Into<String>) -> Self {
        self.backends.push((language.into(), backend.into()));
        self
    }

    /// Set a shared workspace root for all registered backends.
    pub fn workspace_root(mut self, path: impl Into<String>) -> Self {
        self.workspace_root = Some(path.into());
        self
    }

    /// Enable compression (default: disabled).
    pub fn enable_compression(mut self, enabled: bool) -> Self {
        self.compression = enabled;
        self
    }

    /// Create an [`AgentPool`] with registered backends.
    ///
    /// Sessions are **not** spawned eagerly — they are created lazily on first
    /// query via the internal language dispatcher.
    pub async fn start_all(self) -> Result<AgentPool, anyhow::Error> {
        let mut backends = HashMap::new();
        for (language, backend) in &self.backends {
            backends.insert(
                language.clone(),
                BackendConfig {
                    backend: backend.clone(),
                    workspace_root: self.workspace_root.clone(),
                },
            );
        }

        Ok(AgentPool {
            handles: HashMap::new(),
            backends,
            compression: self.compression,
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::codec::json_rpc::LspMessage;
    use crate::mcp::LspSession;
    use crate::transport::mock::MockTransport;
    use serde_json::Value;

    use super::*;

    fn mock_handle(responses: Vec<LspMessage>) -> AgentHandle {
        let mock = MockTransport::new();
        for msg in responses {
            mock.push_message(&msg).unwrap();
        }
        let session = LspSession::with_transport(Box::new(mock));
        AgentHandle::new(session, "rust".into(), false)
    }

    #[tokio::test]
    async fn test_builder_register_languages() {
        let pool = AgentPool::builder()
            .register("rust", "rust-analyzer")
            .register("go", "gopls")
            .start_all()
            .await
            .unwrap();

        assert_eq!(pool.backends.len(), 2);
    }

    #[tokio::test]
    async fn test_get_diagnostics_unknown_language() {
        let mut pool = AgentPool::builder()
            .register("rust", "rust-analyzer")
            .start_all()
            .await
            .unwrap();

        let (uri, _tmp) = temp_file("fn main() {}");
        let err = pool.get_diagnostics(&uri, "python").await.unwrap_err();
        assert!(err.to_string().contains("no backend registered"), "{err}");
    }

    #[tokio::test]
    async fn test_insert_handle_and_query() {
        let (uri, _tmp) = temp_file("fn main() {}");
        let diag_notif = LspMessage::Notification {
            method: "textDocument/publishDiagnostics".into(),
            params: serde_json::json!({
                "uri": uri,
                "diagnostics": [{
                    "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 1, "character": 0 } },
                    "severity": 1,
                    "message": "pool test",
                }],
            }),
        };

        let handle = mock_handle(vec![diag_notif]);

        let mut pool = AgentPool::builder()
            .register("rust", "rust-analyzer")
            .start_all()
            .await
            .unwrap();

        pool.insert_handle("rust", handle);

        let result = pool.get_diagnostics(&uri, "rust").await.unwrap();
        let parsed: Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["diagnostics"][0]["message"], "pool test");
    }

    #[tokio::test]
    async fn test_multi_language_cross_talk() {
        let (uri_a, _keep_a) = temp_file("fn main() {}");
        let (uri_b, _keep_b) = temp_file("x = 1");

        let handle_a = {
            let mock = MockTransport::new();
            mock.push_message(&LspMessage::Notification {
                method: "textDocument/publishDiagnostics".into(),
                params: serde_json::json!({
                    "uri": uri_a,
                    "diagnostics": [{
                        "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 1, "character": 0 } },
                        "severity": 1,
                        "message": "rust diag",
                    }],
                }),
            })
            .unwrap();
            let session = LspSession::with_transport(Box::new(mock));
            AgentHandle::new(session, "rust".into(), false)
        };

        let handle_b = {
            let mock = MockTransport::new();
            mock.push_message(&LspMessage::Notification {
                method: "textDocument/publishDiagnostics".into(),
                params: serde_json::json!({
                    "uri": uri_b,
                    "diagnostics": [{
                        "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 1, "character": 0 } },
                        "severity": 2,
                        "message": "python diag",
                    }],
                }),
            })
            .unwrap();
            let session = LspSession::with_transport(Box::new(mock));
            AgentHandle::new(session, "python".into(), false)
        };

        let mut pool = AgentPool::builder()
            .register("rust", "rust-analyzer")
            .register("python", "basedpyright")
            .start_all()
            .await
            .unwrap();

        pool.insert_handle("rust", handle_a);
        pool.insert_handle("python", handle_b);

        let result_a = pool.get_diagnostics(&uri_a, "rust").await.unwrap();
        let parsed_a: Value = serde_json::from_str(&result_a).unwrap();
        assert_eq!(parsed_a["diagnostics"][0]["message"], "rust diag");

        let result_b = pool.get_diagnostics(&uri_b, "python").await.unwrap();
        let parsed_b: Value = serde_json::from_str(&result_b).unwrap();
        assert_eq!(parsed_b["diagnostics"][0]["message"], "python diag");
    }

    #[tokio::test]
    async fn test_inflate_compress() {
        let raw = serde_json::json!({
            "uri": "file:///test.rs",
            "diagnostics": []
        });
        let compact = AgentPool::compress(&raw.to_string()).unwrap();
        let expanded = AgentPool::inflate(&compact).unwrap();
        let parsed: Value = serde_json::from_str(&expanded).unwrap();
        assert_eq!(parsed["uri"], "file:///test.rs");
    }

    fn temp_file(content: &str) -> (String, tempfile::NamedTempFile) {
        let mut f = tempfile::Builder::new().suffix(".rs").tempfile().unwrap();
        use std::io::Write;
        f.write_all(content.as_bytes()).unwrap();
        let path = f.path().to_string_lossy().to_string();
        (format!("file://{path}"), f)
    }
}