adk_agent/ambient/runner_bridge.rs
1//! Driving an agent from a trigger without hand-rolling the invocation.
2//!
3//! [`TriggerHandler`](crate::ambient::TriggerHandler) hands a closure a [`TriggerEvent`] and an agent, and
4//! leaves it to build content, pick a session, and start a run. Every ambient caller therefore
5//! wrote the same three things, and getting the session wrong fails inside the event stream
6//! rather than at the call site. [`AmbientAgent::with_invoker`](super::AmbientAgent::with_invoker)
7//! supplies that wiring.
8
9use std::sync::Arc;
10
11use adk_core::{AgentInvoker, Content};
12
13use super::agent::{AmbientAgent, TriggerHandler};
14use super::event_source::TriggerEvent;
15
16/// Builds the prompt text a trigger event is turned into.
17type PromptFn = Arc<dyn Fn(&TriggerEvent) -> String + Send + Sync>;
18
19/// How trigger events map onto sessions.
20#[derive(Debug, Clone, Default)]
21pub enum TriggerSessionPolicy {
22 /// A fresh session per trigger, so each run starts with no history.
23 ///
24 /// The default. A schedule that fires every minute into one shared session would grow that
25 /// session's history — and the token cost of every subsequent run — without bound.
26 #[default]
27 PerTrigger,
28 /// One session reused by every trigger, carrying history forward.
29 ///
30 /// Suits a trigger that should accumulate context, and only where the run frequency is low
31 /// enough that unbounded history growth is acceptable. `Runner` serializes externally invoked
32 /// turns for the same shared session so their history cannot overlap.
33 Shared(String),
34}
35
36/// Configures how [`AmbientAgent::with_invoker`](super::AmbientAgent::with_invoker) turns trigger
37/// events into agent runs.
38///
39/// # Example
40///
41/// ```rust,ignore
42/// use adk_agent::ambient::{RunnerTriggerConfig, TriggerSessionPolicy};
43///
44/// let config = RunnerTriggerConfig::new("system")
45/// .with_session_policy(TriggerSessionPolicy::Shared("nightly-sweep".into()))
46/// .with_prompt(|event| format!("Disk sweep triggered by {}", event.source));
47/// ```
48#[derive(Clone)]
49pub struct RunnerTriggerConfig {
50 user_id: String,
51 session_policy: TriggerSessionPolicy,
52 prompt: PromptFn,
53}
54
55impl RunnerTriggerConfig {
56 /// Creates a configuration attributing runs to `user_id`.
57 ///
58 /// A trigger has no interactive user, so this is the identity the runs are recorded under —
59 /// `"system"` or a service account name rather than a person.
60 pub fn new(user_id: impl Into<String>) -> Self {
61 Self {
62 user_id: user_id.into(),
63 session_policy: TriggerSessionPolicy::default(),
64 prompt: Arc::new(default_prompt),
65 }
66 }
67
68 /// Sets how trigger events map onto sessions. Defaults to
69 /// [`TriggerSessionPolicy::PerTrigger`].
70 pub fn with_session_policy(mut self, policy: TriggerSessionPolicy) -> Self {
71 self.session_policy = policy;
72 self
73 }
74
75 /// Sets how a trigger event becomes prompt text.
76 ///
77 /// The default states the source and serializes the payload, which is rarely the phrasing an
78 /// agent should act on. Supply the instruction the run is meant to carry out.
79 pub fn with_prompt(
80 mut self,
81 prompt: impl Fn(&TriggerEvent) -> String + Send + Sync + 'static,
82 ) -> Self {
83 self.prompt = Arc::new(prompt);
84 self
85 }
86
87 /// The identity runs are attributed to.
88 pub fn user_id(&self) -> &str {
89 &self.user_id
90 }
91
92 /// Resolves the session id for `event` under the configured policy.
93 fn session_id(&self, event: &TriggerEvent) -> String {
94 match &self.session_policy {
95 TriggerSessionPolicy::PerTrigger => {
96 format!("{}-{}", event.source, uuid::Uuid::new_v4())
97 }
98 TriggerSessionPolicy::Shared(session_id) => session_id.clone(),
99 }
100 }
101}
102
103impl std::fmt::Debug for RunnerTriggerConfig {
104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 f.debug_struct("RunnerTriggerConfig")
106 .field("user_id", &self.user_id)
107 .field("session_policy", &self.session_policy)
108 .finish_non_exhaustive()
109 }
110}
111
112/// States the source and payload. Callers are expected to replace this with the instruction the
113/// run should carry out.
114fn default_prompt(event: &TriggerEvent) -> String {
115 format!("Triggered by {}. Payload: {}", event.source, event.payload)
116}
117
118impl AmbientAgent {
119 /// Drives the agent through `invoker` on every trigger.
120 ///
121 /// Pass a `Runner`, which implements [`AgentInvoker`]. This replaces the hand-written
122 /// [`with_trigger_handler`](AmbientAgent::with_trigger_handler) closure and creates the
123 /// session for each run, which [`Runner::run`](adk_core::AgentInvoker) does not do on its
124 /// own.
125 ///
126 /// When the invoker exposes its executable agent, as `Runner` does, the ambient wrapper adopts
127 /// that agent for logging and diagnostics. Opaque invokers retain the agent supplied to
128 /// [`AmbientAgent::new`].
129 ///
130 /// # Example
131 ///
132 /// ```rust,ignore
133 /// use std::sync::Arc;
134 /// use adk_agent::ambient::{AmbientAgent, CronTrigger, RunnerTriggerConfig};
135 ///
136 /// let runner = Arc::new(Runner::builder()
137 /// .app_name("sweeper")
138 /// .agent(Arc::clone(&agent))
139 /// .session_service(sessions)
140 /// .build()?);
141 ///
142 /// let mut ambient = AmbientAgent::new(agent, Arc::new(CronTrigger::new("0 * * * * *")?))
143 /// .with_invoker(runner, RunnerTriggerConfig::new("system"));
144 /// ambient.start().await?;
145 /// ```
146 pub fn with_invoker(
147 mut self,
148 invoker: Arc<dyn AgentInvoker>,
149 config: RunnerTriggerConfig,
150 ) -> Self {
151 if let Some(executable_agent) = invoker.agent() {
152 self.agent = executable_agent;
153 }
154 let handler: TriggerHandler = Arc::new(move |event, _agent| {
155 let invoker = Arc::clone(&invoker);
156 let config = config.clone();
157 Box::pin(async move {
158 let session_id = config.session_id(&event);
159 let content = Content::new("user").with_text((config.prompt)(&event));
160 invoker.invoke(&config.user_id, &session_id, content).await
161 })
162 });
163
164 self.with_trigger_handler(handler)
165 }
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171
172 fn event() -> TriggerEvent {
173 TriggerEvent {
174 source: "cron:0 * * * * *".to_string(),
175 payload: serde_json::json!({ "tick": "2026-08-22T13:45:00Z" }),
176 principal: None,
177 }
178 }
179
180 #[test]
181 fn per_trigger_is_the_default_policy() {
182 let config = RunnerTriggerConfig::new("system");
183
184 assert!(matches!(config.session_policy, TriggerSessionPolicy::PerTrigger));
185 }
186
187 #[test]
188 fn per_trigger_gives_every_event_its_own_session() {
189 let config = RunnerTriggerConfig::new("system");
190
191 let first = config.session_id(&event());
192 let second = config.session_id(&event());
193
194 assert_ne!(first, second, "a shared session would grow history without bound across ticks");
195 assert!(first.starts_with("cron:0 * * * * *-"), "got {first}");
196 }
197
198 #[test]
199 fn shared_reuses_one_session_across_events() {
200 let config = RunnerTriggerConfig::new("system")
201 .with_session_policy(TriggerSessionPolicy::Shared("sweep".to_string()));
202
203 assert_eq!(config.session_id(&event()), "sweep");
204 assert_eq!(config.session_id(&event()), "sweep");
205 }
206
207 #[test]
208 fn the_default_prompt_names_the_source_and_payload() {
209 let rendered = default_prompt(&event());
210
211 assert!(rendered.contains("cron:0 * * * * *"), "got {rendered}");
212 assert!(rendered.contains("2026-08-22T13:45:00Z"), "got {rendered}");
213 }
214
215 #[test]
216 fn a_custom_prompt_replaces_the_default() {
217 let config =
218 RunnerTriggerConfig::new("system").with_prompt(|event| format!("go: {}", event.source));
219
220 assert_eq!((config.prompt)(&event()), "go: cron:0 * * * * *");
221 }
222
223 #[test]
224 fn user_id_is_reported() {
225 assert_eq!(RunnerTriggerConfig::new("service-account").user_id(), "service-account");
226 }
227}