diff --git a/akode-rs/config/src/config_toml.rs b/akode-rs/config/src/config_toml.rs index da4cec93..f1b19289 100644 --- a/akode-rs/config/src/config_toml.rs +++ b/akode-rs/config/src/config_toml.rs @@ -795,6 +795,13 @@ pub struct AgentToml { /// the tests") without calling any tool, send it one short reminder and let it continue, /// at most this many times per turn. Default: 1. `0` disables the reminder. pub announce_nudges: Option, + /// Stop the turn when the model calls the same tool with the same arguments this many + /// times in a row, whatever the result (polling tools such as `write_stdin` excluded). + /// Default: 5. `0` disables the check. + pub max_identical_tool_calls: Option, + /// Stop the answer while it streams when the same piece of text repeats this many times + /// back to back (code blocks excluded). Default: 10. `0` disables the check. + pub max_repeated_text: Option, } /// `[memoria]` table: session-start briefing and session delivery of the imeAI `memoria` plugin. diff --git a/akode-rs/core/config.schema.json b/akode-rs/core/config.schema.json index c881b9a9..b240325a 100644 --- a/akode-rs/core/config.schema.json +++ b/akode-rs/core/config.schema.json @@ -41,11 +41,23 @@ "minimum": 0.0, "type": "integer" }, + "max_identical_tool_calls": { + "description": "Stop the turn when the model calls the same tool with the same arguments this many times in a row, whatever the result (polling tools such as `write_stdin` excluded). Default: 5. `0` disables the check.", + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, "max_repeated_failures": { "description": "Stop the turn when the model repeats the same tool call and gets the same failure this many times in a row. Default: 3. `0` disables the check.", "format": "uint32", "minimum": 0.0, "type": "integer" + }, + "max_repeated_text": { + "description": "Stop the answer while it streams when the same piece of text repeats this many times back to back (code blocks excluded). Default: 10. `0` disables the check.", + "format": "uint32", + "minimum": 0.0, + "type": "integer" } }, "type": "object" diff --git a/akode-rs/core/src/compact.rs b/akode-rs/core/src/compact.rs index e419f34c..a7b16c51 100644 --- a/akode-rs/core/src/compact.rs +++ b/akode-rs/core/src/compact.rs @@ -265,6 +265,15 @@ async fn run_compact_task_inner_impl( sess.services .executed_tool_calls .attach_to_compaction_prompt(&mut turn_input); + // The summarizer does not need the raw output of old tool calls: a short placeholder + // keeps the call visible and the compaction prompt much shorter. + let cleared = crate::tool_output_clearing::clear_old_tool_outputs( + &mut turn_input, + crate::tool_output_clearing::KEEP_RECENT_TOOL_OUTPUTS, + ); + if cleared > 0 { + tracing::info!(cleared_chars = cleared, "old tool outputs cleared before compaction"); + } let turn_input_len = turn_input.len(); let base_instructions = if turn_input .iter() diff --git a/akode-rs/core/src/config/mod.rs b/akode-rs/core/src/config/mod.rs index f96a2c84..2a700fa5 100644 --- a/akode-rs/core/src/config/mod.rs +++ b/akode-rs/core/src/config/mod.rs @@ -696,6 +696,12 @@ pub const DEFAULT_MAX_REPEATED_FAILURES: u32 = 3; /// Default for `[agent] announce_nudges`. pub const DEFAULT_ANNOUNCE_NUDGES: u32 = 1; +/// Default for `[agent] max_identical_tool_calls` (the threshold of Gemini CLI). +pub const DEFAULT_MAX_IDENTICAL_TOOL_CALLS: u32 = 5; + +/// Default for `[agent] max_repeated_text` (the threshold of Gemini CLI). +pub const DEFAULT_MAX_REPEATED_TEXT: u32 = 10; + /// Session delivery of the `memoria` plugin (`[memoria] deliver_sessions`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MemoriaDeliveryConfig { @@ -1283,6 +1289,14 @@ pub struct Config { /// (`[agent] announce_nudges`). `0` disables it. pub announce_nudges: u32, + /// Loop protection: stop the turn after this many identical tool calls in a row, whatever + /// the result (`[agent] max_identical_tool_calls`). `0` disables the check. + pub max_identical_tool_calls: u32, + + /// Loop protection: stop a streaming answer that repeats the same text this many times + /// back to back (`[agent] max_repeated_text`). `0` disables the check. + pub max_repeated_text: u32, + /// Session-start briefing of the `memoria` plugin (`[memoria]`). pub memoria_briefing: MemoriaBriefingConfig, @@ -4293,6 +4307,16 @@ impl Config { .as_ref() .and_then(|agent| agent.announce_nudges) .unwrap_or(DEFAULT_ANNOUNCE_NUDGES); + let max_identical_tool_calls = cfg + .agent + .as_ref() + .and_then(|agent| agent.max_identical_tool_calls) + .unwrap_or(DEFAULT_MAX_IDENTICAL_TOOL_CALLS); + let max_repeated_text = cfg + .agent + .as_ref() + .and_then(|agent| agent.max_repeated_text) + .unwrap_or(DEFAULT_MAX_REPEATED_TEXT); let memoria_briefing = { let defaults = MemoriaBriefingConfig::default(); let toml = cfg.memoria.clone().unwrap_or_default(); @@ -4935,6 +4959,8 @@ impl Config { background_terminal_max_timeout, max_repeated_failures, announce_nudges, + max_identical_tool_calls, + max_repeated_text, memoria_briefing, memoria_delivery, memoria_anchors, diff --git a/akode-rs/core/src/lib.rs b/akode-rs/core/src/lib.rs index 4bc58cda..a2883c27 100644 --- a/akode-rs/core/src/lib.rs +++ b/akode-rs/core/src/lib.rs @@ -42,6 +42,7 @@ mod compact_token_budget; pub mod compaction_metadata; mod merge_system_messages; mod tool_order; +mod tool_output_clearing; mod thread_startup_metadata; pub use akode_network_proxy::EnvironmentNetworkPolicy; pub use akode_network_proxy::NetworkDomainPermission; diff --git a/akode-rs/core/src/session/loop_guard.rs b/akode-rs/core/src/session/loop_guard.rs index 2c0fd4a2..6fb63d07 100644 --- a/akode-rs/core/src/session/loop_guard.rs +++ b/akode-rs/core/src/session/loop_guard.rs @@ -1,4 +1,6 @@ -//! Loop protection: stops a turn when the model keeps repeating the same failing tool call. +//! Loop protection: stops a turn when the model keeps repeating the same failing tool call, +//! the same tool call whatever its result, or the same text while it streams (the last two in +//! the style of Gemini CLI's loop detection). use akode_protocol::models::FunctionCallOutputPayload; use akode_protocol::models::ResponseItem; @@ -7,6 +9,10 @@ use std::collections::HashMap; pub(crate) const REPEATED_FAILURE_MESSAGE: &str = "Il modello ripete lo stesso comando senza risultato: turno interrotto."; +pub(crate) const IDENTICAL_CALLS_MESSAGE: &str = + "Il modello ripete la stessa chiamata a strumento con gli stessi argomenti: turno interrotto."; +pub(crate) const REPEATED_TEXT_MESSAGE: &str = + "Il modello ripete lo stesso testo: risposta interrotta."; pub(crate) const SANDBOX_HINT: &str = "Sembra un blocco della sandbox: usa /permissions per concedere più accesso."; @@ -66,6 +72,179 @@ pub(crate) fn repeated_failure_message<'a>( Some(message) } +/// Tools that are legitimately called again with the same arguments: polling a running +/// process or waiting for sub-agents. +const POLLING_TOOLS: &[&str] = &["write_stdin", "wait_agent", "wait"]; + +/// Returns the message to show when the model made the same tool call (same tool, same +/// arguments) in `threshold` consecutive responses of the current turn, whatever the result. +/// Calls of one response (a parallel batch, with no output in between) count once. +/// `threshold == 0` disables the check. +pub(crate) fn identical_calls_message<'a>( + items: impl IntoIterator, + threshold: u32, +) -> Option { + if threshold == 0 { + return None; + } + // One entry per response with tool calls: `Some(signature)` when all its calls are the + // same, `None` when they differ. + let mut steps: Vec> = Vec::new(); + let mut batch: Vec<(String, String)> = Vec::new(); + let flush = |batch: &mut Vec<(String, String)>, steps: &mut Vec>| { + if let Some(first) = batch.first().cloned() { + let same = batch.iter().all(|(_, signature)| *signature == first.1); + steps.push(same.then_some(first)); + } + batch.clear(); + }; + for item in items { + match item { + ResponseItem::Message { role, .. } if role == "user" => { + batch.clear(); + steps.clear(); + } + ResponseItem::FunctionCall { + name, + namespace, + arguments, + .. + } => batch.push((name.clone(), call_signature(name, namespace.as_deref(), arguments))), + ResponseItem::CustomToolCall { + name, + namespace, + input, + .. + } => batch.push((name.clone(), call_signature(name, namespace.as_deref(), input))), + ResponseItem::LocalShellCall { action, .. } => { + batch.push(("local_shell".to_string(), format!("local_shell:{action:?}"))); + } + ResponseItem::FunctionCallOutput { .. } | ResponseItem::CustomToolCallOutput { .. } => { + flush(&mut batch, &mut steps); + } + _ => {} + } + } + flush(&mut batch, &mut steps); + let (last_name, last) = steps.last()?.as_ref()?; + if POLLING_TOOLS + .iter() + .any(|tool| last_name == tool || last_name.ends_with(&format!("__{tool}"))) + { + return None; + } + let streak = steps + .iter() + .rev() + .take_while(|step| step.as_ref().is_some_and(|(_, signature)| signature == last)) + .count(); + (streak >= threshold as usize).then(|| IDENTICAL_CALLS_MESSAGE.to_string()) +} + +/// Length of the text window compared while streaming. +const TEXT_CHUNK: usize = 50; +/// Shorter repeated units are dividers (`=====`, `|---|`), not loops. +const MIN_REPEATED_UNIT: usize = 20; +/// Beyond this size the stream is no longer checked (memory bound). +const MAX_CHECKED_TEXT: usize = 200_000; + +/// Detects a model stuck repeating the same text while it streams: the same unit of text +/// (at least [`MIN_REPEATED_UNIT`] characters, with letters or digits) repeated `threshold` +/// times back to back. Code blocks reset the check, since code repeats legitimately. +#[derive(Debug)] +pub(crate) struct TextLoopDetector { + threshold: usize, + text: String, + next: usize, + positions: HashMap>, + in_code: bool, +} + +impl TextLoopDetector { + /// `threshold == 0` disables the check. + pub(crate) fn new(threshold: u32) -> Self { + Self { + threshold: threshold as usize, + text: String::new(), + next: 0, + positions: HashMap::new(), + in_code: false, + } + } + + /// Adds a streamed delta; returns true when the text has started looping. + pub(crate) fn push(&mut self, delta: &str) -> bool { + if self.threshold < 2 || self.text.len() > MAX_CHECKED_TEXT { + return false; + } + let fences = delta.matches("```").count(); + if fences > 0 { + // Code repeats legitimately: skip it and start over after the closing fence. + if fences % 2 == 1 { + self.in_code = !self.in_code; + } + self.text.clear(); + self.positions.clear(); + self.next = 0; + if !self.in_code { + self.text + .push_str(delta.rsplit("```").next().unwrap_or_default()); + } + return false; + } + if self.in_code { + return false; + } + self.text.push_str(delta); + while self.next + TEXT_CHUNK <= self.text.len() { + let start = self.next; + self.next += 1; + let end = start + TEXT_CHUNK; + if !self.text.is_char_boundary(start) || !self.text.is_char_boundary(end) { + continue; + } + let hash = { + use std::hash::Hash; + use std::hash::Hasher; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + self.text[start..end].hash(&mut hasher); + hasher.finish() + }; + let positions = self.positions.entry(hash).or_default(); + positions.push(start); + if positions.len() >= self.threshold + && is_back_to_back_repetition( + &self.text, + &positions[positions.len() - self.threshold..], + ) + { + return true; + } + } + false + } +} + +/// True when `starts` are evenly spaced by a period of at least [`MIN_REPEATED_UNIT`] and the +/// text of each period is identical and contains letters or digits. +fn is_back_to_back_repetition(text: &str, starts: &[usize]) -> bool { + let period = starts[1] - starts[0]; + if period < MIN_REPEATED_UNIT || starts.windows(2).any(|pair| pair[1] - pair[0] != period) { + return false; + } + let first = starts[0]; + let Some(unit) = text.get(first..first + period) else { + return false; + }; + if !unit.chars().any(char::is_alphanumeric) { + return false; + } + starts[1..] + .iter() + .all(|&start| text.get(start..start + period).is_none_or(|other| other == unit) + && text.get(start - period..start) == Some(unit)) +} + fn turn_tool_results<'a>(items: impl IntoIterator) -> Vec { let mut signatures: HashMap = HashMap::new(); let mut results = Vec::new(); diff --git a/akode-rs/core/src/session/loop_guard_tests.rs b/akode-rs/core/src/session/loop_guard_tests.rs index 71c0608d..04a3d47f 100644 --- a/akode-rs/core/src/session/loop_guard_tests.rs +++ b/akode-rs/core/src/session/loop_guard_tests.rs @@ -131,3 +131,110 @@ fn prompt_over_context_warning_text() { Some("Il prompt iniziale (~9000 token) supera la finestra del modello (8192).".to_string()) ); } + +fn named_call(call_id: &str, name: &str, arguments: serde_json::Value) -> ResponseItem { + serde_json::from_value(json!({ + "type": "function_call", + "name": name, + "arguments": arguments.to_string(), + "call_id": call_id, + })) + .expect("function call") +} + +#[test] +fn identical_calls_stop_the_turn_whatever_the_result() { + let mut items = vec![user("leggi il file")]; + for index in 0..5 { + let id = format!("c{index}"); + items.push(named_call(&id, "exec_command", json!({"cmd": "cat a.txt"}))); + items.push(output(&id, "contenuto", Some(true))); + } + assert_eq!( + identical_calls_message(&items[..items.len() - 2], 5), + None, + "four calls are not a loop yet" + ); + assert_eq!( + identical_calls_message(&items, 5).as_deref(), + Some(IDENTICAL_CALLS_MESSAGE) + ); + assert_eq!(identical_calls_message(&items, 0), None); +} + +#[test] +fn different_arguments_polling_or_a_new_user_message_reset_identical_calls() { + let mut items = vec![user("compila")]; + for index in 0..6 { + let id = format!("p{index}"); + items.push(named_call(&id, "write_stdin", json!({"session_id": 1, "chars": ""}))); + items.push(output(&id, "in corso", Some(true))); + } + assert_eq!(identical_calls_message(&items, 5), None, "polling a process is not a loop"); + + let mut items = vec![user("cerca")]; + for index in 0..6 { + let id = format!("s{index}"); + items.push(named_call(&id, "exec_command", json!({"cmd": format!("grep -n x{index} a")}))); + items.push(output(&id, "", Some(true))); + } + assert_eq!(identical_calls_message(&items, 5), None); + + // One response with many identical parallel calls is a single step. + let mut items = vec![user("aggiorna il piano")]; + for index in 0..8 { + items.push(named_call(&format!("u{index}"), "update_plan", json!({"plan": []}))); + } + for index in 0..8 { + items.push(output(&format!("u{index}"), "ok", Some(true))); + } + assert_eq!(identical_calls_message(&items, 5), None); + + let mut items = Vec::new(); + for index in 0..4 { + let id = format!("a{index}"); + items.push(named_call(&id, "exec_command", json!({"cmd": "ls"}))); + items.push(output(&id, "a.txt", Some(true))); + } + items.push(user("ancora")); + items.push(named_call("b", "exec_command", json!({"cmd": "ls"}))); + assert_eq!(identical_calls_message(&items, 5), None); +} + +fn stream_into(detector: &mut TextLoopDetector, text: &str, piece: usize) -> bool { + let chars: Vec = text.chars().collect(); + chars + .chunks(piece) + .any(|chunk| detector.push(&chunk.iter().collect::())) +} + +#[test] +fn repeated_sentence_while_streaming_is_a_loop() { + let sentence = "Controllo di nuovo il file di configurazione principale. "; + let mut detector = TextLoopDetector::new(10); + assert!(stream_into(&mut detector, &sentence.repeat(12), 7)); + + let mut early = TextLoopDetector::new(10); + assert!(!stream_into(&mut early, &sentence.repeat(8), 7), "8 repetitions are below the threshold"); +} + +#[test] +fn normal_text_lists_dividers_and_code_are_not_loops() { + let mut detector = TextLoopDetector::new(10); + let list: String = (1..=40) + .map(|index| format!("- Passo {index}: controlla il modulo m{index} e i suoi test.\n")) + .collect(); + assert!(!stream_into(&mut detector, &list, 9)); + + let mut divider = TextLoopDetector::new(10); + assert!(!stream_into(&mut divider, &format!("{}\n", "=".repeat(400)), 13)); + let mut table = TextLoopDetector::new(10); + assert!(!stream_into(&mut table, &"|---|---|---|---|---|---|\n".repeat(30), 11)); + + let mut code = TextLoopDetector::new(10); + let block = format!("```rust\n{}```\nFatto.", " assert_eq!(valore(), 1);\n".repeat(15)); + assert!(!stream_into(&mut code, &block, 6), "code is skipped"); + + let mut disabled = TextLoopDetector::new(0); + assert!(!stream_into(&mut disabled, &"ripeto sempre la stessa frase lunga. ".repeat(30), 5)); +} diff --git a/akode-rs/core/src/session/turn.rs b/akode-rs/core/src/session/turn.rs index a84cfcf3..ec517819 100644 --- a/akode-rs/core/src/session/turn.rs +++ b/akode-rs/core/src/session/turn.rs @@ -712,12 +712,22 @@ pub(crate) async fn run_turn( ); } - if needs_follow_up - && let Some(message) = super::loop_guard::repeated_failure_message( - sess.clone_history().await.raw_items(), + let loop_message = if needs_follow_up { + let history = sess.clone_history().await; + super::loop_guard::repeated_failure_message( + history.raw_items(), turn_context.config.max_repeated_failures, ) - { + .or_else(|| { + super::loop_guard::identical_calls_message( + history.raw_items(), + turn_context.config.max_identical_tool_calls, + ) + }) + } else { + None + }; + if let Some(message) = loop_message { let event = EventMsg::Error(ErrorEvent { misalignment: None, message, @@ -2776,6 +2786,11 @@ async fn try_run_sampling_request( let defer_streamed_turn_items_for_contributors = !sess.services.extensions.turn_item_contributors().is_empty(); let mut active_item_is_streaming_to_client = false; + // Loop protection on the streamed text (`[agent] max_repeated_text`): answer and reasoning. + let mut answer_loop = + super::loop_guard::TextLoopDetector::new(turn_context.config.max_repeated_text); + let mut reasoning_loop = + super::loop_guard::TextLoopDetector::new(turn_context.config.max_repeated_text); let receiving_span = trace_span!("receiving_stream"); let outcome: CodexResult = loop { if response_completed && resampling.accepted_output.is_empty() { @@ -3275,6 +3290,11 @@ async fn try_run_sampling_request( } } ResponseEvent::OutputTextDelta(delta) => { + if answer_loop.push(&delta) { + break Err(CodexErr::Fatal( + super::loop_guard::REPEATED_TEXT_MESSAGE.to_string(), + )); + } // In review child threads, suppress assistant text deltas; the // UI will show a selection popup from the final ReviewOutput. if let Some(active) = active_item.as_ref() { @@ -3404,6 +3424,11 @@ async fn try_run_sampling_request( delta, content_index, } => { + if reasoning_loop.push(&delta) { + break Err(CodexErr::Fatal( + super::loop_guard::REPEATED_TEXT_MESSAGE.to_string(), + )); + } if let Some(active) = active_item.as_ref() { if !active_item_is_streaming_to_client { continue; diff --git a/akode-rs/core/src/tool_output_clearing.rs b/akode-rs/core/src/tool_output_clearing.rs new file mode 100644 index 00000000..9c249008 --- /dev/null +++ b/akode-rs/core/src/tool_output_clearing.rs @@ -0,0 +1,122 @@ +//! Tool-output clearing before compaction. +//! +//! The raw output of old tool calls (file listings, logs, test runs) is the bulkiest and least +//! useful part of a long history. Before the summary request, outputs older than the most +//! recent ones are replaced by a short placeholder: the summarizer reads a much shorter prompt +//! (on a CPU server every token of prompt is seconds of waiting) and still sees which tool was +//! called with which arguments, since the calls themselves stay. + +use akode_protocol::models::FunctionCallOutputBody; +use akode_protocol::models::FunctionCallOutputPayload; +use akode_protocol::models::ResponseItem; + +/// Most recent tool outputs kept verbatim. +pub(crate) const KEEP_RECENT_TOOL_OUTPUTS: usize = 3; +/// Outputs up to this size are kept: the placeholder would not save anything. +const MIN_CLEARED_CHARS: usize = 400; + +/// Replaces the body of tool outputs older than the last `keep_recent` with a placeholder. +/// Returns the number of characters removed. +pub(crate) fn clear_old_tool_outputs(items: &mut [ResponseItem], keep_recent: usize) -> usize { + let outputs: Vec = items + .iter() + .enumerate() + .filter(|(_, item)| output_payload(item).is_some()) + .map(|(index, _)| index) + .collect(); + let old = outputs.len().saturating_sub(keep_recent); + let mut removed = 0; + for &index in &outputs[..old] { + let Some(payload) = output_payload_mut(&mut items[index]) else { + continue; + }; + let size = body_chars(&payload.body); + if size <= MIN_CLEARED_CHARS { + continue; + } + let placeholder = format!( + "[tool output cleared before compaction: {size} characters; run the tool again if it is still needed]" + ); + removed += size.saturating_sub(placeholder.chars().count()); + payload.body = FunctionCallOutputBody::Text(placeholder); + } + removed +} + +fn output_payload(item: &ResponseItem) -> Option<&FunctionCallOutputPayload> { + match item { + ResponseItem::FunctionCallOutput { output, .. } + | ResponseItem::CustomToolCallOutput { output, .. } => Some(output), + _ => None, + } +} + +fn output_payload_mut(item: &mut ResponseItem) -> Option<&mut FunctionCallOutputPayload> { + match item { + ResponseItem::FunctionCallOutput { output, .. } + | ResponseItem::CustomToolCallOutput { output, .. } => Some(output), + _ => None, + } +} + +fn body_chars(body: &FunctionCallOutputBody) -> usize { + match body { + FunctionCallOutputBody::Text(text) => text.chars().count(), + // Images and other items are bulky too: count them as text of their JSON size. + FunctionCallOutputBody::ContentItems(items) => serde_json::to_string(items) + .map(|json| json.chars().count()) + .unwrap_or_default(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + fn output(call_id: &str, text: &str) -> ResponseItem { + ResponseItem::FunctionCallOutput { + id: None, + call_id: Some(call_id.to_string()), + name: None, + namespace: None, + output: FunctionCallOutputPayload::from_text(text.to_string()), + internal_chat_message_metadata_passthrough: None, + } + } + + fn text_of(item: &ResponseItem) -> String { + output_payload(item) + .and_then(|payload| payload.body.to_text()) + .unwrap_or_default() + } + + #[test] + fn old_large_outputs_become_placeholders_and_recent_ones_stay() { + let big = "x".repeat(5_000); + let mut items = vec![ + output("c1", &big), + output("c2", "short"), + output("c3", &big), + output("c4", &big), + output("c5", &big), + ]; + + let removed = clear_old_tool_outputs(&mut items, 3); + + assert!(text_of(&items[0]).starts_with("[tool output cleared before compaction: 5000 characters")); + assert_eq!(text_of(&items[1]), "short"); + for item in &items[2..] { + assert_eq!(text_of(item), big); + } + assert!(removed > 4_800, "{removed}"); + } + + #[test] + fn nothing_to_clear_with_few_outputs() { + let big = "y".repeat(2_000); + let mut items = vec![output("c1", &big), output("c2", &big)]; + assert_eq!(clear_old_tool_outputs(&mut items, 3), 0); + assert_eq!(text_of(&items[0]), big); + } +} diff --git a/akode-rs/core/src/tools/handlers/unified_exec/preparation.rs b/akode-rs/core/src/tools/handlers/unified_exec/preparation.rs index 6eafbb99..5c0dd7e2 100644 --- a/akode-rs/core/src/tools/handlers/unified_exec/preparation.rs +++ b/akode-rs/core/src/tools/handlers/unified_exec/preparation.rs @@ -75,13 +75,14 @@ impl PreparedExecCommand { Some("windows") | Some(_) => DangerousCommandPlatform::Windows, None => DangerousCommandPlatform::host(), }; - session + let approval_policy = step.settings.approval_policy(); + let requirement = session .services .exec_policy .create_exec_approval_requirement_for_shell( ExecApprovalRequest { command: &self.resolved.command, - approval_policy: step.settings.approval_policy(), + approval_policy, permission_profile: environment.permission_profile().clone(), environment_policy: environment.config().exec_policy.as_ref(), windows_sandbox_level: windows_sandbox_level_for_legacy_checks( @@ -99,7 +100,17 @@ impl PreparedExecCommand { configured_shell, command_platform, ) - .await + .await; + // POSIX shells only: the check parses `rm`/`find` and POSIX paths. + if command_platform == DangerousCommandPlatform::Posix { + return protect_recursive_deletion( + requirement, + &self.resolved.command, + &self.cwd, + approval_policy, + ); + } + requirement } pub(crate) fn approval_action( @@ -316,3 +327,129 @@ impl<'a> ParsedExecCommand<'a> { }) } } + +/// Recursive deletions of protected paths (root, home, repository root, working directory, +/// anything outside it, run-time targets) always need a fresh human decision, whatever the +/// sandbox, the approval mode or the rules; where nobody can be asked they are refused. +fn protect_recursive_deletion( + requirement: ExecApprovalRequirement, + command: &[String], + cwd: &PathUri, + approval_policy: akode_protocol::protocol::AskForApproval, +) -> ExecApprovalRequirement { + use akode_shell_command::recursive_deletion::DeletionContext; + use akode_shell_command::recursive_deletion::protected_recursive_deletion; + + if matches!(requirement, ExecApprovalRequirement::Forbidden { .. }) { + return requirement; + } + let Ok(cwd) = cwd.to_abs_path() else { + return requirement; + }; + let cwd = cwd.as_path().to_path_buf(); + let repo_root = cwd + .ancestors() + .find(|dir| dir.join(".git").exists()) + .map(Path::to_path_buf); + let context = DeletionContext { + home: dirs::home_dir(), + repo_root, + cwd, + }; + let Some(reason) = protected_recursive_deletion(command, &context) else { + return requirement; + }; + tracing::warn!(%reason, "protected recursive deletion"); + // Like the other dangerous commands, the prompt is allowed in granular modes; only + // `never` (full access without prompts) has nobody to ask. + if matches!(approval_policy, akode_protocol::protocol::AskForApproval::Never) { + ExecApprovalRequirement::Forbidden { + reason: format!( + "rifiutato: {reason}. aKode non esegue cancellazioni ricorsive di percorsi protetti senza la conferma dell'utente: chiedigli di farlo a mano, se serve davvero." + ), + } + } else if prompt_is_rejected_by_policy(approval_policy, /*prompt_is_rule*/ true).is_some() { + // Granular modes that refuse rule prompts still ask for dangerous commands (as for + // `rm -f`): a plain prompt with no reusable rule, so the user still decides. + ExecApprovalRequirement::NeedsApproval { + reason: Some(format!("{reason}: serve la tua conferma")), + proposed_execpolicy_amendment: None, + } + } else { + // A fresh human decision, never a saved rule or an automatic review. + ExecApprovalRequirement::NeedsHumanApproval { + reason: Some(format!("{reason}: serve la tua conferma")), + } + } +} + +#[cfg(test)] +mod recursive_deletion_tests { + use super::*; + use akode_protocol::protocol::AskForApproval; + + fn zsh(script: &str) -> Vec { + vec!["/bin/zsh".to_string(), "-lc".to_string(), script.to_string()] + } + + fn skip() -> ExecApprovalRequirement { + ExecApprovalRequirement::Skip { + bypass_sandbox: false, + proposed_execpolicy_amendment: None, + } + } + + fn cwd() -> PathUri { + let dir = std::env::temp_dir().join("akode-rm-guard"); + PathUri::from_host_native_path(dir).expect("cwd") + } + + #[test] + fn full_access_refuses_and_other_modes_ask_a_human() { + let home = zsh("rm -rf ~"); + assert!(matches!( + protect_recursive_deletion(skip(), &home, &cwd(), AskForApproval::Never), + ExecApprovalRequirement::Forbidden { reason } if reason.contains("cartella home") + )); + assert!(matches!( + protect_recursive_deletion(skip(), &home, &cwd(), AskForApproval::OnRequest), + ExecApprovalRequirement::NeedsHumanApproval { reason: Some(reason) } + if reason.contains("cartella home") + )); + // Granular modes without rule prompts still ask (like the other dangerous commands). + let granular = AskForApproval::Granular(akode_protocol::protocol::GranularApprovalConfig { + sandbox_approval: false, + rules: false, + skill_approval: false, + request_permissions: true, + mcp_elicitations: true, + }); + assert!(matches!( + protect_recursive_deletion(skip(), &home, &cwd(), granular), + ExecApprovalRequirement::NeedsApproval { + proposed_execpolicy_amendment: None, + .. + } + )); + // Rules that would allow the command do not lift the protection. + assert!(matches!( + protect_recursive_deletion(skip(), &zsh("rm -rf $OUT/"), &cwd(), AskForApproval::OnRequest), + ExecApprovalRequirement::NeedsHumanApproval { .. } + )); + } + + #[test] + fn ordinary_commands_keep_their_requirement() { + assert!(matches!( + protect_recursive_deletion(skip(), &zsh("rm -rf build"), &cwd(), AskForApproval::Never), + ExecApprovalRequirement::Skip { .. } + )); + let forbidden = ExecApprovalRequirement::Forbidden { + reason: "blocked".to_string(), + }; + assert!(matches!( + protect_recursive_deletion(forbidden, &zsh("rm -rf /"), &cwd(), AskForApproval::OnRequest), + ExecApprovalRequirement::Forbidden { reason } if reason == "blocked" + )); + } +} diff --git a/akode-rs/model-provider/src/capabilities_tests.rs b/akode-rs/model-provider/src/capabilities_tests.rs index c9b76ea1..f454e43d 100644 --- a/akode-rs/model-provider/src/capabilities_tests.rs +++ b/akode-rs/model-provider/src/capabilities_tests.rs @@ -44,3 +44,22 @@ fn tool_namespaces_are_flattened_unless_the_provider_declares_them() { }); assert!(ProviderCapabilities::from_config(&info).tool_namespaces); } + +/// Compaction runs on the configured provider: local and self-hosted servers use the inline +/// summary on their own `/responses` (never a remote compaction endpoint). +#[test] +fn local_providers_compact_inline_on_their_own_endpoint() { + for (name, base_url) in [ + ("imeAI", "http://192.168.40.25:8080/v1"), + ("ollama", "http://localhost:11434/v1"), + ("lmstudio", "http://localhost:1234/v1"), + ("openrouter", "https://openrouter.ai/api/v1"), + ] { + let info = ModelProviderInfo::create_responses_provider(name, Some(base_url.to_string())); + assert_eq!( + ProviderCapabilities::from_config(&info).remote_compaction, + RemoteCompactionSupport::Unsupported, + "{name}" + ); + } +} diff --git a/akode-rs/shell-command/src/command_safety/mod.rs b/akode-rs/shell-command/src/command_safety/mod.rs index 44d0103a..fa9713cb 100644 --- a/akode-rs/shell-command/src/command_safety/mod.rs +++ b/akode-rs/shell-command/src/command_safety/mod.rs @@ -6,4 +6,5 @@ mod powershell_parser; mod powershell_tree_sitter; pub mod is_dangerous_command; +pub mod recursive_deletion; pub(crate) use powershell_tree_sitter::try_parse_powershell_commands; diff --git a/akode-rs/shell-command/src/command_safety/recursive_deletion.rs b/akode-rs/shell-command/src/command_safety/recursive_deletion.rs new file mode 100644 index 00000000..191f2094 --- /dev/null +++ b/akode-rs/shell-command/src/command_safety/recursive_deletion.rs @@ -0,0 +1,358 @@ +//! Path protection for recursive deletions (`rm -r`, `rm -rf`, `find ... -delete`). +//! +//! The worst documented agent accidents are recursive deletions generated by the agent itself: +//! a wrong `~` expansion, an empty variable (`rm -rf $DIR/`), a cleanup that climbs out of the +//! project. Pattern blocklists do not see variables; this check resolves each target against +//! the working directory and protects, whatever the sandbox or approval mode: +//! - the filesystem root and the home directory (and their ancestors); +//! - the repository root and the working directory itself (and their ancestors); +//! - anything outside the working directory; +//! - targets that are only known at run time (variables, command substitution, `xargs`). + +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use crate::bash::extract_bash_command; + +/// Where the command runs. +#[derive(Debug, Clone)] +pub struct DeletionContext { + pub cwd: PathBuf, + pub home: Option, + pub repo_root: Option, +} + +/// Returns why the command needs an explicit confirmation (or must be refused when nobody can +/// confirm), or `None` when it does not recursively delete a protected path. +pub fn protected_recursive_deletion(command: &[String], context: &DeletionContext) -> Option { + let script = match extract_bash_command(command) { + Some((_, script)) => script.to_string(), + None => shlex::try_join(command.iter().map(String::as_str)) + .unwrap_or_else(|_| command.join(" ")), + }; + for segment in split_segments(&script) { + let words = shlex::split(&segment).unwrap_or_else(|| { + segment + .split_whitespace() + .map(ToString::to_string) + .collect() + }); + for targets in deletion_targets(&words) { + if let Some(reason) = protected_targets(&targets, context) { + return Some(reason); + } + } + } + None +} + +/// Targets of the recursive deletions in one simple command. An empty list means the targets +/// are not in the command line (for example `xargs rm -rf`). +fn deletion_targets(words: &[String]) -> Vec> { + let mut found = Vec::new(); + for (index, word) in words.iter().enumerate() { + match executable_name(strip_substitution(word)) { + "rm" => { + let args = &words[index + 1..]; + let mut recursive = false; + let mut targets = Vec::new(); + let mut options_done = false; + for arg in args { + if !options_done && arg == "--" { + options_done = true; + } else if !options_done && arg == "--recursive" { + recursive = true; + } else if !options_done && arg.starts_with("--") { + } else if !options_done && arg.starts_with('-') && arg.len() > 1 { + recursive |= arg.contains('r') || arg.contains('R'); + } else { + targets.push(arg.clone()); + } + } + if recursive { + found.push(targets); + } + } + "find" => { + let args = &words[index + 1..]; + let deletes = args.iter().enumerate().any(|(position, arg)| { + arg == "-delete" + || (matches!(arg.as_str(), "-exec" | "-execdir" | "-ok" | "-okdir") + && args + .get(position + 1) + .is_some_and(|next| executable_name(next) == "rm")) + }); + if deletes { + let roots: Vec = args + .iter() + .take_while(|arg| !arg.starts_with('-') && *arg != "(" && *arg != "!") + .cloned() + .collect(); + found.push(if roots.is_empty() { + vec![".".to_string()] + } else { + roots + }); + } + } + _ => {} + } + } + found +} + +fn protected_targets(targets: &[String], context: &DeletionContext) -> Option { + if targets.is_empty() { + return Some( + "cancellazione ricorsiva di percorsi non indicati nel comando (calcolati a runtime)" + .to_string(), + ); + } + for target in targets { + if target.starts_with('~') && target != "~" && !target.starts_with("~/") { + return Some(format!( + "cancellazione ricorsiva di `{target}`: colpisce la cartella home di un altro utente" + )); + } + let Some(path) = resolve(target, context) else { + return Some(format!( + "cancellazione ricorsiva di `{target}`, un percorso calcolato a runtime (variabile o sottocomando)" + )); + }; + let cwd = normalize(&context.cwd); + let what = if path == Path::new("/") { + Some("la radice del filesystem".to_string()) + } else if context + .home + .as_ref() + .is_some_and(|home| normalize(home).starts_with(&path)) + { + Some("la cartella home".to_string()) + } else if context + .repo_root + .as_ref() + .is_some_and(|root| normalize(root).starts_with(&path)) + { + Some("la radice del repository".to_string()) + } else if cwd.starts_with(&path) { + Some("la cartella di lavoro".to_string()) + } else if !path.starts_with(&cwd) { + Some(format!("un percorso fuori dalla cartella di lavoro ({})", cwd.display())) + } else { + None + }; + if let Some(what) = what { + return Some(format!( + "cancellazione ricorsiva di `{target}`: colpisce {what}" + )); + } + } + None +} + +/// Absolute, lexically normalized target; `None` when it depends on run-time values. A glob +/// stands for the directory whose contents it matches (`~/*` is the home directory). +fn resolve(target: &str, context: &DeletionContext) -> Option { + let home = context.home.as_ref(); + let expanded = if target == "~" { + home?.clone() + } else if let Some(rest) = target.strip_prefix("~/") { + home?.join(rest) + } else if let Some(rest) = target + .strip_prefix("$HOME") + .or_else(|| target.strip_prefix("${HOME}")) + && (rest.is_empty() || rest.starts_with('/')) + { + home?.join(rest.trim_start_matches('/')) + } else { + PathBuf::from(target) + }; + let text = expanded.to_string_lossy(); + if text.contains('$') || text.contains('`') { + return None; + } + let absolute = if expanded.is_absolute() { + expanded + } else { + context.cwd.join(expanded) + }; + // Cut at the first component with a glob: the deletion empties that directory. + let mut path = PathBuf::new(); + for component in absolute.components() { + let text = component.as_os_str().to_string_lossy(); + if text.contains(['*', '?', '[', '{']) { + break; + } + path.push(component); + } + Some(normalize(&path)) +} + +fn normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + out.pop(); + } + other => out.push(other), + } + } + if out.as_os_str().is_empty() { + PathBuf::from("/") + } else { + out + } +} + +fn executable_name(word: &str) -> &str { + word.rsplit('/').next().unwrap_or(word) +} + +/// `$(rm`, `` `rm ``, `(rm` and `{rm` start a command too. +fn strip_substitution(word: &str) -> &str { + word.trim_start_matches(['$', '(', '`', '{']) +} + +/// Splits a script into simple commands at `;`, `&`, `|`, newlines and parentheses outside +/// quotes. Coarse on purpose: when in doubt it splits, and every piece is checked. +fn split_segments(script: &str) -> Vec { + let mut segments = Vec::new(); + let mut current = String::new(); + let mut quote: Option = None; + let mut escaped = false; + // Inside `${...}`: its closing brace does not end a command. + let mut in_parameter = false; + for ch in script.chars() { + if escaped { + current.push(ch); + escaped = false; + continue; + } + if in_parameter { + current.push(ch); + in_parameter = ch != '}'; + continue; + } + if ch == '{' && quote != Some('\'') && current.ends_with('$') { + current.push(ch); + in_parameter = true; + continue; + } + match (quote, ch) { + (_, '\\') if quote != Some('\'') => { + current.push(ch); + escaped = true; + } + (Some(open), _) if ch == open => { + current.push(ch); + quote = None; + } + (Some(_), _) => current.push(ch), + (None, '\'' | '"') => { + current.push(ch); + quote = Some(ch); + } + (None, ';' | '&' | '|' | '\n' | ')' | '}') => { + segments.push(std::mem::take(&mut current)); + } + (None, _) => current.push(ch), + } + } + segments.push(current); + segments + .into_iter() + .filter(|segment| !segment.trim().is_empty()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + fn context() -> DeletionContext { + DeletionContext { + cwd: PathBuf::from("/Users/andrea/progetto/sub"), + home: Some(PathBuf::from("/Users/andrea")), + repo_root: Some(PathBuf::from("/Users/andrea/progetto")), + } + } + + fn zsh(script: &str) -> Vec { + vec!["/bin/zsh".to_string(), "-lc".to_string(), script.to_string()] + } + + fn check(script: &str) -> Option { + protected_recursive_deletion(&zsh(script), &context()) + } + + #[test] + fn protects_root_home_repo_and_cwd() { + for (script, what) in [ + ("rm -rf /", "la radice del filesystem"), + ("rm -rf ~", "la cartella home"), + ("rm -rf ~/", "la cartella home"), + ("rm -rf $HOME", "la cartella home"), + ("rm -fr ${HOME}/", "la cartella home"), + ("rm -r /Users", "la cartella home"), + ("rm -rf ~/*", "la cartella home"), + ("rm -rf /Users/andrea/progetto", "la radice del repository"), + ("rm -rf ..", "la radice del repository"), + ("rm -rf .", "la cartella di lavoro"), + ("rm -rf *", "la cartella di lavoro"), + ("rm -rf ./", "la cartella di lavoro"), + ("sudo rm -Rf /", "la radice del filesystem"), + ("/bin/rm --recursive --force ~", "la cartella home"), + ("find ~ -name '*.tmp' -delete", "la cartella home"), + ("find / -exec rm -rf {} +", "la radice del filesystem"), + ] { + let reason = check(script).unwrap_or_else(|| panic!("{script} not protected")); + assert!(reason.contains(what), "{script}: {reason}"); + } + } + + #[test] + fn protects_outside_cwd_and_run_time_targets() { + for script in [ + "rm -rf /tmp/build", + "rm -rf ../../altro", + "rm -rf ~/Documenti", + "rm -rf ~utente", + "rm -rf $DIR/", + "rm -rf \"$BUILD_DIR\"", + "rm -rf `pwd`/x", + "cd x && rm -rf $(dirname a)/b", + "ls | xargs rm -rf", + "echo $(rm -rf ~)", + "true; rm -rf /etc", + ] { + assert!(check(script).is_some(), "{script} not protected"); + } + } + + #[test] + fn allows_deletions_inside_the_working_directory() { + for script in [ + "rm -rf target", + "rm -rf ./build dist/*.o", + "rm -rf /Users/andrea/progetto/sub/cache", + "rm -f file.txt /tmp/x", + "rm -r -- node_modules", + "find . -name '*.pyc' -print", + "find build -name '*.o' -delete", + "cargo clean && rm -rf out", + "echo 'rm -rf /'", + ] { + assert_eq!(check(script), None, "{script}"); + } + } + + #[test] + fn direct_argv_is_checked_too() { + let command: Vec = ["rm", "-rf", "/"].iter().map(ToString::to_string).collect(); + assert!(protected_recursive_deletion(&command, &context()).is_some()); + } +} diff --git a/akode-rs/shell-command/src/lib.rs b/akode-rs/shell-command/src/lib.rs index 74b7572d..53cd4a50 100644 --- a/akode-rs/shell-command/src/lib.rs +++ b/akode-rs/shell-command/src/lib.rs @@ -12,3 +12,4 @@ pub mod parse_command; pub mod powershell; pub use command_safety::is_dangerous_command; +pub use command_safety::recursive_deletion; diff --git a/akode-rs/thread-manager-sample/src/main.rs b/akode-rs/thread-manager-sample/src/main.rs index a12558f4..785a8164 100644 --- a/akode-rs/thread-manager-sample/src/main.rs +++ b/akode-rs/thread-manager-sample/src/main.rs @@ -384,6 +384,8 @@ async fn new_config( code_mode: Default::default(), background_terminal_max_timeout: 300_000, max_repeated_failures: 3, + max_identical_tool_calls: 5, + max_repeated_text: 10, thread_unload_delay: std::time::Duration::from_secs(/*secs*/ 60), ghost_snapshot: GhostSnapshotConfig::default(), multi_agent_v2: MultiAgentV2Config::default(),