aKode 0.9.1: escalation non concedibile eseguita in sandbox, avvisi di errore più leggibili

- Se la politica di approvazione non permette di chiedere l'esecuzione fuori dalla
  sandbox (per esempio nelle cartelle senza progetto), il comando gira nella sandbox
  invariata con una nota per il modello invece di essere rifiutato: nessun permesso in
  più, ma il modello non si arrende (prova di Fourier: Qwen rinunciava a creare .venv).
  Test di sicurezza adattati: verificano che il comando non esca dalla sandbox.
- Righe «✗» più leggibili per escalation non consentita, righe di patch non trovate e
  hunk non validi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 00:15:34 +01:00
parent 34587f89c4
commit 45762fc826
7 changed files with 78 additions and 16 deletions

View File

@@ -12901,17 +12901,15 @@ async fn unified_exec_rejects_escalated_permissions_when_policy_not_on_request()
}) })
.await; .await;
let Err(FunctionCallError::RespondToModel(output)) = resp else { // aKode: an escalation nobody can approve is not granted: the command runs with
panic!("expected error result"); // the turn's sandbox unchanged and the model is told so.
}; let output = resp.expect("command runs inside the sandbox");
let text = output.log_output();
let expected = format!( assert!(
"approval policy is {policy:?}; reject command — you cannot ask for escalated permissions if the approval policy is {policy:?}.{}", text.contains(crate::tools::handlers::unified_exec::preparation::ESCALATION_DOWNGRADED_NOTE),
crate::tools::handlers::unified_exec::preparation::ESCALATION_REJECTED_HINT, "missing downgrade note: {text}"
policy = turn_context.approval_policy()
); );
let _ = turn_context.approval_policy();
pretty_assertions::assert_eq!(output, expected);
} }
#[tokio::test] #[tokio::test]

View File

@@ -225,6 +225,7 @@ impl ExecCommandHandler {
let tool_cwd = let tool_cwd =
(!prepared.turn_environment.environment().is_remote()).then(|| prepared.cwd.clone()); (!prepared.turn_environment.environment().is_remote()).then(|| prepared.cwd.clone());
let network_note_context = network_note_context(&prepared, &context).await; let network_note_context = network_note_context(&prepared, &context).await;
let prepared_note = prepared.note;
let request = ExecCommandRequest { let request = ExecCommandRequest {
prepared, prepared,
process_id, process_id,
@@ -239,6 +240,9 @@ impl ExecCommandHandler {
}; };
let result = result.map(|mut response| { let result = result.map(|mut response| {
append_network_note(&mut response.raw_output, &network_note_context); append_network_note(&mut response.raw_output, &network_note_context);
if let Some(note) = prepared_note {
response.raw_output.text.insert_str(0, note);
}
response response
}); });
match result { match result {

View File

@@ -43,6 +43,10 @@ pub(crate) enum ExecCommandLifetime {
OneShot, OneShot,
} }
/// aKode: an escalation the approval policy cannot grant runs inside the sandbox
/// instead (no extra permission), so models do not give up on the command.
pub(crate) const ESCALATION_DOWNGRADED_NOTE: &str = "[aKode] Escalation is not available with the current approval policy, so this command ran inside the sandbox (writes only in the workspace and temporary directories). Do not ask for escalation again: adapt the command to the sandbox (for example install dependencies in a project virtual environment).\n";
/// aKode: what to do instead when escalation is not available (the model otherwise /// aKode: what to do instead when escalation is not available (the model otherwise
/// tends to give up, e.g. on `pip install`). /// tends to give up, e.g. on `pip install`).
pub(crate) const ESCALATION_REJECTED_HINT: &str = " Do not retry with escalation: run the command inside the sandbox instead. Writes are allowed in the workspace and in temporary directories, so install dependencies locally (for example `python3 -m venv .venv` and then `.venv/bin/pip install ...`, or `npm install` without `-g`); if the sandbox has network access, package registries are reachable. If that is not possible, tell the user which command to run."; pub(crate) const ESCALATION_REJECTED_HINT: &str = " Do not retry with escalation: run the command inside the sandbox instead. Writes are allowed in the workspace and in temporary directories, so install dependencies locally (for example `python3 -m venv .venv` and then `.venv/bin/pip install ...`, or `npm install` without `-g`); if the sandbox has network access, package registries are reachable. If that is not possible, tell the user which command to run.";
@@ -61,6 +65,8 @@ pub(crate) struct PreparedExecCommand {
pub(crate) yield_time_ms: u64, pub(crate) yield_time_ms: u64,
pub(crate) max_output_tokens: Option<usize>, pub(crate) max_output_tokens: Option<usize>,
pub(crate) completion_timeout: Option<Duration>, pub(crate) completion_timeout: Option<Duration>,
/// aKode: note for the model prepended to the output (e.g. escalation downgraded).
pub(crate) note: Option<&'static str>,
} }
impl PreparedExecCommand { impl PreparedExecCommand {
@@ -225,7 +231,7 @@ impl<'a> ParsedExecCommand<'a> {
environment: turn_environment, environment: turn_environment,
mut args, mut args,
cwd, cwd,
sandbox_permissions, mut sandbox_permissions,
.. ..
} = self; } = self;
// Remote environments may use a different OS and must build commands with their native // Remote environments may use a different OS and must build commands with their native
@@ -287,6 +293,21 @@ impl<'a> ParsedExecCommand<'a> {
// Sticky turn permissions have already been approved, so they should // Sticky turn permissions have already been approved, so they should
// continue through the normal exec approval flow for the command. // continue through the normal exec approval flow for the command.
let approval_policy = step.settings.approval_policy(); let approval_policy = step.settings.approval_policy();
let mut note = None;
if permissions.sandbox_permissions.requests_sandbox_override()
&& !permissions.permissions_preapproved
&& prompt_is_rejected_by_policy(approval_policy, /*prompt_is_rule*/ false).is_some()
&& permissions.sandbox_permissions == SandboxPermissions::RequireEscalated
&& requested_additional_permissions.is_none()
{
// aKode: nobody can approve the escalation; run the command with the
// turn's sandbox unchanged instead of refusing it.
sandbox_permissions = SandboxPermissions::UseDefault;
permissions.sandbox_permissions = SandboxPermissions::UseDefault;
args.justification = None;
args.prefix_rule = None;
note = Some(ESCALATION_DOWNGRADED_NOTE);
}
if permissions.sandbox_permissions.requests_sandbox_override() if permissions.sandbox_permissions.requests_sandbox_override()
&& !permissions.permissions_preapproved && !permissions.permissions_preapproved
&& prompt_is_rejected_by_policy(approval_policy, /*prompt_is_rule*/ false).is_some() && prompt_is_rejected_by_policy(approval_policy, /*prompt_is_rule*/ false).is_some()
@@ -329,6 +350,7 @@ impl<'a> ParsedExecCommand<'a> {
permissions, permissions,
justification: args.justification, justification: args.justification,
prefix_rule: args.prefix_rule, prefix_rule: args.prefix_rule,
note,
}) })
} }
} }

View File

@@ -1110,6 +1110,17 @@ pub(crate) fn tool_failure_notice(tool_name: &str, error: &str) -> String {
"manca '*** Begin Patch'".to_string() "manca '*** Begin Patch'".to_string()
} else if error.contains("must be '*** End Patch'") { } else if error.contains("must be '*** End Patch'") {
"manca '*** End Patch'".to_string() "manca '*** End Patch'".to_string()
} else if error.contains("you cannot ask for escalated permissions") {
"esecuzione fuori dalla sandbox non consentita".to_string()
} else if error.contains("`justification` requires an explicit `sandbox_permissions`") {
"justification senza sandbox_permissions".to_string()
} else if let Some(rest) = error.split("Failed to find expected lines in ").nth(1) {
let path = rest.split(":\n").next().unwrap_or(rest).trim_end_matches(':');
let file = path.rsplit('/').next().unwrap_or(path);
format!("righe da sostituire non trovate in {file}")
} else if let Some(rest) = error.split("invalid hunk at line ").nth(1) {
let line: String = rest.chars().take_while(char::is_ascii_digit).collect();
format!("patch non valido alla riga {line}")
} else if let Some(rest) = error.split("Unknown process id ").nth(1) { } else if let Some(rest) = error.split("Unknown process id ").nth(1) {
let id: String = rest.chars().take_while(char::is_ascii_digit).collect(); let id: String = rest.chars().take_while(char::is_ascii_digit).collect();
format!("la sessione {id} non esiste") format!("la sessione {id} non esiste")
@@ -1161,6 +1172,27 @@ mod tool_failure_notice_tests {
tool_failure_notice("exec_command", "exec_command failed: boom\ndetails"), tool_failure_notice("exec_command", "exec_command failed: boom\ndetails"),
"✗ exec_command: boom · riprovo" "✗ exec_command: boom · riprovo"
); );
assert_eq!(
tool_failure_notice(
"exec_command",
"approval policy is Granular(GranularApprovalConfig { sandbox_approval: false }); reject command — you cannot ask for escalated permissions if the approval policy is Granular(..)."
),
"✗ exec_command: esecuzione fuori dalla sandbox non consentita · riprovo"
);
assert_eq!(
tool_failure_notice(
"apply_patch",
"apply_patch verification failed: Failed to find expected lines in /tmp/p 1/fourier.py:\nax.grid(True)"
),
"✗ apply_patch: righe da sostituire non trovate in fourier.py · riprovo"
);
assert_eq!(
tool_failure_notice(
"apply_patch",
"apply_patch verification failed: invalid hunk at line 10, Expected update hunk to start with a @@ context marker"
),
"✗ apply_patch: patch non valido alla riga 10 · riprovo"
);
let long = "x".repeat(300); let long = "x".repeat(300);
let notice = tool_failure_notice("tool", &long); let notice = tool_failure_notice("tool", &long);
assert!(notice.ends_with("… · riprovo")); assert!(notice.ends_with("… · riprovo"));

View File

@@ -833,6 +833,7 @@ mod tests {
}, },
justification: None, justification: None,
prefix_rule: None, prefix_rule: None,
note: None,
tty: false, tty: false,
yield_time_ms: 10_000, yield_time_ms: 10_000,
max_output_tokens: None, max_output_tokens: None,

View File

@@ -1109,8 +1109,10 @@ fn scenarios() -> Vec<ScenarioSpec> {
sandbox_permissions: SandboxPermissions::RequireEscalated, sandbox_permissions: SandboxPermissions::RequireEscalated,
features: vec![], features: vec![],
outcome: Outcome::Auto, outcome: Outcome::Auto,
expectation: Expectation::CommandFailure { // aKode: the escalation is not granted; the command runs inside the
output_contains: "you cannot ask for escalated permissions", // unchanged sandbox and the model is told that escalation is unavailable.
expectation: Expectation::CommandSuccess {
stdout_contains: "Escalation is not available with the current approval policy",
}, },
}, },
ScenarioSpec { ScenarioSpec {

View File

@@ -655,10 +655,13 @@ async fn exec_command_escalated_permissions_rejected_then_ok() -> Result<()> {
.function_call_output_content_and_success(call_id_blocked) .function_call_output_content_and_success(call_id_blocked)
.and_then(|(content, _)| content) .and_then(|(content, _)| content)
.expect("blocked output string"); .expect("blocked output string");
// aKode: the rejection is followed by a hint on what to do instead. // aKode: the escalation is not granted; the command runs inside the unchanged
// sandbox and the output starts with a note for the model.
let _ = expected_message;
assert!( assert!(
blocked_output.starts_with(&format!("{expected_message}. Do not retry with escalation")), blocked_output.contains("Escalation is not available with the current approval policy")
"unexpected rejection message: {blocked_output}" && blocked_output.contains("shell ok"),
"unexpected output: {blocked_output}"
); );
let success_output = third_mock let success_output = third_mock