agent_works/handle.rs
1use tokio::sync::mpsc;
2
3use agent_base::{AgentRuntime, RuntimeEvent, SessionId};
4
5/// Agent session handle — unified input/output/cancel interface
6///
7/// `AgentHandle` wraps a command queue, a Worker task, an event stream, and cancellation.
8/// All callers (CLI / UI / HTTP API) interact with agent-base through it.
9///
10/// # Example
11///
12/// ```rust,no_run
13/// use agent_works::AgentHandle;
14/// use agent_base::AgentRuntime;
15///
16/// # async fn example(runtime: AgentRuntime) {
17/// let mut handle = AgentHandle::new(runtime);
18///
19/// // Send user input
20/// handle.send_input("check disk space").await.unwrap();
21///
22/// // Receive events
23/// while let Some(event) = handle.recv_event().await {
24/// // Handle event...
25/// if matches!(event, agent_base::RuntimeEvent::RunFinished { .. }
26/// | agent_base::RuntimeEvent::RunCancelled { .. }) {
27/// break;
28/// }
29/// }
30///
31/// // Cancel current execution
32/// handle.cancel();
33/// # }
34/// ```
35pub struct AgentHandle {
36 cmd_tx: mpsc::Sender<AgentCommand>,
37 event_rx: mpsc::UnboundedReceiver<RuntimeEvent>,
38 runtime: AgentRuntime,
39 default_session_id: Option<SessionId>,
40}
41
42enum AgentCommand {
43 RunTurn {
44 session_id: SessionId,
45 input: String,
46 },
47}
48
49#[derive(Debug)]
50pub enum SendError {
51 ChannelClosed,
52}
53
54impl AgentHandle {
55 /// Create a new AgentHandle, spawning a background Worker
56 pub fn new(runtime: AgentRuntime) -> Self {
57 let (cmd_tx, cmd_rx) = mpsc::channel(32);
58 let (event_tx, event_rx) = mpsc::unbounded_channel();
59 let rt = runtime.clone();
60
61 // Worker task: processes user requests serially
62 tokio::spawn(async move {
63 let mut rx = cmd_rx;
64 while let Some(cmd) = rx.recv().await {
65 match cmd {
66 AgentCommand::RunTurn { session_id, input } => {
67 let tx = event_tx.clone();
68 let sid = session_id.clone();
69 let result = rt.run_turn(session_id, &input, move |event| {
70 let _ = tx.send(event);
71 Ok(())
72 }).await;
73
74 match &result {
75 Ok(_) => {}
76 Err(e) if e.is_cancelled() => {}
77 Err(e) => {
78 tracing::error!(error = %e, "run_turn failed");
79 let _ = event_tx.send(RuntimeEvent::RunFinished {
80 session_id: sid,
81 });
82 }
83 }
84 }
85 }
86 }
87 });
88
89 Self {
90 cmd_tx,
91 event_rx,
92 runtime,
93 default_session_id: None,
94 }
95 }
96
97 /// Create an AgentHandle with a default session_id
98 /// The session_id will be used for all send_input calls unless overridden
99 pub fn with_session(runtime: AgentRuntime, session_id: SessionId) -> Self {
100 let (cmd_tx, cmd_rx) = mpsc::channel(32);
101 let (event_tx, event_rx) = mpsc::unbounded_channel();
102 let rt = runtime.clone();
103
104 // Worker task: processes user requests serially
105 tokio::spawn(async move {
106 let mut rx = cmd_rx;
107 while let Some(cmd) = rx.recv().await {
108 match cmd {
109 AgentCommand::RunTurn { session_id, input } => {
110 let tx = event_tx.clone();
111 let sid = session_id.clone();
112 let result = rt.run_turn(session_id, &input, move |event| {
113 let _ = tx.send(event);
114 Ok(())
115 }).await;
116
117 // Handle errors: ensure caller always gets a terminal event
118 match &result {
119 Ok(_) => {
120 // run_turn already emitted RunFinished or RunCancelled
121 }
122 Err(e) if e.is_cancelled() => {
123 // RunCancelled already emitted inside run_turn
124 }
125 Err(e) => {
126 // Non-cancellation error: emit RunFinished so caller isn't stuck
127 tracing::error!(error = %e, "run_turn failed");
128 let _ = event_tx.send(RuntimeEvent::RunFinished {
129 session_id: sid,
130 });
131 }
132 }
133 }
134 }
135 }
136 });
137
138 Self {
139 cmd_tx,
140 event_rx,
141 runtime,
142 default_session_id: Some(session_id),
143 }
144 }
145
146 /// Send user input (async, with error return)
147 /// Uses the default session_id if set via with_session(), otherwise creates a new session
148 pub async fn send_input(&self, input: &str) -> Result<(), SendError> {
149 let session_id = match &self.default_session_id {
150 Some(id) => id.clone(),
151 None => self.runtime.create_session().await,
152 };
153 self.cmd_tx
154 .send(AgentCommand::RunTurn {
155 session_id,
156 input: input.to_string(),
157 })
158 .await
159 .map_err(|_| SendError::ChannelClosed)
160 }
161
162 /// Send user input with a specified session_id
163 pub async fn send_input_with_session(
164 &self,
165 input: &str,
166 session_id: SessionId,
167 ) -> Result<(), SendError> {
168 self.cmd_tx
169 .send(AgentCommand::RunTurn {
170 session_id,
171 input: input.to_string(),
172 })
173 .await
174 .map_err(|_| SendError::ChannelClosed)
175 }
176
177 /// Receive the next event (blocking)
178 pub async fn recv_event(&mut self) -> Option<RuntimeEvent> {
179 self.event_rx.recv().await
180 }
181
182 /// Try to receive an event (non-blocking)
183 pub fn try_recv_event(&mut self) -> Option<RuntimeEvent> {
184 self.event_rx.try_recv().ok()
185 }
186
187 /// Cancel current execution — delegates to runtime, always cancels the latest token
188 pub fn cancel(&self) {
189 self.runtime.cancel();
190 }
191
192 /// Get a reference to the underlying runtime
193 pub fn runtime(&self) -> &AgentRuntime {
194 &self.runtime
195 }
196}
197
198#[cfg(test)]
199mod tests {
200 #[test]
201 fn test_agent_handle_creation() {
202 // This test requires a full AgentRuntime, skipped for now
203 // Actual testing is done in integration tests
204 }
205}