use crate::tool::{
ToolExecutionOutcome, patch_evidence::WorkspacePatchProposal, proposal::ActionProposal,
};
use merry_core::PendingToolCall;
use std::{future::Future, pin::Pin};
use thiserror::Error;
use tokio_util::sync::CancellationToken;
pub type ToolExecutorFuture<'a> = Pin<Box<dyn Future<Output = ToolExecutionResult> + Send + 'a>>;
pub type ToolActionProposalFuture<'a> =
Pin<Box<dyn Future<Output = ToolActionProposalResult> + Send + 'a>>;
pub type ToolExecutionResult = Result<ToolExecutionOutcome, ToolExecutionError>;
pub type ToolActionProposalResult = Result<ToolActionPreflight, ToolExecutionError>;
#[derive(Debug, Clone)]
pub struct ToolExecutionContext {
pub(super) cancellation_token: CancellationToken,
pub(super) approved_apply_patch: Option<WorkspacePatchProposal>,
pub(super) output_sender: Option<tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>>,
}
impl ToolExecutionContext {
#[must_use]
pub fn new(cancellation_token: CancellationToken) -> Self {
Self {
cancellation_token,
approved_apply_patch: None,
output_sender: None,
}
}
#[must_use]
pub fn cancellation_token(&self) -> &CancellationToken {
&self.cancellation_token
}
#[must_use]
pub fn approved_apply_patch(&self) -> Option<&WorkspacePatchProposal> {
self.approved_apply_patch.as_ref()
}
pub(crate) fn with_approved_apply_patch(mut self, patch: WorkspacePatchProposal) -> Self {
self.approved_apply_patch = Some(patch);
self
}
pub(crate) fn with_output_sender(
mut self,
sender: tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>,
) -> Self {
self.output_sender = Some(sender);
self
}
pub(crate) fn output_sender(
&self,
) -> Option<&tokio::sync::mpsc::Sender<crate::ProcessOutputChunk>> {
self.output_sender.as_ref()
}
}
impl Default for ToolExecutionContext {
fn default() -> Self {
Self {
cancellation_token: CancellationToken::new(),
approved_apply_patch: None,
output_sender: None,
}
}
}
pub trait ToolExecutor: Send + Sync {
fn propose<'a>(
&'a self,
_call: PendingToolCall,
_context: ToolExecutionContext,
) -> ToolActionProposalFuture<'a> {
Box::pin(async { Ok(ToolActionPreflight::NoProposal) })
}
fn execute<'a>(
&'a self,
call: PendingToolCall,
context: ToolExecutionContext,
) -> ToolExecutorFuture<'a>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolActionPreflight {
NoProposal,
Proposal(ActionProposal),
Outcome(ToolExecutionOutcome),
}
#[derive(Debug, Error)]
pub enum ToolExecutionError {
#[error("tool execution cancelled")]
Cancelled,
#[error("tool execution infrastructure error: {message}")]
Infrastructure {
message: String,
},
}
impl ToolExecutionError {
#[must_use]
pub fn infrastructure(message: impl Into<String>) -> Self {
Self::Infrastructure {
message: message.into(),
}
}
}