forked from agentclientprotocol/agent-client-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_agent.rs
More file actions
135 lines (122 loc) · 4.68 KB
/
example_agent.rs
File metadata and controls
135 lines (122 loc) · 4.68 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
//! A simple ACP agent server for educational purposes.
//!
//! The agent communicates with clients over stdio. To run it with logging:
//!
//! ```bash
//! RUST_LOG=info cargo run --example agent
//! ```
//!
//! To connect it to the example client from this crate:
//!
//! ```bash
//! cargo build --example agent && cargo run --example client -- target/debug/examples/agent
//! ```
use std::cell::Cell;
use agent_client_protocol::{self as acp, Client, SessionNotification};
use tokio::sync::{mpsc, oneshot};
use tokio_util::compat::{TokioAsyncReadCompatExt as _, TokioAsyncWriteCompatExt as _};
struct ExampleAgent {
session_update_tx: mpsc::UnboundedSender<(acp::SessionNotification, oneshot::Sender<()>)>,
next_session_id: Cell<u64>,
}
impl ExampleAgent {
fn new(
session_update_tx: mpsc::UnboundedSender<(acp::SessionNotification, oneshot::Sender<()>)>,
) -> Self {
Self {
session_update_tx,
next_session_id: Cell::new(0),
}
}
}
impl acp::Agent for ExampleAgent {
async fn initialize(
&self,
arguments: acp::InitializeRequest,
) -> Result<acp::InitializeResponse, acp::Error> {
log::info!("Received initialize request {arguments:?}");
Ok(acp::InitializeResponse {
protocol_version: acp::V1,
agent_capabilities: acp::AgentCapabilities::default(),
auth_methods: Vec::new(),
})
}
async fn authenticate(&self, arguments: acp::AuthenticateRequest) -> Result<(), acp::Error> {
log::info!("Received authenticate request {arguments:?}");
Ok(())
}
async fn new_session(
&self,
arguments: acp::NewSessionRequest,
) -> Result<acp::NewSessionResponse, acp::Error> {
log::info!("Received new session request {arguments:?}");
let session_id = self.next_session_id.get();
self.next_session_id.set(session_id + 1);
Ok(acp::NewSessionResponse {
session_id: acp::SessionId(session_id.to_string().into()),
})
}
async fn load_session(&self, arguments: acp::LoadSessionRequest) -> Result<(), acp::Error> {
log::info!("Received load session request {arguments:?}");
Err(acp::Error::method_not_found())
}
async fn prompt(
&self,
arguments: acp::PromptRequest,
) -> Result<acp::PromptResponse, acp::Error> {
log::info!("Received prompt request {arguments:?}");
for content in ["Client sent: ".into()].into_iter().chain(arguments.prompt) {
let (tx, rx) = oneshot::channel();
self.session_update_tx
.send((
SessionNotification {
session_id: arguments.session_id.clone(),
update: acp::SessionUpdate::AgentMessageChunk { content },
},
tx,
))
.map_err(|_| acp::Error::internal_error())?;
rx.await.map_err(|_| acp::Error::internal_error())?;
}
Ok(acp::PromptResponse {
stop_reason: acp::StopReason::EndTurn,
})
}
async fn cancel(&self, args: acp::CancelNotification) -> Result<(), acp::Error> {
log::info!("Received cancel request {args:?}");
Ok(())
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
env_logger::init();
let outgoing = tokio::io::stdout().compat_write();
let incoming = tokio::io::stdin().compat();
// The AgentSideConnection will spawn futures onto our Tokio runtime.
// LocalSet and spawn_local are used because the futures from the
// agent-client-protocol crate are not Send.
let local_set = tokio::task::LocalSet::new();
local_set
.run_until(async move {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
// Start up the ExampleAgent connected to stdio.
let (conn, handle_io) =
acp::AgentSideConnection::new(ExampleAgent::new(tx), outgoing, incoming, |fut| {
tokio::task::spawn_local(fut);
});
// Kick off a background task to send the ExampleAgent's session notifications to the client.
tokio::task::spawn_local(async move {
while let Some((session_notification, tx)) = rx.recv().await {
let result = conn.session_notification(session_notification).await;
if let Err(e) = result {
log::error!("{e}");
break;
}
tx.send(()).ok();
}
});
// Run until stdin/stdout are closed.
handle_io.await
})
.await
}