1use std::borrow::Cow;
63use std::fmt::Write as _;
64use std::hash::Hasher;
65use std::marker::PhantomData;
66use std::path::PathBuf;
67use std::sync::Arc;
68use std::time::{Duration, Instant};
69
70use anyhow::{Error, Result};
71use async_trait::async_trait;
72use serde_json::Value;
73use vtcode_commons::serde_helpers::json_to_string_pretty;
74
75use crate::cache::{CacheKey, UnifiedCache, estimate_json_size};
76use crate::tool_policy::ToolPolicy;
77use crate::tools::result::ToolResult as SplitToolResult;
78use crate::tools::traits::Tool;
79
80const MAX_RETRY_ATTEMPTS: u32 = 16;
81const MAX_RETRY_BACKOFF: Duration = Duration::from_secs(30);
82
83pub use vtcode_commons::cgp::{ComponentProvider, HasComponent};
88pub use vtcode_commons::{check_components, delegate_and_check_components, delegate_components};
89
90mod execution;
95use execution::value_to_text;
96pub use execution::{
97 CachedResults, CanApproveTool, CanExecuteTool, CanProvideToolMetadata, CanResolveSandbox, ExponentialBackoffRetry,
98 HasExecutionCaches, HasRetryPolicy, PassthroughMetadata, ToolExecutionCacheKey, ToolFacade,
99};
100
101pub enum ApprovalComponent {}
103
104pub enum SandboxComponent {}
106
107pub enum ExecuteComponent {}
109
110pub enum MetadataComponent {}
112
113pub enum SessionComponent {}
115
116pub enum OutputMapComponent {}
118
119pub enum LoggingComponent {}
121
122pub enum CacheComponent {}
124
125pub enum RetryComponent {}
127
128#[async_trait]
138pub trait ApprovalProvider<Ctx: Send + Sync>: Send + Sync {
139 async fn check_approval(ctx: &Ctx, tool_name: &str, description: &str) -> Result<()>;
142}
143
144pub trait SandboxProvider<Ctx: Send + Sync>: Send + Sync {
146 fn sandbox_enabled(ctx: &Ctx) -> bool;
148
149 fn workspace_root(ctx: &Ctx) -> Option<&PathBuf>;
151}
152
153pub trait MetadataProvider<Ctx>: Send + Sync {
155 fn tool_name(_ctx: &Ctx) -> &str {
156 "unknown"
157 }
158
159 fn tool_description(_ctx: &Ctx) -> &str {
160 ""
161 }
162
163 fn parameter_schema(_ctx: &Ctx) -> Option<Value> {
164 None
165 }
166
167 fn config_schema(_ctx: &Ctx) -> Option<Value> {
168 None
169 }
170
171 fn state_schema(_ctx: &Ctx) -> Option<Value> {
172 None
173 }
174
175 fn prompt_path(_ctx: &Ctx) -> Option<Cow<'static, str>> {
176 None
177 }
178
179 fn default_permission(_ctx: &Ctx) -> ToolPolicy {
180 ToolPolicy::Prompt
181 }
182
183 fn allow_patterns(_ctx: &Ctx) -> Option<&'static [&'static str]> {
184 None
185 }
186
187 fn deny_patterns(_ctx: &Ctx) -> Option<&'static [&'static str]> {
188 None
189 }
190
191 fn is_mutating(_ctx: &Ctx) -> bool {
192 true
193 }
194
195 fn is_parallel_safe(ctx: &Ctx) -> bool {
196 !Self::is_mutating(ctx)
197 }
198
199 fn tool_kind(_ctx: &Ctx) -> &'static str {
200 "unknown"
201 }
202
203 fn resource_hints(_ctx: &Ctx, _args: &Value) -> Vec<String> {
204 Vec::new()
205 }
206
207 fn execution_cost(_ctx: &Ctx) -> u8 {
208 5
209 }
210}
211
212pub trait OutputMapProvider<Ctx>: Send + Sync {
214 type Input;
215 type Output;
216
217 fn map_output(ctx: &Ctx, input: Self::Input) -> Self::Output;
218}
219
220#[async_trait]
226pub trait ExecuteProvider<Ctx: Send + Sync>: Send + Sync {
227 async fn execute(ctx: &Ctx, args: Value) -> Result<Value>;
229
230 async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
234 let result = Self::execute(ctx, args).await?;
235 let name = if let Some(n) = result.get("tool_name").and_then(|v| v.as_str()) {
236 n.to_string()
237 } else {
238 "unknown".to_string()
239 };
240 let content = value_to_text(&result);
241 Ok(SplitToolResult::simple(&name, content))
242 }
243}
244
245pub trait LoggingProvider<Ctx>: Send + Sync {
247 fn on_start(_ctx: &Ctx, _tool_name: &str, _args: &Value) {}
248
249 fn on_cache_hit(_ctx: &Ctx, _tool_name: &str, _args: &Value) {}
250
251 fn on_success(_ctx: &Ctx, _tool_name: &str, _duration: Duration, _attempt: u32, _from_cache: bool) {}
252
253 fn on_retry(_ctx: &Ctx, _tool_name: &str, _next_attempt: u32, _backoff: Duration, _error: &Error) {}
254
255 fn on_failure(_ctx: &Ctx, _tool_name: &str, _duration: Duration, _attempt: u32, _error: &Error) {}
256}
257
258pub trait CacheProvider<Ctx>: Send + Sync {
260 fn get_json(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> Option<Value> {
261 None
262 }
263
264 fn put_json(_ctx: &Ctx, _tool_name: &str, _args: &Value, _result: &Value) {}
265
266 fn get_dual(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> Option<SplitToolResult> {
267 None
268 }
269
270 fn put_dual(_ctx: &Ctx, _tool_name: &str, _args: &Value, _result: &SplitToolResult) {}
271}
272
273pub trait RetryProvider<Ctx>: Send + Sync {
275 fn max_attempts(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> u32 {
276 1
277 }
278
279 fn should_retry(_ctx: &Ctx, _tool_name: &str, _attempt: u32, _error: &Error) -> bool {
280 false
281 }
282
283 fn backoff_duration(_ctx: &Ctx, _tool_name: &str, _attempt: u32) -> Duration {
284 Duration::ZERO
285 }
286}
287
288pub struct AutoApproval;
294
295#[async_trait]
296impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for AutoApproval {
297 async fn check_approval(_ctx: &Ctx, _tool_name: &str, _description: &str) -> Result<()> {
298 Ok(())
299 }
300}
301
302pub struct DenyAllApproval;
304
305#[async_trait]
306impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for DenyAllApproval {
307 async fn check_approval(_ctx: &Ctx, tool_name: &str, _description: &str) -> Result<()> {
308 anyhow::bail!("operation denied: {tool_name} is not permitted in this context")
309 }
310}
311
312pub struct NoSandbox;
314
315#[async_trait]
316impl<Ctx: Send + Sync> SandboxProvider<Ctx> for NoSandbox {
317 fn sandbox_enabled(_ctx: &Ctx) -> bool {
318 false
319 }
320
321 fn workspace_root(_ctx: &Ctx) -> Option<&PathBuf> {
322 None
323 }
324}
325
326pub struct DefaultMetadata;
328
329impl<Ctx> MetadataProvider<Ctx> for DefaultMetadata {}
330
331pub struct NoLogging;
333
334impl<Ctx> LoggingProvider<Ctx> for NoLogging {}
335
336pub struct NoCache;
338
339impl<Ctx> CacheProvider<Ctx> for NoCache {}
340
341pub struct NoRetry;
343
344impl<Ctx> RetryProvider<Ctx> for NoRetry {}
345
346pub struct TracingLogging;
348
349impl<Ctx> LoggingProvider<Ctx> for TracingLogging {
350 fn on_start(_ctx: &Ctx, tool_name: &str, _args: &Value) {
351 tracing::trace!(tool = %tool_name, "CGP tool execution started");
352 }
353
354 fn on_cache_hit(_ctx: &Ctx, tool_name: &str, _args: &Value) {
355 tracing::debug!(tool = %tool_name, "CGP tool result served from cache");
356 }
357
358 fn on_success(_ctx: &Ctx, tool_name: &str, duration: Duration, attempt: u32, from_cache: bool) {
359 tracing::trace!(
360 tool = %tool_name,
361 duration_ms = duration.as_millis() as u64,
362 attempt,
363 from_cache,
364 "CGP tool execution succeeded"
365 );
366 }
367
368 fn on_retry(_ctx: &Ctx, tool_name: &str, next_attempt: u32, backoff: Duration, error: &Error) {
369 tracing::debug!(
370 tool = %tool_name,
371 next_attempt,
372 backoff_ms = backoff.as_millis() as u64,
373 error = %error,
374 "CGP tool execution retry scheduled"
375 );
376 }
377
378 fn on_failure(_ctx: &Ctx, tool_name: &str, duration: Duration, attempt: u32, error: &Error) {
379 tracing::warn!(
380 tool = %tool_name,
381 duration_ms = duration.as_millis() as u64,
382 attempt,
383 error = %error,
384 "CGP tool execution failed"
385 );
386 }
387}
388
389pub use crate::retry::RetryPolicy;
392
393pub struct ComposableRuntime;
403
404impl ComposableRuntime {
405 pub async fn run<Ctx>(ctx: &Ctx, tool_name: &str, description: &str) -> Result<()>
409 where
410 Ctx: CanApproveTool + Send + Sync,
411 {
412 ctx.approve_tool(tool_name, description).await?;
413 Ok(())
414 }
415
416 pub async fn run_with_sandbox<Ctx>(ctx: &Ctx, tool_name: &str, description: &str) -> Result<bool>
419 where
420 Ctx: CanApproveTool + CanResolveSandbox + Send + Sync,
421 {
422 ctx.approve_tool(tool_name, description).await?;
423 Ok(ctx.sandbox_enabled())
424 }
425}
426
427pub struct InteractiveCtx {
436 pub workspace_root: PathBuf,
437}
438
439impl InteractiveCtx {
440 pub fn new(workspace_root: PathBuf) -> Self {
441 Self { workspace_root }
442 }
443}
444
445pub struct PromptApproval;
452
453#[async_trait]
454impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for PromptApproval {
455 async fn check_approval(_ctx: &Ctx, _tool_name: &str, _description: &str) -> Result<()> {
456 Ok(())
459 }
460}
461
462pub trait HasWorkspaceRoot: Send + Sync {
464 fn workspace_root(&self) -> &PathBuf;
465}
466
467impl HasWorkspaceRoot for InteractiveCtx {
468 fn workspace_root(&self) -> &PathBuf {
469 &self.workspace_root
470 }
471}
472
473pub struct WorkspaceSandbox;
478
479#[async_trait]
480impl<Ctx: HasWorkspaceRoot> SandboxProvider<Ctx> for WorkspaceSandbox {
481 fn sandbox_enabled(_ctx: &Ctx) -> bool {
482 true
483 }
484
485 fn workspace_root(ctx: &Ctx) -> Option<&PathBuf> {
486 Some(HasWorkspaceRoot::workspace_root(ctx))
487 }
488}
489
490delegate_components!(InteractiveCtx {
491 ApprovalComponent => PromptApproval,
492 SandboxComponent => WorkspaceSandbox,
493 ExecuteComponent => PassthroughExecutor,
494 MetadataComponent => PassthroughMetadata,
495 LoggingComponent => TracingLogging,
496 CacheComponent => NoCache,
497 RetryComponent => NoRetry,
498});
499
500pub struct CiCtx {
502 pub workspace_root: PathBuf,
503}
504
505impl CiCtx {
506 pub fn new(workspace_root: PathBuf) -> Self {
507 Self { workspace_root }
508 }
509}
510
511impl HasWorkspaceRoot for CiCtx {
512 fn workspace_root(&self) -> &PathBuf {
513 &self.workspace_root
514 }
515}
516
517pub type StrictWorkspaceSandbox = WorkspaceSandbox;
519
520delegate_components!(CiCtx {
521 ApprovalComponent => AutoApproval,
522 SandboxComponent => StrictWorkspaceSandbox,
523 ExecuteComponent => PassthroughExecutor,
524 MetadataComponent => PassthroughMetadata,
525 LoggingComponent => NoLogging,
526 CacheComponent => NoCache,
527 RetryComponent => NoRetry,
528});
529
530pub struct BenchCtx;
532
533delegate_components!(BenchCtx {
534 ApprovalComponent => AutoApproval,
535 SandboxComponent => NoSandbox,
536 ExecuteComponent => PassthroughExecutor,
537 MetadataComponent => PassthroughMetadata,
538 LoggingComponent => NoLogging,
539 CacheComponent => NoCache,
540 RetryComponent => NoRetry,
541});
542
543pub struct PassthroughExecutor;
549
550pub trait HasToolRef: Send + Sync {
553 fn tool(&self) -> &dyn Tool;
554}
555
556pub trait HasInnerTool: Send + Sync {
561 fn inner_tool(&self) -> &dyn Tool;
562}
563
564impl<Ctx> HasToolRef for Ctx
565where
566 Ctx: HasInnerTool + Send + Sync,
567{
568 fn tool(&self) -> &dyn Tool {
569 self.inner_tool()
570 }
571}
572
573#[async_trait]
574impl<Ctx: HasToolRef> ExecuteProvider<Ctx> for PassthroughExecutor {
575 async fn execute(ctx: &Ctx, args: Value) -> Result<Value> {
576 let tool = ctx.tool();
577 tool.validate_args(&args)?;
578 tool.execute(args).await
579 }
580
581 async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
582 let tool = ctx.tool();
583 tool.validate_args(&args)?;
584 tool.execute_dual(args).await
585 }
586}
587
588pub fn wrap_tool_interactive(
601 tool: Arc<dyn Tool>,
602 workspace_root: PathBuf,
603) -> ToolFacade<ToolBridgeCtx<InteractiveCtx>> {
604 let ctx = ToolBridgeCtx {
605 inner: tool,
606 runtime: InteractiveCtx::new(workspace_root),
607 };
608 ToolFacade::new(ctx)
609}
610
611pub fn wrap_tool_ci(tool: Arc<dyn Tool>, workspace_root: PathBuf) -> ToolFacade<ToolBridgeCtx<CiCtx>> {
617 let ctx = ToolBridgeCtx { inner: tool, runtime: CiCtx::new(workspace_root) };
618 ToolFacade::new(ctx)
619}
620
621pub struct ToolBridgeCtx<Runtime> {
628 inner: Arc<dyn Tool>,
629 runtime: Runtime,
633}
634
635impl<Runtime: HasWorkspaceRoot> HasWorkspaceRoot for ToolBridgeCtx<Runtime> {
636 fn workspace_root(&self) -> &PathBuf {
637 self.runtime.workspace_root()
638 }
639}
640
641impl<Runtime: Send + Sync> HasInnerTool for ToolBridgeCtx<Runtime> {
642 fn inner_tool(&self) -> &dyn Tool {
643 self.inner.as_ref()
644 }
645}
646
647impl<Name, Runtime> HasComponent<Name> for ToolBridgeCtx<Runtime>
649where
650 Runtime: HasComponent<Name>,
651{
652 type Provider = ComponentProvider<Runtime, Name>;
653}
654
655pub trait HasToolInstance<T>: Send + Sync {
657 fn tool_instance(&self) -> &T;
658}
659
660pub struct TypedToolExecutor<T>(PhantomData<T>);
662
663#[async_trait]
664impl<Ctx, T> ExecuteProvider<Ctx> for TypedToolExecutor<T>
665where
666 Ctx: HasToolRef + Send + Sync,
667 T: Tool + Send + Sync,
668{
669 async fn execute(ctx: &Ctx, args: Value) -> Result<Value> {
670 <PassthroughExecutor as ExecuteProvider<Ctx>>::execute(ctx, args).await
671 }
672
673 async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
674 <PassthroughExecutor as ExecuteProvider<Ctx>>::execute_dual(ctx, args).await
675 }
676}
677
678pub struct TypedToolMetadata<T>(PhantomData<T>);
680
681impl<Ctx, T> MetadataProvider<Ctx> for TypedToolMetadata<T>
682where
683 Ctx: HasToolRef,
684 T: Tool + Send + Sync,
685{
686 fn tool_name(ctx: &Ctx) -> &str {
687 <PassthroughMetadata as MetadataProvider<Ctx>>::tool_name(ctx)
688 }
689
690 fn tool_description(ctx: &Ctx) -> &str {
691 <PassthroughMetadata as MetadataProvider<Ctx>>::tool_description(ctx)
692 }
693
694 fn parameter_schema(ctx: &Ctx) -> Option<Value> {
695 <PassthroughMetadata as MetadataProvider<Ctx>>::parameter_schema(ctx)
696 }
697
698 fn config_schema(ctx: &Ctx) -> Option<Value> {
699 <PassthroughMetadata as MetadataProvider<Ctx>>::config_schema(ctx)
700 }
701
702 fn state_schema(ctx: &Ctx) -> Option<Value> {
703 <PassthroughMetadata as MetadataProvider<Ctx>>::state_schema(ctx)
704 }
705
706 fn prompt_path(ctx: &Ctx) -> Option<Cow<'static, str>> {
707 <PassthroughMetadata as MetadataProvider<Ctx>>::prompt_path(ctx)
708 }
709
710 fn default_permission(ctx: &Ctx) -> ToolPolicy {
711 <PassthroughMetadata as MetadataProvider<Ctx>>::default_permission(ctx)
712 }
713
714 fn allow_patterns(ctx: &Ctx) -> Option<&'static [&'static str]> {
715 <PassthroughMetadata as MetadataProvider<Ctx>>::allow_patterns(ctx)
716 }
717
718 fn deny_patterns(ctx: &Ctx) -> Option<&'static [&'static str]> {
719 <PassthroughMetadata as MetadataProvider<Ctx>>::deny_patterns(ctx)
720 }
721
722 fn is_mutating(ctx: &Ctx) -> bool {
723 <PassthroughMetadata as MetadataProvider<Ctx>>::is_mutating(ctx)
724 }
725
726 fn is_parallel_safe(ctx: &Ctx) -> bool {
727 <PassthroughMetadata as MetadataProvider<Ctx>>::is_parallel_safe(ctx)
728 }
729
730 fn tool_kind(ctx: &Ctx) -> &'static str {
731 <PassthroughMetadata as MetadataProvider<Ctx>>::tool_kind(ctx)
732 }
733
734 fn resource_hints(ctx: &Ctx, args: &Value) -> Vec<String> {
735 <PassthroughMetadata as MetadataProvider<Ctx>>::resource_hints(ctx, args)
736 }
737
738 fn execution_cost(ctx: &Ctx) -> u8 {
739 <PassthroughMetadata as MetadataProvider<Ctx>>::execution_cost(ctx)
740 }
741}
742
743pub struct TypedToolCtx<Runtime, T> {
745 tool: T,
746 runtime: Runtime,
747}
748
749impl<Runtime, T> TypedToolCtx<Runtime, T> {
750 pub fn new(tool: T, runtime: Runtime) -> Self {
751 Self { tool, runtime }
752 }
753}
754
755impl<Runtime: HasWorkspaceRoot + Send + Sync, T: Send + Sync> HasWorkspaceRoot for TypedToolCtx<Runtime, T> {
756 fn workspace_root(&self) -> &PathBuf {
757 self.runtime.workspace_root()
758 }
759}
760
761impl<Runtime: Send + Sync, T: Send + Sync> HasToolInstance<T> for TypedToolCtx<Runtime, T> {
762 fn tool_instance(&self) -> &T {
763 &self.tool
764 }
765}
766
767impl<Runtime: Send + Sync, T> HasToolRef for TypedToolCtx<Runtime, T>
768where
769 T: Tool + Send + Sync,
770{
771 fn tool(&self) -> &dyn Tool {
772 &self.tool
773 }
774}
775
776macro_rules! delegate_runtime_components_for_typed_ctx {
777 ($($component:ty),+ $(,)?) => {
778 $(
779 impl<Runtime, T> HasComponent<$component> for TypedToolCtx<Runtime, T>
780 where
781 Runtime: HasComponent<$component>,
782 {
783 type Provider = ComponentProvider<Runtime, $component>;
784 }
785 )+
786 };
787}
788
789delegate_runtime_components_for_typed_ctx!(
790 ApprovalComponent,
791 SandboxComponent,
792 SessionComponent,
793 OutputMapComponent,
794 LoggingComponent,
795 CacheComponent,
796 RetryComponent,
797);
798
799impl<Runtime, T> HasComponent<ExecuteComponent> for TypedToolCtx<Runtime, T>
800where
801 Runtime: Send + Sync,
802 T: Tool + Send + Sync,
803{
804 type Provider = TypedToolExecutor<T>;
805}
806
807impl<Runtime, T> HasComponent<MetadataComponent> for TypedToolCtx<Runtime, T>
808where
809 Runtime: Send + Sync,
810 T: Tool + Send + Sync,
811{
812 type Provider = TypedToolMetadata<T>;
813}
814
815pub fn wrap_native_tool_interactive<T>(tool: T, workspace_root: PathBuf) -> ToolFacade<TypedToolCtx<InteractiveCtx, T>>
821where
822 T: Tool + Send + Sync + 'static,
823{
824 ToolFacade::new(TypedToolCtx::new(tool, InteractiveCtx::new(workspace_root)))
825}
826
827pub fn wrap_native_tool_ci<T>(tool: T, workspace_root: PathBuf) -> ToolFacade<TypedToolCtx<CiCtx, T>>
833where
834 T: Tool + Send + Sync + 'static,
835{
836 ToolFacade::new(TypedToolCtx::new(tool, CiCtx::new(workspace_root)))
837}
838
839#[cfg(test)]
840mod tests;