1use crate::InvocationContext;
2use crate::cache::CacheManager;
3#[cfg(feature = "artifacts")]
4use adk_artifact::ArtifactService;
5use adk_core::{
6 Agent, AppName, CacheCapable, Content, ContextCacheConfig, Event, EventStream,
7 FunctionResponseData, InvocationId, Memory, Part, ReadonlyContext, Result, RunConfig,
8 SessionId, UserId,
9};
10#[cfg(feature = "plugins")]
11use adk_plugin::PluginManager;
12use adk_session::SessionService;
13#[cfg(feature = "skills")]
14use adk_skill::{SkillInjector, SkillInjectorConfig};
15use async_stream::stream;
16use std::{collections::HashMap, sync::Arc};
17use tokio_util::sync::CancellationToken;
18
19#[derive(Clone)]
24struct ActiveRun {
25 identity: adk_core::AdkIdentity,
26 token: CancellationToken,
27 inbox: adk_core::SteeringInbox,
28 #[cfg(feature = "plugins")]
30 scope: RunScope,
31}
32
33type ActiveRuns = Arc<std::sync::Mutex<std::collections::HashMap<u64, ActiveRun>>>;
35
36fn preserve_streamed_content(accumulated: &mut HashMap<String, Content>, event: &mut Event) {
37 if event.llm_response.partial {
38 if let Some(chunk) = &event.llm_response.content {
39 accumulated
40 .entry(event.id.clone())
41 .and_modify(|content| content.parts.extend(chunk.parts.clone()))
42 .or_insert_with(|| chunk.clone());
43 }
44 } else if event.llm_response.content.is_none() {
45 event.llm_response.content = accumulated.remove(&event.id);
46 } else {
47 accumulated.remove(&event.id);
48 }
49}
50
51struct InFlightCall {
53 id: Option<String>,
54 name: String,
55 args: serde_json::Value,
56 author: String,
57 branch: String,
58 invocation_id: String,
59}
60
61#[derive(Default)]
64struct InFlightCalls(Vec<InFlightCall>);
65
66impl InFlightCalls {
67 fn observe(&mut self, event: &Event) {
68 if event.llm_response.partial {
69 return;
70 }
71 let Some(content) = &event.llm_response.content else {
72 return;
73 };
74 for part in &content.parts {
75 match part {
76 Part::FunctionCall { name, args, id, .. } => self.0.push(InFlightCall {
77 id: id.clone(),
78 name: name.clone(),
79 args: args.clone(),
80 author: event.author.clone(),
81 branch: event.branch.clone(),
82 invocation_id: event.invocation_id.clone(),
83 }),
84 Part::FunctionResponse { function_response, id, .. } => {
85 let answered = match id {
86 Some(id) => self.0.iter().position(|call| call.id.as_ref() == Some(id)),
87 None => self.0.iter().position(|call| {
88 call.id.is_none() && call.name == function_response.name
89 }),
90 };
91 if let Some(index) = answered {
92 self.0.remove(index);
93 }
94 }
95 _ => {}
96 }
97 }
98 }
99
100 async fn audit_calls(
107 &self,
108 trail: &adk_core::audit_log::AuditTrail,
109 run_config: &RunConfig,
110 identity: &adk_core::AdkIdentity,
111 cause: &str,
112 outcome: impl Fn(&InFlightCall) -> adk_core::audit_log::AuditRecordOutcome,
113 ) -> Result<()> {
114 use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind};
115 for call in &self.0 {
116 let mut draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, call.name.as_str())
117 .actor(AuditActor::new(
118 &run_config.acting_context_for(
119 identity.app_name.as_ref(),
120 &call.author,
121 identity.user_id.as_ref(),
122 ),
123 &call.invocation_id,
124 ))
125 .args_digest(trail.digest(&call.args))
126 .outcome(outcome(call))
127 .ext("cause", serde_json::Value::String(cause.to_string()))
128 .ext("sessionId", serde_json::Value::String(identity.session_id.to_string()));
129 if let Some(id) = &call.id {
130 draft = draft.ext("functionCallId", serde_json::Value::String(id.clone()));
131 }
132 trail.record(draft).await?;
133 }
134 Ok(())
135 }
136
137 fn answer_interrupted(&mut self) -> Vec<Event> {
141 self.answer_with(|call| {
142 let response = adk_core::outcome_unknown_response(format!(
143 "the run was cancelled while '{}' was in flight, so the call may have taken effect; check its result before calling it again",
144 call.name
145 ));
146 (response, adk_core::ToolResultStatus::OutcomeUnknown)
147 })
148 }
149
150 fn answer_with(
153 &mut self,
154 mut respond: impl FnMut(&InFlightCall) -> (serde_json::Value, adk_core::ToolResultStatus),
155 ) -> Vec<Event> {
156 let mut events: Vec<Event> = Vec::new();
157 for call in std::mem::take(&mut self.0) {
158 let (response, status) = respond(&call);
159 let mut response = Part::FunctionResponse {
160 function_response: FunctionResponseData::new(call.name.clone(), response),
161 id: call.id,
162 annotations: None,
163 };
164 response.set_tool_result_status(status, None);
165 let existing = events.iter_mut().find(|event| {
166 event.author == call.author
167 && event.branch == call.branch
168 && event.invocation_id == call.invocation_id
169 });
170 match existing {
171 Some(event) => {
172 if let Some(content) = event.llm_response.content.as_mut() {
173 content.parts.push(response);
174 }
175 }
176 None => {
177 let mut event = Event::new(&call.invocation_id);
178 event.author = call.author;
179 event.branch = call.branch;
180 event.llm_response.content =
181 Some(Content { role: "function".to_string(), parts: vec![response] });
182 events.push(event);
183 }
184 }
185 }
186 events
187 }
188}
189
190fn recovered_call_response(
193 name: &str,
194 record: Option<adk_core::ActionRecord>,
195) -> (serde_json::Value, adk_core::ToolResultStatus) {
196 let outcome = record.and_then(|record| record.outcome);
197 let status = adk_core::ToolResultStatus::of_record(outcome.as_ref());
198 let response = match outcome {
199 Some(adk_core::ActionOutcome::Succeeded { result_digest }) => serde_json::json!({
200 "status": "already_succeeded",
201 "result_digest": result_digest,
202 "detail": format!("this call to '{name}' completed before the run was recovered; it was not executed again"),
203 }),
204 Some(adk_core::ActionOutcome::Failed { error }) => serde_json::json!({
205 "status": "already_failed",
206 "error": error,
207 "detail": format!("this call to '{name}' failed before the run was recovered; it was not executed again"),
208 }),
209 _ => adk_core::outcome_unknown_response(format!(
210 "the process running '{name}' stopped before the call recorded an outcome, so it may have taken effect; check its result before calling it again"
211 )),
212 };
213 (response, status)
214}
215
216async fn screen_unscreened_messages(
229 root: &Arc<dyn Agent>,
230 session: &dyn adk_session::Session,
231 resuming: bool,
232) -> Result<Vec<(usize, Option<Content>)>> {
233 let events = session.events();
234 let is_message = |event: &Event| {
235 event.author == "user"
236 && event.llm_response.content.as_ref().is_some_and(Content::carries_user_input)
237 };
238 let latest = (0..events.len()).rev().find(|&index| events.at(index).is_some_and(is_message));
239 let mut replacements = Vec::new();
240 for index in 0..events.len() {
241 let Some(event) = events.at(index) else { continue };
242 if event.actions.input_screened || !is_message(event) {
243 continue;
244 }
245 let Some(content) = event.llm_response.content.as_ref() else { continue };
246 match root.screen_user_input(content).await {
247 Ok(None) => return Ok(Vec::new()),
249 Ok(Some(screened)) => {
250 if screened.role != content.role || screened.parts != content.parts {
251 replacements.push((index, Some(screened)));
252 }
253 }
254 Err(error) if resuming && Some(index) == latest => return Err(error),
255 Err(error) => {
256 tracing::warn!(
257 event.id = %event.id,
258 error.code = %error.code,
259 "input guardrails block a saved user message; withholding it from this run"
260 );
261 replacements.push((index, None));
262 }
263 }
264 }
265 Ok(replacements)
266}
267
268struct ActiveRunCleanup {
274 active_runs: ActiveRuns,
275 run_id: u64,
276 inbox: adk_core::SteeringInbox,
277 _activity: crate::history::ActivityGuard,
279}
280
281pub struct RunnerInvocation {
286 invocation_id: InvocationId,
287 events: EventStream,
288}
289
290impl RunnerInvocation {
291 pub fn invocation_id(&self) -> &InvocationId {
293 &self.invocation_id
294 }
295
296 pub fn into_events(self) -> EventStream {
298 self.events
299 }
300}
301
302impl std::fmt::Debug for RunnerInvocation {
303 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304 formatter
305 .debug_struct("RunnerInvocation")
306 .field("invocation_id", &self.invocation_id)
307 .finish_non_exhaustive()
308 }
309}
310
311impl Drop for ActiveRunCleanup {
312 fn drop(&mut self) {
313 let mut runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
314 runs.remove(&self.run_id);
315 drop(runs);
316 self.inbox.close();
318 }
319}
320
321#[derive(Clone, Default)]
324struct RunScope(Arc<std::sync::Mutex<Option<Arc<InvocationContext>>>>);
325
326impl RunScope {
327 fn set(&self, ctx: &Arc<InvocationContext>) {
328 *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::clone(ctx));
329 }
330
331 fn take(&self) -> Option<Arc<InvocationContext>> {
332 self.0.lock().unwrap_or_else(|e| e.into_inner()).take()
333 }
334
335 #[cfg(feature = "plugins")]
336 fn get(&self) -> Option<Arc<InvocationContext>> {
337 self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
338 }
339}
340
341struct RunFinish {
352 scope: RunScope,
353 #[cfg(feature = "plugins")]
354 plugins: Option<Arc<PluginManager>>,
355 session_service: Arc<dyn SessionService>,
356 identity: adk_core::AdkIdentity,
357 in_flight: InFlightCalls,
358 finished: bool,
359}
360
361impl RunFinish {
362 async fn on_event(&self, event: Event) -> Event {
364 #[cfg(feature = "plugins")]
365 if let (Some(manager), Some(ctx)) = (self.plugins.as_ref(), self.scope.get()) {
366 return match manager
367 .run_on_event(ctx as Arc<dyn adk_core::InvocationContext>, event.clone())
368 .await
369 {
370 Ok(modified) => modified.unwrap_or(event),
371 Err(error) => {
372 tracing::warn!(error = %error, "on_event failed for the run's final event; keeping the event");
373 event
374 }
375 };
376 }
377 event
378 }
379
380 async fn after_run(&mut self) {
382 self.finished = true;
383 #[cfg(feature = "plugins")]
384 if let (Some(manager), Some(ctx)) = (self.plugins.as_ref(), self.scope.take()) {
385 manager.run_after_run(ctx as Arc<dyn adk_core::InvocationContext>).await;
386 }
387 }
388}
389
390impl Drop for RunFinish {
391 fn drop(&mut self) {
392 if self.finished {
393 return;
394 }
395 let Some(ctx) = self.scope.take() else { return };
396 if adk_core::InvocationContext::run_config(ctx.as_ref()).durable_run_id.is_some() {
397 tracing::debug!(
398 session.id = %self.identity.session_id,
399 "a durable attempt was dropped; the worker that recovers the run finishes it"
400 );
401 return;
402 }
403 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
404 tracing::warn!(
405 session.id = %self.identity.session_id,
406 "no Tokio runtime to finish a dropped run on; after_run and in-flight answers are skipped"
407 );
408 return;
409 };
410 let mut in_flight = std::mem::take(&mut self.in_flight);
411 #[cfg(feature = "plugins")]
412 let plugins = self.plugins.take();
413 let session_service = Arc::clone(&self.session_service);
414 let identity = self.identity.clone();
415 runtime.spawn(async move {
416 let run_config = adk_core::InvocationContext::run_config(ctx.as_ref());
417 if let Some(trail) = &run_config.audit {
418 let _ = in_flight
420 .audit_calls(trail, run_config, &identity, "disconnected", |_| {
421 adk_core::audit_log::AuditRecordOutcome::OutcomeUnknown
422 })
423 .await;
424 }
425 for event in in_flight.answer_interrupted() {
426 #[cfg(feature = "plugins")]
427 let event = match plugins.as_ref() {
428 Some(manager) => match manager
429 .run_on_event(ctx.clone() as Arc<dyn adk_core::InvocationContext>, event.clone())
430 .await
431 {
432 Ok(modified) => modified.unwrap_or(event),
433 Err(_) => event,
434 },
435 None => event,
436 };
437 ctx.mutable_session().append_event(event.clone());
438 if let Err(error) = session_service
439 .append_event_for_identity(adk_session::AppendEventRequest {
440 identity: identity.clone(),
441 event,
442 })
443 .await
444 {
445 tracing::error!(error = %error, "failed to persist the outcome of a tool call a dropped run left in flight");
446 }
447 }
448 #[cfg(feature = "plugins")]
449 if let Some(manager) = plugins {
450 manager.run_after_run(ctx as Arc<dyn adk_core::InvocationContext>).await;
451 }
452 });
453 }
454}
455use tracing::Instrument;
456
457pub struct RunnerConfig {
461 pub app_name: String,
463 pub agent: Arc<dyn Agent>,
465 pub session_service: Arc<dyn SessionService>,
467 #[cfg(feature = "artifacts")]
468 pub artifact_service: Option<Arc<dyn ArtifactService>>,
470 pub memory_service: Option<Arc<dyn Memory>>,
472 #[cfg(feature = "plugins")]
473 pub plugin_manager: Option<Arc<PluginManager>>,
475 #[allow(dead_code)]
478 pub run_config: Option<RunConfig>,
479 pub compaction_config: Option<adk_core::EventsCompactionConfig>,
483 pub context_cache_config: Option<ContextCacheConfig>,
491 pub cache_capable: Option<Arc<dyn CacheCapable>>,
494 pub request_context: Option<adk_core::RequestContext>,
498 pub cancellation_token: Option<CancellationToken>,
503 pub intra_compaction_config: Option<adk_core::IntraCompactionConfig>,
511 pub intra_compaction_summarizer: Option<Arc<dyn adk_core::BaseEventsSummarizer>>,
514 #[cfg(feature = "context-compaction")]
522 pub context_compaction: Option<crate::compaction::CompactionConfig>,
523 pub tool_policy: Option<Arc<dyn adk_core::ToolPolicy>>,
527 pub egress_policy: Option<adk_core::egress::EgressPolicy>,
531 pub governance: Option<adk_core::GovernanceControl>,
534 pub action_ledger: Option<Arc<dyn adk_core::ActionLedger>>,
538 pub approval_store: Option<Arc<dyn adk_core::ApprovalStore>>,
542 pub spend_ledger: Option<Arc<dyn adk_core::SpendLedger>>,
546 pub durable_runs: Option<Arc<dyn adk_core::DurableRunStore>>,
552 pub audit: Option<adk_core::audit_log::AuditTrail>,
557 pub identity_source: Option<Arc<dyn adk_core::IdentitySource>>,
565 pub subject_delegation: Option<Arc<dyn adk_core::SubjectDelegationPolicy>>,
568}
569
570pub struct Runner {
576 app_name: String,
577 root_agent: Arc<dyn Agent>,
578 session_service: Arc<dyn SessionService>,
579 #[cfg(feature = "artifacts")]
580 artifact_service: Option<Arc<dyn ArtifactService>>,
581 memory_service: Option<Arc<dyn Memory>>,
582 #[cfg(feature = "plugins")]
583 plugin_manager: Option<Arc<PluginManager>>,
584 #[cfg(feature = "skills")]
585 skill_injector: Option<Arc<SkillInjector>>,
586 run_config: RunConfig,
587 compaction_config: Option<adk_core::EventsCompactionConfig>,
588 context_cache_config: Option<ContextCacheConfig>,
589 cache_capable: Option<Arc<dyn CacheCapable>>,
590 cache_manager: Option<Arc<tokio::sync::Mutex<CacheManager>>>,
591 request_context: Option<adk_core::RequestContext>,
592 cancellation_token: Option<CancellationToken>,
593 intra_compaction: adk_core::IntraCompactionConfig,
595 intra_summarizer: Option<Arc<dyn adk_core::BaseEventsSummarizer>>,
597 background_compactions: Arc<crate::intra_compaction::BackgroundCompactions>,
600 #[cfg(feature = "context-compaction")]
602 context_compaction: Option<Arc<crate::compaction::CompactionConfig>>,
603 llm_spend_estimate: crate::spend::LlmSpendEstimate,
605 active_runs: ActiveRuns,
608 session_activity: crate::history::SessionActivity,
610 next_run_id: Arc<std::sync::atomic::AtomicU64>,
611 tool_policy: Option<Arc<dyn adk_core::ToolPolicy>>,
613 egress_policy: Option<adk_core::egress::EgressPolicy>,
614 governance: adk_core::GovernanceControl,
616 action_ledger: Option<Arc<dyn adk_core::ActionLedger>>,
618 approval_store: Option<Arc<dyn adk_core::ApprovalStore>>,
619 spend_ledger: Option<Arc<dyn adk_core::SpendLedger>>,
620 durable_runs: Option<Arc<dyn adk_core::DurableRunStore>>,
621 audit: Option<adk_core::audit_log::AuditTrail>,
623 identity_source: Option<Arc<dyn adk_core::IdentitySource>>,
624 subject_delegation: Option<Arc<dyn adk_core::SubjectDelegationPolicy>>,
625 pub(crate) external_session_locks: Arc<
628 std::sync::Mutex<
629 std::collections::HashMap<String, std::sync::Weak<tokio::sync::Mutex<()>>>,
630 >,
631 >,
632}
633
634impl Runner {
635 pub fn builder() -> crate::builder::RunnerConfigBuilder<
651 crate::builder::NoAppName,
652 crate::builder::NoAgent,
653 crate::builder::NoSessionService,
654 > {
655 crate::builder::RunnerConfigBuilder::new()
656 }
657
658 pub fn new(config: RunnerConfig) -> Result<Self> {
662 let run_config = config.run_config.unwrap_or_default();
663
664 let effective_cache_config = config
667 .context_cache_config
668 .or_else(|| config.cache_capable.as_ref().map(|_| ContextCacheConfig::default()));
669
670 let cache_manager = effective_cache_config
671 .as_ref()
672 .map(|c| Arc::new(tokio::sync::Mutex::new(CacheManager::new(c.clone()))));
673
674 let intra_compaction = config.intra_compaction_config.unwrap_or_default();
675 let intra_summarizer = config.intra_compaction_summarizer;
676
677 let governance = config.governance.unwrap_or_default();
678 if let Some(audit) = &config.audit {
679 governance.attach_audit(audit.clone());
680 }
681
682 Ok(Self {
683 app_name: config.app_name,
684 root_agent: config.agent,
685 session_service: config.session_service,
686 #[cfg(feature = "artifacts")]
687 artifact_service: config.artifact_service,
688 memory_service: config.memory_service,
689 #[cfg(feature = "plugins")]
690 plugin_manager: config.plugin_manager,
691 #[cfg(feature = "skills")]
692 skill_injector: None,
693 run_config,
694 compaction_config: config.compaction_config,
695 context_cache_config: effective_cache_config,
696 cache_capable: config.cache_capable,
697 cache_manager,
698 request_context: config.request_context,
699 cancellation_token: config.cancellation_token,
700 intra_compaction,
701 intra_summarizer,
702 background_compactions: Arc::default(),
703 #[cfg(feature = "context-compaction")]
704 context_compaction: config.context_compaction.map(Arc::new),
705 llm_spend_estimate: crate::spend::LlmSpendEstimate::default(),
706 active_runs: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
707 session_activity: crate::history::SessionActivity::new(),
708 next_run_id: Arc::new(std::sync::atomic::AtomicU64::new(1)),
709 tool_policy: config.tool_policy,
710 egress_policy: config.egress_policy,
711 governance,
712 action_ledger: config.action_ledger,
713 approval_store: config.approval_store,
714 spend_ledger: config.spend_ledger,
715 durable_runs: config.durable_runs,
716 audit: config.audit,
717 identity_source: config.identity_source,
718 subject_delegation: config.subject_delegation,
719 external_session_locks: Arc::new(std::sync::Mutex::new(
720 std::collections::HashMap::new(),
721 )),
722 })
723 }
724
725 pub(crate) fn root_agent(&self) -> Arc<dyn Agent> {
727 Arc::clone(&self.root_agent)
728 }
729
730 pub fn root_agent_name(&self) -> &str {
732 self.root_agent.name()
733 }
734
735 pub fn audit_trail(&self) -> Option<&adk_core::audit_log::AuditTrail> {
737 self.audit.as_ref().or(self.run_config.audit.as_ref())
738 }
739
740 pub async fn default_principal(&self, agent_name: &str) -> Result<adk_core::AgentPrincipal> {
750 if let Some(source) = &self.identity_source {
751 if let Some(principal) = source.principal_for(agent_name).await? {
752 return Ok(principal);
753 }
754 if agent_name == self.root_agent.name() {
755 return source.current().await;
756 }
757 }
758 Ok(adk_core::AgentPrincipal::derived(&self.app_name, agent_name))
759 }
760
761 fn acting_resolver(&self) -> crate::acting::ActingResolver {
762 crate::acting::ActingResolver {
763 app_name: self.app_name.clone(),
764 root: Arc::clone(&self.root_agent),
765 source: self.identity_source.clone(),
766 delegation: self.subject_delegation.clone(),
767 }
768 }
769
770 pub fn with_llm_spend_estimate(mut self, estimate: crate::LlmSpendEstimate) -> Self {
777 self.llm_spend_estimate = estimate;
778 self
779 }
780
781 #[cfg(feature = "skills")]
785 pub fn with_skill_injector(mut self, injector: SkillInjector) -> Self {
786 self.skill_injector = Some(Arc::new(injector));
787 self
788 }
789
790 #[cfg(feature = "skills")]
792 #[deprecated(note = "Use with_auto_skills_mut instead")]
793 pub fn with_auto_skills(
794 mut self,
795 root: impl AsRef<std::path::Path>,
796 config: SkillInjectorConfig,
797 ) -> adk_skill::SkillResult<Self> {
798 self.with_auto_skills_mut(root, config)?;
799 Ok(self)
800 }
801
802 #[cfg(feature = "skills")]
808 pub fn with_auto_skills_mut(
809 &mut self,
810 root: impl AsRef<std::path::Path>,
811 config: SkillInjectorConfig,
812 ) -> adk_skill::SkillResult<()> {
813 let injector = SkillInjector::from_root(root, config)?;
814 self.skill_injector = Some(Arc::new(injector));
815 Ok(())
816 }
817
818 pub async fn run(
823 &self,
824 user_id: UserId,
825 session_id: SessionId,
826 user_content: Content,
827 ) -> Result<EventStream> {
828 self.run_with_config(user_id, session_id, user_content, None).await
829 }
830
831 pub fn app_name(&self) -> &str {
833 &self.app_name
834 }
835
836 pub fn session_service(&self) -> &Arc<dyn adk_session::SessionService> {
838 &self.session_service
839 }
840
841 pub fn governance(&self) -> &adk_core::GovernanceControl {
854 &self.governance
855 }
856
857 pub fn tool_policy(&self) -> Option<&Arc<dyn adk_core::ToolPolicy>> {
872 self.tool_policy.as_ref()
873 }
874
875 pub async fn close(&self) {
893 self.root_agent.close().await;
894 #[cfg(feature = "plugins")]
895 if let Some(manager) = &self.plugin_manager {
896 manager.close().await;
897 }
898 }
899
900 pub async fn prewarm(&self, request: crate::Prewarm) -> Result<crate::PrewarmReport> {
927 self.governance.check()?;
928 self.run_config.check_governance()?;
929 let started = std::time::Instant::now();
930 let budget = request.budget_or_default();
931 let session_read = request.session.is_some();
932 let work = async {
933 if let Some((user_id, session_id)) = &request.session {
934 let identity = adk_core::AdkIdentity::new(
935 AppName::try_from(self.app_name.clone())?,
936 user_id.clone(),
937 session_id.clone(),
938 );
939 let session = self.session_service.get_for_identity(&identity).await?;
940 adk_session::ensure_writable(session.as_ref())?;
941 }
942 self.root_agent.prewarm().await
943 };
944 match tokio::time::timeout(budget, work).await {
945 Ok(result) => result?,
946 Err(_) => {
947 return Err(adk_core::AdkError::new(
948 adk_core::ErrorComponent::Agent,
949 adk_core::ErrorCategory::Timeout,
950 "runner.prewarm.timeout",
951 format!(
952 "prewarming did not finish within {budget:?}; the first turn readies \
953 what it did not, or give Prewarm::budget more time"
954 ),
955 ));
956 }
957 }
958 let elapsed = started.elapsed();
959 tracing::debug!(
960 prewarm.elapsed_ms = elapsed.as_millis() as u64,
961 session_read,
962 "runner prewarmed"
963 );
964 let warm_for = chrono::Duration::from_std(crate::prewarm::WARM_FOR).unwrap_or_default();
965 Ok(crate::PrewarmReport {
966 elapsed,
967 session_read,
968 warm_until: chrono::Utc::now() + warm_for,
969 })
970 }
971
972 pub fn run_config(&self) -> &RunConfig {
976 &self.run_config
977 }
978
979 pub async fn run_with_config(
990 &self,
991 user_id: UserId,
992 session_id: SessionId,
993 user_content: Content,
994 run_config: Option<RunConfig>,
995 ) -> Result<EventStream> {
996 Ok(self
997 .start_with_config(user_id, session_id, user_content, run_config)
998 .await?
999 .into_events())
1000 }
1001
1002 pub async fn start_with_config(
1013 &self,
1014 user_id: UserId,
1015 session_id: SessionId,
1016 user_content: Content,
1017 run_config: Option<RunConfig>,
1018 ) -> Result<RunnerInvocation> {
1019 let invocation_id = InvocationId::try_from(format!("inv-{}", uuid::Uuid::new_v4()))?;
1020 let stream_invocation_id = invocation_id.to_string();
1021 let app_name = self.app_name.clone();
1022 let typed_app_name = AppName::try_from(app_name.clone())?;
1023 let session_service = self.session_service.clone();
1024 let root_agent = self.root_agent.clone();
1025 #[cfg(feature = "artifacts")]
1026 let artifact_service = self.artifact_service.clone();
1027 let memory_service = self.memory_service.clone();
1028 #[cfg(feature = "plugins")]
1029 let plugin_manager = self.plugin_manager.clone();
1030 #[cfg(feature = "skills")]
1031 let skill_injector = self.skill_injector.clone();
1032 let mut run_config = run_config.unwrap_or_else(|| self.run_config.clone());
1033 if run_config.tool_policy.is_none() {
1036 run_config.tool_policy = self.tool_policy.clone();
1037 }
1038 if let Some(ceiling) = &self.egress_policy {
1040 run_config.egress_policy = Some(match run_config.egress_policy.take() {
1041 Some(own) => ceiling.narrow(&own),
1042 None => ceiling.clone(),
1043 });
1044 }
1045 if run_config.action_ledger.is_none() {
1046 run_config.action_ledger = self.action_ledger.clone();
1047 }
1048 if run_config.approval_store.is_none() {
1049 run_config.approval_store = self.approval_store.clone();
1050 }
1051 if run_config.spend_ledger.is_none() {
1052 run_config.spend_ledger = self.spend_ledger.clone();
1053 }
1054 if run_config.audit.is_none() {
1055 run_config.audit = self.audit.clone();
1056 }
1057 if !run_config.governance.iter().any(|control| control.same_as(&self.governance)) {
1058 run_config.governance.push(self.governance.clone());
1059 }
1060 if run_config.budget_tracker.is_none()
1063 && let Some(budget) = run_config.budget.clone()
1064 {
1065 run_config.budget_tracker = Some(Arc::new(adk_core::BudgetTracker::new(budget)));
1066 }
1067 let budget_tracker = run_config.budget_tracker.clone();
1068 #[cfg(feature = "plugins")]
1071 if let Some(manager) = plugin_manager.as_ref() {
1072 let hooks: Arc<dyn adk_core::InvocationHooks> = manager.clone();
1073 if !run_config.invocation_hooks.iter().any(|existing| Arc::ptr_eq(existing, &hooks)) {
1074 run_config.invocation_hooks.insert(0, hooks);
1075 }
1076 }
1077 run_config.llm_spend_estimate.get_or_insert(self.llm_spend_estimate);
1079 let acting_resolver = self.acting_resolver();
1080 let compaction_config = self.compaction_config.clone();
1081 let context_cache_config = self.context_cache_config.clone();
1082 let cache_capable = self.cache_capable.clone();
1083 let cache_manager_ref = self.cache_manager.clone();
1084 let request_context = match run_config.request_context.clone() {
1087 Some(context) if context.user_id != user_id.as_str() => {
1088 return Err(adk_core::AdkError::new(
1089 adk_core::ErrorComponent::Auth,
1090 adk_core::ErrorCategory::Forbidden,
1091 adk_core::SUBJECT_MISMATCH_CODE,
1092 format!(
1093 "the run's request context authenticates user '{}' but the run is for \
1094 user '{}'; a run's request context must name the run's own user",
1095 context.user_id,
1096 user_id.as_str()
1097 ),
1098 ));
1099 }
1100 Some(context) => Some(context),
1101 None => self.request_context.clone(),
1102 };
1103 let telemetry_user_id = match &run_config.consent_gate {
1106 Some(gate) => {
1107 let subject =
1108 adk_core::SubjectRef::new(run_config.acting.subject_kind, user_id.as_str());
1109 gate.ensure_writable(&subject).await?;
1110 gate.permits(&subject, &adk_core::subject::ConsentPurpose::Analytics)
1111 .await?
1112 .then(|| user_id.as_str().to_owned())
1113 }
1114 None => Some(user_id.as_str().to_owned()),
1115 };
1116 let mut intra_compactor = if run_config.history_compactor.is_some() {
1119 None
1120 } else {
1121 self.intra_compactor(run_config.intra_compaction.as_ref())
1122 };
1123 let background_compactions = self.background_compactions.clone();
1124
1125 let identity =
1128 adk_core::AdkIdentity::new(typed_app_name.clone(), user_id.clone(), session_id.clone());
1129
1130 let session_token = match self.cancellation_token.as_ref() {
1139 Some(global) => global.child_token(),
1140 None => CancellationToken::new(),
1141 };
1142 let run_id = self.next_run_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1143 let steering_inbox = adk_core::SteeringInbox::new();
1144 let run_scope = RunScope::default();
1145 {
1146 let mut runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
1147 runs.insert(
1148 run_id,
1149 ActiveRun {
1150 identity: identity.clone(),
1151 token: session_token.clone(),
1152 inbox: steering_inbox.clone(),
1153 #[cfg(feature = "plugins")]
1154 scope: run_scope.clone(),
1155 },
1156 );
1157 }
1158 let active_runs = self.active_runs.clone();
1159 let effective_token = Some(session_token);
1160
1161 let cleanup = ActiveRunCleanup {
1166 active_runs: active_runs.clone(),
1167 run_id,
1168 inbox: steering_inbox.clone(),
1169 _activity: self.session_activity.enter(identity.clone()),
1170 };
1171 let stop_invocation_id = invocation_id.to_string();
1172 let stop_default_author = self.root_agent.name().to_string();
1173 let mut finish = RunFinish {
1174 scope: run_scope.clone(),
1175 #[cfg(feature = "plugins")]
1176 plugins: self.plugin_manager.clone(),
1177 session_service: self.session_service.clone(),
1178 identity: identity.clone(),
1179 in_flight: InFlightCalls::default(),
1180 finished: false,
1181 };
1182
1183 let s = stream! {
1184 if let Err(error) = run_config.check_governance() {
1186 yield Err(error);
1187 return;
1188 }
1189
1190 if let Err(error) = acting_resolver
1194 .resolve(&mut run_config, user_id.as_ref(), session_id.as_ref(), &stream_invocation_id)
1195 .await
1196 {
1197 tracing::warn!(error = %error, "run identity refused; the run does not start");
1198 yield Err(error);
1199 return;
1200 }
1201
1202 let cancellation_token = effective_token;
1204 let session = match session_service
1206 .get(adk_session::GetRequest {
1207 app_name: app_name.clone(),
1208 user_id: user_id.to_string(),
1209 session_id: session_id.to_string(),
1210 num_recent_events: run_config.history_max_events,
1211 after: None,
1212 })
1213 .await
1214 {
1215 Ok(s) => s,
1216 Err(e) => {
1217 yield Err(e);
1218 return;
1219 }
1220 };
1221 if let Err(error) = adk_session::ensure_writable(session.as_ref()) {
1223 yield Err(error);
1224 return;
1225 }
1226
1227 let unscreened = match screen_unscreened_messages(
1230 &root_agent,
1231 session.as_ref(),
1232 !user_content.carries_user_input(),
1233 )
1234 .await
1235 {
1236 Ok(replacements) => replacements,
1237 Err(error) => {
1238 yield Err(error);
1239 return;
1240 }
1241 };
1242
1243 let agent_to_run = Self::find_agent_to_run(&root_agent, session.as_ref());
1245
1246 if agent_to_run.name() != root_agent.name() {
1249 let (parent_name, peer_names) =
1250 Self::compute_transfer_context(&root_agent, agent_to_run.name());
1251 let mut targets = Vec::new();
1252 if let Some(ref parent) = parent_name {
1253 targets.push(parent.clone());
1254 }
1255 targets.extend(peer_names);
1256 run_config.transfer_targets = targets;
1257 run_config.parent_agent = parent_name;
1258 }
1259
1260 root_agent.configure_run(agent_to_run.name(), &mut run_config);
1263 if let Some(targets) = root_agent.transfer_targets_for(agent_to_run.name()) {
1264 run_config.transfer_targets = targets;
1265 run_config.parent_agent = None;
1266 }
1267 run_config.transfer_target_descriptions =
1268 Self::describe_agents(&root_agent, &run_config.transfer_targets);
1269
1270 #[cfg(feature = "artifacts")]
1272 let artifact_service_clone = artifact_service.clone();
1273 let memory_service_clone = memory_service.clone();
1274
1275 let invocation_id = stream_invocation_id;
1277 #[cfg(any(feature = "skills", feature = "plugins"))]
1278 let mut effective_user_content = user_content.clone();
1279 #[cfg(not(any(feature = "skills", feature = "plugins")))]
1280 let effective_user_content = user_content.clone();
1281 #[cfg(feature = "skills")]
1282 let mut selected_skill_name = String::new();
1283 #[cfg(not(feature = "skills"))]
1284 let selected_skill_name = String::new();
1285 #[cfg(feature = "skills")]
1286 let mut selected_skill_id = String::new();
1287 #[cfg(not(feature = "skills"))]
1288 let selected_skill_id = String::new();
1289
1290 #[cfg(feature = "skills")]
1291 if let Some(injector) = skill_injector.as_ref()
1292 && let Some(matched) = adk_skill::apply_skill_injection(
1293 &mut effective_user_content,
1294 injector.index(),
1295 injector.policy(),
1296 injector.max_injected_chars(),
1297 ) {
1298 selected_skill_name = matched.skill.name;
1299 selected_skill_id = matched.skill.id;
1300 }
1301
1302 let mut invocation_ctx = match InvocationContext::new_typed(
1303 invocation_id.clone(),
1304 agent_to_run.clone(),
1305 user_id.clone(),
1306 typed_app_name.clone(),
1307 session_id.clone(),
1308 effective_user_content.clone(),
1309 Arc::from(session),
1310 ) {
1311 Ok(ctx) => ctx,
1312 Err(e) => {
1313 yield Err(e);
1314 return;
1315 }
1316 };
1317 if !unscreened.is_empty() {
1318 let mut events = invocation_ctx.mutable_session().events_snapshot();
1319 for (index, content) in unscreened {
1320 if let Some(event) = events.get_mut(index) {
1321 event.llm_response.content = content;
1322 }
1323 }
1324 invocation_ctx.mutable_session().replace_events(events);
1325 }
1326
1327 #[cfg(feature = "artifacts")]
1329 if let Some(service) = artifact_service {
1330 let scoped = adk_artifact::ScopedArtifacts::new(
1332 service,
1333 app_name.clone(),
1334 user_id.to_string(),
1335 session_id.to_string(),
1336 );
1337 invocation_ctx = invocation_ctx.with_artifacts(Arc::new(scoped));
1338 }
1339 if let Some(memory) = memory_service {
1340 invocation_ctx = invocation_ctx.with_memory(memory);
1341 }
1342
1343 if let Some(compactor) = intra_compactor.take() {
1346 let background =
1347 compactor.config().background.then(|| background_compactions.clone());
1348 run_config.history_compactor = Some(Arc::new(
1349 crate::intra_compaction::RunCompactor::new(
1350 compactor,
1351 invocation_ctx.mutable_session().clone(),
1352 )
1353 .with_background(background),
1354 ));
1355 }
1356
1357 invocation_ctx = invocation_ctx
1359 .with_run_config(run_config.clone())
1360 .with_steering_inbox(steering_inbox.clone());
1361
1362 if let Some(rc) = request_context.clone() {
1364 invocation_ctx = invocation_ctx.with_request_context(rc);
1365 }
1366
1367 if let Some(token) = cancellation_token.as_ref() {
1369 invocation_ctx = invocation_ctx.with_cancellation_token(token.clone());
1370 }
1371
1372 let mut ctx = Arc::new(invocation_ctx);
1373 run_scope.set(&ctx);
1375
1376 #[cfg(feature = "plugins")]
1377 if let Some(manager) = plugin_manager.as_ref() {
1378 match manager
1379 .run_before_run(ctx.clone() as Arc<dyn adk_core::InvocationContext>)
1380 .await
1381 {
1382 Ok(Some(content)) => {
1383 let mut early_event = adk_core::Event::new(ctx.invocation_id());
1384 early_event.author = agent_to_run.name().to_string();
1385 early_event.llm_response.content = Some(content);
1386 match manager
1387 .run_on_event(
1388 ctx.clone() as Arc<dyn adk_core::InvocationContext>,
1389 early_event.clone(),
1390 )
1391 .await
1392 {
1393 Ok(Some(modified)) => early_event = modified,
1394 Ok(None) => {}
1395 Err(e) => {
1396 yield Err(e);
1397 return;
1398 }
1399 }
1400
1401 ctx.mutable_session().append_event(early_event.clone());
1402 if let Err(e) = session_service
1403 .append_event_for_identity(adk_session::AppendEventRequest {
1404 identity: identity.clone(),
1405 event: early_event.clone(),
1406 })
1407 .await {
1408 yield Err(e);
1409 return;
1410 }
1411
1412 yield Ok(early_event);
1413 return;
1414 }
1415 Ok(None) => {}
1416 Err(e) => {
1417 yield Err(e);
1418 return;
1419 }
1420 }
1421
1422 match manager
1423 .run_on_user_message(
1424 ctx.clone() as Arc<dyn adk_core::InvocationContext>,
1425 effective_user_content.clone(),
1426 )
1427 .await
1428 {
1429 Ok(Some(modified)) => {
1430 effective_user_content = modified;
1431
1432 let mut refreshed_ctx = match InvocationContext::with_mutable_session(
1433 ctx.invocation_id().to_string(),
1434 agent_to_run.clone(),
1435 ctx.user_id().to_string(),
1436 ctx.app_name().to_string(),
1437 ctx.session_id().to_string(),
1438 effective_user_content.clone(),
1439 ctx.mutable_session().clone(),
1440 ) {
1441 Ok(ctx) => ctx,
1442 Err(e) => {
1443 yield Err(e);
1444 return;
1445 }
1446 };
1447 refreshed_ctx = refreshed_ctx.with_orchestration_root_invocation_id(
1448 adk_core::InvocationContext::orchestration_root_invocation_id(
1449 ctx.as_ref(),
1450 )
1451 .to_string(),
1452 );
1453
1454 #[cfg(feature = "artifacts")]
1455 if let Some(service) = artifact_service_clone.clone() {
1456 let scoped = adk_artifact::ScopedArtifacts::new(
1457 service,
1458 ctx.app_name().to_string(),
1459 ctx.user_id().to_string(),
1460 ctx.session_id().to_string(),
1461 );
1462 refreshed_ctx = refreshed_ctx.with_artifacts(Arc::new(scoped));
1463 }
1464 if let Some(memory) = memory_service_clone.clone() {
1465 refreshed_ctx = refreshed_ctx.with_memory(memory);
1466 }
1467 refreshed_ctx = refreshed_ctx
1468 .with_run_config(run_config.clone())
1469 .with_steering_inbox(steering_inbox.clone());
1470 if let Some(rc) = request_context.clone() {
1471 refreshed_ctx = refreshed_ctx.with_request_context(rc);
1472 }
1473 if let Some(token) = cancellation_token.as_ref() {
1474 refreshed_ctx = refreshed_ctx.with_cancellation_token(token.clone());
1475 }
1476 ctx = Arc::new(refreshed_ctx);
1477 run_scope.set(&ctx);
1478 }
1479 Ok(None) => {}
1480 Err(e) => {
1481 yield Err(e);
1482 return;
1483 }
1484 }
1485 }
1486
1487 let screened = if effective_user_content.carries_user_input() {
1491 match root_agent.screen_user_input(&effective_user_content).await {
1492 Ok(screened) => screened,
1493 Err(error) => {
1494 yield Err(error);
1495 return;
1496 }
1497 }
1498 } else {
1499 None
1500 };
1501 let input_screened = screened.is_some();
1502 let effective_user_content = match screened {
1503 Some(screened)
1504 if screened.role != effective_user_content.role
1505 || screened.parts != effective_user_content.parts =>
1506 {
1507 ctx = Arc::new(ctx.with_user_content(screened.clone()));
1508 run_scope.set(&ctx);
1509 screened
1510 }
1511 Some(_) | None => effective_user_content,
1512 };
1513
1514 let mut user_event = adk_core::Event::new(ctx.invocation_id());
1516 user_event.author = "user".to_string();
1517 user_event.llm_response.content = Some(effective_user_content.clone());
1518 user_event.actions.input_screened = input_screened;
1519
1520 ctx.mutable_session().append_event(user_event.clone());
1523
1524 if let Err(e) = session_service
1525 .append_event_for_identity(adk_session::AppendEventRequest {
1526 identity: identity.clone(),
1527 event: user_event,
1528 })
1529 .await {
1530 yield Err(e);
1531 return;
1532 }
1533
1534 if let (Some(cm_mutex), Some(cache_model)) = (&cache_manager_ref, &cache_capable) {
1539 let should_refresh_cache = {
1540 let cm = cm_mutex.lock().await;
1541 cm.is_enabled() && (cm.active_cache_name().is_none() || cm.needs_refresh())
1542 };
1543
1544 if should_refresh_cache {
1545 let system_instruction = agent_to_run.description().to_string();
1549 let tools = adk_core::ToolDeclarations::new();
1550 let ttl = context_cache_config.as_ref().map_or(600, |c| c.ttl_seconds);
1551
1552 match cache_model.create_cache(&system_instruction, &tools, ttl).await {
1553 Ok(name) => {
1554 let old_cache = {
1555 let mut cm = cm_mutex.lock().await;
1556 let old = cm.clear_active_cache();
1557 cm.set_active_cache(name);
1558 old
1559 };
1560
1561 if let Some(old) = old_cache
1562 && let Err(e) = cache_model.delete_cache(&old).await {
1563 tracing::warn!(
1564 old_cache = %old,
1565 error = %e,
1566 "failed to delete old cache, proceeding with new cache"
1567 );
1568 }
1569 }
1570 Err(e) => {
1571 tracing::warn!(
1573 error = %e.diagnostics(),
1574 "cache creation failed, proceeding without cache"
1575 );
1576 }
1577 }
1578 }
1579
1580 let cache_name = {
1582 let mut cm = cm_mutex.lock().await;
1583 if cm.is_enabled() {
1584 cm.record_invocation().map(str::to_string)
1585 } else {
1586 None
1587 }
1588 };
1589
1590 if let Some(cache_name) = cache_name {
1591 run_config.cached_content = Some(cache_name);
1592 let mut refreshed_ctx = match InvocationContext::with_mutable_session(
1594 ctx.invocation_id().to_string(),
1595 agent_to_run.clone(),
1596 ctx.user_id().to_string(),
1597 ctx.app_name().to_string(),
1598 ctx.session_id().to_string(),
1599 effective_user_content.clone(),
1600 ctx.mutable_session().clone(),
1601 ) {
1602 Ok(ctx) => ctx,
1603 Err(e) => {
1604 yield Err(e);
1605 return;
1606 }
1607 };
1608 refreshed_ctx = refreshed_ctx.with_orchestration_root_invocation_id(
1609 adk_core::InvocationContext::orchestration_root_invocation_id(ctx.as_ref())
1610 .to_string(),
1611 );
1612 #[cfg(feature = "artifacts")]
1613 if let Some(service) = artifact_service_clone.clone() {
1614 let scoped = adk_artifact::ScopedArtifacts::new(
1615 service,
1616 ctx.app_name().to_string(),
1617 ctx.user_id().to_string(),
1618 ctx.session_id().to_string(),
1619 );
1620 refreshed_ctx = refreshed_ctx.with_artifacts(Arc::new(scoped));
1621 }
1622 if let Some(memory) = memory_service_clone.clone() {
1623 refreshed_ctx = refreshed_ctx.with_memory(memory);
1624 }
1625 refreshed_ctx = refreshed_ctx
1626 .with_run_config(run_config.clone())
1627 .with_steering_inbox(steering_inbox.clone());
1628 if let Some(rc) = request_context.clone() {
1629 refreshed_ctx = refreshed_ctx.with_request_context(rc);
1630 }
1631 if let Some(token) = cancellation_token.as_ref() {
1632 refreshed_ctx = refreshed_ctx.with_cancellation_token(token.clone());
1633 }
1634 ctx = Arc::new(refreshed_ctx);
1635 run_scope.set(&ctx);
1636 }
1637 }
1638
1639 let agent_span = tracing::info_span!(
1643 "agent.execute",
1644 otel.name = %format!("invoke_agent {}", agent_to_run.name()),
1645 otel.kind = "internal",
1646 "gen_ai.operation.name" = "invoke_agent",
1647 "gen_ai.agent.name" = %agent_to_run.name(),
1648 "gen_ai.agent.description" = tracing::field::Empty,
1649 "gcp.vertex.agent.invocation_id" = ctx.invocation_id(),
1650 "gcp.vertex.agent.session_id" = ctx.session_id(),
1651 "gcp.vertex.agent.event_id" = ctx.invocation_id(), "gen_ai.conversation.id" = ctx.session_id(),
1653 "adk.app_name" = ctx.app_name(),
1654 "adk.user_id" = tracing::field::Empty,
1655 "agent.name" = %agent_to_run.name(),
1656 "adk.skills.selected_name" = %selected_skill_name,
1657 "adk.skills.selected_id" = %selected_skill_id
1658 );
1659
1660 if let Some(user) = &telemetry_user_id {
1661 agent_span.record("adk.user_id", user.as_str());
1662 }
1663 if !agent_to_run.description().is_empty() {
1664 agent_span.record("gen_ai.agent.description", agent_to_run.description());
1665 }
1666
1667 let mut agent_stream = match agent_to_run.run(ctx.clone()).instrument(agent_span.clone()).await {
1668 Ok(s) => s,
1669 Err(e) => {
1670 yield Err(e);
1671 return;
1672 }
1673 };
1674
1675 use futures::StreamExt;
1677 let mut transfer_target: Option<(String, String)> = None;
1678 let mut streamed_content = HashMap::new();
1679 let mut in_flight = InFlightCalls::default();
1680 let mut cancelled = false;
1681
1682 while let Some(result) = {
1683 match cancellation_token.as_ref() {
1688 Some(token) => {
1689 tokio::select! {
1690 biased;
1691 _ = token.cancelled() => {
1692 tracing::info!("cancellation fired during agent stream await");
1693 cancelled = true;
1694 None
1695 }
1696 result = agent_stream.next().instrument(agent_span.clone()) => result,
1702 }
1703 }
1704 None => agent_stream.next().instrument(agent_span.clone()).await,
1705 }
1706 } {
1707 match result {
1708 Ok(mut event) => {
1709 let steer_id =
1712 event.actions.steering.as_ref().map(|marker| marker.steer_id.clone());
1713 #[cfg(feature = "plugins")]
1714 if let Some(manager) = plugin_manager.as_ref() {
1715 match manager
1716 .run_on_event(
1717 ctx.clone() as Arc<dyn adk_core::InvocationContext>,
1718 event.clone(),
1719 )
1720 .await
1721 {
1722 Ok(Some(modified)) => {
1723 event = modified;
1724 }
1725 Ok(None) => {}
1726 Err(e) => {
1727 yield Err(e);
1728 return;
1729 }
1730 }
1731 }
1732
1733 preserve_streamed_content(&mut streamed_content, &mut event);
1734 let budget_check = budget_tracker
1737 .as_ref()
1738 .map_or(Ok(()), |tracker| tracker.record_event(&mut event));
1739 in_flight.observe(&event);
1740
1741 if let Some(target) = &event.actions.transfer_to_agent {
1743 let source = Self::transfer_source(&root_agent, &event.author, agent_to_run.name());
1744 if let Some(allowed) = Self::allowed_transfer_targets(&root_agent, source)
1745 && !allowed.contains(target)
1746 {
1747 if root_agent.strict_transfer_policy() {
1748 yield Err(adk_core::AdkError::new(
1749 adk_core::ErrorComponent::Agent,
1750 adk_core::ErrorCategory::Forbidden,
1751 "agent.transfer.target_forbidden",
1752 format!(
1753 "agent '{source}' cannot hand off to '{target}'; allowed targets: {}",
1754 allowed.join(", ")
1755 ),
1756 ));
1757 return;
1758 }
1759 tracing::warn!(source, target, allowed = ?allowed, "transfer refused: the agent may not hand off to this target");
1760 } else {
1761 transfer_target = Some((source.to_string(), target.clone()));
1762 }
1763 }
1764
1765 if !event.actions.state_delta.is_empty() {
1771 ctx.mutable_session().apply_state_delta(&event.actions.state_delta);
1772 }
1773
1774 ctx.mutable_session().append_event(event.clone());
1776
1777 if !event.llm_response.partial
1784 && let Err(e) = session_service
1785 .append_event_for_identity(adk_session::AppendEventRequest {
1786 identity: identity.clone(),
1787 event: event.clone(),
1788 })
1789 .await {
1790 yield Err(e);
1791 return;
1792 }
1793 if let Some(steer_id) = &steer_id
1794 && !event.llm_response.partial
1795 {
1796 steering_inbox.delivered(steer_id, &event.id);
1797 }
1798 yield Ok(event);
1799 if let Err(exceeded) = budget_check {
1800 yield Err(exceeded.into());
1801 return;
1802 }
1803 }
1804 Err(e) => {
1805 yield Err(e);
1806 return;
1807 }
1808 }
1809 }
1810
1811 const DEFAULT_MAX_TRANSFER_DEPTH: u32 = 10;
1818 let max_depth = run_config.max_transfer_depth.unwrap_or(DEFAULT_MAX_TRANSFER_DEPTH);
1819 let mut transfer_depth: u32 = 0;
1820 let mut current_transfer_target = transfer_target;
1821
1822 while !cancelled
1823 && let Some((transfer_source, target_name)) = current_transfer_target.take()
1824 {
1825 transfer_depth += 1;
1826 if transfer_depth > max_depth {
1827 tracing::warn!(
1828 depth = transfer_depth,
1829 target = %target_name,
1830 "max transfer depth exceeded, stopping transfer chain"
1831 );
1832 if root_agent.strict_transfer_policy() {
1833 yield Err(adk_core::AdkError::new(
1834 adk_core::ErrorComponent::Agent,
1835 adk_core::ErrorCategory::InvalidInput,
1836 "agent.transfer.depth_exceeded",
1837 format!(
1838 "maximum handoff depth {max_depth} exceeded while transferring to '{target_name}'"
1839 ),
1840 ));
1841 return;
1842 }
1843 break;
1844 }
1845
1846 let governance = adk_core::AgentTransferRequest {
1847 invocation_id: invocation_id.clone(),
1848 from: transfer_source.clone(),
1849 to: target_name.clone(),
1850 depth: transfer_depth,
1851 };
1852 match root_agent.govern_transfer(&governance).await {
1853 Ok(adk_core::AgentTransferDecision::Allow) => {}
1854 Ok(adk_core::AgentTransferDecision::Deny { reason }) => {
1855 yield Err(adk_core::AdkError::new(
1856 adk_core::ErrorComponent::Agent,
1857 adk_core::ErrorCategory::Forbidden,
1858 "agent.transfer.denied",
1859 format!(
1860 "handoff from '{transfer_source}' to '{target_name}' was denied: {reason}"
1861 ),
1862 ));
1863 return;
1864 }
1865 Err(error) => {
1866 yield Err(error);
1867 return;
1868 }
1869 }
1870
1871 let target_agent = match Self::find_agent(&root_agent, &target_name) {
1872 Some(a) => a,
1873 None => {
1874 tracing::warn!(target = %target_name, "transfer target not found in agent tree");
1875 if root_agent.strict_transfer_policy() {
1876 yield Err(adk_core::AdkError::new(
1877 adk_core::ErrorComponent::Agent,
1878 adk_core::ErrorCategory::NotFound,
1879 "agent.transfer.target_not_found",
1880 format!(
1881 "handoff target '{target_name}' was not found in the agent tree"
1882 ),
1883 ));
1884 return;
1885 }
1886 break;
1887 }
1888 };
1889
1890 let mut transfer_run_config = run_config.clone();
1895 if let Some(targets) = root_agent.transfer_targets_for(&target_name) {
1896 transfer_run_config.transfer_targets = targets;
1897 transfer_run_config.parent_agent = None;
1898 } else {
1899 let (parent_name, peer_names) =
1900 Self::compute_transfer_context(&root_agent, &target_name);
1901 let mut targets = Vec::new();
1902 if let Some(ref parent) = parent_name {
1903 targets.push(parent.clone());
1904 }
1905 targets.extend(peer_names);
1906 transfer_run_config.transfer_targets = targets;
1907 transfer_run_config.parent_agent = parent_name;
1908 }
1909 root_agent.configure_run(&target_name, &mut transfer_run_config);
1910 transfer_run_config.transfer_target_descriptions =
1911 Self::describe_agents(&root_agent, &transfer_run_config.transfer_targets);
1912
1913 let transfer_invocation_id = format!("inv-{}", uuid::Uuid::new_v4());
1915 let mut transfer_ctx = match InvocationContext::with_mutable_session(
1916 transfer_invocation_id.clone(),
1917 target_agent.clone(),
1918 ctx.user_id().to_string(),
1919 ctx.app_name().to_string(),
1920 ctx.session_id().to_string(),
1921 effective_user_content.clone(),
1922 ctx.mutable_session().clone(),
1923 ) {
1924 Ok(ctx) => ctx,
1925 Err(e) => {
1926 yield Err(e);
1927 return;
1928 }
1929 };
1930 transfer_ctx = transfer_ctx.with_orchestration_root_invocation_id(
1931 adk_core::InvocationContext::orchestration_root_invocation_id(ctx.as_ref())
1932 .to_string(),
1933 );
1934
1935 #[cfg(feature = "artifacts")]
1936 if let Some(ref service) = artifact_service_clone {
1937 let scoped = adk_artifact::ScopedArtifacts::new(
1938 service.clone(),
1939 ctx.app_name().to_string(),
1940 ctx.user_id().to_string(),
1941 ctx.session_id().to_string(),
1942 );
1943 transfer_ctx = transfer_ctx.with_artifacts(Arc::new(scoped));
1944 }
1945 if let Some(ref memory) = memory_service_clone {
1946 transfer_ctx = transfer_ctx.with_memory(memory.clone());
1947 }
1948 transfer_ctx = transfer_ctx
1949 .with_run_config(transfer_run_config)
1950 .with_steering_inbox(steering_inbox.clone());
1951 if let Some(rc) = request_context.clone() {
1952 transfer_ctx = transfer_ctx.with_request_context(rc);
1953 }
1954 if let Some(token) = cancellation_token.as_ref() {
1955 transfer_ctx = transfer_ctx.with_cancellation_token(token.clone());
1956 }
1957 if let Some(shared_state) = adk_core::CallbackContext::shared_state(ctx.as_ref()) {
1958 transfer_ctx = transfer_ctx.with_shared_state(shared_state);
1959 }
1960
1961 let transfer_ctx = Arc::new(transfer_ctx);
1962
1963 let mut transfer_stream = match target_agent.run(transfer_ctx.clone()).await {
1965 Ok(s) => s,
1966 Err(e) => {
1967 yield Err(e);
1968 return;
1969 }
1970 };
1971
1972 while let Some(result) = {
1974 match cancellation_token.as_ref() {
1977 Some(token) => {
1978 tokio::select! {
1979 biased;
1980 _ = token.cancelled() => {
1981 tracing::info!("cancellation fired during transferred agent stream await");
1982 cancelled = true;
1983 None
1984 }
1985 result = transfer_stream.next() => result,
1986 }
1987 }
1988 None => transfer_stream.next().await,
1989 }
1990 } {
1991 match result {
1992 Ok(mut event) => {
1993 let steer_id = event
1994 .actions
1995 .steering
1996 .as_ref()
1997 .map(|marker| marker.steer_id.clone());
1998 #[cfg(feature = "plugins")]
1999 if let Some(manager) = plugin_manager.as_ref() {
2000 match manager
2001 .run_on_event(
2002 transfer_ctx.clone() as Arc<dyn adk_core::InvocationContext>,
2003 event.clone(),
2004 )
2005 .await
2006 {
2007 Ok(Some(modified)) => {
2008 event = modified;
2009 }
2010 Ok(None) => {}
2011 Err(e) => {
2012 yield Err(e);
2013 return;
2014 }
2015 }
2016 }
2017
2018 preserve_streamed_content(&mut streamed_content, &mut event);
2019 let budget_check = budget_tracker
2020 .as_ref()
2021 .map_or(Ok(()), |tracker| tracker.record_event(&mut event));
2022 in_flight.observe(&event);
2023
2024 if let Some(target) = &event.actions.transfer_to_agent {
2026 let source = Self::transfer_source(&root_agent, &event.author, target_agent.name());
2027 if let Some(allowed) = Self::allowed_transfer_targets(&root_agent, source)
2028 && !allowed.contains(target)
2029 {
2030 if root_agent.strict_transfer_policy() {
2031 yield Err(adk_core::AdkError::new(
2032 adk_core::ErrorComponent::Agent,
2033 adk_core::ErrorCategory::Forbidden,
2034 "agent.transfer.target_forbidden",
2035 format!(
2036 "agent '{source}' cannot hand off to '{target}'; allowed targets: {}",
2037 allowed.join(", ")
2038 ),
2039 ));
2040 return;
2041 }
2042 tracing::warn!(source, target, allowed = ?allowed, "transfer refused: the agent may not hand off to this target");
2043 } else {
2044 current_transfer_target =
2045 Some((source.to_string(), target.clone()));
2046 }
2047 }
2048
2049 if !event.actions.state_delta.is_empty() {
2051 transfer_ctx.mutable_session().apply_state_delta(&event.actions.state_delta);
2052 }
2053
2054 transfer_ctx.mutable_session().append_event(event.clone());
2056
2057 if !event.llm_response.partial
2058 && let Err(e) = session_service
2059 .append_event_for_identity(adk_session::AppendEventRequest {
2060 identity: identity.clone(),
2061 event: event.clone(),
2062 })
2063 .await {
2064 yield Err(e);
2065 return;
2066 }
2067 if let Some(steer_id) = &steer_id
2068 && !event.llm_response.partial
2069 {
2070 steering_inbox.delivered(steer_id, &event.id);
2071 }
2072 yield Ok(event);
2073 if let Err(exceeded) = budget_check {
2074 yield Err(exceeded.into());
2075 return;
2076 }
2077 }
2078 Err(e) => {
2079 yield Err(e);
2080 return;
2081 }
2082 }
2083 }
2084 }
2085
2086 if cancelled {
2087 drop(agent_stream);
2089 if let Some(trail) = &run_config.audit {
2090 let _ = in_flight
2092 .audit_calls(
2093 trail,
2094 &run_config,
2095 &identity,
2096 "cancelled",
2097 |_| adk_core::audit_log::AuditRecordOutcome::OutcomeUnknown,
2098 )
2099 .await;
2100 }
2101 for event in in_flight.answer_interrupted() {
2102 #[cfg(feature = "plugins")]
2103 let event = match plugin_manager.as_ref() {
2104 Some(manager) => match manager
2105 .run_on_event(ctx.clone() as Arc<dyn adk_core::InvocationContext>, event.clone())
2106 .await
2107 {
2108 Ok(modified) => modified.unwrap_or(event),
2109 Err(error) => {
2110 tracing::warn!(error = %error, "on_event failed for an interrupted call's answer; keeping the answer");
2111 event
2112 }
2113 },
2114 None => event,
2115 };
2116 ctx.mutable_session().append_event(event.clone());
2117 if let Err(error) = session_service
2118 .append_event_for_identity(adk_session::AppendEventRequest {
2119 identity: identity.clone(),
2120 event: event.clone(),
2121 })
2122 .await
2123 {
2124 tracing::error!(error = %error, "failed to persist the outcome of an interrupted tool call");
2125 }
2126 yield Ok(event);
2127 }
2128 return;
2129 }
2130
2131 if let Some(ref compaction_cfg) = compaction_config {
2135 let event_count = ctx.mutable_session().as_ref().events_len();
2136
2137 if event_count > 0 {
2138 let all_events = ctx.mutable_session().as_ref().events_snapshot();
2139 let starts_invocation =
2141 |e: &Event| e.author == "user" && e.actions.steering.is_none();
2142 let invocation_count =
2143 all_events.iter().filter(|e| starts_invocation(e)).count() as u32;
2144
2145 if invocation_count > 0
2146 && invocation_count.is_multiple_of(compaction_cfg.compaction_interval)
2147 {
2148 let overlap = compaction_cfg.overlap_size as usize;
2151
2152 let user_msg_indices: Vec<usize> = all_events.iter()
2154 .enumerate()
2155 .filter(|(_, e)| starts_invocation(e))
2156 .map(|(i, _)| i)
2157 .collect();
2158
2159 let compact_up_to = if overlap == 0 {
2162 all_events.len()
2163 } else if user_msg_indices.len() > overlap {
2164 user_msg_indices[user_msg_indices.len() - overlap]
2166 } else {
2167 0
2169 };
2170 let compact_up_to = adk_core::history::balanced_cut(
2173 &all_events,
2174 adk_core::held_call_compaction_limit(&all_events, compact_up_to),
2175 );
2176
2177 if compact_up_to > 0 {
2178 let events_to_compact = &all_events[..compact_up_to];
2179
2180 let scope = adk_core::ModelCallScope::for_run(
2181 adk_core::InvocationContext::run_config(ctx.as_ref()),
2182 ctx.app_name(),
2183 ctx.agent_name(),
2184 );
2185 match scope.within(compaction_cfg.summarizer.summarize_events(events_to_compact)).await {
2186 Ok(Some(compaction_event))
2189 if adk_core::intra_compaction::estimate_tokens(
2190 std::slice::from_ref(&compaction_event),
2191 4,
2192 ) >= adk_core::intra_compaction::estimate_tokens(
2193 events_to_compact,
2194 4,
2195 ) =>
2196 {
2197 tracing::info!(
2198 "compaction summary is not smaller than the history it replaces; keeping the history"
2199 );
2200 }
2201 Ok(Some(compaction_event)) => {
2202 if let Err(e) = session_service
2204 .append_event_for_identity(adk_session::AppendEventRequest {
2205 identity: identity.clone(),
2206 event: compaction_event.clone(),
2207 })
2208 .await {
2209 tracing::warn!(error = %e, "Failed to persist compaction event");
2210 } else {
2211 tracing::info!(
2212 compacted_events = compact_up_to,
2213 "Context compaction completed"
2214 );
2215 }
2216 }
2217 Ok(None) => {
2218 tracing::debug!("Compaction summarizer returned no result");
2219 }
2220 Err(e) => {
2221 tracing::warn!(error = %e.diagnostics(), "Context compaction failed");
2223 }
2224 }
2225 }
2226 }
2227 }
2228 }
2229
2230 };
2231
2232 let inner: EventStream = Box::pin(s);
2238 let events = stream! {
2239 use futures::StreamExt;
2240 let _cleanup = cleanup;
2241 let mut inner = inner;
2242 let mut author = stop_default_author;
2243 let mut failure = None;
2244 while let Some(item) = inner.next().await {
2245 match item {
2246 Ok(event) => {
2247 if !event.author.is_empty() && event.author != "user" {
2248 author.clone_from(&event.author);
2249 }
2250 finish.in_flight.observe(&event);
2251 yield Ok(event);
2252 }
2253 Err(error) => {
2254 failure = Some(error);
2255 break;
2256 }
2257 }
2258 }
2259 drop(inner);
2261 if let Some(error) = &failure
2262 && let Some(stop_event) =
2263 adk_core::budget_exceeded_event(&stop_invocation_id, &author, error)
2264 {
2265 let stop_event = finish.on_event(stop_event).await;
2266 if let Err(persist_error) = finish
2267 .session_service
2268 .append_event_for_identity(adk_session::AppendEventRequest {
2269 identity: finish.identity.clone(),
2270 event: stop_event.clone(),
2271 })
2272 .await
2273 {
2274 tracing::warn!(error = %persist_error, "failed to persist the budget stop event");
2275 }
2276 yield Ok(stop_event);
2277 }
2278 finish.after_run().await;
2279 if let Some(error) = failure {
2280 yield Err(error);
2281 }
2282 };
2283
2284 let events: EventStream = Box::pin(events);
2285 Ok(RunnerInvocation { invocation_id, events })
2286 }
2287
2288 pub async fn run_str(
2298 &self,
2299 user_id: &str,
2300 session_id: &str,
2301 user_content: Content,
2302 ) -> Result<EventStream> {
2303 let user_id = UserId::try_from(user_id)?;
2304 let session_id = SessionId::try_from(session_id)?;
2305 self.run(user_id, session_id, user_content).await
2306 }
2307
2308 pub fn interrupt(&self, session_id: &str) -> bool {
2333 self.request_durable_cancel(None, session_id);
2334 let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
2335 let matching: Vec<&ActiveRun> =
2336 runs.values().filter(|run| run.identity.session_id.as_ref() == session_id).collect();
2337 if matching.is_empty() {
2338 tracing::debug!(session.id = session_id, "no active run to interrupt");
2339 return false;
2340 }
2341 tracing::info!(
2342 session.id = session_id,
2343 run.count = matching.len(),
2344 "interrupting running agent"
2345 );
2346 for run in matching {
2347 run.token.cancel();
2348 }
2349 true
2350 }
2351
2352 fn request_durable_cancel(&self, user_id: Option<&str>, session_id: &str) {
2357 let Some(store) = self.durable_runs.clone() else { return };
2358 let Ok(handle) = tokio::runtime::Handle::try_current() else {
2359 tracing::warn!(
2360 session.id = session_id,
2361 "no tokio runtime to request durable cancellation on; call cancel_durable_runs"
2362 );
2363 return;
2364 };
2365 let filter = durable_filter(&self.app_name, user_id, session_id);
2366 let session = session_id.to_string();
2367 handle.spawn(async move {
2368 if let Err(error) = cancel_matching(store.as_ref(), filter).await {
2369 tracing::error!(session.id = %session, error = %error, "could not request durable run cancellation");
2370 }
2371 });
2372 }
2373
2374 pub async fn cancel_durable_runs(&self, user_id: &str, session_id: &str) -> Result<usize> {
2391 match &self.durable_runs {
2392 Some(store) => {
2393 cancel_matching(
2394 store.as_ref(),
2395 durable_filter(&self.app_name, Some(user_id), session_id),
2396 )
2397 .await
2398 }
2399 None => Ok(0),
2400 }
2401 }
2402
2403 pub async fn recover_unanswered_calls(&self, user_id: &str, session_id: &str) -> Result<usize> {
2424 self.recover_unanswered_calls_with_config(user_id, session_id, None).await
2425 }
2426
2427 pub async fn recover_unanswered_calls_with_config(
2439 &self,
2440 user_id: &str,
2441 session_id: &str,
2442 run_config: Option<RunConfig>,
2443 ) -> Result<usize> {
2444 let identity = adk_core::AdkIdentity::new(
2445 AppName::try_from(self.app_name.clone())?,
2446 UserId::try_from(user_id)?,
2447 SessionId::try_from(session_id)?,
2448 );
2449 let session = self.session_service.get_for_identity(&identity).await?;
2450 adk_session::ensure_writable(session.as_ref())?;
2451 let mut in_flight = InFlightCalls::default();
2452 for event in session.events().all() {
2453 in_flight.observe(&event);
2454 }
2455 if in_flight.0.is_empty() {
2456 return Ok(0);
2457 }
2458 let ledger = self.action_ledger.clone().or_else(|| self.run_config.action_ledger.clone());
2459 let mut records = HashMap::new();
2460 for call in &in_flight.0 {
2461 let (Some(ledger), Some(id)) = (&ledger, &call.id) else { continue };
2462 let key =
2463 format!("{}/{user_id}/{session_id}/{}/{id}", self.app_name, call.invocation_id);
2464 records.insert(id.clone(), ledger.get(&key).await?);
2465 }
2466 if let Some(trail) = self.audit.as_ref().or(self.run_config.audit.as_ref()) {
2469 let mut run_config = run_config.unwrap_or_else(|| self.run_config.clone());
2470 if run_config.audit.is_none() {
2471 run_config.audit = Some(trail.clone());
2472 }
2473 let invocation = in_flight.0.first().map(|call| call.invocation_id.clone());
2474 self.acting_resolver()
2475 .resolve(&mut run_config, user_id, session_id, invocation.as_deref().unwrap_or(""))
2476 .await?;
2477 in_flight
2478 .audit_calls(trail, &run_config, &identity, "recovered", |call| {
2479 use adk_core::audit_log::AuditRecordOutcome;
2480 let record = call.id.as_ref().and_then(|id| records.get(id)).cloned();
2481 match record.flatten().and_then(|record| record.outcome) {
2482 Some(adk_core::ActionOutcome::Succeeded { .. }) => {
2483 AuditRecordOutcome::Succeeded
2484 }
2485 Some(adk_core::ActionOutcome::Failed { error })
2488 if adk_core::is_not_run(&error) =>
2489 {
2490 AuditRecordOutcome::NotRun
2491 }
2492 Some(adk_core::ActionOutcome::Failed { .. }) => AuditRecordOutcome::Failed,
2493 _ => AuditRecordOutcome::OutcomeUnknown,
2494 }
2495 })
2496 .await?;
2497 }
2498 let answered = in_flight.0.len();
2499 let events = in_flight.answer_with(|call| {
2500 let record = call.id.as_ref().and_then(|id| records.get(id).cloned().flatten());
2501 recovered_call_response(&call.name, record)
2502 });
2503 for event in events {
2504 tracing::warn!(
2505 session.id = session_id,
2506 invocation.id = %event.invocation_id,
2507 "answering function calls a stopped process left unanswered"
2508 );
2509 self.session_service
2510 .append_event_for_identity(adk_session::AppendEventRequest {
2511 identity: identity.clone(),
2512 event,
2513 })
2514 .await?;
2515 }
2516 Ok(answered)
2517 }
2518
2519 pub fn interrupt_identity(&self, app_name: &str, user_id: &str, session_id: &str) -> bool {
2531 let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
2532 let mut cancelled = false;
2533 for run in runs.values() {
2534 if run.identity.app_name.as_ref() == app_name
2535 && run.identity.user_id.as_ref() == user_id
2536 && run.identity.session_id.as_ref() == session_id
2537 {
2538 run.token.cancel();
2539 cancelled = true;
2540 }
2541 }
2542 if !cancelled {
2543 tracing::debug!(
2544 app.name = app_name,
2545 user.id = user_id,
2546 session.id = session_id,
2547 "no active run to interrupt"
2548 );
2549 }
2550 cancelled
2551 }
2552
2553 pub async fn steer(
2605 &self,
2606 identity: &adk_core::AdkIdentity,
2607 content: Content,
2608 ) -> Result<adk_core::SteerReceipt> {
2609 adk_core::validate_steering_message(&content)?;
2610 let run = {
2611 let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
2612 runs.iter()
2613 .filter(|(_, run)| run.identity == *identity)
2614 .max_by_key(|(run_id, _)| **run_id)
2615 .map(|(_, run)| run.clone())
2616 };
2617 let Some(run) = run else {
2618 tracing::debug!(
2619 app.name = %identity.app_name,
2620 user.id = %identity.user_id,
2621 session.id = %identity.session_id,
2622 "no active run to steer"
2623 );
2624 return Err(adk_core::AdkError::new(
2625 adk_core::ErrorComponent::Agent,
2626 adk_core::ErrorCategory::NotFound,
2627 adk_core::STEER_NO_ACTIVE_RUN_CODE,
2628 format!(
2629 "no run is in flight for session '{}' of user '{}'; send the message as \
2630 the session's next message",
2631 identity.session_id, identity.user_id
2632 ),
2633 ));
2634 };
2635 #[cfg(not(feature = "plugins"))]
2637 let screening = content.clone();
2638 #[cfg(feature = "plugins")]
2639 let screening = match self.plugin_manager.as_ref() {
2640 Some(manager) => {
2641 let Some(ctx) = run.scope.get() else {
2642 return Err(adk_core::AdkError::new(
2643 adk_core::ErrorComponent::Agent,
2644 adk_core::ErrorCategory::Unavailable,
2645 "agent.steer.run_not_ready",
2646 format!(
2647 "the run for session '{}' is starting or finishing, so its plugins \
2648 cannot screen the message; steer again once the run has produced \
2649 an event, or send it as the session's next message",
2650 identity.session_id
2651 ),
2652 ));
2653 };
2654 manager
2655 .run_on_user_message(
2656 ctx as Arc<dyn adk_core::InvocationContext>,
2657 content.clone(),
2658 )
2659 .await?
2660 .unwrap_or_else(|| content.clone())
2661 }
2662 None => content.clone(),
2663 };
2664 let screened = self.root_agent.screen_user_input(&screening).await?;
2665 let input_screened = screened.is_some();
2666 let receipt = run.inbox.push(
2667 content,
2668 screened.unwrap_or(screening),
2669 identity.user_id.as_ref(),
2670 input_screened,
2671 )?;
2672 tracing::info!(
2673 session.id = %identity.session_id,
2674 steer.id = receipt.steer_id(),
2675 steer.sequence = receipt.sequence(),
2676 "steering message queued"
2677 );
2678 Ok(receipt)
2679 }
2680
2681 pub fn active_runs(&self) -> Vec<adk_core::AdkIdentity> {
2686 let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
2687 runs.values().map(|run| run.identity.clone()).collect()
2688 }
2689
2690 #[must_use]
2696 pub fn with_session_activity(mut self, activity: crate::history::SessionActivity) -> Self {
2697 self.session_activity = activity;
2698 self
2699 }
2700
2701 pub fn session_activity(&self) -> &crate::history::SessionActivity {
2703 &self.session_activity
2704 }
2705
2706 pub fn history_control(&self) -> crate::history::HistoryControl {
2726 let mut control = crate::history::HistoryControl::new(self.session_service.clone())
2727 .with_activity(self.session_activity.clone());
2728 if let Some(trail) = self.audit_trail() {
2729 control = control.with_audit(trail.clone());
2730 }
2731 if let Some(store) = &self.durable_runs {
2732 control = control.with_run_store(store.clone());
2733 }
2734 control
2735 }
2736
2737 pub fn active_session_ids(&self) -> Vec<String> {
2742 let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
2743 let mut ids: Vec<String> =
2744 runs.values().map(|run| run.identity.session_id.as_ref().to_string()).collect();
2745 ids.sort();
2746 ids.dedup();
2747 ids
2748 }
2749
2750 #[cfg(feature = "context-compaction")]
2754 pub fn context_compaction(&self) -> Option<&crate::compaction::CompactionConfig> {
2755 self.context_compaction.as_deref()
2756 }
2757
2758 fn intra_compactor(
2761 &self,
2762 run: Option<&adk_core::IntraCompactionConfig>,
2763 ) -> Option<Arc<crate::intra_compaction::IntraInvocationCompactor>> {
2764 use crate::intra_compaction::IntraInvocationCompactor;
2765 let config = run.unwrap_or(&self.intra_compaction).clone();
2766 if !config.enabled {
2767 return None;
2768 }
2769 #[cfg(feature = "context-compaction")]
2770 if let Some(strategy) = &self.context_compaction {
2771 return Some(Arc::new(IntraInvocationCompactor::with_strategy(
2772 config,
2773 strategy.clone(),
2774 )));
2775 }
2776 Some(Arc::new(match &self.intra_summarizer {
2777 Some(summarizer) => IntraInvocationCompactor::new(config, summarizer.clone()),
2778 None => IntraInvocationCompactor::with_model_summary(config),
2779 }))
2780 }
2781
2782 pub fn find_agent_to_run(
2784 root_agent: &Arc<dyn Agent>,
2785 session: &dyn adk_session::Session,
2786 ) -> Arc<dyn Agent> {
2787 let events = session.events();
2789 for i in (0..events.len()).rev() {
2790 if let Some(event) = events.at(i) {
2791 if let Some(target_name) = &event.actions.transfer_to_agent
2793 && let Some(agent) = Self::find_agent(root_agent, target_name)
2794 {
2795 return agent;
2796 }
2797
2798 if event.author == "user" {
2799 continue;
2800 }
2801
2802 if let Some(agent) = Self::find_agent(root_agent, &event.author) {
2804 if Self::is_transferable(root_agent, &agent) {
2806 return agent;
2807 }
2808 }
2809 }
2810 }
2811
2812 root_agent.clone()
2814 }
2815
2816 fn is_transferable(root_agent: &Arc<dyn Agent>, agent: &Arc<dyn Agent>) -> bool {
2832 fn path_supports_transfer(current: &Arc<dyn Agent>, target: &str) -> Option<bool> {
2838 if current.name() == target {
2839 return Some(current.supports_agent_transfer());
2840 }
2841 for sub in current.sub_agents() {
2842 if let Some(sub_ok) = path_supports_transfer(sub, target) {
2843 return Some(current.supports_agent_transfer() && sub_ok);
2844 }
2845 }
2846 None
2847 }
2848
2849 path_supports_transfer(root_agent, agent.name()).unwrap_or(true)
2850 }
2851
2852 fn transfer_source<'a>(root: &Arc<dyn Agent>, author: &'a str, running: &'a str) -> &'a str {
2855 if !author.is_empty() && Self::find_agent(root, author).is_some() {
2856 author
2857 } else {
2858 running
2859 }
2860 }
2861
2862 pub fn allowed_transfer_targets(root: &Arc<dyn Agent>, source: &str) -> Option<Vec<String>> {
2870 if let Some(targets) = root.transfer_targets_for(source) {
2871 return Some(targets);
2872 }
2873 let agent = Self::find_agent(root, source)?;
2874 let mut targets: Vec<String> =
2875 agent.sub_agents().iter().map(|sub| sub.name().to_string()).collect();
2876 let (parent, peers) = Self::compute_transfer_context(root, source);
2877 if let Some(parent) = parent
2878 && agent.allows_transfer_to_parent()
2879 {
2880 targets.push(parent);
2881 }
2882 if agent.allows_transfer_to_peers() {
2883 targets.extend(peers);
2884 }
2885 Some(targets)
2886 }
2887
2888 pub fn find_agent(current: &Arc<dyn Agent>, target_name: &str) -> Option<Arc<dyn Agent>> {
2890 if current.name() == target_name {
2891 return Some(current.clone());
2892 }
2893
2894 for sub_agent in current.sub_agents() {
2895 if let Some(found) = Self::find_agent(sub_agent, target_name) {
2896 return Some(found);
2897 }
2898 }
2899
2900 None
2901 }
2902
2903 pub fn describe_agents(
2906 root: &Arc<dyn Agent>,
2907 names: &[String],
2908 ) -> std::collections::HashMap<String, String> {
2909 fn visit(
2910 agent: &Arc<dyn Agent>,
2911 names: &[String],
2912 found: &mut std::collections::HashMap<String, String>,
2913 ) {
2914 if names.iter().any(|name| name == agent.name())
2915 && !agent.description().trim().is_empty()
2916 {
2917 found.insert(agent.name().to_string(), agent.description().to_string());
2918 }
2919 for sub in agent.sub_agents() {
2920 visit(sub, names, found);
2921 }
2922 }
2923 let mut found = std::collections::HashMap::new();
2924 if !names.is_empty() {
2925 visit(root, names, &mut found);
2926 }
2927 found
2928 }
2929
2930 pub fn compute_transfer_context(
2936 root: &Arc<dyn Agent>,
2937 target_name: &str,
2938 ) -> (Option<String>, Vec<String>) {
2939 if root.name() == target_name {
2941 return (None, Vec::new());
2942 }
2943
2944 fn find_parent(current: &Arc<dyn Agent>, target: &str) -> Option<Arc<dyn Agent>> {
2946 for sub in current.sub_agents() {
2947 if sub.name() == target {
2948 return Some(current.clone());
2949 }
2950 if let Some(found) = find_parent(sub, target) {
2951 return Some(found);
2952 }
2953 }
2954 None
2955 }
2956
2957 match find_parent(root, target_name) {
2958 Some(parent) => {
2959 let parent_name = parent.name().to_string();
2960 let peers: Vec<String> = parent
2961 .sub_agents()
2962 .iter()
2963 .filter(|a| a.name() != target_name)
2964 .map(|a| a.name().to_string())
2965 .collect();
2966 (Some(parent_name), peers)
2967 }
2968 None => (None, Vec::new()),
2969 }
2970 }
2971}
2972
2973#[cfg(test)]
2974mod streamed_content_tests {
2975 use super::preserve_streamed_content;
2976 use adk_core::{Content, Event, Part};
2977 use std::collections::HashMap;
2978
2979 fn text(event: &Event) -> String {
2980 event
2981 .content()
2982 .map(|content| content.parts.iter().filter_map(Part::text).collect())
2983 .unwrap_or_default()
2984 }
2985
2986 #[test]
2987 fn final_empty_event_preserves_streamed_text_for_persistence() {
2988 let mut accumulated = HashMap::new();
2989 let mut first = Event::with_id("response-1", "inv-1");
2990 first.llm_response.partial = true;
2991 first.llm_response.content = Some(Content::new("model").with_text("Verify "));
2992 preserve_streamed_content(&mut accumulated, &mut first);
2993
2994 let mut second = Event::with_id("response-1", "inv-1");
2995 second.llm_response.partial = true;
2996 second.llm_response.content = Some(Content::new("model").with_text("the invoice."));
2997 preserve_streamed_content(&mut accumulated, &mut second);
2998
2999 let mut final_event = Event::with_id("response-1", "inv-1");
3000 final_event.llm_response.turn_complete = true;
3001 preserve_streamed_content(&mut accumulated, &mut final_event);
3002
3003 assert_eq!(text(&final_event), "Verify the invoice.");
3004 assert!(accumulated.is_empty());
3005 }
3006}
3007
3008fn durable_filter(app_name: &str, user_id: Option<&str>, session_id: &str) -> adk_core::RunFilter {
3010 let filter = adk_core::RunFilter::default().app_name(app_name).session_id(session_id).states([
3011 adk_core::RunState::Queued,
3012 adk_core::RunState::Running,
3013 adk_core::RunState::Waiting,
3014 ]);
3015 match user_id {
3016 Some(user_id) => filter.user_id(user_id),
3017 None => filter,
3018 }
3019}
3020
3021async fn cancel_matching(
3022 store: &dyn adk_core::DurableRunStore,
3023 filter: adk_core::RunFilter,
3024) -> Result<usize> {
3025 let runs = store.list(filter).await?;
3026 for run in &runs {
3027 store.request_cancel(&run.run_id).await?;
3028 tracing::info!(run.id = %run.run_id, run.state = ?run.state, "durable run cancellation requested");
3029 }
3030 Ok(runs.len())
3031}
3032
3033#[cfg(test)]
3034mod in_flight_tests {
3035 use super::InFlightCalls;
3036 use adk_core::{Content, Event, FunctionResponseData, Part};
3037 use serde_json::json;
3038
3039 fn call(name: &str, id: Option<&str>) -> Part {
3040 Part::FunctionCall {
3041 name: name.to_string(),
3042 args: json!({}),
3043 id: id.map(str::to_string),
3044 thought_signature: None,
3045 }
3046 }
3047
3048 fn response(name: &str, id: Option<&str>) -> Part {
3049 Part::FunctionResponse {
3050 function_response: FunctionResponseData::new(name, json!({"ok": true})),
3051 id: id.map(str::to_string),
3052 annotations: None,
3053 }
3054 }
3055
3056 fn event(author: &str, role: &str, parts: Vec<Part>) -> Event {
3057 let mut event = Event::new("inv-1");
3058 event.author = author.to_string();
3059 event.llm_response.content = Some(Content { role: role.to_string(), parts });
3060 event
3061 }
3062
3063 #[test]
3064 fn only_unanswered_calls_are_answered_once_each() {
3065 let mut in_flight = InFlightCalls::default();
3066 in_flight.observe(&event(
3067 "agent",
3068 "model",
3069 vec![call("pay", Some("c1")), call("ship", Some("c2")), call("notify", None)],
3070 ));
3071 in_flight.observe(&event("agent", "function", vec![response("ship", Some("c2"))]));
3072 let mut partial = event("agent", "model", vec![call("refund", Some("c3"))]);
3074 partial.llm_response.partial = true;
3075 in_flight.observe(&partial);
3076
3077 let answered = in_flight.answer_interrupted();
3078
3079 assert_eq!(answered.len(), 1, "one event per author, branch, and invocation");
3080 assert_eq!(answered[0].author, "agent");
3081 let parts = &answered[0].llm_response.content.as_ref().unwrap().parts;
3082 let answered_calls: Vec<_> = parts
3083 .iter()
3084 .map(|part| match part {
3085 Part::FunctionResponse { function_response, id, .. } => {
3086 assert!(adk_core::is_outcome_unknown(&function_response.response));
3087 (function_response.name.as_str(), id.as_deref())
3088 }
3089 other => panic!("unexpected part {other:?}"),
3090 })
3091 .collect();
3092 assert_eq!(answered_calls, [("pay", Some("c1")), ("notify", None)]);
3093 assert!(in_flight.answer_interrupted().is_empty(), "calls are answered once");
3094 }
3095
3096 fn answered(name: &str, id: &str, response: serde_json::Value, status: &str) -> Part {
3097 Part::FunctionResponse {
3098 function_response: FunctionResponseData::new(name, response),
3099 id: Some(id.to_string()),
3100 annotations: Some(json!({ adk_core::TOOL_RESULT_STATUS_KEY: status })),
3101 }
3102 }
3103
3104 #[test]
3107 fn a_cancelled_runs_calls_are_answered_with_an_unknown_outcome() {
3108 let mut in_flight = InFlightCalls::default();
3109 in_flight.observe(&event("agent", "model", vec![call("pay", Some("c1"))]));
3110
3111 let answered_events = in_flight.answer_interrupted();
3112
3113 let parts = answered_events[0].llm_response.content.clone().unwrap().parts;
3114 assert_eq!(
3115 parts,
3116 vec![answered(
3117 "pay",
3118 "c1",
3119 adk_core::outcome_unknown_response(
3120 "the run was cancelled while 'pay' was in flight, so the call may have \
3121 taken effect; check its result before calling it again"
3122 ),
3123 "outcome_unknown",
3124 )]
3125 );
3126 }
3127
3128 #[test]
3129 fn a_recovered_call_is_answered_with_the_status_its_record_shows() {
3130 let record = |outcome: Option<adk_core::ActionOutcome>| {
3131 let mut record = adk_core::ActionRecord::new(
3132 "k",
3133 "pay",
3134 &json!({}),
3135 adk_core::ToolEffect::NonIdempotent,
3136 );
3137 record.outcome = outcome;
3138 Some(record)
3139 };
3140 let frozen = adk_core::not_run_text(&adk_core::AdkError::agent("execution is frozen"));
3141 let cases = [
3142 (
3143 record(Some(adk_core::ActionOutcome::Succeeded { result_digest: "d".into() })),
3144 json!({
3145 "status": "already_succeeded",
3146 "result_digest": "d",
3147 "detail": "this call to 'pay' completed before the run was recovered; it \
3148 was not executed again",
3149 }),
3150 "succeeded",
3151 ),
3152 (
3153 record(Some(adk_core::ActionOutcome::Failed { error: "declined".into() })),
3154 json!({
3155 "status": "already_failed",
3156 "error": "declined",
3157 "detail": "this call to 'pay' failed before the run was recovered; it was \
3158 not executed again",
3159 }),
3160 "failed",
3161 ),
3162 (
3163 record(Some(adk_core::ActionOutcome::Failed { error: frozen.clone() })),
3164 json!({
3165 "status": "already_failed",
3166 "error": frozen,
3167 "detail": "this call to 'pay' failed before the run was recovered; it was \
3168 not executed again",
3169 }),
3170 "not_run",
3171 ),
3172 (
3173 None,
3174 adk_core::outcome_unknown_response(
3175 "the process running 'pay' stopped before the call recorded an outcome, so \
3176 it may have taken effect; check its result before calling it again",
3177 ),
3178 "outcome_unknown",
3179 ),
3180 ];
3181 for (record, response, status) in cases {
3182 let mut in_flight = InFlightCalls::default();
3183 in_flight.observe(&event("agent", "model", vec![call("pay", Some("c1"))]));
3184 let answered_events = in_flight
3185 .answer_with(|call| super::recovered_call_response(&call.name, record.clone()));
3186 assert_eq!(
3187 answered_events[0].llm_response.content.clone().unwrap().parts,
3188 vec![answered("pay", "c1", response, status)],
3189 "{status}"
3190 );
3191 }
3192 }
3193}