Skip to main content

gadk_agent/context/
invocation.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 invocation context: the context of one agent invocation, and the artifact wrapper that
17//! records saves into the event actions.
18
19use std::collections::BTreeMap;
20use std::ops::Deref;
21use std::sync::Arc;
22use std::sync::atomic::Ordering;
23
24use gadk_artifact::{ListResponse, LoadResponse, SaveResponse};
25use gadk_genai::Part;
26use gadk_platform::Platform;
27use gadk_session::{EventActions, Session, SessionService};
28use serde_json::Value;
29use tokio_util::sync::CancellationToken;
30
31use crate::agent::Agent;
32use crate::context::activation::ActivationId;
33use crate::context::builder::ContextBuilder;
34use crate::context::cancel::CancelCause;
35use crate::context::context::Context;
36use crate::context::delta::ContextDelta;
37use crate::context::readonly::{ContextInner, ReadonlyContext};
38use crate::error::AgentError;
39use crate::mode::BoundModes;
40use crate::parent_map::ParentMap;
41use crate::plugin_manager::PluginManager;
42use crate::run_config::RunConfig;
43use crate::run_config::run_limits::LlmCallLimiter;
44use crate::services::{ArtifactBacking, Artifacts, Memory};
45
46/// The context of one agent invocation.
47#[derive(Clone)]
48pub struct InvocationContext {
49    pub(crate) ro: ReadonlyContext,
50}
51
52impl Deref for InvocationContext {
53    type Target = ReadonlyContext;
54
55    fn deref(&self) -> &ReadonlyContext {
56        &self.ro
57    }
58}
59
60impl InvocationContext {
61    /// A [`ContextBuilder`] with documented defaults.
62    pub fn builder() -> ContextBuilder {
63        ContextBuilder::new()
64    }
65
66    pub(crate) fn from_inner(inner: ContextInner) -> Self {
67        Self {
68            ro: ReadonlyContext {
69                inner: Arc::new(inner),
70            },
71        }
72    }
73
74    /// The invocation context a [`ReadonlyContext`] views, sharing its state (no copy). For
75    /// gadk's own crates (e.g. templating an instruction provider's output); not a stable API.
76    #[doc(hidden)]
77    pub fn from_readonly(ctx: &ReadonlyContext) -> Self {
78        Self { ro: ctx.clone() }
79    }
80
81    pub(crate) fn inner(&self) -> &ContextInner {
82        &self.ro.inner
83    }
84
85    /// The current agent.
86    pub fn agent(&self) -> Arc<dyn Agent> {
87        self.inner().agent.clone()
88    }
89
90    /// The artifacts of the session: tracked (records saves into the actions' `artifact_delta`)
91    /// when the context has actions, as for callback and tool contexts; the raw handle otherwise;
92    /// `None` without an artifact service.
93    pub fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
94        let raw = self.inner().shared.artifacts.clone()?;
95        Some(match &self.inner().actions {
96            Some(a) => Arc::new(TrackedArtifacts::new(raw, a.clone())),
97            None => raw,
98        })
99    }
100
101    /// The memory of the user, if a memory service is configured.
102    pub fn memory(&self) -> Option<Arc<dyn Memory>> {
103        self.inner().shared.memory.clone()
104    }
105
106    /// The session.
107    pub fn session(&self) -> Arc<dyn Session> {
108        self.inner().session.clone()
109    }
110
111    /// The isolation scope; events with a different non-empty scope are not visible.
112    pub fn isolation_scope(&self) -> String {
113        self.inner().isolation_scope.clone()
114    }
115
116    /// The run configuration.
117    pub fn run_config(&self) -> &RunConfig {
118        &self.inner().shared.run_config
119    }
120
121    /// Ends the invocation: the agent stops at its next check.
122    pub fn end_invocation(&self) {
123        self.inner().ended.store(true, Ordering::SeqCst)
124    }
125
126    /// Whether the invocation has ended.
127    pub fn ended(&self) -> bool {
128        self.inner().ended.load(Ordering::SeqCst)
129    }
130
131    /// The identity of this context's end flag (see [`ActivationId`]): equal for every callback
132    /// and tool context of one agent run, distinct across runs and forks, never reused.
133    pub fn activation_id(&self) -> ActivationId {
134        self.inner().activation
135    }
136
137    /// This context's resume input for `interrupt_id`.
138    pub fn resumed_input(&self, interrupt_id: &str) -> Option<Value> {
139        self.inner()
140            .resumed_inputs
141            .as_ref()?
142            .get(interrupt_id)
143            .cloned()
144    }
145
146    /// The cancellation token.
147    pub fn cancellation_token(&self) -> &CancellationToken {
148        &self.inner().cancel_scope.token
149    }
150
151    /// Cancels this context's own
152    /// cancel scope with `cause`, unless it is already cancelled (first cause wins). Contexts
153    /// sharing the scope (every delta but a raw `cancellation_token`, and contexts derived by
154    /// [`Context::with_agent_cancel`](crate::Context::with_agent_cancel) from it) are cancelled
155    /// with it.
156    pub fn cancel_with_cause(&self, cause: CancelCause) {
157        self.inner().cancel_scope.cancel_with_cause(cause);
158    }
159
160    /// The cancel cause: `None` while the cancellation token is live; else the cause recorded
161    /// by the nearest cancelled scope walking outward from this context's own (a scope cancelled
162    /// only by its parent defers to it), else `Canceled` (e.g. a raw `token.cancel()`).
163    pub fn cause(&self) -> Option<CancelCause> {
164        self.inner().cancel_scope.cause()
165    }
166
167    /// The platform (time, UUIDs, task runner).
168    pub fn platform(&self) -> &Platform {
169        &self.inner().shared.platform
170    }
171
172    /// The plugin manager, if plugins are configured.
173    pub fn plugin_manager(&self) -> Option<Arc<PluginManager>> {
174        self.inner().shared.plugin_manager.clone()
175    }
176
177    /// A derived context marked so that the
178    /// next runner started with it (`Runner::run_with_context`) keeps this context's plugin
179    /// manager ([`InvocationContext::plugin_manager`]) when that runner has no
180    /// plugins of its own. Only the agent tool sets this mark, for the sub-runner it starts; any
181    /// other runner uses only its own plugins. The receiver is unchanged.
182    pub fn with_inherited_plugins(&self) -> InvocationContext {
183        let mut n = self.inner().clone();
184        n.inherited_plugins = self.plugin_manager();
185        Self::from_inner(n)
186    }
187
188    /// Takes the plugin manager marked by
189    /// [`InvocationContext::with_inherited_plugins`] (`None` without a mark) and a derived context
190    /// with the mark cleared, so that the mark applies to one runner only and not to runners
191    /// started further down.
192    pub fn take_inherited_plugins(&self) -> (InvocationContext, Option<Arc<PluginManager>>) {
193        let Some(pm) = self.inner().inherited_plugins.clone() else {
194            return (self.clone(), None);
195        };
196        let mut n = self.inner().clone();
197        n.inherited_plugins = None;
198        (Self::from_inner(n), Some(pm))
199    }
200
201    /// A derived context marked so that
202    /// resuming a nested graph workflow is done for it and every context derived from it (a loop
203    /// agent runs its later passes with it: only the first pass narrows to the sub-agents holding
204    /// the callers of the user's function responses). The receiver is unchanged.
205    pub fn with_graph_resume_done(&self) -> InvocationContext {
206        let mut n = self.inner().clone();
207        n.graph_resume_done = true;
208        Self::from_inner(n)
209    }
210
211    /// Whether the context is marked by [`InvocationContext::with_graph_resume_done`].
212    pub fn graph_resume_done(&self) -> bool {
213        self.inner().graph_resume_done
214    }
215
216    /// The agent tree's parent map, if set.
217    pub fn parent_map(&self) -> Option<Arc<ParentMap>> {
218        self.inner().shared.parent_map.clone()
219    }
220
221    /// The session service, if set.
222    pub fn session_service(&self) -> Option<Arc<dyn SessionService>> {
223        self.inner().shared.session_service.clone()
224    }
225
226    /// The invocation's LLM-call limiter, shared by every agent in it.
227    #[doc(hidden)]
228    pub fn llm_call_limiter(&self) -> Option<Arc<LlmCallLimiter>> {
229        self.inner().shared.llm_call_limiter.clone()
230    }
231
232    /// The engine's per-invocation compaction runtime, if compaction is configured
233    /// (engine-internal).
234    #[doc(hidden)]
235    pub fn compaction_runtime(&self) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
236        self.inner().shared.compaction.clone()
237    }
238
239    /// The bound agent modes.
240    pub fn bound_modes(&self) -> &BoundModes {
241        &self.inner().bound_modes
242    }
243
244    /// The active live session's resumption
245    /// handle, used to resume a bidirectional streaming session after a reconnect.
246    pub fn live_session_resumption_handle(&self) -> String {
247        self.inner().live_handle.lock().clone()
248    }
249
250    /// Stores the latest handle received
251    /// from the model, visible to every context of this invocation.
252    pub fn set_live_session_resumption_handle(&self, handle: &str) {
253        *self.inner().live_handle.lock() = handle.to_owned();
254    }
255
256    /// A derived context with `d` applied; the receiver is unchanged.
257    pub fn with_delta(&self, d: ContextDelta) -> InvocationContext {
258        Self::from_inner(self.inner().apply(d))
259    }
260
261    /// The same fields, seen as a [`Context`].
262    pub fn into_context(self) -> Context {
263        Context { ic: self }
264    }
265
266    /// The read-only view.
267    pub fn as_readonly(&self) -> &ReadonlyContext {
268        &self.ro
269    }
270}
271
272/// Records each successful save, keeping the highest version per name.
273pub(crate) struct TrackedArtifacts {
274    inner: Arc<dyn Artifacts>,
275    actions: Arc<parking_lot::Mutex<EventActions>>,
276}
277
278impl TrackedArtifacts {
279    /// Wraps `inner`, recording saves into the context's actions.
280    pub(crate) fn new(
281        inner: Arc<dyn Artifacts>,
282        actions: Arc<parking_lot::Mutex<EventActions>>,
283    ) -> Self {
284        Self { inner, actions }
285    }
286}
287
288#[async_trait::async_trait]
289impl Artifacts for TrackedArtifacts {
290    async fn save(&self, name: &str, data: Part) -> Result<SaveResponse, AgentError> {
291        let resp = self.inner.save(name, data).await?;
292        let mut a = self.actions.lock();
293        let delta = a.artifact_delta.get_or_insert_with(BTreeMap::new);
294        if delta.get(name).is_none_or(|v| resp.version > *v) {
295            delta.insert(name.to_string(), resp.version);
296        }
297        Ok(resp)
298    }
299
300    async fn list(&self) -> Result<ListResponse, AgentError> {
301        self.inner.list().await
302    }
303
304    async fn load(&self, name: &str) -> Result<LoadResponse, AgentError> {
305        self.inner.load(name).await
306    }
307
308    async fn load_version(&self, name: &str, version: i64) -> Result<LoadResponse, AgentError> {
309        self.inner.load_version(name, version).await
310    }
311
312    fn backing_service(&self) -> Option<ArtifactBacking> {
313        self.inner.backing_service()
314    }
315}
316
317#[cfg(test)]
318#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
319mod tests {
320    use std::any::Any;
321    use std::sync::Arc;
322
323    use crate::context::delta::ContextDelta;
324
325    use super::*;
326
327    fn slot(ctx: &InvocationContext) -> Option<Arc<dyn Any + Send + Sync>> {
328        ctx.compaction_runtime()
329    }
330
331    #[test]
332    fn compaction_runtime_slot_round_trips_and_is_shared() {
333        let rt: Arc<dyn Any + Send + Sync> = Arc::new(7u32);
334        let ctx = InvocationContext::builder()
335            .compaction_runtime(rt.clone())
336            .build_invocation();
337        let got = slot(&ctx).expect("slot set");
338        assert!(Arc::ptr_eq(&got, &rt));
339        assert_eq!(got.downcast_ref::<u32>(), Some(&7));
340
341        // Every derivation inside the invocation sees the same Arc.
342        let derived = [
343            ctx.with_delta(ContextDelta {
344                branch: Some("a.b".into()),
345                ..Default::default()
346            }),
347            ctx.with_delta(ContextDelta {
348                fresh_invocation: true,
349                ..Default::default()
350            }),
351            ctx.clone()
352                .into_context()
353                .with_delta(ContextDelta {
354                    function_call_id: Some("fc".into()),
355                    ..Default::default()
356                })
357                .as_invocation()
358                .clone(),
359            ctx.clone()
360                .into_context()
361                .with_agent_cancel()
362                .0
363                .as_invocation()
364                .clone(),
365        ];
366        for d in &derived {
367            assert!(Arc::ptr_eq(&slot(d).expect("derived slot"), &rt));
368        }
369    }
370
371    #[test]
372    fn compaction_runtime_slot_defaults_to_none() {
373        assert!(
374            InvocationContext::builder()
375                .build_invocation()
376                .compaction_runtime()
377                .is_none()
378        );
379    }
380
381    /// Go `WithGraphResumeDone` is a context value: every context derived from a marked one,
382    /// fresh invocations included, carries it; the receiver stays unmarked.
383    #[test]
384    fn graph_resume_done_is_inherited_by_every_derivation() {
385        let ctx = InvocationContext::builder().build_invocation();
386        assert!(!ctx.graph_resume_done());
387        let done = ctx.with_graph_resume_done();
388        assert!(done.graph_resume_done());
389        assert!(!ctx.graph_resume_done(), "the receiver is unchanged");
390        let derived = [
391            done.with_delta(ContextDelta {
392                branch: Some("a.b".into()),
393                ..Default::default()
394            }),
395            done.with_delta(ContextDelta {
396                fresh_invocation: true,
397                ..Default::default()
398            }),
399            done.clone()
400                .into_context()
401                .with_delta(ContextDelta {
402                    function_call_id: Some("fc".into()),
403                    ..Default::default()
404                })
405                .as_invocation()
406                .clone(),
407        ];
408        for d in &derived {
409            assert!(d.graph_resume_done());
410        }
411    }
412}