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::collections::HashMap;
20use std::sync::Arc;
21use std::sync::atomic::AtomicBool;
22
23use gadk_genai::Content;
24use gadk_platform::Platform;
25use gadk_session::{
26    EventActions, ReadonlyState, Session, SessionError, SessionService, ToolConfirmation,
27};
28use serde_json::{Map, Value};
29use tokio_util::sync::CancellationToken;
30
31use crate::agent::Agent;
32use crate::context::activation::ActivationId;
33use crate::context::cancel::CancelScope;
34use crate::context::identity::Identity;
35use crate::context::prompt_use::PromptUse;
36use crate::mode::BoundModes;
37use crate::parent_map::ParentMap;
38use crate::plugin_manager::PluginManager;
39use crate::run_config::RunConfig;
40use crate::run_config::run_limits::LlmCallLimiter;
41use crate::scheduler::DynamicSubScheduler;
42use crate::services::{Artifacts, Memory};
43
44/// Invocation-wide values, fixed when the context is built (the invocation fields that no
45/// delta changes, plus the runner's parent map, run config and plugin manager).
46/// Every derivation shares this `Arc`, so a `with_delta` context keeps the same `llm_call_limiter`.
47pub(crate) struct Shared {
48    pub(crate) invocation_id: String,
49    pub(crate) artifacts: Option<Arc<dyn Artifacts>>,
50    pub(crate) memory: Option<Arc<dyn Memory>>,
51    pub(crate) run_config: RunConfig,
52    pub(crate) platform: Platform,
53    pub(crate) plugin_manager: Option<Arc<PluginManager>>,
54    pub(crate) parent_map: Option<Arc<ParentMap>>,
55    pub(crate) session_service: Option<Arc<dyn SessionService>>,
56    pub(crate) llm_call_limiter: Option<Arc<LlmCallLimiter>>,
57    /// The engine's per-invocation compaction runtime. Opaque here:
58    /// only the engine downcasts it. Every context derived within one invocation shares it.
59    pub(crate) compaction: Option<Arc<dyn Any + Send + Sync>>,
60    /// The invocation's teardown registry ([`crate::teardown::Teardowns`]); the runner installs
61    /// one per invocation.
62    pub(crate) teardowns: Option<Arc<crate::teardown::Teardowns>>,
63    /// The prompt version each agent's instruction was last rendered from, by agent name
64    /// ([`ReadonlyContext::record_prompt`]). Created empty with the invocation; every derived
65    /// context (deltas included) shares it.
66    pub(crate) prompts: parking_lot::Mutex<HashMap<String, PromptUse>>,
67}
68
69/// One snapshot of every context field; deltas clone it (cheap: `Arc`s and short strings).
70#[derive(Clone)]
71pub(crate) struct ContextInner {
72    pub(crate) shared: Arc<Shared>,
73    // Invocation level (a delta touching any of these forks `ended`).
74    pub(crate) session: Arc<dyn Session>,
75    pub(crate) agent: Arc<dyn Agent>,
76    pub(crate) branch: String,
77    pub(crate) isolation_scope: String,
78    pub(crate) user_content: Option<Arc<Content>>,
79    pub(crate) ended: Arc<AtomicBool>,
80    /// The identity of `ended`: replaced together with it, never without it.
81    pub(crate) activation: ActivationId,
82    /// The context's cancel scope (cancellation and cause); its token is
83    /// the context's cancellation token.
84    pub(crate) cancel_scope: Arc<CancelScope>,
85    pub(crate) bound_modes: BoundModes,
86    /// The live session resumption handle. One slot per invocation, shared by
87    /// every derived context (the live reader and the reconnect loop run on different tasks);
88    /// `ContextDelta::fresh_invocation` installs a new empty slot.
89    pub(crate) live_handle: Arc<parking_lot::Mutex<String>>,
90    // Node / tool / callback level.
91    pub(crate) resumed_inputs: Option<Arc<Map<String, Value>>>,
92    pub(crate) actions: Option<Arc<parking_lot::Mutex<EventActions>>>,
93    pub(crate) function_call_id: String,
94    pub(crate) tool_confirmation: Option<ToolConfirmation>,
95    pub(crate) path: String,
96    pub(crate) run_id: String,
97    pub(crate) sub_scheduler: Option<Arc<dyn DynamicSubScheduler>>,
98    pub(crate) output_for_ancestors: Option<Vec<String>>,
99    /// The walk past a fresh invocation context: the path of the context a
100    /// `fresh_invocation` / `fresh_end_flag` delta forked from (its own path, else its enclosing
101    /// path); every other delta copies it unchanged.
102    pub(crate) enclosing_path: String,
103    /// The plugin manager a plugin-less
104    /// runner started with this context keeps (`None`: no mark, or a cleared one). Every
105    /// derivation copies it.
106    pub(crate) inherited_plugins: Option<Arc<PluginManager>>,
107    /// The graph-resume-done mark (`InvocationContext::with_graph_resume_done`): resuming a
108    /// nested graph workflow is done for this context and every context derived from it, so
109    /// composite agents run all their sub-agents. Every derivation copies it.
110    pub(crate) graph_resume_done: bool,
111}
112
113/// Read-only access to the invocation's values.
114#[derive(Clone)]
115pub struct ReadonlyContext {
116    pub(crate) inner: Arc<ContextInner>,
117}
118
119impl ReadonlyContext {
120    /// The user content that started the invocation.
121    pub fn user_content(&self) -> Option<&Content> {
122        self.inner.user_content.as_deref()
123    }
124
125    /// The invocation id.
126    pub fn invocation_id(&self) -> &str {
127        &self.inner.shared.invocation_id
128    }
129
130    /// The name of the current agent.
131    pub fn agent_name(&self) -> String {
132        self.inner.agent.name().to_string()
133    }
134
135    /// The session's state, without the actions overlay.
136    pub fn readonly_state(&self) -> Arc<dyn ReadonlyState> {
137        Arc::new(SessionReadonlyState(self.inner.session.clone()))
138    }
139
140    /// The session's user id, read from the session on every call, never cached.
141    pub fn user_id(&self) -> &str {
142        self.inner.session.user_id()
143    }
144
145    /// The session's app name, read from the session on every call.
146    pub fn app_name(&self) -> &str {
147        self.inner.session.app_name()
148    }
149
150    /// The session id, read from the session on every call.
151    pub fn session_id(&self) -> &str {
152        self.inner.session.id()
153    }
154
155    /// The invocation's identity from one
156    /// `session` read, then one accessor call per field, so the identity cannot be torn.
157    pub fn identity(&self) -> Identity {
158        let s = self.inner.session.clone();
159        Identity {
160            user_id: s.user_id().to_string(),
161            app_name: s.app_name().to_string(),
162            session_id: s.id().to_string(),
163        }
164    }
165
166    /// The branch, like `agent_1.agent_2.agent_3`.
167    pub fn branch(&self) -> String {
168        self.inner.branch.clone()
169    }
170
171    /// The invocation's cancellation token: the
172    /// same token [`InvocationContext::cancellation_token`](crate::InvocationContext::cancellation_token)
173    /// returns, so a toolset's `tools` can stop when the invocation is cancelled.
174    pub fn cancellation_token(&self) -> &CancellationToken {
175        &self.inner.cancel_scope.token
176    }
177
178    /// Records `used` as the prompt version this context's agent rendered its instruction from,
179    /// replacing an earlier record of the same agent. Every context of the invocation (including
180    /// `fresh_invocation` deltas such as parallel branches) sees it; each runner invocation starts
181    /// with none. Records are keyed by agent name, so two agents with the same name in one
182    /// invocation share one record.
183    pub fn record_prompt(&self, used: PromptUse) {
184        self.inner
185            .shared
186            .prompts
187            .lock()
188            .insert(self.agent_name(), used);
189    }
190
191    /// Removes the prompt version recorded for this context's agent.
192    pub fn clear_recorded_prompt(&self) {
193        self.inner.shared.prompts.lock().remove(&self.agent_name());
194    }
195
196    /// The prompt version recorded for this context's agent, if any.
197    pub fn recorded_prompt(&self) -> Option<PromptUse> {
198        self.inner
199            .shared
200            .prompts
201            .lock()
202            .get(&self.agent_name())
203            .cloned()
204    }
205}
206
207/// The session's state seen read-only.
208pub(crate) struct SessionReadonlyState(pub(crate) Arc<dyn Session>);
209
210impl ReadonlyState for SessionReadonlyState {
211    fn get(&self, key: &str) -> Result<Value, SessionError> {
212        self.0.state().get(key)
213    }
214
215    fn all(&self) -> Vec<(String, Value)> {
216        self.0.state().all()
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use tokio_util::sync::CancellationToken;
223
224    use crate::context::builder::test_support::named_agent;
225    use crate::context::prompt_use::PromptUse;
226    use crate::context::{ContextDelta, InvocationContext};
227
228    /// R18: the read-only view hands out the invocation's own token, on every context shape.
229    #[test]
230    fn readonly_cancellation_token_is_the_invocations() {
231        let token = CancellationToken::new();
232        let ic = InvocationContext::builder()
233            .cancellation_token(token.clone())
234            .build_invocation();
235        let ctx = ic.clone().into_context();
236        let tool_ctx = ctx.with_delta(ContextDelta {
237            function_call_id: Some("fc".into()),
238            ..Default::default()
239        });
240        let views = [
241            ("invocation", (*ic).clone()),
242            ("context", (**ctx.as_invocation()).clone()),
243            ("tool context", (**tool_ctx.as_invocation()).clone()),
244        ];
245        for (name, ro) in &views {
246            assert!(!ro.cancellation_token().is_cancelled(), "{name}");
247        }
248        token.cancel();
249        for (name, ro) in &views {
250            assert!(ro.cancellation_token().is_cancelled(), "{name}");
251        }
252        assert!(ic.cancellation_token().is_cancelled());
253    }
254
255    /// R2: records are per agent name, shared by every context of the invocation (fresh
256    /// invocation deltas and tool contexts included), replaced by a later record and removed by
257    /// a clear.
258    #[test]
259    fn recorded_prompts_are_per_agent_and_shared_by_the_invocation() {
260        let inv = InvocationContext::builder()
261            .agent(named_agent("a"))
262            .build_invocation();
263        assert_eq!(inv.recorded_prompt(), None);
264        inv.record_prompt(PromptUse::new("triage", 2).with_label("production"));
265
266        let branch_b = inv.with_delta(ContextDelta {
267            fresh_invocation: true,
268            agent: Some(named_agent("b")),
269            ..Default::default()
270        });
271        assert_eq!(branch_b.recorded_prompt(), None, "b has no record");
272        branch_b.record_prompt(PromptUse::new("summary", 1));
273
274        let a_again = branch_b.with_delta(ContextDelta {
275            agent: Some(named_agent("a")),
276            ..Default::default()
277        });
278        assert_eq!(
279            a_again.recorded_prompt(),
280            Some(PromptUse::new("triage", 2).with_label("production")),
281            "a fresh-invocation delta sees the invocation's records"
282        );
283        let tool_ctx = inv.clone().into_context().with_delta(ContextDelta {
284            function_call_id: Some("fc-1".into()),
285            ..Default::default()
286        });
287        assert_eq!(
288            tool_ctx.recorded_prompt(),
289            Some(PromptUse::new("triage", 2).with_label("production"))
290        );
291
292        tool_ctx.record_prompt(PromptUse::new("triage", 3));
293        assert_eq!(
294            inv.recorded_prompt(),
295            Some(PromptUse::new("triage", 3)),
296            "replaced"
297        );
298
299        a_again.clear_recorded_prompt();
300        assert_eq!(inv.recorded_prompt(), None, "cleared");
301        assert_eq!(
302            branch_b.recorded_prompt(),
303            Some(PromptUse::new("summary", 1)),
304            "b's record is untouched"
305        );
306    }
307
308    /// R2: each built invocation starts with an empty slot.
309    #[test]
310    fn each_built_invocation_starts_empty() {
311        let first = InvocationContext::builder()
312            .agent(named_agent("a"))
313            .build_invocation();
314        first.record_prompt(PromptUse::new("triage", 1));
315        let second = InvocationContext::builder()
316            .agent(named_agent("a"))
317            .build_invocation();
318        assert_eq!(second.recorded_prompt(), None);
319        assert_eq!(first.recorded_prompt(), Some(PromptUse::new("triage", 1)));
320    }
321}