Skip to main content

tirea_contract/runtime/tool_call/
executor.rs

1use crate::runtime::activity::ActivityManager;
2use crate::runtime::behavior::AgentBehavior;
3use crate::runtime::run::RunIdentity;
4use crate::runtime::tool_call::lifecycle::SuspendedCall;
5use crate::runtime::tool_call::{CallerContext, Tool, ToolDescriptor, ToolResult};
6use crate::thread::{Message, ToolCall};
7use crate::RunPolicy;
8use async_trait::async_trait;
9use serde_json::Value;
10use std::collections::HashMap;
11use std::sync::Arc;
12use thiserror::Error;
13use tirea_state::TrackedPatch;
14use tokio_util::sync::CancellationToken;
15
16/// Result of one tool call execution.
17#[derive(Debug, Clone)]
18pub struct ToolExecution {
19    pub call: ToolCall,
20    pub result: ToolResult,
21    pub patch: Option<TrackedPatch>,
22}
23
24/// Canonical outcome for one tool call lifecycle.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
26#[serde(rename_all = "snake_case")]
27pub enum ToolCallOutcome {
28    /// Tool execution was suspended and needs external resume/decision.
29    Suspended,
30    /// Tool execution succeeded.
31    Succeeded,
32    /// Tool execution failed.
33    Failed,
34}
35
36impl ToolCallOutcome {
37    /// Derive outcome from a concrete `ToolResult`.
38    pub fn from_tool_result(result: &ToolResult) -> Self {
39        match result.status {
40            crate::runtime::tool_call::ToolStatus::Pending => Self::Suspended,
41            crate::runtime::tool_call::ToolStatus::Error => Self::Failed,
42            crate::runtime::tool_call::ToolStatus::Success
43            | crate::runtime::tool_call::ToolStatus::Warning => Self::Succeeded,
44        }
45    }
46}
47
48/// Input envelope passed to tool execution strategies.
49pub struct ToolExecutionRequest<'a> {
50    pub tools: &'a HashMap<String, Arc<dyn Tool>>,
51    pub calls: &'a [ToolCall],
52    pub state: &'a Value,
53    pub tool_descriptors: &'a [ToolDescriptor],
54    /// Agent behavior for declarative phase dispatch.
55    pub agent_behavior: Option<&'a dyn AgentBehavior>,
56    pub activity_manager: Arc<dyn ActivityManager>,
57    pub run_policy: &'a RunPolicy,
58    pub run_identity: RunIdentity,
59    pub caller_context: CallerContext,
60    pub thread_id: &'a str,
61    pub thread_messages: &'a [Arc<Message>],
62    pub state_version: u64,
63    pub cancellation_token: Option<&'a CancellationToken>,
64}
65
66/// Output item produced by tool execution strategies.
67#[derive(Debug, Clone)]
68pub struct ToolExecutionResult {
69    pub execution: ToolExecution,
70    pub outcome: ToolCallOutcome,
71    /// Suspension payload for suspended outcomes.
72    pub suspended_call: Option<SuspendedCall>,
73    pub reminders: Vec<String>,
74    /// User messages to append after tool execution.
75    pub user_messages: Vec<String>,
76    pub pending_patches: Vec<TrackedPatch>,
77    /// Serialized state actions captured during this tool execution (intent log).
78    pub serialized_state_actions: Vec<crate::runtime::state::SerializedStateAction>,
79}
80
81/// Error returned by custom tool executors.
82#[derive(Debug, Clone, Error)]
83pub enum ToolExecutorError {
84    #[error("tool execution cancelled")]
85    Cancelled { thread_id: String },
86    #[error("tool execution failed: {message}")]
87    Failed { message: String },
88}
89
90/// Policy controlling when resume decisions are replayed into tool execution.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum DecisionReplayPolicy {
93    /// Replay each resolved suspended call as soon as its decision arrives.
94    Immediate,
95    /// Replay only when all currently suspended calls have decisions.
96    BatchAllSuspended,
97}
98
99/// Strategy abstraction for tool execution.
100#[async_trait]
101pub trait ToolExecutor: Send + Sync {
102    async fn execute(
103        &self,
104        request: ToolExecutionRequest<'_>,
105    ) -> Result<Vec<ToolExecutionResult>, ToolExecutorError>;
106
107    /// Stable strategy label for logs/debug output.
108    fn name(&self) -> &'static str;
109
110    /// Whether apply step should enforce parallel patch conflict checks.
111    fn requires_parallel_patch_conflict_check(&self) -> bool {
112        false
113    }
114
115    /// How runtime should replay resolved suspend decisions for this executor.
116    fn decision_replay_policy(&self) -> DecisionReplayPolicy {
117        DecisionReplayPolicy::Immediate
118    }
119}