Skip to main content

adk_runner/
runner.rs

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/// A run currently in flight, tracked so it can be interrupted and steered.
20///
21/// Keyed by run ID rather than session ID: a session ID is only unique within an
22/// app and user, and one identity may have several runs in flight at once.
23#[derive(Clone)]
24struct ActiveRun {
25    identity: adk_core::AdkIdentity,
26    token: CancellationToken,
27    inbox: adk_core::SteeringInbox,
28    /// The run's context, which plugins screen a steering message with.
29    #[cfg(feature = "plugins")]
30    scope: RunScope,
31}
32
33/// Registry of in-flight runs, keyed by run ID.
34type 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
51/// A tool call the run has seen requested but not yet answered.
52struct 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/// Tracks tool calls from request to response, so a cancelled run can answer
62/// the calls still in flight instead of leaving them unpaired.
63#[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    /// Records every call still in flight with the outcome `outcome` assigns it.
101    ///
102    /// # Errors
103    ///
104    /// Returns the first error the trail reports, which it does only in
105    /// [`AuditFailureMode::Block`](adk_core::audit_log::AuditFailureMode::Block).
106    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    /// Answers every call still in flight with an outcome-unknown response, one
138    /// event per author, branch, and invocation, so each call keeps exactly one
139    /// response.
140    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    /// Answers every call still in flight with `respond(call)`, a response and its status,
151    /// one event per author, branch, and invocation.
152    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
190/// The function response a recovering worker gives a call that a stopped process left
191/// unanswered, from the action ledger's record of it, with the status the record shows.
192fn 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
216/// Screens the saved user messages of `session` that lack the
217/// [`input_screened`](adk_core::EventActions::input_screened) marker with `root`'s input
218/// guardrails, so no model sees them unscreened.
219///
220/// Returns, by event index, what this run's view of the session holds instead: the screened
221/// content of a message a guardrail transformed, or `None` for a message a guardrail blocks,
222/// which is withheld. The store is not rewritten. A run that brings no message of its own
223/// (`resuming`) continues the latest saved message, so a block on that message fails the run.
224///
225/// # Errors
226///
227/// Returns the guardrail's error when it blocks the latest saved message of a resuming run.
228async 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            // No agent in the tree screens input, so no saved message needs it.
248            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
268/// Deregisters a run when its event stream is dropped, and returns the steering messages
269/// no safe point took.
270///
271/// Removal is by run ID, so a finishing run can never deregister a different run
272/// that happens to share the same session ID.
273struct ActiveRunCleanup {
274    active_runs: ActiveRuns,
275    run_id: u64,
276    inbox: adk_core::SteeringInbox,
277    /// Keeps the run in the runner's session activity until the stream ends.
278    _activity: crate::history::ActivityGuard,
279}
280
281/// A newly registered runner invocation and its event stream.
282///
283/// The invocation identity is available before the stream is polled, so hosts
284/// can durably correlate failures that happen before the first agent event.
285pub struct RunnerInvocation {
286    invocation_id: InvocationId,
287    events: EventStream,
288}
289
290impl RunnerInvocation {
291    /// Returns the identity assigned to this invocation.
292    pub fn invocation_id(&self) -> &InvocationId {
293        &self.invocation_id
294    }
295
296    /// Consumes the invocation and returns its event stream.
297    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        // Deregistered first, so `steer` either finds the run before this or not at all.
317        self.inbox.close();
318    }
319}
320
321/// The invocation context of a run that has started, shared by the run stream that builds it
322/// and the stage that finishes the run.
323#[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
341/// Finishes a run once its plugins' `before_run` has run.
342///
343/// The run stream calls [`after_run`](Self::after_run) when the run ends. A stream that is
344/// dropped first — a client that disconnects — is finished on the current Tokio runtime
345/// instead: each tool call still in flight is answered outcome-unknown, persisted and
346/// audited, then `after_run` runs.
347///
348/// A durable run's attempt ([`RunConfig::durable_run_id`]) is the exception: the worker
349/// drops it when its lease is lost, and the worker that recovers the run answers its calls
350/// from the action ledger and finishes it, so the dropped attempt writes nothing more.
351struct 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    /// Passes `event` through the plugins' `on_event`, keeping it when a plugin fails.
363    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    /// Runs the plugins' `after_run` for a run that started.
381    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                // The run is already over, so a failed write is logged by the trail.
419                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
457/// Configuration for constructing a [`Runner`].
458///
459/// Use [`Runner::builder()`] for a compile-time-safe way to construct this.
460pub struct RunnerConfig {
461    /// Application name used for session scoping.
462    pub app_name: String,
463    /// The root agent to execute.
464    pub agent: Arc<dyn Agent>,
465    /// Session persistence backend.
466    pub session_service: Arc<dyn SessionService>,
467    #[cfg(feature = "artifacts")]
468    /// Optional artifact storage service.
469    pub artifact_service: Option<Arc<dyn ArtifactService>>,
470    /// Optional memory/RAG service.
471    pub memory_service: Option<Arc<dyn Memory>>,
472    #[cfg(feature = "plugins")]
473    /// Optional plugin manager for lifecycle hooks.
474    pub plugin_manager: Option<Arc<PluginManager>>,
475    /// Optional run configuration (streaming mode, etc.)
476    /// If not provided, uses default (SSE streaming)
477    #[allow(dead_code)]
478    pub run_config: Option<RunConfig>,
479    /// Optional context compaction configuration.
480    /// When set, the runner will periodically summarize older events
481    /// to reduce context size sent to the LLM.
482    pub compaction_config: Option<adk_core::EventsCompactionConfig>,
483    /// Optional context cache configuration for automatic prompt caching lifecycle.
484    /// When set alongside `cache_capable`, the runner will automatically create and
485    /// manage cached content resources for supported providers.
486    ///
487    /// When `cache_capable` is set but this field is `None`, the runner
488    /// automatically uses [`ContextCacheConfig::default()`] (4096 min tokens,
489    /// 600s TTL, refresh every 3 invocations).
490    pub context_cache_config: Option<ContextCacheConfig>,
491    /// Optional cache-capable model reference for automatic cache management.
492    /// Set this to the same model used by the agent if it supports caching.
493    pub cache_capable: Option<Arc<dyn CacheCapable>>,
494    /// Optional request context from the server's auth middleware bridge.
495    /// When set, the runner passes it to `InvocationContext` so that
496    /// `user_scopes()` and `user_id()` reflect the authenticated identity.
497    pub request_context: Option<adk_core::RequestContext>,
498    /// Optional cooperative cancellation token for externally managed runs.
499    ///
500    /// Each run derives a child of this token, so cancelling it stops every in-flight
501    /// run, while [`Runner::interrupt`] cancels only the targeted run's child.
502    pub cancellation_token: Option<CancellationToken>,
503    /// When the run's agents compact their history before a model call (auto-compaction).
504    ///
505    /// `None` is the default, which is on: a request is compacted once it passes 80% of the
506    /// model's context window, or 100,000 estimated tokens when the model reports none
507    /// ([`IntraCompactionConfig::default`](adk_core::IntraCompactionConfig)).
508    /// `Some(IntraCompactionConfig::disabled())` turns it off. A run's
509    /// [`RunConfig::intra_compaction`] takes precedence.
510    pub intra_compaction_config: Option<adk_core::IntraCompactionConfig>,
511    /// The summarizer auto-compaction uses. `None` summarizes with the model the agent is
512    /// calling ([`LlmEventSummarizer`](adk_core::LlmEventSummarizer)).
513    pub intra_compaction_summarizer: Option<Arc<dyn adk_core::BaseEventsSummarizer>>,
514    /// A compaction strategy auto-compaction applies in place of a summary.
515    ///
516    /// When set, an agent's history is shortened with the configured
517    /// [`CompactionStrategy`](crate::compaction::CompactionStrategy) before any model call
518    /// whose request passes `context_budget` estimated tokens, up to `max_retries` times.
519    ///
520    /// This field is only available when the `context-compaction` feature is enabled.
521    #[cfg(feature = "context-compaction")]
522    pub context_compaction: Option<crate::compaction::CompactionConfig>,
523    /// Optional policy evaluated for every tool call.
524    ///
525    /// Installed on each run's [`RunConfig::tool_policy`] when the run carries none.
526    pub tool_policy: Option<Arc<dyn adk_core::ToolPolicy>>,
527    /// Optional network egress ceiling for tool calls.
528    ///
529    /// Each run's [`RunConfig::egress_policy`] is narrowed by it, never widened.
530    pub egress_policy: Option<adk_core::egress::EgressPolicy>,
531    /// Optional kill switch shared with other runners. Without one the runner creates
532    /// its own; see [`Runner::governance`].
533    pub governance: Option<adk_core::GovernanceControl>,
534    /// Optional ledger of non-idempotent tool calls.
535    ///
536    /// Installed on each run's [`RunConfig::action_ledger`] when the run carries none.
537    pub action_ledger: Option<Arc<dyn adk_core::ActionLedger>>,
538    /// Optional store for calls held for approval and their decisions.
539    ///
540    /// Installed on each run's [`RunConfig::approval_store`] when the run carries none.
541    pub approval_store: Option<Arc<dyn adk_core::ApprovalStore>>,
542    /// Optional ledger that model calls and payment tools reserve budget against.
543    ///
544    /// Installed on each run's [`RunConfig::spend_ledger`] when the run carries none.
545    pub spend_ledger: Option<Arc<dyn adk_core::SpendLedger>>,
546    /// Optional durable run queue shared by every replica.
547    ///
548    /// When set, [`Runner::interrupt`] also requests cancellation of the session's
549    /// unfinished durable runs, so the worker that owns one stops it on its next
550    /// heartbeat, whichever replica it runs on.
551    pub durable_runs: Option<Arc<dyn adk_core::DurableRunStore>>,
552    /// Optional audit trail for governed actions.
553    ///
554    /// Installed on each run's [`RunConfig::audit`] when the run carries none, and
555    /// attached to the runner's kill switch so freezes and unfreezes are recorded.
556    pub audit: Option<adk_core::audit_log::AuditTrail>,
557    /// Optional source of the principals each run's agents act as.
558    ///
559    /// Read at the start of every run: the root agent acts as the source's principal for
560    /// it, and every other agent as the source's principal for it when the source maps
561    /// one. A principal the run's [`RunConfig::acting`] names for an agent takes
562    /// precedence. Without one, each agent acts as
563    /// `urn:adk:agent:{app_name}/{agent_name}`.
564    pub identity_source: Option<Arc<dyn adk_core::IdentitySource>>,
565    /// Optional policy allowing runs to act for a subject other than their session's
566    /// user. Without one, such runs are refused with `identity.subject_mismatch`.
567    pub subject_delegation: Option<Arc<dyn adk_core::SubjectDelegationPolicy>>,
568}
569
570/// Agent execution runtime.
571///
572/// Orchestrates session retrieval, agent dispatch, event streaming, context
573/// caching, and compaction. Construct via [`Runner::builder()`] or
574/// [`Runner::new()`].
575pub 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    /// When agents compact their history during a run; a run's own setting takes precedence.
594    intra_compaction: adk_core::IntraCompactionConfig,
595    /// The summarizer auto-compaction uses; `None` uses the agent's model.
596    intra_summarizer: Option<Arc<dyn adk_core::BaseEventsSummarizer>>,
597    /// Summaries written off the critical path, kept across runs so a session's next turn
598    /// swaps in what the last one started.
599    background_compactions: Arc<crate::intra_compaction::BackgroundCompactions>,
600    /// A compaction strategy auto-compaction applies in place of a summary.
601    #[cfg(feature = "context-compaction")]
602    context_compaction: Option<Arc<crate::compaction::CompactionConfig>>,
603    /// Hold taken before each model call when the run config carries a spend ledger.
604    llm_spend_estimate: crate::spend::LlmSpendEstimate,
605    /// Per-session cancellation tokens for the interrupt API.
606    /// Each `run()` call registers a token here; `interrupt()` cancels it.
607    active_runs: ActiveRuns,
608    /// The sessions this runner's runs are on, shared with other runners a host builds.
609    session_activity: crate::history::SessionActivity,
610    next_run_id: Arc<std::sync::atomic::AtomicU64>,
611    /// Policy installed on runs that carry none.
612    tool_policy: Option<Arc<dyn adk_core::ToolPolicy>>,
613    egress_policy: Option<adk_core::egress::EgressPolicy>,
614    /// Kill switch checked at the start of every run and carried into it.
615    governance: adk_core::GovernanceControl,
616    /// Durable stores installed on runs that carry none.
617    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 trail installed on runs that carry none.
622    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    /// Serializes externally triggered invocations per session. The weak values prevent the
626    /// per-trigger session policy from retaining one lock forever for every completed event.
627    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    /// Create a typestate builder for constructing a `Runner`.
636    ///
637    /// The builder enforces at compile time that the three required fields
638    /// (`app_name`, `agent`, `session_service`) are set before `build()` is
639    /// callable.
640    ///
641    /// # Example
642    ///
643    /// ```rust,ignore
644    /// let runner = Runner::builder()
645    ///     .app_name("my-app")
646    ///     .agent(agent)
647    ///     .session_service(session_service)
648    ///     .build()?;
649    /// ```
650    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    /// Create a new runner from a [`RunnerConfig`].
659    ///
660    /// Prefer [`Runner::builder()`] for a compile-time-safe construction API.
661    pub fn new(config: RunnerConfig) -> Result<Self> {
662        let run_config = config.run_config.unwrap_or_default();
663
664        // When a cache-capable model is provided but no explicit cache config,
665        // use the default ContextCacheConfig to enable caching automatically.
666        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    /// The executable root owned by this runner.
726    pub(crate) fn root_agent(&self) -> Arc<dyn Agent> {
727        Arc::clone(&self.root_agent)
728    }
729
730    /// The name of the runner's root agent.
731    pub fn root_agent_name(&self) -> &str {
732        self.root_agent.name()
733    }
734
735    /// The audit trail installed on runs that carry none, if any.
736    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    /// The principal the agent named `agent_name` acts as when a run names none for it.
741    ///
742    /// The identity source's principal for the agent; for the root agent, falling back
743    /// to the source's current principal; otherwise
744    /// [`AgentPrincipal::derived`](adk_core::AgentPrincipal::derived).
745    ///
746    /// # Errors
747    ///
748    /// Returns the identity source's error.
749    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    /// Sets what a call to an unpriced model commits in the run's
771    /// [`spend_ledger`](RunConfig::spend_ledger) when its response reports no cost.
772    ///
773    /// Priced calls reserve and commit their upper-bound cost instead; see
774    /// [`ModelCallScope`](adk_core::ModelCallScope). The runner writes the estimate into
775    /// [`RunConfig::llm_spend_estimate`] when the run's config has none. Defaults to [`LlmSpendEstimate::default`](crate::LlmSpendEstimate::default).
776    pub fn with_llm_spend_estimate(mut self, estimate: crate::LlmSpendEstimate) -> Self {
777        self.llm_spend_estimate = estimate;
778        self
779    }
780
781    /// Enable skill injection using a pre-built injector.
782    ///
783    /// Skill injection runs before plugin `on_user_message` callbacks.
784    #[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    /// Enable skill injection by auto-loading `.skills/` from the given root path.
791    #[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    /// Enable skill injection by auto-loading `.skills/` from the given root path.
803    ///
804    /// Unlike [`with_auto_skills`](Self::with_auto_skills), this method borrows
805    /// the Runner mutably instead of consuming it. On error, the Runner remains
806    /// valid with no skill injector configured.
807    #[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    /// Execute the root agent for the given user and session, returning an event stream.
819    ///
820    /// Retrieves the existing session, resolves the target agent, runs plugins and skills, and
821    /// streams events as the agent executes.
822    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    /// Returns the runner's application name.
832    pub fn app_name(&self) -> &str {
833        &self.app_name
834    }
835
836    /// Returns the runner's session service.
837    pub fn session_service(&self) -> &Arc<dyn adk_session::SessionService> {
838        &self.session_service
839    }
840
841    /// Returns the runner's kill switch.
842    ///
843    /// Freezing it fails new runs at their start and stops running ones before their
844    /// next model or tool call, with an error carrying the freeze reason.
845    ///
846    /// # Example
847    ///
848    /// ```rust,ignore
849    /// runner.governance().freeze("incident 4012");
850    /// // ... investigate ...
851    /// runner.governance().unfreeze();
852    /// ```
853    pub fn governance(&self) -> &adk_core::GovernanceControl {
854        &self.governance
855    }
856
857    /// The tool policy every run whose own config sets none is governed by.
858    ///
859    /// A host that layers a run-specific policy under it — a sub-agent's tool ceiling —
860    /// composes the two with [`StrictestPolicy`](adk_core::StrictestPolicy), so the runner's
861    /// decisions still apply.
862    ///
863    /// # Example
864    ///
865    /// ```rust,ignore
866    /// let mut config = runner.run_config().clone();
867    /// let mut layers: Vec<Arc<dyn ToolPolicy>> = config.tool_policy.clone().or_else(|| runner.tool_policy().cloned()).into_iter().collect();
868    /// layers.push(Arc::new(ToolCeiling::new(["read_file"])));
869    /// config.tool_policy = Some(Arc::new(StrictestPolicy::new(layers)));
870    /// ```
871    pub fn tool_policy(&self) -> Option<&Arc<dyn adk_core::ToolPolicy>> {
872        self.tool_policy.as_ref()
873    }
874
875    /// Releases what the runner's agents and plugins hold: every agent's toolsets, through
876    /// [`Agent::close`] on the root agent, then the plugins' close hooks.
877    ///
878    /// Call it once the application stops running the agent; runs started afterwards use
879    /// toolsets that are closed.
880    ///
881    /// # Example
882    ///
883    /// ```rust,ignore
884    /// let runner = Runner::builder()
885    ///     .app_name("support")
886    ///     .agent(agent)
887    ///     .session_service(sessions)
888    ///     .build()?;
889    /// // ... serve requests ...
890    /// runner.close().await;
891    /// ```
892    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    /// Readies the root agent, and optionally a session, before the first message: the
901    /// model's pooled connection, the servers an agent starts on its first turn, and the
902    /// session store's connection (see [`crate::prewarm`]). It sends no prompt and spends no
903    /// tokens.
904    ///
905    /// # Errors
906    ///
907    /// Returns the kill switch's error when the runner is frozen, `runner.prewarm.timeout`
908    /// when it takes longer than the request's budget, `session.archived` when the session
909    /// is archived, `session.not_found`, or the model's error.
910    ///
911    /// # Example
912    ///
913    /// ```rust,no_run
914    /// use adk_core::{SessionId, UserId};
915    /// use adk_runner::{Prewarm, Runner};
916    ///
917    /// # async fn example(runner: &Runner) -> adk_core::Result<()> {
918    /// // While the person is still typing: the first turn starts on a warm connection.
919    /// let report = runner
920    ///     .prewarm(Prewarm::new().session(UserId::new("ana")?, SessionId::new("trip")?))
921    ///     .await?;
922    /// println!("ready in {:?}, warm until {}", report.elapsed, report.warm_until);
923    /// # Ok(())
924    /// # }
925    /// ```
926    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    /// Returns the runner's configured [`RunConfig`].
973    ///
974    /// Useful as a base to clone and adjust for [`Self::run_with_config`].
975    pub fn run_config(&self) -> &RunConfig {
976        &self.run_config
977    }
978
979    /// Runs the agent with a per-invocation [`RunConfig`] override.
980    ///
981    /// Passing `None` uses the runner's configured `RunConfig`. Supply one to vary a single
982    /// invocation — injecting `runtime_toolsets` for tools that only exist for the duration of
983    /// that run, for example, as `SandboxRunner` does with tools bound to a live sandbox session.
984    ///
985    /// # Errors
986    ///
987    /// Returns an error if invocation setup fails before the stream is created. Session lookup
988    /// and agent execution failures are yielded by the returned stream.
989    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    /// Registers one invocation and returns its identity with the event stream.
1003    ///
1004    /// Prefer this method when a host must durably associate its own turn or
1005    /// operation record before the first agent event can be produced.
1006    ///
1007    /// # Errors
1008    ///
1009    /// Returns an error if invocation setup fails before the stream is created.
1010    /// Session lookup and agent execution failures are yielded by the returned
1011    /// stream.
1012    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        // The runner's policy and kill switch govern every run, including one started with
1034        // its own config; the config travels into transfers and agent tools with them.
1035        if run_config.tool_policy.is_none() {
1036            run_config.tool_policy = self.tool_policy.clone();
1037        }
1038        // A run's own egress policy narrows the runner's ceiling; it never replaces it.
1039        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        // Each run counts against fresh counters unless the caller supplied a tracker to share.
1061        // Transfer targets, workflow sub-agents and agent tools inherit it through the config.
1062        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        // Plugin model and tool callbacks run inside the agent, which reaches them through the
1069        // run config; transfer targets and agent tools inherit the config, and with it the hooks.
1070        #[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        // Agents, compaction, sampling and routing read the estimate from the config.
1078        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        // A run's own request context replaces the runner's, and authenticates only the run's
1085        // user (spec 3.1 §9.2 I6).
1086        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        // No run starts for a subject being erased, and its spans name the user only with
1104        // consent for analytics.
1105        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        // The compactor the run's agents call before each model call, unless the run brings
1117        // its own or turns compaction off.
1118        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        // Built once and used for every persistence write, so a backend with a
1126        // composite natural key can bind each event to its tenant.
1127        let identity =
1128            adk_core::AdkIdentity::new(typed_app_name.clone(), user_id.clone(), session_id.clone());
1129
1130        // Register this run for the interrupt API. The registration is keyed by a
1131        // unique run ID rather than the raw session ID: two identities can share a
1132        // session ID, and one identity can have two runs in flight, and both cases
1133        // previously overwrote each other's token.
1134        //
1135        // A child of the global token fires when either the global token or this run's
1136        // interrupt does, with no watcher task to outlive the run; dropping the run's
1137        // last handle detaches the child from the global token.
1138        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        // Built here rather than inside the generator: registration happens as soon
1162        // as `run` is called, so deregistration must also survive a stream that is
1163        // dropped before it is ever polled. Moving the guard into the generator
1164        // keeps it alive exactly as long as the stream.
1165        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            // A frozen runner refuses new work before touching the session.
1185            if let Err(error) = run_config.check_governance() {
1186                yield Err(error);
1187                return;
1188            }
1189
1190            // Read per run, so a rotating workload identity is current; the agent id is
1191            // stable across redeploys while the instance may change. The subject is pinned
1192            // to the session's user before any agent runs.
1193            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            // Use the effective token (combines global + per-session)
1203            let cancellation_token = effective_token;
1204            // Resolve the existing session.
1205            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            // An archived session is read-only: no turn adds to it until it is unarchived.
1222            if let Err(error) = adk_session::ensure_writable(session.as_ref()) {
1223                yield Err(error);
1224                return;
1225            }
1226
1227            // A saved message that was never screened — saved by an earlier release, or
1228            // appended to the session directly — is screened before any model sees it.
1229            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            // Find which agent should handle this request
1244            let agent_to_run = Self::find_agent_to_run(&root_agent, session.as_ref());
1245
1246            // A resumed sub-agent gets the same parent and peer targets as on the
1247            // transfer path, so it can still hand the conversation on.
1248            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            // Let validated composite roots apply policy for the concrete agent
1261            // selected for this turn. Ordinary agents keep the default no-op.
1262            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            // Clone services for potential reuse in transfer
1271            #[cfg(feature = "artifacts")]
1272            let artifact_service_clone = artifact_service.clone();
1273            let memory_service_clone = memory_service.clone();
1274
1275            // Create invocation context with MutableSession
1276            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            // Add optional services
1328            #[cfg(feature = "artifacts")]
1329            if let Some(service) = artifact_service {
1330                // Wrap service with ScopedArtifacts to bind session context
1331                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            // Agents compact their history through the run config, and each compaction is
1344            // recorded in this run's session.
1345            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            // Apply run config (streaming mode, etc.)
1358            invocation_ctx = invocation_ctx
1359                .with_run_config(run_config.clone())
1360                .with_steering_inbox(steering_inbox.clone());
1361
1362            // Apply request context from auth middleware bridge if present
1363            if let Some(rc) = request_context.clone() {
1364                invocation_ctx = invocation_ctx.with_request_context(rc);
1365            }
1366
1367            // Expose cooperative cancellation to the agent/tools.
1368            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            // From here on the run has started, so the finishing stage runs `after_run`.
1374            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            // Every agent in the tree screens the message before it is saved, so the session,
1488            // and every later run, holds only what the guardrails let through. A blank turn,
1489            // which only resumes held calls, carries nothing to screen.
1490            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            // Append user message to session service (persistent storage)
1515            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            // Also add to mutable session for immediate visibility
1521            // Note: adk_session::Event is a re-export of adk_core::Event, so we can use it directly
1522            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            // ===== CONTEXT CACHE LIFECYCLE =====
1535            // If context caching is configured and a cache-capable model is available,
1536            // create or refresh the cached content before agent execution.
1537            // Cache failures are non-fatal — log a warning and proceed without cache.
1538            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                    // Gather system instruction from the agent's description
1546                    // (the full instruction is resolved inside the agent, but the
1547                    // description provides a reasonable proxy for cache keying).
1548                    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                            // A model error can echo the cached instruction.
1572                            tracing::warn!(
1573                                error = %e.diagnostics(),
1574                                "cache creation failed, proceeding without cache"
1575                            );
1576                        }
1577                    }
1578                }
1579
1580                // Attach cache name to run config so agents can use it.
1581                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                    // Rebuild the invocation context with the updated run config.
1593                    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            // Run the agent with instrumentation (ADK-Go style attributes)
1640            // The GenAI `invoke_agent` span of an in-process agent; the tracing name and the
1641            // `gcp.vertex.agent.*` fields stay for the in-process debug exporter.
1642            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(), // Use invocation_id as event_id for agent spans
1652                "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            // Stream events and check for transfers
1676            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                // Race the next event against cancellation so an in-flight
1684                // await (LLM streaming, tool I/O) is interrupted promptly
1685                // rather than only at poll boundaries. Dropping the stream on
1686                // cancellation releases the underlying provider connection.
1687                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                            // Instrument the poll, not just the construction of the
1697                            // stream: `agent_to_run.run(..)` merely builds the
1698                            // stream, so without this every span created while the
1699                            // stream is drained — i.e. the whole agent execution —
1700                            // is created outside `agent_span`.
1701                            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                        // Read before plugins see the event, so one that rewrites it cannot
1710                        // leave the message's receipt waiting.
1711                        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                        // Counts usage from agents that call models directly and
1735                        // audits the budget after every event.
1736                        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                        // Check for transfer action
1742                        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                        // CRITICAL: Apply state_delta to the mutable session immediately.
1766                        // This is the key fix for state propagation between sequential agents.
1767                        // When an agent sets output_key, it emits an event with state_delta.
1768                        // We must apply this to the mutable session so downstream agents
1769                        // can read the value via ctx.session().state().get().
1770                        if !event.actions.state_delta.is_empty() {
1771                            ctx.mutable_session().apply_state_delta(&event.actions.state_delta);
1772                        }
1773
1774                        // Also add the event to the mutable session's event list
1775                        ctx.mutable_session().append_event(event.clone());
1776
1777                        // Append event to session service (persistent storage)
1778                        // Skip partial streaming chunks — only persist the final
1779                        // event. Streaming chunks share the same event ID, so
1780                        // persisting each one would violate the primary key
1781                        // constraint. The final chunk (partial=false) carries the
1782                        // complete accumulated content.
1783                        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            // ===== TRANSFER LOOP =====
1812            // Support multi-hop transfers with a max-depth guard.
1813            // When an agent emits transfer_to_agent, the runner resolves the
1814            // target from the root agent tree, computes transfer_targets
1815            // (parent + peers) for the new agent, and runs it. This repeats
1816            // until no further transfer is requested or the depth limit is hit.
1817            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                // Compute transfer_targets for the target agent:
1891                // - parent: the agent that transferred to it (or root if applicable)
1892                // - peers: siblings in the agent tree
1893                // - children: handled by the agent itself via sub_agents()
1894                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                // For transfers, we reuse the same mutable session to preserve state
1914                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                // Run the transferred agent
1964                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                // Stream events from the transferred agent, capturing any further transfer
1973                while let Some(result) = {
1974                    // Race the next event against cancellation for prompt
1975                    // mid-await interruption of the transferred agent.
1976                    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                            // Capture further transfer requests
2025                            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                            // Apply state delta for transferred agent too
2050                            if !event.actions.state_delta.is_empty() {
2051                                transfer_ctx.mutable_session().apply_state_delta(&event.actions.state_delta);
2052                            }
2053
2054                            // Add to mutable session
2055                            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                // Stops the interrupted tool before its calls are answered.
2088                drop(agent_stream);
2089                if let Some(trail) = &run_config.audit {
2090                    // The run is already over, so a failed write is logged by the trail.
2091                    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            // ===== CONTEXT COMPACTION =====
2132            // After all events have been processed, check if compaction should trigger.
2133            // This runs in the background after the invocation completes.
2134            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                    // A steering message joins the run it reached, so it starts no invocation.
2140                    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                        // Determine the window of events to compact
2149                        // We compact all events except the most recent overlap_size invocations
2150                        let overlap = compaction_cfg.overlap_size as usize;
2151
2152                        // Find the boundary: keep the last `overlap` user messages and everything after
2153                        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                        // Keep the last `overlap` user messages intact.
2160                        // When overlap is 0, compact everything.
2161                        let compact_up_to = if overlap == 0 {
2162                            all_events.len()
2163                        } else if user_msg_indices.len() > overlap {
2164                            // Compact up to (but not including) the overlap-th-from-last user message
2165                            user_msg_indices[user_msg_indices.len() - overlap]
2166                        } else {
2167                            // Not enough user messages to satisfy overlap — skip compaction
2168                            0
2169                        };
2170                        // A held call must stay visible for its approval to resume it, and the
2171                        // cut never separates a function response from its call.
2172                        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                                // A summary that is not smaller than what it replaces would
2187                                // not shrink later requests.
2188                                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                                    // Persist the compaction event
2203                                    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                                    // Compaction failure is non-fatal — log and continue
2222                                    tracing::warn!(error = %e.diagnostics(), "Context compaction failed");
2223                                }
2224                            }
2225                        }
2226                    }
2227                }
2228            }
2229
2230        };
2231
2232        // Every run ends here, however the run stream ends: a run stopped by its budget ends
2233        // with an event that explains why, persisted like any other and followed by the
2234        // structured `ResourceExhausted` error, and `after_run` runs once the run is over.
2235        // Boxed before the finishing stream takes it, so polling that stream does not copy the
2236        // whole run state onto the stack.
2237        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            // The agent's streams are released before the run is finished.
2260            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    /// Convenience method that accepts string arguments.
2289    ///
2290    /// Converts `user_id` and `session_id` to their typed equivalents
2291    /// and delegates to [`run()`](Self::run).
2292    ///
2293    /// # Errors
2294    ///
2295    /// Returns an error if either string fails identity validation
2296    /// (empty, contains null bytes, or exceeds length limit).
2297    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    /// Interrupt a running agent for the given session.
2309    ///
2310    /// Cancels the agent's current execution within the event loop. Events
2311    /// already produced and appended to the session are preserved — only
2312    /// future events are stopped. The caller can then issue a new `run()`
2313    /// call with a different instruction to redirect the agent.
2314    ///
2315    /// Returns `true` if a running session was found and interrupted,
2316    /// `false` if no active run exists for that session ID.
2317    ///
2318    /// # Example
2319    ///
2320    /// ```rust,ignore
2321    /// // Start a run in the background
2322    /// let mut stream = runner.run(user_id, session_id, content).await?;
2323    /// tokio::spawn(async move { while stream.next().await.is_some() {} });
2324    ///
2325    /// // Later, interrupt it
2326    /// let was_running = runner.interrupt("session-1");
2327    /// assert!(was_running);
2328    ///
2329    /// // Redirect with a new instruction
2330    /// let mut stream = runner.run(user_id, session_id, new_content).await?;
2331    /// ```
2332    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    /// Requests cancellation of the session's unfinished durable runs in the background.
2353    ///
2354    /// `interrupt` is synchronous, so the store write runs on a spawned task; callers that
2355    /// need the outcome use [`Runner::cancel_durable_runs`].
2356    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    /// Requests cancellation of every unfinished durable run of this app for the session,
2375    /// and returns how many were asked to stop.
2376    ///
2377    /// Queued and waiting runs are cancelled at once; a running run is flagged, and the
2378    /// worker that owns it stops it on its next heartbeat. Returns 0 when the runner has
2379    /// no [`durable_runs`](RunnerConfig::durable_runs) store.
2380    ///
2381    /// # Errors
2382    ///
2383    /// Returns the run store's error.
2384    ///
2385    /// # Example
2386    ///
2387    /// ```rust,ignore
2388    /// let asked = runner.cancel_durable_runs("user-1", "session-1").await?;
2389    /// ```
2390    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    /// Answers every function call in the session that has no response, from the action
2404    /// ledger, and returns how many were answered.
2405    ///
2406    /// A process that stops mid-tool leaves its call unanswered. Before a recovered run
2407    /// continues the session, this appends one response per such call, keyed by the
2408    /// call's original [idempotency key](adk_core::ToolContext::idempotency_key):
2409    ///
2410    /// | Ledger record | Response |
2411    /// |---------------|----------|
2412    /// | Completed with a value | `already_succeeded` with the result digest |
2413    /// | Completed with an error | `already_failed` with the error |
2414    /// | Begun, no outcome; or none | [`outcome_unknown`](adk_core::outcome_unknown_response) |
2415    ///
2416    /// No tool executes: a call the model wants again is a new call with a new
2417    /// idempotency key. The ledger consulted is the runner's
2418    /// [`action_ledger`](RunnerConfig::action_ledger), falling back to its run config's.
2419    ///
2420    /// # Errors
2421    ///
2422    /// Returns the session or ledger error.
2423    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    /// [`recover_unanswered_calls`](Self::recover_unanswered_calls), recording the
2428    /// recovered calls under the identity `run_config` resolves to rather than the
2429    /// runner's configured one.
2430    ///
2431    /// A durable worker passes the config it continues the run with, so the recovery
2432    /// records name the same subject as the run's other records.
2433    ///
2434    /// # Errors
2435    ///
2436    /// Returns the session or ledger error, or `identity.subject_mismatch` when
2437    /// `run_config` asks to act for a subject the runner does not allow.
2438    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        // Recorded before the calls are answered, so a refused write leaves them for the
2467        // next recovery rather than resolved without a record.
2468        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                        // Refused by the kill switch between the ledger write and the
2486                        // execution: it never ran.
2487                        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    /// Interrupts runs for one exact identity.
2520    ///
2521    /// A session ID is only unique within an app and user, so this is the precise
2522    /// form of [`Runner::interrupt`] for a `Runner` shared across tenants.
2523    /// Returns `true` when at least one run was cancelled.
2524    ///
2525    /// # Example
2526    ///
2527    /// ```rust,ignore
2528    /// let cancelled = runner.interrupt_identity("my-app", "user-1", "session-1");
2529    /// ```
2530    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    /// Sends `content` to the run in flight for `identity`, which takes it at its next safe
2554    /// point instead of after the turn ends.
2555    ///
2556    /// The message is screened as a run's own message is: the plugins' `on_user_message`,
2557    /// then the agent tree's input guardrails ([`Agent::screen_user_input`]). What they let
2558    /// through is queued on the run's [`SteeringInbox`](adk_core::SteeringInbox). An
2559    /// `LlmAgent` or `CodeActAgent` takes the queue after a tool step's results are in its
2560    /// history and before its next model call, and yields each message as a user-authored
2561    /// event carrying a [`SteeringMarker`](adk_core::SteeringMarker), which the runner saves
2562    /// like any other event. A turn that ends with a direct answer takes none. Workflow
2563    /// members and transfer targets of the run share its queue; `ParallelAgent` branches do
2564    /// not take it, so a message sent during a fan-out waits for the first safe point after
2565    /// the join. With several runs in flight for `identity`, the most recently started one
2566    /// receives the message.
2567    ///
2568    /// The receipt resolves to [`SteerOutcome::Delivered`](adk_core::SteerOutcome::Delivered)
2569    /// once the runner saves the message's event, or to
2570    /// [`SteerOutcome::Returned`](adk_core::SteerOutcome::Returned) with the message as sent
2571    /// when the run ends first — it finished, failed, was frozen or interrupted, reached
2572    /// `max_iterations` or held a call. Send a returned message as the session's next message,
2573    /// which the runner screens as it screens any.
2574    ///
2575    /// # Errors
2576    ///
2577    /// | Code | When |
2578    /// |------|------|
2579    /// | `agent.steer.invalid_message` | `content` is not role `user` with text or attachments only |
2580    /// | `agent.steer.no_active_run` | No run is in flight for `identity` |
2581    /// | `agent.steer.run_not_ready` | Plugins are configured and the run has not built its context yet, or has finished |
2582    /// | The guardrail's or plugin's code | An input guardrail blocks the message, or a plugin fails |
2583    ///
2584    /// # Example
2585    ///
2586    /// ```rust,ignore
2587    /// use adk_core::{AdkIdentity, AppName, Content, SessionId, SteerOutcome, UserId};
2588    ///
2589    /// let identity = AdkIdentity::new(
2590    ///     AppName::try_from("support")?,
2591    ///     UserId::try_from("alice")?,
2592    ///     SessionId::try_from("session-1")?,
2593    /// );
2594    /// let receipt = runner
2595    ///     .steer(&identity, Content::new("user").with_text("use the staging database"))
2596    ///     .await?;
2597    /// match receipt.outcome().await? {
2598    ///     SteerOutcome::Delivered { event_id } => println!("delivered as {event_id}"),
2599    ///     SteerOutcome::Returned(message) => {
2600    ///         let _next_turn = runner.run(identity.user_id.clone(), identity.session_id.clone(), message);
2601    ///     }
2602    /// }
2603    /// ```
2604    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        // A returned message goes back as sent, so the next run's screening applies once.
2636        #[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    /// Returns the identity of every run currently in flight.
2682    ///
2683    /// One identity appears once per in-flight run, so a repeated entry means that
2684    /// identity has concurrent runs.
2685    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    /// Records this runner's runs in `activity` instead of a registry of its own, so a
2691    /// [`HistoryControl`](crate::HistoryControl) over another runner, or over the sessions
2692    /// alone, sees them.
2693    ///
2694    /// Set it before the first run.
2695    #[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    /// The registry this runner records its runs in.
2702    pub fn session_activity(&self) -> &crate::history::SessionActivity {
2703        &self.session_activity
2704    }
2705
2706    /// Fork, rewind, and edit of this runner's sessions under the runtime's rules: refused
2707    /// while a run of this runner, or of any runner sharing its
2708    /// [`session_activity`](Self::session_activity), is on the session, and recorded in the
2709    /// runner's audit trail. The runner's durable run store, when set, also refuses sessions a
2710    /// worker is running.
2711    ///
2712    /// # Example
2713    ///
2714    /// ```rust,ignore
2715    /// use adk_core::audit_log::AuditActor;
2716    /// use adk_core::principal::SubjectRef;
2717    /// use adk_session::ForkRequest;
2718    ///
2719    /// let actor = AuditActor::subject(SubjectRef::human("alice"));
2720    /// let fork = runner
2721    ///     .history_control()
2722    ///     .fork(&actor, ForkRequest::new(identity).at_event(event_id))
2723    ///     .await?;
2724    /// ```
2725    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    /// Returns the session IDs of all currently running agent executions.
2738    ///
2739    /// Session IDs are deduplicated. Use [`Runner::active_runs`] when the app and
2740    /// user dimensions matter.
2741    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    /// Returns a reference to the context compaction configuration, if set.
2751    ///
2752    /// Auto-compaction applies its strategy in place of a summary.
2753    #[cfg(feature = "context-compaction")]
2754    pub fn context_compaction(&self) -> Option<&crate::compaction::CompactionConfig> {
2755        self.context_compaction.as_deref()
2756    }
2757
2758    /// The compactor a run's agents use: from `run`, the run's own setting, or the runner's,
2759    /// with the runner's summarizer or strategy; `None` when compaction is off.
2760    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    /// Find which agent should handle the request based on session history
2783    pub fn find_agent_to_run(
2784        root_agent: &Arc<dyn Agent>,
2785        session: &dyn adk_session::Session,
2786    ) -> Arc<dyn Agent> {
2787        // Look at recent events to find last agent that responded
2788        let events = session.events();
2789        for i in (0..events.len()).rev() {
2790            if let Some(event) = events.at(i) {
2791                // Check for explicit transfer
2792                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                // Try to find this agent in the tree
2803                if let Some(agent) = Self::find_agent(root_agent, &event.author) {
2804                    // Check if agent allows transfer up the tree
2805                    if Self::is_transferable(root_agent, &agent) {
2806                        return agent;
2807                    }
2808                }
2809            }
2810        }
2811
2812        // Default to root agent
2813        root_agent.clone()
2814    }
2815
2816    /// Check if an agent found in session history can be resumed directly for
2817    /// the next user message.
2818    ///
2819    /// An agent is a valid direct-resumption target only if it *and* every
2820    /// ancestor up to the root permit agent transfer
2821    /// ([`Agent::supports_agent_transfer`]). A deterministic workflow agent
2822    /// (sequential, parallel, loop, conditional) anywhere on that path returns
2823    /// `false`, which forces resumption to restart from the workflow root
2824    /// rather than a single sub-agent that happened to respond last. This
2825    /// mirrors Google ADK's `_is_transferable_across_agent_tree`.
2826    ///
2827    /// LLM-driven transfer-policy enforcement
2828    /// (`disallow_transfer_to_parent` / `disallow_transfer_to_peers`) is still
2829    /// handled inside `LlmAgent::run()` when it builds the `transfer_to_agent`
2830    /// tool's valid-target list; this check only governs cross-turn resumption.
2831    fn is_transferable(root_agent: &Arc<dyn Agent>, agent: &Arc<dyn Agent>) -> bool {
2832        // Walk the tree from the root down to the target. Every agent on that
2833        // path (root through target, inclusive) must support transfer for the
2834        // target to be a valid direct-resumption point. `Some(true)` = found
2835        // and fully transferable, `Some(false)` = found but a workflow agent
2836        // sits on the path, `None` = target not present in this subtree.
2837        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    /// The agent a transfer request in an event comes from: the event's author when it is in
2853    /// the tree, else the agent the runner is running.
2854    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    /// The agents `source` may hand control to, or `None` when `source` is not in the tree.
2863    ///
2864    /// A composite root with an explicit topology decides for its members. Otherwise an agent
2865    /// may transfer to its sub-agents, to its parent unless
2866    /// [`Agent::allows_transfer_to_parent`] says no, and to its parent's other sub-agents
2867    /// unless [`Agent::allows_transfer_to_peers`] says no: the targets `LlmAgent` offers its
2868    /// model. Every transfer is checked, whether a model or a tool requested it.
2869    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    /// Recursively search agent tree for agent with given name
2889    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    /// The description of each agent named in `names`, found in the tree under `root`.
2904    /// A name the tree does not hold, or an agent without a description, is left out.
2905    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    /// Compute the parent name and peer names for a given agent in the tree.
2931    /// Returns `(parent_name, peer_names)`.
2932    ///
2933    /// Walks the agent tree to find the parent of `target_name`, then collects
2934    /// the parent's name and the sibling agent names (excluding the target itself).
2935    pub fn compute_transfer_context(
2936        root: &Arc<dyn Agent>,
2937        target_name: &str,
2938    ) -> (Option<String>, Vec<String>) {
2939        // If the target is the root itself, there's no parent or peers
2940        if root.name() == target_name {
2941            return (None, Vec::new());
2942        }
2943
2944        // BFS/DFS to find the parent of target_name
2945        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
3008/// The unfinished durable runs of `app_name` continuing `session_id`.
3009fn 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        // A partial chunk never opens a call.
3073        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    /// #1006 left the runner's answers without a status, so a cancelled call read as the
3105    /// tool's own result.
3106    #[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}