Skip to main content

infinity_agent_core/tools/
mod.rs

1pub mod cancel_subscription;
2pub mod config;
3pub mod rap_tool;
4pub mod sleep;
5pub mod thread;
6
7use crate::message::{InputMessage, InputMessageContent};
8use crate::traits::InputSender;
9use async_trait::async_trait;
10use infinity_provider_protocol::message::Text;
11use infinity_provider_protocol::message::{ToolResult, ToolResultContent, UserContent};
12
13pub(crate) type ToolError = Box<dyn std::error::Error + Send + Sync>;
14
15/// Enqueue an error as the result of a tool call so the agent can recover.
16pub(crate) async fn send_tool_error<M: InputSender>(
17    context: &ToolContext<M>,
18    id: &rap_protocol::ToolCallId<str>,
19    call_id: Option<rap_protocol::ProviderCallId>,
20    error: impl Into<String>,
21) -> Result<(), ToolError>
22where
23    M::Error: 'static,
24{
25    let message = InputMessage {
26        content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
27            id: id.as_str().to_owned(),
28            call_id: call_id.map(|c| c.into_inner()),
29            content: vec![ToolResultContent::Text(Text {
30                text: format!("Error: {}", error.into()),
31            })],
32        })),
33        group_id: context.group_id.clone(),
34        metadata: None,
35        synthetic: None,
36        display_as: None,
37        subscription: false,
38    };
39
40    context
41        .message_sender
42        .send_to_input_queue(message, id.as_str())
43        .await
44        .map_err(|error| Box::new(error) as ToolError)
45}
46
47/// Context passed to tool implementations — generic over platform backends.
48#[derive(Clone)]
49pub struct ToolContext<M: InputSender> {
50    pub message_sender: M,
51    pub group_id: rap_protocol::ThreadId,
52    pub callback_url: String,
53    pub user_id: Option<String>,
54    /// Full thread stack: [root, ..ancestors, current_thread].
55    pub thread_stack: Vec<rap_protocol::ThreadId>,
56    /// The current thread's safe spawn point at the moment of a synchronous
57    /// tool execution: the absolute store order cutting right *before* the
58    /// tool call being executed (see
59    /// [`HistoryManager::safe_spawn_point`](crate::event_processor::HistoryManager::safe_spawn_point)).
60    /// `spawn_thread` uses it to exclude its own call from the child's
61    /// inherited history (the child gets a duplicated copy in its own store
62    /// instead, so the call survives parent-side compaction). Only set
63    /// during synchronous tool execution; `None` elsewhere.
64    pub safe_spawn_point: Option<usize>,
65}
66
67#[async_trait]
68pub trait Tool<M: InputSender>: Send + Sync {
69    fn name(&self) -> &str;
70    fn description(&self) -> &str;
71    fn parameters(&self) -> serde_json::Value;
72    async fn execute(
73        &self,
74        args: serde_json::Value,
75        id: rap_protocol::ToolCallId,
76        call_id: Option<rap_protocol::ProviderCallId>,
77        context: &ToolContext<M>,
78    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
79
80    fn supports_sync(&self) -> bool {
81        false
82    }
83
84    /// Whether a dispatched call to this tool represents *waiting* rather
85    /// than in-flight work (e.g. the sleep tools). While a thread's last
86    /// history entry is an unanswered call to a non-passive tool, deferrable
87    /// synthetic events are held back so they don't interrupt the running
88    /// call; calls to passive tools may be interrupted freely.
89    fn is_passive(&self) -> bool {
90        false
91    }
92
93    /// Optional Rhai script for pretty-printing this tool call.
94    fn display_script(&self) -> Option<&str> {
95        None
96    }
97
98    /// Execute the tool synchronously, returning results that should be
99    /// injected into the conversation history immediately. When this returns
100    /// `Some`, `execute` will not be called — the returned messages are
101    /// processed inline and the completion loop continues. This avoids race
102    /// conditions where a concurrent event can make the tool call appear
103    /// cancelled even though it already launched.
104    async fn execute_synchronous(
105        &self,
106        _args: &serde_json::Value,
107        _id: &rap_protocol::ToolCallId<str>,
108        _call_id: Option<&rap_protocol::ProviderCallId<str>>,
109        _context: &ToolContext<M>,
110    ) -> Option<ToolResult> {
111        None
112    }
113}
114
115/// Evaluate a Rhai display script with tool arguments as scope variables.
116/// Returns `Some(pretty_string)` on success, `None` if script is absent or fails.
117pub fn eval_display_script(script: Option<&str>, args: &serde_json::Value) -> Option<String> {
118    let script = script?;
119    let engine = rhai::Engine::new();
120    let mut scope = rhai::Scope::new();
121    let mut map = rhai::Map::new();
122    if let Some(obj) = args.as_object() {
123        for (k, v) in obj {
124            let val: rhai::Dynamic = match v {
125                serde_json::Value::String(s) => s.clone().into(),
126                serde_json::Value::Bool(b) => (*b).into(),
127                serde_json::Value::Number(n) => {
128                    if let Some(i) = n.as_i64() {
129                        i.into()
130                    } else if let Some(f) = n.as_f64() {
131                        f.into()
132                    } else {
133                        continue;
134                    }
135                }
136                other => other.to_string().into(),
137            };
138            map.insert(k.as_str().into(), val);
139        }
140    }
141    scope.push("args", map);
142    engine.eval_with_scope::<String>(&mut scope, script).ok()
143}