Skip to main content

gemini_adk_rs/orchestration/
mod.rs

1//! Agent orchestration — invoke an agent in a [`AgentMode`].
2//!
3//! An agent is a value ([`TextAgent`] — a local agent, a composed pipeline, or a
4//! remote A2A agent). Orchestration is the single question of *how* you invoke
5//! it; the result always lands in governed `State` under `{name}:result` (or
6//! `{name}:error`), so coordination is reactive and uniform regardless of the
7//! invoker (the model, a `Flow`, an `Extract`, or a watcher).
8//!
9//! | Mode | Sync? | Lowers to |
10//! |------|-------|-----------|
11//! | [`AgentMode::Call`] | sync — caller awaits | [`call_agent`] (agent-as-tool, awaited inline) |
12//! | [`AgentMode::Dispatch`] | async, fire-and-forget | [`BackgroundAgentDispatcher::dispatch`](crate::live::BackgroundAgentDispatcher) |
13//! | [`AgentMode::Background`] | async, model-aware | an agent-tool marked [`ToolExecutionMode::Background`](crate::live::ToolExecutionMode) |
14//!
15//! All three write `{name}:result`, so a `Flow` step can complete on a resolved
16//! result via [`Guard::resolved`](crate::flow::Guard::resolved), and any
17//! consumer reads the value the same way.
18
19use std::future::Future;
20use std::sync::Arc;
21
22use serde_json::Value;
23
24use crate::AsyncSourceFn;
25use crate::error::AgentError;
26use crate::llm::{BaseLlm, LlmRequest};
27use crate::state::State;
28use crate::text::TextAgent;
29
30/// How an agent is invoked.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum AgentMode {
33    /// Synchronous — the caller awaits the result. Use only for *fast*
34    /// dependencies (a voice session should not block on slow work).
35    Call,
36    /// Asynchronous, fire-and-forget — the conversation does not wait.
37    Dispatch,
38    /// Asynchronous, model-aware — runs detached; the result is delivered back
39    /// to the model via `FunctionResponseScheduling`.
40    Background,
41}
42
43/// State key an agent's successful result is written to.
44pub fn result_key(name: &str) -> String {
45    format!("{name}:result")
46}
47
48/// State key an agent's error is written to.
49pub fn error_key(name: &str) -> String {
50    format!("{name}:error")
51}
52
53/// The provenance source of a value at `key` (e.g. `"agent"`, `"fetch"`,
54/// `"llm"`, or `"extraction"`), if one was recorded under `state_meta:{key}`.
55pub fn provenance(state: &State, key: &str) -> Option<String> {
56    state
57        .get::<serde_json::Value>(&format!("state_meta:{key}"))
58        .and_then(|m| m.get("source").and_then(|s| s.as_str().map(String::from)))
59}
60
61/// Invoke `agent` **synchronously**: run it to completion, write its result to
62/// `{name}:result` (or its error to `{name}:error`), and return the result.
63///
64/// This is the [`AgentMode::Call`] lowering. It uses the same `{name}:result`
65/// convention as [`BackgroundAgentDispatcher::dispatch`](crate::live::BackgroundAgentDispatcher),
66/// so sync and async invocations are observed identically.
67pub async fn call_agent(
68    name: &str,
69    agent: Arc<dyn TextAgent>,
70    state: &State,
71) -> Result<String, AgentError> {
72    let result = agent.run(state).await;
73    match &result {
74        Ok(r) => {
75            let key = result_key(name);
76            let _ = state.set(
77                format!("state_meta:{key}"),
78                serde_json::json!({ "source": "agent", "resolver": name }),
79            );
80            let _ = state.set(key, r);
81        }
82        Err(e) => {
83            let _ = state.set(error_key(name), e.to_string());
84        }
85    }
86    result
87}
88
89enum Source {
90    /// Run a [`TextAgent`] (which reads its inputs from `State`).
91    Agent(Arc<dyn TextAgent>),
92    /// Run an async closure that reads `State` and returns a value — the seam
93    /// for a tool call, an HTTP fetch, or an MCP request.
94    Fetch(AsyncSourceFn),
95    /// One-shot OOB LLM completion over a `State`-interpolated prompt.
96    Llm {
97        /// The out-of-band LLM.
98        llm: Arc<dyn BaseLlm>,
99        /// Prompt template; `{key}` interpolates the `State` value at `key`.
100        prompt: String,
101    },
102}
103
104/// Interpolate `{key}` placeholders in `template` with `State` values.
105fn interpolate(template: &str, state: &State) -> String {
106    crate::utils::text::interpolate_with(template, |key| state.get::<serde_json::Value>(key))
107}
108
109/// A named async value source whose inputs come from `State` and whose result
110/// lands back in `State` under `{name}:result` (or `{name}:error`).
111///
112/// `Resolver` is the async sibling of the deterministic
113/// [`Recognizer`](crate::extract::Recognizer): both are *inputs from State →
114/// value*. A `Resolver`
115/// generalizes [`call_agent`] from "a sub-agent" to **any** async source — a sub-agent
116/// ([`Resolver::agent`]) or a system fetch / tool call / MCP request
117/// ([`Resolver::fetch`]) — under one result convention, so a `Flow` step can
118/// complete on it via [`Guard::resolved`](crate::flow::Guard::resolved)
119/// regardless of where the value came from.
120pub struct Resolver {
121    name: String,
122    source: Source,
123}
124
125impl Resolver {
126    /// Resolve by running a sub-agent. Its `String` output becomes the result.
127    pub fn agent(name: impl Into<String>, agent: Arc<dyn TextAgent>) -> Self {
128        Self {
129            name: name.into(),
130            source: Source::Agent(agent),
131        }
132    }
133
134    /// Resolve by running an async closure over a clone of `State` — the seam
135    /// for an HTTP fetch, a tool call, or an MCP request. The closure returns
136    /// `Ok(value)` on success or `Err(message)` to record an error.
137    pub fn fetch<F, Fut>(name: impl Into<String>, f: F) -> Self
138    where
139        F: Fn(State) -> Fut + Send + Sync + 'static,
140        Fut: Future<Output = Result<Value, String>> + Send + 'static,
141    {
142        let f = Arc::new(f);
143        Self {
144            name: name.into(),
145            source: Source::Fetch(Arc::new(move |state| {
146                let f = f.clone();
147                Box::pin(async move { f(state).await })
148            })),
149        }
150    }
151
152    /// Resolve by running a one-shot OOB LLM over a `State`-interpolated prompt
153    /// (`{key}` placeholders). The completion text becomes the result.
154    pub fn llm(name: impl Into<String>, llm: Arc<dyn BaseLlm>, prompt: impl Into<String>) -> Self {
155        Self {
156            name: name.into(),
157            source: Source::Llm {
158                llm,
159                prompt: prompt.into(),
160            },
161        }
162    }
163
164    /// The resolver's name (the `{name}:result` prefix it writes).
165    pub fn name(&self) -> &str {
166        &self.name
167    }
168
169    /// The provenance kind of this resolver's source (`agent`/`fetch`/`llm`).
170    fn source_kind(&self) -> &'static str {
171        match &self.source {
172            Source::Agent(_) => "agent",
173            Source::Fetch(_) => "fetch",
174            Source::Llm { .. } => "llm",
175        }
176    }
177
178    /// Resolve **synchronously** ([`AgentMode::Call`]): await the source, write its
179    /// value to `{name}:result` (or its error to `{name}:error`), record its
180    /// provenance under `state_meta:{name}:result`, and return it.
181    pub async fn resolve(&self, state: &State) -> Result<Value, String> {
182        let outcome = match &self.source {
183            Source::Agent(a) => a
184                .run(state)
185                .await
186                .map(Value::from)
187                .map_err(|e| e.to_string()),
188            Source::Fetch(f) => f(state.clone()).await,
189            Source::Llm { llm, prompt } => {
190                let rendered = interpolate(prompt, state);
191                llm.generate(LlmRequest::from_text(rendered))
192                    .await
193                    .map(|r| Value::from(r.text()))
194                    .map_err(|e| e.to_string())
195            }
196        };
197        match &outcome {
198            Ok(v) => {
199                let key = result_key(&self.name);
200                let _ = state.set(
201                    format!("state_meta:{key}"),
202                    serde_json::json!({ "source": self.source_kind(), "resolver": self.name }),
203                );
204                let _ = state.set(key, v.clone());
205            }
206            Err(e) => {
207                let _ = state.set(error_key(&self.name), e);
208            }
209        }
210        outcome
211    }
212
213    /// Resolve **detached** ([`AgentMode::Dispatch`]): spawn the resolution on the
214    /// runtime and return immediately. The conversation does not wait; consumers
215    /// observe completion reactively via `{name}:result`.
216    pub fn dispatch(self, state: State) {
217        tokio::spawn(async move {
218            let _ = self.resolve(&state).await;
219        });
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    use async_trait::async_trait;
227    use serde_json::json;
228
229    struct Echo(&'static str);
230    #[async_trait]
231    impl TextAgent for Echo {
232        fn name(&self) -> &str {
233            "echo"
234        }
235        async fn run(&self, _state: &State) -> Result<String, AgentError> {
236            Ok(self.0.to_string())
237        }
238    }
239
240    struct Boom;
241    #[async_trait]
242    impl TextAgent for Boom {
243        fn name(&self) -> &str {
244            "boom"
245        }
246        async fn run(&self, _state: &State) -> Result<String, AgentError> {
247            Err(AgentError::Other("kaboom".into()))
248        }
249    }
250
251    #[tokio::test]
252    async fn call_writes_result_to_state() {
253        let state = State::new();
254        let out = call_agent("verify", Arc::new(Echo("ok-123")), &state)
255            .await
256            .unwrap();
257        assert_eq!(out, "ok-123");
258        assert_eq!(
259            state.get::<String>("verify:result").as_deref(),
260            Some("ok-123")
261        );
262    }
263
264    #[tokio::test]
265    async fn call_writes_error_to_state() {
266        let state = State::new();
267        let r = call_agent("verify", Arc::new(Boom), &state).await;
268        assert!(r.is_err());
269        assert!(state.contains("verify:error"));
270        assert!(!state.contains("verify:result"));
271    }
272
273    #[tokio::test]
274    async fn resolver_fetch_binds_state_and_writes_result() {
275        let state = State::new();
276        let _ = state.set("slot", "afternoon");
277        let r = Resolver::fetch("availability", |s: State| async move {
278            // Inputs come from State; the value is arbitrary JSON.
279            let slot = s.get::<String>("slot").unwrap_or_default();
280            Ok(json!({ "open": slot == "afternoon" }))
281        });
282        let out = r.resolve(&state).await.unwrap();
283        assert_eq!(out, json!({ "open": true }));
284        assert_eq!(
285            state.get::<Value>("availability:result"),
286            Some(json!({ "open": true }))
287        );
288        // Provenance is recorded for the resolved value.
289        assert_eq!(
290            provenance(&state, "availability:result").as_deref(),
291            Some("fetch")
292        );
293    }
294
295    #[tokio::test]
296    async fn resolver_agent_uses_result_convention() {
297        let state = State::new();
298        // An agent resolver shares the `{name}:result` convention with `call`.
299        Resolver::agent("verify", Arc::new(Echo("ok-9")))
300            .resolve(&state)
301            .await
302            .unwrap();
303        assert_eq!(
304            state.get::<String>("verify:result").as_deref(),
305            Some("ok-9")
306        );
307    }
308
309    #[tokio::test]
310    async fn resolver_fetch_records_error() {
311        let state = State::new();
312        let r = Resolver::fetch("lookup", |_s: State| async move {
313            Err::<Value, String>("upstream 503".into())
314        });
315        assert!(r.resolve(&state).await.is_err());
316        assert_eq!(
317            state.get::<String>("lookup:error").as_deref(),
318            Some("upstream 503")
319        );
320        assert!(!state.contains("lookup:result"));
321    }
322
323    #[tokio::test]
324    async fn resolver_llm_interpolates_prompt_and_stores_text() {
325        use crate::llm::MockLlm;
326
327        // Echo the (interpolated) prompt back as the completion.
328        let state = State::new();
329        let _ = state.set("topic", "billing");
330        let out = Resolver::llm(
331            "summary",
332            Arc::new(MockLlm::echo()),
333            "Summarize the {topic} issue",
334        )
335        .resolve(&state)
336        .await
337        .unwrap();
338        assert_eq!(out, json!("Summarize the billing issue"));
339        assert_eq!(
340            state.get::<String>("summary:result").as_deref(),
341            Some("Summarize the billing issue")
342        );
343    }
344
345    #[tokio::test]
346    async fn resolver_dispatch_runs_detached() {
347        let state = State::new();
348        Resolver::fetch("ping", |_s: State| async move { Ok(json!("pong")) })
349            .dispatch(state.clone());
350        // The spawned task writes the result; await it becoming visible.
351        for _ in 0..100 {
352            if state.contains("ping:result") {
353                break;
354            }
355            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
356        }
357        assert_eq!(state.get::<String>("ping:result").as_deref(), Some("pong"));
358    }
359}