Skip to main content

gadk_agent/context/
readonly.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 read-only context view and the shared context state.
17
18use std::any::Any;
19use std::sync::Arc;
20use std::sync::atomic::AtomicBool;
21
22use gadk_genai::Content;
23use gadk_platform::Platform;
24use gadk_session::{
25    EventActions, ReadonlyState, Session, SessionError, SessionService, ToolConfirmation,
26};
27use serde_json::{Map, Value};
28use tokio_util::sync::CancellationToken;
29
30use crate::agent::Agent;
31use crate::context::activation::ActivationId;
32use crate::context::cancel::CancelScope;
33use crate::context::identity::Identity;
34use crate::mode::BoundModes;
35use crate::parent_map::ParentMap;
36use crate::plugin_manager::PluginManager;
37use crate::run_config::RunConfig;
38use crate::run_config::run_limits::LlmCallLimiter;
39use crate::scheduler::DynamicSubScheduler;
40use crate::services::{Artifacts, Memory};
41
42/// Invocation-wide values, fixed when the context is built (the invocation fields that no
43/// delta changes, plus the runner's parent map, run config and plugin manager).
44/// Every derivation shares this `Arc`, so a `with_delta` context keeps the same `llm_call_limiter`.
45pub(crate) struct Shared {
46    pub(crate) invocation_id: String,
47    pub(crate) artifacts: Option<Arc<dyn Artifacts>>,
48    pub(crate) memory: Option<Arc<dyn Memory>>,
49    pub(crate) run_config: RunConfig,
50    pub(crate) platform: Platform,
51    pub(crate) plugin_manager: Option<Arc<PluginManager>>,
52    pub(crate) parent_map: Option<Arc<ParentMap>>,
53    pub(crate) session_service: Option<Arc<dyn SessionService>>,
54    pub(crate) llm_call_limiter: Option<Arc<LlmCallLimiter>>,
55    /// The engine's per-invocation compaction runtime. Opaque here:
56    /// only the engine downcasts it. Every context derived within one invocation shares it.
57    pub(crate) compaction: Option<Arc<dyn Any + Send + Sync>>,
58    /// The invocation's teardown registry ([`crate::teardown::Teardowns`]); the runner installs
59    /// one per invocation.
60    pub(crate) teardowns: Option<Arc<crate::teardown::Teardowns>>,
61}
62
63/// One snapshot of every context field; deltas clone it (cheap: `Arc`s and short strings).
64#[derive(Clone)]
65pub(crate) struct ContextInner {
66    pub(crate) shared: Arc<Shared>,
67    // Invocation level (a delta touching any of these forks `ended`).
68    pub(crate) session: Arc<dyn Session>,
69    pub(crate) agent: Arc<dyn Agent>,
70    pub(crate) branch: String,
71    pub(crate) isolation_scope: String,
72    pub(crate) user_content: Option<Arc<Content>>,
73    pub(crate) ended: Arc<AtomicBool>,
74    /// The identity of `ended`: replaced together with it, never without it.
75    pub(crate) activation: ActivationId,
76    /// The context's cancel scope (cancellation and cause); its token is
77    /// the context's cancellation token.
78    pub(crate) cancel_scope: Arc<CancelScope>,
79    pub(crate) bound_modes: BoundModes,
80    /// The live session resumption handle. One slot per invocation, shared by
81    /// every derived context (the live reader and the reconnect loop run on different tasks);
82    /// `ContextDelta::fresh_invocation` installs a new empty slot.
83    pub(crate) live_handle: Arc<parking_lot::Mutex<String>>,
84    // Node / tool / callback level.
85    pub(crate) resumed_inputs: Option<Arc<Map<String, Value>>>,
86    pub(crate) actions: Option<Arc<parking_lot::Mutex<EventActions>>>,
87    pub(crate) function_call_id: String,
88    pub(crate) tool_confirmation: Option<ToolConfirmation>,
89    pub(crate) path: String,
90    pub(crate) run_id: String,
91    pub(crate) sub_scheduler: Option<Arc<dyn DynamicSubScheduler>>,
92    pub(crate) output_for_ancestors: Option<Vec<String>>,
93    /// The walk past a fresh invocation context: the path of the context a
94    /// `fresh_invocation` / `fresh_end_flag` delta forked from (its own path, else its enclosing
95    /// path); every other delta copies it unchanged.
96    pub(crate) enclosing_path: String,
97    /// The plugin manager a plugin-less
98    /// runner started with this context keeps (`None`: no mark, or a cleared one). Every
99    /// derivation copies it.
100    pub(crate) inherited_plugins: Option<Arc<PluginManager>>,
101    /// The graph-resume-done mark (`InvocationContext::with_graph_resume_done`): resuming a
102    /// nested graph workflow is done for this context and every context derived from it, so
103    /// composite agents run all their sub-agents. Every derivation copies it.
104    pub(crate) graph_resume_done: bool,
105}
106
107/// Read-only access to the invocation's values.
108#[derive(Clone)]
109pub struct ReadonlyContext {
110    pub(crate) inner: Arc<ContextInner>,
111}
112
113impl ReadonlyContext {
114    /// The user content that started the invocation.
115    pub fn user_content(&self) -> Option<&Content> {
116        self.inner.user_content.as_deref()
117    }
118
119    /// The invocation id.
120    pub fn invocation_id(&self) -> &str {
121        &self.inner.shared.invocation_id
122    }
123
124    /// The name of the current agent.
125    pub fn agent_name(&self) -> String {
126        self.inner.agent.name().to_string()
127    }
128
129    /// The session's state, without the actions overlay.
130    pub fn readonly_state(&self) -> Arc<dyn ReadonlyState> {
131        Arc::new(SessionReadonlyState(self.inner.session.clone()))
132    }
133
134    /// The session's user id, read from the session on every call, never cached.
135    pub fn user_id(&self) -> &str {
136        self.inner.session.user_id()
137    }
138
139    /// The session's app name, read from the session on every call.
140    pub fn app_name(&self) -> &str {
141        self.inner.session.app_name()
142    }
143
144    /// The session id, read from the session on every call.
145    pub fn session_id(&self) -> &str {
146        self.inner.session.id()
147    }
148
149    /// The invocation's identity from one
150    /// `session` read, then one accessor call per field, so the identity cannot be torn.
151    pub fn identity(&self) -> Identity {
152        let s = self.inner.session.clone();
153        Identity {
154            user_id: s.user_id().to_string(),
155            app_name: s.app_name().to_string(),
156            session_id: s.id().to_string(),
157        }
158    }
159
160    /// The branch, like `agent_1.agent_2.agent_3`.
161    pub fn branch(&self) -> String {
162        self.inner.branch.clone()
163    }
164
165    /// The invocation's cancellation token: the
166    /// same token [`InvocationContext::cancellation_token`](crate::InvocationContext::cancellation_token)
167    /// returns, so a toolset's `tools` can stop when the invocation is cancelled.
168    pub fn cancellation_token(&self) -> &CancellationToken {
169        &self.inner.cancel_scope.token
170    }
171}
172
173/// The session's state seen read-only.
174pub(crate) struct SessionReadonlyState(pub(crate) Arc<dyn Session>);
175
176impl ReadonlyState for SessionReadonlyState {
177    fn get(&self, key: &str) -> Result<Value, SessionError> {
178        self.0.state().get(key)
179    }
180
181    fn all(&self) -> Vec<(String, Value)> {
182        self.0.state().all()
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use tokio_util::sync::CancellationToken;
189
190    use crate::context::{ContextDelta, InvocationContext};
191
192    /// R18: the read-only view hands out the invocation's own token, on every context shape.
193    #[test]
194    fn readonly_cancellation_token_is_the_invocations() {
195        let token = CancellationToken::new();
196        let ic = InvocationContext::builder()
197            .cancellation_token(token.clone())
198            .build_invocation();
199        let ctx = ic.clone().into_context();
200        let tool_ctx = ctx.with_delta(ContextDelta {
201            function_call_id: Some("fc".into()),
202            ..Default::default()
203        });
204        let views = [
205            ("invocation", (*ic).clone()),
206            ("context", (**ctx.as_invocation()).clone()),
207            ("tool context", (**tool_ctx.as_invocation()).clone()),
208        ];
209        for (name, ro) in &views {
210            assert!(!ro.cancellation_token().is_cancelled(), "{name}");
211        }
212        token.cancel();
213        for (name, ro) in &views {
214            assert!(ro.cancellation_token().is_cancelled(), "{name}");
215        }
216        assert!(ic.cancellation_token().is_cancelled());
217    }
218}