use crate::{
final_output::FINAL_OUTPUT_TOOL_NAME,
tool::{
executor::{ToolExecutionContext, ToolExecutionError, ToolExecutor, ToolExecutorFuture},
proposal::ToolActionKind,
},
tool_input_validation::{CompiledToolInputValidator, ToolInputValidationError},
};
use merry_core::{PendingToolCall, ToolName, ToolSpec};
use std::{collections::BTreeMap, sync::Arc};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolRunner {
Runtime,
Bridge,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolConcurrency {
ParallelSafe,
Exclusive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PlanIntrinsicTool {
EnterPlanMode,
WritePlan,
ReadPlan,
ExitPlanMode,
UpdateTodos,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RuntimeIntrinsicTool {
Plan(PlanIntrinsicTool),
RequestPermissions,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolActionProposalMode {
Disabled,
Enabled,
LowRiskWorkspacePatch,
}
#[derive(Clone)]
pub struct RegisteredTool {
pub(super) spec: ToolSpec,
pub(super) external_binding: Option<merry_core::ExternalToolBinding>,
pub(super) executor: Arc<dyn ToolExecutor>,
pub(super) action_kind: ToolActionKind,
pub(super) proposal_mode: ToolActionProposalMode,
pub(super) permissioned_network_lane: bool,
pub(super) intrinsic: Option<RuntimeIntrinsicTool>,
pub(super) runner: ToolRunner,
pub(super) concurrency: ToolConcurrency,
}
impl RegisteredTool {
#[must_use]
pub fn new(
spec: ToolSpec,
executor: Arc<dyn ToolExecutor>,
action_kind: ToolActionKind,
) -> Self {
Self {
spec,
external_binding: None,
executor,
action_kind,
proposal_mode: ToolActionProposalMode::Disabled,
permissioned_network_lane: false,
intrinsic: None,
runner: ToolRunner::Runtime,
concurrency: ToolConcurrency::Exclusive,
}
}
#[must_use]
pub(crate) fn intrinsic(spec: ToolSpec, intrinsic: RuntimeIntrinsicTool) -> Self {
Self {
spec,
external_binding: None,
executor: Arc::new(IntrinsicToolExecutor),
action_kind: ToolActionKind::RuntimeControl,
proposal_mode: ToolActionProposalMode::Disabled,
permissioned_network_lane: false,
intrinsic: Some(intrinsic),
runner: ToolRunner::Runtime,
concurrency: ToolConcurrency::Exclusive,
}
}
#[must_use]
pub fn with_external_binding(mut self, binding: merry_core::ExternalToolBinding) -> Self {
self.external_binding = Some(binding);
self
}
#[must_use]
pub fn external_binding(&self) -> Option<&merry_core::ExternalToolBinding> {
self.external_binding.as_ref()
}
#[must_use]
pub fn with_action_proposal(mut self) -> Self {
if self.proposal_mode == ToolActionProposalMode::Disabled {
self.proposal_mode = ToolActionProposalMode::Enabled;
}
self
}
#[must_use]
pub fn with_low_risk_workspace_patch_lane(mut self) -> Self {
self.proposal_mode = ToolActionProposalMode::LowRiskWorkspacePatch;
self
}
#[must_use]
pub fn with_permissioned_network_lane(mut self) -> Self {
self.permissioned_network_lane = true;
self
}
#[must_use]
pub fn with_parallel_safe_execution(mut self) -> Self {
self.concurrency = ToolConcurrency::ParallelSafe;
self
}
#[must_use]
pub fn read_only(spec: ToolSpec, executor: Arc<dyn ToolExecutor>) -> Self {
Self::new(spec, executor, ToolActionKind::ReadOnly)
}
#[must_use]
pub fn bridge(spec: ToolSpec) -> Self {
Self {
spec,
external_binding: None,
executor: Arc::new(BridgeExecutor),
action_kind: ToolActionKind::ReadOnly,
proposal_mode: ToolActionProposalMode::Disabled,
permissioned_network_lane: false,
intrinsic: None,
runner: ToolRunner::Bridge,
concurrency: ToolConcurrency::Exclusive,
}
}
#[must_use]
pub fn spec(&self) -> &ToolSpec {
&self.spec
}
#[must_use]
pub fn action_kind(&self) -> ToolActionKind {
self.action_kind
}
#[must_use]
pub fn runner(&self) -> ToolRunner {
self.runner
}
#[must_use]
pub fn concurrency(&self) -> ToolConcurrency {
self.concurrency
}
#[must_use]
pub const fn proposals_enabled(&self) -> bool {
!matches!(self.proposal_mode, ToolActionProposalMode::Disabled)
}
#[must_use]
pub const fn low_risk_workspace_patch_lane(&self) -> bool {
matches!(
self.proposal_mode,
ToolActionProposalMode::LowRiskWorkspacePatch
)
}
#[must_use]
pub const fn permissioned_network_lane(&self) -> bool {
self.permissioned_network_lane
}
#[must_use]
pub(crate) const fn proposal_mode(&self) -> ToolActionProposalMode {
self.proposal_mode
}
#[must_use]
pub(crate) const fn runtime_intrinsic(&self) -> Option<RuntimeIntrinsicTool> {
self.intrinsic
}
pub(crate) fn executor(&self) -> Arc<dyn ToolExecutor> {
Arc::clone(&self.executor)
}
}
struct IntrinsicToolExecutor;
impl ToolExecutor for IntrinsicToolExecutor {
fn execute<'a>(
&'a self,
call: PendingToolCall,
_context: ToolExecutionContext,
) -> ToolExecutorFuture<'a> {
Box::pin(async move {
Err(ToolExecutionError::infrastructure(format!(
"intrinsic runtime tool {} reached the generic executor",
call.name().as_str()
)))
})
}
}
pub(super) struct BridgeExecutor;
impl ToolExecutor for BridgeExecutor {
fn execute<'a>(
&'a self,
call: PendingToolCall,
_context: ToolExecutionContext,
) -> ToolExecutorFuture<'a> {
Box::pin(async move {
Err(ToolExecutionError::infrastructure(format!(
"bridge tool {} must be executed by a bridge runner",
call.name().as_str()
)))
})
}
}
impl std::fmt::Debug for RegisteredTool {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("RegisteredTool")
.field("spec", &self.spec)
.field("action_kind", &self.action_kind)
.field("proposal_mode", &self.proposal_mode)
.field("intrinsic", &self.intrinsic)
.field("runner", &self.runner)
.field("concurrency", &self.concurrency)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct ToolRegistry {
pub(super) tools: BTreeMap<ToolName, RegisteredToolEntry>,
pub(super) order: Vec<ToolName>,
}
#[derive(Debug, Clone)]
pub(super) struct RegisteredToolEntry {
pub(super) tool: RegisteredTool,
pub(super) input_validator: CompiledToolInputValidator,
}
impl ToolRegistry {
pub(crate) fn from_registered(tools: Vec<RegisteredTool>) -> Result<Self, ToolRegistryError> {
let mut registry = BTreeMap::new();
let mut order = Vec::with_capacity(tools.len());
for tool in tools {
let name = tool.spec().name().clone();
if name.as_str() == FINAL_OUTPUT_TOOL_NAME {
return Err(ToolRegistryError::ReservedName { name });
}
let input_validator = CompiledToolInputValidator::compile(tool.spec().input_schema())
.map_err(|source| ToolRegistryError::InvalidToolInputSchema {
name: name.clone(),
message: source.to_string(),
})?;
let entry = RegisteredToolEntry {
tool,
input_validator,
};
if registry.insert(name.clone(), entry).is_some() {
return Err(ToolRegistryError::DuplicateName { name });
}
order.push(name);
}
Ok(Self {
tools: registry,
order,
})
}
pub(crate) fn tool_specs(&self) -> Vec<ToolSpec> {
self.order
.iter()
.filter_map(|name| self.tools.get(name))
.map(|entry| entry.tool.spec().clone())
.collect()
}
pub(crate) fn external_tool_catalog(
&self,
) -> Result<merry_core::SessionToolCatalog, merry_core::CoreError> {
merry_core::SessionToolCatalog::new(
self.order
.iter()
.filter_map(|name| {
let tool = &self.tools.get(name)?.tool;
Some(merry_core::SessionToolCatalogEntry::new(
tool.spec().clone(),
tool.external_binding()?.clone(),
))
})
.collect(),
)
}
pub(crate) fn registered_tool(&self, name: &ToolName) -> Option<&RegisteredTool> {
self.tools.get(name).map(|entry| &entry.tool)
}
pub(crate) fn validate_tool_input(
&self,
call: &PendingToolCall,
) -> Option<Result<(), ToolInputValidationError>> {
self.tools
.get(call.name())
.map(|entry| entry.input_validator.validate_call(call))
}
pub(crate) fn first_bridge_tool_name(&self) -> Option<&ToolName> {
self.tools
.iter()
.find_map(|(name, entry)| (entry.tool.runner() == ToolRunner::Bridge).then_some(name))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ToolRegistryError {
DuplicateName { name: ToolName },
ReservedName { name: ToolName },
InvalidToolInputSchema { name: ToolName, message: String },
}