collet 0.1.0

Relentless agentic coding orchestrator with zero-drop agent loops
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
pub mod convert;
pub mod server_config;

mod tests;

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use anyhow::{Context, Result};
use serde::Deserialize;
use serde_json::json;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};

use super::protocol::{
    ClientCapabilities, Diagnostic, DocumentSymbol, DocumentSymbolParams, InitializeParams,
    LspNotification, LspRequest, LspResponse, TextDocumentIdentifier,
};

pub use convert::{path_to_uri, to_repo_symbols, uri_to_path};
pub use server_config::{
    LspServerConfig, extension_to_language_id, find_missing_server_for_language,
    find_server_for_language, known_servers,
};

// ---------------------------------------------------------------------------
// Diagnostics cache type
// ---------------------------------------------------------------------------

/// Shared diagnostics cache: URI -> diagnostics list.
pub type DiagnosticsCache = Arc<std::sync::Mutex<HashMap<String, Vec<Diagnostic>>>>;

/// Helper for parsing `textDocument/publishDiagnostics` params.
#[derive(Deserialize)]
struct PublishDiagnosticsParams {
    uri: String,
    diagnostics: Vec<Diagnostic>,
}

// ---------------------------------------------------------------------------
// Pending request tracking
// ---------------------------------------------------------------------------

type PendingRequests =
    Arc<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<LspResponse>>>>;

// ---------------------------------------------------------------------------
// LSP client
// ---------------------------------------------------------------------------

pub struct LspClient {
    process: Child,
    stdin: BufWriter<ChildStdin>,
    next_id: u64,
    server_name: String,
    /// Pending request senders — the background reader routes responses here.
    pending_requests: PendingRequests,
    /// Diagnostics cache populated by the background reader.
    diagnostics: DiagnosticsCache,
    /// Monotonically increasing counter; incremented on every `publishDiagnostics`.
    /// Callers read this before sending a notification and poll until it advances.
    diag_version: Arc<AtomicU64>,
    /// Handle for the background stdout reader task.
    _reader_handle: tokio::task::JoinHandle<()>,
}

impl LspClient {
    /// Return the child process PID (if available).
    pub fn pid(&self) -> Option<u32> {
        self.process.id()
    }

    /// Current value of the diagnostics version counter.
    ///
    /// Incremented by the background reader on every `publishDiagnostics`
    /// notification.  Read this before sending a file notification, then poll
    /// until the value advances to detect when fresh diagnostics have arrived.
    pub fn diag_version(&self) -> u64 {
        self.diag_version.load(Ordering::Relaxed)
    }

    /// Spawn a language server process with piped stdio.
    pub fn start(config: &LspServerConfig, _root_dir: &str) -> Result<Self> {
        let mut child = Command::new(&config.command)
            .args(&config.args)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .with_context(|| format!("Failed to start language server: {}", config.command))?;

        let stdin = child.stdin.take().expect("stdin should be piped");
        let stdout = child.stdout.take().expect("stdout should be piped");

        let pending_requests: PendingRequests = Arc::new(std::sync::Mutex::new(HashMap::new()));
        let diagnostics: DiagnosticsCache = Arc::new(std::sync::Mutex::new(HashMap::new()));
        let diag_version = Arc::new(AtomicU64::new(0));

        let server_name = config.command.clone();
        let reader_handle = {
            let pending = Arc::clone(&pending_requests);
            let diags = Arc::clone(&diagnostics);
            let ver = Arc::clone(&diag_version);
            let name = server_name.clone();
            tokio::spawn(async move {
                background_reader(BufReader::new(stdout), pending, diags, ver, name).await;
            })
        };

        Ok(Self {
            process: child,
            stdin: BufWriter::new(stdin),
            next_id: 1,
            server_name,
            pending_requests,
            diagnostics,
            diag_version,
            _reader_handle: reader_handle,
        })
    }

    /// Send a JSON-RPC request and wait for the matching response.
    pub async fn send_request(
        &mut self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<LspResponse> {
        let id = self.next_id;
        self.next_id += 1;

        let request = LspRequest {
            jsonrpc: "2.0".into(),
            id,
            method: method.into(),
            params,
        };

        let body = serde_json::to_string(&request)?;
        let header = format!("Content-Length: {}\r\n\r\n", body.len());

        // Register a oneshot channel for this request ID.
        let (tx, rx) = tokio::sync::oneshot::channel();
        {
            let mut pending = self
                .pending_requests
                .lock()
                .map_err(|e| anyhow::anyhow!("pending_requests mutex poisoned: {e}"))?;
            pending.insert(id, tx);
        }

        self.stdin.write_all(header.as_bytes()).await?;
        self.stdin.write_all(body.as_bytes()).await?;
        self.stdin.flush().await?;

        // Wait for the background reader to deliver the response.
        rx.await.context(format!(
            "Background reader dropped before response for request {id} to {}",
            self.server_name
        ))
    }

    /// Send a JSON-RPC notification (no response expected).
    pub async fn send_notification(
        &mut self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<()> {
        let notification = LspNotification {
            jsonrpc: "2.0".into(),
            method: method.into(),
            params,
        };

        let body = serde_json::to_string(&notification)?;
        let header = format!("Content-Length: {}\r\n\r\n", body.len());

        self.stdin.write_all(header.as_bytes()).await?;
        self.stdin.write_all(body.as_bytes()).await?;
        self.stdin.flush().await?;
        Ok(())
    }

    /// Perform the LSP `initialize` + `initialized` handshake.
    ///
    /// A 30-second timeout is applied so a hung server cannot block the caller
    /// indefinitely.
    pub async fn initialize(&mut self, root_dir: &str) -> Result<()> {
        let params = serde_json::to_value(InitializeParams {
            process_id: std::process::id(),
            root_uri: path_to_uri(root_dir),
            capabilities: ClientCapabilities {},
        })?;

        tokio::time::timeout(
            std::time::Duration::from_secs(30),
            self.send_request("initialize", params),
        )
        .await
        .context("LSP initialize timed out after 30 s")?
        .context("LSP initialize request failed")?;

        self.send_notification("initialized", json!({})).await?;
        Ok(())
    }

    /// Request document symbols for the given file URI.
    pub async fn document_symbols(&mut self, file_uri: &str) -> Result<Vec<DocumentSymbol>> {
        let params = serde_json::to_value(DocumentSymbolParams {
            text_document: TextDocumentIdentifier {
                uri: file_uri.into(),
            },
        })?;

        let resp = self
            .send_request("textDocument/documentSymbol", params)
            .await?;

        if let Some(err) = resp.error {
            anyhow::bail!("LSP error {}: {}", err.code, err.message);
        }

        match resp.result {
            Some(value) => {
                let symbols: Vec<DocumentSymbol> = serde_json::from_value(value)?;
                Ok(symbols)
            }
            None => Ok(vec![]),
        }
    }

    /// Send textDocument/didOpen notification.
    pub async fn send_did_open(
        &mut self,
        uri: &str,
        language_id: &str,
        content: &str,
    ) -> Result<()> {
        // Construct a TextDocumentItem (the canonical LSP protocol type) so that
        // the notification payload is type-checked against the protocol schema.
        let doc = crate::lsp::protocol::TextDocumentItem {
            uri: uri.to_string(),
            language_id: language_id.to_string(),
            version: 1,
            text: content.to_string(),
        };
        let params = json!({
            "textDocument": {
                "uri": doc.uri,
                "languageId": doc.language_id,
                "version": doc.version,
                "text": doc.text
            }
        });
        self.send_notification("textDocument/didOpen", params).await
    }

    /// Send textDocument/didChange notification.
    pub async fn send_did_change(&mut self, uri: &str, content: &str) -> Result<()> {
        let params = json!({
            "textDocument": {
                "uri": uri,
                "version": self.next_id // Use incrementing version
            },
            "contentChanges": [{
                "text": content
            }]
        });
        self.next_id += 1;
        self.send_notification("textDocument/didChange", params)
            .await
    }

    /// Send textDocument/didSave notification.
    pub async fn send_did_save(&mut self, uri: &str) -> Result<()> {
        let params = json!({
            "textDocument": {
                "uri": uri
            }
        });
        self.send_notification("textDocument/didSave", params).await
    }

    /// Return a reference to the shared diagnostics cache.
    pub fn diagnostics_cache(&self) -> &DiagnosticsCache {
        &self.diagnostics
    }

    /// Gracefully shut down the language server.
    ///
    /// Applies a 5-second timeout so a hung server doesn't block app exit.
    pub async fn shutdown(mut self) -> Result<()> {
        let fut = async {
            let _resp = self.send_request("shutdown", json!(null)).await?;
            self.send_notification("exit", json!(null)).await?;
            let _ = self.process.wait().await;
            Ok::<(), anyhow::Error>(())
        };
        match crate::util::timeout::with_timeout(
            std::time::Duration::from_secs(5),
            "LSP shutdown",
            fut,
        )
        .await
        {
            Ok(_) => {}
            Err(_) => {
                tracing::warn!("LSP shutdown timed out after 5s — killing process");
                let _ = self.process.kill().await;
            }
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Background stdout reader
// ---------------------------------------------------------------------------

/// Read LSP messages from stdout in a loop, routing responses to pending
/// request channels and caching `publishDiagnostics` notifications.
async fn background_reader(
    mut reader: BufReader<ChildStdout>,
    pending: PendingRequests,
    diagnostics: DiagnosticsCache,
    diag_version: Arc<AtomicU64>,
    server_name: String,
) {
    loop {
        let message = match read_message(&mut reader).await {
            Ok(msg) => msg,
            Err(e) => {
                // EOF or broken pipe — the server process has exited.
                tracing::debug!("LSP background reader for {server_name} ending: {e}");
                break;
            }
        };

        // Parse as generic JSON to determine message type.
        let msg: serde_json::Value = match serde_json::from_str(&message) {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!("Failed to parse LSP message from {server_name}: {e}");
                continue;
            }
        };

        if msg.get("id").is_some() && msg.get("method").is_none() {
            // It's a response (has `id`, no `method`).
            match serde_json::from_value::<LspResponse>(msg) {
                Ok(resp) => {
                    let mut map = match pending.lock() {
                        Ok(g) => g,
                        Err(e) => e.into_inner(),
                    };
                    if let Some(tx) = map.remove(&resp.id) {
                        let _ = tx.send(resp);
                    }
                }
                Err(e) => {
                    tracing::warn!("Failed to parse LSP response from {server_name}: {e}");
                }
            }
        } else if let Some(method) = msg.get("method").and_then(|m| m.as_str()) {
            // It's a notification or server request.
            if method == "textDocument/publishDiagnostics"
                && let Some(params_val) = msg.get("params")
            {
                match serde_json::from_value::<PublishDiagnosticsParams>(params_val.clone()) {
                    Ok(params) => {
                        let mut cache = match diagnostics.lock() {
                            Ok(g) => g,
                            Err(e) => e.into_inner(),
                        };
                        cache.insert(params.uri, params.diagnostics);
                        diag_version.fetch_add(1, Ordering::Relaxed);
                    }
                    Err(e) => {
                        tracing::warn!(
                            "Failed to parse publishDiagnostics from {server_name}: {e}"
                        );
                    }
                }
            }
            // Other notifications are silently ignored.
        }
    }
}

/// Read one LSP message (Content-Length framed) from a buffered reader.
async fn read_message(reader: &mut BufReader<ChildStdout>) -> Result<String> {
    let mut content_length: usize = 0;

    // Read headers until blank line.
    loop {
        let mut line = String::new();
        let bytes_read = reader.read_line(&mut line).await?;
        if bytes_read == 0 {
            anyhow::bail!("EOF while reading LSP headers");
        }
        let trimmed = line.trim();
        if trimmed.is_empty() {
            break;
        }
        if let Some(value) = trimmed.strip_prefix("Content-Length: ") {
            content_length = value.parse()?;
        }
    }

    anyhow::ensure!(content_length > 0, "Missing Content-Length header");

    let mut buf = vec![0u8; content_length];
    reader.read_exact(&mut buf).await?;
    String::from_utf8(buf).context("LSP response is not valid UTF-8")
}