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: &str,
19    call_id: Option<String>,
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.to_owned(),
28            call_id,
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)
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}
57
58#[async_trait]
59pub trait Tool<M: InputSender>: Send + Sync {
60    fn name(&self) -> &str;
61    fn description(&self) -> &str;
62    fn parameters(&self) -> serde_json::Value;
63    async fn execute(
64        &self,
65        args: serde_json::Value,
66        id: String,
67        call_id: Option<String>,
68        context: &ToolContext<M>,
69    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
70
71    fn supports_sync(&self) -> bool {
72        false
73    }
74
75    /// Whether a dispatched call to this tool represents *waiting* rather
76    /// than in-flight work (e.g. the sleep tools). While a thread's last
77    /// history entry is an unanswered call to a non-passive tool, deferrable
78    /// synthetic events are held back so they don't interrupt the running
79    /// call; calls to passive tools may be interrupted freely.
80    fn is_passive(&self) -> bool {
81        false
82    }
83
84    /// Optional Rhai script for pretty-printing this tool call.
85    fn display_script(&self) -> Option<&str> {
86        None
87    }
88
89    /// Execute the tool synchronously, returning results that should be
90    /// injected into the conversation history immediately. When this returns
91    /// `Some`, `execute` will not be called — the returned messages are
92    /// processed inline and the completion loop continues. This avoids race
93    /// conditions where a concurrent event can make the tool call appear
94    /// cancelled even though it already launched.
95    async fn execute_synchronous(
96        &self,
97        _args: &serde_json::Value,
98        _id: &str,
99        _call_id: Option<&str>,
100        _context: &ToolContext<M>,
101    ) -> Option<ToolResult> {
102        None
103    }
104}
105
106/// Evaluate a Rhai display script with tool arguments as scope variables.
107/// Returns `Some(pretty_string)` on success, `None` if script is absent or fails.
108pub fn eval_display_script(script: Option<&str>, args: &serde_json::Value) -> Option<String> {
109    let script = script?;
110    let engine = rhai::Engine::new();
111    let mut scope = rhai::Scope::new();
112    let mut map = rhai::Map::new();
113    if let Some(obj) = args.as_object() {
114        for (k, v) in obj {
115            let val: rhai::Dynamic = match v {
116                serde_json::Value::String(s) => s.clone().into(),
117                serde_json::Value::Bool(b) => (*b).into(),
118                serde_json::Value::Number(n) => {
119                    if let Some(i) = n.as_i64() {
120                        i.into()
121                    } else if let Some(f) = n.as_f64() {
122                        f.into()
123                    } else {
124                        continue;
125                    }
126                }
127                other => other.to_string().into(),
128            };
129            map.insert(k.as_str().into(), val);
130        }
131    }
132    scope.push("args", map);
133    engine.eval_with_scope::<String>(&mut scope, script).ok()
134}