Skip to main content

hanzo_agent/
context.rs

1//! Runtime context for agent execution
2
3use crate::types::Usage;
4use std::any::Any;
5use std::sync::Arc;
6
7/// Runtime context wrapper for agent execution
8///
9/// The context holds user-provided state and usage statistics.
10/// It is passed to tools, hooks, and other callbacks during execution.
11#[derive(Debug, Clone)]
12pub struct RunContext {
13    /// User-provided context data
14    context: Option<Arc<dyn Any + Send + Sync>>,
15
16    /// Usage statistics
17    usage: Usage,
18}
19
20impl RunContext {
21    /// Create a new run context
22    pub fn new() -> Self {
23        Self {
24            context: None,
25            usage: Usage::default(),
26        }
27    }
28
29    /// Create a run context with user data
30    pub fn with_context<T: Any + Send + Sync + 'static>(data: T) -> Self {
31        Self {
32            context: Some(Arc::new(data)),
33            usage: Usage::default(),
34        }
35    }
36
37    /// Get the user context data
38    pub fn context<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
39        self.context.as_ref().and_then(|c| c.downcast_ref::<T>())
40    }
41
42    /// Get mutable access to usage statistics
43    pub fn usage_mut(&mut self) -> &mut Usage {
44        &mut self.usage
45    }
46
47    /// Get usage statistics
48    pub fn usage(&self) -> &Usage {
49        &self.usage
50    }
51
52    /// Add usage from a model response
53    pub fn add_usage(&mut self, usage: &Usage) {
54        self.usage.add(usage);
55    }
56}
57
58impl Default for RunContext {
59    fn default() -> Self {
60        Self::new()
61    }
62}