Skip to main content

strands/vended_tools/
sleep.rs

1//! The `sleep` tool: pauses for a bounded number of seconds and stops at once when the call is
2//! cancelled.
3
4use serde_json::json;
5
6use super::input::InputReader;
7use super::{js_number, js_number_text, seconds};
8use crate::cancel::CancelSignal;
9use crate::error::{Error, Result};
10use crate::tools::{FunctionTool, ToolError};
11use crate::types::{JsonSchema, JsonValue};
12
13/// The default upper bound on `duration`, in seconds (`DEFAULT_MAX_DURATION`).
14pub const DEFAULT_MAX_DURATION: f64 = 60.0;
15
16/// The description of the default `sleep` tool (`SLEEP_DESCRIPTION`), with its 60-second cap.
17pub const SLEEP_DESCRIPTION: &str = "Pauses execution for a specified number of seconds (max 60). Cooperative and cancellable: the sleep aborts immediately when the agent invocation is cancelled. Rejects negative, NaN, infinite, or non-numeric durations, and durations above 60.";
18
19/// The model-facing description for a cap of `max_duration` seconds.
20#[must_use]
21pub fn sleep_description(max_duration: f64) -> String {
22    let max = js_number_text(max_duration);
23    format!(
24        "Pauses execution for a specified number of seconds (max {max}). Cooperative and cancellable: the sleep aborts immediately when the agent invocation is cancelled. Rejects negative, NaN, infinite, or non-numeric durations, and durations above {max}."
25    )
26}
27
28/// Options for [`make_sleep`] (`MakeSleepOptions`).
29#[derive(Debug, Clone, Default, bon::Builder)]
30#[builder(on(String, into))]
31pub struct MakeSleepOptions {
32    /// The largest `duration` accepted, in seconds; [`DEFAULT_MAX_DURATION`] when absent.
33    pub max_duration: Option<f64>,
34    /// The tool name; `sleep` when absent.
35    pub name: Option<String>,
36    /// The tool description; [`sleep_description`] of the cap when absent.
37    pub description: Option<String>,
38}
39
40fn input_schema(max_duration: f64) -> JsonSchema {
41    json!({
42        "type": "object",
43        "properties": {
44            "duration": {
45                "type": "number",
46                "minimum": 0,
47                "maximum": js_number(max_duration),
48                "description": format!(
49                    "Seconds to pause. Must be finite, non-negative, and no larger than {}.",
50                    js_number_text(max_duration)
51                )
52            }
53        },
54        "required": ["duration"],
55        "additionalProperties": false
56    })
57}
58
59/// The default `sleep` tool, capped at 60 seconds (`sleep`).
60#[must_use]
61pub fn sleep() -> FunctionTool {
62    build(DEFAULT_MAX_DURATION, "sleep".to_owned(), SLEEP_DESCRIPTION.to_owned())
63}
64
65/// Creates a sleep tool with a configurable cap. The call returns
66/// `Slept for <duration> seconds`, or fails at once when its cancel signal fires.
67///
68/// ```
69/// use strands::vended_tools::sleep::{MakeSleepOptions, make_sleep};
70///
71/// let short_sleep = make_sleep(MakeSleepOptions::builder().max_duration(5.0).build())?;
72/// assert!(strands::Tool::description(&short_sleep).contains("max 5"));
73/// # Ok::<(), strands::Error>(())
74/// ```
75///
76/// # Errors
77///
78/// When `max_duration` is not a positive finite number.
79pub fn make_sleep(options: MakeSleepOptions) -> Result<FunctionTool> {
80    let max_duration = options.max_duration.unwrap_or(DEFAULT_MAX_DURATION);
81    if !max_duration.is_finite() || max_duration <= 0.0 {
82        return Err(Error::other(format!(
83            "maxDuration must be a positive, finite number, got {}",
84            js_number_text(max_duration)
85        )));
86    }
87    let name = options.name.unwrap_or_else(|| "sleep".to_owned());
88    let description = options.description.unwrap_or_else(|| sleep_description(max_duration));
89    Ok(build(max_duration, name, description))
90}
91
92fn build(max_duration: f64, name: String, description: String) -> FunctionTool {
93    FunctionTool::builder(name, description)
94        .input_schema(input_schema(max_duration))
95        .callback(move |input, context| {
96            let signal = context.cancel_signal().clone();
97            async move { run(&input, max_duration, &signal).await }
98        })
99}
100
101/// Sleeps `duration` seconds; a duration too long for a
102/// [`Duration`](std::time::Duration) never ends.
103async fn sleep_for(duration: f64) {
104    match seconds(duration) {
105        Some(duration) => tokio::time::sleep(duration).await,
106        None => std::future::pending().await,
107    }
108}
109
110fn cancelled(signal: &CancelSignal, fallback: &str) -> ToolError {
111    ToolError::msg(signal.reason().unwrap_or_else(|| fallback.to_owned()))
112}
113
114async fn run(input: &JsonValue, max_duration: f64, signal: &CancelSignal) -> std::result::Result<JsonValue, ToolError> {
115    let mut reader = InputReader::new(input);
116    let duration = reader.number("duration");
117    if let Some(duration) = duration {
118        if duration < 0.0 {
119            reader.issue("duration", "duration must be non-negative");
120        } else if duration > max_duration {
121            let message = format!("duration exceeds maximum of {} seconds", js_number_text(max_duration));
122            reader.issue("duration", message);
123        }
124    }
125    reader.finish()?;
126    let duration = duration.unwrap_or_default();
127    if signal.is_cancelled() {
128        return Err(cancelled(signal, "Sleep cancelled before it started"));
129    }
130    tokio::select! {
131        () = sleep_for(duration) => {}
132        () = signal.cancelled() => return Err(cancelled(signal, "Sleep cancelled")),
133    }
134    Ok(format!("Slept for {} seconds", js_number_text(duration)).into())
135}
136
137#[cfg(test)]
138mod tests {
139    //! Time is paused, so no test waits for real.
140
141    use std::time::Duration;
142
143    use super::*;
144    use crate::cancel::{CancelHandle, CancelOptions};
145    use crate::types::ToolResultStatus;
146    use crate::vended_tools::test_support::{agent, error_text, ok_text, run_with_signal, text};
147
148    async fn rejects(tool: &FunctionTool, duration: JsonValue) -> String {
149        error_text(tool, json!({"duration": duration}), &agent()).await
150    }
151
152    #[tokio::test(start_paused = true)]
153    async fn rejects_negative_durations() {
154        assert!(rejects(&sleep(), json!(-0.1)).await.contains("non-negative"));
155    }
156
157    #[tokio::test(start_paused = true)]
158    async fn rejects_non_numeric_input_via_schema() {
159        let message = rejects(&sleep(), json!("one")).await;
160        assert!(message.contains("expected number, received string"), "{message}");
161    }
162
163    #[tokio::test(start_paused = true)]
164    async fn rejects_boolean_input_via_schema() {
165        rejects(&sleep(), json!(true)).await;
166        rejects(&sleep(), json!(false)).await;
167    }
168
169    #[tokio::test(start_paused = true)]
170    async fn rejects_duration_above_default_maximum() {
171        let message = rejects(&sleep(), json!(DEFAULT_MAX_DURATION + 1.0)).await;
172        assert!(message.contains("duration exceeds maximum of 60 seconds"), "{message}");
173    }
174
175    #[tokio::test(start_paused = true)]
176    async fn rejects_duration_above_configured_maximum() {
177        let capped = make_sleep(MakeSleepOptions::builder().max_duration(0.5).build()).unwrap();
178        assert!(rejects(&capped, json!(0.6)).await.contains("exceeds maximum"));
179    }
180
181    #[test]
182    fn rejects_invalid_max_duration() {
183        for value in [0.0, -1.0, f64::NAN, f64::INFINITY] {
184            let error = make_sleep(MakeSleepOptions::builder().max_duration(value).build()).unwrap_err();
185            assert!(error.to_string().contains("positive"), "{error}");
186        }
187    }
188
189    #[tokio::test(start_paused = true)]
190    async fn aborts_immediately_when_cancel_signal_fires_mid_sleep() {
191        let handle = CancelHandle::new();
192        let canceller = handle.clone();
193        tokio::spawn(async move {
194            tokio::time::sleep(Duration::from_millis(10)).await;
195            canceller.cancel(CancelOptions::default());
196        });
197        let started = tokio::time::Instant::now();
198        let result = run_with_signal(&sleep(), json!({"duration": 5}), &agent(), handle.signal()).await;
199        assert!(started.elapsed() < Duration::from_secs(1));
200        assert_eq!(result.status, ToolResultStatus::Error);
201        assert_eq!(text(&result), "Error: Sleep cancelled");
202    }
203
204    #[tokio::test(start_paused = true)]
205    async fn sleeps_until_cancelled_when_the_duration_is_too_long_for_a_timer() {
206        let capped = make_sleep(MakeSleepOptions::builder().max_duration(1e300).build()).unwrap();
207        let handle = CancelHandle::new();
208        let canceller = handle.clone();
209        tokio::spawn(async move {
210            tokio::time::sleep(Duration::from_millis(10)).await;
211            canceller.cancel(CancelOptions::default());
212        });
213        let result = run_with_signal(&capped, json!({"duration": 1e300}), &agent(), handle.signal()).await;
214        assert_eq!(text(&result), "Error: Sleep cancelled");
215    }
216
217    #[tokio::test(start_paused = true)]
218    async fn rejects_synchronously_when_the_signal_is_already_aborted() {
219        let handle = CancelHandle::new();
220        handle.cancel(CancelOptions {
221            message: Some("stop now".to_owned()),
222            ..CancelOptions::default()
223        });
224        let result = run_with_signal(&sleep(), json!({"duration": 1}), &agent(), handle.signal()).await;
225        assert_eq!(text(&result), "Error: stop now");
226    }
227
228    #[tokio::test(start_paused = true)]
229    async fn returns_the_expected_message_after_a_short_sleep() {
230        let started = tokio::time::Instant::now();
231        assert_eq!(
232            ok_text(&sleep(), json!({"duration": 0.05}), &agent()).await,
233            "Slept for 0.05 seconds"
234        );
235        assert!(started.elapsed() >= Duration::from_millis(50));
236    }
237
238    #[tokio::test(start_paused = true)]
239    async fn accepts_zero_duration() {
240        assert_eq!(
241            ok_text(&sleep(), json!({"duration": 0}), &agent()).await,
242            "Slept for 0 seconds"
243        );
244    }
245
246    #[tokio::test(start_paused = true)]
247    async fn drives_the_timer_with_the_requested_duration() {
248        let started = tokio::time::Instant::now();
249        assert_eq!(
250            ok_text(&sleep(), json!({"duration": 2}), &agent()).await,
251            "Slept for 2 seconds"
252        );
253        assert_eq!(started.elapsed(), Duration::from_secs(2));
254    }
255
256    #[test]
257    fn describes_the_configured_cap() {
258        assert_eq!(sleep_description(DEFAULT_MAX_DURATION), SLEEP_DESCRIPTION);
259    }
260}