Skip to main content

gadk_engine/runner/
mod.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The runner (context compaction is in `compaction`, live mode is in `live`): [`Runner`],
17//! [`RunnerConfig`], [`PluginConfig`], [`RunOptions`].
18
19pub(crate) mod agent_node;
20pub(crate) mod compaction;
21pub(crate) mod find_agent;
22pub(crate) mod live;
23pub(crate) mod run_node;
24
25use std::sync::Arc;
26use std::time::Duration;
27
28use futures::StreamExt;
29use gadk_agent::fiber::FiberStream;
30use gadk_agent::{
31    Agent, AgentError, Context, ContextDelta, EventStream, InvocationContext, Mode, ParentMap,
32    Plugin, PluginManager, RunConfig,
33};
34use gadk_genai::{Content, Part};
35use gadk_platform::Platform;
36use gadk_session::{CreateRequest, Event, EventCompaction, GetRequest, Session, SessionService};
37use serde_json::{Map, Value};
38use tokio_util::sync::CancellationToken;
39
40use crate::llm::agent::underlying_session;
41use crate::llm::mode::resolve_mode;
42use crate::llm::state::reveal;
43use find_agent::find_active_task_isolation_scope;
44use run_node::is_llm_agent;
45
46/// The `custom_metadata` key that marks an event as a before-run reply.
47pub const BEFORE_RUN_REPLY_KEY: &str = "adk:before_run_reply";
48
49/// Configuration for a [`Runner`].
50#[derive(Clone)]
51pub struct RunnerConfig {
52    /// The application name sessions are scoped to.
53    pub app_name: String,
54    /// The root agent, which starts the execution.
55    pub agent: Arc<dyn Agent>,
56    /// The session service.
57    pub session_service: Arc<dyn SessionService>,
58    /// Optional artifact service.
59    pub artifact_service: Option<Arc<dyn gadk_artifact::ArtifactService>>,
60    /// Optional memory service.
61    pub memory_service: Option<Arc<dyn gadk_memory::MemoryService>>,
62    /// Plugins and their close timeout.
63    pub plugin_config: PluginConfig,
64    /// Create the session on `run` / `run_live` when it does not exist: when the session ID is
65    /// empty (the service generates one) or when the session service's `get` reports
66    /// `SessionError::NotFound`. Any other `get` error is returned as is, so a transient storage
67    /// failure never replaces an existing session.
68    pub auto_create_session: bool,
69    /// Clock and ID source.
70    pub platform: Platform,
71    /// Context compaction for the sessions this runner drives; `None` disables it. A config without
72    /// a summarizer gets an [`LlmSummarizer`] over the root agent's model, which then has to be an
73    /// LLM agent.
74    ///
75    /// [`LlmSummarizer`]: gadk_session::compaction::LlmSummarizer
76    pub compaction: Option<gadk_session::compaction::Config>,
77}
78
79/// The plugins a [`Runner`] applies and how long it waits for them to close.
80#[derive(Clone, Default)]
81pub struct PluginConfig {
82    /// The plugins, in registration order.
83    pub plugins: Vec<Plugin>,
84    /// How long [`Runner::close`] waits for the plugins to close.
85    pub close_timeout: Duration,
86}
87
88/// Per-run options: `state_delta` and `yield_user_message` (honored by the node path only).
89#[derive(Clone, Default)]
90pub struct RunOptions {
91    /// State delta attached to the user message event.
92    pub state_delta: Option<Map<String, Value>>,
93    /// Yield the appended user message event before any agent event (node path only).
94    pub yield_user_message: bool,
95}
96
97/// Runs the agent tree within a session, persisting events and driving plugins.
98pub struct Runner {
99    inner: Arc<RunnerInner>,
100}
101
102pub(crate) struct RunnerInner {
103    app_name: String,
104    root_agent: Arc<dyn Agent>,
105    session_service: Arc<dyn SessionService>,
106    artifact_service: Option<Arc<dyn gadk_artifact::ArtifactService>>,
107    memory_service: Option<Arc<dyn gadk_memory::MemoryService>>,
108    parents: Arc<ParentMap>,
109    plugin_manager: Arc<PluginManager>,
110    auto_create_session: bool,
111    platform: Platform,
112    /// A validated copy of [`RunnerConfig::compaction`] with the summarizer resolved; `None`
113    /// when compaction is disabled.
114    compaction: Option<Arc<gadk_session::compaction::Config>>,
115}
116
117/// An error with a context prefix; displays as `<context>: <source>` and keeps the source chain.
118#[derive(Debug)]
119struct Wrapped {
120    context: String,
121    source: Box<dyn std::error::Error + Send + Sync>,
122}
123
124impl std::fmt::Display for Wrapped {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        write!(f, "{}: {}", self.context, self.source)
127    }
128}
129
130impl std::error::Error for Wrapped {
131    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
132        Some(&*self.source)
133    }
134}
135
136/// Wraps `source` with a context prefix: the message is `<context>: <source>` and the source chain
137/// stays walkable.
138pub(crate) fn wrap(
139    context: impl Into<String>,
140    source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
141) -> AgentError {
142    AgentError::Other(Box::new(Wrapped {
143        context: context.into(),
144        source: source.into(),
145    }))
146}
147
148/// Whether `err`, or anything in its source chain, is an LLM-calls-limit error.
149fn is_llm_calls_limit(err: &AgentError) -> bool {
150    let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
151    while let Some(e) = cur {
152        if matches!(
153            e.downcast_ref::<AgentError>(),
154            Some(AgentError::LlmCallsLimitExceeded { .. })
155        ) {
156            return true;
157        }
158        cur = e.source();
159    }
160    false
161}
162
163/// Whatever the plugin returns, the framework's compaction record wins. A replacement also keeps
164/// the identity of the event it replaces: its ID, invocation ID and timestamp, and its author when
165/// the replacement names none; its other fields win as given. The plugin's own copy is never
166/// written to (it handed the replacement over by value).
167pub(crate) fn from_plugin(
168    original: Event,
169    modified: Option<Event>,
170    record: Option<EventCompaction>,
171) -> Event {
172    let Some(mut out) = modified else {
173        let mut ev = original;
174        ev.actions.compaction = record;
175        return ev;
176    };
177    out.actions.compaction = record;
178    out.id = original.id;
179    out.invocation_id = original.invocation_id;
180    out.timestamp = original.timestamp;
181    if out.author.is_empty() {
182        out.author = original.author;
183    }
184    out
185}
186
187/// An event without a timestamp (an agent yielded one built without `Event::new`, or a plugin left
188/// one without it) gets the time the runner received it, so a stored event never moves the
189/// session's last update time back to year 1.
190pub(crate) fn stamp_timestamp(ctx: &InvocationContext, event: &mut Event) {
191    if event.timestamp == gadk_session::zero_time() {
192        event.timestamp = ctx.platform().now();
193    }
194}
195
196/// The error for a user message containing function calls: only a model makes function calls, so
197/// storing one from a user message would put a call no model produced into the history.
198pub(crate) const ERR_USER_FUNCTION_CALL: &str = "user message cannot contain function calls";
199
200/// Whether the content holds any function call.
201pub(crate) fn has_function_call(content: Option<&Content>) -> bool {
202    !crate::tool::utils::function_calls(content).is_empty()
203}
204
205/// The inbound message of a run is a user turn whatever role the caller (or an `on_user_message`
206/// plugin) set, so the role becomes `user`. An empty role would be skipped when the model request
207/// is built, and a `model` role would present the caller's text as the model's own earlier turn.
208/// The caller's message is not modified (it is handed over by value).
209fn as_user_content(msg: Option<Content>) -> Option<Content> {
210    msg.map(|mut m| {
211        m.role = gadk_genai::ROLE_USER.to_string();
212        m
213    })
214}
215
216/// Outcome of the per-event pipeline shared by both run paths.
217pub(crate) enum Processed {
218    /// The (possibly plugin-replaced) event, persisted unless partial: yield it.
219    Event(Box<Event>),
220    /// An `on_event` plugin failed: yield the error and continue.
221    PluginError(AgentError),
222    /// Persisting failed: yield the error and end the run.
223    AppendError(AgentError),
224}
225
226impl Runner {
227    /// Builds a runner from `cfg`.
228    pub fn new(cfg: RunnerConfig) -> Result<Runner, AgentError> {
229        Self::new_with_summarizer_timeout(cfg, compaction::DEFAULT_SUMMARIZER_TIMEOUT)
230    }
231
232    /// [`Runner::new`] with the default summarizer's timeout overridden (a test seam).
233    pub(crate) fn new_with_summarizer_timeout(
234        cfg: RunnerConfig,
235        summarizer_timeout: Duration,
236    ) -> Result<Runner, AgentError> {
237        let parents =
238            ParentMap::new(&cfg.agent).map_err(|e| wrap("failed to create agent tree", e))?;
239        let plugin_manager =
240            PluginManager::new(cfg.plugin_config.plugins, cfg.plugin_config.close_timeout)
241                .map_err(|e| wrap("failed to create plugin manager", e))?;
242        let compaction = compaction::resolve_compaction_config(
243            cfg.compaction.as_ref(),
244            &cfg.agent,
245            summarizer_timeout,
246        )?;
247        Ok(Runner {
248            inner: Arc::new(RunnerInner {
249                app_name: cfg.app_name,
250                root_agent: cfg.agent,
251                session_service: cfg.session_service,
252                artifact_service: cfg.artifact_service,
253                memory_service: cfg.memory_service,
254                parents: Arc::new(parents),
255                plugin_manager: Arc::new(plugin_manager),
256                auto_create_session: cfg.auto_create_session,
257                platform: cfg.platform,
258                compaction,
259            }),
260        })
261    }
262
263    /// In-memory session, artifact and memory services with session auto-creation, for local
264    /// development and tests.
265    pub fn in_memory(app_name: &str, agent: Arc<dyn Agent>) -> Result<Runner, AgentError> {
266        Runner::new(RunnerConfig {
267            app_name: app_name.to_string(),
268            agent,
269            session_service: Arc::new(gadk_session::InMemorySessionService::new()),
270            artifact_service: Some(Arc::new(gadk_artifact::InMemoryArtifactService::new())),
271            memory_service: Some(Arc::new(gadk_memory::InMemoryMemoryService::new())),
272            plugin_config: PluginConfig::default(),
273            auto_create_session: true,
274            platform: Platform::default(),
275            compaction: None,
276        })
277    }
278
279    /// Runs the agent for `msg` (`None` for no new message) in the session, yielding its events.
280    /// Dropping the returned stream ends the invocation, depending on where it is dropped:
281    ///
282    /// - Dropped at a yield (the consumer stopped reading): work the run had already started
283    ///   (in-flight tool calls, ParallelAgent branches, workflow node tasks) is finished first
284    ///   (each component cancels it plainly and hands it to the invocation's
285    ///   [`gadk_agent::Teardowns`]), then the after-run callbacks run on a spawned task with the
286    ///   invocation's context still live, and only then is the invocation cancelled.
287    /// - Dropped inside an await (the run was still waiting on a model call, tool or append): the
288    ///   invocation is cancelled at once; started work still finishes before the after-run
289    ///   callbacks, which see the cancellation.
290    ///
291    /// Started work is never aborted, so a tool that ignores cancellation runs to completion and
292    /// delays the after-run callbacks until it returns.
293    ///
294    /// With compaction configured, a sliding-window compaction runs after the invocation's events
295    /// are persisted: inline when the stream ends (its error, if any, is the last item), or on a
296    /// spawned task after the after-run callbacks when the stream is dropped early, in which case
297    /// its error is logged. Dropping the stream does not cancel that task.
298    ///
299    /// The stream runs on the consumer's fiber ([`FiberStream::consumer`]: the one current at its
300    /// first poll, else a new root it keeps); the after-run callbacks of a stream dropped early
301    /// re-enter that fiber.
302    pub fn run(
303        &self,
304        user_id: &str,
305        session_id: &str,
306        msg: Option<Content>,
307        cfg: RunConfig,
308        opts: RunOptions,
309    ) -> EventStream {
310        self.run_inner(None, user_id, session_id, msg, cfg, opts)
311    }
312
313    /// [`Runner::run`] started from a caller's context; only the context's plugin-inheritance mark
314    /// is read ([`InvocationContext::with_inherited_plugins`]).
315    ///
316    /// A runner with no plugins of its own, started with a context the agent tool marked, puts the
317    /// marked (calling run's) plugin manager in its invocation context, so those plugins also see
318    /// the sub-run's agents, models and tools. Any other runner uses only its own plugins. The mark
319    /// is taken, so it applies to this runner only. Run-level callbacks (`on_user_message`,
320    /// `before_run`, `on_event`, `after_run`) always stay with this runner's own plugins.
321    pub fn run_with_context(
322        &self,
323        ctx: &InvocationContext,
324        user_id: &str,
325        session_id: &str,
326        msg: Option<Content>,
327        cfg: RunConfig,
328        opts: RunOptions,
329    ) -> EventStream {
330        let (_, inherited) = ctx.take_inherited_plugins();
331        self.run_inner(inherited, user_id, session_id, msg, cfg, opts)
332    }
333
334    fn run_inner(
335        &self,
336        inherited: Option<Arc<PluginManager>>,
337        user_id: &str,
338        session_id: &str,
339        msg: Option<Content>,
340        cfg: RunConfig,
341        opts: RunOptions,
342    ) -> EventStream {
343        let inner = self.inner.clone();
344        let root = inner.root_agent.clone();
345        let plugins = inner.with_plugin_manager(inherited);
346        let stream = crate::telemetry::instrumentation::instrument_invocation(
347            root.as_ref(),
348            session_id,
349            || {
350                inner.run_stream(
351                    plugins,
352                    user_id.to_string(),
353                    session_id.to_string(),
354                    msg,
355                    cfg,
356                    opts,
357                )
358            },
359        );
360        FiberStream::consumer(stream).boxed()
361    }
362
363    /// Closes every plugin.
364    pub async fn close(&self) -> Result<(), AgentError> {
365        self.inner.plugin_manager.close().await
366    }
367}
368
369impl RunnerInner {
370    /// The plugin manager the invocation context carries (where tools and callbacks look it up). A
371    /// runner without plugins keeps the `inherited` manager (taken from an agent tool's mark) when
372    /// that one has plugins; otherwise this runner's own. Run-level callbacks always use
373    /// `self.plugin_manager`.
374    pub(crate) fn with_plugin_manager(
375        &self,
376        inherited: Option<Arc<PluginManager>>,
377    ) -> Arc<PluginManager> {
378        match inherited {
379            Some(pm) if !self.plugin_manager.has_plugins() && pm.has_plugins() => pm,
380            _ => self.plugin_manager.clone(),
381        }
382    }
383
384    /// The agent path's route for a function response: the agent that made the call the first
385    /// response in `msg` answers, its branch, and `true`, when that agent is in the tree and not in
386    /// a graph workflow; else the root, `""` and `false`.
387    fn route_function_response(
388        &self,
389        stored: &dyn Session,
390        msg: Option<&Content>,
391    ) -> (Arc<dyn Agent>, String, bool) {
392        let events = stored.events();
393        if let Some(ev) = find_agent::handle_user_function_call_response(&events, msg)
394            && let Some(sub) = self.root_agent.find_agent(&ev.author)
395            && !self.is_in_graph_workflow(&sub)
396        {
397            return (sub, ev.branch.clone(), true);
398        }
399        (self.root_agent.clone(), String::new(), false)
400    }
401
402    /// Whether `a` or one of its ancestors is a graph workflow agent.
403    fn is_in_graph_workflow(&self, a: &Arc<dyn Agent>) -> bool {
404        let mut cur = Some(a.clone());
405        while let Some(x) = cur {
406            if x.agent_state().agent_type == gadk_agent::AgentType::WorkflowAgent {
407                return true;
408            }
409            cur = self.parents.parent(x.name());
410        }
411        false
412    }
413
414    /// With auto-create on, the session is created when the session ID is empty (the service
415    /// generates one; services reject an empty ID in `get` with a validation error) or when `get`
416    /// reports [`SessionError::NotFound`]. Any other `get` error is returned as is, so a transient
417    /// storage failure never replaces an existing session.
418    ///
419    /// [`SessionError::NotFound`]: gadk_session::SessionError::NotFound
420    async fn get_or_create_session(
421        &self,
422        user_id: &str,
423        session_id: &str,
424    ) -> Result<Arc<dyn Session>, AgentError> {
425        let got = self
426            .session_service
427            .get(GetRequest {
428                app_name: self.app_name.clone(),
429                user_id: user_id.into(),
430                session_id: session_id.into(),
431                ..Default::default()
432            })
433            .await;
434        match got {
435            Ok(s) => Ok(s),
436            Err(e)
437                if !self.auto_create_session
438                    || (!session_id.is_empty()
439                        && !matches!(e, gadk_session::SessionError::NotFound)) =>
440            {
441                Err(e.into())
442            }
443            Err(_) => Ok(self
444                .session_service
445                .create(CreateRequest {
446                    app_name: self.app_name.clone(),
447                    user_id: user_id.into(),
448                    session_id: Some(session_id.into()),
449                    state: None,
450                })
451                .await?),
452        }
453    }
454
455    /// An LlmAgent root takes the node path ([`run_node::run_node`]); any other root runs directly.
456    fn run_stream(
457        self: Arc<Self>,
458        plugins: Arc<PluginManager>,
459        user_id: String,
460        session_id: String,
461        msg: Option<Content>,
462        cfg: RunConfig,
463        opts: RunOptions,
464    ) -> EventStream {
465        let this = self;
466        // Normalized once, so find_agent_to_run, the invocation context and the stored event all
467        // see the same message.
468        let msg = as_user_content(msg);
469        Box::pin(async_stream::stream! {
470            let stored = match this.get_or_create_session(&user_id, &session_id).await {
471                Ok(s) => s,
472                Err(e) => { yield Err(e); return; }
473            };
474
475            // Node path: an LlmAgent root.
476            if is_llm_agent(&*this.root_agent) {
477                let Some(state) = reveal(&*this.root_agent) else {
478                    yield Err(AgentError::Config(format!(
479                        "agent {} is not an LlmAgent",
480                        this.root_agent.name()
481                    )));
482                    return;
483                };
484                // An LlmAgent root must be in chat mode.
485                let root_mode = resolve_mode(state.cfg.mode, Mode::Chat);
486                if root_mode != Mode::Chat {
487                    yield Err(AgentError::Config(format!(
488                        "root agent {} must be a chat LlmAgent, but has mode {}",
489                        this.root_agent.name(),
490                        root_mode.as_str()
491                    )));
492                    return;
493                }
494                // A chat coordinator with task-mode sub-agents delegates through its own node;
495                // the legacy sub-agent picker must not bypass it on resume.
496                let has_task_sub_agent = this
497                    .root_agent
498                    .sub_agents()
499                    .iter()
500                    .any(|s| reveal(&**s).is_some_and(|st| st.cfg.mode == Mode::Task));
501                let agent_to_run = if has_task_sub_agent {
502                    this.root_agent.clone()
503                } else {
504                    match this.find_agent_to_run(&*stored, msg.as_ref()) {
505                        Ok(a) => a,
506                        Err(e) => { yield Err(e); return; }
507                    }
508                };
509                let mut events = run_node::run_node(
510                    this.clone(),
511                    plugins,
512                    stored,
513                    agent_to_run,
514                    root_mode,
515                    msg,
516                    cfg,
517                    opts,
518                );
519                while let Some(item) = events.next().await {
520                    yield item;
521                }
522                return;
523            }
524
525            // Agent path.
526            //
527            // A function response goes back to the agent that made the call, on the branch it ran
528            // on: re-running the root would run agents that never saw the call, and they fail on
529            // the unmatched response. A call made inside a graph workflow is the exception: the
530            // root runs. The first response in the message decides the route.
531            let (agent_to_run, branch, routed_to_caller) = this.route_function_response(&*stored, msg.as_ref());
532            // Answers to calls from several invocations start a new invocation when they go back to
533            // the calling agent; otherwise the first call's invocation is kept.
534            let (mut invocation_id, spans_invocations) =
535                run_node::resolve_invocation_id(Some(&*stored), msg.as_ref());
536            if spans_invocations && routed_to_caller {
537                invocation_id = String::new();
538            }
539            let token = CancellationToken::new();
540            let cancel_on_drop = token.clone().drop_guard();
541            let ictx = this.new_invocation_context(
542                &stored,
543                agent_to_run.clone(),
544                msg.clone(),
545                &cfg,
546                &token,
547                true,
548                plugins,
549                invocation_id,
550                branch,
551            );
552            let appended = this
553                .append_message_to_session(
554                    ictx.into_context(),
555                    &stored,
556                    msg,
557                    cfg.save_input_blobs_as_artifacts,
558                    opts.state_delta.clone(),
559                )
560                .await;
561            let ctx = match appended {
562                Ok((ctx, _)) => ctx,
563                Err(e) => { yield Err(e); return; }
564            };
565            let ictx = ctx.as_invocation().clone();
566            let mut guard = compaction::InvocationGuard::new(this.clone(), stored.clone(), ictx.clone());
567            guard.cancel_on_drop(cancel_on_drop);
568            guard.defer_after_run();
569            let mut early = false;
570            'run: {
571                match this.run_before_run_callback(&ictx).await {
572                    Err(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); early = true; break 'run; }
573                    Ok(Some(ev)) => { guard.at_yield(true); yield Ok(ev); guard.at_yield(false); early = true; break 'run; }
574                    Ok(None) => {}
575                }
576                let mut events = agent_to_run.run(ictx.clone());
577                while let Some(item) = events.next().await {
578                    let event = match item {
579                        Ok(ev) => ev,
580                        Err(e) => {
581                            // The model-call budget is spent for the whole invocation, so
582                            // nothing after this can reach a model (adk-python parity).
583                            let stop = is_llm_calls_limit(&e);
584                            guard.mark_failed();
585                            guard.at_yield(true);
586                            yield Err(e);
587                            guard.at_yield(false);
588                            if stop {
589                                early = true;
590                                break 'run;
591                            }
592                            continue;
593                        }
594                    };
595                    match this.process_event(&ictx, &*stored, event).await {
596                        Processed::Event(ev) => { guard.at_yield(true); yield Ok(*ev); guard.at_yield(false); }
597                        Processed::PluginError(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); }
598                        Processed::AppendError(e) => { guard.mark_failed(); guard.at_yield(true); yield Err(e); guard.at_yield(false); early = true; break 'run; }
599                    }
600                }
601            }
602            if early {
603                guard.finish_early().await;
604            } else {
605                // Compact once every event of the invocation is persisted; the consumer
606                // drained the stream, so a failure can still be reported.
607                if let Some(e) = guard.compact_inline().await {
608                    guard.at_yield(true);
609                    yield Err(e);
610                    guard.at_yield(false);
611                }
612                guard.finish().await;
613            }
614        })
615    }
616
617    /// The per-event pipeline shared by both run paths: clear a message-as-output event's output,
618    /// run `on_event`, restore the compaction record, persist unless partial.
619    pub(crate) async fn process_event(
620        &self,
621        ctx: &InvocationContext,
622        stored: &dyn Session,
623        mut event: Event,
624    ) -> Processed {
625        stamp_timestamp(ctx, &mut event);
626        if !event.response.partial
627            && event
628                .node_info
629                .as_ref()
630                .is_some_and(|n| n.message_as_output)
631            && event.response.content.is_some()
632        {
633            event.output = None;
634        }
635        // Captured before the plugin runs.
636        let record = event.actions.compaction.clone();
637        match self
638            .plugin_manager
639            .run_on_event(ctx.clone(), event.clone())
640            .await
641        {
642            Err(e) => return Processed::PluginError(e),
643            Ok(modified) => event = from_plugin(event, modified, record),
644        }
645        // A plugin may have handed back an event without a timestamp.
646        stamp_timestamp(ctx, &mut event);
647        // Only non-partial events are committed to the session.
648        if !event.response.partial
649            && let Err(e) = self.session_service.append_event(stored, &mut event).await
650        {
651            return Processed::AppendError(wrap("failed to add event to session", e));
652        }
653        Processed::Event(Box::new(event))
654    }
655
656    /// Processes and persists a plugin's replacement reply. `Ok(None)` means: run the agent.
657    pub(crate) async fn run_before_run_callback(
658        &self,
659        ctx: &InvocationContext,
660    ) -> Result<Option<Event>, AgentError> {
661        let Some(content) = self.plugin_manager.run_before_run(ctx.clone()).await? else {
662            return Ok(None);
663        };
664        let mut event = Event::new(ctx.platform(), ctx.invocation_id());
665        // Match RunLive's attribution so later turns can resolve the agent from history.
666        event.author = ctx.agent().name().to_string();
667        event.response.content = Some(content);
668        let record = event.actions.compaction.clone();
669        let modified = self
670            .plugin_manager
671            .run_on_event(ctx.clone(), event.clone())
672            .await?;
673        let mut event = from_plugin(event, modified, record);
674        // Stamped after on_event so a replacement keeps its before-run origin; the plugin's own
675        // copy is not mutated (the event was moved/cloned out of it).
676        event
677            .response
678            .custom_metadata
679            .insert(BEFORE_RUN_REPLY_KEY.to_string(), Value::Bool(true));
680        stamp_timestamp(ctx, &mut event);
681        if !event.response.partial {
682            // Writers always use the unwrapped session.
683            let session = underlying_session(&ctx.session());
684            self.session_service
685                .append_event(&*session, &mut event)
686                .await
687                .map_err(|e| wrap("failed to add event to session", e))?;
688        }
689        Ok(Some(event))
690    }
691
692    /// Runs `on_user_message`, saves inline blobs as artifacts when asked, and appends the user
693    /// event. `None` (no message) appends nothing.
694    pub(crate) async fn append_message_to_session(
695        &self,
696        mut ctx: Context,
697        stored: &Arc<dyn Session>,
698        msg: Option<Content>,
699        save_input_blobs_as_artifacts: bool,
700        state_delta: Option<Map<String, Value>>,
701    ) -> Result<(Context, Option<Event>), AgentError> {
702        let Some(mut msg) = msg else {
703            return Ok((ctx, None));
704        };
705        let modified = self
706            .plugin_manager
707            .run_on_user_message(ctx.as_invocation().clone(), msg.clone())
708            .await
709            .map_err(|e| wrap("error running on run user message callback ", e))?;
710        if let Some(m) = modified {
711            // A plugin can return a message with any role.
712            msg = m;
713            msg.role = gadk_genai::ROLE_USER.to_string();
714            ctx = ctx.with_delta(ContextDelta {
715                user_content: Some(Some(msg.clone())),
716                ..Default::default()
717            });
718        }
719
720        if has_function_call(Some(&msg)) {
721            return Err(AgentError::other(ERR_USER_FUNCTION_CALL));
722        }
723
724        if let (Some(artifacts), true) = (ctx.artifacts(), save_input_blobs_as_artifacts) {
725            let mut replaced = false;
726            for i in 0..msg.parts.len() {
727                if msg.parts[i].inline_data.is_none() {
728                    continue;
729                }
730                let file_name = format!("artifact_{}_{}", ctx.invocation_id(), i);
731                artifacts
732                    .save(&file_name, msg.parts[i].clone())
733                    .await
734                    .map_err(|e| wrap(format!("failed to save artifact {file_name}"), e))?;
735                // Replace the part with a text placeholder.
736                msg.parts[i] = Part::from_text(format!(
737                    "Uploaded file: {file_name}. It has been saved to the artifacts"
738                ));
739                replaced = true;
740            }
741            // The context's user content is replaced with the modified message.
742            if replaced {
743                ctx = ctx.with_delta(ContextDelta {
744                    user_content: Some(Some(msg.clone())),
745                    ..Default::default()
746                });
747            }
748        }
749
750        let mut event = Event::new(ctx.platform(), ctx.invocation_id());
751        event.author = "user".to_string();
752        event.response.content = Some(msg);
753        if let Some(delta) = state_delta {
754            event.actions.state_delta = Some(delta);
755        }
756        if event.isolation_scope.is_empty() {
757            let iso = find_active_task_isolation_scope(Some(&**stored));
758            if !iso.is_empty() {
759                event.isolation_scope = iso;
760            }
761        }
762        self.session_service
763            .append_event(&**stored, &mut event)
764            .await
765            .map_err(|e| wrap("failed to append event to sessionService", e))?;
766        Ok((ctx, Some(event)))
767    }
768}
769
770#[cfg(test)]
771impl Runner {
772    pub(crate) fn session_service(&self) -> Arc<dyn SessionService> {
773        self.inner.session_service.clone()
774    }
775    pub(crate) fn has_artifact_service(&self) -> bool {
776        self.inner.artifact_service.is_some()
777    }
778    pub(crate) fn has_memory_service(&self) -> bool {
779        self.inner.memory_service.is_some()
780    }
781    pub(crate) fn auto_create_session(&self) -> bool {
782        self.inner.auto_create_session
783    }
784}