1use std::borrow::Cow;
58use std::fmt::Write as _;
59use std::hash::Hasher;
60use std::marker::PhantomData;
61use std::path::PathBuf;
62use std::sync::Arc;
63use std::time::{Duration, Instant};
64
65use anyhow::{Error, Result};
66use async_trait::async_trait;
67use serde_json::Value;
68use vtcode_commons::serde_helpers::json_to_string_pretty;
69
70use crate::cache::{CacheKey, UnifiedCache, estimate_json_size};
71use crate::tool_policy::ToolPolicy;
72use crate::tools::result::ToolResult as SplitToolResult;
73use crate::tools::traits::Tool;
74
75const MAX_RETRY_ATTEMPTS: u32 = 16;
76const MAX_RETRY_BACKOFF: Duration = Duration::from_secs(30);
77
78pub use vtcode_commons::cgp::{ComponentProvider, HasComponent};
83pub use vtcode_commons::delegate_components;
84
85mod execution;
90use execution::value_to_text;
91pub use execution::{
92 CachedResults, CanApproveTool, CanExecuteTool, CanProvideToolMetadata, CanResolveSandbox, ExponentialBackoffRetry,
93 HasExecutionCaches, HasRetryPolicy, PassthroughMetadata, ToolExecutionCacheKey, ToolFacade,
94};
95
96pub enum ApprovalComponent {}
98
99pub enum SandboxComponent {}
101
102pub enum ExecuteComponent {}
104
105pub enum MetadataComponent {}
107
108pub enum SessionComponent {}
110
111pub enum OutputMapComponent {}
113
114pub enum LoggingComponent {}
116
117pub enum CacheComponent {}
119
120pub enum RetryComponent {}
122
123#[async_trait]
133pub trait ApprovalProvider<Ctx: Send + Sync>: Send + Sync {
134 async fn check_approval(ctx: &Ctx, tool_name: &str, description: &str) -> Result<()>;
137}
138
139pub trait SandboxProvider<Ctx: Send + Sync>: Send + Sync {
141 fn sandbox_enabled(ctx: &Ctx) -> bool;
143
144 fn workspace_root(ctx: &Ctx) -> Option<&PathBuf>;
146}
147
148pub trait MetadataProvider<Ctx>: Send + Sync {
150 fn tool_name(_ctx: &Ctx) -> &str {
151 "unknown"
152 }
153
154 fn tool_description(_ctx: &Ctx) -> &str {
155 ""
156 }
157
158 fn parameter_schema(_ctx: &Ctx) -> Option<Value> {
159 None
160 }
161
162 fn config_schema(_ctx: &Ctx) -> Option<Value> {
163 None
164 }
165
166 fn state_schema(_ctx: &Ctx) -> Option<Value> {
167 None
168 }
169
170 fn prompt_path(_ctx: &Ctx) -> Option<Cow<'static, str>> {
171 None
172 }
173
174 fn default_permission(_ctx: &Ctx) -> ToolPolicy {
175 ToolPolicy::Prompt
176 }
177
178 fn allow_patterns(_ctx: &Ctx) -> Option<&'static [&'static str]> {
179 None
180 }
181
182 fn deny_patterns(_ctx: &Ctx) -> Option<&'static [&'static str]> {
183 None
184 }
185
186 fn is_mutating(_ctx: &Ctx) -> bool {
187 true
188 }
189
190 fn is_parallel_safe(ctx: &Ctx) -> bool {
191 !Self::is_mutating(ctx)
192 }
193
194 fn tool_kind(_ctx: &Ctx) -> &'static str {
195 "unknown"
196 }
197
198 fn resource_hints(_ctx: &Ctx, _args: &Value) -> Vec<String> {
199 Vec::new()
200 }
201
202 fn execution_cost(_ctx: &Ctx) -> u8 {
203 5
204 }
205}
206
207pub trait OutputMapProvider<Ctx>: Send + Sync {
209 type Input;
210 type Output;
211
212 fn map_output(ctx: &Ctx, input: Self::Input) -> Self::Output;
213}
214
215#[async_trait]
221pub trait ExecuteProvider<Ctx: Send + Sync>: Send + Sync {
222 async fn execute(ctx: &Ctx, args: Value) -> Result<Value>;
224
225 async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
229 let result = Self::execute(ctx, args).await?;
230 let name = if let Some(n) = result.get("tool_name").and_then(|v| v.as_str()) {
231 n.to_string()
232 } else {
233 "unknown".to_string()
234 };
235 let content = value_to_text(&result);
236 Ok(SplitToolResult::simple(&name, content))
237 }
238}
239
240pub trait LoggingProvider<Ctx>: Send + Sync {
242 fn on_start(_ctx: &Ctx, _tool_name: &str, _args: &Value) {}
243
244 fn on_cache_hit(_ctx: &Ctx, _tool_name: &str, _args: &Value) {}
245
246 fn on_success(_ctx: &Ctx, _tool_name: &str, _duration: Duration, _attempt: u32, _from_cache: bool) {}
247
248 fn on_retry(_ctx: &Ctx, _tool_name: &str, _next_attempt: u32, _backoff: Duration, _error: &Error) {}
249
250 fn on_failure(_ctx: &Ctx, _tool_name: &str, _duration: Duration, _attempt: u32, _error: &Error) {}
251}
252
253pub trait CacheProvider<Ctx>: Send + Sync {
255 fn get_json(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> Option<Value> {
256 None
257 }
258
259 fn put_json(_ctx: &Ctx, _tool_name: &str, _args: &Value, _result: &Value) {}
260
261 fn get_dual(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> Option<SplitToolResult> {
262 None
263 }
264
265 fn put_dual(_ctx: &Ctx, _tool_name: &str, _args: &Value, _result: &SplitToolResult) {}
266}
267
268pub trait RetryProvider<Ctx>: Send + Sync {
270 fn max_attempts(_ctx: &Ctx, _tool_name: &str, _args: &Value) -> u32 {
271 1
272 }
273
274 fn should_retry(_ctx: &Ctx, _tool_name: &str, _attempt: u32, _error: &Error) -> bool {
275 false
276 }
277
278 fn backoff_duration(_ctx: &Ctx, _tool_name: &str, _attempt: u32) -> Duration {
279 Duration::ZERO
280 }
281}
282
283pub struct AutoApproval;
289
290#[async_trait]
291impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for AutoApproval {
292 async fn check_approval(_ctx: &Ctx, _tool_name: &str, _description: &str) -> Result<()> {
293 Ok(())
294 }
295}
296
297pub struct DenyAllApproval;
299
300#[async_trait]
301impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for DenyAllApproval {
302 async fn check_approval(_ctx: &Ctx, tool_name: &str, _description: &str) -> Result<()> {
303 anyhow::bail!("operation denied: {tool_name} is not permitted in this context")
304 }
305}
306
307pub struct NoSandbox;
309
310#[async_trait]
311impl<Ctx: Send + Sync> SandboxProvider<Ctx> for NoSandbox {
312 fn sandbox_enabled(_ctx: &Ctx) -> bool {
313 false
314 }
315
316 fn workspace_root(_ctx: &Ctx) -> Option<&PathBuf> {
317 None
318 }
319}
320
321pub struct DefaultMetadata;
323
324impl<Ctx> MetadataProvider<Ctx> for DefaultMetadata {}
325
326pub struct NoLogging;
328
329impl<Ctx> LoggingProvider<Ctx> for NoLogging {}
330
331pub struct NoCache;
333
334impl<Ctx> CacheProvider<Ctx> for NoCache {}
335
336pub struct NoRetry;
338
339impl<Ctx> RetryProvider<Ctx> for NoRetry {}
340
341pub struct TracingLogging;
343
344impl<Ctx> LoggingProvider<Ctx> for TracingLogging {
345 fn on_start(_ctx: &Ctx, tool_name: &str, _args: &Value) {
346 tracing::trace!(tool = %tool_name, "CGP tool execution started");
347 }
348
349 fn on_cache_hit(_ctx: &Ctx, tool_name: &str, _args: &Value) {
350 tracing::debug!(tool = %tool_name, "CGP tool result served from cache");
351 }
352
353 fn on_success(_ctx: &Ctx, tool_name: &str, duration: Duration, attempt: u32, from_cache: bool) {
354 tracing::trace!(
355 tool = %tool_name,
356 duration_ms = duration.as_millis() as u64,
357 attempt,
358 from_cache,
359 "CGP tool execution succeeded"
360 );
361 }
362
363 fn on_retry(_ctx: &Ctx, tool_name: &str, next_attempt: u32, backoff: Duration, error: &Error) {
364 tracing::debug!(
365 tool = %tool_name,
366 next_attempt,
367 backoff_ms = backoff.as_millis() as u64,
368 error = %error,
369 "CGP tool execution retry scheduled"
370 );
371 }
372
373 fn on_failure(_ctx: &Ctx, tool_name: &str, duration: Duration, attempt: u32, error: &Error) {
374 tracing::warn!(
375 tool = %tool_name,
376 duration_ms = duration.as_millis() as u64,
377 attempt,
378 error = %error,
379 "CGP tool execution failed"
380 );
381 }
382}
383
384pub use crate::retry::RetryPolicy;
387
388pub struct ComposableRuntime;
398
399impl ComposableRuntime {
400 pub async fn run<Ctx>(ctx: &Ctx, tool_name: &str, description: &str) -> Result<()>
404 where
405 Ctx: CanApproveTool + Send + Sync,
406 {
407 ctx.approve_tool(tool_name, description).await?;
408 Ok(())
409 }
410
411 pub async fn run_with_sandbox<Ctx>(ctx: &Ctx, tool_name: &str, description: &str) -> Result<bool>
414 where
415 Ctx: CanApproveTool + CanResolveSandbox + Send + Sync,
416 {
417 ctx.approve_tool(tool_name, description).await?;
418 Ok(ctx.sandbox_enabled())
419 }
420}
421
422pub struct InteractiveCtx {
431 pub workspace_root: PathBuf,
432}
433
434impl InteractiveCtx {
435 pub fn new(workspace_root: PathBuf) -> Self {
436 Self { workspace_root }
437 }
438}
439
440pub struct PromptApproval;
447
448#[async_trait]
449impl<Ctx: Send + Sync> ApprovalProvider<Ctx> for PromptApproval {
450 async fn check_approval(_ctx: &Ctx, _tool_name: &str, _description: &str) -> Result<()> {
451 Ok(())
454 }
455}
456
457pub trait HasWorkspaceRoot: Send + Sync {
459 fn workspace_root(&self) -> &PathBuf;
460}
461
462impl HasWorkspaceRoot for InteractiveCtx {
463 fn workspace_root(&self) -> &PathBuf {
464 &self.workspace_root
465 }
466}
467
468pub struct WorkspaceSandbox;
473
474#[async_trait]
475impl<Ctx: HasWorkspaceRoot> SandboxProvider<Ctx> for WorkspaceSandbox {
476 fn sandbox_enabled(_ctx: &Ctx) -> bool {
477 true
478 }
479
480 fn workspace_root(ctx: &Ctx) -> Option<&PathBuf> {
481 Some(HasWorkspaceRoot::workspace_root(ctx))
482 }
483}
484
485delegate_components!(InteractiveCtx {
486 ApprovalComponent => PromptApproval,
487 SandboxComponent => WorkspaceSandbox,
488 ExecuteComponent => PassthroughExecutor,
489 MetadataComponent => PassthroughMetadata,
490 LoggingComponent => TracingLogging,
491 CacheComponent => NoCache,
492 RetryComponent => NoRetry,
493});
494
495pub struct CiCtx {
497 pub workspace_root: PathBuf,
498}
499
500impl CiCtx {
501 pub fn new(workspace_root: PathBuf) -> Self {
502 Self { workspace_root }
503 }
504}
505
506impl HasWorkspaceRoot for CiCtx {
507 fn workspace_root(&self) -> &PathBuf {
508 &self.workspace_root
509 }
510}
511
512pub type StrictWorkspaceSandbox = WorkspaceSandbox;
514
515delegate_components!(CiCtx {
516 ApprovalComponent => AutoApproval,
517 SandboxComponent => StrictWorkspaceSandbox,
518 ExecuteComponent => PassthroughExecutor,
519 MetadataComponent => PassthroughMetadata,
520 LoggingComponent => NoLogging,
521 CacheComponent => NoCache,
522 RetryComponent => NoRetry,
523});
524
525pub struct BenchCtx;
527
528delegate_components!(BenchCtx {
529 ApprovalComponent => AutoApproval,
530 SandboxComponent => NoSandbox,
531 ExecuteComponent => PassthroughExecutor,
532 MetadataComponent => PassthroughMetadata,
533 LoggingComponent => NoLogging,
534 CacheComponent => NoCache,
535 RetryComponent => NoRetry,
536});
537
538pub struct PassthroughExecutor;
544
545pub trait HasToolRef: Send + Sync {
548 fn tool(&self) -> &dyn Tool;
549}
550
551pub trait HasInnerTool: Send + Sync {
556 fn inner_tool(&self) -> &dyn Tool;
557}
558
559impl<Ctx> HasToolRef for Ctx
560where
561 Ctx: HasInnerTool + Send + Sync,
562{
563 fn tool(&self) -> &dyn Tool {
564 self.inner_tool()
565 }
566}
567
568#[async_trait]
569impl<Ctx: HasToolRef> ExecuteProvider<Ctx> for PassthroughExecutor {
570 async fn execute(ctx: &Ctx, args: Value) -> Result<Value> {
571 let tool = ctx.tool();
572 tool.validate_args(&args)?;
573 tool.execute(args).await
574 }
575
576 async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
577 let tool = ctx.tool();
578 tool.validate_args(&args)?;
579 tool.execute_dual(args).await
580 }
581}
582
583pub fn wrap_tool_interactive(
596 tool: Arc<dyn Tool>,
597 workspace_root: PathBuf,
598) -> ToolFacade<ToolBridgeCtx<InteractiveCtx>> {
599 let ctx = ToolBridgeCtx {
600 inner: tool,
601 runtime: InteractiveCtx::new(workspace_root),
602 };
603 ToolFacade::new(ctx)
604}
605
606pub fn wrap_tool_ci(tool: Arc<dyn Tool>, workspace_root: PathBuf) -> ToolFacade<ToolBridgeCtx<CiCtx>> {
612 let ctx = ToolBridgeCtx { inner: tool, runtime: CiCtx::new(workspace_root) };
613 ToolFacade::new(ctx)
614}
615
616pub struct ToolBridgeCtx<Runtime> {
623 inner: Arc<dyn Tool>,
624 runtime: Runtime,
628}
629
630impl<Runtime: HasWorkspaceRoot> HasWorkspaceRoot for ToolBridgeCtx<Runtime> {
631 fn workspace_root(&self) -> &PathBuf {
632 self.runtime.workspace_root()
633 }
634}
635
636impl<Runtime: Send + Sync> HasInnerTool for ToolBridgeCtx<Runtime> {
637 fn inner_tool(&self) -> &dyn Tool {
638 self.inner.as_ref()
639 }
640}
641
642impl<Name, Runtime> HasComponent<Name> for ToolBridgeCtx<Runtime>
644where
645 Runtime: HasComponent<Name>,
646{
647 type Provider = ComponentProvider<Runtime, Name>;
648}
649
650pub trait HasToolInstance<T>: Send + Sync {
652 fn tool_instance(&self) -> &T;
653}
654
655pub struct TypedToolExecutor<T>(PhantomData<T>);
657
658#[async_trait]
659impl<Ctx, T> ExecuteProvider<Ctx> for TypedToolExecutor<T>
660where
661 Ctx: HasToolRef + Send + Sync,
662 T: Tool + Send + Sync,
663{
664 async fn execute(ctx: &Ctx, args: Value) -> Result<Value> {
665 <PassthroughExecutor as ExecuteProvider<Ctx>>::execute(ctx, args).await
666 }
667
668 async fn execute_dual(ctx: &Ctx, args: Value) -> Result<SplitToolResult> {
669 <PassthroughExecutor as ExecuteProvider<Ctx>>::execute_dual(ctx, args).await
670 }
671}
672
673pub struct TypedToolMetadata<T>(PhantomData<T>);
675
676impl<Ctx, T> MetadataProvider<Ctx> for TypedToolMetadata<T>
677where
678 Ctx: HasToolRef,
679 T: Tool + Send + Sync,
680{
681 fn tool_name(ctx: &Ctx) -> &str {
682 <PassthroughMetadata as MetadataProvider<Ctx>>::tool_name(ctx)
683 }
684
685 fn tool_description(ctx: &Ctx) -> &str {
686 <PassthroughMetadata as MetadataProvider<Ctx>>::tool_description(ctx)
687 }
688
689 fn parameter_schema(ctx: &Ctx) -> Option<Value> {
690 <PassthroughMetadata as MetadataProvider<Ctx>>::parameter_schema(ctx)
691 }
692
693 fn config_schema(ctx: &Ctx) -> Option<Value> {
694 <PassthroughMetadata as MetadataProvider<Ctx>>::config_schema(ctx)
695 }
696
697 fn state_schema(ctx: &Ctx) -> Option<Value> {
698 <PassthroughMetadata as MetadataProvider<Ctx>>::state_schema(ctx)
699 }
700
701 fn prompt_path(ctx: &Ctx) -> Option<Cow<'static, str>> {
702 <PassthroughMetadata as MetadataProvider<Ctx>>::prompt_path(ctx)
703 }
704
705 fn default_permission(ctx: &Ctx) -> ToolPolicy {
706 <PassthroughMetadata as MetadataProvider<Ctx>>::default_permission(ctx)
707 }
708
709 fn allow_patterns(ctx: &Ctx) -> Option<&'static [&'static str]> {
710 <PassthroughMetadata as MetadataProvider<Ctx>>::allow_patterns(ctx)
711 }
712
713 fn deny_patterns(ctx: &Ctx) -> Option<&'static [&'static str]> {
714 <PassthroughMetadata as MetadataProvider<Ctx>>::deny_patterns(ctx)
715 }
716
717 fn is_mutating(ctx: &Ctx) -> bool {
718 <PassthroughMetadata as MetadataProvider<Ctx>>::is_mutating(ctx)
719 }
720
721 fn is_parallel_safe(ctx: &Ctx) -> bool {
722 <PassthroughMetadata as MetadataProvider<Ctx>>::is_parallel_safe(ctx)
723 }
724
725 fn tool_kind(ctx: &Ctx) -> &'static str {
726 <PassthroughMetadata as MetadataProvider<Ctx>>::tool_kind(ctx)
727 }
728
729 fn resource_hints(ctx: &Ctx, args: &Value) -> Vec<String> {
730 <PassthroughMetadata as MetadataProvider<Ctx>>::resource_hints(ctx, args)
731 }
732
733 fn execution_cost(ctx: &Ctx) -> u8 {
734 <PassthroughMetadata as MetadataProvider<Ctx>>::execution_cost(ctx)
735 }
736}
737
738pub struct TypedToolCtx<Runtime, T> {
740 tool: T,
741 runtime: Runtime,
742}
743
744impl<Runtime, T> TypedToolCtx<Runtime, T> {
745 pub fn new(tool: T, runtime: Runtime) -> Self {
746 Self { tool, runtime }
747 }
748}
749
750impl<Runtime: HasWorkspaceRoot + Send + Sync, T: Send + Sync> HasWorkspaceRoot for TypedToolCtx<Runtime, T> {
751 fn workspace_root(&self) -> &PathBuf {
752 self.runtime.workspace_root()
753 }
754}
755
756impl<Runtime: Send + Sync, T: Send + Sync> HasToolInstance<T> for TypedToolCtx<Runtime, T> {
757 fn tool_instance(&self) -> &T {
758 &self.tool
759 }
760}
761
762impl<Runtime: Send + Sync, T> HasToolRef for TypedToolCtx<Runtime, T>
763where
764 T: Tool + Send + Sync,
765{
766 fn tool(&self) -> &dyn Tool {
767 &self.tool
768 }
769}
770
771macro_rules! delegate_runtime_components_for_typed_ctx {
772 ($($component:ty),+ $(,)?) => {
773 $(
774 impl<Runtime, T> HasComponent<$component> for TypedToolCtx<Runtime, T>
775 where
776 Runtime: HasComponent<$component>,
777 {
778 type Provider = ComponentProvider<Runtime, $component>;
779 }
780 )+
781 };
782}
783
784delegate_runtime_components_for_typed_ctx!(
785 ApprovalComponent,
786 SandboxComponent,
787 SessionComponent,
788 OutputMapComponent,
789 LoggingComponent,
790 CacheComponent,
791 RetryComponent,
792);
793
794impl<Runtime, T> HasComponent<ExecuteComponent> for TypedToolCtx<Runtime, T>
795where
796 Runtime: Send + Sync,
797 T: Tool + Send + Sync,
798{
799 type Provider = TypedToolExecutor<T>;
800}
801
802impl<Runtime, T> HasComponent<MetadataComponent> for TypedToolCtx<Runtime, T>
803where
804 Runtime: Send + Sync,
805 T: Tool + Send + Sync,
806{
807 type Provider = TypedToolMetadata<T>;
808}
809
810pub fn wrap_native_tool_interactive<T>(tool: T, workspace_root: PathBuf) -> ToolFacade<TypedToolCtx<InteractiveCtx, T>>
816where
817 T: Tool + Send + Sync + 'static,
818{
819 ToolFacade::new(TypedToolCtx::new(tool, InteractiveCtx::new(workspace_root)))
820}
821
822pub fn wrap_native_tool_ci<T>(tool: T, workspace_root: PathBuf) -> ToolFacade<TypedToolCtx<CiCtx, T>>
828where
829 T: Tool + Send + Sync + 'static,
830{
831 ToolFacade::new(TypedToolCtx::new(tool, CiCtx::new(workspace_root)))
832}
833
834#[cfg(test)]
835mod tests;