1use std::collections::HashMap;
2use std::sync::Mutex;
3
4use async_trait::async_trait;
5
6use crate::engine::middleware::{Middleware, PostLlmCtx, UserMessageCtx};
7use crate::types::{AgentResult, SessionId};
8
9pub const DEFAULT_NUDGE_AFTER: usize = 5;
12pub const DEFAULT_BLOCK_AFTER: usize = 10;
15
16#[derive(Clone, Debug)]
18pub struct RepeatToolLimitConfig {
19 pub nudge_after: usize,
22 pub block_after: usize,
24 pub nudge_message: String,
25 pub block_message: String,
26}
27
28impl Default for RepeatToolLimitConfig {
29 fn default() -> Self {
30 Self {
31 nudge_after: DEFAULT_NUDGE_AFTER,
32 block_after: DEFAULT_BLOCK_AFTER,
33 nudge_message: "You have issued the exact same tool call with the same arguments \
34 repeatedly. Identical repetition cannot change the outcome: if the call keeps \
35 failing, fix the payload or take a different action; if the work is done, \
36 write your response and end the turn."
37 .to_string(),
38 block_message: "You have issued this identical tool call far too many times. The \
39 pending calls were discarded. Based on everything you already know, write your \
40 response and end the turn. Do not call this tool again."
41 .to_string(),
42 }
43 }
44}
45
46pub struct RepeatToolLimitMiddleware {
74 config: RepeatToolLimitConfig,
75 counts: Mutex<HashMap<SessionId, HashMap<String, usize>>>,
76}
77
78impl RepeatToolLimitMiddleware {
79 pub fn new(config: RepeatToolLimitConfig) -> Self {
80 Self {
81 config,
82 counts: Mutex::new(HashMap::new()),
83 }
84 }
85
86 fn bump(&self, session_id: &SessionId, fingerprint: &str) -> usize {
92 let mut counts = self.counts.lock().unwrap();
93 let session_counts = counts.entry(session_id.clone()).or_default();
94 let entry = session_counts.entry(fingerprint.to_string()).or_insert(0);
95 *entry += 1;
96 *entry
97 }
98}
99
100#[async_trait]
101impl Middleware for RepeatToolLimitMiddleware {
102 async fn on_user_message(&self, ctx: &mut UserMessageCtx) -> AgentResult<()> {
103 self.counts.lock().unwrap().remove(&ctx.session_id);
105 Ok(())
106 }
107
108 async fn on_post_llm(&self, ctx: &mut PostLlmCtx) -> AgentResult<()> {
109 if ctx.actions().is_empty() {
110 return Ok(());
111 }
112
113 let mut max_count = 0usize;
114 let mut offending_tool = String::new();
115 for action in ctx.actions() {
116 let count = self.bump(&ctx.session_id, &action.identity);
117 if count > max_count {
118 max_count = count;
119 offending_tool = action.name.clone();
120 }
121 }
122
123 if max_count >= self.config.block_after {
124 tracing::warn!(
125 session_id = ctx.session_id.id,
126 tool = %offending_tool,
127 count = max_count,
128 pending_calls = ctx.actions().len(),
129 "RepeatToolLimit: blocking tool calls — identical-call limit reached"
130 );
131 ctx.demote_to_text();
132 ctx.follow_up_message = Some(self.config.block_message.clone());
133 } else if self.config.nudge_after > 0 && max_count == self.config.nudge_after {
134 tracing::info!(
137 session_id = ctx.session_id.id,
138 tool = %offending_tool,
139 count = max_count,
140 "RepeatToolLimit: nudging — identical-call threshold reached"
141 );
142 ctx.follow_up_message = Some(self.config.nudge_message.clone());
143 }
144
145 Ok(())
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use crate::engine::executor::ParseOutcome;
153 use crate::types::{Action, ActionFormat, FinishReason};
154
155 fn mw() -> RepeatToolLimitMiddleware {
156 RepeatToolLimitMiddleware::new(RepeatToolLimitConfig::default())
157 }
158
159 fn ctx(session: u64, calls: Vec<(&str, &str)>) -> PostLlmCtx {
160 let actions = calls
161 .into_iter()
162 .enumerate()
163 .map(|(i, (name, args))| Action {
164 id: format!("call_{i}"),
165 name: name.to_string(),
166 args: serde_json::Value::String(args.to_string()),
167 identity: Action::tool_call_identity(name, args),
168 format: ActionFormat::ToolCall,
169 })
170 .collect::<Vec<Action>>();
171 let parse = if actions.is_empty() {
172 ParseOutcome::Empty
173 } else {
174 ParseOutcome::Actions(actions)
175 };
176 PostLlmCtx {
177 session_id: SessionId::new(session),
178 full_text: String::new(),
179 parse,
180 available_tools: vec![],
181 turn_count: 1,
182 total_actions: 0,
183 nudge_count: 0,
184 turn_actions: 0,
185 skip_push: false,
186 follow_up_message: None,
187 finish_reason: FinishReason::ToolUse,
188 }
189 }
190
191 async fn call(mw: &RepeatToolLimitMiddleware, session: u64, calls: Vec<(&str, &str)>) {
192 let mut c = ctx(session, calls);
193 mw.on_post_llm(&mut c).await.unwrap();
194 }
195
196 #[tokio::test]
197 async fn interleaved_identical_calls_still_count() {
198 let mw = mw();
202 for _ in 0..4 {
203 call(
204 &mw,
205 1,
206 vec![("list_agents", "{}"), ("read_file", r#"{"path":"a.rs"}"#)],
207 )
208 .await;
209 }
210 let mut c = ctx(
212 1,
213 vec![("list_agents", "{}"), ("read_file", r#"{"path":"b.rs"}"#)],
214 );
215 mw.on_post_llm(&mut c).await.unwrap();
216 assert!(c.follow_up_message.is_some(), "5th identical call nudges");
217 assert!(
218 !c.actions().is_empty() && c.has_action_intent(),
219 "nudge is soft — calls still execute"
220 );
221 }
222
223 #[tokio::test]
224 async fn nudge_fires_only_once_per_fingerprint() {
225 let mw = mw();
226 let mut fired = 0;
227 for _ in 0..8 {
228 let mut c = ctx(1, vec![("list_agents", "{}")]);
229 mw.on_post_llm(&mut c).await.unwrap();
230 if c.follow_up_message.is_some() {
231 fired += 1;
232 }
233 }
234 assert_eq!(fired, 1, "nudge must fire exactly once, got {fired}");
235 }
236
237 #[tokio::test]
238 async fn blocks_at_threshold_and_discards_pending_calls() {
239 let mw = mw();
240 for _ in 0..9 {
241 call(&mw, 1, vec![("list_agents", "{}")]).await;
242 }
243 let mut c = ctx(
244 1,
245 vec![("list_agents", "{}"), ("read_file", r#"{"path":"x"}"#)],
246 );
247 mw.on_post_llm(&mut c).await.unwrap();
248 assert!(c.actions().is_empty(), "pending calls discarded");
249 assert!(!c.has_action_intent(), "response demoted to text-only");
250 assert!(c.follow_up_message.is_some(), "block carries a follow-up");
251 }
252
253 #[tokio::test]
254 async fn different_args_are_different_fingerprints() {
255 let mw = mw();
260 for i in 0..20 {
261 call(
262 &mw,
263 1,
264 vec![("read_file", &format!(r#"{{"path":"f{i}.rs"}}"#))],
265 )
266 .await;
267 let mut probe = ctx(
268 1,
269 vec![("read_file", &format!(r#"{{"path":"probe{i}.rs"}}"#))],
270 );
271 mw.on_post_llm(&mut probe).await.unwrap();
272 assert!(
273 probe.follow_up_message.is_none() && probe.has_action_intent(),
274 "legitimate distinct calls must never be limited"
275 );
276 }
277 }
278
279 #[tokio::test]
280 async fn same_args_reordered_keys_share_fingerprint() {
281 let mw = mw();
282 for _ in 0..4 {
283 call(&mw, 1, vec![("wait_agent", r#"{"name":"a","timeout":5}"#)]).await;
284 }
285 let mut c = ctx(1, vec![("wait_agent", r#"{"timeout":5,"name":"a"}"#)]);
287 mw.on_post_llm(&mut c).await.unwrap();
288 assert!(c.follow_up_message.is_some(), "canonical args must unify");
289 }
290
291 #[tokio::test]
292 async fn counting_key_is_the_parse_time_identity() {
293 fn action_with(id: &str, name: &str, args: &str, identity: &str) -> Action {
297 Action {
298 id: id.to_string(),
299 name: name.to_string(),
300 args: serde_json::Value::String(args.to_string()),
301 identity: identity.to_string(),
302 format: ActionFormat::ToolCall,
303 }
304 }
305 fn post(actions: Vec<Action>) -> PostLlmCtx {
306 let parse = if actions.is_empty() {
307 ParseOutcome::Empty
308 } else {
309 ParseOutcome::Actions(actions)
310 };
311 PostLlmCtx {
312 session_id: SessionId::new(1),
313 full_text: String::new(),
314 parse,
315 available_tools: vec![],
316 turn_count: 1,
317 total_actions: 0,
318 nudge_count: 0,
319 turn_actions: 0,
320 skip_push: false,
321 follow_up_message: None,
322 finish_reason: FinishReason::ToolUse,
323 }
324 }
325
326 let mw1 = mw();
328 for i in 0..4 {
329 let mut c = post(vec![action_with(&format!("c{i}"), "a", "{}", "shared")]);
330 mw1.on_post_llm(&mut c).await.unwrap();
331 assert!(c.follow_up_message.is_none(), "below threshold");
332 }
333 let mut c = post(vec![action_with(
334 "c4",
335 "totally_different",
336 r#"{"x":1}"#,
337 "shared",
338 )]);
339 mw1.on_post_llm(&mut c).await.unwrap();
340 assert!(
341 c.follow_up_message.is_some(),
342 "same identity counts together even across different names"
343 );
344
345 let mw2 = mw();
347 for i in 0..4 {
348 let mut c = post(vec![action_with(
349 &format!("d{i}"),
350 "b",
351 "{}",
352 &format!("distinct-{i}"),
353 )]);
354 mw2.on_post_llm(&mut c).await.unwrap();
355 assert!(
356 c.follow_up_message.is_none(),
357 "distinct identities do not stack"
358 );
359 }
360 let mut c = post(vec![action_with("d4", "b", "{}", "distinct-again")]);
361 mw2.on_post_llm(&mut c).await.unwrap();
362 assert!(
363 c.follow_up_message.is_none(),
364 "identity is the key — name+args alone do not accumulate"
365 );
366 }
367
368 #[tokio::test]
369 async fn on_user_message_resets_counts() {
370 let mw = mw();
371 for _ in 0..4 {
372 call(&mw, 1, vec![("list_agents", "{}")]).await;
373 }
374 mw.on_user_message(&mut UserMessageCtx {
375 session_id: SessionId::new(1),
376 user_input: "next run".to_string(),
377 })
378 .await
379 .unwrap();
380 for _ in 0..4 {
382 let mut c = ctx(1, vec![("list_agents", "{}")]);
383 mw.on_post_llm(&mut c).await.unwrap();
384 assert!(c.follow_up_message.is_none(), "counts must reset per run");
385 }
386 }
387
388 #[tokio::test]
389 async fn sessions_are_isolated() {
390 let mw = mw();
391 for _ in 0..4 {
392 call(&mw, 1, vec![("list_agents", "{}")]).await;
393 }
394 let mut other = ctx(2, vec![("list_agents", "{}")]);
395 mw.on_post_llm(&mut other).await.unwrap();
396 assert!(
397 other.follow_up_message.is_none(),
398 "session 2's first call must not see session 1's count"
399 );
400 }
401}