use std::borrow::Cow;
use std::fmt::Write as _;
use std::hash::Hasher;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{Error, Result};
use async_trait::async_trait;
use serde_json::Value;
use vtcode_commons::serde_helpers::json_to_string_pretty;
use crate::cache::{CacheKey, UnifiedCache, estimate_json_size};
use crate::tool_policy::ToolPolicy;
use crate::tools::result::ToolResult as SplitToolResult;
use crate::tools::traits::Tool;
const MAX_RETRY_ATTEMPTS: u32 = 16;
const MAX_RETRY_BACKOFF: Duration = Duration::from_secs(30);
pub use vtcode_commons::cgp::{ComponentProvider, HasComponent};
pub use vtcode_commons::delegate_components;
mod execution;
use execution::value_to_text;
pub use execution::{
CachedResults, CanApproveTool, CanExecuteTool, CanProvideToolMetadata, CanResolveSandbox, ExponentialBackoffRetry,
HasExecutionCaches, HasRetryPolicy, PassthroughMetadata, ToolExecutionCacheKey, ToolFacade,
};
pub enum ApprovalComponent {}
pub enum SandboxComponent {}
pub enum ExecuteComponent {}
pub enum MetadataComponent {}
pub enum SessionComponent {}
pub enum OutputMapComponent {}
pub enum LoggingComponent {}
pub enum CacheComponent {}
pub enum RetryComponent {}
#[async_trait]
pub trait ApprovalProvider<Ctx: Send + Sync>: Send + Sync {
async fn check_approval(ctx: &Ctx, tool_name: &str, description: &str) -> Result<()>;
}
pub trait SandboxProvider<Ctx: Send + Sync>: Send + Sync {
fn sandbox_enabled(ctx: &Ctx) -> bool;
fn workspace_root(ctx: &Ctx) -> Option<&PathBuf>;
}
pub trait MetadataProvider<Ctx>: Send + Sync {
fn tool_name(_ctx: &Ctx) -> &str {
"unknown"
}
fn tool_description(_ctx: &Ctx) -> &str {
""
}
fn parameter_schema(_ctx: &Ctx) -> Option<Value> {
None
}
fn config_schema(_ctx: &Ctx) -> Option<Value> {
None
}
fn state_schema(_ctx: &Ctx) -> Option<Value> {
None
}
fn prompt_path(_ctx: &Ctx) -> Option<Cow<'static, str>> {
None
}
fn default_permission(_ctx: &Ctx) -> ToolPolicy {
ToolPolicy::Prompt
}
fn allow_patterns(_ctx: &Ctx) -> Option<&'static [&'static str]> {
None
}
fn deny_patterns(_ctx: &Ctx) -> Option<&'static [&'static str]> {
None
}
fn is_mutating(_ctx: &Ctx) -> bool {
true
}
fn is_parallel_safe(ctx: &Ctx) -> bool {
!Self::is_mutating(ctx)
}
fn tool_kind(_ctx: &Ctx) -> &'static str {
"unknown"
}
fn resource_hints(_ctx: &Ctx, _args: &Value) -> Vec<String> {
Vec::new()
}
fn execution_cost(_ctx: &Ctx) -> u8 {
5
}
}
pub trait OutputMapProvider<Ctx>: Send + Sync {
type Input;
type Output;
fn map_output(ctx: &Ctx, input: Self::Input) -> Self::Output;
}
#[async_trait]
pub trait ExecuteProvider<Ctx: Send + Sync>: Send + Sync {
async fn execute(ctx: &Ctx, args: Value) -> Result<Value>;
async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
let result = Self::execute(ctx, args).await?;
let name = if let Some(n) = result.get("tool_name").and_then(|v| v.as_str()) {
n.to_string()
} else {
"unknown".to_string()
};
let content = value_to_text(&result);
Ok(SplitToolResult::simple(&name, content))
}
}
pub trait LoggingProvider<Ctx>: Send + Sync {
fn on_start(_ctx: &Ctx, _tool_name: &str, _args: &Value) {}
fn on_cache_hit(_ctx: &Ctx, _tool_name: &str, _args: &Value) {}
fn on_success(_ctx: &Ctx, _tool_name: &str, _duration: Duration, _attempt: u32, _from_cache: bool) {}
fn on_retry(_ctx: &Ctx, _tool_name: &str, _next_attempt: u32, _backoff: Duration, _error: &Error) {}
fn on_failure(_ctx: &Ctx, _tool_name: &str, _duration: Duration, _attempt: u32, _error: &Error) {}
}
pub trait CacheProvider<Ctx>: Send + Sync {
fn get_json(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> Option<Value> {
None
}
fn put_json(_ctx: &Ctx, _tool_name: &str, _args: &Value, _result: &Value) {}
fn get_dual(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> Option<SplitToolResult> {
None
}
fn put_dual(_ctx: &Ctx, _tool_name: &str, _args: &Value, _result: &SplitToolResult) {}
}
pub trait RetryProvider<Ctx>: Send + Sync {
fn max_attempts(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> u32 {
1
}
fn should_retry(_ctx: &Ctx, _tool_name: &str, _attempt: u32, _error: &Error) -> bool {
false
}
fn backoff_duration(_ctx: &Ctx, _tool_name: &str, _attempt: u32) -> Duration {
Duration::ZERO
}
}
pub struct AutoApproval;
#[async_trait]
impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for AutoApproval {
async fn check_approval(_ctx: &Ctx, _tool_name: &str, _description: &str) -> Result<()> {
Ok(())
}
}
pub struct DenyAllApproval;
#[async_trait]
impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for DenyAllApproval {
async fn check_approval(_ctx: &Ctx, tool_name: &str, _description: &str) -> Result<()> {
anyhow::bail!("operation denied: {tool_name} is not permitted in this context")
}
}
pub struct NoSandbox;
#[async_trait]
impl<Ctx: Send + Sync> SandboxProvider<Ctx> for NoSandbox {
fn sandbox_enabled(_ctx: &Ctx) -> bool {
false
}
fn workspace_root(_ctx: &Ctx) -> Option<&PathBuf> {
None
}
}
pub struct DefaultMetadata;
impl<Ctx> MetadataProvider<Ctx> for DefaultMetadata {}
pub struct NoLogging;
impl<Ctx> LoggingProvider<Ctx> for NoLogging {}
pub struct NoCache;
impl<Ctx> CacheProvider<Ctx> for NoCache {}
pub struct NoRetry;
impl<Ctx> RetryProvider<Ctx> for NoRetry {}
pub struct TracingLogging;
impl<Ctx> LoggingProvider<Ctx> for TracingLogging {
fn on_start(_ctx: &Ctx, tool_name: &str, _args: &Value) {
tracing::trace!(tool = %tool_name, "CGP tool execution started");
}
fn on_cache_hit(_ctx: &Ctx, tool_name: &str, _args: &Value) {
tracing::debug!(tool = %tool_name, "CGP tool result served from cache");
}
fn on_success(_ctx: &Ctx, tool_name: &str, duration: Duration, attempt: u32, from_cache: bool) {
tracing::trace!(
tool = %tool_name,
duration_ms = duration.as_millis() as u64,
attempt,
from_cache,
"CGP tool execution succeeded"
);
}
fn on_retry(_ctx: &Ctx, tool_name: &str, next_attempt: u32, backoff: Duration, error: &Error) {
tracing::debug!(
tool = %tool_name,
next_attempt,
backoff_ms = backoff.as_millis() as u64,
error = %error,
"CGP tool execution retry scheduled"
);
}
fn on_failure(_ctx: &Ctx, tool_name: &str, duration: Duration, attempt: u32, error: &Error) {
tracing::warn!(
tool = %tool_name,
duration_ms = duration.as_millis() as u64,
attempt,
error = %error,
"CGP tool execution failed"
);
}
}
pub use crate::retry::RetryPolicy;
pub struct ComposableRuntime;
impl ComposableRuntime {
pub async fn run<Ctx>(ctx: &Ctx, tool_name: &str, description: &str) -> Result<()>
where
Ctx: CanApproveTool + Send + Sync,
{
ctx.approve_tool(tool_name, description).await?;
Ok(())
}
pub async fn run_with_sandbox<Ctx>(ctx: &Ctx, tool_name: &str, description: &str) -> Result<bool>
where
Ctx: CanApproveTool + CanResolveSandbox + Send + Sync,
{
ctx.approve_tool(tool_name, description).await?;
Ok(ctx.sandbox_enabled())
}
}
pub struct InteractiveCtx {
pub workspace_root: PathBuf,
}
impl InteractiveCtx {
pub fn new(workspace_root: PathBuf) -> Self {
Self { workspace_root }
}
}
pub struct PromptApproval;
#[async_trait]
impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for PromptApproval {
async fn check_approval(_ctx: &Ctx, _tool_name: &str, _description: &str) -> Result<()> {
Ok(())
}
}
pub trait HasWorkspaceRoot: Send + Sync {
fn workspace_root(&self) -> &PathBuf;
}
impl HasWorkspaceRoot for InteractiveCtx {
fn workspace_root(&self) -> &PathBuf {
&self.workspace_root
}
}
pub struct WorkspaceSandbox;
#[async_trait]
impl<Ctx: HasWorkspaceRoot> SandboxProvider<Ctx> for WorkspaceSandbox {
fn sandbox_enabled(_ctx: &Ctx) -> bool {
true
}
fn workspace_root(ctx: &Ctx) -> Option<&PathBuf> {
Some(HasWorkspaceRoot::workspace_root(ctx))
}
}
delegate_components!(InteractiveCtx {
ApprovalComponent => PromptApproval,
SandboxComponent => WorkspaceSandbox,
ExecuteComponent => PassthroughExecutor,
MetadataComponent => PassthroughMetadata,
LoggingComponent => TracingLogging,
CacheComponent => NoCache,
RetryComponent => NoRetry,
});
pub struct CiCtx {
pub workspace_root: PathBuf,
}
impl CiCtx {
pub fn new(workspace_root: PathBuf) -> Self {
Self { workspace_root }
}
}
impl HasWorkspaceRoot for CiCtx {
fn workspace_root(&self) -> &PathBuf {
&self.workspace_root
}
}
pub type StrictWorkspaceSandbox = WorkspaceSandbox;
delegate_components!(CiCtx {
ApprovalComponent => AutoApproval,
SandboxComponent => StrictWorkspaceSandbox,
ExecuteComponent => PassthroughExecutor,
MetadataComponent => PassthroughMetadata,
LoggingComponent => NoLogging,
CacheComponent => NoCache,
RetryComponent => NoRetry,
});
pub struct BenchCtx;
delegate_components!(BenchCtx {
ApprovalComponent => AutoApproval,
SandboxComponent => NoSandbox,
ExecuteComponent => PassthroughExecutor,
MetadataComponent => PassthroughMetadata,
LoggingComponent => NoLogging,
CacheComponent => NoCache,
RetryComponent => NoRetry,
});
pub struct PassthroughExecutor;
pub trait HasToolRef: Send + Sync {
fn tool(&self) -> &dyn Tool;
}
pub trait HasInnerTool: Send + Sync {
fn inner_tool(&self) -> &dyn Tool;
}
impl<Ctx> HasToolRef for Ctx
where
Ctx: HasInnerTool + Send + Sync,
{
fn tool(&self) -> &dyn Tool {
self.inner_tool()
}
}
#[async_trait]
impl<Ctx: HasToolRef> ExecuteProvider<Ctx> for PassthroughExecutor {
async fn execute(ctx: &Ctx, args: Value) -> Result<Value> {
let tool = ctx.tool();
tool.validate_args(&args)?;
tool.execute(args).await
}
async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
let tool = ctx.tool();
tool.validate_args(&args)?;
tool.execute_dual(args).await
}
}
pub fn wrap_tool_interactive(
tool: Arc<dyn Tool>,
workspace_root: PathBuf,
) -> ToolFacade<ToolBridgeCtx<InteractiveCtx>> {
let ctx = ToolBridgeCtx {
inner: tool,
runtime: InteractiveCtx::new(workspace_root),
};
ToolFacade::new(ctx)
}
pub fn wrap_tool_ci(tool: Arc<dyn Tool>, workspace_root: PathBuf) -> ToolFacade<ToolBridgeCtx<CiCtx>> {
let ctx = ToolBridgeCtx { inner: tool, runtime: CiCtx::new(workspace_root) };
ToolFacade::new(ctx)
}
pub struct ToolBridgeCtx<Runtime> {
inner: Arc<dyn Tool>,
runtime: Runtime,
}
impl<Runtime: HasWorkspaceRoot> HasWorkspaceRoot for ToolBridgeCtx<Runtime> {
fn workspace_root(&self) -> &PathBuf {
self.runtime.workspace_root()
}
}
impl<Runtime: Send + Sync> HasInnerTool for ToolBridgeCtx<Runtime> {
fn inner_tool(&self) -> &dyn Tool {
self.inner.as_ref()
}
}
impl<Name, Runtime> HasComponent<Name> for ToolBridgeCtx<Runtime>
where
Runtime: HasComponent<Name>,
{
type Provider = ComponentProvider<Runtime, Name>;
}
pub trait HasToolInstance<T>: Send + Sync {
fn tool_instance(&self) -> &T;
}
pub struct TypedToolExecutor<T>(PhantomData<T>);
#[async_trait]
impl<Ctx, T> ExecuteProvider<Ctx> for TypedToolExecutor<T>
where
Ctx: HasToolRef + Send + Sync,
T: Tool + Send + Sync,
{
async fn execute(ctx: &Ctx, args: Value) -> Result<Value> {
<PassthroughExecutor as ExecuteProvider<Ctx>>::execute(ctx, args).await
}
async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
<PassthroughExecutor as ExecuteProvider<Ctx>>::execute_dual(ctx, args).await
}
}
pub struct TypedToolMetadata<T>(PhantomData<T>);
impl<Ctx, T> MetadataProvider<Ctx> for TypedToolMetadata<T>
where
Ctx: HasToolRef,
T: Tool + Send + Sync,
{
fn tool_name(ctx: &Ctx) -> &str {
<PassthroughMetadata as MetadataProvider<Ctx>>::tool_name(ctx)
}
fn tool_description(ctx: &Ctx) -> &str {
<PassthroughMetadata as MetadataProvider<Ctx>>::tool_description(ctx)
}
fn parameter_schema(ctx: &Ctx) -> Option<Value> {
<PassthroughMetadata as MetadataProvider<Ctx>>::parameter_schema(ctx)
}
fn config_schema(ctx: &Ctx) -> Option<Value> {
<PassthroughMetadata as MetadataProvider<Ctx>>::config_schema(ctx)
}
fn state_schema(ctx: &Ctx) -> Option<Value> {
<PassthroughMetadata as MetadataProvider<Ctx>>::state_schema(ctx)
}
fn prompt_path(ctx: &Ctx) -> Option<Cow<'static, str>> {
<PassthroughMetadata as MetadataProvider<Ctx>>::prompt_path(ctx)
}
fn default_permission(ctx: &Ctx) -> ToolPolicy {
<PassthroughMetadata as MetadataProvider<Ctx>>::default_permission(ctx)
}
fn allow_patterns(ctx: &Ctx) -> Option<&'static [&'static str]> {
<PassthroughMetadata as MetadataProvider<Ctx>>::allow_patterns(ctx)
}
fn deny_patterns(ctx: &Ctx) -> Option<&'static [&'static str]> {
<PassthroughMetadata as MetadataProvider<Ctx>>::deny_patterns(ctx)
}
fn is_mutating(ctx: &Ctx) -> bool {
<PassthroughMetadata as MetadataProvider<Ctx>>::is_mutating(ctx)
}
fn is_parallel_safe(ctx: &Ctx) -> bool {
<PassthroughMetadata as MetadataProvider<Ctx>>::is_parallel_safe(ctx)
}
fn tool_kind(ctx: &Ctx) -> &'static str {
<PassthroughMetadata as MetadataProvider<Ctx>>::tool_kind(ctx)
}
fn resource_hints(ctx: &Ctx, args: &Value) -> Vec<String> {
<PassthroughMetadata as MetadataProvider<Ctx>>::resource_hints(ctx, args)
}
fn execution_cost(ctx: &Ctx) -> u8 {
<PassthroughMetadata as MetadataProvider<Ctx>>::execution_cost(ctx)
}
}
pub struct TypedToolCtx<Runtime, T> {
tool: T,
runtime: Runtime,
}
impl<Runtime, T> TypedToolCtx<Runtime, T> {
pub fn new(tool: T, runtime: Runtime) -> Self {
Self { tool, runtime }
}
}
impl<Runtime: HasWorkspaceRoot + Send + Sync, T: Send + Sync> HasWorkspaceRoot for TypedToolCtx<Runtime, T> {
fn workspace_root(&self) -> &PathBuf {
self.runtime.workspace_root()
}
}
impl<Runtime: Send + Sync, T: Send + Sync> HasToolInstance<T> for TypedToolCtx<Runtime, T> {
fn tool_instance(&self) -> &T {
&self.tool
}
}
impl<Runtime: Send + Sync, T> HasToolRef for TypedToolCtx<Runtime, T>
where
T: Tool + Send + Sync,
{
fn tool(&self) -> &dyn Tool {
&self.tool
}
}
macro_rules! delegate_runtime_components_for_typed_ctx {
($($component:ty),+ $(,)?) => {
$(
impl<Runtime, T> HasComponent<$component> for TypedToolCtx<Runtime, T>
where
Runtime: HasComponent<$component>,
{
type Provider = ComponentProvider<Runtime, $component>;
}
)+
};
}
delegate_runtime_components_for_typed_ctx!(
ApprovalComponent,
SandboxComponent,
SessionComponent,
OutputMapComponent,
LoggingComponent,
CacheComponent,
RetryComponent,
);
impl<Runtime, T> HasComponent<ExecuteComponent> for TypedToolCtx<Runtime, T>
where
Runtime: Send + Sync,
T: Tool + Send + Sync,
{
type Provider = TypedToolExecutor<T>;
}
impl<Runtime, T> HasComponent<MetadataComponent> for TypedToolCtx<Runtime, T>
where
Runtime: Send + Sync,
T: Tool + Send + Sync,
{
type Provider = TypedToolMetadata<T>;
}
pub fn wrap_native_tool_interactive<T>(tool: T, workspace_root: PathBuf) -> ToolFacade<TypedToolCtx<InteractiveCtx, T>>
where
T: Tool + Send + Sync + 'static,
{
ToolFacade::new(TypedToolCtx::new(tool, InteractiveCtx::new(workspace_root)))
}
pub fn wrap_native_tool_ci<T>(tool: T, workspace_root: PathBuf) -> ToolFacade<TypedToolCtx<CiCtx, T>>
where
T: Tool + Send + Sync + 'static,
{
ToolFacade::new(TypedToolCtx::new(tool, CiCtx::new(workspace_root)))
}
#[cfg(test)]
mod tests;