1pub(crate) mod agent_node;
20pub(crate) mod compaction;
21pub(crate) mod find_agent;
22pub(crate) mod live;
23pub(crate) mod run_node;
24
25use std::sync::Arc;
26use std::time::Duration;
27
28use futures::StreamExt;
29use gadk_agent::fiber::FiberStream;
30use gadk_agent::{
31 Agent, AgentError, Context, ContextDelta, EventStream, InvocationContext, Mode, ParentMap,
32 Plugin, PluginManager, RunConfig,
33};
34use gadk_genai::{Content, Part};
35use gadk_platform::Platform;
36use gadk_session::{CreateRequest, Event, EventCompaction, GetRequest, Session, SessionService};
37use serde_json::{Map, Value};
38use tokio_util::sync::CancellationToken;
39
40use crate::llm::agent::underlying_session;
41use crate::llm::mode::resolve_mode;
42use crate::llm::state::reveal;
43use find_agent::find_active_task_isolation_scope;
44use run_node::is_llm_agent;
45
46pub const BEFORE_RUN_REPLY_KEY: &str = "adk:before_run_reply";
48
49#[derive(Clone)]
51pub struct RunnerConfig {
52 pub app_name: String,
54 pub agent: Arc<dyn Agent>,
56 pub session_service: Arc<dyn SessionService>,
58 pub artifact_service: Option<Arc<dyn gadk_artifact::ArtifactService>>,
60 pub memory_service: Option<Arc<dyn gadk_memory::MemoryService>>,
62 pub plugin_config: PluginConfig,
64 pub auto_create_session: bool,
69 pub platform: Platform,
71 pub compaction: Option<gadk_session::compaction::Config>,
77}
78
79#[derive(Clone, Default)]
81pub struct PluginConfig {
82 pub plugins: Vec<Plugin>,
84 pub close_timeout: Duration,
86}
87
88#[derive(Clone, Default)]
90pub struct RunOptions {
91 pub state_delta: Option<Map<String, Value>>,
93 pub yield_user_message: bool,
95}
96
97pub struct Runner {
99 inner: Arc<RunnerInner>,
100}
101
102pub(crate) struct RunnerInner {
103 app_name: String,
104 root_agent: Arc<dyn Agent>,
105 session_service: Arc<dyn SessionService>,
106 artifact_service: Option<Arc<dyn gadk_artifact::ArtifactService>>,
107 memory_service: Option<Arc<dyn gadk_memory::MemoryService>>,
108 parents: Arc<ParentMap>,
109 plugin_manager: Arc<PluginManager>,
110 auto_create_session: bool,
111 platform: Platform,
112 compaction: Option<Arc<gadk_session::compaction::Config>>,
115}
116
117#[derive(Debug)]
119struct Wrapped {
120 context: String,
121 source: Box<dyn std::error::Error + Send + Sync>,
122}
123
124impl std::fmt::Display for Wrapped {
125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126 write!(f, "{}: {}", self.context, self.source)
127 }
128}
129
130impl std::error::Error for Wrapped {
131 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
132 Some(&*self.source)
133 }
134}
135
136pub(crate) fn wrap(
139 context: impl Into<String>,
140 source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
141) -> AgentError {
142 AgentError::Other(Box::new(Wrapped {
143 context: context.into(),
144 source: source.into(),
145 }))
146}
147
148fn is_llm_calls_limit(err: &AgentError) -> bool {
150 let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
151 while let Some(e) = cur {
152 if matches!(
153 e.downcast_ref::<AgentError>(),
154 Some(AgentError::LlmCallsLimitExceeded { .. })
155 ) {
156 return true;
157 }
158 cur = e.source();
159 }
160 false
161}
162
163pub(crate) fn from_plugin(
168 original: Event,
169 modified: Option<Event>,
170 record: Option<EventCompaction>,
171) -> Event {
172 let Some(mut out) = modified else {
173 let mut ev = original;
174 ev.actions.compaction = record;
175 return ev;
176 };
177 out.actions.compaction = record;
178 out.id = original.id;
179 out.invocation_id = original.invocation_id;
180 out.timestamp = original.timestamp;
181 if out.author.is_empty() {
182 out.author = original.author;
183 }
184 out
185}
186
187pub(crate) fn stamp_timestamp(ctx: &InvocationContext, event: &mut Event) {
191 if event.timestamp == gadk_session::zero_time() {
192 event.timestamp = ctx.platform().now();
193 }
194}
195
196pub(crate) const ERR_USER_FUNCTION_CALL: &str = "user message cannot contain function calls";
199
200pub(crate) fn has_function_call(content: Option<&Content>) -> bool {
202 !crate::tool::utils::function_calls(content).is_empty()
203}
204
205fn as_user_content(msg: Option<Content>) -> Option<Content> {
210 msg.map(|mut m| {
211 m.role = gadk_genai::ROLE_USER.to_string();
212 m
213 })
214}
215
216pub(crate) enum Processed {
218 Event(Box<Event>),
220 PluginError(AgentError),
222 AppendError(AgentError),
224}
225
226impl Runner {
227 pub fn new(cfg: RunnerConfig) -> Result<Runner, AgentError> {
229 Self::new_with_summarizer_timeout(cfg, compaction::DEFAULT_SUMMARIZER_TIMEOUT)
230 }
231
232 pub(crate) fn new_with_summarizer_timeout(
234 cfg: RunnerConfig,
235 summarizer_timeout: Duration,
236 ) -> Result<Runner, AgentError> {
237 let parents =
238 ParentMap::new(&cfg.agent).map_err(|e| wrap("failed to create agent tree", e))?;
239 let plugin_manager =
240 PluginManager::new(cfg.plugin_config.plugins, cfg.plugin_config.close_timeout)
241 .map_err(|e| wrap("failed to create plugin manager", e))?;
242 let compaction = compaction::resolve_compaction_config(
243 cfg.compaction.as_ref(),
244 &cfg.agent,
245 summarizer_timeout,
246 )?;
247 Ok(Runner {
248 inner: Arc::new(RunnerInner {
249 app_name: cfg.app_name,
250 root_agent: cfg.agent,
251 session_service: cfg.session_service,
252 artifact_service: cfg.artifact_service,
253 memory_service: cfg.memory_service,
254 parents: Arc::new(parents),
255 plugin_manager: Arc::new(plugin_manager),
256 auto_create_session: cfg.auto_create_session,
257 platform: cfg.platform,
258 compaction,
259 }),
260 })
261 }
262
263 pub fn in_memory(app_name: &str, agent: Arc<dyn Agent>) -> Result<Runner, AgentError> {
266 Runner::new(RunnerConfig {
267 app_name: app_name.to_string(),
268 agent,
269 session_service: Arc::new(gadk_session::InMemorySessionService::new()),
270 artifact_service: Some(Arc::new(gadk_artifact::InMemoryArtifactService::new())),
271 memory_service: Some(Arc::new(gadk_memory::InMemoryMemoryService::new())),
272 plugin_config: PluginConfig::default(),
273 auto_create_session: true,
274 platform: Platform::default(),
275 compaction: None,
276 })
277 }
278
279 pub fn run(
303 &self,
304 user_id: &str,
305 session_id: &str,
306 msg: Option<Content>,
307 cfg: RunConfig,
308 opts: RunOptions,
309 ) -> EventStream {
310 self.run_inner(None, user_id, session_id, msg, cfg, opts)
311 }
312
313 pub fn run_with_context(
322 &self,
323 ctx: &InvocationContext,
324 user_id: &str,
325 session_id: &str,
326 msg: Option<Content>,
327 cfg: RunConfig,
328 opts: RunOptions,
329 ) -> EventStream {
330 let (_, inherited) = ctx.take_inherited_plugins();
331 self.run_inner(inherited, user_id, session_id, msg, cfg, opts)
332 }
333
334 fn run_inner(
335 &self,
336 inherited: Option<Arc<PluginManager>>,
337 user_id: &str,
338 session_id: &str,
339 msg: Option<Content>,
340 cfg: RunConfig,
341 opts: RunOptions,
342 ) -> EventStream {
343 let inner = self.inner.clone();
344 let root = inner.root_agent.clone();
345 let plugins = inner.with_plugin_manager(inherited);
346 let stream = crate::telemetry::instrumentation::instrument_invocation(
347 root.as_ref(),
348 session_id,
349 || {
350 inner.run_stream(
351 plugins,
352 user_id.to_string(),
353 session_id.to_string(),
354 msg,
355 cfg,
356 opts,
357 )
358 },
359 );
360 FiberStream::consumer(stream).boxed()
361 }
362
363 pub async fn close(&self) -> Result<(), AgentError> {
365 self.inner.plugin_manager.close().await
366 }
367}
368
369impl RunnerInner {
370 pub(crate) fn with_plugin_manager(
375 &self,
376 inherited: Option<Arc<PluginManager>>,
377 ) -> Arc<PluginManager> {
378 match inherited {
379 Some(pm) if !self.plugin_manager.has_plugins() && pm.has_plugins() => pm,
380 _ => self.plugin_manager.clone(),
381 }
382 }
383
384 fn route_function_response(
388 &self,
389 stored: &dyn Session,
390 msg: Option<&Content>,
391 ) -> (Arc<dyn Agent>, String, bool) {
392 let events = stored.events();
393 if let Some(ev) = find_agent::handle_user_function_call_response(&events, msg)
394 && let Some(sub) = self.root_agent.find_agent(&ev.author)
395 && !self.is_in_graph_workflow(&sub)
396 {
397 return (sub, ev.branch.clone(), true);
398 }
399 (self.root_agent.clone(), String::new(), false)
400 }
401
402 fn is_in_graph_workflow(&self, a: &Arc<dyn Agent>) -> bool {
404 let mut cur = Some(a.clone());
405 while let Some(x) = cur {
406 if x.agent_state().agent_type == gadk_agent::AgentType::WorkflowAgent {
407 return true;
408 }
409 cur = self.parents.parent(x.name());
410 }
411 false
412 }
413
414 async fn get_or_create_session(
421 &self,
422 user_id: &str,
423 session_id: &str,
424 ) -> Result<Arc<dyn Session>, AgentError> {
425 let got = self
426 .session_service
427 .get(GetRequest {
428 app_name: self.app_name.clone(),
429 user_id: user_id.into(),
430 session_id: session_id.into(),
431 ..Default::default()
432 })
433 .await;
434 match got {
435 Ok(s) => Ok(s),
436 Err(e)
437 if !self.auto_create_session
438 || (!session_id.is_empty()
439 && !matches!(e, gadk_session::SessionError::NotFound)) =>
440 {
441 Err(e.into())
442 }
443 Err(_) => Ok(self
444 .session_service
445 .create(CreateRequest {
446 app_name: self.app_name.clone(),
447 user_id: user_id.into(),
448 session_id: Some(session_id.into()),
449 state: None,
450 })
451 .await?),
452 }
453 }
454
455 fn run_stream(
457 self: Arc<Self>,
458 plugins: Arc<PluginManager>,
459 user_id: String,
460 session_id: String,
461 msg: Option<Content>,
462 cfg: RunConfig,
463 opts: RunOptions,
464 ) -> EventStream {
465 let this = self;
466 let msg = as_user_content(msg);
469 Box::pin(async_stream::stream! {
470 let stored = match this.get_or_create_session(&user_id, &session_id).await {
471 Ok(s) => s,
472 Err(e) => { yield Err(e); return; }
473 };
474
475 if is_llm_agent(&*this.root_agent) {
477 let Some(state) = reveal(&*this.root_agent) else {
478 yield Err(AgentError::Config(format!(
479 "agent {} is not an LlmAgent",
480 this.root_agent.name()
481 )));
482 return;
483 };
484 let root_mode = resolve_mode(state.cfg.mode, Mode::Chat);
486 if root_mode != Mode::Chat {
487 yield Err(AgentError::Config(format!(
488 "root agent {} must be a chat LlmAgent, but has mode {}",
489 this.root_agent.name(),
490 root_mode.as_str()
491 )));
492 return;
493 }
494 let has_task_sub_agent = this
497 .root_agent
498 .sub_agents()
499 .iter()
500 .any(|s| reveal(&**s).is_some_and(|st| st.cfg.mode == Mode::Task));
501 let agent_to_run = if has_task_sub_agent {
502 this.root_agent.clone()
503 } else {
504 match this.find_agent_to_run(&*stored, msg.as_ref()) {
505 Ok(a) => a,
506 Err(e) => { yield Err(e); return; }
507 }
508 };
509 let mut events = run_node::run_node(
510 this.clone(),
511 plugins,
512 stored,
513 agent_to_run,
514 root_mode,
515 msg,
516 cfg,
517 opts,
518 );
519 while let Some(item) = events.next().await {
520 yield item;
521 }
522 return;
523 }
524
525 let (agent_to_run, branch, routed_to_caller) = this.route_function_response(&*stored, msg.as_ref());
532 let (mut invocation_id, spans_invocations) =
535 run_node::resolve_invocation_id(Some(&*stored), msg.as_ref());
536 if spans_invocations && routed_to_caller {
537 invocation_id = String::new();
538 }
539 let token = CancellationToken::new();
540 let cancel_on_drop = token.clone().drop_guard();
541 let ictx = this.new_invocation_context(
542 &stored,
543 agent_to_run.clone(),
544 msg.clone(),
545 &cfg,
546 &token,
547 true,
548 plugins,
549 invocation_id,
550 branch,
551 );
552 let appended = this
553 .append_message_to_session(
554 ictx.into_context(),
555 &stored,
556 msg,
557 cfg.save_input_blobs_as_artifacts,
558 opts.state_delta.clone(),
559 )
560 .await;
561 let ctx = match appended {
562 Ok((ctx, _)) => ctx,
563 Err(e) => { yield Err(e); return; }
564 };
565 let ictx = ctx.as_invocation().clone();
566 let mut guard = compaction::InvocationGuard::new(this.clone(), stored.clone(), ictx.clone());
567 guard.cancel_on_drop(cancel_on_drop);
568 guard.defer_after_run();
569 let mut early = false;
570 'run: {
571 match this.run_before_run_callback(&ictx).await {
572 Err(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); early = true; break 'run; }
573 Ok(Some(ev)) => { guard.at_yield(true); yield Ok(ev); guard.at_yield(false); early = true; break 'run; }
574 Ok(None) => {}
575 }
576 let mut events = agent_to_run.run(ictx.clone());
577 while let Some(item) = events.next().await {
578 let event = match item {
579 Ok(ev) => ev,
580 Err(e) => {
581 let stop = is_llm_calls_limit(&e);
584 guard.mark_failed();
585 guard.at_yield(true);
586 yield Err(e);
587 guard.at_yield(false);
588 if stop {
589 early = true;
590 break 'run;
591 }
592 continue;
593 }
594 };
595 match this.process_event(&ictx, &*stored, event).await {
596 Processed::Event(ev) => { guard.at_yield(true); yield Ok(*ev); guard.at_yield(false); }
597 Processed::PluginError(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); }
598 Processed::AppendError(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); early = true; break 'run; }
599 }
600 }
601 }
602 if early {
603 guard.finish_early().await;
604 } else {
605 if let Some(e) = guard.compact_inline().await {
608 guard.at_yield(true);
609 yield Err(e);
610 guard.at_yield(false);
611 }
612 guard.finish().await;
613 }
614 })
615 }
616
617 pub(crate) async fn process_event(
620 &self,
621 ctx: &InvocationContext,
622 stored: &dyn Session,
623 mut event: Event,
624 ) -> Processed {
625 stamp_timestamp(ctx, &mut event);
626 if !event.response.partial
627 && event
628 .node_info
629 .as_ref()
630 .is_some_and(|n| n.message_as_output)
631 && event.response.content.is_some()
632 {
633 event.output = None;
634 }
635 let record = event.actions.compaction.clone();
637 match self
638 .plugin_manager
639 .run_on_event(ctx.clone(), event.clone())
640 .await
641 {
642 Err(e) => return Processed::PluginError(e),
643 Ok(modified) => event = from_plugin(event, modified, record),
644 }
645 stamp_timestamp(ctx, &mut event);
647 if !event.response.partial
649 && let Err(e) = self.session_service.append_event(stored, &mut event).await
650 {
651 return Processed::AppendError(wrap("failed to add event to session", e));
652 }
653 Processed::Event(Box::new(event))
654 }
655
656 pub(crate) async fn run_before_run_callback(
658 &self,
659 ctx: &InvocationContext,
660 ) -> Result<Option<Event>, AgentError> {
661 let Some(content) = self.plugin_manager.run_before_run(ctx.clone()).await? else {
662 return Ok(None);
663 };
664 let mut event = Event::new(ctx.platform(), ctx.invocation_id());
665 event.author = ctx.agent().name().to_string();
667 event.response.content = Some(content);
668 let record = event.actions.compaction.clone();
669 let modified = self
670 .plugin_manager
671 .run_on_event(ctx.clone(), event.clone())
672 .await?;
673 let mut event = from_plugin(event, modified, record);
674 event
677 .response
678 .custom_metadata
679 .insert(BEFORE_RUN_REPLY_KEY.to_string(), Value::Bool(true));
680 stamp_timestamp(ctx, &mut event);
681 if !event.response.partial {
682 let session = underlying_session(&ctx.session());
684 self.session_service
685 .append_event(&*session, &mut event)
686 .await
687 .map_err(|e| wrap("failed to add event to session", e))?;
688 }
689 Ok(Some(event))
690 }
691
692 pub(crate) async fn append_message_to_session(
695 &self,
696 mut ctx: Context,
697 stored: &Arc<dyn Session>,
698 msg: Option<Content>,
699 save_input_blobs_as_artifacts: bool,
700 state_delta: Option<Map<String, Value>>,
701 ) -> Result<(Context, Option<Event>), AgentError> {
702 let Some(mut msg) = msg else {
703 return Ok((ctx, None));
704 };
705 let modified = self
706 .plugin_manager
707 .run_on_user_message(ctx.as_invocation().clone(), msg.clone())
708 .await
709 .map_err(|e| wrap("error running on run user message callback ", e))?;
710 if let Some(m) = modified {
711 msg = m;
713 msg.role = gadk_genai::ROLE_USER.to_string();
714 ctx = ctx.with_delta(ContextDelta {
715 user_content: Some(Some(msg.clone())),
716 ..Default::default()
717 });
718 }
719
720 if has_function_call(Some(&msg)) {
721 return Err(AgentError::other(ERR_USER_FUNCTION_CALL));
722 }
723
724 if let (Some(artifacts), true) = (ctx.artifacts(), save_input_blobs_as_artifacts) {
725 let mut replaced = false;
726 for i in 0..msg.parts.len() {
727 if msg.parts[i].inline_data.is_none() {
728 continue;
729 }
730 let file_name = format!("artifact_{}_{}", ctx.invocation_id(), i);
731 artifacts
732 .save(&file_name, msg.parts[i].clone())
733 .await
734 .map_err(|e| wrap(format!("failed to save artifact {file_name}"), e))?;
735 msg.parts[i] = Part::from_text(format!(
737 "Uploaded file: {file_name}. It has been saved to the artifacts"
738 ));
739 replaced = true;
740 }
741 if replaced {
743 ctx = ctx.with_delta(ContextDelta {
744 user_content: Some(Some(msg.clone())),
745 ..Default::default()
746 });
747 }
748 }
749
750 let mut event = Event::new(ctx.platform(), ctx.invocation_id());
751 event.author = "user".to_string();
752 event.response.content = Some(msg);
753 if let Some(delta) = state_delta {
754 event.actions.state_delta = Some(delta);
755 }
756 if event.isolation_scope.is_empty() {
757 let iso = find_active_task_isolation_scope(Some(&**stored));
758 if !iso.is_empty() {
759 event.isolation_scope = iso;
760 }
761 }
762 self.session_service
763 .append_event(&**stored, &mut event)
764 .await
765 .map_err(|e| wrap("failed to append event to sessionService", e))?;
766 Ok((ctx, Some(event)))
767 }
768}
769
770#[cfg(test)]
771impl Runner {
772 pub(crate) fn session_service(&self) -> Arc<dyn SessionService> {
773 self.inner.session_service.clone()
774 }
775 pub(crate) fn has_artifact_service(&self) -> bool {
776 self.inner.artifact_service.is_some()
777 }
778 pub(crate) fn has_memory_service(&self) -> bool {
779 self.inner.memory_service.is_some()
780 }
781 pub(crate) fn auto_create_session(&self) -> bool {
782 self.inner.auto_create_session
783 }
784}