use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;
use gadk_memory::SearchResponse;
use gadk_session::{EventActions, Session, SessionError, State, ToolConfirmation};
use serde_json::Value;
use crate::context::builder::ContextBuilder;
use crate::context::cancel::{CancelCause, CancelScope};
pub use crate::context::cancel::CancelGuard;
use crate::context::delta::ContextDelta;
use crate::context::invocation::InvocationContext;
use crate::error::{AgentError, ToolError};
use crate::scheduler::DynamicSubScheduler;
#[derive(Clone)]
pub struct Context {
pub(crate) ic: InvocationContext,
}
impl Deref for Context {
type Target = InvocationContext;
fn deref(&self) -> &InvocationContext {
&self.ic
}
}
impl Context {
pub fn builder() -> ContextBuilder {
ContextBuilder::new()
}
pub fn state(&self) -> Arc<dyn State> {
Arc::new(CallbackState {
actions: self.inner().actions.clone(),
session: self.inner().session.clone(),
})
}
pub fn function_call_id(&self) -> String {
self.inner().function_call_id.clone()
}
pub fn actions(&self) -> EventActions {
self.inner()
.actions
.as_ref()
.map(|a| a.lock().clone())
.unwrap_or_default()
}
pub fn update_actions(&self, f: impl FnOnce(&mut EventActions)) {
match &self.inner().actions {
Some(a) => f(&mut a.lock()),
None => tracing::debug!("update_actions on a context without actions is ignored"),
}
}
pub async fn search_memory(&self, query: &str) -> Result<SearchResponse, AgentError> {
let Some(m) = self.memory() else {
return Err(AgentError::other("memory service is not set"));
};
m.search_memory(query).await
}
pub fn tool_confirmation(&self) -> Option<ToolConfirmation> {
self.inner().tool_confirmation.clone()
}
pub fn request_confirmation(
&self,
hint: &str,
payload: Option<Value>,
) -> Result<(), ToolError> {
let id = self.inner().function_call_id.clone();
if id.is_empty() {
return Err(ToolError::InvalidArgument(
"error function call id not set when requesting confirmation for tool".into(),
));
}
self.update_actions(|a| {
a.requested_tool_confirmations.insert(
id,
ToolConfirmation {
hint: hint.to_string(),
confirmed: false,
payload,
},
);
a.skip_summarization = true;
});
Ok(())
}
pub fn path(&self) -> String {
self.inner().path.clone()
}
pub fn run_id(&self) -> String {
self.inner().run_id.clone()
}
pub fn sub_scheduler(&self) -> Option<Arc<dyn DynamicSubScheduler>> {
self.inner().sub_scheduler.clone()
}
pub fn output_for_ancestors(&self) -> Vec<String> {
self.inner()
.output_for_ancestors
.clone()
.unwrap_or_default()
}
pub fn with_delta(&self, d: ContextDelta) -> Context {
Context {
ic: self.ic.with_delta(d),
}
}
pub fn as_invocation(&self) -> &InvocationContext {
&self.ic
}
pub fn with_agent_cancel(&self) -> (Context, CancelGuard) {
let scope = CancelScope::child(&self.inner().cancel_scope);
let mut inner = self.inner().clone();
inner.cancel_scope = scope.clone();
(
InvocationContext::from_inner(inner).into_context(),
CancelGuard {
scope: Some(scope),
timer: None,
},
)
}
pub fn with_agent_timeout(&self, timeout: Duration) -> (Context, CancelGuard) {
let (ctx, mut guard) = self.with_agent_cancel();
let Some(scope) = guard.scope.clone() else {
return (ctx, guard);
};
if timeout.is_zero() {
scope.cancel_with_cause(CancelCause::DeadlineExceeded);
return (ctx, guard);
}
match tokio::runtime::Handle::try_current() {
Ok(h) => {
guard.timer = Some(h.spawn(async move {
tokio::select! {
() = tokio::time::sleep(timeout) => {
scope.cancel_with_cause(CancelCause::DeadlineExceeded);
}
() = scope.token.cancelled() => {}
}
}));
}
Err(_) => tracing::warn!(
"with_agent_timeout outside a Tokio runtime: the timeout is not enforced"
),
}
(ctx, guard)
}
pub fn context_path(&self) -> String {
let inner = self.inner();
if inner.path.is_empty() {
inner.enclosing_path.clone()
} else {
inner.path.clone()
}
}
}
struct CallbackState {
actions: Option<Arc<parking_lot::Mutex<EventActions>>>,
session: Arc<dyn Session>,
}
impl State for CallbackState {
fn get(&self, key: &str) -> Result<Value, SessionError> {
let pending = self.actions.as_ref().and_then(|a| {
a.lock()
.state_delta
.as_ref()
.and_then(|d| d.get(key).cloned())
});
if let Some(v) = pending {
return Ok(v);
}
self.session.state().get(key)
}
fn set(&self, key: &str, value: Value) -> Result<(), SessionError> {
if let Some(a) = &self.actions
&& let Some(d) = a.lock().state_delta.as_mut()
{
d.insert(key.to_string(), value.clone());
}
self.session.state().set(key, value)
}
fn all(&self) -> Vec<(String, Value)> {
self.session.state().all()
}
}