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 (from the RustLab 2025 CGP talk)
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//!
22//! ## Dictionary-passing interpretation
23//!
24//! This module intentionally mirrors dictionary-passing style for Rust traits.
25//! `HasComponent<Name>::Provider` is the elaborated "dictionary" selected for a
26//! capability, while the blanket consumer impls (`CanApproveTool`,
27//! `CanExecuteTool`, etc.) are the point where the compiler proves that the
28//! selected provider implements the required provider trait for the current
29//! context. That keeps the capability wiring explicit and avoids depending on
30//! deeper associated-type reasoning at call sites.
31//!
32//! # Example
33//!
34//! ```rust,ignore
35//! use vtcode_core::components::*;
36//!
37//! // Define a context for interactive sessions
38//! struct InteractiveCtx { /* ... */ }
39//!
40//! // Wire components to providers
41//! delegate_components!(InteractiveCtx {
42//!     ApprovalComponent  => PromptApproval,
43//!     SandboxComponent   => WorkspaceSandbox,
44//!     ExecuteComponent   => DefaultExecutor,
45//! });
46//!
47//! // Define a CI context with different providers
48//! struct CiCtx { /* ... */ }
49//!
50//! delegate_components!(CiCtx {
51//!     ApprovalComponent  => AutoApproval,
52//!     SandboxComponent   => StrictSandbox,
53//!     ExecuteComponent   => DefaultExecutor,
54//! });
55//! ```
56
57use 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
78// ============================================================================
79// Core wiring trait (re-exported from vtcode-commons::cgp)
80// ============================================================================
81
82pub use vtcode_commons::cgp::{ComponentProvider, HasComponent};
83pub use vtcode_commons::delegate_components;
84
85// ============================================================================
86// Component name markers
87// ============================================================================
88
89mod execution;
90use execution::value_to_text;
91pub use execution::{
92    CachedResults, CanApproveTool, CanExecuteTool, CanProvideToolMetadata, CanResolveSandbox, ExponentialBackoffRetry,
93    HasExecutionCaches, HasRetryPolicy, PassthroughMetadata, ToolExecutionCacheKey, ToolFacade,
94};
95
96/// Component for approval/permission checks before tool execution.
97pub enum ApprovalComponent {}
98
99/// Component for sandbox policy selection and enforcement.
100pub enum SandboxComponent {}
101
102/// Component for the core tool execution logic.
103pub enum ExecuteComponent {}
104
105/// Component for tool metadata (name, description, schemas).
106pub enum MetadataComponent {}
107
108/// Component for session/turn context creation.
109pub enum SessionComponent {}
110
111/// Component for mapping between output formats (JSON ↔ dual-channel, etc.).
112pub enum OutputMapComponent {}
113
114/// Component for execution logging and telemetry.
115pub enum LoggingComponent {}
116
117/// Component for cached tool results.
118pub enum CacheComponent {}
119
120/// Component for retry policy around tool execution.
121pub enum RetryComponent {}
122
123// ============================================================================
124// Provider traits (explicit Context parameter — the CGP "provider" pattern)
125// ============================================================================
126
127/// Provider trait for approval/permission checks.
128///
129/// Moves the traditional `Self` type to an explicit `Ctx` parameter so that
130/// multiple overlapping implementations can coexist (e.g., prompt-based,
131/// auto-approve, session-cached).
132#[async_trait]
133pub trait ApprovalProvider<Ctx: Send + Sync>: Send + Sync {
134    /// Check whether the operation described by `description` is approved
135    /// in the given context.
136    async fn check_approval(ctx: &Ctx, tool_name: &str, description: &str) -> Result<()>;
137}
138
139/// Provider trait for sandbox policy resolution.
140pub trait SandboxProvider<Ctx: Send + Sync>: Send + Sync {
141    /// Resolve the sandbox policy for the given context.
142    fn sandbox_enabled(ctx: &Ctx) -> bool;
143
144    /// Get the workspace root enforced by the sandbox.
145    fn workspace_root(ctx: &Ctx) -> Option<&PathBuf>;
146}
147
148/// Provider trait for tool metadata.
149pub 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
207/// Provider trait for output format mapping.
208pub 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/// Provider trait for tool execution (the core "handle" operation).
216///
217/// Separates execution logic from metadata, approval, and output mapping
218/// so the same executor can be projected through both `Tool` and `ToolHandler`
219/// facades without bidirectional adapters.
220#[async_trait]
221pub trait ExecuteProvider<Ctx: Send + Sync>: Send + Sync {
222    /// Execute a tool with JSON arguments and return JSON output.
223    async fn execute(ctx: &Ctx, args: Value) -> Result<Value>;
224
225    /// Execute with dual-channel output (LLM summary + UI content).
226    ///
227    /// Default delegates to `execute()` for backward compatibility.
228    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
240/// Provider trait for execution logging and telemetry.
241pub 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
253/// Provider trait for cached tool results.
254pub 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
268/// Provider trait for retry behavior around tool execution.
269pub 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
283// ============================================================================
284// Named provider implementations (CGP "named providers")
285// ============================================================================
286
287/// Always-approve provider for CI/test contexts.
288pub 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
297/// Provider that denies all operations (useful for read-only/audit contexts).
298pub 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
307/// No-sandbox provider for trusted/test contexts.
308pub 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
321/// Default metadata provider for contexts that do not customize tool metadata.
322pub struct DefaultMetadata;
323
324impl<Ctx> MetadataProvider<Ctx> for DefaultMetadata {}
325
326/// No-op logging provider for contexts that don't need telemetry.
327pub struct NoLogging;
328
329impl<Ctx> LoggingProvider<Ctx> for NoLogging {}
330
331/// No-op cache provider for contexts that should always execute directly.
332pub struct NoCache;
333
334impl<Ctx> CacheProvider<Ctx> for NoCache {}
335
336/// No-op retry provider for contexts that should fail fast.
337pub struct NoRetry;
338
339impl<Ctx> RetryProvider<Ctx> for NoRetry {}
340
341/// Logging provider that traces tool execution lifecycle.
342pub 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
384// Re-export the canonical RetryPolicy from the retry module for backward
385// compatibility with existing imports via `components::RetryPolicy`.
386pub use crate::retry::RetryPolicy;
387
388// ============================================================================
389// Composite runtime via CGP delegation
390// ============================================================================
391
392/// A generic tool runtime that composes approval + sandbox + execution
393/// through CGP component wiring.
394///
395/// Instead of hard-coding policy logic, `ComposableRuntime` delegates to
396/// whatever providers the context has wired for each component.
397pub struct ComposableRuntime;
398
399impl ComposableRuntime {
400    /// Execute a tool operation through the full approval → sandbox → execute
401    /// pipeline, with all behavior determined by the context's component
402    /// wiring.
403    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    /// Full pipeline: approval → sandbox check → delegate to caller for
412    /// execution.
413    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
422// ============================================================================
423// Concrete runtime contexts
424// ============================================================================
425
426/// Interactive runtime context — used during normal TUI sessions.
427///
428/// Wires prompt-based approval, workspace-scoped sandbox, and tracing-only
429/// static middleware. Carries workspace root for path validation.
430pub 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
440/// Prompt-based approval provider for interactive sessions.
441///
442/// In the current implementation this auto-approves (the existing
443/// `ToolPolicyGateway` handles actual prompting at a higher layer).
444/// This provider exists so the CGP pipeline is structurally complete
445/// and ready for deeper integration.
446pub 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        // Approval is handled by ToolPolicyGateway at registry level;
452        // this provider completes the CGP pipeline without double-gating.
453        Ok(())
454    }
455}
456
457/// Trait for contexts that expose a workspace root path.
458pub 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
468/// Workspace-scoped sandbox provider.
469///
470/// Reports sandbox as enabled and exposes the workspace root for path
471/// validation. Generic over any context that implements `HasWorkspaceRoot`.
472pub 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
495/// CI/automation runtime context — auto-approves, strict sandbox.
496pub 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
512/// Strict sandbox that enforces workspace boundaries in CI.
513pub 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
525/// Benchmark runtime context — auto-approves, no sandbox, no static middleware.
526pub 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
538/// Passthrough executor — delegates to a stored `Arc<dyn Tool>`.
539///
540/// This bridges existing `Tool` implementations into the CGP pipeline,
541/// so concrete tools (grep, file_ops, exec, etc.) can be composed with
542/// CGP approval/sandbox/logging/cache/retry without rewriting them.
543pub struct PassthroughExecutor;
544
545/// Trait for contexts that can expose a tool reference for delegated metadata,
546/// validation, and execution.
547pub trait HasToolRef: Send + Sync {
548    fn tool(&self) -> &dyn Tool;
549}
550
551/// Trait for contexts that can borrow an inner `Tool` for passthrough.
552///
553/// Keep shared ownership inside the bridge context; callers only need a borrowed
554/// `dyn Tool` to delegate metadata, validation, and execution.
555pub 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
583// ============================================================================
584// Registry integration bridge
585// ============================================================================
586
587/// Create a `ToolFacade` that wraps an existing `Arc<dyn Tool>` with
588/// CGP-wired approval, sandbox, and middleware for interactive sessions.
589///
590/// Prefer `wrap_native_tool_interactive()` when you still own the concrete
591/// tool instance. Use this bridge when the tool is already shared elsewhere.
592///
593/// The returned facade implements `Tool` and can be registered directly
594/// with `ToolRegistration::from_tool()`.
595pub 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
606/// Create a `ToolFacade` that wraps an existing `Arc<dyn Tool>` with
607/// CGP-wired auto-approval and no middleware for CI contexts.
608///
609/// Prefer `wrap_native_tool_ci()` when you still own the concrete tool
610/// instance. Use this bridge when the tool is already shared elsewhere.
611pub 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
616/// Bridge context: combines a runtime context with shared tool ownership.
617///
618/// This keeps the `Arc<dyn Tool>` inside the bridge while
619/// `PassthroughExecutor` only borrows `&dyn Tool`. The rest of the CGP
620/// pipeline (approval, sandbox, middleware) is provided by the runtime
621/// context's component wiring.
622pub struct ToolBridgeCtx<Runtime> {
623    inner: Arc<dyn Tool>,
624    /// The runtime context whose component wiring is inherited via
625    /// the blanket `HasComponent` impl below. Accessed at the type
626    /// level, not at runtime — the compiler doesn't see field reads.
627    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
642// Component wiring for bridge contexts delegates to the runtime's wiring.
643impl<Name, Runtime> HasComponent<Name> for ToolBridgeCtx<Runtime>
644where
645    Runtime: HasComponent<Name>,
646{
647    type Provider = ComponentProvider<Runtime, Name>;
648}
649
650/// Trait for contexts that carry a concrete tool instance.
651pub trait HasToolInstance<T>: Send + Sync {
652    fn tool_instance(&self) -> &T;
653}
654
655/// Execute provider that dispatches directly to a typed tool instance.
656pub 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
673/// Metadata provider that dispatches directly to a typed tool instance.
674pub 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
738/// Typed CGP context that carries a concrete tool instance plus runtime policy.
739pub 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
810/// Wrap a concrete tool instance in an interactive CGP facade without
811/// erasing it to `Arc<dyn Tool>` first.
812///
813/// Prefer this path when the caller still owns the tool and does not need
814/// shared ownership.
815pub 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
822/// Wrap a concrete tool instance in a CI CGP facade without
823/// erasing it to `Arc<dyn Tool>` first.
824///
825/// Prefer this path when the caller still owns the tool and does not need
826/// shared ownership.
827pub 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;