vtcode_acp_client/
client_v2.rs

1//! ACP Client V2 with full protocol compliance
2//!
3//! This module implements the ACP client with:
4//! - JSON-RPC 2.0 transport
5//! - Full session lifecycle (initialize, session/new, session/prompt)
6//! - SSE streaming for session updates
7//! - Capability negotiation
8//!
9//! Reference: https://agentclientprotocol.com/llms.txt
10
11use crate::capabilities::{
12    AgentCapabilities, AuthenticateParams, AuthenticateResult, ClientCapabilities, ClientInfo,
13    InitializeParams, InitializeResult, SUPPORTED_VERSIONS,
14};
15use crate::error::{AcpError, AcpResult};
16use crate::jsonrpc::{JsonRpcId, JsonRpcRequest, JsonRpcResponse, JSONRPC_VERSION};
17use crate::session::{
18    AcpSession, SessionCancelParams, SessionLoadParams, SessionLoadResult, SessionNewParams,
19    SessionNewResult, SessionPromptParams, SessionPromptResult, SessionState,
20    SessionUpdateNotification,
21};
22
23use reqwest::{Client as HttpClient, StatusCode};
24use serde::de::DeserializeOwned;
25use serde::Serialize;
26use serde_json::Value;
27use std::collections::HashMap;
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::time::Duration;
30use tokio::sync::{mpsc, RwLock};
31use tracing::{debug, trace, warn};
32
33/// ACP Client V2 with full protocol compliance
34///
35/// This client implements the complete ACP session lifecycle:
36/// 1. `initialize()` - Negotiate protocol version and capabilities
37/// 2. `authenticate()` - Optional authentication (if required by agent)
38/// 3. `session_new()` - Create a new conversation session
39/// 4. `session_prompt()` - Send prompts and receive responses
40/// 5. `session_cancel()` - Cancel ongoing operations
41///
42/// Streaming updates are delivered via SSE and can be subscribed to
43/// using `subscribe_updates()`.
44pub struct AcpClientV2 {
45    /// HTTP client for JSON-RPC requests
46    http_client: HttpClient,
47
48    /// Base URL of the ACP agent
49    base_url: String,
50
51    /// Local client identifier
52    #[allow(dead_code)]
53    client_id: String,
54
55    /// Client capabilities
56    capabilities: ClientCapabilities,
57
58    /// Request timeout
59    #[allow(dead_code)]
60    timeout: Duration,
61
62    /// Request ID counter for correlation
63    request_counter: AtomicU64,
64
65    /// Negotiated protocol version (set after initialize)
66    protocol_version: RwLock<Option<String>>,
67
68    /// Agent capabilities (set after initialize)
69    agent_capabilities: RwLock<Option<AgentCapabilities>>,
70
71    /// Active sessions
72    sessions: RwLock<HashMap<String, AcpSession>>,
73
74    /// Authentication token (if authenticated)
75    auth_token: RwLock<Option<String>>,
76}
77
78/// Builder for AcpClientV2
79pub struct AcpClientV2Builder {
80    base_url: String,
81    client_id: String,
82    capabilities: ClientCapabilities,
83    timeout: Duration,
84}
85
86impl AcpClientV2Builder {
87    /// Create a new builder
88    pub fn new(base_url: impl Into<String>) -> Self {
89        Self {
90            base_url: base_url.into(),
91            client_id: format!("vtcode-{}", uuid::Uuid::new_v4()),
92            capabilities: ClientCapabilities::default(),
93            timeout: Duration::from_secs(30),
94        }
95    }
96
97    /// Set client identifier
98    pub fn with_client_id(mut self, id: impl Into<String>) -> Self {
99        self.client_id = id.into();
100        self
101    }
102
103    /// Set client capabilities
104    pub fn with_capabilities(mut self, caps: ClientCapabilities) -> Self {
105        self.capabilities = caps;
106        self
107    }
108
109    /// Set request timeout
110    pub fn with_timeout(mut self, timeout: Duration) -> Self {
111        self.timeout = timeout;
112        self
113    }
114
115    /// Build the client
116    pub fn build(self) -> AcpResult<AcpClientV2> {
117        let http_client = HttpClient::builder()
118            .timeout(self.timeout)
119            .build()
120            .map_err(|e| AcpError::ConfigError(format!("Failed to create HTTP client: {}", e)))?;
121
122        Ok(AcpClientV2 {
123            http_client,
124            base_url: self.base_url,
125            client_id: self.client_id,
126            capabilities: self.capabilities,
127            timeout: self.timeout,
128            request_counter: AtomicU64::new(1),
129            protocol_version: RwLock::new(None),
130            agent_capabilities: RwLock::new(None),
131            sessions: RwLock::new(HashMap::new()),
132            auth_token: RwLock::new(None),
133        })
134    }
135}
136
137impl AcpClientV2 {
138    /// Create a new client with default settings
139    pub fn new(base_url: impl Into<String>) -> AcpResult<Self> {
140        AcpClientV2Builder::new(base_url).build()
141    }
142
143    /// Get the next request ID
144    fn next_request_id(&self) -> JsonRpcId {
145        let id = self.request_counter.fetch_add(1, Ordering::SeqCst);
146        JsonRpcId::Number(id as i64)
147    }
148
149    /// Check if client has been initialized
150    pub async fn is_initialized(&self) -> bool {
151        self.protocol_version.read().await.is_some()
152    }
153
154    /// Get negotiated protocol version
155    pub async fn protocol_version(&self) -> Option<String> {
156        self.protocol_version.read().await.clone()
157    }
158
159    /// Get agent capabilities (after initialization)
160    pub async fn agent_capabilities(&self) -> Option<AgentCapabilities> {
161        self.agent_capabilities.read().await.clone()
162    }
163
164    // ========================================================================
165    // JSON-RPC Transport Layer
166    // ========================================================================
167
168    /// Send a JSON-RPC request and parse the response
169    async fn call<P: Serialize, R: DeserializeOwned>(
170        &self,
171        method: &str,
172        params: Option<P>,
173    ) -> AcpResult<R> {
174        let id = self.next_request_id();
175        let params_value = params
176            .map(|p| serde_json::to_value(p))
177            .transpose()
178            .map_err(|e| AcpError::SerializationError(e.to_string()))?;
179
180        let request = JsonRpcRequest {
181            jsonrpc: JSONRPC_VERSION.to_string(),
182            method: method.to_string(),
183            params: params_value,
184            id: Some(id.clone()),
185        };
186
187        debug!(method = method, id = %id, "Sending JSON-RPC request");
188
189        let url = format!("{}/rpc", self.base_url.trim_end_matches('/'));
190
191        let mut req_builder = self.http_client.post(&url).json(&request);
192
193        // Add auth token if present
194        if let Some(token) = self.auth_token.read().await.as_ref() {
195            req_builder = req_builder.bearer_auth(token);
196        }
197
198        let response = req_builder
199            .send()
200            .await
201            .map_err(|e| AcpError::NetworkError(format!("Request failed: {}", e)))?;
202
203        let status = response.status();
204
205        match status {
206            StatusCode::OK => {
207                let body = response
208                    .text()
209                    .await
210                    .map_err(|e| AcpError::NetworkError(e.to_string()))?;
211
212                trace!(body_len = body.len(), "Received JSON-RPC response");
213
214                let rpc_response: JsonRpcResponse = serde_json::from_str(&body)
215                    .map_err(|e| AcpError::SerializationError(format!("Invalid response: {}", e)))?;
216
217                if let Some(error) = rpc_response.error {
218                    return Err(AcpError::RemoteError {
219                        agent_id: self.base_url.clone(),
220                        message: error.message,
221                        code: Some(error.code),
222                    });
223                }
224
225                let result = rpc_response.result.unwrap_or(Value::Null);
226                serde_json::from_value(result)
227                    .map_err(|e| AcpError::SerializationError(format!("Result parse error: {}", e)))
228            }
229
230            StatusCode::UNAUTHORIZED => Err(AcpError::RemoteError {
231                agent_id: self.base_url.clone(),
232                message: "Authentication required".to_string(),
233                code: Some(401),
234            }),
235
236            StatusCode::REQUEST_TIMEOUT => {
237                Err(AcpError::Timeout("Request timed out".to_string()))
238            }
239
240            _ => {
241                let body = response.text().await.unwrap_or_default();
242                Err(AcpError::RemoteError {
243                    agent_id: self.base_url.clone(),
244                    message: format!("HTTP {}: {}", status.as_u16(), body),
245                    code: Some(status.as_u16() as i32),
246                })
247            }
248        }
249    }
250
251    /// Send a notification (no response expected)
252    async fn notify<P: Serialize>(&self, method: &str, params: Option<P>) -> AcpResult<()> {
253        let params_value = params
254            .map(|p| serde_json::to_value(p))
255            .transpose()
256            .map_err(|e| AcpError::SerializationError(e.to_string()))?;
257
258        let request = JsonRpcRequest::notification(method, params_value);
259
260        debug!(method = method, "Sending JSON-RPC notification");
261
262        let url = format!("{}/rpc", self.base_url.trim_end_matches('/'));
263
264        let mut req_builder = self.http_client.post(&url).json(&request);
265
266        if let Some(token) = self.auth_token.read().await.as_ref() {
267            req_builder = req_builder.bearer_auth(token);
268        }
269
270        // Fire and forget
271        let _ = req_builder.send().await;
272
273        Ok(())
274    }
275
276    // ========================================================================
277    // ACP Protocol Methods
278    // ========================================================================
279
280    /// Initialize the connection with the agent
281    ///
282    /// This must be called before any other method. It negotiates:
283    /// - Protocol version
284    /// - Client and agent capabilities
285    /// - Authentication requirements
286    pub async fn initialize(&self) -> AcpResult<InitializeResult> {
287        let params = InitializeParams {
288            protocol_versions: SUPPORTED_VERSIONS.iter().map(|s| s.to_string()).collect(),
289            capabilities: self.capabilities.clone(),
290            client_info: ClientInfo::default(),
291        };
292
293        let result: InitializeResult = self.call("initialize", Some(params)).await?;
294
295        // Validate negotiated protocol version is one we support
296        if !SUPPORTED_VERSIONS.contains(&result.protocol_version.as_str()) {
297            return Err(AcpError::InvalidRequest(format!(
298                "Agent negotiated unsupported protocol version: {}",
299                result.protocol_version
300            )));
301        }
302
303        // Store negotiated state
304        *self.protocol_version.write().await = Some(result.protocol_version.clone());
305        *self.agent_capabilities.write().await = Some(result.capabilities.clone());
306
307        debug!(
308            protocol = %result.protocol_version,
309            agent = %result.agent_info.name,
310            "ACP connection initialized"
311        );
312
313        Ok(result)
314    }
315
316    /// Authenticate with the agent (if required)
317    pub async fn authenticate(&self, params: AuthenticateParams) -> AcpResult<AuthenticateResult> {
318        let result: AuthenticateResult = self.call("authenticate", Some(params)).await?;
319
320        if result.authenticated {
321            if let Some(token) = &result.session_token {
322                *self.auth_token.write().await = Some(token.clone());
323            }
324            debug!("Authentication successful");
325        } else {
326            warn!("Authentication failed");
327        }
328
329        Ok(result)
330    }
331
332    /// Create a new session
333    pub async fn session_new(&self, params: SessionNewParams) -> AcpResult<SessionNewResult> {
334        if !self.is_initialized().await {
335            return Err(AcpError::InvalidRequest(
336                "Client not initialized. Call initialize() first.".to_string(),
337            ));
338        }
339
340        let result: SessionNewResult = self.call("session/new", Some(params)).await?;
341
342        // Track session locally
343        let session = AcpSession::new(&result.session_id);
344        self.sessions
345            .write()
346            .await
347            .insert(result.session_id.clone(), session);
348
349        debug!(session_id = %result.session_id, "Session created");
350
351        Ok(result)
352    }
353
354    /// Load an existing session
355    pub async fn session_load(&self, session_id: &str) -> AcpResult<SessionLoadResult> {
356        if !self.is_initialized().await {
357            return Err(AcpError::InvalidRequest(
358                "Client not initialized. Call initialize() first.".to_string(),
359            ));
360        }
361
362        let params = SessionLoadParams {
363            session_id: session_id.to_string(),
364        };
365
366        let result: SessionLoadResult = self.call("session/load", Some(params)).await?;
367
368        // Track session locally
369        self.sessions
370            .write()
371            .await
372            .insert(session_id.to_string(), result.session.clone());
373
374        debug!(session_id = session_id, turns = result.history.len(), "Session loaded");
375
376        Ok(result)
377    }
378
379    /// Send a prompt to the session
380    ///
381    /// Returns the turn result. For streaming responses, use `subscribe_updates()`
382    /// before calling this method.
383    pub async fn session_prompt(
384        &self,
385        params: SessionPromptParams,
386    ) -> AcpResult<SessionPromptResult> {
387        self.session_prompt_with_timeout(params, None).await
388    }
389
390    /// Send a prompt with a custom timeout
391    pub async fn session_prompt_with_timeout(
392        &self,
393        params: SessionPromptParams,
394        timeout: Option<Duration>,
395    ) -> AcpResult<SessionPromptResult> {
396        if !self.is_initialized().await {
397            return Err(AcpError::InvalidRequest(
398                "Client not initialized. Call initialize() first.".to_string(),
399            ));
400        }
401
402        let session_id = params.session_id.clone();
403
404        // Update session state
405        if let Some(session) = self.sessions.write().await.get_mut(&session_id) {
406            session.set_state(SessionState::Active);
407            session.increment_turn();
408        }
409
410        // Use custom timeout if provided
411        let result: SessionPromptResult = if let Some(custom_timeout) = timeout {
412            tokio::time::timeout(
413                custom_timeout,
414                self.call::<_, SessionPromptResult>("session/prompt", Some(params))
415            )
416            .await
417            .map_err(|_| AcpError::Timeout("Prompt request timed out".to_string()))?
418            ?
419        } else {
420            self.call("session/prompt", Some(params)).await?
421        };
422
423        // Update session state based on result
424        if let Some(session) = self.sessions.write().await.get_mut(&session_id) {
425            match result.status {
426                crate::session::TurnStatus::Completed => {
427                    session.set_state(SessionState::AwaitingInput);
428                }
429                crate::session::TurnStatus::Cancelled => {
430                    session.set_state(SessionState::Cancelled);
431                }
432                crate::session::TurnStatus::Failed => {
433                    session.set_state(SessionState::Failed);
434                }
435                crate::session::TurnStatus::AwaitingInput => {
436                    session.set_state(SessionState::AwaitingInput);
437                }
438            }
439        }
440
441        debug!(
442            session_id = %session_id,
443            turn_id = %result.turn_id,
444            status = ?result.status,
445            "Prompt completed"
446        );
447
448        Ok(result)
449    }
450
451    /// Cancel an ongoing operation
452    pub async fn session_cancel(&self, session_id: &str, turn_id: Option<&str>) -> AcpResult<()> {
453        let params = SessionCancelParams {
454            session_id: session_id.to_string(),
455            turn_id: turn_id.map(String::from),
456        };
457
458        self.notify("session/cancel", Some(params)).await?;
459
460        // Update local session state
461        if let Some(session) = self.sessions.write().await.get_mut(session_id) {
462            session.set_state(SessionState::Cancelled);
463        }
464
465        debug!(session_id = session_id, "Session cancelled");
466
467        Ok(())
468    }
469
470    /// Get a session by ID
471    pub async fn get_session(&self, session_id: &str) -> Option<AcpSession> {
472        self.sessions.read().await.get(session_id).cloned()
473    }
474
475    /// List all active sessions
476    pub async fn list_sessions(&self) -> Vec<AcpSession> {
477        self.sessions.read().await.values().cloned().collect()
478    }
479
480    // ========================================================================
481    // SSE Streaming
482    // ========================================================================
483
484    /// Subscribe to session updates via Server-Sent Events
485    ///
486    /// Returns a receiver channel that will receive update notifications.
487    /// The connection will remain open until the receiver is dropped.
488    pub async fn subscribe_updates(
489        &self,
490        session_id: &str,
491    ) -> AcpResult<mpsc::Receiver<SessionUpdateNotification>> {
492        let (tx, rx) = mpsc::channel(100);
493
494        let url = format!(
495            "{}/sse/session/{}",
496            self.base_url.trim_end_matches('/'),
497            session_id
498        );
499
500        let _http_client = self.http_client.clone();
501        let auth_token = self.auth_token.read().await.clone();
502
503        // Spawn SSE listener task
504        tokio::spawn(async move {
505            if let Err(e) = Self::sse_listener(url, auth_token, tx).await {
506                warn!("SSE listener error: {}", e);
507            }
508        });
509
510        Ok(rx)
511    }
512
513    /// Internal SSE listener implementation
514    async fn sse_listener(
515        url: String,
516        auth_token: Option<String>,
517        tx: mpsc::Sender<SessionUpdateNotification>,
518    ) -> AcpResult<()> {
519        let client = HttpClient::new();
520
521        let mut req = client.get(&url);
522        if let Some(token) = auth_token {
523            req = req.bearer_auth(token);
524        }
525
526        let response = req
527            .header("Accept", "text/event-stream")
528            .send()
529            .await
530            .map_err(|e| AcpError::NetworkError(e.to_string()))?;
531
532        if !response.status().is_success() {
533            return Err(AcpError::NetworkError(format!(
534                "SSE connection failed: {}",
535                response.status()
536            )));
537        }
538
539        let mut stream = response.bytes_stream();
540        use futures_util::StreamExt;
541
542        let mut buffer = String::new();
543
544        while let Some(chunk) = stream.next().await {
545            let chunk = chunk.map_err(|e| AcpError::NetworkError(e.to_string()))?;
546            buffer.push_str(&String::from_utf8_lossy(&chunk));
547
548            // Process complete events
549            while let Some(event_end) = buffer.find("\n\n") {
550                let event = buffer[..event_end].to_string();
551                buffer = buffer[event_end + 2..].to_string();
552
553                // Parse SSE event fields
554                let mut event_type = None;
555                let mut data_lines = Vec::new();
556
557                for line in event.lines() {
558                    if let Some(data) = line.strip_prefix("data:") {
559                        data_lines.push(data.trim());
560                    } else if let Some(evt) = line.strip_prefix("event:") {
561                        event_type = Some(evt.trim());
562                    }
563                    // Ignore: id:, retry:, and comment lines
564                }
565
566                // Process session/update events
567                if event_type.is_none() || event_type == Some("session/update") {
568                    if !data_lines.is_empty() {
569                        let data = data_lines.join("\n");
570                        if let Ok(notification) = serde_json::from_str::<SessionUpdateNotification>(&data)
571                        {
572                            if tx.send(notification).await.is_err() {
573                                // Receiver dropped, exit
574                                return Ok(());
575                            }
576                        }
577                    }
578                }
579            }
580        }
581
582        Ok(())
583    }
584}
585
586#[cfg(test)]
587mod tests {
588    use super::*;
589
590    #[test]
591    fn test_client_builder() {
592        let client = AcpClientV2Builder::new("http://localhost:8080")
593            .with_client_id("test-client")
594            .with_timeout(Duration::from_secs(60))
595            .build()
596            .unwrap();
597
598        assert_eq!(client.base_url, "http://localhost:8080");
599        assert_eq!(client.client_id, "test-client");
600        assert_eq!(client.timeout, Duration::from_secs(60));
601    }
602
603    #[tokio::test]
604    async fn test_client_not_initialized() {
605        let client = AcpClientV2::new("http://localhost:8080").unwrap();
606        assert!(!client.is_initialized().await);
607    }
608
609    #[test]
610    fn test_request_id_generation() {
611        let client = AcpClientV2::new("http://localhost:8080").unwrap();
612
613        let id1 = client.next_request_id();
614        let id2 = client.next_request_id();
615
616        assert_ne!(id1, id2);
617    }
618}