Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

same-call-guard: a bot stops repeating a call that keeps failing the same way (15c) (#657)

Oleksandr Ivanchenkoe9f9bf32eeb6
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 1f5363cb..dc93d6db 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -1355,14 +1355,19 @@ impl ApiDriver {
.send(RuntimeEvent::ToolCallPending { id: id.to_string(), name: name.to_string(), args: shown_args })
.await;
let outcome = session.call(caller, id, name, raw_args).await;
+ let mut completed = json!({
+ "status": outcome.status,
+ "content": crate::mcp::truncate_text(&outcome.text, crate::mcp::RECORD_RESULT_MAX_CHARS),
+ });
+ // 15c: a call kwnt didn't send says so, so the failure line doesn't count it
+ if let Some(n) = outcome.record.get("repeat_stopped") {
+ completed["repeat_stopped"] = n.clone();
+ }
let _ = event_tx
.send(RuntimeEvent::ToolCallCompleted {
id: id.to_string(),
result: super::activity::with_page_title(
- json!({
- "status": outcome.status,
- "content": crate::mcp::truncate_text(&outcome.text, crate::mcp::RECORD_RESULT_MAX_CHARS),
- }),
+ completed,
name,
&outcome.text,
),
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index d82ab3be..6753eed0 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -13,6 +13,7 @@ pub mod prod_floor;
pub mod oauth_mock;
pub mod directory;
pub mod registry;
+pub mod repeat_guard;
pub mod session;
pub mod shell_risk;
diff --git a/src/mcp/repeat_guard.rs b/src/mcp/repeat_guard.rs
new file mode 100644
index 00000000..67f82b96
--- /dev/null
+++ b/src/mcp/repeat_guard.rs
@@ -0,0 +1,229 @@
+//! 15c: a turn stops sending a call that keeps failing the same way.
+//!
+//! [`McpToolSession`](super::session::McpToolSession) holds one guard per turn. After a call,
+//! [`RepeatGuard::after`] counts identical failures (same tool, same arguments, same error text);
+//! before a call, [`RepeatGuard::check`] refuses a call that already failed [`REPEAT_LIMIT`]
+//! times the same way, so the turn tries another way instead of spending its call cap on it.
+//! Successful calls (polling a status) and calls whose error changes never stop. Only `ok` and
+//! `error` outcomes count: a denied, unanswered or rehearsed call was the person's decision.
+
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+use std::sync::Mutex;
+
+/// Identical failures after which the same call is no longer sent.
+pub const REPEAT_LIMIT: u32 = 3;
+/// Calls the guard remembers per turn; the least recently failed one is dropped first.
+pub const MAX_KEYS: usize = 64;
+/// How much of the repeated error the stop text quotes.
+const QUOTE_MAX_CHARS: usize = 200;
+
+struct Entry {
+ key: [u8; 32],
+ error: String,
+ count: u32,
+}
+
+/// One turn's failing calls, oldest first. Interior mutability: calls may run concurrently.
+#[derive(Default)]
+pub struct RepeatGuard {
+ entries: Mutex<Vec<Entry>>,
+}
+
+/// What the guard says before a call.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Stopped {
+ /// The text the model gets instead of the call's result.
+ pub text: String,
+ /// How many identical failures came before ([`REPEAT_LIMIT`]).
+ pub count: u32,
+}
+
+impl RepeatGuard {
+ /// The same call is the same key: tool name plus the arguments' JSON. serde_json here has
+ /// no `preserve_order`, so object keys serialize sorted and key order doesn't matter.
+ /// Hashed, so 64 large argument objects don't stay in memory.
+ pub fn key(name: &str, arguments: &Value) -> [u8; 32] {
+ let mut h = Sha256::new();
+ h.update(name.as_bytes());
+ h.update([0u8]);
+ h.update(arguments.to_string().as_bytes());
+ h.finalize().into()
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Entry>> {
+ self.entries.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// `Some` when this call already failed [`REPEAT_LIMIT`] times in a row with the same error:
+ /// don't send it.
+ pub fn check(&self, key: &[u8; 32]) -> Option<Stopped> {
+ let entries = self.lock();
+ let e = entries.iter().find(|e| &e.key == key)?;
+ (e.count >= REPEAT_LIMIT).then(|| Stopped { text: stop_text(e.count, &e.error), count: e.count })
+ }
+
+ /// Records a call's outcome: `error` with the same (redacted) text as last time counts one
+ /// more, a different text starts again at 1, `ok` forgets the call; anything else (denied,
+ /// unanswered, rehearsed) leaves the count as it is.
+ pub fn after(&self, key: &[u8; 32], status: &str, text: &str) {
+ let mut entries = self.lock();
+ let at = entries.iter().position(|e| &e.key == key);
+ match status {
+ "ok" => {
+ if let Some(i) = at {
+ entries.remove(i);
+ }
+ }
+ "error" => {
+ let text = text.trim();
+ let mut entry = match at {
+ Some(i) => entries.remove(i),
+ None => Entry { key: *key, error: String::new(), count: 0 },
+ };
+ if entry.count > 0 && entry.error == text {
+ entry.count += 1;
+ } else {
+ entry.error = text.to_string();
+ entry.count = 1;
+ }
+ if entries.len() >= MAX_KEYS {
+ entries.remove(0);
+ }
+ entries.push(entry);
+ }
+ _ => {}
+ }
+ }
+
+ #[cfg(test)]
+ fn len(&self) -> usize {
+ self.lock().len()
+ }
+}
+
+/// What the model reads instead of a stopped call's result. No connection words of its own, so
+/// tool_failures doesn't read it as a connection failure (the quoted error may have some; a
+/// stopped call is skipped there by its `repeat_stopped` field).
+pub fn stop_text(count: u32, error: &str) -> String {
+ let error = super::truncate_text(error.trim(), QUOTE_MAX_CHARS);
+ format!(
+ "kwnt didn't send this call: the same call (same tool, same arguments) already failed {count} times in this \
+ turn with the same error: \"{error}\". Change the arguments or try another way. If only the person can fix \
+ it, end your reply with \"Blocked: <what is blocked>. <what would unblock it>\"."
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn fail(g: &RepeatGuard, k: &[u8; 32], times: u32, error: &str) {
+ for _ in 0..times {
+ assert!(g.check(k).is_none(), "stopped too early");
+ g.after(k, "error", error);
+ }
+ }
+
+ #[test]
+ fn three_same_failures_stop_the_fourth() {
+ let g = RepeatGuard::default();
+ let k = RepeatGuard::key("mcp__gh__create_issue", &json!({"repo": "a/b", "title": "x"}));
+ fail(&g, &k, 3, "422 Validation Failed: title too short");
+ let s = g.check(&k).expect("4th call stopped");
+ assert_eq!(s.count, 3);
+ assert!(s.text.starts_with("kwnt didn't send this call: the same call (same tool, same arguments) already failed 3 times"));
+ assert!(s.text.contains("\"422 Validation Failed: title too short\""));
+ assert!(s.text.ends_with("end your reply with \"Blocked: <what is blocked>. <what would unblock it>\"."));
+ // Still stopped on a 5th try: the stop itself isn't recorded as a new outcome
+ assert!(g.check(&k).is_some());
+ }
+
+ #[test]
+ fn a_different_error_text_starts_again() {
+ let g = RepeatGuard::default();
+ let k = RepeatGuard::key("mcp__a__b", &json!({}));
+ fail(&g, &k, 2, "boom");
+ g.after(&k, "error", "boom, but different");
+ assert!(g.check(&k).is_none());
+ g.after(&k, "error", "boom, but different");
+ assert!(g.check(&k).is_none());
+ g.after(&k, "error", "boom, but different");
+ assert!(g.check(&k).is_some());
+ }
+
+ #[test]
+ fn an_ok_forgets_the_call() {
+ let g = RepeatGuard::default();
+ let k = RepeatGuard::key("mcp__a__status", &json!({"id": 7}));
+ fail(&g, &k, 2, "not ready");
+ g.after(&k, "ok", "ready");
+ fail(&g, &k, 2, "not ready");
+ assert!(g.check(&k).is_none());
+ // Polling that keeps working never stops
+ for _ in 0..20 {
+ g.after(&k, "ok", "running");
+ }
+ assert!(g.check(&k).is_none());
+ }
+
+ #[test]
+ fn different_arguments_are_a_different_call() {
+ let g = RepeatGuard::default();
+ let a = RepeatGuard::key("mcp__a__get", &json!({"id": 1}));
+ let b = RepeatGuard::key("mcp__a__get", &json!({"id": 2}));
+ let c = RepeatGuard::key("mcp__a__other", &json!({"id": 1}));
+ fail(&g, &a, 3, "not found");
+ assert!(g.check(&a).is_some());
+ assert!(g.check(&b).is_none());
+ assert!(g.check(&c).is_none());
+ }
+
+ #[test]
+ fn key_order_in_arguments_does_not_matter() {
+ let x: Value = serde_json::from_str(r#"{"b": 1, "a": {"y": 2, "x": 3}}"#).unwrap();
+ let y: Value = serde_json::from_str(r#"{"a": {"x": 3, "y": 2}, "b": 1}"#).unwrap();
+ assert_eq!(RepeatGuard::key("t", &x), RepeatGuard::key("t", &y));
+ assert_ne!(RepeatGuard::key("t", &x), RepeatGuard::key("u", &x));
+ }
+
+ #[test]
+ fn denied_unanswered_and_rehearsed_do_not_count() {
+ let g = RepeatGuard::default();
+ let k = RepeatGuard::key("mcp__a__b", &json!({}));
+ for status in ["denied", "unanswered", "rehearsed", "denied", "denied"] {
+ g.after(&k, status, "The person declined this tool call.");
+ }
+ assert!(g.check(&k).is_none());
+ // and don't reset a count either
+ fail(&g, &k, 2, "boom");
+ g.after(&k, "denied", "no");
+ g.after(&k, "error", "boom");
+ assert!(g.check(&k).is_some());
+ }
+
+ #[test]
+ fn at_most_64_calls_are_remembered_oldest_dropped() {
+ let g = RepeatGuard::default();
+ let keys: Vec<_> = (0..65).map(|i| RepeatGuard::key("mcp__a__b", &json!({ "i": i }))).collect();
+ fail(&g, &keys[0], 3, "boom");
+ for k in &keys[1..] {
+ g.after(k, "error", "boom");
+ }
+ assert_eq!(g.len(), MAX_KEYS);
+ // The oldest one was dropped, so it is no longer stopped
+ assert!(g.check(&keys[0]).is_none());
+ fail(&g, &keys[64], 2, "boom");
+ assert!(g.check(&keys[64]).is_some());
+ assert_eq!(g.len(), MAX_KEYS);
+ }
+
+ #[test]
+ fn a_long_error_is_cut_to_200_characters() {
+ let long = "e".repeat(500);
+ let t = stop_text(3, &long);
+ assert!(t.contains(&format!("\"{}… [truncated]\"", "e".repeat(200))));
+ assert!(!t.contains(&"e".repeat(201)));
+ }
+}
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
index 95601981..2a012f47 100644
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@ -87,6 +87,8 @@ pub struct McpToolSession {
clients: Vec<(String, McpClient)>,
tools: Vec<OfferedTool>,
secrets: Vec<String>,
+ /// 15c: this turn's identical failing calls (one session per turn).
+ repeats: super::repeat_guard::RepeatGuard,
}
/// The outcome of one call, already redacted; `text` goes back to the model.
@@ -102,7 +104,7 @@ impl McpToolSession {
/// (redacted) errors are returned so the user can be told.
pub async fn open(ctx: &McpTurnContext, cwd: Option<&Path>) -> (Self, Vec<String>) {
let secrets = ctx.secret_values();
- let mut session = Self { ctx: ctx.clone(), clients: Vec::new(), tools: Vec::new(), secrets };
+ let mut session = Self { ctx: ctx.clone(), clients: Vec::new(), tools: Vec::new(), secrets, repeats: Default::default() };
let mut problems = Vec::new();
let connections = ctx.servers.iter().map(|s| async move {
let client = McpClient::connect(s, cwd).await?;
@@ -231,6 +233,24 @@ impl McpToolSession {
Err(_) => Value::String(raw_arguments.to_string()),
}
};
+ // 15c: the same call that already failed 3 times the same way isn't sent (no card either)
+ let repeat_key = super::repeat_guard::RepeatGuard::key(name, &arguments);
+ if let Some(stopped) = self.repeats.check(&repeat_key) {
+ let (server, tool) = super::split_tool_name(name).unwrap_or(("", name));
+ let record = json!({
+ "id": call_id,
+ "name": name,
+ "server": server,
+ "tool": tool,
+ "arguments": arguments,
+ "status": "error",
+ "duration_ms": start.elapsed().as_millis() as u64,
+ "result": truncate_text(&stopped.text, RECORD_RESULT_MAX_CHARS),
+ "repeat_stopped": stopped.count,
+ });
+ self.ctx.record(record.clone());
+ return CallOutcome { text: stopped.text, status: "error", record };
+ }
let offered = self.tools.iter().find(|t| t.name == name);
let (status, text) = match offered {
None => ("error", format!("Unknown tool {name}.")),
@@ -274,6 +294,7 @@ impl McpToolSession {
}
};
let text = redact(&text, &self.secrets);
+ self.repeats.after(&repeat_key, status, &text);
let (server, tool) = super::split_tool_name(name).unwrap_or(("", name));
let mut record = json!({
"id": call_id,
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index a9907ade..4162ff34 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -1420,7 +1420,9 @@ async fn gateway_rpc(
}
};
// The chat's failure line (0.9.5): codex and grok calls are reported here, by their real server
- if let Some(w) = super::tool_failures::TurnWatch::find(&session.turn_id) {
+ // A call the repeat guard (15c) didn't send isn't new news about the connection
+ let sent = outcome.record.get("repeat_stopped").is_none();
+ if let Some(w) = super::tool_failures::TurnWatch::find(&session.turn_id).filter(|_| sent) {
match outcome.status {
"ok" => w.call_done(&tool_name, &arguments, None).await,
"error" => w.call_done(&tool_name, &arguments, Some(&outcome.text)).await,
diff --git a/src/server/tool_failures.rs b/src/server/tool_failures.rs
index 78e130b6..9d1b1a2a 100644
--- a/src/server/tool_failures.rs
+++ b/src/server/tool_failures.rs
@@ -267,6 +267,14 @@ pub fn cause_of(conn: &Connection, why: &str) -> Option<Cause> {
None
}
+/// Whether a finished call's result can say anything about its connection. A card the person
+/// declined, or a call the turn's end cut off, isn't the connection's; nor is a call the repeat
+/// guard (15c) didn't send, whose earlier failures were already counted.
+pub fn about_the_connection(result: &Value) -> bool {
+ let status = result["status"].as_str().unwrap_or("");
+ !matches!(status, "denied" | "cancelled" | "unanswered") && result.get("repeat_stopped").is_none()
+}
+
/// A failed call → the connection failure it is, if any.
pub fn classify(name: &str, args: &Value, why: &str, servers: &[Server]) -> Option<Failure> {
let conn = connection_of(name, args, servers)?;
@@ -546,9 +554,7 @@ impl TurnWatch {
let Some((name, args)) = self.lock().calls.remove(id) else {
return;
};
- let status = result["status"].as_str().unwrap_or("");
- // A card the person declined, or a call the turn's end cut off, isn't the connection's
- if matches!(status, "denied" | "cancelled" | "unanswered") {
+ if !about_the_connection(result) {
return;
}
let why = crate::drivers::activity::failed_reason(result);
diff --git a/src/server/tool_failures/tests.rs b/src/server/tool_failures/tests.rs
index 305735f5..49a3d19e 100644
--- a/src/server/tool_failures/tests.rs
+++ b/src/server/tool_failures/tests.rs
@@ -54,6 +54,26 @@ fn a_tools_own_error_is_not_a_connection_failure() {
assert!(classify("mcp__unknown__x", &json!({}), "401", &servers()).is_none());
}
+/// 15c: the repeat guard's stop text has no connection words of its own, and a stopped call is
+/// skipped before classifying (its quoted error may have some).
+#[test]
+fn a_repeat_stop_is_not_a_connection_failure() {
+ let stop = crate::mcp::repeat_guard::stop_text(3, "invalid arguments: repo is required");
+ for name in ["mcp__github__get_repo", "mcp__composio__GITHUB_GET_REPO", "mcp__kwnt__kwnt_fetch"] {
+ assert!(classify(name, &json!({}), &stop, &servers()).is_none(), "{name}");
+ }
+ let conn = Connection { key: "kwnt".into(), label: "kwant's own tools".into(), server_id: None };
+ assert_eq!(cause_of(&conn, &stop), None);
+ // A stopped 401 would read as a sign-in, so it never gets that far
+ let stopped_401 = json!({"status": "error", "content": crate::mcp::repeat_guard::stop_text(3, "401 Unauthorized"), "repeat_stopped": 3});
+ assert!(!about_the_connection(&stopped_401));
+ assert!(about_the_connection(&json!({"status": "error", "content": "401 Unauthorized"})));
+ assert!(about_the_connection(&json!({"status": "ok"})));
+ for status in ["denied", "cancelled", "unanswered"] {
+ assert!(!about_the_connection(&json!({ "status": status })), "{status}");
+ }
+}
+
/// A Composio app that lost its account needs connecting again, keyed by the app, not the server.
#[test]
fn composio_failures_are_per_app_and_need_a_reconnect() {
diff --git a/tests/repeat_guard_test.rs b/tests/repeat_guard_test.rs
new file mode 100644
index 00000000..1890c83d
--- /dev/null
+++ b/tests/repeat_guard_test.rs
@@ -0,0 +1,308 @@
+//! 15c: a turn stops sending a call that keeps failing the same way. A fake http MCP server
+//! whose `fail` tool always errors counts the calls that reach it; a mock OpenAI endpoint plays
+//! the model. No network beyond 127.0.0.1 and no API keys.
+
+use async_trait::async_trait;
+use axum::{extract::State, routing::post, Json, Router};
+use kwnt::{
+ db::models::{Kwant, McpServer},
+ drivers::{events::RuntimeEvent, ApiDriver, Driver, TurnInput},
+ mcp::{session::Caller, session::McpToolSession, McpTurnContext, ToolApprovalRequest, ToolApprover},
+};
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+const FAIL_TEXT: &str = "invalid_request: the board 'roadmap' does not exist";
+
+/// `tools/call` hits per tool name.
+#[derive(Clone, Default)]
+struct Hits(Arc<Mutex<BTreeMap<String, usize>>>);
+
+impl Hits {
+ fn of(&self, tool: &str) -> usize {
+ self.0.lock().unwrap().get(tool).copied().unwrap_or(0)
+ }
+}
+
+/// An http MCP server with `fail` (always the same error), `flaky` (a new error each time) and
+/// `status` (always works).
+async fn fake_mcp() -> (String, Hits) {
+ async fn mcp(State(hits): State<Hits>, Json(msg): Json<Value>) -> axum::response::Response {
+ use axum::response::IntoResponse;
+ let id = msg["id"].clone();
+ let tool = |name: &str| json!({"name": name, "inputSchema": {"type": "object", "properties": {"board": {"type": "string"}}}});
+ let result = match msg["method"].as_str().unwrap_or("") {
+ "initialize" => json!({"protocolVersion": "2025-06-18", "capabilities": {"tools": {}},
+ "serverInfo": {"name": "fake-fail", "version": "1.0.0"}}),
+ "tools/list" => json!({"tools": [tool("fail"), tool("flaky"), tool("status")]}),
+ "tools/call" => {
+ let name = msg["params"]["name"].as_str().unwrap_or("").to_string();
+ let n = {
+ let mut h = hits.0.lock().unwrap();
+ let n = h.entry(name.clone()).or_default();
+ *n += 1;
+ *n
+ };
+ match name.as_str() {
+ "fail" => json!({"content": [{"type": "text", "text": FAIL_TEXT}], "isError": true}),
+ "flaky" => json!({"content": [{"type": "text", "text": format!("attempt {n} failed")}], "isError": true}),
+ _ => json!({"content": [{"type": "text", "text": "running"}]}),
+ }
+ }
+ _ => return axum::http::StatusCode::ACCEPTED.into_response(),
+ };
+ Json(json!({"jsonrpc": "2.0", "id": id, "result": result})).into_response()
+ }
+ let hits = Hits::default();
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let app = Router::new().route("/mcp", post(mcp)).with_state(hits.clone());
+ tokio::spawn(async move { axum::serve(listener, app).await });
+ (format!("{base}/mcp"), hits)
+}
+
+/// Allows (or denies) every call and counts the cards it was asked.
+struct Counting {
+ allow: AtomicBool,
+ cards: AtomicUsize,
+}
+
+#[async_trait]
+impl ToolApprover for Counting {
+ async fn approve(&self, _request: ToolApprovalRequest) -> bool {
+ self.cards.fetch_add(1, Ordering::SeqCst);
+ self.allow.load(Ordering::SeqCst)
+ }
+}
+
+fn ctx(url: &str, approver: Arc<dyn ToolApprover>, max: usize) -> McpTurnContext {
+ McpTurnContext {
+ servers: vec![McpServer {
+ id: "s-board".into(),
+ name: "board".into(),
+ transport: "http".into(),
+ command: None,
+ args: vec![],
+ url: Some(url.to_string()),
+ env: BTreeMap::new(),
+ headers: BTreeMap::new(),
+ enabled: true,
+ timeout_secs: 10,
+ created_at: None,
+ }],
+ approver,
+ config_dir: std::env::temp_dir(),
+ permission_url: None,
+ gateway: None,
+ max_tool_iterations: max,
+ approvals: kwnt::mcp::Approvals::Ask,
+ records: Default::default(),
+ kwnt_only: false,
+ }
+}
+
+fn caller() -> Caller {
+ Caller { kwant_id: "k1".into(), kwant_name: "Ada".into(), turn_id: "t1".into() }
+}
+
+fn counting(allow: bool) -> Arc<Counting> {
+ Arc::new(Counting { allow: AtomicBool::new(allow), cards: AtomicUsize::new(0) })
+}
+
+/// The 4th identical failing call never reaches the server, nor asks a card; the record says so.
+#[tokio::test]
+async fn the_fourth_identical_failure_is_not_sent() {
+ let (url, hits) = fake_mcp().await;
+ let approver = counting(true);
+ let c = ctx(&url, approver.clone(), 8);
+ let (session, problems) = McpToolSession::open(&c, None).await;
+ assert!(problems.is_empty(), "{problems:?}");
+ // Key order doesn't matter: these are the same call
+ let args = [r#"{"board": "roadmap", "limit": 5}"#, r#"{"limit": 5, "board": "roadmap"}"#];
+ for i in 0..3 {
+ let o = session.call(&caller(), &format!("c{i}"), "mcp__board__fail", args[i % 2]).await;
+ assert_eq!((o.status, o.text.as_str()), ("error", FAIL_TEXT));
+ assert!(o.record.get("repeat_stopped").is_none());
+ }
+ assert_eq!(hits.of("fail"), 3);
+ assert_eq!(approver.cards.load(Ordering::SeqCst), 3);
+ for i in 3..5 {
+ let o = session.call(&caller(), &format!("c{i}"), "mcp__board__fail", args[i % 2]).await;
+ assert_eq!(o.status, "error");
+ assert!(o.text.starts_with("kwnt didn't send this call: the same call (same tool, same arguments) already failed 3 times in this turn"), "{}", o.text);
+ assert!(o.text.contains(&format!("\"{FAIL_TEXT}\"")), "{}", o.text);
+ assert!(o.text.contains("Blocked: <what is blocked>. <what would unblock it>"));
+ assert_eq!(o.record["repeat_stopped"], 3);
+ assert_eq!(o.record["name"], "mcp__board__fail");
+ }
+ assert_eq!(hits.of("fail"), 3, "the 4th and 5th calls never reached the server");
+ assert_eq!(approver.cards.load(Ordering::SeqCst), 3, "and asked no card");
+ // Other arguments are another call
+ let o = session.call(&caller(), "d1", "mcp__board__fail", r#"{"board": "backlog"}"#).await;
+ assert_eq!(o.text, FAIL_TEXT);
+ assert_eq!(hits.of("fail"), 4);
+ // The trail has every call, the stopped ones included
+ let records = c.take_records();
+ assert_eq!(records.len(), 6);
+ assert_eq!(records.iter().filter(|r| r.get("repeat_stopped").is_some()).count(), 2);
+ session.shutdown().await;
+}
+
+/// Polling that works, and failures whose text changes, are never stopped; denied calls don't count.
+#[tokio::test]
+async fn working_polls_changing_errors_and_denials_are_not_stopped() {
+ let (url, hits) = fake_mcp().await;
+ let approver = counting(false);
+ let c = ctx(&url, approver.clone(), 8);
+ let (session, _) = McpToolSession::open(&c, None).await;
+ for i in 0..5 {
+ let o = session.call(&caller(), &format!("d{i}"), "mcp__board__fail", r#"{"board": "roadmap"}"#).await;
+ assert_eq!(o.status, "denied");
+ }
+ assert_eq!(approver.cards.load(Ordering::SeqCst), 5, "every denied call still asked");
+ approver.allow.store(true, Ordering::SeqCst);
+ for i in 0..6 {
+ let o = session.call(&caller(), &format!("s{i}"), "mcp__board__status", r#"{"board": "roadmap"}"#).await;
+ assert_eq!((o.status, o.text.as_str()), ("ok", "running"));
+ let o = session.call(&caller(), &format!("f{i}"), "mcp__board__flaky", r#"{"board": "roadmap"}"#).await;
+ assert_eq!(o.text, format!("attempt {} failed", i + 1));
+ }
+ assert_eq!((hits.of("status"), hits.of("flaky")), (6, 6));
+ // After 5 denials the person allows: the call runs 3 times before it is stopped
+ for _ in 0..4 {
+ session.call(&caller(), "x", "mcp__board__fail", r#"{"board": "roadmap"}"#).await;
+ }
+ assert_eq!(hits.of("fail"), 3);
+ session.shutdown().await;
+}
+
+// ---- One API-engine turn with a stub model (no paid call) ----
+
+#[derive(Clone, Default)]
+struct Mock {
+ replies: Arc<Vec<Value>>,
+ requests: Arc<Mutex<Vec<Value>>>,
+}
+
+async fn completions(State(mock): State<Mock>, Json(body): Json<Value>) -> Json<Value> {
+ let n = {
+ let mut r = mock.requests.lock().unwrap();
+ r.push(body);
+ r.len()
+ };
+ Json(mock.replies[(n - 1).min(mock.replies.len() - 1)].clone())
+}
+
+fn tool_call(id: &str, name: &str, args: Value) -> Value {
+ json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [
+ {"id": id, "type": "function", "function": {"name": name, "arguments": args.to_string()}}]}}],
+ "usage": {"total_tokens": 10}})
+}
+
+fn input(mcp: McpTurnContext) -> TurnInput {
+ TurnInput {
+ fresh_eyes: false,
+ expects: String::new(),
+ continuity: String::new(),
+ skills: String::new(),
+ person: Default::default(),
+ store: None,
+ browser_api_url: None,
+ thread_id: "t1".into(),
+ kwant: Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
+ id: "k1".into(),
+ name: "Ada".into(),
+ title: "Lead".into(),
+ persona_prompt: "p".into(),
+ soul: String::new(),
+ avatar_sprite: "s".into(),
+ driver_type: "api".into(),
+ preferred_model: "mock-model".into(),
+ temperature: 0.2,
+ max_tokens: 256,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ },
+ prompt: "add a card to the roadmap board".into(),
+ history: vec![],
+ model_override: None,
+ model: None,
+ effort_level: Some("low".into()),
+ team_context: None,
+ workspace_dir: None,
+ sandbox_id: None,
+ teammates: vec![],
+ mcp: Some(mcp),
+ no_tools: false,
+ read_only: false,
+ delivery: None,
+ }
+}
+
+/// A stub model that would retry forever: the guard answers its 4th try, and the model (scripted
+/// as a well-behaved one would) ends with a Blocked line instead of spending the turn's cap.
+#[tokio::test]
+async fn an_api_turn_hits_the_guard_and_ends_blocked() {
+ let (mcp_url, hits) = fake_mcp().await;
+ let call = || tool_call("c", "mcp__board__fail", json!({"board": "roadmap"}));
+ let blocked = "I couldn't add the card: the roadmap board doesn't exist on this server.\n\n\
+ Blocked: the \"roadmap\" board is missing. Create it, or tell me which board to use.";
+ let replies = vec![
+ call(),
+ call(),
+ call(),
+ call(),
+ json!({"choices": [{"message": {"role": "assistant", "content": blocked}}], "usage": {"total_tokens": 7}}),
+ ];
+ let mock = Mock { replies: Arc::new(replies), ..Default::default() };
+ let app = Router::new().route("/v1/chat/completions", post(completions)).with_state(mock.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/v1/chat/completions", listener.local_addr().unwrap());
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let c = ctx(&mcp_url, counting(true), 12);
+ let driver = ApiDriver::new(Some("test-key-not-real".into()), Some(url));
+ let (tx, mut rx) = tokio::sync::mpsc::channel(256);
+ let events = tokio::spawn(async move {
+ let mut events = Vec::new();
+ while let Some(e) = rx.recv().await {
+ events.push(e);
+ }
+ events
+ });
+ let out = driver.stream_turn(input(c.clone()), tx).await.unwrap();
+ let events = events.await.unwrap();
+
+ assert_eq!(hits.of("fail"), 3, "the 4th try never reached the server");
+ let requests = mock.requests.lock().unwrap().clone();
+ assert_eq!(requests.len(), 5, "4 tool rounds and the answer, not the cap of 12");
+ let told = requests[4]["messages"].as_array().unwrap().iter().rev().find(|m| m["role"] == "tool").unwrap()["content"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ assert!(told.starts_with("kwnt didn't send this call"), "{told}");
+ assert_eq!(out.text, blocked);
+ // The chat's activity marks the stopped call, so the failure line skips it
+ let stopped: Vec<_> = events
+ .iter()
+ .filter_map(|e| match e {
+ RuntimeEvent::ToolCallCompleted { result, .. } if result.get("repeat_stopped").is_some() => Some(result.clone()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(stopped.len(), 1);
+ assert_eq!(stopped[0]["status"], "error");
+ let records = c.take_records();
+ assert_eq!(records.len(), 4);
+ assert_eq!(records[3]["repeat_stopped"], 3);
+ // The replay quoted in impl.md
+ println!("--- replay ---");
+ for (i, r) in records.iter().enumerate() {
+ println!("call {}: {} {} -> {}: {}", i + 1, r["name"], r["arguments"], r["status"], r["result"].as_str().unwrap_or(""));
+ }
+ println!("model's reply:\n{}", out.text);
+}