Merge pull request 'agent: hint after 3 identical tool calls' (#162) from feat/loop-guard into main

This commit was merged in pull request #162.
This commit is contained in:
hermes committed 2026-10-15 20:37:33 +00:00
commit 846756c0bd
1 file changed
+71 -1
+71 -1
View File
@@ -62,6 +62,37 @@ impl Snap {
} }
} }
const REPEAT_HINT: &str = "\n[hx: this exact call returned the same result 3 times in a row; change approach or ask the user]";
/// Counts identical consecutive tool calls (same tool, args and result).
// ponytail: exact match only, and calls with a `timeout` arg (polling) are exempt; widen if loops vary args.
#[derive(Default)]
struct Repeat {
last: u64,
n: u32,
}
impl Repeat {
/// True from the 3rd identical call on.
fn seen(&mut self, name: &str, args: &serde_json::Value, content: &str) -> bool {
use std::hash::{Hash, Hasher};
if args.get("timeout").is_some() {
self.n = 0;
return false;
}
let mut h = std::collections::hash_map::DefaultHasher::new();
(name, args.to_string(), content).hash(&mut h);
let k = h.finish();
self.n = if self.n > 0 && k == self.last {
self.n + 1
} else {
1
};
self.last = k;
self.n >= 3
}
}
fn transient(status: u16) -> bool { fn transient(status: u16) -> bool {
matches!(status, 408 | 429 | 500 | 502 | 503 | 529) matches!(status, 408 | 429 | 500 | 502 | 503 | 529)
} }
@@ -390,6 +421,7 @@ impl Agent {
async fn run_inner(&mut self, prompt: String) -> Result<Message, Error> { async fn run_inner(&mut self, prompt: String) -> Result<Message, Error> {
self.push(Message::user(prompt))?; self.push(Message::user(prompt))?;
let mut empty_retries = 0; let mut empty_retries = 0;
let mut repeat = Repeat::default();
for _ in 0..self.max_turns { for _ in 0..self.max_turns {
if self.aborted() { if self.aborted() {
return Err(Error::Aborted); return Err(Error::Aborted);
@@ -520,8 +552,11 @@ impl Agent {
&self.cx, &self.cx,
) )
.await; .await;
for ((i, name, args), r) in runnable.into_iter().zip(outs) { for ((i, name, args), mut r) in runnable.into_iter().zip(outs) {
let id = calls[i].0.clone(); let id = calls[i].0.clone();
if repeat.seen(&name, &args, &r.content) {
r.content.push_str(REPEAT_HINT);
}
self.emit(Event::ToolResult { self.emit(Event::ToolResult {
id: id.clone(), id: id.clone(),
name, name,
@@ -845,6 +880,41 @@ mod tests {
assert_eq!(n, 1, "400 is not retried"); assert_eq!(n, 1, "400 is not retried");
} }
#[tokio::test]
async fn identical_calls_get_a_hint_on_the_third() {
let mut script: Vec<Message> = (0..4)
.map(|i| asst(vec![tu(&i.to_string(), "x")]))
.collect();
script.push(asst(vec![ContentBlock::Text { text: "fin".into() }]));
let dir = tempfile::tempdir().unwrap();
let mut tools = Registry::default();
tools.add(Echo);
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let (mut a, _h) = Agent::new(
Arc::new(Script(Mutex::new(script), Mutex::new(vec![]))),
tools,
Session::open(dir.path().join("s.jsonl")).unwrap(),
cx,
);
a.run("go").await.unwrap();
let hinted: Vec<bool> = a
.session
.messages()
.iter()
.flat_map(|m| m.content.iter())
.filter_map(|b| match b {
ContentBlock::ToolResult { content, .. } => {
Some(content.contains("same result 3 times"))
}
_ => None,
})
.collect();
assert_eq!(hinted, [false, false, true, true]);
}
#[tokio::test] #[tokio::test]
async fn abort_and_max_turns() { async fn abort_and_max_turns() {
let loop_forever = Arc::new(Script( let loop_forever = Arc::new(Script(