mixtape_acp/lib.rs
1//! ACP (Agent Client Protocol) adapter for mixtape agents.
2//!
3//! This crate bridges [mixtape-core](mixtape_core) agents to the
4//! [Agent Client Protocol](https://agentclientprotocol.com), enabling editors
5//! and IDEs — VS Code, Zed, Neovim, JetBrains, Emacs, etc. — to use
6//! mixtape agents.
7//!
8//! # Architecture
9//!
10//! The ACP SDK returns `!Send` futures (uses RPITIT without `+ Send` bounds),
11//! while mixtape's `Agent` is `Send + Sync`. The bridge works as follows:
12//!
13//! 1. The ACP protocol loop runs on a `tokio::task::LocalSet`
14//! 2. `MixtapeAcpAgent` implements `acp::Agent` — its methods run in `!Send` context
15//! 3. Inside `prompt()`, `Agent::run()` is dispatched via `tokio::spawn()` onto
16//! the multi-threaded runtime
17//! 4. Events flow back via mpsc channels to a `spawn_local` relay task that
18//! calls `conn.session_notification()`
19//! 5. Permission requests carry an `Arc<Agent>` — the relay task calls
20//! `conn.request_permission()` to show a dialog in the IDE, then delivers
21//! the result via `agent.respond_to_authorization()`, unblocking the agent's
22//! `request_authorization()` which is waiting on an mpsc channel
23//!
24//! # Example
25//!
26//! ```rust,no_run
27//! use mixtape_acp::{MixtapeAcpBuilder, serve_stdio};
28//! use mixtape_core::Agent;
29//!
30//! #[tokio::main]
31//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
32//! let server = MixtapeAcpBuilder::new("my-agent", "0.1.0")
33//! .with_agent_factory(|| async {
34//! Agent::builder()
35//! // .bedrock(ClaudeSonnet4)
36//! .build()
37//! .await
38//! })
39//! .build()?;
40//!
41//! serve_stdio(server).await?;
42//! Ok(())
43//! }
44//! ```
45
46mod adapter;
47mod builder;
48mod convert;
49pub mod error;
50mod permission;
51mod session;
52mod types;
53
54pub use builder::{MixtapeAcpBuilder, MixtapeAcpServer};
55pub use error::AcpError;
56
57use agent_client_protocol::{
58 AgentSideConnection, Client, RequestPermissionRequest, SessionNotification,
59};
60use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
61
62use crate::permission::{
63 build_permission_options, build_permission_tool_call, outcome_to_authorization,
64};
65
66/// Serve the ACP protocol over stdin/stdout.
67///
68/// This is the main entry point for running a mixtape agent as an ACP server.
69/// It sets up the `LocalSet` required by the ACP SDK, connects via stdio,
70/// and drives the notification/permission relay.
71pub async fn serve_stdio(server: MixtapeAcpServer) -> Result<(), AcpError> {
72 let MixtapeAcpServer {
73 adapter,
74 mut notification_rx,
75 mut permission_rx,
76 } = server;
77
78 let local = tokio::task::LocalSet::new();
79 local
80 .run_until(async move {
81 let stdin = tokio::io::stdin().compat();
82 let stdout = tokio::io::stdout().compat_write();
83
84 let (conn, io_future) = AgentSideConnection::new(adapter, stdout, stdin, |fut| {
85 tokio::task::spawn_local(fut);
86 });
87
88 // Notification and permission relay task
89 tokio::task::spawn_local(async move {
90 loop {
91 tokio::select! {
92 Some(msg) = notification_rx.recv() => {
93 let notification = SessionNotification::new(
94 msg.session_id,
95 msg.update,
96 );
97 let _ = conn.session_notification(notification).await;
98 }
99 Some(req) = permission_rx.recv() => {
100 let tool_call = build_permission_tool_call(
101 &req.proposal_id,
102 &req.params,
103 );
104 let options = build_permission_options();
105
106 let perm_request = RequestPermissionRequest::new(
107 req.session_id,
108 tool_call,
109 options,
110 );
111
112 let auth = match conn.request_permission(perm_request).await {
113 Ok(response) => outcome_to_authorization(
114 response.outcome,
115 &req.tool_name,
116 ),
117 Err(_) => mixtape_core::AuthorizationResponse::Deny {
118 reason: Some("Permission request failed".to_string()),
119 },
120 };
121
122 // Deliver the IDE's response back to the agent,
123 // unblocking request_authorization().
124 if let Err(e) = req.agent
125 .respond_to_authorization(&req.proposal_id, auth)
126 .await
127 {
128 log::warn!(
129 "Failed to deliver permission response for {}: {}",
130 req.proposal_id, e
131 );
132 }
133 }
134 else => break,
135 }
136 }
137 });
138
139 io_future
140 .await
141 .map_err(|e| AcpError::Transport(e.to_string()))
142 })
143 .await
144}