aKode 0.2.0: protezione dai loop, errori del server chiari, pulizia
- Protezione dai loop: se il modello ripete lo stesso comando con lo stesso errore 3 volte di fila il turno si ferma con un messaggio chiaro (e un suggerimento su /permissions per i blocchi della sandbox); configurabile con [agent] max_repeated_failures (0 = disattivata). - Errori dello stream: si mostra il messaggio del server invece di "stream closed before response.completed"; il contesto superato (llama.cpp, vLLM) diventa un messaggio in italiano; avviso una volta se il prompt iniziale supera la finestra del modello. - Pulizia: tolta la logica morta per le chiavi OpenAI nel credential broker (prefisso "sk-", watermark, prefissi ignorati); link alla documentazione OpenAI nella TUI sostituiti con il README del repository; test dello snapshot del broker adattato al token GitHub. - Versione 0.2.0 e sezione Novità nel README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -120,8 +120,10 @@ impl Session {
|
||||
.then(|| self.build_effective_session_config(&state.session_configuration));
|
||||
state.session_configuration.original_config_do_not_use = Arc::clone(&config);
|
||||
if refresh_model_settings {
|
||||
state.session_configuration.model_info_overrides.context_windows =
|
||||
config.model_context_windows();
|
||||
state
|
||||
.session_configuration
|
||||
.model_info_overrides
|
||||
.context_windows = config.model_context_windows();
|
||||
self.services
|
||||
.model_client
|
||||
.set_model_settings(config.model_provider.models.clone());
|
||||
|
||||
177
akode-rs/core/src/session/loop_guard.rs
Normal file
177
akode-rs/core/src/session/loop_guard.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
//! Loop protection: stops a turn when the model keeps repeating the same failing tool call.
|
||||
|
||||
use akode_protocol::models::FunctionCallOutputPayload;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(crate) const REPEATED_FAILURE_MESSAGE: &str =
|
||||
"Il modello ripete lo stesso comando senza risultato: turno interrotto.";
|
||||
pub(crate) const SANDBOX_HINT: &str =
|
||||
"Sembra un blocco della sandbox: usa /permissions per concedere più accesso.";
|
||||
|
||||
/// Output lines that change between identical runs (timings, ids) and must not make two
|
||||
/// failures look different.
|
||||
const VOLATILE_PREFIXES: &[&str] = &[
|
||||
"Wall time",
|
||||
"Chunk ID",
|
||||
"Process running with session ID",
|
||||
"Original token count",
|
||||
];
|
||||
|
||||
const SANDBOX_MARKERS: &[&str] = &[
|
||||
"operation not permitted",
|
||||
"unix bind fail",
|
||||
"seatbelt",
|
||||
"landlock",
|
||||
"sandbox denied",
|
||||
"denied by the sandbox",
|
||||
"blocked by the sandbox",
|
||||
];
|
||||
|
||||
struct ToolResult {
|
||||
signature: String,
|
||||
output: String,
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
/// Returns the message to show when the last `threshold` tool results of the current turn
|
||||
/// (after the latest user message) are the same call with the same failure. `threshold == 0`
|
||||
/// disables the check.
|
||||
pub(crate) fn repeated_failure_message<'a>(
|
||||
items: impl IntoIterator<Item = &'a ResponseItem>,
|
||||
threshold: u32,
|
||||
) -> Option<String> {
|
||||
if threshold == 0 {
|
||||
return None;
|
||||
}
|
||||
let results = turn_tool_results(items);
|
||||
let last = results.last().filter(|result| result.failed)?;
|
||||
let streak = results
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|result| {
|
||||
result.failed && result.signature == last.signature && result.output == last.output
|
||||
})
|
||||
.count();
|
||||
if streak < threshold as usize {
|
||||
return None;
|
||||
}
|
||||
let lower = last.output.to_lowercase();
|
||||
let mut message = REPEATED_FAILURE_MESSAGE.to_string();
|
||||
if SANDBOX_MARKERS.iter().any(|marker| lower.contains(marker)) {
|
||||
message.push(' ');
|
||||
message.push_str(SANDBOX_HINT);
|
||||
}
|
||||
Some(message)
|
||||
}
|
||||
|
||||
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();
|
||||
for item in items {
|
||||
match item {
|
||||
ResponseItem::Message { role, .. } if role == "user" => {
|
||||
signatures.clear();
|
||||
results.clear();
|
||||
}
|
||||
ResponseItem::FunctionCall {
|
||||
name,
|
||||
namespace,
|
||||
arguments,
|
||||
call_id,
|
||||
..
|
||||
} => {
|
||||
signatures.insert(
|
||||
call_id.clone(),
|
||||
call_signature(name, namespace.as_deref(), arguments),
|
||||
);
|
||||
}
|
||||
ResponseItem::CustomToolCall {
|
||||
name,
|
||||
namespace,
|
||||
input,
|
||||
call_id,
|
||||
..
|
||||
} => {
|
||||
signatures.insert(
|
||||
call_id.clone(),
|
||||
call_signature(name, namespace.as_deref(), input),
|
||||
);
|
||||
}
|
||||
ResponseItem::LocalShellCall {
|
||||
call_id: Some(call_id),
|
||||
action,
|
||||
..
|
||||
} => {
|
||||
signatures.insert(call_id.clone(), format!("local_shell:{action:?}"));
|
||||
}
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: Some(call_id),
|
||||
output,
|
||||
..
|
||||
}
|
||||
| ResponseItem::CustomToolCallOutput {
|
||||
call_id, output, ..
|
||||
} => {
|
||||
if let Some(signature) = signatures.get(call_id) {
|
||||
results.push(tool_result(signature.clone(), output));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
/// Identifies a call: shell-like tools by their command only (so a changed timeout or
|
||||
/// justification still counts as the same command), other tools by all their arguments.
|
||||
fn call_signature(name: &str, namespace: Option<&str>, arguments: &str) -> String {
|
||||
let tool = match namespace {
|
||||
Some(namespace) => format!("{namespace}.{name}"),
|
||||
None => name.to_string(),
|
||||
};
|
||||
let parsed = serde_json::from_str::<Value>(arguments).ok();
|
||||
let command = parsed
|
||||
.as_ref()
|
||||
.and_then(|value| value.get("command").or_else(|| value.get("cmd")));
|
||||
match (command, parsed.as_ref()) {
|
||||
(Some(command), _) => format!("{tool}:command={command}"),
|
||||
(None, Some(value)) => format!("{tool}:{value}"),
|
||||
(None, None) => format!("{tool}:{}", arguments.trim()),
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_result(signature: String, payload: &FunctionCallOutputPayload) -> ToolResult {
|
||||
let text = payload.body.to_text().unwrap_or_default();
|
||||
let output = text
|
||||
.lines()
|
||||
.filter(|line| {
|
||||
!VOLATILE_PREFIXES
|
||||
.iter()
|
||||
.any(|prefix| line.trim_start().starts_with(prefix))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let failed = payload.success == Some(false) || has_nonzero_exit_code(&output);
|
||||
ToolResult {
|
||||
signature,
|
||||
output,
|
||||
failed,
|
||||
}
|
||||
}
|
||||
|
||||
fn has_nonzero_exit_code(output: &str) -> bool {
|
||||
output.lines().any(|line| {
|
||||
let line = line.trim();
|
||||
let code = line
|
||||
.strip_prefix("Process exited with code ")
|
||||
.or_else(|| line.strip_prefix("Exit code: "));
|
||||
code.and_then(|code| code.trim().parse::<i64>().ok())
|
||||
.is_some_and(|code| code != 0)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "loop_guard_tests.rs"]
|
||||
mod tests;
|
||||
133
akode-rs/core/src/session/loop_guard_tests.rs
Normal file
133
akode-rs/core/src/session/loop_guard_tests.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
use super::*;
|
||||
use akode_protocol::models::FunctionCallOutputBody;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn call(call_id: &str, command: &str, timeout_ms: u64) -> ResponseItem {
|
||||
let arguments = json!({ "command": command, "timeout_ms": timeout_ms }).to_string();
|
||||
serde_json::from_value(json!({
|
||||
"type": "function_call",
|
||||
"name": "shell_command",
|
||||
"arguments": arguments,
|
||||
"call_id": call_id,
|
||||
}))
|
||||
.expect("function call")
|
||||
}
|
||||
|
||||
fn output(call_id: &str, text: &str, success: Option<bool>) -> ResponseItem {
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some(call_id.to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: FunctionCallOutputPayload {
|
||||
body: FunctionCallOutputBody::Text(text.to_string()),
|
||||
success,
|
||||
},
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn user(text: &str) -> ResponseItem {
|
||||
serde_json::from_value(json!({
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{ "type": "input_text", "text": text }],
|
||||
}))
|
||||
.expect("user message")
|
||||
}
|
||||
|
||||
fn exec_failure(wall: &str, error: &str) -> String {
|
||||
format!("Wall time: {wall} seconds\nProcess exited with code 1\nOutput:\n{error}")
|
||||
}
|
||||
|
||||
fn repeated(times: usize, error: &str) -> Vec<ResponseItem> {
|
||||
let mut items = vec![user("avvia il server")];
|
||||
for i in 0..times {
|
||||
let id = format!("c{i}");
|
||||
items.push(call(&id, "npm run dev", 1000 + i as u64));
|
||||
items.push(output(&id, &exec_failure(&format!("0.{i}"), error), None));
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_after_three_identical_failures() {
|
||||
let items = repeated(3, "Error: EADDRINUSE");
|
||||
assert_eq!(
|
||||
repeated_failure_message(&items, 3),
|
||||
Some(REPEATED_FAILURE_MESSAGE.to_string())
|
||||
);
|
||||
assert_eq!(repeated_failure_message(&items[..5], 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sandbox_denial_adds_permissions_hint() {
|
||||
let items = repeated(3, "listen: unix bind fail: Operation not permitted");
|
||||
assert_eq!(
|
||||
repeated_failure_message(&items, 3),
|
||||
Some(format!("{REPEATED_FAILURE_MESSAGE} {SANDBOX_HINT}"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_threshold_disables_check() {
|
||||
let items = repeated(5, "boom");
|
||||
assert_eq!(repeated_failure_message(&items, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_errors_or_success_break_the_streak() {
|
||||
let mut items = repeated(2, "boom");
|
||||
items.push(call("x", "npm run dev", 1));
|
||||
items.push(output("x", &exec_failure("0.9", "other error"), None));
|
||||
assert_eq!(repeated_failure_message(&items, 3), None);
|
||||
|
||||
let mut items = repeated(3, "boom");
|
||||
items.push(call("ok", "npm run dev", 1));
|
||||
items.push(output(
|
||||
"ok",
|
||||
"Process exited with code 0\nOutput:\nready",
|
||||
None,
|
||||
));
|
||||
assert_eq!(repeated_failure_message(&items, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_user_message_resets_the_streak() {
|
||||
let mut items = repeated(2, "boom");
|
||||
items.extend(repeated(1, "boom"));
|
||||
assert_eq!(repeated_failure_message(&items, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_failure_flag_counts_for_non_shell_tools() {
|
||||
let mut items = vec![user("leggi")];
|
||||
for i in 0..3 {
|
||||
let id = format!("r{i}");
|
||||
items.push(
|
||||
serde_json::from_value(json!({
|
||||
"type": "function_call",
|
||||
"name": "read_file",
|
||||
"arguments": "{\"path\":\"/etc/x\"}",
|
||||
"call_id": id,
|
||||
}))
|
||||
.expect("function call"),
|
||||
);
|
||||
items.push(output(&id, "file not found", Some(false)));
|
||||
}
|
||||
assert_eq!(
|
||||
repeated_failure_message(&items, 3),
|
||||
Some(REPEATED_FAILURE_MESSAGE.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_over_context_warning_text() {
|
||||
use crate::session::turn::prompt_over_context_message;
|
||||
assert_eq!(prompt_over_context_message(4000, 8192), None);
|
||||
assert_eq!(
|
||||
prompt_over_context_message(9000, 8192),
|
||||
Some("Il prompt iniziale (~9000 token) supera la finestra del modello (8192).".to_string())
|
||||
);
|
||||
}
|
||||
@@ -254,6 +254,7 @@ mod submission;
|
||||
pub(crate) use reasoning_effort::RequestEffortUsage;
|
||||
pub(crate) use submission::Submission;
|
||||
mod input_queue;
|
||||
mod loop_guard;
|
||||
mod mcp;
|
||||
mod mcp_prewarm;
|
||||
mod mcp_refresh;
|
||||
|
||||
@@ -711,6 +711,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(),
|
||||
turn_context.config.max_repeated_failures,
|
||||
)
|
||||
{
|
||||
let event = EventMsg::Error(ErrorEvent {
|
||||
misalignment: None,
|
||||
message,
|
||||
codex_error_info: Some(CodexErrorInfo::Other),
|
||||
rejected_audio_file_ids: Vec::new(),
|
||||
});
|
||||
sess.send_event(&turn_context, event).await;
|
||||
break;
|
||||
}
|
||||
|
||||
let candidate = if needs_follow_up {
|
||||
super::async_compaction::take_ready(&sess, &turn_context).await
|
||||
} else {
|
||||
@@ -1622,6 +1638,41 @@ pub(crate) fn build_prompt(
|
||||
}
|
||||
}
|
||||
|
||||
/// Warns once per session when the estimated prompt already exceeds the model window, so a
|
||||
/// later server error about the context size is not a surprise.
|
||||
async fn warn_if_prompt_exceeds_context_window(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
history: &crate::context_manager::ContextManager,
|
||||
) {
|
||||
let Some(window) = turn_context.model_info().resolved_context_window() else {
|
||||
return;
|
||||
};
|
||||
let Some(estimated) = history.estimate_token_count(turn_context) else {
|
||||
return;
|
||||
};
|
||||
let Some(message) = prompt_over_context_message(estimated, window) else {
|
||||
return;
|
||||
};
|
||||
{
|
||||
let mut state = sess.state.lock().await;
|
||||
if state.prompt_over_context_warned {
|
||||
return;
|
||||
}
|
||||
state.prompt_over_context_warned = true;
|
||||
}
|
||||
sess.send_event(turn_context, EventMsg::Warning(WarningEvent { message }))
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(crate) fn prompt_over_context_message(estimated: i64, window: i64) -> Option<String> {
|
||||
(window > 0 && estimated > window).then(|| {
|
||||
format!(
|
||||
"Il prompt iniziale (~{estimated} token) supera la finestra del modello ({window})."
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[allow(deprecated)]
|
||||
#[instrument(level = "trace",
|
||||
@@ -1685,6 +1736,9 @@ async fn run_sampling_request(
|
||||
sess.clone_history().await
|
||||
};
|
||||
let input_item_count = history.raw_items().len();
|
||||
if first_attempt {
|
||||
warn_if_prompt_exceeds_context_window(&sess, &turn_context, &history).await;
|
||||
}
|
||||
let sampling_step_context = Arc::new(StepContext {
|
||||
sampled_through_sequence: Some(history.input_sequence()),
|
||||
..step_context.as_ref().clone()
|
||||
|
||||
Reference in New Issue
Block a user