Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 508df26f5f | |||
| 4aea5abf29 | |||
| 52dd6697c6 | |||
| c44c7f04be | |||
| 6af43341c8 | |||
| e622befc30 |
@@ -439,6 +439,7 @@ impl OpenAiProvider {
|
||||
const PROVIDERS_NEEDING_MAX_TOKENS_REMAP: &[&str] = &[
|
||||
"cerebras",
|
||||
"custom_deepseek",
|
||||
"custom_deepseek-cp",
|
||||
"groq",
|
||||
"inception",
|
||||
"kimi",
|
||||
@@ -449,6 +450,23 @@ impl OpenAiProvider {
|
||||
"ovhcloud",
|
||||
];
|
||||
|
||||
/// DashScope / Memind relay rejects max_tokens above 131072 for DeepSeek V4.
|
||||
const DASHSCOPE_COMPAT_MAX_TOKENS: i32 = 131_072;
|
||||
|
||||
const PROVIDERS_DASHSCOPE_MAX_TOKENS_CAP: &[&str] = &["custom_deepseek", "custom_deepseek-cp"];
|
||||
|
||||
fn cap_token_limits_for_dashscope_compat(obj: &mut serde_json::Map<String, serde_json::Value>) {
|
||||
for key in ["max_tokens", "max_completion_tokens"] {
|
||||
if let Some(value) = obj.get_mut(key) {
|
||||
if let Some(n) = value.as_i64() {
|
||||
if n > i64::from(Self::DASHSCOPE_COMPAT_MAX_TOKENS) {
|
||||
*value = json!(Self::DASHSCOPE_COMPAT_MAX_TOKENS);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const PROVIDERS_NEEDING_STANDARD_CHAT_PARAMS: &[&str] = &["nearai", "pleumrouter"];
|
||||
|
||||
/// Providers whose reasoning models accept an OpenAI-style
|
||||
@@ -524,6 +542,10 @@ impl OpenAiProvider {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if Self::PROVIDERS_DASHSCOPE_MAX_TOKENS_CAP.contains(&self.name.as_str()) {
|
||||
Self::cap_token_limits_for_dashscope_compat(obj);
|
||||
}
|
||||
}
|
||||
|
||||
payload
|
||||
@@ -1039,6 +1061,39 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_caps_deepseek_cp_max_tokens_for_dashscope() {
|
||||
let provider = make_provider("custom_deepseek-cp");
|
||||
let payload = json!({
|
||||
"model": "deepseek-v4-flash",
|
||||
"messages": [],
|
||||
"max_tokens": 384000
|
||||
});
|
||||
|
||||
let result =
|
||||
provider.sanitize_request_for_compat(payload, &ModelConfig::new("deepseek-v4-flash"));
|
||||
let obj = result.as_object().unwrap();
|
||||
|
||||
assert_eq!(obj.get("max_tokens").unwrap(), &json!(131_072));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_caps_deepseek_cp_max_completion_tokens_for_dashscope() {
|
||||
let provider = make_provider("custom_deepseek-cp");
|
||||
let payload = json!({
|
||||
"model": "deepseek-v4-flash",
|
||||
"messages": [],
|
||||
"max_completion_tokens": 384000
|
||||
});
|
||||
|
||||
let result =
|
||||
provider.sanitize_request_for_compat(payload, &ModelConfig::new("deepseek-v4-flash"));
|
||||
let obj = result.as_object().unwrap();
|
||||
|
||||
assert_eq!(obj.get("max_tokens").unwrap(), &json!(131_072));
|
||||
assert!(!obj.contains_key("max_completion_tokens"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_remaps_max_completion_tokens_for_compat_provider() {
|
||||
let provider = make_provider("mistral");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use axum::{extract::State, routing::post, Json, Router};
|
||||
@@ -15,6 +15,82 @@ use super::{errors::ErrorResponse, state::AppState};
|
||||
const DEFAULT_QUERY: &str =
|
||||
"project architecture conventions current goals decisions risks and recent work";
|
||||
const DEFAULT_MAX_CHARS: usize = 6_000;
|
||||
const BREAKER_FAILURE_THRESHOLD: u32 = 3;
|
||||
const BREAKER_COOLDOWN: Duration = Duration::from_secs(600);
|
||||
const STDERR_LOG_TAIL_CHARS: usize = 600;
|
||||
|
||||
struct HarnessBreaker {
|
||||
consecutive_failures: u32,
|
||||
open_until: Option<Instant>,
|
||||
}
|
||||
|
||||
impl HarnessBreaker {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
consecutive_failures: 0,
|
||||
open_until: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn allows(&mut self, now: Instant) -> bool {
|
||||
match self.open_until {
|
||||
Some(until) if now < until => false,
|
||||
Some(_) => {
|
||||
self.open_until = None;
|
||||
true
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true when this failure trips the breaker open.
|
||||
fn record(&mut self, success: bool, now: Instant) -> bool {
|
||||
if success {
|
||||
self.consecutive_failures = 0;
|
||||
self.open_until = None;
|
||||
return false;
|
||||
}
|
||||
self.consecutive_failures += 1;
|
||||
if self.consecutive_failures >= BREAKER_FAILURE_THRESHOLD {
|
||||
self.consecutive_failures = 0;
|
||||
self.open_until = Some(now + BREAKER_COOLDOWN);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
static HARNESS_BREAKER: Mutex<HarnessBreaker> = Mutex::new(HarnessBreaker::new());
|
||||
|
||||
fn harness_allowed() -> bool {
|
||||
HARNESS_BREAKER
|
||||
.lock()
|
||||
.map(|mut breaker| breaker.allows(Instant::now()))
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
fn record_harness_result(success: bool) {
|
||||
let tripped = HARNESS_BREAKER
|
||||
.lock()
|
||||
.map(|mut breaker| breaker.record(success, Instant::now()))
|
||||
.unwrap_or(false);
|
||||
if tripped {
|
||||
tracing::warn!(
|
||||
cooldown_secs = BREAKER_COOLDOWN.as_secs(),
|
||||
"Harness failing repeatedly; pausing harness calls"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn stderr_tail(stderr: &[u8]) -> String {
|
||||
let text = String::from_utf8_lossy(stderr);
|
||||
let text = text.trim();
|
||||
let count = text.chars().count();
|
||||
if count <= STDERR_LOG_TAIL_CHARS {
|
||||
return text.to_string();
|
||||
}
|
||||
text.chars().skip(count - STDERR_LOG_TAIL_CHARS).collect()
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -69,16 +145,25 @@ fn harness_binary() -> PathBuf {
|
||||
}
|
||||
|
||||
async fn recall(repo: &str, query: &str, working_dir: &Path) -> Option<String> {
|
||||
let output = timeout(
|
||||
if !harness_allowed() {
|
||||
return None;
|
||||
}
|
||||
let result = timeout(
|
||||
Duration::from_secs(8),
|
||||
Command::new(harness_binary())
|
||||
.args(["recall", "--repo", repo, "--query", query])
|
||||
.current_dir(working_dir)
|
||||
.output(),
|
||||
)
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
.await;
|
||||
let output = match result {
|
||||
Ok(Ok(output)) => output,
|
||||
_ => {
|
||||
record_harness_result(false);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
record_harness_result(output.status.success());
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
@@ -209,6 +294,10 @@ async fn harness_remember(
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or("H5 conversation memory");
|
||||
if !harness_allowed() {
|
||||
tracing::debug!(session_id = %request.session_id, "Harness paused; skipping remember");
|
||||
return Ok(Json(HarnessRememberResponse { remembered: false }));
|
||||
}
|
||||
let remembered = match timeout(
|
||||
Duration::from_secs(8),
|
||||
Command::new(harness_binary())
|
||||
@@ -233,7 +322,7 @@ async fn harness_remember(
|
||||
tracing::warn!(
|
||||
session_id = %request.session_id,
|
||||
status = ?output.status.code(),
|
||||
stderr = %String::from_utf8_lossy(&output.stderr).trim(),
|
||||
stderr = %stderr_tail(&output.stderr),
|
||||
"Harness remember failed"
|
||||
);
|
||||
false
|
||||
@@ -247,9 +336,46 @@ async fn harness_remember(
|
||||
false
|
||||
}
|
||||
};
|
||||
record_harness_result(remembered);
|
||||
Ok(Json(HarnessRememberResponse { remembered }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn breaker_opens_after_threshold_and_recovers_after_cooldown() {
|
||||
let mut breaker = HarnessBreaker::new();
|
||||
let t0 = Instant::now();
|
||||
assert!(breaker.allows(t0));
|
||||
assert!(!breaker.record(false, t0));
|
||||
assert!(!breaker.record(false, t0));
|
||||
assert!(breaker.record(false, t0));
|
||||
assert!(!breaker.allows(t0 + Duration::from_secs(1)));
|
||||
assert!(breaker.allows(t0 + BREAKER_COOLDOWN + Duration::from_secs(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breaker_success_resets_failure_count() {
|
||||
let mut breaker = HarnessBreaker::new();
|
||||
let t0 = Instant::now();
|
||||
breaker.record(false, t0);
|
||||
breaker.record(false, t0);
|
||||
breaker.record(true, t0);
|
||||
assert!(!breaker.record(false, t0));
|
||||
assert!(breaker.allows(t0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stderr_tail_keeps_last_chars() {
|
||||
let long = format!("{}错误结尾", "x".repeat(2_000));
|
||||
let tail = stderr_tail(long.as_bytes());
|
||||
assert_eq!(tail.chars().count(), STDERR_LOG_TAIL_CHARS);
|
||||
assert!(tail.ends_with("错误结尾"));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn routes(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/agent/harness_bootstrap", post(harness_bootstrap))
|
||||
|
||||
@@ -198,7 +198,30 @@ impl Drop for RequestGuard {
|
||||
if !self.disarmed {
|
||||
let bus = self.bus.clone();
|
||||
let request_id = self.request_id.clone();
|
||||
// A panicking reply task never reaches its own Finish; without a terminal
|
||||
// event here, clients wait for their full reply timeout.
|
||||
let panicked = std::thread::panicking();
|
||||
if panicked {
|
||||
tracing::error!(request_id = %request_id, "Reply task panicked; publishing terminal events");
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
if panicked {
|
||||
bus.publish(
|
||||
Some(request_id.clone()),
|
||||
MessageEvent::Error {
|
||||
error: "reply task aborted unexpectedly".to_string(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
bus.publish(
|
||||
Some(request_id.clone()),
|
||||
MessageEvent::Finish {
|
||||
reason: "aborted".to_string(),
|
||||
token_state: Default::default(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
bus.cleanup_request(&request_id).await;
|
||||
});
|
||||
}
|
||||
@@ -286,6 +309,44 @@ mod tests {
|
||||
assert!(!cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_request_guard_publishes_terminal_events_when_task_panics() {
|
||||
let bus = std::sync::Arc::new(SessionEventBus::new());
|
||||
bus.register_request("req-p".to_string()).await;
|
||||
|
||||
let task_bus = bus.clone();
|
||||
let handle = tokio::spawn(async move {
|
||||
let _guard = RequestGuard::new(task_bus, "req-p".to_string());
|
||||
panic!("simulated tool panic");
|
||||
});
|
||||
assert!(handle.await.unwrap_err().is_panic());
|
||||
|
||||
let mut events = Vec::new();
|
||||
for _ in 0..50 {
|
||||
let (replay, _, _rx) = bus.subscribe(None).await.unwrap();
|
||||
if replay.len() >= 2 {
|
||||
events = replay;
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
assert!(matches!(events[0].event, MessageEvent::Error { .. }));
|
||||
assert!(
|
||||
matches!(&events[1].event, MessageEvent::Finish { reason, .. } if reason == "aborted")
|
||||
);
|
||||
assert_eq!(events[1].request_id.as_deref(), Some("req-p"));
|
||||
assert!(!bus.cancel_request("req-p").await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_request_guard_does_not_publish_on_normal_early_return() {
|
||||
let bus = std::sync::Arc::new(SessionEventBus::new());
|
||||
drop(RequestGuard::new(bus.clone(), "req-e".to_string()));
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
let (replay, _, _rx) = bus.subscribe(None).await.unwrap();
|
||||
assert!(replay.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cleanup_request() {
|
||||
let bus = SessionEventBus::new();
|
||||
|
||||
@@ -20,7 +20,7 @@ use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
|
||||
use crate::agents::{AgentEvent, SessionConfig};
|
||||
use crate::agents::{loop_stop_reason, AgentEvent, SessionConfig};
|
||||
use crate::conversation::message::{ActionRequiredData, Message, MessageContent};
|
||||
use crate::conversation::Conversation;
|
||||
|
||||
@@ -414,10 +414,12 @@ pub async fn session_reply(
|
||||
}
|
||||
};
|
||||
|
||||
let mut finish_reason = "stop";
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = task_cancel.cancelled() => {
|
||||
tracing::info!("Agent task cancelled for request {}", task_request_id);
|
||||
finish_reason = "cancelled";
|
||||
break;
|
||||
}
|
||||
response = timeout(Duration::from_millis(500), stream.next()) => {
|
||||
@@ -426,6 +428,9 @@ pub async fn session_reply(
|
||||
for content in &message.content {
|
||||
track_tool_telemetry(content, all_messages.messages());
|
||||
}
|
||||
if let Some(reason) = loop_stop_reason(&message) {
|
||||
finish_reason = reason;
|
||||
}
|
||||
all_messages.push(message.clone());
|
||||
let token_state = get_token_state(
|
||||
task_state.session_manager(),
|
||||
@@ -466,6 +471,7 @@ pub async fn session_reply(
|
||||
}
|
||||
Ok(Some(Err(e))) => {
|
||||
tracing::error!("Error processing message: {}", e);
|
||||
finish_reason = "error";
|
||||
publish(
|
||||
Some(task_request_id.clone()),
|
||||
MessageEvent::Error {
|
||||
@@ -543,10 +549,17 @@ pub async fn session_reply(
|
||||
let final_token_state =
|
||||
get_token_state(task_state.session_manager(), &task_session_id).await;
|
||||
|
||||
tracing::info!(
|
||||
session_id = %task_session_id,
|
||||
request_id = %task_request_id,
|
||||
finish_reason,
|
||||
duration_ms = session_duration.as_millis() as u64,
|
||||
"Reply finished"
|
||||
);
|
||||
publish(
|
||||
Some(task_request_id.clone()),
|
||||
MessageEvent::Finish {
|
||||
reason: "stop".to_string(),
|
||||
reason: finish_reason.to_string(),
|
||||
token_state: final_token_state,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -93,6 +93,39 @@ const COMPACTION_PROGRESS_TEXT: &str = "goose is compacting the conversation..."
|
||||
const MAX_EMPTY_TURN_RETRIES: u32 = 3;
|
||||
const EMPTY_TURN_MESSAGE: &str =
|
||||
"The model returned an empty response. Please resend your message to continue.";
|
||||
const PROVIDER_REFUSED_MESSAGE: &str = "The provider refused this request.";
|
||||
const PROVIDER_ERROR_PREFIX: &str = "Ran into this error:";
|
||||
const NETWORK_ERROR_SUFFIX: &str = "Please resend your message to try again.";
|
||||
|
||||
/// Classifies the assistant notices the loop emits when it stops on a guard,
|
||||
/// so HTTP clients can report why a reply ended instead of a generic "stop".
|
||||
pub fn loop_stop_reason(message: &Message) -> Option<&'static str> {
|
||||
if message.role != rmcp::model::Role::Assistant {
|
||||
return None;
|
||||
}
|
||||
if message.error_kind().is_some() {
|
||||
return Some("provider_error");
|
||||
}
|
||||
let credits_exhausted = message.content.iter().any(|content| {
|
||||
content
|
||||
.as_system_notification()
|
||||
.is_some_and(|notification| {
|
||||
notification.notification_type == SystemNotificationType::CreditsExhausted
|
||||
})
|
||||
});
|
||||
if credits_exhausted {
|
||||
return Some("credits_exhausted");
|
||||
}
|
||||
match message.as_concat_text().trim() {
|
||||
text if text == MAX_TURNS_MESSAGE => Some("max_turns"),
|
||||
text if text == EMPTY_TURN_MESSAGE => Some("empty_response"),
|
||||
text if text.starts_with(PROVIDER_REFUSED_MESSAGE) => Some("provider_refused"),
|
||||
text if text.starts_with(PROVIDER_ERROR_PREFIX) || text.ends_with(NETWORK_ERROR_SUFFIX) => {
|
||||
Some("provider_error")
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn provider_creation_error(error: anyhow::Error, context: impl fmt::Display) -> anyhow::Error {
|
||||
let message = format!("{context}: {error}");
|
||||
@@ -801,7 +834,7 @@ impl Agent {
|
||||
)));
|
||||
|
||||
// Add repetition inspector (lower priority - basic repetition checking)
|
||||
tool_inspection_manager.add_inspector(Box::new(RepetitionInspector::new(None)));
|
||||
tool_inspection_manager.add_inspector(Box::new(RepetitionInspector::from_config()));
|
||||
|
||||
tool_inspection_manager
|
||||
}
|
||||
@@ -3267,7 +3300,7 @@ impl Agent {
|
||||
|
||||
let category = category.as_deref().map(|c| format!("\n\nCategory: {c}")).unwrap_or_default();
|
||||
yield AgentEvent::Message(Message::assistant().with_text(format!(
|
||||
"The provider refused this request.\n\n{details}{category}\n\nPlease start a new session to continue — resending this conversation is likely to be refused again."
|
||||
"{PROVIDER_REFUSED_MESSAGE}\n\n{details}{category}\n\nPlease start a new session to continue — resending this conversation is likely to be refused again."
|
||||
)));
|
||||
// A refusal is terminal: skip goal/grind nudges and
|
||||
// recipe retry_config, which would resend the same
|
||||
@@ -3297,7 +3330,7 @@ impl Agent {
|
||||
error!("Error: {}", provider_err);
|
||||
yield AgentEvent::Message(
|
||||
Message::assistant().with_text(
|
||||
format!("{provider_err}\n\nPlease resend your message to try again.")
|
||||
format!("{provider_err}\n\n{NETWORK_ERROR_SUFFIX}")
|
||||
)
|
||||
);
|
||||
break;
|
||||
@@ -3307,9 +3340,11 @@ impl Agent {
|
||||
#[cfg(feature = "telemetry")]
|
||||
crate::posthog::emit_error(provider_err.telemetry_type(), &provider_err.to_string());
|
||||
error!("Error: {}", provider_err);
|
||||
// Portal matches this text (session-reply-wait providerReplyError) to
|
||||
// classify and recover poisoned sessions; keep it as plain text.
|
||||
yield AgentEvent::Message(
|
||||
Message::assistant().with_text(
|
||||
format!("Ran into this error: {provider_err}.\n\nPlease retry if you think this is a transient or recoverable error.")
|
||||
format!("{PROVIDER_ERROR_PREFIX} {provider_err}.\n\nPlease retry if you think this is a transient or recoverable error.")
|
||||
)
|
||||
);
|
||||
break;
|
||||
@@ -4235,6 +4270,67 @@ mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn loop_stop_reason_classifies_guard_notices() {
|
||||
assert_eq!(
|
||||
loop_stop_reason(&Message::assistant().with_text(MAX_TURNS_MESSAGE)),
|
||||
Some("max_turns")
|
||||
);
|
||||
assert_eq!(
|
||||
loop_stop_reason(&Message::assistant().with_text(EMPTY_TURN_MESSAGE)),
|
||||
Some("empty_response")
|
||||
);
|
||||
assert_eq!(
|
||||
loop_stop_reason(&Message::assistant().with_text("页面已生成")),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
loop_stop_reason(&Message::user().with_text(MAX_TURNS_MESSAGE)),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_stop_reason_classifies_provider_failures() {
|
||||
let auth = ProviderError::Authentication("Invalid API key".to_string());
|
||||
assert_eq!(
|
||||
loop_stop_reason(&Message::from_provider_error(&auth)),
|
||||
Some("provider_error")
|
||||
);
|
||||
assert_eq!(
|
||||
loop_stop_reason(&Message::assistant().with_text(format!(
|
||||
"{PROVIDER_ERROR_PREFIX} boom.\n\nPlease retry if you think this is a transient or recoverable error."
|
||||
))),
|
||||
Some("provider_error")
|
||||
);
|
||||
assert_eq!(
|
||||
loop_stop_reason(
|
||||
&Message::assistant().with_text(format!("timeout\n\n{NETWORK_ERROR_SUFFIX}"))
|
||||
),
|
||||
Some("provider_error")
|
||||
);
|
||||
assert_eq!(
|
||||
loop_stop_reason(
|
||||
&Message::assistant().with_text(format!("{PROVIDER_REFUSED_MESSAGE}\n\nunsafe"))
|
||||
),
|
||||
Some("provider_refused")
|
||||
);
|
||||
assert_eq!(
|
||||
loop_stop_reason(&Message::assistant().with_system_notification_with_data(
|
||||
SystemNotificationType::CreditsExhausted,
|
||||
"add credits",
|
||||
serde_json::json!({}),
|
||||
)),
|
||||
Some("credits_exhausted")
|
||||
);
|
||||
assert_eq!(
|
||||
loop_stop_reason(
|
||||
&Message::assistant().with_text("Ran into this error trying to compact")
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
fn persisted_builtin(name: &str) -> ExtensionConfig {
|
||||
ExtensionConfig::Builtin {
|
||||
name: name.to_string(),
|
||||
|
||||
@@ -309,10 +309,15 @@ pub(crate) fn recover_mangled_tool_name<'a>(
|
||||
let owner_mangled = owner.map(|o| format!("{o}.{name}"));
|
||||
let owner_prefixed = owner.map(|o| format!("{o}__{name}"));
|
||||
|
||||
// Models prompted with bare tool names ("write_file") drop the extension
|
||||
// prefix entirely; recover only when exactly one extension owns that tool.
|
||||
let bare_tool = name.split_once("__").map(|(_, tool)| tool);
|
||||
|
||||
let matches = stripped == name
|
||||
|| separator_mangled.as_deref() == Some(stripped)
|
||||
|| owner_mangled.as_deref() == Some(stripped)
|
||||
|| owner_prefixed.as_deref() == Some(stripped);
|
||||
|| owner_prefixed.as_deref() == Some(stripped)
|
||||
|| bare_tool == Some(stripped);
|
||||
if name == emitted || !matches {
|
||||
continue;
|
||||
}
|
||||
@@ -3805,6 +3810,36 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recover_mangled_tool_name_bare_tool_without_extension_prefix() {
|
||||
let tools = [
|
||||
("sandbox-fs__write_file", None),
|
||||
("sandbox-fs__read_file", None),
|
||||
("developer__shell", None),
|
||||
];
|
||||
assert_eq!(
|
||||
recover_mangled_tool_name("write_file", tools.iter().copied()).as_deref(),
|
||||
Some("sandbox-fs__write_file")
|
||||
);
|
||||
assert_eq!(
|
||||
recover_mangled_tool_name("functions.read_file", tools.iter().copied()).as_deref(),
|
||||
Some("sandbox-fs__read_file")
|
||||
);
|
||||
assert_eq!(
|
||||
recover_mangled_tool_name("edit_file", tools.iter().copied()),
|
||||
None
|
||||
);
|
||||
|
||||
let ambiguous = [
|
||||
("sandbox-fs__write_file", None),
|
||||
("other__write_file", None),
|
||||
];
|
||||
assert_eq!(
|
||||
recover_mangled_tool_name("write_file", ambiguous.iter().copied()),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recover_mangled_tool_name_non_extension_manager_tools() {
|
||||
// recipe__final_output and platform__manage_schedule are appended by
|
||||
|
||||
@@ -26,7 +26,9 @@ mod tool_schema_normalize;
|
||||
pub mod types;
|
||||
pub mod validate_extensions;
|
||||
|
||||
pub use agent::{Agent, AgentConfig, ExtensionLoadResult, GoosePlatform, MCP_PROTOCOL_VERSION};
|
||||
pub use agent::{
|
||||
loop_stop_reason, Agent, AgentConfig, ExtensionLoadResult, GoosePlatform, MCP_PROTOCOL_VERSION,
|
||||
};
|
||||
pub use container::Container;
|
||||
pub use execute_commands::{context_management_unsupported_message, COMPACT_TRIGGERS};
|
||||
pub use extension::{ExtensionConfig, ExtensionError};
|
||||
|
||||
@@ -60,32 +60,45 @@ impl WebClient {
|
||||
})
|
||||
}
|
||||
|
||||
fn floor_char_boundary(s: &str, index: usize) -> usize {
|
||||
if index >= s.len() {
|
||||
return s.len();
|
||||
}
|
||||
let mut i = index;
|
||||
while !s.is_char_boundary(i) {
|
||||
i -= 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn truncate(s: String) -> String {
|
||||
if s.len() > MAX_OUTPUT_CHARS {
|
||||
format!("{}\n[output truncated]", &s[..MAX_OUTPUT_CHARS])
|
||||
let end = Self::floor_char_boundary(&s, MAX_OUTPUT_CHARS);
|
||||
format!("{}\n[output truncated]", &s[..end])
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
// Byte offsets found in the lowercased copy are reused to slice the original,
|
||||
// so lowercasing must preserve byte length: ASCII-only.
|
||||
fn remove_blocks(mut text: String, open: &str, close: &str) -> String {
|
||||
loop {
|
||||
let lower = text.to_ascii_lowercase();
|
||||
let Some(start) = lower.find(open) else {
|
||||
break;
|
||||
};
|
||||
let Some(end) = lower[start..].find(close) else {
|
||||
break;
|
||||
};
|
||||
text.replace_range(start..start + end + close.len(), "");
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn strip_html(html: &str) -> String {
|
||||
let mut text = html.to_string();
|
||||
|
||||
while let Some(start) = text.to_lowercase().find("<script") {
|
||||
if let Some(end) = text.to_lowercase()[start..].find("</script>") {
|
||||
text = format!("{}{}", &text[..start], &text[start + end + 9..]);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
while let Some(start) = text.to_lowercase().find("<style") {
|
||||
if let Some(end) = text.to_lowercase()[start..].find("</style>") {
|
||||
text = format!("{}{}", &text[..start], &text[start + end + 8..]);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let text = Self::remove_blocks(html.to_string(), "<script", "</script>");
|
||||
let text = Self::remove_blocks(text, "<style", "</style>");
|
||||
|
||||
let mut result = String::new();
|
||||
let mut in_tag = false;
|
||||
@@ -183,7 +196,7 @@ impl WebClient {
|
||||
|
||||
fn parse_ddg_results(html: &str, max: usize) -> String {
|
||||
let mut results = Vec::new();
|
||||
let lower = html.to_lowercase();
|
||||
let lower = html.to_ascii_lowercase();
|
||||
|
||||
let mut pos = 0;
|
||||
while results.len() < max {
|
||||
@@ -194,15 +207,15 @@ impl WebClient {
|
||||
|
||||
let before = &html[..link_start + search_str.len()];
|
||||
let a_start = before.rfind('<').unwrap_or(0);
|
||||
let a_block = &html[a_start
|
||||
..link_start
|
||||
+ search_str.len()
|
||||
+ 100.min(html.len() - link_start - search_str.len())];
|
||||
let a_end = Self::floor_char_boundary(html, link_start + search_str.len() + 100);
|
||||
let a_block = &html[a_start..a_end];
|
||||
|
||||
let href = Self::extract_attr(a_block, "href").unwrap_or_default();
|
||||
|
||||
let after_a_tag_end = link_start + search_str.len();
|
||||
let close_offset = html[after_a_tag_end..].find('>').unwrap_or(0);
|
||||
let Some(close_offset) = html[after_a_tag_end..].find('>') else {
|
||||
break;
|
||||
};
|
||||
let content_start = after_a_tag_end + close_offset + 1;
|
||||
let close_a = html[content_start..].find("</a>").unwrap_or(0);
|
||||
let title = Self::strip_html(&html[content_start..content_start + close_a]);
|
||||
@@ -247,7 +260,7 @@ impl WebClient {
|
||||
|
||||
fn extract_attr(tag: &str, attr: &str) -> Option<String> {
|
||||
let search = format!("{attr}=\"");
|
||||
let lower = tag.to_lowercase();
|
||||
let lower = tag.to_ascii_lowercase();
|
||||
let start = lower.find(&search)? + search.len();
|
||||
let end = tag[start..].find('"')?;
|
||||
Some(tag[start..start + end].to_string())
|
||||
@@ -329,3 +342,63 @@ impl McpClientTrait for WebClient {
|
||||
Some(&self.info)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::WebClient;
|
||||
use super::MAX_OUTPUT_CHARS;
|
||||
|
||||
#[test]
|
||||
fn truncate_does_not_split_multibyte_chars() {
|
||||
let s = format!("a{}", "中".repeat(MAX_OUTPUT_CHARS));
|
||||
let out = WebClient::truncate(s);
|
||||
assert!(out.ends_with("\n[output truncated]"));
|
||||
let body = out.trim_end_matches("\n[output truncated]");
|
||||
assert!(body.len() <= MAX_OUTPUT_CHARS);
|
||||
assert!(body.chars().skip(1).all(|c| c == '中'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_keeps_short_input() {
|
||||
assert_eq!(WebClient::truncate("短文本".to_string()), "短文本");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_html_handles_chars_that_change_length_when_lowercased() {
|
||||
let html =
|
||||
"<p>İstanbul Ⱥ 中文</p><SCRIPT>var x = 'İ';</SCRIPT><Style>.a{}</Style><p>尾部</p>";
|
||||
let text = WebClient::strip_html(html);
|
||||
assert_eq!(text, "İstanbul Ⱥ 中文尾部");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_html_keeps_text_when_block_is_unclosed() {
|
||||
assert_eq!(WebClient::strip_html("<p>前</p><script>x"), "前x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ddg_results_handles_multibyte_near_link() {
|
||||
let html = format!(
|
||||
"<div>İİİ<a class=\"result__a\" href=\"https://example.com/中\">{}标题</a>\
|
||||
<a class=\"result__snippet\">摘要 İ</a></div>",
|
||||
"长".repeat(60)
|
||||
);
|
||||
let out = WebClient::parse_ddg_results(&html, 5);
|
||||
assert!(out.starts_with("1. "));
|
||||
assert!(out.contains("标题"));
|
||||
assert!(out.contains("https://example.com/中"));
|
||||
assert!(out.contains("摘要 İ"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ddg_results_handles_truncated_link_tag() {
|
||||
assert_eq!(
|
||||
WebClient::parse_ddg_results("<a class=\"result__a\"", 5),
|
||||
"No results found."
|
||||
);
|
||||
assert_eq!(
|
||||
WebClient::parse_ddg_results("<a class=\"result__a\"中文", 5),
|
||||
"No results found."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
use crate::config::GooseMode;
|
||||
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;
|
||||
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)]
|
||||
@@ -36,6 +46,7 @@ pub struct RepetitionInspector {
|
||||
last_call: Option<InternalToolCall>,
|
||||
repeat_count: u32,
|
||||
call_counts: HashMap<String, u32>,
|
||||
sessions: Mutex<HashMap<String, SessionRepetitionState>>,
|
||||
}
|
||||
|
||||
impl RepetitionInspector {
|
||||
@@ -45,9 +56,26 @@ impl RepetitionInspector {
|
||||
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
|
||||
@@ -96,37 +124,69 @@ impl ToolInspector for RepetitionInspector {
|
||||
self
|
||||
}
|
||||
|
||||
fn is_enabled(&self) -> bool {
|
||||
self.max_repetitions.is_some()
|
||||
}
|
||||
|
||||
async fn inspect(
|
||||
&self,
|
||||
_session_id: &str,
|
||||
session_id: &str,
|
||||
tool_requests: &[ToolRequest],
|
||||
_messages: &[Message],
|
||||
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();
|
||||
|
||||
// Check repetition limits for each tool request
|
||||
for tool_request in tool_requests {
|
||||
if let Ok(tool_call) = &tool_request.tool_call {
|
||||
// Create a temporary clone to check without modifying state
|
||||
let mut temp_inspector = RepetitionInspector::new(self.max_repetitions);
|
||||
temp_inspector.last_call = self.last_call.clone();
|
||||
temp_inspector.repeat_count = self.repeat_count;
|
||||
temp_inspector.call_counts = self.call_counts.clone();
|
||||
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 !temp_inspector.check_tool_call(tool_call.clone()) {
|
||||
results.push(InspectionResult {
|
||||
tool_request_id: tool_request.id.clone(),
|
||||
action: InspectionAction::Deny,
|
||||
reason: format!(
|
||||
"Tool '{}' has exceeded maximum repetitions",
|
||||
tool_call.name
|
||||
),
|
||||
confidence: 1.0,
|
||||
inspector_name: "repetition".to_string(),
|
||||
finding_id: Some("REP-001".to_string()),
|
||||
});
|
||||
}
|
||||
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()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,132 @@
|
||||
use goose::config::GooseMode;
|
||||
use goose::conversation::message::{Message, ToolRequest};
|
||||
use goose::tool_inspection::{InspectionAction, ToolInspector};
|
||||
use goose::tool_monitor::RepetitionInspector;
|
||||
use rmcp::model::CallToolRequestParams;
|
||||
use rmcp::model::{CallToolRequestParams, CallToolResult};
|
||||
use rmcp::object;
|
||||
|
||||
fn request(id: &str, tool: &str, args: serde_json::Map<String, serde_json::Value>) -> ToolRequest {
|
||||
ToolRequest {
|
||||
id: id.into(),
|
||||
tool_call: Ok(CallToolRequestParams::new(tool.to_string()).with_arguments(args)),
|
||||
metadata: None,
|
||||
tool_meta: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn denied(
|
||||
inspector: &RepetitionInspector,
|
||||
session: &str,
|
||||
req: ToolRequest,
|
||||
messages: &[Message],
|
||||
) -> bool {
|
||||
inspector
|
||||
.inspect(session, &[req], messages, GooseMode::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| r.action == InspectionAction::Deny)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inspect_tracks_repeats_across_calls_within_a_user_turn() {
|
||||
let inspector = RepetitionInspector::new(Some(2));
|
||||
let mut history = vec![Message::user().with_text("生成页面")];
|
||||
let args = object!({"path": "public/a.html"});
|
||||
|
||||
assert!(
|
||||
!denied(
|
||||
&inspector,
|
||||
"s1",
|
||||
request("1", "read_file", args.clone()),
|
||||
&history
|
||||
)
|
||||
.await
|
||||
);
|
||||
history.push(Message::user().with_tool_response("1", Ok(CallToolResult::success(vec![]))));
|
||||
assert!(
|
||||
!denied(
|
||||
&inspector,
|
||||
"s1",
|
||||
request("2", "read_file", args.clone()),
|
||||
&history
|
||||
)
|
||||
.await
|
||||
);
|
||||
history.push(Message::user().with_tool_response("2", Ok(CallToolResult::success(vec![]))));
|
||||
assert!(
|
||||
denied(
|
||||
&inspector,
|
||||
"s1",
|
||||
request("3", "read_file", args.clone()),
|
||||
&history
|
||||
)
|
||||
.await
|
||||
);
|
||||
|
||||
// A different call resets the consecutive counter.
|
||||
assert!(
|
||||
!denied(
|
||||
&inspector,
|
||||
"s1",
|
||||
request("4", "list_dir", object!({})),
|
||||
&history
|
||||
)
|
||||
.await
|
||||
);
|
||||
assert!(!denied(&inspector, "s1", request("5", "read_file", args), &history).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inspect_resets_on_new_user_message_and_isolates_sessions() {
|
||||
let inspector = RepetitionInspector::new(Some(1));
|
||||
let args = object!({"q": "x"});
|
||||
let mut history = vec![Message::user().with_text("第一轮")];
|
||||
|
||||
assert!(
|
||||
!denied(
|
||||
&inspector,
|
||||
"s1",
|
||||
request("1", "search", args.clone()),
|
||||
&history
|
||||
)
|
||||
.await
|
||||
);
|
||||
assert!(
|
||||
!denied(
|
||||
&inspector,
|
||||
"s2",
|
||||
request("1", "search", args.clone()),
|
||||
&history
|
||||
)
|
||||
.await
|
||||
);
|
||||
assert!(
|
||||
denied(
|
||||
&inspector,
|
||||
"s1",
|
||||
request("2", "search", args.clone()),
|
||||
&history
|
||||
)
|
||||
.await
|
||||
);
|
||||
|
||||
history.push(Message::assistant().with_text("好的"));
|
||||
history.push(Message::user().with_text("第二轮"));
|
||||
assert!(!denied(&inspector, "s1", request("3", "search", args), &history).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inspect_is_disabled_without_limit() {
|
||||
let inspector = RepetitionInspector::new(None);
|
||||
assert!(!inspector.is_enabled());
|
||||
let history = vec![Message::user().with_text("hi")];
|
||||
for i in 0..10 {
|
||||
let req = request(&i.to_string(), "read_file", object!({"path": "a"}));
|
||||
assert!(!denied(&inspector, "s1", req, &history).await);
|
||||
}
|
||||
}
|
||||
|
||||
// This test targets RepetitionInspector::check_tool_call
|
||||
// It verifies that:
|
||||
// - consecutive identical tool calls are allowed up to max_repetitions times
|
||||
|
||||
Reference in New Issue
Block a user