Skip to main content

vtcode_core/components/
mod.rs

1//! Context-Generic Programming (CGP) substrate for VT Code
2//!
3//! Applies the provider-trait pattern from CGP to decouple tool runtime
4//! composition from coherence restrictions. Instead of relying on blanket
5//! impls or adapter newtypes, each capability (approval, sandboxing,
6//! execution, metadata, etc.) is expressed as a **provider trait** with an
7//! explicit `Context` parameter. A lightweight wiring step maps named
8//! **components** to concrete **providers** per context type.
9//!
10//! # Key ideas
11//!
12//! 1. **Provider traits** move `Self` to an explicit generic parameter,
13//!    bypassing Rust's coherence/orphan restrictions.
14//! 2. **Component names** are zero-sized marker types that act as keys in a
15//!    type-level lookup table.
16//! 3. **`delegate_components!`** wires component names to provider types for
17//!    a given context, producing `HasComponent` implementations.
18//! 4. Consumer code depends only on the component name, not the concrete
19//!    provider, enabling the same tool/request to run under different
20//!    policies by simply switching the context.
21//! 5. **`check_components!` / `delegate_and_check_components!`** (CGP v0.8.0
22//!    style) prove at the wiring entry that a selected provider implements the
23//!    capability trait, so a bad choice fails there instead of deep inside a
24//!    consumer bound. Grouped macros emit one entry per family of contexts
25//!    rather than repeating a wiring table for each one.
26//!
27//! ## Dictionary-passing interpretation
28//!
29//! This module intentionally mirrors dictionary-passing style for Rust traits.
30//! `HasComponent<Name>::Provider` is the elaborated "dictionary" selected for a
31//! capability, while the blanket consumer impls (`CanApproveTool`,
32//! `CanExecuteTool`, etc.) are the point where the compiler proves that the
33//! selected provider implements the required provider trait for the current
34//! context. That keeps the capability wiring explicit and avoids depending on
35//! deeper associated-type reasoning at call sites.
36//!
37//! # Example
38//!
39//! ```rust,ignore
40//! use vtcode_core::components::*;
41//!
42//! // Define a context for interactive sessions
43//! struct InteractiveCtx { /* ... */ }
44//!
45//! // Wire components to providers
46//! delegate_components!(InteractiveCtx {
47//!     ApprovalComponent  => PromptApproval,
48//!     SandboxComponent   => WorkspaceSandbox,
49//!     ExecuteComponent   => DefaultExecutor,
50//! });
51//!
52//! // Define a CI context with different providers
53//! struct CiCtx { /* ... */ }
54//!
55//! delegate_components!(CiCtx {
56//!     ApprovalComponent  => AutoApproval,
57//!     SandboxComponent   => StrictSandbox,
58//!     ExecuteComponent   => DefaultExecutor,
59//! });
60//! ```
61
62use 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
83// ============================================================================
84// Core wiring trait (re-exported from vtcode-commons::cgp)
85// ============================================================================
86
87pub use vtcode_commons::cgp::{ComponentProvider, HasComponent};
88pub use vtcode_commons::{check_components, delegate_and_check_components, delegate_components};
89
90// ============================================================================
91// Component name markers
92// ============================================================================
93
94mod execution;
95use execution::value_to_text;
96pub use execution::{
97    CachedResults, CanApproveTool, CanExecuteTool, CanProvideToolMetadata, CanResolveSandbox, ExponentialBackoffRetry,
98    HasExecutionCaches, HasRetryPolicy, PassthroughMetadata, ToolExecutionCacheKey, ToolFacade,
99};
100
101/// Component for approval/permission checks before tool execution.
102pub enum ApprovalComponent {}
103
104/// Component for sandbox policy selection and enforcement.
105pub enum SandboxComponent {}
106
107/// Component for the core tool execution logic.
108pub enum ExecuteComponent {}
109
110/// Component for tool metadata (name, description, schemas).
111pub enum MetadataComponent {}
112
113/// Component for session/turn context creation.
114pub enum SessionComponent {}
115
116/// Component for mapping between output formats (JSON ↔ dual-channel, etc.).
117pub enum OutputMapComponent {}
118
119/// Component for execution logging and telemetry.
120pub enum LoggingComponent {}
121
122/// Component for cached tool results.
123pub enum CacheComponent {}
124
125/// Component for retry policy around tool execution.
126pub enum RetryComponent {}
127
128// ============================================================================
129// Provider traits (explicit Context parameter — the CGP "provider" pattern)
130// ============================================================================
131
132/// Provider trait for approval/permission checks.
133///
134/// Moves the traditional `Self` type to an explicit `Ctx` parameter so that
135/// multiple overlapping implementations can coexist (e.g., prompt-based,
136/// auto-approve, session-cached).
137#[async_trait]
138pub trait ApprovalProvider<Ctx: Send + Sync>: Send + Sync {
139    /// Check whether the operation described by `description` is approved
140    /// in the given context.
141    async fn check_approval(ctx: &Ctx, tool_name: &str, description: &str) -> Result<()>;
142}
143
144/// Provider trait for sandbox policy resolution.
145pub trait SandboxProvider<Ctx: Send + Sync>: Send + Sync {
146    /// Resolve the sandbox policy for the given context.
147    fn sandbox_enabled(ctx: &Ctx) -> bool;
148
149    /// Get the workspace root enforced by the sandbox.
150    fn workspace_root(ctx: &Ctx) -> Option<&PathBuf>;
151}
152
153/// Provider trait for tool metadata.
154pub 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
212/// Provider trait for output format mapping.
213pub 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/// Provider trait for tool execution (the core "handle" operation).
221///
222/// Separates execution logic from metadata, approval, and output mapping
223/// so the same executor can be projected through both `Tool` and `ToolHandler`
224/// facades without bidirectional adapters.
225#[async_trait]
226pub trait ExecuteProvider<Ctx: Send + Sync>: Send + Sync {
227    /// Execute a tool with JSON arguments and return JSON output.
228    async fn execute(ctx: &Ctx, args: Value) -> Result<Value>;
229
230    /// Execute with dual-channel output (LLM summary + UI content).
231    ///
232    /// Default delegates to `execute()` for backward compatibility.
233    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
245/// Provider trait for execution logging and telemetry.
246pub 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
258/// Provider trait for cached tool results.
259pub 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
273/// Provider trait for retry behavior around tool execution.
274pub 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
288// ============================================================================
289// Named provider implementations (CGP "named providers")
290// ============================================================================
291
292/// Always-approve provider for CI/test contexts.
293pub 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
302/// Provider that denies all operations (useful for read-only/audit contexts).
303pub 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
312/// No-sandbox provider for trusted/test contexts.
313pub 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
326/// Default metadata provider for contexts that do not customize tool metadata.
327pub struct DefaultMetadata;
328
329impl<Ctx> MetadataProvider<Ctx> for DefaultMetadata {}
330
331/// No-op logging provider for contexts that don't need telemetry.
332pub struct NoLogging;
333
334impl<Ctx> LoggingProvider<Ctx> for NoLogging {}
335
336/// No-op cache provider for contexts that should always execute directly.
337pub struct NoCache;
338
339impl<Ctx> CacheProvider<Ctx> for NoCache {}
340
341/// No-op retry provider for contexts that should fail fast.
342pub struct NoRetry;
343
344impl<Ctx> RetryProvider<Ctx> for NoRetry {}
345
346/// Logging provider that traces tool execution lifecycle.
347pub 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
389// Re-export the canonical RetryPolicy from the retry module for backward
390// compatibility with existing imports via `components::RetryPolicy`.
391pub use crate::retry::RetryPolicy;
392
393// ============================================================================
394// Composite runtime via CGP delegation
395// ============================================================================
396
397/// A generic tool runtime that composes approval + sandbox + execution
398/// through CGP component wiring.
399///
400/// Instead of hard-coding policy logic, `ComposableRuntime` delegates to
401/// whatever providers the context has wired for each component.
402pub struct ComposableRuntime;
403
404impl ComposableRuntime {
405    /// Execute a tool operation through the full approval → sandbox → execute
406    /// pipeline, with all behavior determined by the context's component
407    /// wiring.
408    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    /// Full pipeline: approval → sandbox check → delegate to caller for
417    /// execution.
418    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
427// ============================================================================
428// Concrete runtime contexts
429// ============================================================================
430
431/// Interactive runtime context — used during normal TUI sessions.
432///
433/// Wires prompt-based approval, workspace-scoped sandbox, and tracing-only
434/// static middleware. Carries workspace root for path validation.
435pub 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
445/// Prompt-based approval provider for interactive sessions.
446///
447/// In the current implementation this auto-approves (the existing
448/// `ToolPolicyGateway` handles actual prompting at a higher layer).
449/// This provider exists so the CGP pipeline is structurally complete
450/// and ready for deeper integration.
451pub 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        // Approval is handled by ToolPolicyGateway at registry level;
457        // this provider completes the CGP pipeline without double-gating.
458        Ok(())
459    }
460}
461
462/// Trait for contexts that expose a workspace root path.
463pub 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
473/// Workspace-scoped sandbox provider.
474///
475/// Reports sandbox as enabled and exposes the workspace root for path
476/// validation. Generic over any context that implements `HasWorkspaceRoot`.
477pub 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
500/// CI/automation runtime context — auto-approves, strict sandbox.
501pub 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
517/// Strict sandbox that enforces workspace boundaries in CI.
518pub 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
530/// Benchmark runtime context — auto-approves, no sandbox, no static middleware.
531pub 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
543/// Passthrough executor — delegates to a stored `Arc<dyn Tool>`.
544///
545/// This bridges existing `Tool` implementations into the CGP pipeline,
546/// so concrete tools (grep, file_ops, exec, etc.) can be composed with
547/// CGP approval/sandbox/logging/cache/retry without rewriting them.
548pub struct PassthroughExecutor;
549
550/// Trait for contexts that can expose a tool reference for delegated metadata,
551/// validation, and execution.
552pub trait HasToolRef: Send + Sync {
553    fn tool(&self) -> &dyn Tool;
554}
555
556/// Trait for contexts that can borrow an inner `Tool` for passthrough.
557///
558/// Keep shared ownership inside the bridge context; callers only need a borrowed
559/// `dyn Tool` to delegate metadata, validation, and execution.
560pub 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
588// ============================================================================
589// Registry integration bridge
590// ============================================================================
591
592/// Create a `ToolFacade` that wraps an existing `Arc<dyn Tool>` with
593/// CGP-wired approval, sandbox, and middleware for interactive sessions.
594///
595/// Prefer `wrap_native_tool_interactive()` when you still own the concrete
596/// tool instance. Use this bridge when the tool is already shared elsewhere.
597///
598/// The returned facade implements `Tool` and can be registered directly
599/// with `ToolRegistration::from_tool()`.
600pub 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
611/// Create a `ToolFacade` that wraps an existing `Arc<dyn Tool>` with
612/// CGP-wired auto-approval and no middleware for CI contexts.
613///
614/// Prefer `wrap_native_tool_ci()` when you still own the concrete tool
615/// instance. Use this bridge when the tool is already shared elsewhere.
616pub 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
621/// Bridge context: combines a runtime context with shared tool ownership.
622///
623/// This keeps the `Arc<dyn Tool>` inside the bridge while
624/// `PassthroughExecutor` only borrows `&dyn Tool`. The rest of the CGP
625/// pipeline (approval, sandbox, middleware) is provided by the runtime
626/// context's component wiring.
627pub struct ToolBridgeCtx<Runtime> {
628    inner: Arc<dyn Tool>,
629    /// The runtime context whose component wiring is inherited via
630    /// the blanket `HasComponent` impl below. Accessed at the type
631    /// level, not at runtime — the compiler doesn't see field reads.
632    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
647// Component wiring for bridge contexts delegates to the runtime's wiring.
648impl<Name, Runtime> HasComponent<Name> for ToolBridgeCtx<Runtime>
649where
650    Runtime: HasComponent<Name>,
651{
652    type Provider = ComponentProvider<Runtime, Name>;
653}
654
655/// Trait for contexts that carry a concrete tool instance.
656pub trait HasToolInstance<T>: Send + Sync {
657    fn tool_instance(&self) -> &T;
658}
659
660/// Execute provider that dispatches directly to a typed tool instance.
661pub 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
678/// Metadata provider that dispatches directly to a typed tool instance.
679pub 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
743/// Typed CGP context that carries a concrete tool instance plus runtime policy.
744pub 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
815/// Wrap a concrete tool instance in an interactive CGP facade without
816/// erasing it to `Arc<dyn Tool>` first.
817///
818/// Prefer this path when the caller still owns the tool and does not need
819/// shared ownership.
820pub 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
827/// Wrap a concrete tool instance in a CI CGP facade without
828/// erasing it to `Arc<dyn Tool>` first.
829///
830/// Prefer this path when the caller still owns the tool and does not need
831/// shared ownership.
832pub 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;