-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathacp.rs
More file actions
309 lines (272 loc) · 9.76 KB
/
acp.rs
File metadata and controls
309 lines (272 loc) · 9.76 KB
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
use std::{fmt::Debug, hash::Hash};
use agent_client_protocol_schema::{NewSessionRequest, NewSessionResponse, SessionId};
use crate::jsonrpc::{Builder, handlers::NullHandler, run::NullRun};
use crate::role::{HasPeer, RemoteStyle};
use crate::schema::{InitializeProxyRequest, InitializeRequest, METHOD_INITIALIZE_PROXY};
use crate::util::MatchDispatchFrom;
use crate::{ConnectTo, ConnectionTo, Dispatch, HandleDispatchFrom, Handled, Role, RoleId};
/// The client role - typically an IDE or CLI that controls an agent.
///
/// Clients send prompts and receive responses from agents.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Client;
impl Role for Client {
type Counterpart = Agent;
async fn default_handle_dispatch_from(
&self,
message: Dispatch,
_connection: ConnectionTo<Client>,
) -> Result<Handled<Dispatch>, crate::Error> {
Ok(Handled::No {
message,
retry: false,
})
}
fn role_id(&self) -> RoleId {
RoleId::from_singleton(self)
}
fn counterpart(&self) -> Self::Counterpart {
Agent
}
}
impl Client {
/// Create a connection builder for a client.
pub fn builder(self) -> Builder<Client, NullHandler, NullRun> {
Builder::new(self)
}
/// Connect to `agent` and run `main_fn` with the [`ConnectionTo`].
/// Returns the result of `main_fn` (or an error if something goes wrong).
///
/// Equivalent to `self.builder().connect_with(agent, main_fn)`.
pub async fn connect_with<R>(
self,
agent: impl ConnectTo<Client>,
main_fn: impl AsyncFnOnce(ConnectionTo<Agent>) -> Result<R, crate::Error>,
) -> Result<R, crate::Error> {
self.builder().connect_with(agent, main_fn).await
}
}
impl HasPeer<Client> for Client {
fn remote_style(&self, _peer: Client) -> RemoteStyle {
RemoteStyle::Counterpart
}
}
/// The agent role - typically an LLM that responds to prompts.
///
/// Agents receive prompts from clients and respond with answers,
/// potentially invoking tools along the way.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Agent;
impl Role for Agent {
type Counterpart = Client;
fn role_id(&self) -> RoleId {
RoleId::from_singleton(self)
}
fn counterpart(&self) -> Self::Counterpart {
Client
}
async fn default_handle_dispatch_from(
&self,
message: Dispatch,
connection: ConnectionTo<Agent>,
) -> Result<Handled<Dispatch>, crate::Error> {
MatchDispatchFrom::new(message, &connection)
.if_message_from(Agent, async |message: Dispatch| {
// Subtle: messages that have a session-id field
// should be captured by a dynamic message handler
// for that session -- but there is a race condition
// between the dynamic handler being added and
// possible updates. Therefore, we "retry" all such
// messages, so that they will be resent as new handlers
// are added.
let retry = message.has_session_id();
Ok(Handled::No { message, retry })
})
.await
.done()
}
}
impl Agent {
/// Create a connection builder for an agent.
pub fn builder(self) -> Builder<Agent, NullHandler, NullRun> {
Builder::new(self)
}
}
impl HasPeer<Agent> for Agent {
fn remote_style(&self, _peer: Agent) -> RemoteStyle {
RemoteStyle::Counterpart
}
}
/// The proxy role - an intermediary that can intercept and modify messages.
///
/// Proxies sit between a client and an agent (or another proxy), and can:
/// - Add tools via MCP servers
/// - Filter or transform messages
/// - Inject additional context
///
/// Proxies connect to a [`Conductor`] which orchestrates the proxy chain.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Proxy;
impl Role for Proxy {
type Counterpart = Conductor;
async fn default_handle_dispatch_from(
&self,
message: crate::Dispatch,
_connection: crate::ConnectionTo<Self>,
) -> Result<crate::Handled<crate::Dispatch>, crate::Error> {
Ok(Handled::No {
message,
retry: false,
})
}
fn role_id(&self) -> RoleId {
RoleId::from_singleton(self)
}
fn counterpart(&self) -> Self::Counterpart {
Conductor
}
}
impl Proxy {
/// Create a connection builder for a proxy.
pub fn builder(self) -> Builder<Proxy, NullHandler, NullRun> {
Builder::new(self)
}
}
impl HasPeer<Proxy> for Proxy {
fn remote_style(&self, _peer: Proxy) -> RemoteStyle {
RemoteStyle::Counterpart
}
}
/// The conductor role - orchestrates proxy chains.
///
/// Conductors manage connections between clients, proxies, and agents,
/// routing messages through the appropriate proxy chain.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Conductor;
impl Role for Conductor {
type Counterpart = Proxy;
fn role_id(&self) -> RoleId {
RoleId::from_singleton(self)
}
fn counterpart(&self) -> Self::Counterpart {
Proxy
}
async fn default_handle_dispatch_from(
&self,
message: Dispatch,
cx: ConnectionTo<Conductor>,
) -> Result<Handled<Dispatch>, crate::Error> {
// Handle various special messages:
MatchDispatchFrom::new(message, &cx)
.if_request_from(Client, async |_req: InitializeRequest, responder| {
responder.respond_with_error(crate::Error::invalid_request().data(format!(
"proxies must be initialized with `{METHOD_INITIALIZE_PROXY}`"
)))
})
.await
// Initialize Proxy coming from the client -- forward to the agent but
// convert into a regular initialize.
.if_request_from(
Client,
async |request: InitializeProxyRequest, responder| {
let InitializeProxyRequest { initialize } = request;
cx.send_request_to(Agent, initialize)
.forward_response_to(responder)
},
)
.await
// New session coming from the client -- proxy to the agent
// and add a dynamic handler for that session-id.
.if_request_from(Client, async |request: NewSessionRequest, responder| {
cx.send_request_to(Agent, request).on_receiving_result({
let cx = cx.clone();
async move |result| {
if let Ok(NewSessionResponse { session_id, .. }) = &result {
cx.add_dynamic_handler(ProxySessionMessages::new(session_id.clone()))?
.run_indefinitely();
}
responder.respond_with_result(result)
}
})
})
.await
// Incoming message from the client -- forward to the agent
.if_message_from(Client, async |message: Dispatch| {
cx.send_proxied_message_to(Agent, message)
})
.await
// Incoming message from the agent -- forward to the client
.if_message_from(Agent, async |message: Dispatch| {
cx.send_proxied_message_to(Client, message)
})
.await
.done()
}
}
impl Conductor {
/// Create a connection builder for a conductor.
pub fn builder(self) -> Builder<Conductor, NullHandler, NullRun> {
Builder::new(self)
}
}
impl HasPeer<Client> for Conductor {
fn remote_style(&self, _peer: Client) -> RemoteStyle {
RemoteStyle::Predecessor
}
}
impl HasPeer<Agent> for Conductor {
fn remote_style(&self, _peer: Agent) -> RemoteStyle {
RemoteStyle::Successor
}
}
/// Dynamic handler that proxies session messages from Agent to Client.
///
/// This is used internally to handle session message routing after a
/// `session.new` request has been forwarded.
pub(crate) struct ProxySessionMessages {
session_id: SessionId,
}
impl ProxySessionMessages {
/// Create a new proxy handler for the given session.
pub fn new(session_id: SessionId) -> Self {
Self { session_id }
}
}
impl<Counterpart: Role> HandleDispatchFrom<Counterpart> for ProxySessionMessages
where
Counterpart: HasPeer<Agent> + HasPeer<Client>,
{
async fn handle_dispatch_from(
&mut self,
message: Dispatch,
connection: ConnectionTo<Counterpart>,
) -> Result<Handled<Dispatch>, crate::Error> {
MatchDispatchFrom::new(message, &connection)
.if_message_from(Agent, async |message| {
// If this is for our session-id, proxy it to the client.
let session_id = match message.get_session_id() {
Ok(session_id) => session_id,
Err(error) => {
message.respond_with_error(error, connection.clone())?;
return Ok(Handled::Yes);
}
};
if let Some(session_id) = session_id
&& session_id == self.session_id
{
connection.send_proxied_message_to(Client, message)?;
return Ok(Handled::Yes);
}
// Otherwise, leave it alone.
Ok(Handled::No {
message,
retry: false,
})
})
.await
.done()
}
fn describe_chain(&self) -> impl std::fmt::Debug {
format!("ProxySessionMessages({})", self.session_id)
}
}