vtcode-acp 0.99.3

ACP bridge and client implementation for VT Code
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
418
419
420
//! JSON-RPC 2.0 types for ACP protocol compliance
//!
//! This module implements the JSON-RPC 2.0 specification as required by the
//! Agent Client Protocol (ACP). All ACP methods use JSON-RPC 2.0 as the
//! transport layer.
//!
//! Reference: <https://agentclientprotocol.com/llms.txt>

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// JSON-RPC 2.0 version string (always "2.0")
pub const JSONRPC_VERSION: &str = "2.0";

/// JSON-RPC 2.0 request object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcRequest {
    /// Protocol version (always "2.0")
    pub jsonrpc: String,

    /// Method name to invoke
    pub method: String,

    /// Method parameters (positional or named)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<Value>,

    /// Request ID for correlation (null for notifications)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<JsonRpcId>,
}

/// JSON-RPC 2.0 response object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcResponse {
    /// Protocol version (always "2.0")
    pub jsonrpc: String,

    /// Result on success (mutually exclusive with error)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,

    /// Error on failure (mutually exclusive with result)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,

    /// Request ID this response corresponds to
    pub id: Option<JsonRpcId>,
}

/// JSON-RPC 2.0 error object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcError {
    /// Error code (integer)
    pub code: i32,

    /// Short error description
    pub message: String,

    /// Additional error data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

/// JSON-RPC 2.0 request/response ID
///
/// Per spec, ID can be a string, number, or null
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum JsonRpcId {
    /// String ID
    String(String),
    /// Numeric ID
    Number(i64),
}

impl JsonRpcId {
    /// Create a new string ID
    pub fn string(s: impl Into<String>) -> Self {
        Self::String(s.into())
    }

    /// Create a new numeric ID
    pub fn number(n: i64) -> Self {
        Self::Number(n)
    }

    /// Generate a new UUID-based string ID
    pub fn new_uuid() -> Self {
        Self::String(uuid::Uuid::new_v4().to_string())
    }
}

impl std::fmt::Display for JsonRpcId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JsonRpcId::String(s) => write!(f, "{}", s),
            JsonRpcId::Number(n) => write!(f, "{}", n),
        }
    }
}

/// Standard JSON-RPC 2.0 error codes
pub mod error_codes {
    /// Parse error: Invalid JSON was received
    pub const PARSE_ERROR: i32 = -32700;

    /// Invalid request: The JSON sent is not a valid Request object
    pub const INVALID_REQUEST: i32 = -32600;

    /// Method not found: The method does not exist / is not available
    pub const METHOD_NOT_FOUND: i32 = -32601;

    /// Invalid params: Invalid method parameter(s)
    pub const INVALID_PARAMS: i32 = -32602;

    /// Internal error: Internal JSON-RPC error
    pub const INTERNAL_ERROR: i32 = -32603;

    /// Server error range: -32000 to -32099 (reserved for implementation-defined server-errors)
    pub const SERVER_ERROR_START: i32 = -32099;
    pub const SERVER_ERROR_END: i32 = -32000;

    // ACP-specific error codes (in server error range)

    /// Authentication required
    pub const AUTH_REQUIRED: i32 = -32001;

    /// Permission denied
    pub const PERMISSION_DENIED: i32 = -32002;

    /// Session not found
    pub const SESSION_NOT_FOUND: i32 = -32003;

    /// Rate limited
    pub const RATE_LIMITED: i32 = -32004;

    /// Resource not found
    pub const RESOURCE_NOT_FOUND: i32 = -32005;
}

impl JsonRpcRequest {
    /// Create a new JSON-RPC 2.0 request
    pub fn new(method: impl Into<String>, params: Option<Value>, id: Option<JsonRpcId>) -> Self {
        Self {
            jsonrpc: JSONRPC_VERSION.to_string(),
            method: method.into(),
            params,
            id,
        }
    }

    /// Create a request with auto-generated UUID ID
    pub fn with_uuid(method: impl Into<String>, params: Option<Value>) -> Self {
        Self::new(method, params, Some(JsonRpcId::new_uuid()))
    }

    /// Create a notification (request without ID, no response expected)
    pub fn notification(method: impl Into<String>, params: Option<Value>) -> Self {
        Self::new(method, params, None)
    }

    /// Check if this is a notification (no ID means no response expected)
    pub fn is_notification(&self) -> bool {
        self.id.is_none()
    }
}

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

    /// Create an error response
    pub fn error(error: JsonRpcError, id: Option<JsonRpcId>) -> Self {
        Self {
            jsonrpc: JSONRPC_VERSION.to_string(),
            result: None,
            error: Some(error),
            id,
        }
    }

    /// Check if response is successful
    pub fn is_success(&self) -> bool {
        self.error.is_none() && self.result.is_some()
    }

    /// Check if response is an error
    pub fn is_error(&self) -> bool {
        self.error.is_some()
    }

    /// Get result, returning error if response was an error
    pub fn into_result(self) -> Result<Value, JsonRpcError> {
        if let Some(error) = self.error {
            Err(error)
        } else {
            Ok(self.result.unwrap_or(Value::Null))
        }
    }
}

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

    /// Create error with additional data
    pub fn with_data(code: i32, message: impl Into<String>, data: Value) -> Self {
        Self {
            code,
            message: message.into(),
            data: Some(data),
        }
    }

    /// Create a parse error
    pub fn parse_error(details: impl Into<String>) -> Self {
        Self::new(error_codes::PARSE_ERROR, details)
    }

    /// Create an invalid request error
    pub fn invalid_request(details: impl Into<String>) -> Self {
        Self::new(error_codes::INVALID_REQUEST, details)
    }

    /// Create a method not found error
    pub fn method_not_found(method: impl Into<String>) -> Self {
        Self::new(
            error_codes::METHOD_NOT_FOUND,
            format!("Method not found: {}", method.into()),
        )
    }

    /// Create an invalid params error
    pub fn invalid_params(details: impl Into<String>) -> Self {
        Self::new(error_codes::INVALID_PARAMS, details)
    }

    /// Create an internal error
    pub fn internal_error(details: impl Into<String>) -> Self {
        Self::new(error_codes::INTERNAL_ERROR, details)
    }

    /// Create an authentication required error with list of available methods
    ///
    /// Per ACP spec, includes authMethods in error data to help clients
    /// present appropriate UI for authentication options.
    pub fn auth_required(auth_methods: Vec<super::AuthMethod>) -> Self {
        let data = serde_json::json!({
            "authMethods": auth_methods,
        });
        Self::with_data(error_codes::AUTH_REQUIRED, "Authentication required", data)
    }

    /// Create a permission denied error
    pub fn permission_denied(details: impl Into<String>) -> Self {
        Self::new(error_codes::PERMISSION_DENIED, details)
    }

    /// Create a session not found error
    pub fn session_not_found(session_id: impl Into<String>) -> Self {
        Self::new(
            error_codes::SESSION_NOT_FOUND,
            format!("Session not found: {}", session_id.into()),
        )
    }

    /// Create a rate limited error
    pub fn rate_limited(details: impl Into<String>) -> Self {
        Self::new(error_codes::RATE_LIMITED, details)
    }

    /// Create a resource not found error
    pub fn resource_not_found(resource: impl Into<String>) -> Self {
        Self::new(
            error_codes::RESOURCE_NOT_FOUND,
            format!("Resource not found: {}", resource.into()),
        )
    }
}

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

    #[test]
    fn test_request_serialization() {
        let req = JsonRpcRequest::new(
            "initialize",
            Some(json!({"protocolVersions": ["2025-01-01"]})),
            Some(JsonRpcId::string("req-1")),
        );

        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("\"jsonrpc\":\"2.0\""));
        assert!(json.contains("\"method\":\"initialize\""));
        assert!(json.contains("\"id\":\"req-1\""));
    }

    #[test]
    fn test_response_success() {
        let resp = JsonRpcResponse::success(
            json!({"session_id": "sess-123"}),
            Some(JsonRpcId::string("req-1")),
        );

        assert!(resp.is_success());
        assert!(!resp.is_error());
    }

    #[test]
    fn test_response_error() {
        let resp = JsonRpcResponse::error(
            JsonRpcError::method_not_found("unknown"),
            Some(JsonRpcId::string("req-1")),
        );

        assert!(resp.is_error());
        assert!(!resp.is_success());
    }

    #[test]
    fn test_notification() {
        let notif = JsonRpcRequest::notification("session/update", Some(json!({"delta": "hello"})));

        assert!(notif.is_notification());
        assert!(notif.id.is_none());
    }

    #[test]
    fn test_id_types() {
        let string_id = JsonRpcId::string("abc");
        let number_id = JsonRpcId::number(123);

        assert_eq!(format!("{}", string_id), "abc");
        assert_eq!(format!("{}", number_id), "123");
    }

    #[test]
    fn test_auth_required_error() {
        use super::super::AuthMethod;

        let auth_methods = vec![
            AuthMethod::Agent {
                id: "agent_auth".to_string(),
                name: "Agent Auth".to_string(),
                description: None,
            },
            AuthMethod::EnvVar {
                id: "openai_key".to_string(),
                name: "OpenAI Key".to_string(),
                description: None,
                var_name: "OPENAI_API_KEY".to_string(),
                link: None,
            },
        ];

        let error = JsonRpcError::auth_required(auth_methods);

        assert_eq!(error.code, error_codes::AUTH_REQUIRED);
        assert_eq!(error.message, "Authentication required");
        assert!(error.data.is_some());

        let data = error.data.unwrap();
        assert!(data["authMethods"].is_array());
        assert_eq!(data["authMethods"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn test_auth_required_error_serialization() {
        use super::super::AuthMethod;

        let auth_methods = vec![AuthMethod::EnvVar {
            id: "test".to_string(),
            name: "Test".to_string(),
            description: None,
            var_name: "TEST_VAR".to_string(),
            link: Some("https://example.com".to_string()),
        }];

        let error = JsonRpcError::auth_required(auth_methods);
        let json = serde_json::to_value(&error).unwrap();

        assert_eq!(json["code"], -32001);
        assert_eq!(json["message"], "Authentication required");
        assert_eq!(json["data"]["authMethods"][0]["type"], "env_var");
        assert_eq!(json["data"]["authMethods"][0]["id"], "test");
    }

    #[test]
    fn test_acp_error_helpers() {
        let err_perm = JsonRpcError::permission_denied("Not allowed");
        assert_eq!(err_perm.code, error_codes::PERMISSION_DENIED);

        let err_session = JsonRpcError::session_not_found("sess-123");
        assert_eq!(err_session.code, error_codes::SESSION_NOT_FOUND);
        assert!(err_session.message.contains("sess-123"));

        let err_rate = JsonRpcError::rate_limited("Too many requests");
        assert_eq!(err_rate.code, error_codes::RATE_LIMITED);

        let err_resource = JsonRpcError::resource_not_found("file.txt");
        assert_eq!(err_resource.code, error_codes::RESOURCE_NOT_FOUND);
        assert!(err_resource.message.contains("file.txt"));
    }
}