agentmux_srv_core/agents/
loop_guard.rs1use serde_json::Value;
14use std::collections::HashMap;
15
16pub const FAILING_CALLS: u32 = 5;
18const LINE_RUN: usize = 20;
20const TAIL_CHARS: usize = 4_000;
22const MIN_WORDS: usize = 60;
24const STREAM_KEEP: usize = 8_000;
26const STREAM_READ_EVERY: usize = 200;
28const MAX_DISTINCT: usize = 4;
30
31const ACP_THOUGHT: u64 = 1_000;
33const ACP_MESSAGE: u64 = 1_001;
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum Stuck {
38 FailingCall { tool: String, count: u32 },
40 SameThought,
42}
43
44impl Stuck {
45 pub fn describe(&self) -> String {
47 match self {
48 Stuck::FailingCall { tool, count } => {
49 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#[derive(Debug, Default)]
60pub struct LoopGuard {
61 pending: HashMap<String, (String, String)>,
63 failing: HashMap<String, (String, u32)>,
65 streaming: HashMap<u64, (String, usize)>,
67 ended: std::collections::HashSet<String>,
69}
70
71impl LoopGuard {
72 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 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 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 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 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 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 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 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 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 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
224fn 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;