Skip to main content

agentmux_srv_core/agents/
loop_guard.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! Two loops an agent can be in without anyone noticing, read off the harness's stream
4//! (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md` section 5):
5//!
6//! - the same tool called with the same arguments and failing again and again in one turn (Glim made 49
7//!   identical failing `Tasks` calls), and
8//! - a thought that repeats itself ("Hmm. Hmm. Hmm.", #31427).
9//!
10//! The guard only looks: it answers [`Stuck`] for the frame that crossed a threshold, and the caller ends the
11//! turn and tells the agent and its leader. It holds no state across turns.
12
13use serde_json::Value;
14use std::collections::HashMap;
15
16/// The same failing call this many times in a turn ends the turn.
17pub const FAILING_CALLS: u32 = 5;
18/// A normalized line repeated this many times in a row is a loop.
19const LINE_RUN: usize = 20;
20/// How much of the end of a thought is looked at for repeated words.
21const TAIL_CHARS: usize = 4_000;
22/// Fewest words in the tail before a lack of variety means anything.
23const MIN_WORDS: usize = 60;
24/// How much of a streamed thought is kept to read: enough for a run of repeated lines and for [`TAIL_CHARS`].
25const STREAM_KEEP: usize = 8_000;
26/// A streamed thought is read again after this many more bytes.
27const STREAM_READ_EVERY: usize = 200;
28/// At most this many different words in the tail, of at least [`MIN_WORDS`], is a loop.
29const MAX_DISTINCT: usize = 4;
30
31/// The block indices an ACP agent's thought and message text are read under (a Claude stream numbers its own).
32const ACP_THOUGHT: u64 = 1_000;
33const ACP_MESSAGE: u64 = 1_001;
34
35/// What the agent is stuck doing.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum Stuck {
38    /// `tool` failed `count` times with the same arguments.
39    FailingCall { tool: String, count: u32 },
40    /// The same thought, over and over.
41    SameThought,
42}
43
44impl Stuck {
45    /// The row text and the message to the leader, in a few words.
46    pub fn describe(&self) -> String {
47        match self {
48            Stuck::FailingCall { tool, count } => {
49                // An MCP tool arrives as `mcp__<server>__<tool>`: the person knows it by the last part.
50                let tool = tool.rsplit("__").next().unwrap_or(tool);
51                format!("repeated failing call: {tool} x{count} (the same arguments)")
52            }
53            Stuck::SameThought => "stuck: repeating the same thought".to_string(),
54        }
55    }
56}
57
58/// Per agent: what the current turn has done so far.
59#[derive(Debug, Default)]
60pub struct LoopGuard {
61    /// A tool call's key by its `tool_use` id, until its result arrives.
62    pending: HashMap<String, (String, String)>,
63    /// Failures in this turn by call key, with the tool's name.
64    failing: HashMap<String, (String, u32)>,
65    /// The end of each thought being streamed, by content block index, with the characters added since it was last read.
66    streaming: HashMap<u64, (String, usize)>,
67    /// ACP calls that have ended in this turn, so a repeated terminal update counts once.
68    ended: std::collections::HashSet<String>,
69}
70
71impl LoopGuard {
72    /// A new turn starts: nothing failed yet.
73    pub fn new_turn(&mut self) {
74        self.pending.clear();
75        self.failing.clear();
76        self.streaming.clear();
77        self.ended.clear();
78    }
79
80    /// One frame of the harness's stdout. `Some` when this frame is the one that crossed a threshold.
81    pub fn observe(&mut self, frame: &Value) -> Option<Stuck> {
82        match frame.get("type").and_then(Value::as_str)? {
83            "assistant" => self.assistant(frame),
84            "stream_event" => self.stream_event(frame),
85            "user" => self.tool_results(frame),
86            "result" => {
87                self.new_turn();
88                None
89            }
90            _ => None,
91        }
92    }
93
94    fn assistant(&mut self, frame: &Value) -> Option<Stuck> {
95        let blocks = frame.pointer("/message/content")?.as_array()?;
96        let mut stuck = None;
97        for block in blocks {
98            match block.get("type").and_then(Value::as_str) {
99                Some("tool_use") => {
100                    let (Some(id), Some(name)) = (block.get("id").and_then(Value::as_str), block.get("name").and_then(Value::as_str)) else { continue };
101                    let key = format!("{name}\u{1f}{}", block.get("input").map(Value::to_string).unwrap_or_default());
102                    self.pending.insert(id.to_string(), (key, name.to_string()));
103                }
104                Some("thinking") => stuck = stuck.or_else(|| block.get("thinking").and_then(Value::as_str).and_then(repeats_itself)),
105                Some("text") => stuck = stuck.or_else(|| block.get("text").and_then(Value::as_str).and_then(repeats_itself)),
106                _ => {}
107            }
108        }
109        stuck
110    }
111
112    /// A streamed thought (`--include-partial-messages`): read as it arrives, so a loop is cut while the model is
113    /// still producing it and not after it has spent its output budget. The finished `assistant` snapshot is
114    /// read too, which finds the same loop if this missed it.
115    fn stream_event(&mut self, frame: &Value) -> Option<Stuck> {
116        let event = frame.get("event")?;
117        let index = event.get("index").and_then(Value::as_u64).unwrap_or(0);
118        match event.get("type").and_then(Value::as_str)? {
119            "content_block_stop" => {
120                self.streaming.remove(&index);
121                None
122            }
123            "content_block_delta" => {
124                let delta = event.get("delta")?;
125                let piece = delta.get("thinking").or_else(|| delta.get("text")).and_then(Value::as_str)?;
126                self.stream(index, piece)
127            }
128            _ => None,
129        }
130    }
131
132    /// `piece` more of the thought being streamed as block `index`.
133    fn stream(&mut self, index: u64, piece: &str) -> Option<Stuck> {
134        let (tail, added) = self.streaming.entry(index).or_default();
135        tail.push_str(piece);
136        *added += piece.len();
137        if tail.len() > STREAM_KEEP {
138            let cut = (tail.len() - STREAM_KEEP..).find(|&i| tail.is_char_boundary(i)).unwrap_or(tail.len());
139            tail.drain(..cut);
140        }
141        if *added < STREAM_READ_EVERY {
142            return None;
143        }
144        *added = 0;
145        repeats_itself(tail)
146    }
147
148    /// One line of an ACP agent's stdout (`blockcontroller/acp.rs`): a `session/update` notification, or the answer to a
149    /// `session/prompt`, which ends the turn. Reads the same two loops as [`Self::observe`]: `tool_call` and
150    /// `tool_call_update` (`status` `failed` or `completed`) for the calls, `agent_thought_chunk` and
151    /// `agent_message_chunk` for the text.
152    pub fn observe_acp(&mut self, line: &Value) -> Option<Stuck> {
153        if line.get("id").is_some() && (line.pointer("/result/stopReason").is_some() || line.get("error").is_some()) {
154            self.new_turn();
155            return None;
156        }
157        if line.get("method").and_then(Value::as_str) != Some("session/update") {
158            return None;
159        }
160        let update = line.pointer("/params/update")?;
161        match update.get("sessionUpdate").and_then(Value::as_str)? {
162            "agent_thought_chunk" => self.stream(ACP_THOUGHT, update.pointer("/content/text").and_then(Value::as_str)?),
163            "agent_message_chunk" => self.stream(ACP_MESSAGE, update.pointer("/content/text").and_then(Value::as_str)?),
164            "tool_call" => {
165                // A call is the end of the text before it.
166                self.streaming.remove(&ACP_THOUGHT);
167                self.streaming.remove(&ACP_MESSAGE);
168                self.acp_call(update)
169            }
170            "tool_call_update" => self.acp_call(update),
171            _ => None,
172        }
173    }
174
175    /// A call, or an update of one, in ACP's shape: `toolCallId`, `title`, `rawInput`, `status`.
176    fn acp_call(&mut self, update: &Value) -> Option<Stuck> {
177        let id = update.get("toolCallId").and_then(Value::as_str)?;
178        let known = self.pending.get(id).cloned();
179        // The call may name itself or fill in its input in a later update: the latest of each is the call's.
180        let title = update.get("title").and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_string);
181        let name = title.or_else(|| known.as_ref().map(|k| k.1.clone())).or_else(|| update.get("kind").and_then(Value::as_str).map(str::to_string))?;
182        let input = update.get("rawInput").filter(|i| !i.is_null() && i.as_object().map_or(true, |o| !o.is_empty())).map(Value::to_string);
183        let input = input.or_else(|| known.as_ref().and_then(|k| k.0.split_once('\u{1f}')).map(|(_, i)| i.to_string())).unwrap_or_default();
184        let key = format!("{name}\u{1f}{input}");
185        let status = update.get("status").and_then(Value::as_str);
186        if !matches!(status, Some("failed" | "completed")) {
187            self.pending.insert(id.to_string(), (key, name));
188            return None;
189        }
190        self.pending.remove(id);
191        // A repeated terminal update of a call already ended says nothing new.
192        if !self.ended.insert(id.to_string()) {
193            return None;
194        }
195        if status == Some("completed") {
196            self.failing.remove(&key);
197            return None;
198        }
199        let entry = self.failing.entry(key).or_insert((name, 0));
200        entry.1 += 1;
201        (entry.1 >= FAILING_CALLS).then(|| Stuck::FailingCall { tool: entry.0.clone(), count: entry.1 })
202    }
203
204    fn tool_results(&mut self, frame: &Value) -> Option<Stuck> {
205        let blocks = frame.pointer("/message/content")?.as_array()?;
206        let mut stuck = None;
207        for block in blocks.iter().filter(|b| b.get("type").and_then(Value::as_str) == Some("tool_result")) {
208            let Some((key, name)) = block.get("tool_use_id").and_then(Value::as_str).and_then(|id| self.pending.remove(id)) else { continue };
209            if block.get("is_error").and_then(Value::as_bool) != Some(true) {
210                // It worked this time: the run of failures of that call is over.
211                self.failing.remove(&key);
212                continue;
213            }
214            let entry = self.failing.entry(key).or_insert((name, 0));
215            entry.1 += 1;
216            if entry.1 >= FAILING_CALLS && stuck.is_none() {
217                stuck = Some(Stuck::FailingCall { tool: entry.0.clone(), count: entry.1 });
218            }
219        }
220        stuck
221    }
222}
223
224/// The same thought repeated: a normalized line (lowercase, punctuation dropped) of three characters or more
225/// repeated [`LINE_RUN`] times in a row, or an end of the text with a handful of different words over and over.
226fn repeats_itself(text: &str) -> Option<Stuck> {
227    let normal = |s: &str| s.chars().filter(|c| c.is_alphanumeric() || c.is_whitespace()).collect::<String>().to_lowercase();
228    let mut run = 0usize;
229    let mut last = String::new();
230    for line in text.lines() {
231        let line = normal(line).split_whitespace().collect::<Vec<_>>().join(" ");
232        if line.chars().count() < 3 {
233            continue;
234        }
235        if line == last {
236            run += 1;
237            if run + 1 >= LINE_RUN {
238                return Some(Stuck::SameThought);
239            }
240        } else {
241            last = line;
242            run = 0;
243        }
244    }
245    let tail: String = text.chars().rev().take(TAIL_CHARS).collect::<Vec<_>>().into_iter().rev().collect();
246    let words: Vec<String> = normal(&tail).split_whitespace().map(str::to_string).collect();
247    if words.len() >= MIN_WORDS {
248        let distinct: std::collections::HashSet<&String> = words.iter().collect();
249        if distinct.len() <= MAX_DISTINCT {
250            return Some(Stuck::SameThought);
251        }
252    }
253    None
254}
255
256#[cfg(test)]
257#[path = "loop_guard_tests.rs"]
258mod tests;