1use crate::capabilities::{
12 AgentCapabilities, AuthenticateParams, AuthenticateResult, ClientCapabilities, ClientInfo,
13 InitializeParams, InitializeResult, SUPPORTED_VERSIONS,
14};
15use crate::error::{AcpError, AcpResult};
16use crate::jsonrpc::{JSONRPC_VERSION, JsonRpcId, JsonRpcRequest, JsonRpcResponse};
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::Serialize;
25use serde::de::DeserializeOwned;
26use serde_json::Value;
27use std::collections::HashMap;
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::time::Duration;
30use tokio::sync::{RwLock, mpsc};
31use tracing::{debug, trace, warn};
32
33pub struct AcpClientV2 {
45 http_client: HttpClient,
47
48 base_url: String,
50
51 #[allow(dead_code)]
53 client_id: String,
54
55 capabilities: ClientCapabilities,
57
58 #[allow(dead_code)]
60 timeout: Duration,
61
62 request_counter: AtomicU64,
64
65 protocol_version: RwLock<Option<String>>,
67
68 agent_capabilities: RwLock<Option<AgentCapabilities>>,
70
71 sessions: RwLock<HashMap<String, AcpSession>>,
73
74 auth_token: RwLock<Option<String>>,
76}
77
78pub struct AcpClientV2Builder {
80 base_url: String,
81 client_id: String,
82 capabilities: ClientCapabilities,
83 timeout: Duration,
84}
85
86impl AcpClientV2Builder {
87 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 pub fn with_client_id(mut self, id: impl Into<String>) -> Self {
99 self.client_id = id.into();
100 self
101 }
102
103 pub fn with_capabilities(mut self, caps: ClientCapabilities) -> Self {
105 self.capabilities = caps;
106 self
107 }
108
109 pub fn with_timeout(mut self, timeout: Duration) -> Self {
111 self.timeout = timeout;
112 self
113 }
114
115 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 pub fn new(base_url: impl Into<String>) -> AcpResult<Self> {
140 AcpClientV2Builder::new(base_url).build()
141 }
142
143 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 pub async fn is_initialized(&self) -> bool {
151 self.protocol_version.read().await.is_some()
152 }
153
154 pub async fn protocol_version(&self) -> Option<String> {
156 self.protocol_version.read().await.clone()
157 }
158
159 pub async fn agent_capabilities(&self) -> Option<AgentCapabilities> {
161 self.agent_capabilities.read().await.clone()
162 }
163
164 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 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).map_err(|e| {
215 AcpError::SerializationError(format!("Invalid response: {}", e))
216 })?;
217
218 if let Some(error) = rpc_response.error {
219 return Err(AcpError::RemoteError {
220 agent_id: self.base_url.clone(),
221 message: error.message,
222 code: Some(error.code),
223 });
224 }
225
226 let result = rpc_response.result.unwrap_or(Value::Null);
227 serde_json::from_value(result)
228 .map_err(|e| AcpError::SerializationError(format!("Result parse error: {}", e)))
229 }
230
231 StatusCode::UNAUTHORIZED => Err(AcpError::RemoteError {
232 agent_id: self.base_url.clone(),
233 message: "Authentication required".to_string(),
234 code: Some(401),
235 }),
236
237 StatusCode::REQUEST_TIMEOUT => Err(AcpError::Timeout("Request timed out".to_string())),
238
239 _ => {
240 let body = response.text().await.unwrap_or_default();
241 Err(AcpError::RemoteError {
242 agent_id: self.base_url.clone(),
243 message: format!("HTTP {}: {}", status.as_u16(), body),
244 code: Some(status.as_u16() as i32),
245 })
246 }
247 }
248 }
249
250 async fn notify<P: Serialize>(&self, method: &str, params: Option<P>) -> AcpResult<()> {
252 let params_value = params
253 .map(|p| serde_json::to_value(p))
254 .transpose()
255 .map_err(|e| AcpError::SerializationError(e.to_string()))?;
256
257 let request = JsonRpcRequest::notification(method, params_value);
258
259 debug!(method = method, "Sending JSON-RPC notification");
260
261 let url = format!("{}/rpc", self.base_url.trim_end_matches('/'));
262
263 let mut req_builder = self.http_client.post(&url).json(&request);
264
265 if let Some(token) = self.auth_token.read().await.as_ref() {
266 req_builder = req_builder.bearer_auth(token);
267 }
268
269 let _ = req_builder.send().await;
271
272 Ok(())
273 }
274
275 pub async fn initialize(&self) -> AcpResult<InitializeResult> {
286 let params = InitializeParams {
287 protocol_versions: SUPPORTED_VERSIONS.iter().map(|s| s.to_string()).collect(),
288 capabilities: self.capabilities.clone(),
289 client_info: ClientInfo::default(),
290 };
291
292 let result: InitializeResult = self.call("initialize", Some(params)).await?;
293
294 if !SUPPORTED_VERSIONS.contains(&result.protocol_version.as_str()) {
296 return Err(AcpError::InvalidRequest(format!(
297 "Agent negotiated unsupported protocol version: {}",
298 result.protocol_version
299 )));
300 }
301
302 *self.protocol_version.write().await = Some(result.protocol_version.clone());
304 *self.agent_capabilities.write().await = Some(result.capabilities.clone());
305
306 debug!(
307 protocol = %result.protocol_version,
308 agent = %result.agent_info.name,
309 "ACP connection initialized"
310 );
311
312 Ok(result)
313 }
314
315 pub async fn authenticate(&self, params: AuthenticateParams) -> AcpResult<AuthenticateResult> {
317 let result: AuthenticateResult = self.call("authenticate", Some(params)).await?;
318
319 if result.authenticated {
320 if let Some(token) = &result.session_token {
321 *self.auth_token.write().await = Some(token.clone());
322 }
323 debug!("Authentication successful");
324 } else {
325 warn!("Authentication failed");
326 }
327
328 Ok(result)
329 }
330
331 pub async fn session_new(&self, params: SessionNewParams) -> AcpResult<SessionNewResult> {
333 if !self.is_initialized().await {
334 return Err(AcpError::InvalidRequest(
335 "Client not initialized. Call initialize() first.".to_string(),
336 ));
337 }
338
339 let result: SessionNewResult = self.call("session/new", Some(params)).await?;
340
341 let session = AcpSession::new(&result.session_id);
343 self.sessions
344 .write()
345 .await
346 .insert(result.session_id.clone(), session);
347
348 debug!(session_id = %result.session_id, "Session created");
349
350 Ok(result)
351 }
352
353 pub async fn session_load(&self, session_id: &str) -> AcpResult<SessionLoadResult> {
355 if !self.is_initialized().await {
356 return Err(AcpError::InvalidRequest(
357 "Client not initialized. Call initialize() first.".to_string(),
358 ));
359 }
360
361 let params = SessionLoadParams {
362 session_id: session_id.to_string(),
363 };
364
365 let result: SessionLoadResult = self.call("session/load", Some(params)).await?;
366
367 self.sessions
369 .write()
370 .await
371 .insert(session_id.to_string(), result.session.clone());
372
373 debug!(
374 session_id = session_id,
375 turns = result.history.len(),
376 "Session loaded"
377 );
378
379 Ok(result)
380 }
381
382 pub async fn session_prompt(
387 &self,
388 params: SessionPromptParams,
389 ) -> AcpResult<SessionPromptResult> {
390 self.session_prompt_with_timeout(params, None).await
391 }
392
393 pub async fn session_prompt_with_timeout(
395 &self,
396 params: SessionPromptParams,
397 timeout: Option<Duration>,
398 ) -> AcpResult<SessionPromptResult> {
399 if !self.is_initialized().await {
400 return Err(AcpError::InvalidRequest(
401 "Client not initialized. Call initialize() first.".to_string(),
402 ));
403 }
404
405 let session_id = params.session_id.clone();
406
407 if let Some(session) = self.sessions.write().await.get_mut(&session_id) {
409 session.set_state(SessionState::Active);
410 session.increment_turn();
411 }
412
413 let result: SessionPromptResult = if let Some(custom_timeout) = timeout {
415 tokio::time::timeout(
416 custom_timeout,
417 self.call::<_, SessionPromptResult>("session/prompt", Some(params)),
418 )
419 .await
420 .map_err(|_| AcpError::Timeout("Prompt request timed out".to_string()))??
421 } else {
422 self.call("session/prompt", Some(params)).await?
423 };
424
425 if let Some(session) = self.sessions.write().await.get_mut(&session_id) {
427 match result.status {
428 crate::session::TurnStatus::Completed => {
429 session.set_state(SessionState::AwaitingInput);
430 }
431 crate::session::TurnStatus::Cancelled => {
432 session.set_state(SessionState::Cancelled);
433 }
434 crate::session::TurnStatus::Failed => {
435 session.set_state(SessionState::Failed);
436 }
437 crate::session::TurnStatus::AwaitingInput => {
438 session.set_state(SessionState::AwaitingInput);
439 }
440 }
441 }
442
443 debug!(
444 session_id = %session_id,
445 turn_id = %result.turn_id,
446 status = ?result.status,
447 "Prompt completed"
448 );
449
450 Ok(result)
451 }
452
453 pub async fn session_cancel(&self, session_id: &str, turn_id: Option<&str>) -> AcpResult<()> {
455 let params = SessionCancelParams {
456 session_id: session_id.to_string(),
457 turn_id: turn_id.map(String::from),
458 };
459
460 self.notify("session/cancel", Some(params)).await?;
461
462 if let Some(session) = self.sessions.write().await.get_mut(session_id) {
464 session.set_state(SessionState::Cancelled);
465 }
466
467 debug!(session_id = session_id, "Session cancelled");
468
469 Ok(())
470 }
471
472 pub async fn get_session(&self, session_id: &str) -> Option<AcpSession> {
474 self.sessions.read().await.get(session_id).cloned()
475 }
476
477 pub async fn list_sessions(&self) -> Vec<AcpSession> {
479 self.sessions.read().await.values().cloned().collect()
480 }
481
482 pub async fn subscribe_updates(
491 &self,
492 session_id: &str,
493 ) -> AcpResult<mpsc::Receiver<SessionUpdateNotification>> {
494 let (tx, rx) = mpsc::channel(100);
495
496 let url = format!(
497 "{}/sse/session/{}",
498 self.base_url.trim_end_matches('/'),
499 session_id
500 );
501
502 let _http_client = self.http_client.clone();
503 let auth_token = self.auth_token.read().await.clone();
504
505 tokio::spawn(async move {
507 if let Err(e) = Self::sse_listener(url, auth_token, tx).await {
508 warn!("SSE listener error: {}", e);
509 }
510 });
511
512 Ok(rx)
513 }
514
515 async fn sse_listener(
517 url: String,
518 auth_token: Option<String>,
519 tx: mpsc::Sender<SessionUpdateNotification>,
520 ) -> AcpResult<()> {
521 let client = HttpClient::new();
522
523 let mut req = client.get(&url);
524 if let Some(token) = auth_token {
525 req = req.bearer_auth(token);
526 }
527
528 let response = req
529 .header("Accept", "text/event-stream")
530 .send()
531 .await
532 .map_err(|e| AcpError::NetworkError(e.to_string()))?;
533
534 if !response.status().is_success() {
535 return Err(AcpError::NetworkError(format!(
536 "SSE connection failed: {}",
537 response.status()
538 )));
539 }
540
541 let mut stream = response.bytes_stream();
542 use futures_util::StreamExt;
543
544 let mut buffer = String::new();
545
546 while let Some(chunk) = stream.next().await {
547 let chunk = chunk.map_err(|e| AcpError::NetworkError(e.to_string()))?;
548 buffer.push_str(&String::from_utf8_lossy(&chunk));
549
550 while let Some(event_end) = buffer.find("\n\n") {
552 let event = buffer[..event_end].to_string();
553 buffer = buffer[event_end + 2..].to_string();
554
555 let mut event_type = None;
557 let mut data_lines = Vec::new();
558
559 for line in event.lines() {
560 if let Some(data) = line.strip_prefix("data:") {
561 data_lines.push(data.trim());
562 } else if let Some(evt) = line.strip_prefix("event:") {
563 event_type = Some(evt.trim());
564 }
565 }
567
568 if event_type.is_none() || event_type == Some("session/update") {
570 if !data_lines.is_empty() {
571 let data = data_lines.join("\n");
572 if let Ok(notification) =
573 serde_json::from_str::<SessionUpdateNotification>(&data)
574 {
575 if tx.send(notification).await.is_err() {
576 return Ok(());
578 }
579 }
580 }
581 }
582 }
583 }
584
585 Ok(())
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592
593 #[test]
594 fn test_client_builder() {
595 let client = AcpClientV2Builder::new("http://localhost:8080")
596 .with_client_id("test-client")
597 .with_timeout(Duration::from_secs(60))
598 .build()
599 .unwrap();
600
601 assert_eq!(client.base_url, "http://localhost:8080");
602 assert_eq!(client.client_id, "test-client");
603 assert_eq!(client.timeout, Duration::from_secs(60));
604 }
605
606 #[tokio::test]
607 async fn test_client_not_initialized() {
608 let client = AcpClientV2::new("http://localhost:8080").unwrap();
609 assert!(!client.is_initialized().await);
610 }
611
612 #[test]
613 fn test_request_id_generation() {
614 let client = AcpClientV2::new("http://localhost:8080").unwrap();
615
616 let id1 = client.next_request_id();
617 let id2 = client.next_request_id();
618
619 assert_ne!(id1, id2);
620 }
621}