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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
kwnt-tools-repeat-guard: on the claude engine, kwant's own tools stop repeating a call that keeps failing (18a) (#671)
Oleksandr Ivanchenko270f35b567cd
diff --git a/src/mcp/repeat_guard.rs b/src/mcp/repeat_guard.rsindex 67f82b96..0f3d3e8e 100644--- a/src/mcp/repeat_guard.rs+++ b/src/mcp/repeat_guard.rs@@ -30,6 +30,13 @@ pub struct RepeatGuard {entries: Mutex<Vec<Entry>>,}+/// 18a: `SelfScope` derives `Debug`; the entries hold hashes and error texts, so only their count shows.+impl std::fmt::Debug for RepeatGuard {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("RepeatGuard").field("entries", &self.lock().len()).finish()+ }+}+/// What the guard says before a call.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Stopped {@@ -102,13 +109,22 @@ impl RepeatGuard {}}+/// How every stop text starts. A result that carries it is a call the guard didn't send (18a: the+/// claude CLI's results reach tool_failures as plain text, without a `repeat_stopped` field).+pub const STOP_PREFIX: &str = "kwnt didn't send this call: the same call (same tool, same arguments)";++/// Whether a call's result text is the guard's stop text.+pub fn is_stop_text(text: &str) -> bool {+ text.contains(STOP_PREFIX)+}+/// 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 \+ "{STOP_PREFIX} 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>\".")@@ -140,6 +156,19 @@ mod tests {assert!(g.check(&k).is_some());}+ #[test]+ fn the_stop_text_is_recognised_and_debug_shows_only_a_count() {+ let g = RepeatGuard::default();+ let k = RepeatGuard::key("browser_open", &json!({"url": "https://x.test"}));+ fail(&g, &k, 3, "secret-looking error: connection closed");+ let s = g.check(&k).unwrap();+ assert!(s.text.starts_with(STOP_PREFIX));+ assert!(is_stop_text(&s.text));+ assert!(is_stop_text(&format!("Error: {}", s.text)), "a wrapper in front still reads as a stop");+ assert!(!is_stop_text("secret-looking error: connection closed"));+ assert_eq!(format!("{g:?}"), "RepeatGuard { entries: 1 }");+ }+#[test]fn a_different_error_text_starts_again() {let g = RepeatGuard::default();diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 072b8185..1ef21098 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -405,6 +405,10 @@ pub struct SelfScope {/// The bot browser shown in this turn's side panel (team, channel or kwant id). The/// `browser_*` tools are offered only when it is set and only ever drive this one.pub sandbox_target: Option<String>,+ /// 18a: the turn's repeat guard for its own tools. The claude CLI posts them straight to+ /// [`self_endpoint`], past `McpToolSession::call`'s guard; every clone of this turn's scope+ /// shares this one, and it goes when `finish_turn` drops the scope.+ pub repeats: Arc<crate::mcp::repeat_guard::RepeatGuard>,}/// Where a turn runs, for the delegation tools: results go back to this chat.@@ -1173,6 +1177,15 @@ fn tool_text(id: Value, text: impl Into<String>, is_error: bool) -> Response {)}+/// A tool result's text parts, joined: what the repeat guard compares (an image part has none).+fn content_text(content: &Value) -> String {+ match content {+ Value::String(s) => s.clone(),+ Value::Array(parts) => parts.iter().filter_map(|p| p["text"].as_str()).collect::<Vec<_>>().join("\n"),+ _ => String::new(),+ }+}+fn bearer(headers: &HeaderMap) -> Option<&str> {let value = headers.get(AUTHORIZATION)?.to_str().ok()?;let (scheme, token) = value.split_once(' ')?;@@ -1269,16 +1282,23 @@ pub async fn self_endpoint(};return tool_text(id, text, is_error);}- if name == "read_attachment" && scope.origin.is_some() {- let (content, is_error) = super::attachments::tool_read(&state, &scope, args).await;- return rpc_result(id, json!({"content": content, "isError": is_error}));+ // 18a: after the refusal gates (a refused call isn't a failed one, and is never counted),+ // the same call that already failed 3 times the same way in this turn doesn't run+ let repeat_key = crate::mcp::repeat_guard::RepeatGuard::key(name, args);+ if let Some(stopped) = scope.repeats.check(&repeat_key) {+ tracing::info!(kwant = %scope.kwant_id, tool = %name, count = stopped.count, "repeat guard: didn't run an own-tool call that kept failing the same way");+ return tool_text(id, stopped.text, true);}- if name == BROWSER_SCREENSHOT {- let (content, is_error) = browser_screenshot_tool(&state, &scope, args).await;- return rpc_result(id, json!({"content": content, "isError": is_error}));- }- let (text, is_error) = call_tool(&state, &scope, name, args).await;- tool_text(id, text, is_error)+ let (content, is_error) = if name == "read_attachment" && scope.origin.is_some() {+ super::attachments::tool_read(&state, &scope, args).await+ } else if name == BROWSER_SCREENSHOT {+ browser_screenshot_tool(&state, &scope, args).await+ } else {+ let (text, is_error) = call_tool(&state, &scope, name, args).await;+ (json!([{"type": "text", "text": text}]), is_error)+ };+ scope.repeats.after(&repeat_key, if is_error { "error" } else { "ok" }, &content_text(&content));+ rpc_result(id, json!({"content": content, "isError": is_error}))}_ => Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "method not found"}})).into_response(),}@@ -2325,6 +2345,7 @@ mod tests {turn_id: Some("turn".into()),workspace: None,sandbox_target: browser.then(|| "t".into()),+ repeats: Default::default(),}}diff --git a/src/server/human_steps.rs b/src/server/human_steps.rsindex 0c760125..8979318e 100644--- a/src/server/human_steps.rs+++ b/src/server/human_steps.rs@@ -937,6 +937,7 @@ mod tests {turn_id: Some(format!("turn-{kwant}")),workspace: None,sandbox_target: Some("team".into()),+ repeats: Default::default(),}}diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 4162ff34..def9a791 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -1048,7 +1048,9 @@ pub async fn prepare_turn_with_opts(};let session = PermissionSession::new(kwant.id.clone(), kwant.name.clone(), turn_id, ctx.clone(), cwd);state.mcp_sessions.lock().await.insert(token.clone(), session);- if let (true, Some(scope)) = (self_tools, self_scope) {+ if let (true, Some(mut scope)) = (self_tools, self_scope) {+ // 18a: one repeat guard per turn token, fresh even when the caller's scope was cloned before+ scope.repeats = Default::default();state.self_tools.lock().await.insert(token.clone(), scope);}Some((ctx, token))diff --git a/src/server/routes.rs b/src/server/routes.rsindex ebeac127..90682f76 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3013,6 +3013,7 @@ async fn run_kwant_turn_inner(turn_id: Some(tag.turn_id.clone()),workspace: workspace_dir.clone(),sandbox_target: Some(sandbox_target.clone()),+ repeats: Default::default(),};// A replay works in its own scratch browser and asks nobodylet _turn_on_browser = opts.rehearse.is_none().then(|| state.human_steps.track_turn(&sandbox_target, turn_scope.clone()));diff --git a/src/server/tool_failures.rs b/src/server/tool_failures.rsindex 9d1b1a2a..5db095f9 100644--- a/src/server/tool_failures.rs+++ b/src/server/tool_failures.rs@@ -272,7 +272,11 @@ pub fn cause_of(conn: &Connection, why: &str) -> Option<Cause> {/// 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()+ if matches!(status, "denied" | "cancelled" | "unanswered") || result.get("repeat_stopped").is_some() {+ return false;+ }+ // 18a: the claude CLI's result of a stopped own-tool call is just its text+ !crate::drivers::activity::failed_reason(result).flatten().is_some_and(crate::mcp::repeat_guard::is_stop_text)}/// A failed call → the connection failure it is, if any.diff --git a/src/server/tool_failures/tests.rs b/src/server/tool_failures/tests.rsindex 49a3d19e..bfcbed9c 100644--- a/src/server/tool_failures/tests.rs+++ b/src/server/tool_failures/tests.rs@@ -74,6 +74,20 @@ fn a_repeat_stop_is_not_a_connection_failure() {}}+/// 18a: on the claude CLI, a stopped own-tool call comes back as plain error text (no+/// `repeat_stopped`), and its quoted error can be one kwnt's own tools count as a failure.+#[test]+fn a_cli_repeat_stop_is_not_a_connection_failure() {+ let conn = connection_of("mcp__kwnt_tools__browser_open", &json!({}), &servers()).unwrap();+ assert_eq!(conn.key, "kwnt");+ let stop = crate::mcp::repeat_guard::stop_text(3, "connection closed");+ // Read alone, the quoted error would count as kwnt's tools going down+ assert_eq!(cause_of(&conn, &stop), Some(Cause::Down));+ // ...so the result is skipped first, as the CLI driver shapes it+ assert!(!about_the_connection(&json!({"status": "error", "error": stop})));+ assert!(about_the_connection(&json!({"status": "error", "error": "connection closed"})));+}+/// 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/self_repeat_guard_test.rs b/tests/self_repeat_guard_test.rsnew file mode 100644index 00000000..0e6513e0--- /dev/null+++ b/tests/self_repeat_guard_test.rs@@ -0,0 +1,199 @@+//! 18a: on the claude engine, kwant's own tools stop repeating a call that keeps failing. The+//! claude CLI posts `mcp__kwnt_tools__*` calls straight to `/api/mcp/self`, past+//! `McpToolSession::call`'s guard (15c), so the endpoint keeps one guard per turn token.+//!+//! The failing tool is `skill_get` for a skill that is turned off: "You have no enabled skill+//! called …" every time. Turning the skill on between calls makes the same call work, so a call+//! that answers with the stop text after that provably didn't run.++mod common;++use axum::http::StatusCode;+use common::*;+use kwnt::db::skills::clean_skill_text;+use kwnt::db::spaces::SpaceId;+use kwnt::mcp::repeat_guard::{RepeatGuard, STOP_PREFIX};+use kwnt::mcp::session::{Caller, McpToolSession};+use kwnt::server::continuity::{SelfScope, TurnOrigin};+use kwnt::server::{fresh_eyes, mcp_runtime};+use serde_json::{json, Value};++const SKILL: &str = "deploy-notes";+const OFF_TEXT: &str = "You have no enabled skill called deploy-notes.";++/// A `tools/call` to kwant's own tools, as the claude CLI sends it: (text, isError).+async fn call_tool(env: &Env, token: &str, name: &str, args: Value) -> (String, bool) {+ let (s, v) = call_with(+ &env.app,+ "POST",+ "/api/mcp/self",+ Some(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}})),+ &[("authorization", &format!("Bearer {token}"))],+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let r = &v["result"];+ let text = r["content"].as_array().unwrap().iter().filter_map(|c| c["text"].as_str()).collect::<Vec<_>>().join("\n");+ (text, r["isError"].as_bool().unwrap())+}++async fn get_skill(env: &Env, token: &str) -> (String, bool) {+ call_tool(env, token, "skill_get", json!({"name": SKILL})).await+}++/// A live turn for `kwant`, opened the way a chat turn opens it; returns its token.+async fn open_turn(env: &Env, kwant: &str, turn_id: &str, opts: mcp_runtime::TurnApprovalOpts) -> String {+ let k = env.state.db.get_kwant(kwant).await.unwrap().unwrap();+ let scope = SelfScope {+ kwant_id: k.id.clone(),+ kwant_name: k.name.clone(),+ origin: Some(TurnOrigin { direct_kwant_id: Some(k.id.clone()), ..Default::default() }),+ turn_id: Some(turn_id.into()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_opts(&env.state, &k, Some(turn_id.into()), None, Some(scope), opts).await.unwrap().1+}++/// A shared skill, turned off; returns its id.+async fn skill_off(env: &Env) -> String {+ let s = env+ .state+ .db+ .create_user_skill(&SpaceId::default_space(), None, clean_skill_text(SKILL, "How we deploy", "Run the checks first.").unwrap())+ .await+ .unwrap();+ env.state.db.set_skill_status(&s.id, "disabled").await.unwrap();+ s.id+}++async fn set_skill(env: &Env, id: &str, on: bool) {+ env.state.db.set_skill_status(id, if on { "enabled" } else { "disabled" }).await.unwrap();+}++fn is_stop(text: &str) -> bool {+ text.starts_with(STOP_PREFIX)+}++/// Calls 1–3 run; the 4th (and 5th) answer the stop text with isError and don't run, even though+/// the call would now work. Other arguments still run, and another turn has its own count.+#[tokio::test]+async fn the_fourth_identical_failure_does_not_run() {+ let env = setup().await;+ let skill = skill_off(&env).await;+ let tok = open_turn(&env, &env.a, "turn-a", Default::default()).await;+ for i in 1..=3 {+ assert_eq!(get_skill(&env, &tok).await, (OFF_TEXT.to_string(), true), "call {i} runs");+ }+ // If the 4th call ran, it would now work+ set_skill(&env, &skill, true).await;+ for i in 4..=5 {+ let (text, is_error) = get_skill(&env, &tok).await;+ assert!(is_error, "call {i}");+ assert!(text.starts_with("kwnt didn't send this call: the same call (same tool, same arguments) already failed 3 times in this turn"), "call {i}: {text}");+ assert!(text.contains(&format!("\"{OFF_TEXT}\"")), "{text}");+ assert!(text.ends_with("end your reply with \"Blocked: <what is blocked>. <what would unblock it>\"."), "{text}");+ }+ // Other arguments are another call: it runs+ let (text, is_error) = call_tool(&env, &tok, "skill_get", json!({"name": "other-notes"})).await;+ assert_eq!((text.as_str(), is_error), ("You have no enabled skill called other-notes.", true));+ // Another turn's token has its own count: the same call runs (and works) there+ let other = open_turn(&env, &env.a, "turn-a2", Default::default()).await;+ let (text, is_error) = get_skill(&env, &other).await;+ assert!(!is_error && text.starts_with("Skill deploy-notes"), "{text}");+ // ...and the first turn is still stopped+ assert!(is_stop(&get_skill(&env, &tok).await.0));+ // The turn's end drops its guard with its scope+ mcp_runtime::finish_turn(&env.state, &tok).await;+ assert!(env.state.self_tools.lock().await.get(&tok).is_none());+ mcp_runtime::finish_turn(&env.state, &other).await;+}++/// A success in between forgets the call: it fails 3 more times before it is stopped.+#[tokio::test]+async fn a_success_in_between_resets_the_count() {+ let env = setup().await;+ let skill = skill_off(&env).await;+ let tok = open_turn(&env, &env.a, "turn-reset", Default::default()).await;+ for _ in 0..2 {+ assert_eq!(get_skill(&env, &tok).await, (OFF_TEXT.to_string(), true));+ }+ set_skill(&env, &skill, true).await;+ let (text, is_error) = get_skill(&env, &tok).await;+ assert!(!is_error && text.starts_with("Skill deploy-notes"), "{text}");+ set_skill(&env, &skill, false).await;+ for i in 1..=3 {+ assert_eq!(get_skill(&env, &tok).await, (OFF_TEXT.to_string(), true), "failure {i} after the success runs");+ }+ assert!(is_stop(&get_skill(&env, &tok).await.0));+ mcp_runtime::finish_turn(&env.state, &tok).await;+}++/// A refused call isn't a failed call: a fresh-eyes or customer refusal stays a refusal however+/// often it comes, and never counts toward the stop.+#[tokio::test]+async fn refusals_stay_refusals() {+ let env = setup().await;+ skill_off(&env).await;++ // Fresh eyes: skill_get isn't on its list+ let tok = open_turn(&env, &env.a, "turn-fresh", Default::default()).await;+ {+ let _fresh = fresh_eyes::Guard::new("turn-fresh");+ for i in 1..=5 {+ assert_eq!(get_skill(&env, &tok).await, (fresh_eyes::REFUSED_TEXT.to_string(), true), "fresh-eyes refusal {i}");+ }+ }+ // Once the review is over the call runs: none of the 5 refusals counted+ for i in 1..=3 {+ assert_eq!(get_skill(&env, &tok).await, (OFF_TEXT.to_string(), true), "call {i} runs");+ }+ assert!(is_stop(&get_skill(&env, &tok).await.0));+ mcp_runtime::finish_turn(&env.state, &tok).await;++ // A customer's turn: no pass from the approver, so every call is refused, never stopped+ let opts = mcp_runtime::TurnApprovalOpts { every_call: true, ..Default::default() };+ let tok = open_turn(&env, &env.a, "turn-customer", opts).await;+ for i in 1..=5 {+ assert_eq!(get_skill(&env, &tok).await, (mcp_runtime::EVERY_CALL_REFUSED.to_string(), true), "customer refusal {i}");+ }+ let scope = env.state.self_tools.lock().await.get(&tok).cloned().unwrap();+ assert!(scope.repeats.check(&RepeatGuard::key("skill_get", &json!({"name": SKILL}))).is_none(), "refusals never counted");+ mcp_runtime::finish_turn(&env.state, &tok).await;+}++/// API and gateway turns reach kwant's own tools through `McpToolSession`, which still stops the+/// 4th call first. The endpoint's guard saw the same 3 failures and holds the same count, and the+/// session's stop never reaches it.+#[tokio::test]+async fn api_turns_still_stop_at_the_session_with_the_same_count() {+ let env = setup().await;+ let skill = skill_off(&env).await;+ let k = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();+ let scope = SelfScope { kwant_id: k.id.clone(), kwant_name: k.name.clone(), turn_id: Some("turn-api".into()), ..Default::default() };+ let (ctx, tok) = mcp_runtime::prepare_turn_with_self(&env.state, &k, Some("turn-api".into()), None, Some(scope)).await.unwrap();+ let (session, problems) = McpToolSession::open(&ctx, None).await;+ assert!(problems.is_empty(), "{problems:?}");+ let caller = Caller { kwant_id: k.id.clone(), kwant_name: k.name.clone(), turn_id: "turn-api".into() };+ let name = "mcp__kwnt_tools__skill_get";+ let args = format!(r#"{{"name": "{SKILL}"}}"#);+ for i in 1..=3 {+ let o = session.call(&caller, &format!("c{i}"), name, &args).await;+ assert_eq!((o.status, o.text.as_str()), ("error", OFF_TEXT), "call {i}");+ }+ let endpoint_count = |scope: &SelfScope| scope.repeats.check(&RepeatGuard::key("skill_get", &json!({"name": SKILL}))).map(|s| s.count);+ let scope = env.state.self_tools.lock().await.get(&tok).cloned().unwrap();+ assert_eq!(endpoint_count(&scope), Some(3), "the endpoint counted the same 3 failures");+ // The session stops the 4th first, with its record, before it reaches the endpoint+ set_skill(&env, &skill, true).await;+ let o = session.call(&caller, "c4", name, &args).await;+ assert_eq!(o.status, "error");+ assert!(is_stop(&o.text), "{}", o.text);+ assert_eq!(o.record["repeat_stopped"], 3);+ assert_eq!(endpoint_count(&scope), Some(3), "the session's stop never reached the endpoint");+ // Both guards give the model the same words+ let (text, is_error) = get_skill(&env, &tok).await;+ assert!(is_error);+ assert_eq!(text, o.text);+ session.shutdown().await;+ mcp_runtime::finish_turn(&env.state, &tok).await;+}diff --git a/tests/spaces_isolation_test.rs b/tests/spaces_isolation_test.rsindex e8f60fb8..a6b3c955 100644--- a/tests/spaces_isolation_test.rs+++ b/tests/spaces_isolation_test.rs@@ -325,6 +325,7 @@ async fn delegation_without_a_member_list_stays_in_the_leads_space() {turn_id: None,workspace: None,sandbox_target: None,+ repeats: Default::default(),};let (text, is_error) = delegation::tool_delegate(&env.state, &scope, &json!({"to": "Remy", "task": "help"})).await;assert!(is_error, "{text}");@@ -500,6 +501,7 @@ async fn the_search_tool_only_finds_messages_in_the_agents_space() {turn_id: None,workspace: None,sandbox_target: None,+ repeats: Default::default(),},);let resp = env