gadk_agent/context/
invocation.rs1use 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#[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 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 #[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 pub fn agent(&self) -> Arc<dyn Agent> {
87 self.inner().agent.clone()
88 }
89
90 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 pub fn memory(&self) -> Option<Arc<dyn Memory>> {
103 self.inner().shared.memory.clone()
104 }
105
106 pub fn session(&self) -> Arc<dyn Session> {
108 self.inner().session.clone()
109 }
110
111 pub fn isolation_scope(&self) -> String {
113 self.inner().isolation_scope.clone()
114 }
115
116 pub fn run_config(&self) -> &RunConfig {
118 &self.inner().shared.run_config
119 }
120
121 pub fn end_invocation(&self) {
123 self.inner().ended.store(true, Ordering::SeqCst)
124 }
125
126 pub fn ended(&self) -> bool {
128 self.inner().ended.load(Ordering::SeqCst)
129 }
130
131 pub fn activation_id(&self) -> ActivationId {
134 self.inner().activation
135 }
136
137 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 pub fn cancellation_token(&self) -> &CancellationToken {
148 &self.inner().cancel_scope.token
149 }
150
151 pub fn cancel_with_cause(&self, cause: CancelCause) {
157 self.inner().cancel_scope.cancel_with_cause(cause);
158 }
159
160 pub fn cause(&self) -> Option<CancelCause> {
164 self.inner().cancel_scope.cause()
165 }
166
167 pub fn platform(&self) -> &Platform {
169 &self.inner().shared.platform
170 }
171
172 pub fn plugin_manager(&self) -> Option<Arc<PluginManager>> {
174 self.inner().shared.plugin_manager.clone()
175 }
176
177 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 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 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 pub fn graph_resume_done(&self) -> bool {
213 self.inner().graph_resume_done
214 }
215
216 pub fn parent_map(&self) -> Option<Arc<ParentMap>> {
218 self.inner().shared.parent_map.clone()
219 }
220
221 pub fn session_service(&self) -> Option<Arc<dyn SessionService>> {
223 self.inner().shared.session_service.clone()
224 }
225
226 #[doc(hidden)]
228 pub fn llm_call_limiter(&self) -> Option<Arc<LlmCallLimiter>> {
229 self.inner().shared.llm_call_limiter.clone()
230 }
231
232 #[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 pub fn bound_modes(&self) -> &BoundModes {
241 &self.inner().bound_modes
242 }
243
244 pub fn live_session_resumption_handle(&self) -> String {
247 self.inner().live_handle.lock().clone()
248 }
249
250 pub fn set_live_session_resumption_handle(&self, handle: &str) {
253 *self.inner().live_handle.lock() = handle.to_owned();
254 }
255
256 pub fn with_delta(&self, d: ContextDelta) -> InvocationContext {
258 Self::from_inner(self.inner().apply(d))
259 }
260
261 pub fn into_context(self) -> Context {
263 Context { ic: self }
264 }
265
266 pub fn as_readonly(&self) -> &ReadonlyContext {
268 &self.ro
269 }
270}
271
272pub(crate) struct TrackedArtifacts {
274 inner: Arc<dyn Artifacts>,
275 actions: Arc<parking_lot::Mutex<EventActions>>,
276}
277
278impl TrackedArtifacts {
279 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 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 #[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}