use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use async_trait::async_trait;
use serde_json::{Value, json};
use tokio::sync::mpsc;
use crate::engine::SessionStore;
use crate::types::{AgentError, AgentResult, RuntimeEvent, SessionId, UserEvent};
pub mod auto_continue;
pub mod policy;
pub mod update_plan;
pub(crate) mod schema_budget;
mod activate_tool;
mod activation;
mod deferred;
pub use activate_tool::ActivateTool;
pub use activation::ToolActivation;
pub use deferred::DeferredTool;
pub use auto_continue::AutoContinueTool;
pub use update_plan::UpdatePlanTool;
pub use policy::{DenyAllToolPolicy, ToolDecision, ToolPolicy};
pub use agent_types::{
ActivationContext, Content, ToolExposure, ToolMetadata, content_details, content_images,
content_text,
};
#[derive(Clone, Default)]
pub struct ExecClock {
inner: Arc<ExecClockInner>,
}
#[derive(Default)]
struct ExecClockInner {
state: std::sync::Mutex<ExecClockState>,
}
#[derive(Default)]
struct ExecClockState {
live: usize,
started: Option<std::time::Instant>,
total: std::time::Duration,
}
impl ExecClock {
pub fn pause(&self) -> ExecPauseGuard {
let mut state = self.lock();
state.live += 1;
if state.live == 1 {
state.started = Some(std::time::Instant::now());
}
ExecPauseGuard {
clock: self.clone(),
}
}
pub fn paused_total(&self) -> std::time::Duration {
let state = self.lock();
state.total
+ state
.started
.map_or(std::time::Duration::ZERO, |s| s.elapsed())
}
fn resume(&self) {
let mut state = self.lock();
state.live = state.live.saturating_sub(1);
if state.live == 0
&& let Some(started) = state.started.take()
{
state.total += started.elapsed();
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, ExecClockState> {
self.inner
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
pub struct ExecPauseGuard {
clock: ExecClock,
}
impl Drop for ExecPauseGuard {
fn drop(&mut self) {
self.clock.resume();
}
}
#[derive(Clone)]
pub struct ToolContext {
pub session_id: SessionId,
pub user_event_tx: mpsc::UnboundedSender<UserEvent>,
pub llm_client: Option<Arc<dyn llm_trait::LlmProvider>>,
pub session_store: Option<Arc<dyn SessionStore>>,
pub language: crate::types::Language,
pub cancel_token: tokio_util::sync::CancellationToken,
pub max_output_chars: Option<usize>,
pub exec_clock: ExecClock,
pub waiting_for_human: Arc<AtomicBool>,
pub(crate) event_bus: crate::engine::EventBus,
}
impl ToolContext {
pub fn pause_execution_clock(&self) -> ExecPauseGuard {
self.exec_clock.pause()
}
pub fn mark_waiting_for_human(&self) {
self.waiting_for_human.store(true, Ordering::Relaxed);
}
pub fn emit_user_event(&self, event: UserEvent) {
let _ = self.user_event_tx.send(event.clone());
self.event_bus.emit(RuntimeEvent::UserEvent {
session_id: self.session_id.clone(),
event,
agent_id: None,
trace_id: None,
});
}
pub fn emit_progress(&self, text: impl Into<String>) {
self.emit_user_event(UserEvent::Progress { text: text.into() });
}
pub fn emit_partial_result(
&self,
tool_call_id: &str,
content: impl Into<String>,
is_partial: bool,
) {
self.emit_user_event(UserEvent::ToolPartialResult {
tool_call_id: tool_call_id.to_string(),
content: content.into(),
is_partial,
});
}
pub fn for_test() -> Self {
let (tx, _rx) = mpsc::unbounded_channel();
ToolContext {
session_id: SessionId::new(0),
user_event_tx: tx,
llm_client: None,
session_store: None,
language: crate::types::Language::En,
cancel_token: tokio_util::sync::CancellationToken::new(),
max_output_chars: None,
exec_clock: ExecClock::default(),
waiting_for_human: Arc::new(AtomicBool::new(false)),
event_bus: crate::engine::EventBus::new(1),
}
}
pub fn new(
session_id: SessionId,
llm_client: Option<Arc<dyn crate::llm_trait::LlmProvider>>,
session_store: Option<Arc<dyn SessionStore>>,
cancel_token: tokio_util::sync::CancellationToken,
) -> Self {
let (tx, _rx) = mpsc::unbounded_channel();
ToolContext {
session_id,
user_event_tx: tx,
llm_client,
session_store,
language: crate::types::Language::En,
cancel_token,
max_output_chars: None,
exec_clock: ExecClock::default(),
waiting_for_human: Arc::new(AtomicBool::new(false)),
event_bus: crate::engine::EventBus::new(1),
}
}
}
#[async_trait]
pub trait Tool: Send + Sync {
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
fn schema(&self) -> Value;
async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>>;
fn timeout_ms(&self) -> Option<u64> {
None }
fn call_timeout_ms(&self, _args: &Value) -> Option<u64> {
self.timeout_ms()
}
fn metadata(&self) -> ToolMetadata {
ToolMetadata {
name: self.name().to_string(),
description: self.description().to_string(),
origin: "custom".to_string(),
version: "unknown".to_string(),
requirements: vec![],
}
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
fn should_activate(&self, ctx: &ActivationContext) -> bool {
ctx.current_tools.iter().any(|n| n == self.name())
}
}
#[async_trait]
pub trait TypedTool: Send + Sync {
type Args: serde::de::DeserializeOwned + schemars::JsonSchema;
type Output: serde::Serialize;
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
async fn call_typed(&self, args: Self::Args, ctx: &ToolContext) -> AgentResult<Self::Output>;
fn format_output(&self, output: Self::Output) -> Content {
match serde_json::to_value(&output) {
Ok(serde_json::Value::String(s)) => Content::text(s),
Ok(other) => Content::text(other.to_string()),
Err(_) => Content::text(String::new()),
}
}
fn origin(&self) -> &'static str {
"custom"
}
fn version(&self) -> &'static str {
"unknown"
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
fn should_activate(&self, ctx: &ActivationContext) -> bool {
ctx.current_tools.iter().any(|n| n == self.name())
}
}
#[async_trait]
impl<T: TypedTool + Send + Sync + 'static> Tool for T {
fn name(&self) -> &'static str {
TypedTool::name(self)
}
fn description(&self) -> &'static str {
TypedTool::description(self)
}
fn schema(&self) -> Value {
let settings = schemars::generate::SchemaSettings::draft07().with(|s| {
s.inline_subschemas = true;
s.meta_schema = None;
});
let generator = schemars::SchemaGenerator::new(settings);
let schema = generator.into_root_schema_for::<T::Args>();
serde_json::to_value(schema).unwrap_or(Value::Null)
}
fn metadata(&self) -> ToolMetadata {
ToolMetadata {
name: self.name().to_string(),
description: self.description().to_string(),
origin: self.origin().to_string(),
version: self.version().to_string(),
requirements: vec![],
}
}
fn exposure(&self) -> ToolExposure {
TypedTool::exposure(self)
}
fn should_activate(&self, ctx: &ActivationContext) -> bool {
TypedTool::should_activate(self, ctx)
}
async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
let typed_args: T::Args =
serde_json::from_value(args.clone()).map_err(|e| AgentError::ToolArgsInvalid {
name: self.name().to_string(),
raw: format!("{e} (args: {args})"),
})?;
let output = self.call_typed(typed_args, ctx).await?;
Ok(vec![self.format_output(output)])
}
}
pub fn render_tool_definition(tool: &dyn Tool) -> Value {
let mut parameters = tool.schema();
match schema_budget::fit_schema_to_budget(&mut parameters) {
schema_budget::FitOutcome::Untouched => {}
schema_budget::FitOutcome::Compressed(pass) => {
tracing::info!(
tool = tool.name(),
pass,
"tool schema compressed to fit the request budget"
);
}
schema_budget::FitOutcome::OverBudget => {
tracing::warn!(
tool = tool.name(),
budget = schema_budget::MAX_TOOL_SCHEMA_BYTES,
"tool schema exceeds the request budget after every pass; sent as-is"
);
}
}
json!({
"type": "function",
"function": {
"name": tool.name(),
"description": tool.description(),
"parameters": parameters,
}
})
}
pub(crate) type ToolRef = Arc<dyn Tool>;
#[derive(Clone, Default)]
pub struct ToolRegistry {
tools: HashMap<String, ToolRef>,
deferred: HashSet<String>,
}
impl ToolRegistry {
pub fn register(&mut self, tool: impl Tool + 'static) {
self.register_arc(Arc::new(tool));
}
pub fn register_arc(&mut self, tool: Arc<dyn Tool>) {
let name = tool.name().to_string();
let tool = if self.deferred.contains(&name) && tool.exposure() != ToolExposure::Deferred {
Arc::new(DeferredTool::new(tool)) as ToolRef
} else {
tool
};
self.tools.insert(name, tool);
}
pub fn remove(&mut self, name: &str) {
self.tools.remove(name);
}
pub fn get(&self, name: &str) -> Option<ToolRef> {
self.tools.get(name).cloned()
}
pub fn defer(&mut self, name: &str) -> Option<Value> {
self.deferred.insert(name.to_string());
let inner = self.tools.get(name)?;
let definition = render_tool_definition(inner.as_ref());
if inner.exposure() != ToolExposure::Deferred {
let wrapped = Arc::new(DeferredTool::new(inner.clone())) as ToolRef;
self.tools.insert(name.to_string(), wrapped);
}
Some(definition)
}
pub fn definitions(&self) -> Vec<Value> {
let mut tools: Vec<_> = self.tools.values().collect();
tools.sort_by_key(|t| t.name());
tools
.into_iter()
.map(|t| render_tool_definition(t.as_ref()))
.collect()
}
pub fn definitions_filtered(&self, ctx: &ActivationContext) -> Vec<Value> {
let mut tools: Vec<_> = self.tools.values().collect();
tools.sort_by_key(|t| t.name());
let direct_names: Vec<String> = tools
.iter()
.filter(|t| t.exposure() == ToolExposure::Direct)
.map(|t| t.name().to_string())
.collect();
let mut activated_names = direct_names.clone();
for name in &ctx.current_tools {
if !activated_names.contains(name) {
activated_names.push(name.clone());
}
}
for t in &tools {
if t.exposure() == ToolExposure::Deferred {
let mut ctx_with_tools = ctx.clone();
ctx_with_tools.current_tools = activated_names.clone();
if t.should_activate(&ctx_with_tools) {
activated_names.push(t.name().to_string());
}
}
}
tools
.into_iter()
.filter(|t| match t.exposure() {
ToolExposure::Direct => true,
ToolExposure::Deferred => activated_names.contains(&t.name().to_string()),
ToolExposure::Hidden => false,
})
.map(|t| render_tool_definition(t.as_ref()))
.collect()
}
pub fn len(&self) -> usize {
self.tools.len()
}
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
pub fn metadatas(&self) -> Vec<ToolMetadata> {
let mut list: Vec<_> = self.tools.values().map(|tool| tool.metadata()).collect();
list.sort_by(|a, b| a.name.cmp(&b.name));
list
}
}
#[cfg(test)]
mod tests;