4aea5abf29
Unused Dependencies / machete (push) Has been cancelled
- RepetitionInspector keeps per-session state, resets per user turn and is
enabled via GOOSE_MAX_TOOL_REPETITIONS (off by default); denials are logged.
- tkmind Finish reason now reports stop/max_turns/empty_response/cancelled/
error, with a 'Reply finished' log line.
- RequestGuard publishes Error + Finish{aborted} when the reply task panics
so clients stop waiting for the full timeout.
Co-authored-by: Cursor <cursoragent@cursor.com>
196 lines
5.9 KiB
Rust
196 lines
5.9 KiB
Rust
use crate::config::{Config, GooseMode};
|
|
use crate::conversation::message::{Message, ToolRequest};
|
|
use crate::tool_inspection::{InspectionAction, InspectionResult, ToolInspector};
|
|
use anyhow::Result;
|
|
use async_trait::async_trait;
|
|
use rmcp::model::{CallToolRequestParams, Role};
|
|
use serde_json::Value;
|
|
use std::collections::HashMap;
|
|
use std::sync::Mutex;
|
|
|
|
const MAX_TRACKED_SESSIONS: usize = 4096;
|
|
|
|
#[derive(Debug, Default)]
|
|
struct SessionRepetitionState {
|
|
turn_marker: Option<usize>,
|
|
last_call: Option<InternalToolCall>,
|
|
repeat_count: u32,
|
|
}
|
|
|
|
// Helper struct for internal tracking
|
|
#[derive(Debug, Clone)]
|
|
struct InternalToolCall {
|
|
name: String,
|
|
parameters: Value,
|
|
}
|
|
|
|
impl InternalToolCall {
|
|
fn matches(&self, other: &InternalToolCall) -> bool {
|
|
self.name == other.name && self.parameters == other.parameters
|
|
}
|
|
|
|
fn from_tool_call(tool_call: &CallToolRequestParams) -> Self {
|
|
let name = tool_call.name.to_string();
|
|
let parameters = tool_call
|
|
.arguments
|
|
.as_ref()
|
|
.map(|obj| Value::Object(obj.clone()))
|
|
.unwrap_or(Value::Null);
|
|
Self { name, parameters }
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct RepetitionInspector {
|
|
max_repetitions: Option<u32>,
|
|
last_call: Option<InternalToolCall>,
|
|
repeat_count: u32,
|
|
call_counts: HashMap<String, u32>,
|
|
sessions: Mutex<HashMap<String, SessionRepetitionState>>,
|
|
}
|
|
|
|
impl RepetitionInspector {
|
|
pub fn new(max_repetitions: Option<u32>) -> Self {
|
|
Self {
|
|
max_repetitions,
|
|
last_call: None,
|
|
repeat_count: 0,
|
|
call_counts: HashMap::new(),
|
|
sessions: Mutex::new(HashMap::new()),
|
|
}
|
|
}
|
|
|
|
/// Limit from `GOOSE_MAX_TOOL_REPETITIONS`; unset or 0 disables the check.
|
|
pub fn from_config() -> Self {
|
|
let max = Config::global()
|
|
.get_param::<u32>("GOOSE_MAX_TOOL_REPETITIONS")
|
|
.ok()
|
|
.filter(|value| *value > 0);
|
|
Self::new(max)
|
|
}
|
|
|
|
/// Index of the latest real user message; changes when a new user turn starts.
|
|
fn turn_marker(messages: &[Message]) -> Option<usize> {
|
|
messages
|
|
.iter()
|
|
.rposition(|m| m.role == Role::User && !m.is_tool_response())
|
|
}
|
|
|
|
pub fn check_tool_call(&mut self, tool_call: CallToolRequestParams) -> bool {
|
|
let internal_call = InternalToolCall::from_tool_call(&tool_call);
|
|
let total_calls = self
|
|
.call_counts
|
|
.entry(internal_call.name.clone())
|
|
.or_insert(0);
|
|
*total_calls += 1;
|
|
|
|
if self.max_repetitions.is_none() {
|
|
self.last_call = Some(internal_call);
|
|
self.repeat_count = 1;
|
|
return true;
|
|
}
|
|
|
|
if let Some(last) = &self.last_call {
|
|
if last.matches(&internal_call) {
|
|
self.repeat_count += 1;
|
|
if self.repeat_count > self.max_repetitions.unwrap() {
|
|
return false;
|
|
}
|
|
} else {
|
|
self.repeat_count = 1;
|
|
}
|
|
} else {
|
|
self.repeat_count = 1;
|
|
}
|
|
|
|
self.last_call = Some(internal_call);
|
|
true
|
|
}
|
|
|
|
pub fn reset(&mut self) {
|
|
self.last_call = None;
|
|
self.repeat_count = 0;
|
|
self.call_counts.clear();
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl ToolInspector for RepetitionInspector {
|
|
fn name(&self) -> &'static str {
|
|
"repetition"
|
|
}
|
|
|
|
fn as_any(&self) -> &dyn std::any::Any {
|
|
self
|
|
}
|
|
|
|
fn is_enabled(&self) -> bool {
|
|
self.max_repetitions.is_some()
|
|
}
|
|
|
|
async fn inspect(
|
|
&self,
|
|
session_id: &str,
|
|
tool_requests: &[ToolRequest],
|
|
messages: &[Message],
|
|
_goose_mode: GooseMode,
|
|
) -> Result<Vec<InspectionResult>> {
|
|
let Some(max_repetitions) = self.max_repetitions else {
|
|
return Ok(Vec::new());
|
|
};
|
|
let marker = Self::turn_marker(messages);
|
|
let mut sessions = self
|
|
.sessions
|
|
.lock()
|
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
if sessions.len() >= MAX_TRACKED_SESSIONS && !sessions.contains_key(session_id) {
|
|
sessions.clear();
|
|
}
|
|
let state = sessions.entry(session_id.to_string()).or_default();
|
|
if state.turn_marker != marker {
|
|
*state = SessionRepetitionState {
|
|
turn_marker: marker,
|
|
..Default::default()
|
|
};
|
|
}
|
|
|
|
let mut results = Vec::new();
|
|
for tool_request in tool_requests {
|
|
let Ok(tool_call) = &tool_request.tool_call else {
|
|
continue;
|
|
};
|
|
let call = InternalToolCall::from_tool_call(tool_call);
|
|
let repeated = state
|
|
.last_call
|
|
.as_ref()
|
|
.is_some_and(|last| last.matches(&call));
|
|
state.repeat_count = if repeated { state.repeat_count + 1 } else { 1 };
|
|
state.last_call = Some(call);
|
|
|
|
if state.repeat_count > max_repetitions {
|
|
tracing::warn!(
|
|
session_id,
|
|
tool = %tool_call.name,
|
|
repeat_count = state.repeat_count,
|
|
max_repetitions,
|
|
"Tool call denied: exceeded maximum consecutive repetitions"
|
|
);
|
|
results.push(InspectionResult {
|
|
tool_request_id: tool_request.id.clone(),
|
|
action: InspectionAction::Deny,
|
|
reason: format!(
|
|
"Tool '{}' was called with identical arguments {} times in a row; \
|
|
change approach instead of repeating it",
|
|
tool_call.name, state.repeat_count
|
|
),
|
|
confidence: 1.0,
|
|
inspector_name: "repetition".to_string(),
|
|
finding_id: Some("REP-001".to_string()),
|
|
});
|
|
}
|
|
}
|
|
|
|
Ok(results)
|
|
}
|
|
}
|