diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 3b97466..b90e1c2 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -72,6 +72,10 @@ pub enum Error { Aborted, #[error("stream ended without Done")] Truncated, + #[error( + "empty reply from the provider (stop: {0:?}), also on retry; try /compact or /model, or lower the effort" + )] + EmptyReply(StopReason), #[error("max turns ({0}) reached")] MaxTurns(u32), } @@ -351,6 +355,7 @@ impl Agent { async fn run_inner(&mut self, prompt: String) -> Result { self.push(Message::user(prompt))?; + let mut empty_retries = 0; for _ in 0..self.max_turns { if self.aborted() { return Err(Error::Aborted); @@ -390,6 +395,25 @@ impl Agent { } let (msg, stop, usage) = done.ok_or(Error::Truncated)?; self.usage.add(&usage); + // no text and no tool call (e.g. output_tokens 0): never store it, it would poison + // the context and every "continue" would hit the same empty reply + let useful = msg.content.iter().any(|b| match b { + ContentBlock::Text { text } => !text.trim().is_empty(), + ContentBlock::ToolUse { .. } => true, + _ => false, + }); + if !useful { + if empty_retries == 0 { + empty_retries += 1; + self.emit(Event::Info(format!( + "empty reply from the provider (stop: {stop:?}); retrying once" + ))) + .await; + continue; + } + return Err(Error::EmptyReply(stop)); + } + empty_retries = 0; let total = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens @@ -594,6 +618,34 @@ mod tests { } } + #[tokio::test] + async fn empty_reply_retries_once_and_is_not_stored() { + let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]); + let mk = |v| { + let dir = tempfile::tempdir().unwrap(); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let script = Arc::new(Script(Mutex::new(v), Mutex::new(vec![]))); + let (a, _h) = Agent::new( + script, + Registry::default(), + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + (a, dir) + }; + // empty, then text: retried, only the good reply is stored + let (mut a, _d) = mk(vec![asst(vec![]), text("ok")]); + assert_eq!(a.run("p").await.unwrap().text(), "ok"); + assert_eq!(a.session.messages().len(), 2); + // empty twice: error, nothing stored besides the prompt + let (mut a, _d) = mk(vec![asst(vec![]), asst(vec![])]); + assert!(matches!(a.run("p").await, Err(Error::EmptyReply(_)))); + assert_eq!(a.session.messages().len(), 1); + } + #[tokio::test] async fn btw_reads_snapshot_without_touching_session() { let script = Arc::new(Script(