1use 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
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)
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 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 let _ = req_builder.send().await;
272
273 Ok(())
274 }
275
276 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 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 *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 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 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 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 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 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 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 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 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 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 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 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 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 pub async fn get_session(&self, session_id: &str) -> Option<AcpSession> {
472 self.sessions.read().await.get(session_id).cloned()
473 }
474
475 pub async fn list_sessions(&self) -> Vec<AcpSession> {
477 self.sessions.read().await.values().cloned().collect()
478 }
479
480 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 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 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 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 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 }
565
566 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 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}