Skip to main content

merry_runtime/tool/
executor.rs

1use crate::{
2    PathAccessRule, PermissionedAction, RequestedCapability,
3    tool::{
4        ToolExecutionOutcome, patch_evidence::WorkspacePatchProposal, proposal::ActionProposal,
5    },
6};
7use merry_core::PendingToolCall;
8use std::{future::Future, pin::Pin};
9use thiserror::Error;
10use tokio_util::sync::CancellationToken;
11
12/// Boxed tool executor future used for object-safe async tool boundaries.
13///
14/// Public tool boundaries use an explicit boxed future so registered executors
15/// can be stored behind [`ToolExecutor`].
16pub type ToolExecutorFuture<'a> = Pin<Box<dyn Future<Output = ToolExecutionResult> + Send + 'a>>;
17
18/// Boxed action proposal future used for object-safe async tool boundaries.
19///
20/// The proposal hook is runtime-owned and provider-neutral. It is intentionally
21/// not rendered into provider tool specs or runtime events.
22pub type ToolActionProposalFuture<'a> =
23    Pin<Box<dyn Future<Output = ToolActionProposalResult> + Send + 'a>>;
24
25/// Result returned by a runtime-owned tool executor.
26///
27/// [`ToolExecutionError`] represents executor infrastructure failure or
28/// cooperative cancellation. Tool-domain failures should be returned as a
29/// failed [`ToolExecutionOutcome`] so runtime can durably resolve the pending
30/// tool call.
31pub type ToolExecutionResult = Result<ToolExecutionOutcome, ToolExecutionError>;
32
33/// Optional proposal returned before a write-classified tool can be resolved by policy.
34///
35/// `NoProposal` means the executor cannot provide deterministic proposal
36/// evidence for this call and policy should continue with its normal decision
37/// path.
38pub type ToolActionProposalResult = Result<ToolActionPreflight, ToolExecutionError>;
39
40/// Context passed to a tool executor.
41///
42/// The context is intentionally small for the MVP: cancellation is cooperative
43/// and runtime state mutation stays owned by [`crate::Runtime::execute_tool_call`].
44#[derive(Debug, Clone)]
45pub struct ToolExecutionContext {
46    pub(super) cancellation_token: CancellationToken,
47    pub(super) approved_apply_patch: Option<WorkspacePatchProposal>,
48    pub(super) approved_path_grants: Vec<PathAccessRule>,
49    pub(super) approved_network_domains: Vec<String>,
50    pub(super) output_sender: Option<tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>>,
51    pub(super) plan_mode_read_only: bool,
52}
53
54impl ToolExecutionContext {
55    /// Creates a tool execution context with the provided cancellation token.
56    #[must_use]
57    pub fn new(cancellation_token: CancellationToken) -> Self {
58        Self {
59            cancellation_token,
60            approved_apply_patch: None,
61            approved_path_grants: Vec::new(),
62            approved_network_domains: Vec::new(),
63            output_sender: None,
64            plan_mode_read_only: false,
65        }
66    }
67
68    /// Returns the cancellation token for this tool execution.
69    ///
70    /// Executors should check this token at cancellation points and return
71    /// [`ToolExecutionError::Cancelled`] when no durable result was produced.
72    #[must_use]
73    pub fn cancellation_token(&self) -> &CancellationToken {
74        &self.cancellation_token
75    }
76
77    /// Borrows the approved workspace patch proposal for this execution.
78    ///
79    /// This is executor-internal runtime state. It is never rendered into
80    /// provider-visible tool specs, tool result artifacts, or continuations.
81    #[must_use]
82    pub fn approved_apply_patch(&self) -> Option<&WorkspacePatchProposal> {
83        self.approved_apply_patch.as_ref()
84    }
85
86    /// Returns single-action path grants approved for this exact tool execution.
87    #[must_use]
88    pub fn approved_path_grants(&self) -> &[PathAccessRule] {
89        &self.approved_path_grants
90    }
91
92    /// Returns single-action exact network domain grants approved for this
93    /// exact tool execution.
94    #[must_use]
95    pub fn approved_network_domains(&self) -> &[String] {
96        &self.approved_network_domains
97    }
98
99    pub(crate) fn with_approved_apply_patch(mut self, patch: WorkspacePatchProposal) -> Self {
100        self.approved_apply_patch = Some(patch);
101        self
102    }
103
104    pub(crate) fn with_approved_path_grants(
105        mut self,
106        grants: impl IntoIterator<Item = PathAccessRule>,
107    ) -> Self {
108        self.approved_path_grants.extend(grants);
109        self
110    }
111
112    pub(crate) fn with_approved_network_domains(
113        mut self,
114        domains: impl IntoIterator<Item = String>,
115    ) -> Self {
116        self.approved_network_domains.extend(domains);
117        self
118    }
119
120    pub(crate) fn with_output_sender(
121        mut self,
122        sender: tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>,
123    ) -> Self {
124        self.output_sender = Some(sender);
125        self
126    }
127
128    pub(crate) fn output_sender(
129        &self,
130    ) -> Option<&tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>> {
131        self.output_sender.as_ref()
132    }
133
134    pub(crate) const fn with_plan_mode_read_only(mut self, active: bool) -> Self {
135        self.plan_mode_read_only = active;
136        self
137    }
138
139    pub(crate) const fn is_plan_mode_read_only(&self) -> bool {
140        self.plan_mode_read_only
141    }
142}
143
144impl Default for ToolExecutionContext {
145    fn default() -> Self {
146        Self {
147            cancellation_token: CancellationToken::new(),
148            approved_apply_patch: None,
149            approved_path_grants: Vec::new(),
150            approved_network_domains: Vec::new(),
151            output_sender: None,
152            plan_mode_read_only: false,
153        }
154    }
155}
156
157/// Object-safe runtime tool executor boundary.
158///
159/// The executor returns content and status only. Runtime code records the
160/// artifact, emits events, updates the ledger, and resolves the pending call.
161///
162/// Implementations should not call runtime mutation APIs from inside
163/// [`ToolExecutor::execute`]. The runtime already owns the active-step permit
164/// while this method runs.
165pub trait ToolExecutor: Send + Sync {
166    /// Builds read-only deterministic evidence for a proposed action.
167    ///
168    /// This hook must not mutate workspace, runtime, network, or process state.
169    /// It exists so runtime can record a provider-neutral proposal before a
170    /// mutating action is denied, approved, or otherwise reviewed. Existing
171    /// tools can omit this method; the default returns no proposal.
172    fn propose<'a>(
173        &'a self,
174        _call: PendingToolCall,
175        _context: ToolExecutionContext,
176    ) -> ToolActionProposalFuture<'a> {
177        Box::pin(async { Ok(ToolActionPreflight::NoProposal) })
178    }
179
180    /// Executes one pending model-requested tool call.
181    ///
182    /// The pending call uses Merry-owned ids, tool names, and arguments rather
183    /// than provider response structs.
184    fn execute<'a>(
185        &'a self,
186        call: PendingToolCall,
187        context: ToolExecutionContext,
188    ) -> ToolExecutorFuture<'a>;
189}
190
191/// Result of a tool action preflight/proposal hook.
192///
193/// Mutating tools use this hook before runtime policy decides whether execution
194/// is allowed. Most tools return a proposal or no proposal. Tools may return a
195/// durable failed outcome for provider-supplied argument errors discovered
196/// during preflight, so the model receives actionable feedback instead of an
197/// infrastructure failure.
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub enum ToolActionPreflight {
200    /// The tool did not provide deterministic proposal evidence.
201    NoProposal,
202    /// The tool provided proposal evidence for policy review.
203    Proposal(ActionProposal),
204    /// The tool preflight produced a durable tool outcome.
205    Outcome(ToolExecutionOutcome),
206}
207
208/// Structured permission requirement raised by an in-process tool when a call
209/// targets a resource outside the current [`crate::WorkspaceAccessPolicy`].
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct ToolPermissionRequirement {
212    action: PermissionedAction,
213    requested: Vec<RequestedCapability>,
214    reason: Option<String>,
215    protected_target: bool,
216}
217
218impl ToolPermissionRequirement {
219    /// Creates a new tool permission requirement.
220    #[must_use]
221    pub fn new(
222        action: PermissionedAction,
223        requested: Vec<RequestedCapability>,
224        reason: Option<String>,
225    ) -> Self {
226        Self {
227            action,
228            requested,
229            reason,
230            protected_target: false,
231        }
232    }
233
234    /// Marks this requirement as touching a built-in Merry protected path
235    /// (`providers/`, `MERRY_API_KEY_FILE`, or `config.toml` / `state/` under
236    /// workspace sandbox) so approval remains single-action (`Once`) and
237    /// defaults to `Deny` in interactive review UIs.
238    #[must_use]
239    pub const fn with_protected_target(mut self) -> Self {
240        self.protected_target = true;
241        self
242    }
243
244    /// Returns the exact planned action requiring review.
245    #[must_use]
246    pub fn action(&self) -> &PermissionedAction {
247        &self.action
248    }
249
250    /// Returns the requested capabilities needed for this action.
251    #[must_use]
252    pub fn requested(&self) -> &[RequestedCapability] {
253        &self.requested
254    }
255
256    /// Returns an optional reason describing why the capability is needed.
257    #[must_use]
258    pub fn reason(&self) -> Option<&str> {
259        self.reason.as_deref()
260    }
261
262    /// Consumes this requirement into its owned components.
263    pub(crate) fn into_parts(
264        self,
265    ) -> (
266        PermissionedAction,
267        Vec<RequestedCapability>,
268        Option<String>,
269        bool,
270    ) {
271        (
272            self.action,
273            self.requested,
274            self.reason,
275            self.protected_target,
276        )
277    }
278}
279
280/// Infrastructure-level errors raised by tool executors.
281///
282/// Use this for cancellation, runtime-mediated permission escalations, or
283/// infrastructure failures only. If the tool ran and produced a domain-level
284/// failure, return a failed [`ToolExecutionOutcome`] instead.
285#[derive(Debug, Error)]
286pub enum ToolExecutionError {
287    /// Tool execution was cancelled cooperatively.
288    #[error("tool execution cancelled")]
289    Cancelled,
290
291    /// Tool requires runtime permission review before accessing an external capability.
292    #[error("tool execution requires permission review")]
293    PermissionRequired(Box<ToolPermissionRequirement>),
294
295    /// Tool execution could not complete because the executor infrastructure failed.
296    #[error("tool execution infrastructure error: {message}")]
297    Infrastructure {
298        /// Actionable executor error detail.
299        message: String,
300    },
301}
302
303impl ToolExecutionError {
304    /// Creates an infrastructure error.
305    ///
306    /// Infrastructure errors leave the pending tool call unresolved.
307    #[must_use]
308    pub fn infrastructure(message: impl Into<String>) -> Self {
309        Self::Infrastructure {
310            message: message.into(),
311        }
312    }
313
314    /// Requests runtime permission review before retrying the tool execution.
315    #[must_use]
316    pub fn permission_required(requirement: ToolPermissionRequirement) -> Self {
317        Self::PermissionRequired(Box::new(requirement))
318    }
319}