vtcode-core 0.104.2

Core library for VT Code - a Rust-based terminal coding agent
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
//! RPC endpoint for file search operations
//!
//! Provides JSON-RPC interface to file_search_bridge for remote clients (VS Code extension).
//! Handles request/response serialization and validation.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::path::PathBuf;

use super::file_search_bridge::{self, FileMatchType, FileSearchConfig};

/// JSON-RPC request for searching files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchFilesRequest {
    /// Fuzzy search pattern (e.g., "main", "test.rs")
    pub pattern: String,
    /// Root directory to search
    pub workspace_root: PathBuf,
    /// Maximum number of results to return
    pub max_results: usize,
    /// Patterns to exclude from results (glob-style)
    pub exclude_patterns: Vec<String>,
    /// Whether to respect .gitignore files
    pub respect_gitignore: bool,
}

/// JSON-RPC request for listing files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListFilesRequest {
    /// Root directory to list files from
    pub workspace_root: PathBuf,
    /// Patterns to exclude from results
    pub exclude_patterns: Vec<String>,
    /// Whether to respect .gitignore files
    pub respect_gitignore: bool,
    /// Maximum number of files to return
    pub max_results: usize,
}

/// File match in RPC response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileMatchRpc {
    /// Path relative to workspace root
    pub path: String,
    /// Whether the match is a file or directory
    pub match_type: FileMatchType,
    /// Fuzzy match score (higher = better match)
    pub score: u32,
    /// Character indices for match highlighting (optional)
    pub indices: Option<Vec<u32>>,
}

/// JSON-RPC response for search_files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchFilesResponse {
    /// Matched files
    pub matches: Vec<FileMatchRpc>,
    /// Total number of matches found
    pub total_match_count: usize,
    /// Whether result was truncated
    pub truncated: bool,
}

/// JSON-RPC response for list_files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListFilesResponse {
    /// All discovered files
    pub files: Vec<String>,
    /// Total files found
    pub total: usize,
}

/// Error response for RPC calls
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RpcError {
    /// Error code
    pub code: i32,
    /// Error message
    pub message: String,
    /// Additional error data
    pub data: Option<Value>,
}

impl RpcError {
    /// Create a new RPC error
    pub fn new(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: None,
        }
    }

    /// Invalid request error (-32600)
    pub fn invalid_request(message: impl Into<String>) -> Self {
        Self::new(-32600, message)
    }

    /// Method not found error (-32601)
    pub fn method_not_found() -> Self {
        Self::new(-32601, "Method not found")
    }

    /// Invalid params error (-32602)
    pub fn invalid_params(message: impl Into<String>) -> Self {
        Self::new(-32602, message)
    }

    /// Internal error (-32603)
    pub fn internal_error(message: impl Into<String>) -> Self {
        Self::new(-32603, message)
    }

    /// Custom error code
    pub fn custom(code: i32, message: impl Into<String>) -> Self {
        Self::new(code, message)
    }
}

/// RPC request envelope
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RpcRequest {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// RPC method name
    pub method: String,
    /// RPC method parameters (varies by method)
    pub params: Value,
    /// Request ID (for responses)
    pub id: Option<Value>,
}

/// RPC response envelope
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RpcResponse {
    /// JSON-RPC version
    pub jsonrpc: String,
    /// Response ID (matches request ID)
    pub id: Option<Value>,
    /// Success result (if successful)
    pub result: Option<Value>,
    /// Error response (if failed)
    pub error: Option<RpcError>,
}

impl RpcResponse {
    /// Create a successful response
    pub fn success(id: Option<Value>, result: Value) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id,
            result: Some(result),
            error: None,
        }
    }

    /// Create an error response
    pub fn error(id: Option<Value>, error: RpcError) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id,
            result: None,
            error: Some(error),
        }
    }
}

/// Handler for file search RPC requests
pub struct FileSearchRpcHandler;

impl FileSearchRpcHandler {
    /// Handle an incoming RPC request
    ///
    /// # Arguments
    ///
    /// * `request` - Parsed JSON-RPC request
    ///
    /// # Returns
    ///
    /// JSON-RPC response with result or error
    pub async fn handle_request(request: RpcRequest) -> RpcResponse {
        let id = request.id.clone();

        // Validate JSON-RPC version
        if request.jsonrpc != "2.0" {
            return RpcResponse::error(id, RpcError::invalid_request("Invalid JSON-RPC version"));
        }

        // Dispatch to appropriate handler
        let result = match request.method.as_str() {
            "search_files" => Self::handle_search_files(&request.params, id.clone()).await,
            "list_files" => Self::handle_list_files(&request.params).await,
            "find_references" => Self::handle_find_references(&request.params).await,
            _ => return RpcResponse::error(id, RpcError::method_not_found()),
        };

        match result {
            Ok(response) => RpcResponse::success(id, response),
            Err(error) => RpcResponse::error(id, RpcError::internal_error(error.to_string())),
        }
    }

    /// Handle search_files RPC method
    ///
    /// Performs fuzzy file search with the given pattern.
    async fn handle_search_files(params: &Value, _id: Option<Value>) -> Result<Value> {
        let request: SearchFilesRequest = serde_json::from_value(params.clone())
            .context("Failed to parse search_files parameters")?;

        // Validate workspace root
        if !request.workspace_root.exists() {
            return Err(anyhow::anyhow!(
                "Workspace root does not exist: {}",
                request.workspace_root.display()
            ));
        }

        // Build configuration
        let config = FileSearchConfig::new(request.pattern, request.workspace_root)
            .with_limit(request.max_results)
            .respect_gitignore(request.respect_gitignore);

        // Perform search
        let results = file_search_bridge::search_files(config, None)?;

        // Convert to RPC response format
        let matches: Vec<FileMatchRpc> = results
            .matches
            .into_iter()
            .map(|m| FileMatchRpc {
                path: m.path,
                match_type: m.match_type,
                score: m.score,
                indices: m.indices,
            })
            .collect();

        Ok(json!({
            "matches": matches,
            "total_match_count": results.total_match_count,
            "truncated": matches.len() >= request.max_results,
        }))
    }

    /// Handle list_files RPC method
    ///
    /// Lists all files in the workspace with optional exclusions.
    async fn handle_list_files(params: &Value) -> Result<Value> {
        let request: ListFilesRequest = serde_json::from_value(params.clone())
            .context("Failed to parse list_files parameters")?;

        // Validate workspace root
        if !request.workspace_root.exists() {
            return Err(anyhow::anyhow!(
                "Workspace root does not exist: {}",
                request.workspace_root.display()
            ));
        }

        // Build configuration (empty pattern lists all files)
        let mut config = FileSearchConfig::new(String::new(), request.workspace_root)
            .with_limit(request.max_results)
            .respect_gitignore(request.respect_gitignore);

        for pattern in request.exclude_patterns {
            config = config.exclude(pattern);
        }

        // Perform search
        let results = file_search_bridge::search_files(config, None)?;

        // Extract file paths
        let files: Vec<String> = file_search_bridge::file_matches_only(results.matches)
            .into_iter()
            .map(|m| m.path)
            .collect();
        let total = files.len();

        Ok(json!({
            "files": files,
            "total": total,
        }))
    }

    /// Handle find_references RPC method (stub for future implementation)
    ///
    /// Finds all files containing a symbol reference.
    async fn handle_find_references(params: &Value) -> Result<Value> {
        // This would require more sophisticated symbol analysis
        // For now, return a placeholder that could be implemented later
        let _symbol: String = serde_json::from_value(params.clone())
            .context("Failed to parse find_references parameters")?;

        Ok(json!({
            "matches": [],
            "message": "find_references not yet implemented",
        }))
    }
}

/// Parse JSON-RPC request from raw JSON string
///
/// # Arguments
///
/// * `json_string` - Raw JSON request string
///
/// # Returns
///
/// Parsed RPC request or error response
pub fn parse_rpc_request(json_string: &str) -> Result<RpcRequest, Box<RpcResponse>> {
    match serde_json::from_str::<RpcRequest>(json_string) {
        Ok(request) => Ok(request),
        Err(err) => {
            let error_response =
                RpcResponse::error(None, RpcError::invalid_request(err.to_string()));
            Err(Box::new(error_response))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rpc_error_codes() {
        assert_eq!(RpcError::invalid_request("test").code, -32600);
        assert_eq!(RpcError::method_not_found().code, -32601);
        assert_eq!(RpcError::invalid_params("test").code, -32602);
        assert_eq!(RpcError::internal_error("test").code, -32603);
    }

    #[test]
    fn test_rpc_response_success() {
        let response = RpcResponse::success(Some(json!(1)), json!({"ok": true}));
        assert_eq!(response.jsonrpc, "2.0");
        assert_eq!(response.id, Some(json!(1)));
        assert!(response.result.is_some());
        assert!(response.error.is_none());
    }

    #[test]
    fn test_rpc_response_error() {
        let error = RpcError::internal_error("test error");
        let response = RpcResponse::error(Some(json!(1)), error);
        assert_eq!(response.jsonrpc, "2.0");
        assert_eq!(response.id, Some(json!(1)));
        assert!(response.result.is_none());
        assert!(response.error.is_some());
    }

    #[test]
    fn test_search_files_request_parsing() {
        let json = r#"{
            "pattern": "main",
            "workspace_root": "/workspace",
            "max_results": 100,
            "exclude_patterns": [],
            "respect_gitignore": true
        }"#;

        let value: Value = serde_json::from_str(json).unwrap();
        let request: SearchFilesRequest = serde_json::from_value(value).unwrap();

        assert_eq!(request.pattern, "main");
        assert_eq!(request.max_results, 100);
        assert!(request.respect_gitignore);
    }

    #[test]
    fn test_list_files_request_parsing() {
        let json = r#"{
            "workspace_root": "/workspace",
            "exclude_patterns": ["**/node_modules/**"],
            "respect_gitignore": true,
            "max_results": 1000
        }"#;

        let value: Value = serde_json::from_str(json).unwrap();
        let request: ListFilesRequest = serde_json::from_value(value).unwrap();

        assert_eq!(request.exclude_patterns.len(), 1);
        assert_eq!(request.max_results, 1000);
    }

    #[test]
    fn test_parse_invalid_rpc_request() {
        let invalid_json = "not valid json";
        let result = parse_rpc_request(invalid_json);
        assert!(result.is_err());
    }

    #[test]
    fn test_file_match_rpc_serialization() {
        let file_match = FileMatchRpc {
            path: "src/main.rs".to_string(),
            match_type: FileMatchType::File,
            score: 100,
            indices: Some(vec![4, 5]),
        };

        let json = serde_json::to_string(&file_match).unwrap();
        let deserialized: FileMatchRpc = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.path, "src/main.rs");
        assert_eq!(deserialized.score, 100u32);
        assert_eq!(deserialized.indices, Some(vec![4u32, 5u32]));
    }
}