adk_agent/ambient/agent.rs
1use std::sync::Arc;
2
3use adk_core::{AdkError, Agent, Event, EventStream, Result};
4use futures::StreamExt;
5use tokio::sync::{Notify, RwLock, Semaphore, mpsc};
6use tokio::task::JoinHandle;
7
8use super::event_source::EventSource;
9
10/// Callback invoked when the ambient agent's event source fires.
11///
12/// Receives the trigger event and the agent reference. The callback is responsible
13/// for creating an appropriate `InvocationContext` (e.g. via a Runner) and invoking
14/// the agent. Return the resulting event stream for the ambient agent to consume.
15///
16/// # Example
17///
18/// ```rust,ignore
19/// use std::sync::Arc;
20/// use adk_agent::ambient::{AmbientAgent, TriggerHandler};
21///
22/// let handler: TriggerHandler = Arc::new(move |event, agent| {
23/// let runner = runner.clone();
24/// Box::pin(async move {
25/// // Use the event payload as user content and run through a Runner
26/// let content = Content::new("user").with_text(&event.payload.to_string());
27/// runner.run("user".into(), "session".into(), content).await
28/// })
29/// });
30/// ```
31pub type TriggerHandler = Arc<
32 dyn Fn(
33 super::event_source::TriggerEvent,
34 Arc<dyn Agent>,
35 )
36 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<EventStream>> + Send>>
37 + Send
38 + Sync,
39>;
40
41/// Lifecycle status of an [`AmbientAgent`].
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum AmbientAgentStatus {
44 /// The agent is actively processing events.
45 Running,
46 /// The agent is paused — subscription is alive but events are buffered, not processed.
47 Paused,
48 /// The agent is stopped — no background task is running.
49 Stopped,
50}
51/// Triggers handled at once unless [`AmbientAgent::with_max_concurrent_triggers`] says otherwise.
52const DEFAULT_MAX_CONCURRENT_TRIGGERS: usize = 4;
53
54/// A background agent triggered by an event source.
55///
56/// Wraps an [`Agent`] and an [`EventSource`], providing lifecycle control
57/// (start, stop, pause, resume) over the background event processing loop.
58///
59/// # Lifecycle
60///
61/// ```text
62/// Stopped → start() → Running → pause() → Paused → resume() → Running
63/// │ │
64/// └── stop() → Stopped ←┘
65/// ```
66///
67/// # Example
68///
69/// ```rust,ignore
70/// use std::sync::Arc;
71/// use adk_agent::ambient::{AmbientAgent, CronTrigger};
72///
73/// let trigger = CronTrigger::new("0 * * * * *")?;
74/// let mut ambient = AmbientAgent::new(agent, Arc::new(trigger));
75/// ambient.start().await?;
76/// // ... later
77/// ambient.stop().await?;
78/// ```
79pub struct AmbientAgent {
80 pub(super) agent: Arc<dyn Agent>,
81 source: Arc<dyn EventSource>,
82 trigger_handler: Option<TriggerHandler>,
83 status: Arc<RwLock<AmbientAgentStatus>>,
84 resume_notify: Arc<Notify>,
85 handle: Option<JoinHandle<()>>,
86 /// Bounds how many triggers are handled at once.
87 ///
88 /// Events used to be handled strictly one at a time — the loop drained a handler's whole
89 /// event stream before polling the source again — so one slow trigger blocked every later
90 /// one.
91 max_concurrent_triggers: usize,
92 /// Receives events the agent produces, when a caller asks for them.
93 output_tx: Option<mpsc::Sender<Result<Event>>>,
94}
95
96impl AmbientAgent {
97 /// Create a new ambient agent wrapping the given agent and event source.
98 ///
99 /// The agent starts in [`AmbientAgentStatus::Stopped`] state.
100 pub fn new(agent: Arc<dyn Agent>, source: Arc<dyn EventSource>) -> Self {
101 Self {
102 agent,
103 source,
104 trigger_handler: None,
105 status: Arc::new(RwLock::new(AmbientAgentStatus::Stopped)),
106 resume_notify: Arc::new(Notify::new()),
107 handle: None,
108 max_concurrent_triggers: DEFAULT_MAX_CONCURRENT_TRIGGERS,
109 output_tx: None,
110 }
111 }
112
113 /// Bounds how many triggers are handled concurrently. Defaults to four.
114 ///
115 /// A bound of zero is treated as one.
116 pub fn with_max_concurrent_triggers(mut self, max_concurrent_triggers: usize) -> Self {
117 self.max_concurrent_triggers = max_concurrent_triggers.max(1);
118 self
119 }
120
121 /// Delivers the events the agent produces to the returned receiver.
122 ///
123 /// Without this, produced events were logged at debug level and discarded, so a caller had
124 /// no way to observe what an ambient run did. Errors are delivered too, so a failing trigger
125 /// is visible rather than only logged.
126 ///
127 /// # Example
128 ///
129 /// ```rust,ignore
130 /// let mut outputs = ambient.take_output(64);
131 /// ambient.start().await?;
132 /// while let Some(event) = outputs.recv().await {
133 /// // observe what each trigger produced
134 /// }
135 /// ```
136 pub fn take_output(&mut self, capacity: usize) -> mpsc::Receiver<Result<Event>> {
137 let (tx, rx) = mpsc::channel(capacity.max(1));
138 self.output_tx = Some(tx);
139 rx
140 }
141
142 /// Set a trigger handler that will be called when the event source fires.
143 ///
144 /// The handler receives the trigger event and agent, and should invoke the
145 /// agent via a Runner or other mechanism. Without a handler, the ambient
146 /// agent only logs trigger events.
147 pub fn with_trigger_handler(mut self, handler: TriggerHandler) -> Self {
148 self.trigger_handler = Some(handler);
149 self
150 }
151
152 /// Start listening for events and invoking the agent.
153 ///
154 /// # Errors
155 ///
156 /// Returns an error if the agent is already running or paused, or if no trigger handler is
157 /// configured.
158 ///
159 /// Starting without a handler used to succeed and then only log each trigger, so
160 /// `AmbientAgent::new(..).start()` looked like it was running the agent while the agent was
161 /// never invoked. Refusing makes that visible at the call site.
162 pub async fn start(&mut self) -> Result<()> {
163 let current = *self.status.read().await;
164 if current != AmbientAgentStatus::Stopped {
165 return Err(AdkError::agent("agent already running"));
166 }
167
168 if self.trigger_handler.is_none() {
169 return Err(AdkError::agent(
170 "AmbientAgent has no trigger handler, so starting it would log trigger events \
171 without ever invoking the agent. Call `with_trigger_handler` with a closure \
172 that drives the agent through a Runner.",
173 ));
174 }
175
176 // Subscribe to the event source
177 let stream = self.source.subscribe().await?;
178
179 let status = Arc::clone(&self.status);
180 let resume_notify = Arc::clone(&self.resume_notify);
181 let agent = Arc::clone(&self.agent);
182 let trigger_handler = self.trigger_handler.clone();
183
184 *self.status.write().await = AmbientAgentStatus::Running;
185
186 let permits = Arc::new(Semaphore::new(self.max_concurrent_triggers));
187 let output_tx = self.output_tx.clone();
188 let handler = trigger_handler.expect("checked above");
189
190 let handle = tokio::spawn(async move {
191 let mut stream = stream;
192 let mut running = futures::stream::FuturesUnordered::new();
193
194 loop {
195 // Check if paused — wait until resumed.
196 loop {
197 let current_status = *status.read().await;
198 match current_status {
199 AmbientAgentStatus::Running => break,
200 AmbientAgentStatus::Paused => resume_notify.notified().await,
201 AmbientAgentStatus::Stopped => return,
202 }
203 }
204
205 // Draining finished triggers alongside reading the source is what removes the
206 // head-of-line blocking: one slow trigger no longer holds up every later one.
207 let event = if running.is_empty() {
208 stream.next().await
209 } else {
210 tokio::select! {
211 biased;
212 Some(()) = running.next() => continue,
213 event = stream.next() => event,
214 }
215 };
216
217 let Some(event) = event else {
218 // Source exhausted: let dispatched triggers finish so their output is not
219 // dropped mid-flight.
220 while running.next().await.is_some() {}
221 return;
222 };
223
224 let handler = Arc::clone(&handler);
225 let agent = Arc::clone(&agent);
226 let permits = Arc::clone(&permits);
227 let output_tx = output_tx.clone();
228
229 running.push(async move {
230 let _permit = permits.acquire_owned().await;
231
232 tracing::info!(
233 agent = agent.name(),
234 source = %event.source,
235 "ambient agent triggered"
236 );
237
238 match handler(event, Arc::clone(&agent)).await {
239 Ok(mut event_stream) => {
240 while let Some(result) = event_stream.next().await {
241 let failed = result.is_err();
242 // A run error can echo the prompt, so only its content-free
243 // part is logged.
244 if let Err(ref e) = result {
245 tracing::warn!(error = %e.diagnostics(), "ambient agent invocation error");
246 }
247
248 // Delivered when a caller asked for output, instead of being
249 // logged and dropped.
250 if let Some(ref tx) = output_tx
251 && tx.send(result).await.is_err()
252 {
253 tracing::debug!("ambient output receiver dropped");
254 return;
255 }
256
257 if failed {
258 return;
259 }
260 }
261 }
262 Err(e) => {
263 tracing::warn!(error = %e.diagnostics(), "ambient agent trigger handler failed");
264 if let Some(ref tx) = output_tx {
265 let _ = tx.send(Err(e)).await;
266 }
267 }
268 }
269 });
270 }
271 });
272
273 self.handle = Some(handle);
274 Ok(())
275 }
276
277 /// Stop the agent and cancel in-progress work.
278 ///
279 /// # Errors
280 ///
281 /// Returns an error if the agent is already stopped.
282 pub async fn stop(&mut self) -> Result<()> {
283 let current = *self.status.read().await;
284 if current == AmbientAgentStatus::Stopped {
285 return Err(AdkError::agent("agent already stopped"));
286 }
287
288 *self.status.write().await = AmbientAgentStatus::Stopped;
289
290 // Wake the task if paused so it can observe the Stopped state
291 self.resume_notify.notify_one();
292
293 if let Some(handle) = self.handle.take() {
294 handle.abort();
295 }
296
297 Ok(())
298 }
299
300 /// Pause event processing. The subscription remains alive but events are buffered.
301 ///
302 /// # Errors
303 ///
304 /// Returns an error if the agent is not currently running.
305 pub async fn pause(&mut self) -> Result<()> {
306 let current = *self.status.read().await;
307 if current != AmbientAgentStatus::Running {
308 return Err(AdkError::agent("can only pause a running agent"));
309 }
310
311 *self.status.write().await = AmbientAgentStatus::Paused;
312 Ok(())
313 }
314
315 /// Resume event processing after a pause.
316 ///
317 /// # Errors
318 ///
319 /// Returns an error if the agent is not currently paused.
320 pub async fn resume(&mut self) -> Result<()> {
321 let current = *self.status.read().await;
322 if current != AmbientAgentStatus::Paused {
323 return Err(AdkError::agent("can only resume a paused agent"));
324 }
325
326 *self.status.write().await = AmbientAgentStatus::Running;
327 self.resume_notify.notify_one();
328 Ok(())
329 }
330
331 /// Read the current lifecycle status.
332 pub async fn status(&self) -> AmbientAgentStatus {
333 *self.status.read().await
334 }
335}
336
337impl Drop for AmbientAgent {
338 fn drop(&mut self) {
339 if let Some(handle) = self.handle.take() {
340 handle.abort();
341 }
342 }
343}
344
345impl std::fmt::Debug for AmbientAgent {
346 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347 f.debug_struct("AmbientAgent")
348 .field("agent", &self.agent.name())
349 .field("source", &self.source.name())
350 .finish()
351 }
352}