1use 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
44pub(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 pub(crate) compaction: Option<Arc<dyn Any + Send + Sync>>,
60 pub(crate) teardowns: Option<Arc<crate::teardown::Teardowns>>,
63 pub(crate) prompts: parking_lot::Mutex<HashMap<String, PromptUse>>,
67}
68
69#[derive(Clone)]
71pub(crate) struct ContextInner {
72 pub(crate) shared: Arc<Shared>,
73 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 pub(crate) activation: ActivationId,
82 pub(crate) cancel_scope: Arc<CancelScope>,
85 pub(crate) bound_modes: BoundModes,
86 pub(crate) live_handle: Arc<parking_lot::Mutex<String>>,
90 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 pub(crate) enclosing_path: String,
103 pub(crate) inherited_plugins: Option<Arc<PluginManager>>,
107 pub(crate) graph_resume_done: bool,
111}
112
113#[derive(Clone)]
115pub struct ReadonlyContext {
116 pub(crate) inner: Arc<ContextInner>,
117}
118
119impl ReadonlyContext {
120 pub fn user_content(&self) -> Option<&Content> {
122 self.inner.user_content.as_deref()
123 }
124
125 pub fn invocation_id(&self) -> &str {
127 &self.inner.shared.invocation_id
128 }
129
130 pub fn agent_name(&self) -> String {
132 self.inner.agent.name().to_string()
133 }
134
135 pub fn readonly_state(&self) -> Arc<dyn ReadonlyState> {
137 Arc::new(SessionReadonlyState(self.inner.session.clone()))
138 }
139
140 pub fn user_id(&self) -> &str {
142 self.inner.session.user_id()
143 }
144
145 pub fn app_name(&self) -> &str {
147 self.inner.session.app_name()
148 }
149
150 pub fn session_id(&self) -> &str {
152 self.inner.session.id()
153 }
154
155 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 pub fn branch(&self) -> String {
168 self.inner.branch.clone()
169 }
170
171 pub fn cancellation_token(&self) -> &CancellationToken {
175 &self.inner.cancel_scope.token
176 }
177
178 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 pub fn clear_recorded_prompt(&self) {
193 self.inner.shared.prompts.lock().remove(&self.agent_name());
194 }
195
196 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
207pub(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 #[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 #[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 #[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}