Skip to main content

infinity_agent_core/tools/
sleep.rs

1use async_trait::async_trait;
2use infinity_provider_protocol::message::{Text, ToolResult, ToolResultContent, UserContent};
3use tracing;
4
5use super::{Tool, ToolContext};
6use crate::message::{InputMessage, InputMessageContent};
7use crate::traits::InputSender;
8
9/// A no-op tool that signals the agent should wait indefinitely until an external event or user input arrives.
10/// The agent loop will simply stop after this tool is invoked, and resume when new input comes in.
11pub struct SleepUntilEventOrInputTool;
12
13#[async_trait]
14impl<M: InputSender + 'static> Tool<M> for SleepUntilEventOrInputTool {
15    fn name(&self) -> &str {
16        "sleep_until_event_or_input"
17    }
18
19    fn description(&self) -> &str {
20        "Sleep indefinitely until an external event or user input arrives. Use this when you have completed all current tasks and are waiting for something to happen (e.g., a webhook, a scheduled event, or user input). The agent will pause and automatically resume when new input is received."
21    }
22
23    fn parameters(&self) -> serde_json::Value {
24        serde_json::json!({
25            "type": "object",
26            "properties": {},
27            "required": []
28        })
29    }
30
31    fn display_script(&self) -> Option<&str> {
32        Some(r#""Sleeping until event or input""#)
33    }
34
35    fn is_passive(&self) -> bool {
36        true
37    }
38
39    async fn execute(
40        &self,
41        _args: serde_json::Value,
42        _id: rap_protocol::ToolCallId,
43        _call_id: Option<rap_protocol::ProviderCallId>,
44        _context: &ToolContext<M>,
45    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
46        tracing::info!("sleep_until_event_or_input invoked, agent will pause until next input");
47        Ok(())
48    }
49}
50
51/// Timed sleep tool backed by an in-process tokio timer. Suitable for
52/// resident runtimes (embedded systems, daemons); serverless deployments
53/// need durable timers instead (e.g. SQS delays / EventBridge Scheduler).
54pub struct TokioSleepTool;
55
56#[async_trait]
57impl<M: InputSender + 'static> Tool<M> for TokioSleepTool {
58    fn name(&self) -> &str {
59        "sleep"
60    }
61
62    fn description(&self) -> &str {
63        "Sleep for a specified number of seconds before continuing. Useful for waiting or delaying actions. This tool will automatically be interrupted by the system on user input, so you are free to invoke it in a loop as necessary."
64    }
65
66    fn parameters(&self) -> serde_json::Value {
67        serde_json::json!({
68            "type": "object",
69            "properties": {
70                "seconds": { "type": "number", "description": "Number of seconds to sleep" },
71                "reason": { "type": "string", "description": "Human-readable reason for sleeping" }
72            },
73            "required": ["seconds"]
74        })
75    }
76
77    fn display_script(&self) -> Option<&str> {
78        Some(
79            r#"let s = "Sleeping " + args.seconds + "s"; if args.reason != () { s += ": " + args.reason; } s"#,
80        )
81    }
82
83    fn is_passive(&self) -> bool {
84        true
85    }
86
87    async fn execute(
88        &self,
89        args: serde_json::Value,
90        id: rap_protocol::ToolCallId,
91        call_id: Option<rap_protocol::ProviderCallId>,
92        context: &ToolContext<M>,
93    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
94        let seconds = args["seconds"].as_f64().unwrap_or(0.0);
95        let group_id = context.group_id.clone();
96        let sender = context.message_sender.clone();
97
98        tokio::spawn(rap_protocol::log_panic("sleep_tool", async move {
99            if seconds > 0.0 {
100                tokio::time::sleep(std::time::Duration::from_secs_f64(seconds)).await;
101            }
102            let msg = InputMessage {
103                content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
104                    id: id.clone().into_inner(),
105                    call_id: call_id.map(|c| c.into_inner()),
106                    content: vec![ToolResultContent::Text(Text {
107                        text: format!("Slept for {} seconds", seconds),
108                    })],
109                })),
110                group_id: group_id.clone(),
111                metadata: None,
112                synthetic: None,
113                display_as: None,
114                subscription: false,
115            };
116            if let Err(e) = sender.send_to_input_queue(msg, id.as_str()).await {
117                tracing::error!("Failed to deliver sleep result: {}", e);
118            }
119        }));
120
121        tracing::info!("Sleep scheduled for {} seconds", seconds);
122        Ok(())
123    }
124}
125
126/// Sleep-until-wall-clock-time tool backed by an in-process tokio timer. See
127/// [`TokioSleepTool`] for platform considerations.
128pub struct TokioSleepUntilTool;
129
130#[async_trait]
131impl<M: InputSender + 'static> Tool<M> for TokioSleepUntilTool {
132    fn name(&self) -> &str {
133        "sleep_until"
134    }
135
136    fn description(&self) -> &str {
137        "Sleep until a specific date and time in a given timezone. The agent will hibernate and wake up at the specified time."
138    }
139
140    fn parameters(&self) -> serde_json::Value {
141        serde_json::json!({
142            "type": "object",
143            "properties": {
144                "date": { "type": "string", "description": "Target date in YYYY-MM-DD format" },
145                "time": { "type": "string", "description": "Target time in HH:MM or HH:MM:SS 24-hour format" },
146                "timezone": { "type": "string", "description": "IANA timezone name. Defaults to UTC." }
147            },
148            "required": ["date", "time"]
149        })
150    }
151
152    fn display_script(&self) -> Option<&str> {
153        Some(
154            r#"let s = "Sleeping until " + args.date + " " + args.time; if args.timezone != () { s += " (" + args.timezone + ")"; } s"#,
155        )
156    }
157
158    fn is_passive(&self) -> bool {
159        true
160    }
161
162    async fn execute(
163        &self,
164        args: serde_json::Value,
165        id: rap_protocol::ToolCallId,
166        call_id: Option<rap_protocol::ProviderCallId>,
167        context: &ToolContext<M>,
168    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
169        let date_str = args["date"].as_str().unwrap_or("").to_owned();
170        let time_str = args["time"].as_str().unwrap_or("").to_owned();
171        let tz_str = args["timezone"].as_str().unwrap_or("UTC").to_owned();
172
173        let tz: chrono_tz::Tz = tz_str
174            .parse()
175            .map_err(|_| format!("Invalid timezone: '{}'", tz_str))?;
176        let date = chrono::NaiveDate::parse_from_str(&date_str, "%Y-%m-%d")?;
177        let time = chrono::NaiveTime::parse_from_str(&time_str, "%H:%M:%S")
178            .or_else(|_| chrono::NaiveTime::parse_from_str(&time_str, "%H:%M"))?;
179
180        let naive_dt = chrono::NaiveDateTime::new(date, time);
181        let local_dt = naive_dt
182            .and_local_timezone(tz)
183            .single()
184            .ok_or(format!("Ambiguous datetime {} in {}", naive_dt, tz_str))?;
185        let target_utc = local_dt.with_timezone(&chrono::Utc);
186        let now = chrono::Utc::now();
187
188        let is_past = target_utc <= now;
189        let result_text = if is_past {
190            format!(
191                "Target time {} {} is in the past. Waking immediately.",
192                date_str, time_str
193            )
194        } else {
195            format!(
196                "Woke up at target time: {} {} ({})",
197                date_str, time_str, tz_str
198            )
199        };
200
201        let group_id = context.group_id.clone();
202        let sender = context.message_sender.clone();
203
204        tokio::spawn(rap_protocol::log_panic("sleep_until_tool", async move {
205            if !is_past {
206                let duration = (target_utc - now).to_std().unwrap_or_default();
207                tokio::time::sleep(duration).await;
208            }
209            let msg = InputMessage {
210                content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
211                    id: id.clone().into_inner(),
212                    call_id: call_id.map(|c| c.into_inner()),
213                    content: vec![ToolResultContent::Text(Text { text: result_text })],
214                })),
215                group_id: group_id.clone(),
216                metadata: None,
217                synthetic: None,
218                display_as: None,
219                subscription: false,
220            };
221            if let Err(e) = sender.send_to_input_queue(msg, id.as_str()).await {
222                tracing::error!("Failed to deliver sleep_until result: {}", e);
223            }
224        }));
225
226        Ok(())
227    }
228}