use std::collections::BTreeMap;
use std::ops::Deref;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use gadk_artifact::{ListResponse, LoadResponse, SaveResponse};
use gadk_genai::Part;
use gadk_platform::Platform;
use gadk_session::{EventActions, Session, SessionService};
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::agent::Agent;
use crate::context::activation::ActivationId;
use crate::context::builder::ContextBuilder;
use crate::context::cancel::CancelCause;
use crate::context::context::Context;
use crate::context::delta::ContextDelta;
use crate::context::readonly::{ContextInner, ReadonlyContext};
use crate::error::AgentError;
use crate::mode::BoundModes;
use crate::parent_map::ParentMap;
use crate::plugin_manager::PluginManager;
use crate::run_config::RunConfig;
use crate::run_config::run_limits::LlmCallLimiter;
use crate::services::{ArtifactBacking, Artifacts, Memory};
#[derive(Clone)]
pub struct InvocationContext {
pub(crate) ro: ReadonlyContext,
}
impl Deref for InvocationContext {
type Target = ReadonlyContext;
fn deref(&self) -> &ReadonlyContext {
&self.ro
}
}
impl InvocationContext {
pub fn builder() -> ContextBuilder {
ContextBuilder::new()
}
pub(crate) fn from_inner(inner: ContextInner) -> Self {
Self {
ro: ReadonlyContext {
inner: Arc::new(inner),
},
}
}
#[doc(hidden)]
pub fn from_readonly(ctx: &ReadonlyContext) -> Self {
Self { ro: ctx.clone() }
}
pub(crate) fn inner(&self) -> &ContextInner {
&self.ro.inner
}
pub fn agent(&self) -> Arc<dyn Agent> {
self.inner().agent.clone()
}
pub fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
let raw = self.inner().shared.artifacts.clone()?;
Some(match &self.inner().actions {
Some(a) => Arc::new(TrackedArtifacts::new(raw, a.clone())),
None => raw,
})
}
pub fn memory(&self) -> Option<Arc<dyn Memory>> {
self.inner().shared.memory.clone()
}
pub fn session(&self) -> Arc<dyn Session> {
self.inner().session.clone()
}
pub fn isolation_scope(&self) -> String {
self.inner().isolation_scope.clone()
}
pub fn run_config(&self) -> &RunConfig {
&self.inner().shared.run_config
}
pub fn end_invocation(&self) {
self.inner().ended.store(true, Ordering::SeqCst)
}
pub fn ended(&self) -> bool {
self.inner().ended.load(Ordering::SeqCst)
}
pub fn activation_id(&self) -> ActivationId {
self.inner().activation
}
pub fn resumed_input(&self, interrupt_id: &str) -> Option<Value> {
self.inner()
.resumed_inputs
.as_ref()?
.get(interrupt_id)
.cloned()
}
pub fn cancellation_token(&self) -> &CancellationToken {
&self.inner().cancel_scope.token
}
pub fn cancel_with_cause(&self, cause: CancelCause) {
self.inner().cancel_scope.cancel_with_cause(cause);
}
pub fn cause(&self) -> Option<CancelCause> {
self.inner().cancel_scope.cause()
}
pub fn platform(&self) -> &Platform {
&self.inner().shared.platform
}
pub fn plugin_manager(&self) -> Option<Arc<PluginManager>> {
self.inner().shared.plugin_manager.clone()
}
pub fn with_inherited_plugins(&self) -> InvocationContext {
let mut n = self.inner().clone();
n.inherited_plugins = self.plugin_manager();
Self::from_inner(n)
}
pub fn take_inherited_plugins(&self) -> (InvocationContext, Option<Arc<PluginManager>>) {
let Some(pm) = self.inner().inherited_plugins.clone() else {
return (self.clone(), None);
};
let mut n = self.inner().clone();
n.inherited_plugins = None;
(Self::from_inner(n), Some(pm))
}
pub fn with_graph_resume_done(&self) -> InvocationContext {
let mut n = self.inner().clone();
n.graph_resume_done = true;
Self::from_inner(n)
}
pub fn graph_resume_done(&self) -> bool {
self.inner().graph_resume_done
}
pub fn parent_map(&self) -> Option<Arc<ParentMap>> {
self.inner().shared.parent_map.clone()
}
pub fn session_service(&self) -> Option<Arc<dyn SessionService>> {
self.inner().shared.session_service.clone()
}
#[doc(hidden)]
pub fn llm_call_limiter(&self) -> Option<Arc<LlmCallLimiter>> {
self.inner().shared.llm_call_limiter.clone()
}
#[doc(hidden)]
pub fn compaction_runtime(&self) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
self.inner().shared.compaction.clone()
}
pub fn bound_modes(&self) -> &BoundModes {
&self.inner().bound_modes
}
pub fn live_session_resumption_handle(&self) -> String {
self.inner().live_handle.lock().clone()
}
pub fn set_live_session_resumption_handle(&self, handle: &str) {
*self.inner().live_handle.lock() = handle.to_owned();
}
pub fn with_delta(&self, d: ContextDelta) -> InvocationContext {
Self::from_inner(self.inner().apply(d))
}
pub fn into_context(self) -> Context {
Context { ic: self }
}
pub fn as_readonly(&self) -> &ReadonlyContext {
&self.ro
}
}
pub(crate) struct TrackedArtifacts {
inner: Arc<dyn Artifacts>,
actions: Arc<parking_lot::Mutex<EventActions>>,
}
impl TrackedArtifacts {
pub(crate) fn new(
inner: Arc<dyn Artifacts>,
actions: Arc<parking_lot::Mutex<EventActions>>,
) -> Self {
Self { inner, actions }
}
}
#[async_trait::async_trait]
impl Artifacts for TrackedArtifacts {
async fn save(&self, name: &str, data: Part) -> Result<SaveResponse, AgentError> {
let resp = self.inner.save(name, data).await?;
let mut a = self.actions.lock();
let delta = a.artifact_delta.get_or_insert_with(BTreeMap::new);
if delta.get(name).is_none_or(|v| resp.version > *v) {
delta.insert(name.to_string(), resp.version);
}
Ok(resp)
}
async fn list(&self) -> Result<ListResponse, AgentError> {
self.inner.list().await
}
async fn load(&self, name: &str) -> Result<LoadResponse, AgentError> {
self.inner.load(name).await
}
async fn load_version(&self, name: &str, version: i64) -> Result<LoadResponse, AgentError> {
self.inner.load_version(name, version).await
}
fn backing_service(&self) -> Option<ArtifactBacking> {
self.inner.backing_service()
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use std::any::Any;
use std::sync::Arc;
use crate::context::delta::ContextDelta;
use super::*;
fn slot(ctx: &InvocationContext) -> Option<Arc<dyn Any + Send + Sync>> {
ctx.compaction_runtime()
}
#[test]
fn compaction_runtime_slot_round_trips_and_is_shared() {
let rt: Arc<dyn Any + Send + Sync> = Arc::new(7u32);
let ctx = InvocationContext::builder()
.compaction_runtime(rt.clone())
.build_invocation();
let got = slot(&ctx).expect("slot set");
assert!(Arc::ptr_eq(&got, &rt));
assert_eq!(got.downcast_ref::<u32>(), Some(&7));
let derived = [
ctx.with_delta(ContextDelta {
branch: Some("a.b".into()),
..Default::default()
}),
ctx.with_delta(ContextDelta {
fresh_invocation: true,
..Default::default()
}),
ctx.clone()
.into_context()
.with_delta(ContextDelta {
function_call_id: Some("fc".into()),
..Default::default()
})
.as_invocation()
.clone(),
ctx.clone()
.into_context()
.with_agent_cancel()
.0
.as_invocation()
.clone(),
];
for d in &derived {
assert!(Arc::ptr_eq(&slot(d).expect("derived slot"), &rt));
}
}
#[test]
fn compaction_runtime_slot_defaults_to_none() {
assert!(
InvocationContext::builder()
.build_invocation()
.compaction_runtime()
.is_none()
);
}
#[test]
fn graph_resume_done_is_inherited_by_every_derivation() {
let ctx = InvocationContext::builder().build_invocation();
assert!(!ctx.graph_resume_done());
let done = ctx.with_graph_resume_done();
assert!(done.graph_resume_done());
assert!(!ctx.graph_resume_done(), "the receiver is unchanged");
let derived = [
done.with_delta(ContextDelta {
branch: Some("a.b".into()),
..Default::default()
}),
done.with_delta(ContextDelta {
fresh_invocation: true,
..Default::default()
}),
done.clone()
.into_context()
.with_delta(ContextDelta {
function_call_id: Some("fc".into()),
..Default::default()
})
.as_invocation()
.clone(),
];
for d in &derived {
assert!(d.graph_resume_done());
}
}
}