aKode: robustezza dell'agente (punto 4, blocco B)
- Compattazione: prima del riassunto l'output degli strumenti più vecchi (tutti tranne gli ultimi 3, sopra i 400 caratteri) diventa un segnaposto breve; le chiamate restano. La compattazione usa sempre il provider configurato: verificato, con un test sulle capacità dei provider. - Protezione dai loop in stile Gemini CLI, accanto a max_repeated_failures: [agent] max_identical_tool_calls (5 risposte di fila con la stessa chiamata, qualunque sia il risultato; esclusi write_stdin e wait_agent; le chiamate parallele di una risposta contano una volta) e [agent] max_repeated_text (lo stesso testo ripetuto 10 volte di seguito mentre arriva, nella risposta o nel ragionamento; esclusi blocchi di codice e separatori). - Cancellazioni ricorsive protette (rm -r, rm -rf, find -delete): radice, home, radice del repository, cartella di lavoro, percorsi fuori da essa o calcolati a runtime ($VAR, $(...), xargs) chiedono sempre la conferma dell'utente, anche con regole che li permetterebbero; in accesso completo vengono rifiutati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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"
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Item = &'a ResponseItem>,
|
||||
threshold: u32,
|
||||
) -> Option<String> {
|
||||
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<Option<(String, String)>> = Vec::new();
|
||||
let mut batch: Vec<(String, String)> = Vec::new();
|
||||
let flush = |batch: &mut Vec<(String, String)>, steps: &mut Vec<Option<(String, String)>>| {
|
||||
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<u64, Vec<usize>>,
|
||||
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<Item = &'a ResponseItem>) -> Vec<ToolResult> {
|
||||
let mut signatures: HashMap<String, String> = HashMap::new();
|
||||
let mut results = Vec::new();
|
||||
|
||||
@@ -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<char> = text.chars().collect();
|
||||
chars
|
||||
.chunks(piece)
|
||||
.any(|chunk| detector.push(&chunk.iter().collect::<String>()))
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
|
||||
@@ -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<SamplingRequestResult> = 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;
|
||||
|
||||
122
akode-rs/core/src/tool_output_clearing.rs
Normal file
122
akode-rs/core/src/tool_output_clearing.rs
Normal file
@@ -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<usize> = 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);
|
||||
}
|
||||
}
|
||||
@@ -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<String> {
|
||||
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"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user