Skip to main content

merry_runtime/tool/
executor.rs

1use crate::tool::{
2    ToolExecutionOutcome, patch_evidence::WorkspacePatchProposal, proposal::ActionProposal,
3};
4use merry_core::PendingToolCall;
5use std::{future::Future, pin::Pin};
6use thiserror::Error;
7use tokio_util::sync::CancellationToken;
8
9/// Boxed tool executor future used for object-safe async tool boundaries.
10///
11/// Public tool boundaries use an explicit boxed future so registered executors
12/// can be stored behind [`ToolExecutor`].
13pub type ToolExecutorFuture<'a> = Pin<Box<dyn Future<Output = ToolExecutionResult> + Send + 'a>>;
14
15/// Boxed action proposal future used for object-safe async tool boundaries.
16///
17/// The proposal hook is runtime-owned and provider-neutral. It is intentionally
18/// not rendered into provider tool specs or runtime events.
19pub type ToolActionProposalFuture<'a> =
20    Pin<Box<dyn Future<Output = ToolActionProposalResult> + Send + 'a>>;
21
22/// Result returned by a runtime-owned tool executor.
23///
24/// [`ToolExecutionError`] represents executor infrastructure failure or
25/// cooperative cancellation. Tool-domain failures should be returned as a
26/// failed [`ToolExecutionOutcome`] so runtime can durably resolve the pending
27/// tool call.
28pub type ToolExecutionResult = Result<ToolExecutionOutcome, ToolExecutionError>;
29
30/// Optional proposal returned before a write-classified tool can be resolved by policy.
31///
32/// `NoProposal` means the executor cannot provide deterministic proposal
33/// evidence for this call and policy should continue with its normal decision
34/// path.
35pub type ToolActionProposalResult = Result<ToolActionPreflight, ToolExecutionError>;
36
37/// Context passed to a tool executor.
38///
39/// The context is intentionally small for the MVP: cancellation is cooperative
40/// and runtime state mutation stays owned by [`crate::Runtime::execute_tool_call`].
41#[derive(Debug, Clone)]
42pub struct ToolExecutionContext {
43    pub(super) cancellation_token: CancellationToken,
44    pub(super) approved_apply_patch: Option<WorkspacePatchProposal>,
45    pub(super) output_sender: Option<tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>>,
46}
47
48impl ToolExecutionContext {
49    /// Creates a tool execution context with the provided cancellation token.
50    #[must_use]
51    pub fn new(cancellation_token: CancellationToken) -> Self {
52        Self {
53            cancellation_token,
54            approved_apply_patch: None,
55            output_sender: None,
56        }
57    }
58
59    /// Returns the cancellation token for this tool execution.
60    ///
61    /// Executors should check this token at cancellation points and return
62    /// [`ToolExecutionError::Cancelled`] when no durable result was produced.
63    #[must_use]
64    pub fn cancellation_token(&self) -> &CancellationToken {
65        &self.cancellation_token
66    }
67
68    /// Borrows the approved workspace patch proposal for this execution.
69    ///
70    /// This is executor-internal runtime state. It is never rendered into
71    /// provider-visible tool specs, tool result artifacts, or continuations.
72    #[must_use]
73    pub fn approved_apply_patch(&self) -> Option<&WorkspacePatchProposal> {
74        self.approved_apply_patch.as_ref()
75    }
76
77    pub(crate) fn with_approved_apply_patch(mut self, patch: WorkspacePatchProposal) -> Self {
78        self.approved_apply_patch = Some(patch);
79        self
80    }
81
82    pub(crate) fn with_output_sender(
83        mut self,
84        sender: tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>,
85    ) -> Self {
86        self.output_sender = Some(sender);
87        self
88    }
89
90    pub(crate) fn output_sender(
91        &self,
92    ) -> Option<&tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>> {
93        self.output_sender.as_ref()
94    }
95}
96
97impl Default for ToolExecutionContext {
98    fn default() -> Self {
99        Self {
100            cancellation_token: CancellationToken::new(),
101            approved_apply_patch: None,
102            output_sender: None,
103        }
104    }
105}
106
107/// Object-safe runtime tool executor boundary.
108///
109/// The executor returns content and status only. Runtime code records the
110/// artifact, emits events, updates the ledger, and resolves the pending call.
111///
112/// Implementations should not call runtime mutation APIs from inside
113/// [`ToolExecutor::execute`]. The runtime already owns the active-step permit
114/// while this method runs.
115pub trait ToolExecutor: Send + Sync {
116    /// Builds read-only deterministic evidence for a proposed action.
117    ///
118    /// This hook must not mutate workspace, runtime, network, or process state.
119    /// It exists so runtime can record a provider-neutral proposal before a
120    /// mutating action is denied, approved, or otherwise reviewed. Existing
121    /// tools can omit this method; the default returns no proposal.
122    fn propose<'a>(
123        &'a self,
124        _call: PendingToolCall,
125        _context: ToolExecutionContext,
126    ) -> ToolActionProposalFuture<'a> {
127        Box::pin(async { Ok(ToolActionPreflight::NoProposal) })
128    }
129
130    /// Executes one pending model-requested tool call.
131    ///
132    /// The pending call uses Merry-owned ids, tool names, and arguments rather
133    /// than provider response structs.
134    fn execute<'a>(
135        &'a self,
136        call: PendingToolCall,
137        context: ToolExecutionContext,
138    ) -> ToolExecutorFuture<'a>;
139}
140
141/// Result of a tool action preflight/proposal hook.
142///
143/// Mutating tools use this hook before runtime policy decides whether execution
144/// is allowed. Most tools return a proposal or no proposal. Tools may return a
145/// durable failed outcome for provider-supplied argument errors discovered
146/// during preflight, so the model receives actionable feedback instead of an
147/// infrastructure failure.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum ToolActionPreflight {
150    /// The tool did not provide deterministic proposal evidence.
151    NoProposal,
152    /// The tool provided proposal evidence for policy review.
153    Proposal(ActionProposal),
154    /// The tool preflight produced a durable tool outcome.
155    Outcome(ToolExecutionOutcome),
156}
157
158/// Infrastructure-level errors raised by tool executors.
159///
160/// Use this for cancellation or infrastructure failures only. If the tool ran
161/// and produced a domain-level failure, return a failed [`ToolExecutionOutcome`]
162/// instead.
163#[derive(Debug, Error)]
164pub enum ToolExecutionError {
165    /// Tool execution was cancelled cooperatively.
166    #[error("tool execution cancelled")]
167    Cancelled,
168
169    /// Tool execution could not complete because the executor infrastructure failed.
170    #[error("tool execution infrastructure error: {message}")]
171    Infrastructure {
172        /// Actionable executor error detail.
173        message: String,
174    },
175}
176
177impl ToolExecutionError {
178    /// Creates an infrastructure error.
179    ///
180    /// Infrastructure errors leave the pending tool call unresolved.
181    #[must_use]
182    pub fn infrastructure(message: impl Into<String>) -> Self {
183        Self::Infrastructure {
184            message: message.into(),
185        }
186    }
187}