1use serde_json::json;
8
9use super::input::InputReader;
10use crate::cancel::CancelOptions;
11use crate::error::{Error, Result};
12use crate::tools::{FunctionTool, ToolError};
13use crate::types::{JsonSchema, JsonValue};
14
15pub const DEFAULT_STOP_MESSAGE: &str = "Agent loop stopped.";
17
18pub const DEFAULT_STOP_DESCRIPTION: &str = concat!(
20 "Gracefully ends the agent loop when the task is complete. ",
21 "Call this tool once with an optional final message when no further work is needed. ",
22 "This is a cooperative stop, not an abort: any tools already requested in this turn still run."
23);
24
25pub const DEFAULT_MAX_STOP_MESSAGE_LENGTH: usize = 4096;
27
28#[derive(Debug, Clone, Default, bon::Builder)]
30#[builder(on(String, into))]
31pub struct MakeStopOptions {
32 pub name: Option<String>,
34 pub description: Option<String>,
36 pub max_message_length: Option<usize>,
39}
40
41fn input_schema(max_message_length: usize) -> JsonSchema {
42 json!({
43 "type": "object",
44 "properties": {
45 "message": {
46 "description": "Optional final message summarizing why the loop is ending. Appears as the loop's last assistant turn.",
47 "anyOf": [{"type": "string", "maxLength": max_message_length}, {"type": "null"}]
48 }
49 },
50 "additionalProperties": false
51 })
52}
53
54#[must_use]
56pub fn stop() -> FunctionTool {
57 build(
58 "stop".to_owned(),
59 DEFAULT_STOP_DESCRIPTION.to_owned(),
60 DEFAULT_MAX_STOP_MESSAGE_LENGTH,
61 )
62}
63
64pub fn make_stop(options: MakeStopOptions) -> Result<FunctionTool> {
79 let max_message_length = options.max_message_length.unwrap_or(DEFAULT_MAX_STOP_MESSAGE_LENGTH);
80 if max_message_length == 0 {
81 return Err(Error::other("maxMessageLength must be a positive integer, got 0"));
82 }
83 Ok(build(
84 options.name.unwrap_or_else(|| "stop".to_owned()),
85 options
86 .description
87 .unwrap_or_else(|| DEFAULT_STOP_DESCRIPTION.to_owned()),
88 max_message_length,
89 ))
90}
91
92fn build(name: String, description: String, max_message_length: usize) -> FunctionTool {
93 FunctionTool::builder(name, description)
94 .input_schema(input_schema(max_message_length))
95 .callback(move |input, context| {
96 let result = parse(&input, max_message_length).map(|message| {
97 context.agent().cancel(CancelOptions {
98 message: Some(message.clone()),
99 after_current_tools: true,
100 ..CancelOptions::default()
101 });
102 JsonValue::String(message)
103 });
104 async move { result }
105 })
106}
107
108fn parse(input: &JsonValue, max_message_length: usize) -> std::result::Result<String, ToolError> {
109 let mut reader = InputReader::new(input);
110 let message = reader.nullable_string("message");
111 if message.is_some_and(|message| message.encode_utf16().count() > max_message_length) {
112 reader.issue(
113 "message",
114 format!("`message` length exceeds the maximum of {max_message_length} characters"),
115 );
116 }
117 reader.finish()?;
118 Ok(message
119 .filter(|message| !message.is_empty())
120 .unwrap_or(DEFAULT_STOP_MESSAGE)
121 .to_owned())
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127 use crate::Agent;
128 use crate::agent::ToolAgent;
129 use crate::testing::{MockModel, MockTurn};
130 use crate::tools::Tool;
131 use crate::types::{ContentBlock, StopReason, ToolUseBlock};
132 use crate::vended_tools::test_support::{agent, error_text, ok_text};
133
134 fn assert_cancelled_with(agent: &ToolAgent, message: &str) {
135 let signal = agent.cancel_signal();
136 assert!(signal.is_deferred());
137 assert!(!signal.is_cancelled());
138 assert_eq!(signal.reason().as_deref(), Some(message));
139 }
140
141 #[tokio::test]
142 async fn ends_the_loop_after_the_batch_with_the_message_as_the_final_assistant_message() {
143 let model = MockModel::new()
144 .with_turn(MockTurn::content([ContentBlock::ToolUse(ToolUseBlock::new(
145 "stop",
146 "t1",
147 json!({"message": "All done"}),
148 ))]))
149 .with_turn("unreachable");
150 let mut agent = Agent::builder()
151 .model(model.clone())
152 .tools([stop()])
153 .printer(false)
154 .build()
155 .unwrap();
156 let result = agent.invoke("Go").await.unwrap();
157 assert_eq!(result.stop_reason(), StopReason::Cancelled);
158 assert_eq!(result.last_message().content, vec![ContentBlock::text("All done")]);
159 assert_eq!(agent.messages().last(), Some(result.last_message()));
160 assert_eq!(model.call_count(), 1);
161 }
162
163 #[tokio::test]
164 async fn returns_the_provided_message_verbatim() {
165 assert_eq!(
166 ok_text(&stop(), json!({"message": "all done"}), &agent()).await,
167 "all done"
168 );
169 }
170
171 #[tokio::test]
172 async fn returns_the_default_message_when_none_is_provided() {
173 assert_eq!(ok_text(&stop(), json!({}), &agent()).await, DEFAULT_STOP_MESSAGE);
174 }
175
176 #[tokio::test]
177 async fn defers_the_cancellation_so_sibling_tools_in_the_batch_still_run() {
178 let agent = agent();
179 ok_text(&stop(), json!({"message": "finished"}), &agent).await;
180 assert_cancelled_with(&agent, "finished");
181 }
182
183 #[tokio::test]
184 async fn cancels_with_the_default_message_when_none_is_provided() {
185 let agent = agent();
186 ok_text(&stop(), json!({}), &agent).await;
187 assert_cancelled_with(&agent, DEFAULT_STOP_MESSAGE);
188 }
189
190 #[tokio::test]
191 async fn falls_back_to_the_default_when_message_is_an_empty_string_so_the_loop_still_has_a_final_message() {
192 let agent = agent();
193 assert_eq!(
194 ok_text(&stop(), json!({"message": ""}), &agent).await,
195 DEFAULT_STOP_MESSAGE
196 );
197 assert_cancelled_with(&agent, DEFAULT_STOP_MESSAGE);
198 }
199
200 #[tokio::test]
201 async fn falls_back_to_the_default_when_message_is_null_so_providers_that_serialize_omitted_fields_as_null_still_halt()
202 {
203 let agent = agent();
204 assert_eq!(
205 ok_text(&stop(), json!({"message": null}), &agent).await,
206 DEFAULT_STOP_MESSAGE
207 );
208 assert_cancelled_with(&agent, DEFAULT_STOP_MESSAGE);
209 }
210
211 #[tokio::test]
212 async fn rejects_an_oversized_message() {
213 let oversized = "x".repeat(DEFAULT_MAX_STOP_MESSAGE_LENGTH + 1);
214 let message = error_text(&stop(), json!({"message": oversized}), &agent()).await;
215 assert!(message.contains("maximum"), "{message}");
216 }
217
218 #[tokio::test]
219 async fn accepts_a_message_at_the_length_cap() {
220 let at_cap = "x".repeat(DEFAULT_MAX_STOP_MESSAGE_LENGTH);
221 assert_eq!(ok_text(&stop(), json!({"message": at_cap}), &agent()).await, at_cap);
222 }
223
224 #[tokio::test]
225 async fn rejects_a_non_string_message() {
226 error_text(&stop(), json!({"message": 123}), &agent()).await;
227 }
228
229 #[tokio::test]
230 async fn does_not_cancel_the_agent_when_validation_fails() {
231 let agent = agent();
232 let oversized = "x".repeat(DEFAULT_MAX_STOP_MESSAGE_LENGTH + 1);
233 error_text(&stop(), json!({"message": oversized}), &agent).await;
234 assert!(!agent.cancel_signal().is_deferred());
235 }
236
237 #[tokio::test]
238 async fn relaxes_the_cap_when_max_message_length_is_configured() {
239 let big = make_stop(MakeStopOptions::builder().max_message_length(10_000).build()).unwrap();
240 let message = "x".repeat(8000);
241 assert_eq!(ok_text(&big, json!({"message": message}), &agent()).await, message);
242 }
243
244 #[tokio::test]
245 async fn still_enforces_the_configured_cap_when_it_is_exceeded() {
246 let big = make_stop(MakeStopOptions::builder().max_message_length(10_000).build()).unwrap();
247 let message = error_text(&big, json!({"message": "x".repeat(10_001)}), &agent()).await;
248 assert!(message.contains("maximum of 10000"), "{message}");
249 }
250
251 #[test]
252 fn rejects_a_non_positive_max_message_length_at_factory_time() {
253 let error = make_stop(MakeStopOptions::builder().max_message_length(0).build()).unwrap_err();
254 assert!(error.to_string().contains("positive integer"));
255 }
256
257 #[test]
258 fn supports_a_custom_name() {
259 assert_eq!(
260 make_stop(MakeStopOptions::builder().name("finish").build())
261 .unwrap()
262 .name(),
263 "finish"
264 );
265 }
266
267 #[test]
268 fn supports_a_custom_description() {
269 let custom = make_stop(MakeStopOptions::builder().description("custom desc").build()).unwrap();
270 assert_eq!(custom.description(), "custom desc");
271 }
272
273 #[test]
274 fn exposes_message_as_an_optional_property_in_the_tool_spec() {
275 let schema = stop().tool_spec().input_schema.unwrap();
276 assert!(schema["properties"].get("message").is_some());
277 assert!(schema.get("required").is_none());
278 }
279}