aKode 0.9.1: correzioni dalla prova di Fourier (apply_patch, write_file, errori visibili, rete dei pacchetti)

- apply_patch tollerante: aggiunge '*** Begin Patch'/'*** End Patch' mancanti quando
  il contenuto inizia con Add/Update/Delete File, toglie i recinti ```; ogni altra
  ambiguità resta un errore; riga con il formato e un esempio negli errori di formato.
- Strumento write_file (path + contenuto) sulla pipeline di apply_patch (stesse
  verifiche, sandbox, approvazioni e hook), [tools] write_file (predefinito attivo);
  dopo la scrittura ricorda al modello di verificare il file.
- Chiamate a strumento fallite visibili nella TUI ("✗ strumento: motivo · riprovo").
- Avanzamento mentre il modello scrive una chiamata lunga ("Scrivo file · N token")
  e stato del gateway imeAI ("In coda…", "Leggo il prompt · 42%").
- write_stdin con id inesistente: elenca le sessioni aperte e indica exec_command o
  write_file; descrizione più chiara.
- Protezione dai loop: un avviso al modello prima di fermare il turno.
- Sandbox predefinita: rete attiva solo verso i registri dei pacchetti attraverso il
  proxy di rete ([features.network_proxy] nei default impacchettati); scritture
  invariate; nota al modello sugli errori di rete in sandbox.
- Testi della TUI in italiano (benvenuto, segnaposto, suggerimenti, «Errore fatale»).
- Test adattati ai nuovi default (rete del profilo :workspace, allowlist), snapshot e
  schemi rigenerati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-16 23:01:42 +01:00
parent 1c278642de
commit 3df68b5842
282 changed files with 2750 additions and 707 deletions

View File

@@ -28,6 +28,7 @@ use crate::tools::events::ToolEventCtx;
use crate::tools::handlers::apply_granted_turn_permissions;
use crate::tools::handlers::apply_patch_spec::create_apply_patch_freeform_tool;
use crate::tools::handlers::apply_patch_spec::create_apply_patch_function_tool;
use crate::tools::handlers::apply_patch_spec::create_write_file_tool;
use crate::tools::handlers::file_system_sandbox_policy_context_for_cwd;
use crate::tools::handlers::resolve_tool_environment;
use crate::tools::handlers::selected_executor;
@@ -70,6 +71,9 @@ const APPLY_PATCH_ARGUMENT_DIFF_BUFFER_INTERVAL: Duration = Duration::from_milli
pub struct ApplyPatchHandler {
multi_environment: bool,
tool_type: ApplyPatchToolType,
/// aKode: this handler serves the `write_file` tool (path + whole content),
/// converted into an `*** Add File` patch.
write_file: bool,
}
impl ApplyPatchHandler {
@@ -77,6 +81,17 @@ impl ApplyPatchHandler {
Self {
multi_environment,
tool_type,
write_file: false,
}
}
/// The `write_file` tool: a JSON function tool that goes through the same
/// verification, sandbox, approval and hook path as `apply_patch`.
pub(crate) fn write_file() -> Self {
Self {
multi_environment: false,
tool_type: ApplyPatchToolType::Function,
write_file: true,
}
}
}
@@ -90,10 +105,39 @@ impl Default for ApplyPatchHandler {
}
}
/// Arguments of the JSON function variant of `apply_patch`.
/// Arguments of the JSON function variant of `apply_patch`, or of `write_file`.
#[derive(serde::Deserialize)]
struct ApplyPatchFunctionArgs {
input: String,
#[serde(untagged)]
enum ApplyPatchFunctionArgs {
Patch { input: String },
WriteFile { path: String, content: String },
}
/// aKode: reminder appended to a successful `write_file`, so that the model checks
/// the new file instead of declaring the task done untested.
const WRITE_FILE_VERIFY_HINT: &str = "\nBefore you finish, verify the file: run it, its tests or a quick check (with sample input if it reads stdin, in a non-interactive mode if it opens windows) and fix what fails.";
/// aKode: converts `write_file` arguments into an `*** Add File` patch (which
/// creates the file or replaces its whole content). Every content line gets the
/// `+` prefix, so no content can be read as a patch marker.
pub(crate) fn write_file_patch(path: &str, content: &str) -> Result<String, FunctionCallError> {
let path = path.trim();
if path.is_empty() || path.contains(['\n', '\r']) {
return Err(FunctionCallError::RespondToModel(
"write_file expects a non-empty single-line `path`".to_string(),
));
}
let mut patch = format!("*** Begin Patch\n*** Add File: {path}\n");
if content.is_empty() {
patch.push_str("+\n");
}
for line in content.lines() {
patch.push('+');
patch.push_str(line.strip_suffix('\r').unwrap_or(line));
patch.push('\n');
}
patch.push_str("*** End Patch");
Ok(patch)
}
/// Extracts the patch text from either the freeform or the function payload.
@@ -101,13 +145,15 @@ fn apply_patch_input(payload: &ToolPayload) -> Result<String, FunctionCallError>
match payload {
ToolPayload::Custom { input } => Ok(input.clone()),
ToolPayload::Function { arguments } => {
serde_json::from_str::<ApplyPatchFunctionArgs>(arguments)
.map(|args| args.input)
.map_err(|err| {
FunctionCallError::RespondToModel(format!(
"apply_patch expects JSON arguments {{\"input\": \"<patch>\"}}: {err}"
))
})
match serde_json::from_str::<ApplyPatchFunctionArgs>(arguments) {
Ok(ApplyPatchFunctionArgs::Patch { input }) => Ok(input),
Ok(ApplyPatchFunctionArgs::WriteFile { path, content }) => {
write_file_patch(&path, &content)
}
Err(err) => Err(FunctionCallError::RespondToModel(format!(
"expected JSON arguments {{\"input\": \"<patch>\"}} for apply_patch or {{\"path\": \"<file>\", \"content\": \"<text>\"}} for write_file: {err}"
))),
}
}
ToolPayload::ToolSearch { .. } => Err(FunctionCallError::RespondToModel(
"apply_patch handler received unsupported payload".to_string(),
@@ -322,10 +368,17 @@ fn apply_patch_payload_command(payload: &ToolPayload) -> Option<String> {
impl ToolExecutor<ToolInvocation> for ApplyPatchHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("apply_patch")
if self.write_file {
ToolName::plain("write_file")
} else {
ToolName::plain("apply_patch")
}
}
fn spec(&self) -> ToolSpec {
if self.write_file {
return create_write_file_tool();
}
match self.tool_type {
ApplyPatchToolType::Freeform => {
create_apply_patch_freeform_tool(self.multi_environment)
@@ -371,7 +424,10 @@ impl ApplyPatchHandler {
call_id,
tool_name,
};
let content = execute_prepared_patch(request, Some(&tracker), tool_ctx).await?;
let mut content = execute_prepared_patch(request, Some(&tracker), tool_ctx).await?;
if self.write_file && content.contains("Success.") {
content.push_str(WRITE_FILE_VERIFY_HINT);
}
Ok(boxed_tool_output(ApplyPatchToolOutput::from_text(content)))
}
}
@@ -383,7 +439,7 @@ impl CoreToolRuntime for ApplyPatchHandler {
) -> Result<ToolEnvironments, FunctionCallError> {
let input = apply_patch_input(&invocation.payload)?;
let args = akode_apply_patch::parse_patch(&input).map_err(|err| {
FunctionCallError::RespondToModel(format!("apply_patch verification failed: {err}"))
patch_parse_error_for_model(&err)
})?;
let environment_id =
require_environment_id(args.environment_id.as_deref(), self.multi_environment)?;
@@ -423,7 +479,7 @@ impl CoreToolRuntime for ApplyPatchHandler {
) -> Result<ToolInvocation, FunctionCallError> {
let patch = updated_hook_command(&updated_input)?;
let args = akode_apply_patch::parse_patch(patch).map_err(|err| {
FunctionCallError::RespondToModel(format!("apply_patch verification failed: {err}"))
patch_parse_error_for_model(&err)
})?;
if let Some(id) =
require_environment_id(args.environment_id.as_deref(), self.multi_environment)?
@@ -464,6 +520,26 @@ impl CoreToolRuntime for ApplyPatchHandler {
}
}
/// Parse errors go back to the model with a one-line reminder of the format,
/// so that local models can fix the patch on the next attempt (aKode).
fn patch_parse_error_for_model(err: &akode_apply_patch::ParseError) -> FunctionCallError {
FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {err}\n{}",
akode_apply_patch::PATCH_FORMAT_HINT
))
}
fn patch_correctness_error_for_model(err: &akode_apply_patch::ApplyPatchError) -> FunctionCallError {
match err {
akode_apply_patch::ApplyPatchError::ParseError(parse_error) => {
patch_parse_error_for_model(parse_error)
}
err => FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {err}"
)),
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn intercept_apply_patch(
command: &[String],
@@ -508,9 +584,7 @@ pub(crate) async fn prepare_intercepted_patch(
prepare_verified_patch(changes, turn_environment.clone(), step_context).map(Some)
}
akode_apply_patch::MaybeApplyPatchVerified::CorrectnessError(parse_error) => {
Err(FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {parse_error}"
)))
Err(patch_correctness_error_for_model(&parse_error))
}
akode_apply_patch::MaybeApplyPatchVerified::ShellParseError(error) => {
tracing::trace!("Failed to parse apply_patch input, {error:?}");
@@ -528,9 +602,7 @@ pub(crate) async fn prepare_patch_request(
let args = match akode_apply_patch::parse_patch(patch_input) {
Ok(args) => args,
Err(parse_error) => {
return Err(FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {parse_error}"
)));
return Err(patch_parse_error_for_model(&parse_error));
}
};
let fs = turn_environment.environment().get_filesystem();
@@ -547,9 +619,7 @@ pub(crate) async fn prepare_patch_request(
prepare_verified_patch(changes, turn_environment.clone(), step_context)
}
akode_apply_patch::MaybeApplyPatchVerified::CorrectnessError(parse_error) => {
Err(FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {parse_error}"
)))
Err(patch_correctness_error_for_model(&parse_error))
}
akode_apply_patch::MaybeApplyPatchVerified::ShellParseError(error) => {
tracing::trace!("Failed to parse apply_patch input, {error:?}");

View File

@@ -67,6 +67,36 @@ Grammar (Lark):\n{APPLY_PATCH_LARK_GRAMMAR}"
})
}
/// aKode: `write_file`, a plain JSON function tool to create a file or replace
/// its whole content. Models that only know JSON function calling (and look for a
/// "write" tool) use it instead of hand-writing the patch format; it runs through
/// the same apply_patch verification, sandbox and approvals.
pub fn create_write_file_tool() -> ToolSpec {
ToolSpec::Function(ResponsesApiTool {
name: "write_file".to_string(),
description: "Create a file or replace its whole content. Use it to write new files or to rewrite a file completely; for small edits to an existing file use apply_patch. Parent directories are created. Same sandbox and approval rules as apply_patch.".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::from([
(
"path".to_string(),
JsonSchema::string(Some(
"File path, relative to the working directory or absolute.".to_string(),
)),
),
(
"content".to_string(),
JsonSchema::string(Some("The complete new content of the file.".to_string())),
),
]),
Some(vec!["path".to_string(), "content".to_string()]),
Some(false.into()),
),
output_schema: None,
})
}
#[cfg(test)]
#[path = "apply_patch_spec_tests.rs"]
mod tests;

View File

@@ -435,3 +435,47 @@ fn write_permissions_for_windows_paths_uses_executor_uris() {
)]),
);
}
#[test]
fn write_file_patch_adds_plus_prefixes_and_markers() {
let patch = write_file_patch("src/a.py", "print(1)\n*** End Patch\n\nx").expect("patch");
assert_eq!(
patch,
"*** Begin Patch\n*** Add File: src/a.py\n+print(1)\n+*** End Patch\n+\n+x\n*** End Patch"
);
let args = akode_apply_patch::parse_patch(&patch).expect("parses");
assert_eq!(
args.hunks,
vec![akode_apply_patch::Hunk::AddFile {
path: std::path::PathBuf::from("src/a.py"),
contents: "print(1)\n*** End Patch\n\nx\n".to_string(),
}]
);
}
#[test]
fn write_file_patch_rejects_bad_paths_and_accepts_empty_content() {
assert!(write_file_patch("", "x").is_err());
assert!(write_file_patch("a\nb", "x").is_err());
let patch = write_file_patch("empty.txt", "").expect("patch");
assert!(akode_apply_patch::parse_patch(&patch).is_ok());
}
#[test]
fn function_payload_accepts_write_file_arguments() {
let payload = ToolPayload::Function {
arguments: serde_json::json!({"path": "b.txt", "content": "hi"}).to_string(),
};
assert_eq!(
apply_patch_input(&payload).expect("input"),
"*** Begin Patch\n*** Add File: b.txt\n+hi\n*** End Patch"
);
let payload = ToolPayload::Function {
arguments: serde_json::json!({"input": "*** Begin Patch"}).to_string(),
};
assert_eq!(apply_patch_input(&payload).expect("input"), "*** Begin Patch");
let payload = ToolPayload::Function {
arguments: serde_json::json!({"file": "b.txt"}).to_string(),
};
assert!(apply_patch_input(&payload).is_err());
}

View File

@@ -112,7 +112,7 @@ pub fn create_write_stdin_tool() -> ToolSpec {
(
"session_id".to_string(),
JsonSchema::number(Some(
"Identifier of the running unified exec session.".to_string(),
"Session ID printed by an earlier exec_command whose process is still running (\"Process running with session ID N\"). Never invent one.".to_string(),
)),
),
(
@@ -138,7 +138,7 @@ pub fn create_write_stdin_tool() -> ToolSpec {
ToolSpec::Function(ResponsesApiTool {
name: "write_stdin".to_string(),
description:
"Writes characters to an existing unified exec session and returns recent output."
"Writes characters to a process that an earlier exec_command left running and returns recent output. It cannot start commands or write files: use exec_command to run a command and write_file or apply_patch to create files."
.to_string(),
strict: false,
defer_loading: None,

View File

@@ -98,7 +98,7 @@ fn write_stdin_tool_matches_expected_spec() {
(
"session_id".to_string(),
JsonSchema::number(Some(
"Identifier of the running unified exec session.".to_string(),
"Session ID printed by an earlier exec_command whose process is still running (\"Process running with session ID N\"). Never invent one.".to_string(),
)),
),
(
@@ -126,7 +126,7 @@ fn write_stdin_tool_matches_expected_spec() {
ToolSpec::Function(ResponsesApiTool {
name: "write_stdin".to_string(),
description:
"Writes characters to an existing unified exec session and returns recent output."
"Writes characters to a process that an earlier exec_command left running and returns recent output. It cannot start commands or write files: use exec_command to run a command and write_file or apply_patch to create files."
.to_string(),
strict: false,
defer_loading: None,

View File

@@ -20,6 +20,7 @@ use std::path::PathBuf;
use std::sync::Arc;
mod exec_command;
mod network_note;
pub(crate) mod preparation;
mod write_stdin;
@@ -47,22 +48,58 @@ pub(crate) fn terminal_session_for_input(
&invocation.step_context.environments,
/*environment_id*/ None,
)?;
invocation
let result = invocation
.session
.services
.unified_exec_manager
.resolve_terminal(args.session_id)
.await
.map(ToolEnvironments::Terminal)
.map_err(|err| {
FunctionCallError::RespondToModel(format!(
"{} failed: {err}",
invocation.tool_name.name
.map(ToolEnvironments::Terminal);
match result {
Ok(environments) => Ok(environments),
Err(crate::unified_exec::UnifiedExecError::UnknownProcessId { process_id }) => {
Err(FunctionCallError::RespondToModel(
unknown_session_message(
&invocation.session.services.unified_exec_manager,
&invocation.tool_name.name,
process_id,
)
.await,
))
})
}
Err(err) => Err(FunctionCallError::RespondToModel(format!(
"{} failed: {err}",
invocation.tool_name.name
))),
}
})
}
/// Error for a `session_id` that does not exist (e.g. invented by the model):
/// lists the sessions that are still running and points to `exec_command`.
pub(crate) async fn unknown_session_message(
manager: &crate::unified_exec::UnifiedExecProcessManager,
tool_name: &str,
process_id: i32,
) -> String {
let running = manager.list_processes().await;
let running = if running.is_empty() {
"none".to_string()
} else {
running
.iter()
.map(|info| format!("{} (`{}`)", info.process_id, info.command))
.collect::<Vec<_>>()
.join(", ")
};
format!(
"{tool_name} failed: Unknown process id {process_id}. Running sessions: {running}. \
{tool_name} only works with a session_id returned by an earlier exec_command whose process \
is still running; do not invent ids. It cannot write files or start commands: to run a \
command call exec_command; to create or rewrite a file call write_file (or apply_patch)."
)
}
#[derive(Debug, Deserialize)]
pub(crate) struct ExecCommandArgs {
pub(crate) cmd: String,

View File

@@ -224,6 +224,7 @@ impl ExecCommandHandler {
let hook_command = prepared.hook_command.clone();
let tool_cwd =
(!prepared.turn_environment.environment().is_remote()).then(|| prepared.cwd.clone());
let network_note_context = network_note_context(&prepared, &context).await;
let request = ExecCommandRequest {
prepared,
process_id,
@@ -236,6 +237,10 @@ impl ExecCommandHandler {
}
None => manager.exec_command(request, &context).await,
};
let result = result.map(|mut response| {
append_network_note(&mut response.raw_output, &network_note_context);
response
});
match result {
Ok(response) => Ok(boxed_tool_output(response)),
Err(UnifiedExecError::SandboxDenied {
@@ -244,7 +249,12 @@ impl ExecCommandHandler {
output_omitted_bytes,
..
}) => {
let output_text = output.aggregated_output.text;
let mut output_text = output.aggregated_output.text;
if let Some(note) =
super::network_note::network_note(&output_text, &network_note_context)
{
output_text.push_str(&note);
}
let original_token_count =
original_token_count.unwrap_or_else(|| approx_token_count(&output_text));
Ok(boxed_tool_output(ExecCommandToolOutput {
@@ -277,6 +287,49 @@ impl ExecCommandHandler {
}
}
/// aKode: what the model needs to know to explain a network failure (see
/// `network_note`). Computed before the command runs.
async fn network_note_context(
prepared: &super::preparation::PreparedExecCommand,
context: &UnifiedExecContext,
) -> super::network_note::NetworkNoteContext {
let escalated = prepared
.permissions
.sandbox_permissions
.requests_sandbox_override();
let sandbox_disabled = matches!(
prepared.turn_environment.permission_profile(),
akode_protocol::models::PermissionProfile::Disabled
);
let approval_policy = context.step_context.settings.approval_policy();
let can_request_escalation =
crate::exec_policy::prompt_is_rejected_by_policy(approval_policy, /*prompt_is_rule*/ false)
.is_none();
let allowed_domains = match context.step_context.turn.network.as_ref() {
Some(network) => network
.current_cfg()
.await
.ok()
.and_then(|cfg| cfg.allowed_domains())
.unwrap_or_default(),
None => Vec::new(),
};
super::network_note::NetworkNoteContext {
sandboxed: !escalated && !sandbox_disabled,
can_request_escalation,
allowed_domains,
}
}
fn append_network_note(
output: &mut CapturedStream,
context: &super::network_note::NetworkNoteContext,
) {
if let Some(note) = super::network_note::network_note(&output.text, context) {
output.text.push_str(&note);
}
}
fn one_shot_exec_command_spec(spec: ToolSpec) -> ToolSpec {
let ToolSpec::Function(mut spec) = spec else {
unreachable!("exec_command has a function schema");

View File

@@ -0,0 +1,124 @@
//! aKode: explains to the model that a network failure inside the sandbox comes
//! from the sandbox network policy, not from a broken connection.
//!
//! Local models tend to read `Could not resolve host` or a proxy `403` as "no
//! internet" and give up (e.g. on `pip install`). The note tells them what is
//! reachable and how to ask the user for an unsandboxed run.
/// Output fragments printed by common tools (pip, npm, curl, git, cargo, dart...)
/// when DNS or the connection is refused by the sandbox or by the network proxy.
const NETWORK_FAILURE_PATTERNS: &[&str] = &[
// DNS blocked by the sandbox (macOS / glibc / Node / Python).
"nodename nor servname provided",
"could not resolve host",
"temporary failure in name resolution",
"name or service not known",
"getaddrinfo enotfound",
"getaddrinfo eai_again",
"failed to establish a new connection",
"network is unreachable",
"failed to lookup address information",
"failed host lookup",
// Domain refused by the aKode network proxy (allowlist).
"domain not in allowlist",
"blocked-by-allowlist",
"blocked-by-denylist",
"domain denied by the sandbox policy",
"tunnel connection failed: 403",
"connect tunnel failed, response 403",
];
pub(crate) struct NetworkNoteContext {
/// The command ran inside the sandbox (no escalation, sandbox not disabled).
pub(crate) sandboxed: bool,
/// The approval policy lets the model ask for an unsandboxed run.
pub(crate) can_request_escalation: bool,
/// Domains reachable through the sandbox network proxy, if any.
pub(crate) allowed_domains: Vec<String>,
}
pub(crate) fn looks_like_network_failure(output: &str) -> bool {
let output = output.to_ascii_lowercase();
NETWORK_FAILURE_PATTERNS
.iter()
.any(|pattern| output.contains(pattern))
}
/// Returns the note to append to the command output, or `None` when the
/// output does not look like a network failure or the command was not sandboxed.
pub(crate) fn network_note(output: &str, context: &NetworkNoteContext) -> Option<String> {
if !context.sandboxed || !looks_like_network_failure(output) {
return None;
}
let reachable = if context.allowed_domains.is_empty() {
"The sandbox blocks all network access.".to_string()
} else {
format!(
"Inside the sandbox only these hosts are reachable: {}.",
context.allowed_domains.join(", ")
)
};
let next_step = if context.can_request_escalation {
"If the command needs another host, rerun it with `sandbox_permissions: \"require_escalated\"` and a short `justification`, so the user can approve running it outside the sandbox. Do not conclude that there is no internet connection."
} else {
"The current approval policy does not allow running outside the sandbox: tell the user which command needs network access instead of concluding that there is no internet connection."
};
Some(format!(
"\n[aKode] Network note: this failure comes from the sandbox network policy, not from a broken connection. {reachable} {next_step}"
))
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
fn context(sandboxed: bool, can_request_escalation: bool) -> NetworkNoteContext {
NetworkNoteContext {
sandboxed,
can_request_escalation,
allowed_domains: vec!["pypi.org".to_string()],
}
}
const PIP_DNS_FAILURE: &str = "WARNING: Retrying (Retry(total=2)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known')': /simple/numpy/\nERROR: No matching distribution found for numpy";
#[test]
fn detects_common_network_failures() {
for output in [
PIP_DNS_FAILURE,
"curl: (6) Could not resolve host: example.com",
"curl: (56) CONNECT tunnel failed, response 403",
"npm ERR! request to https://registry.npmjs.org/x failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org",
"ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden'))",
"fatal: unable to access 'https://gitlab.com/x.git/': Could not resolve host: gitlab.com",
] {
assert!(looks_like_network_failure(output), "{output}");
}
assert!(!looks_like_network_failure("ModuleNotFoundError: No module named 'numpy'"));
assert!(!looks_like_network_failure("Successfully installed numpy-2.1.0"));
}
#[test]
fn note_only_for_sandboxed_commands() {
assert_eq!(network_note(PIP_DNS_FAILURE, &context(false, true)), None);
assert_eq!(network_note("all good", &context(true, true)), None);
let note = network_note(PIP_DNS_FAILURE, &context(true, true)).expect("note");
assert!(note.contains("not from a broken connection"));
assert!(note.contains("only these hosts are reachable: pypi.org."));
assert!(note.contains("require_escalated"));
}
#[test]
fn note_without_escalation_asks_to_tell_the_user() {
let note = network_note(PIP_DNS_FAILURE, &NetworkNoteContext {
sandboxed: true,
can_request_escalation: false,
allowed_domains: Vec::new(),
})
.expect("note");
assert!(note.contains("The sandbox blocks all network access."));
assert!(note.contains("tell the user"));
assert!(!note.contains("require_escalated"));
}
}

View File

@@ -111,7 +111,21 @@ impl WriteStdinHandler {
}),
},
)
.await
.await;
let response = match response {
Err(UnifiedExecError::UnknownProcessId { process_id }) => {
return Err(FunctionCallError::RespondToModel(
super::unknown_session_message(
&session.services.unified_exec_manager,
"write_stdin",
process_id,
)
.await,
));
}
response => response,
};
let response = response
.map_err(|err| {
let message = match err {
UnifiedExecError::StdinApproval(ToolError::Rejected(reason)) => {

View File

@@ -20,6 +20,7 @@ pub(crate) mod router;
pub(crate) mod runtimes;
pub(crate) mod sandboxing;
pub(crate) mod spec_plan;
pub(crate) mod tool_call_progress;
pub(crate) mod tool_dispatch_trace;
mod tool_namespaces_info;
mod user_messaging;

View File

@@ -111,6 +111,8 @@ impl ToolCallRuntime {
cancellation_token: CancellationToken,
) -> impl std::future::Future<Output = Result<ResponseItemEnvelope, CodexErr>> {
let error_call = call.clone();
let failure_session = Arc::clone(&self.session);
let failure_turn = Arc::clone(&self.step_context.turn);
let source = call.direct_source();
let recorder = self.session.services.executed_tool_calls.clone();
let item_id_generator = Arc::clone(&self.session.item_id_generator);
@@ -139,6 +141,19 @@ impl ToolCallRuntime {
}
Err(FunctionCallError::Fatal(message)) => return Err(CodexErr::Fatal(message)),
Err(other) => {
if let FunctionCallError::RespondToModel(message) = &other {
// aKode: show every failed tool call in the client (the model
// gets the full error and usually retries).
let message = tool_failure_notice(&error_call.tool_name.name, message);
failure_session
.send_event(
&failure_turn,
akode_protocol::protocol::EventMsg::Warning(
akode_protocol::protocol::WarningEvent { message },
),
)
.await;
}
ResponseItemEnvelope::new(Self::failure_response(error_call, other).into())
}
};
@@ -1082,3 +1097,73 @@ mod observation_tests;
#[cfg(test)]
#[path = "parallel_trace_tests.rs"]
mod trace_tests;
/// Prefix of the client notice for a failed tool call; the TUI renders these
/// warnings as a compact `✗` line.
pub const TOOL_FAILURE_NOTICE_PREFIX: &str = "✗ ";
/// One compact line for a failed tool call, e.g.
/// `✗ apply_patch: manca '*** Begin Patch' · riprovo`.
pub(crate) fn tool_failure_notice(tool_name: &str, error: &str) -> String {
const MAX_CHARS: usize = 120;
let summary = if error.contains("must be '*** Begin Patch'") {
"manca '*** Begin Patch'".to_string()
} else if error.contains("must be '*** End Patch'") {
"manca '*** End Patch'".to_string()
} else if let Some(rest) = error.split("Unknown process id ").nth(1) {
let id: String = rest.chars().take_while(char::is_ascii_digit).collect();
format!("la sessione {id} non esiste")
} else {
let line = error.lines().next().unwrap_or_default().trim();
let line = line
.strip_prefix(&format!("{tool_name} failed: "))
.or_else(|| line.strip_prefix(&format!("{tool_name} verification failed: ")))
.unwrap_or(line);
if line.chars().count() > MAX_CHARS {
let truncated: String = line.chars().take(MAX_CHARS).collect();
format!("{truncated}…")
} else {
line.to_string()
}
};
format!("{TOOL_FAILURE_NOTICE_PREFIX}{tool_name}: {summary} · riprovo")
}
#[cfg(test)]
mod tool_failure_notice_tests {
use super::tool_failure_notice;
use pretty_assertions::assert_eq;
#[test]
fn compact_notices() {
assert_eq!(
tool_failure_notice(
"apply_patch",
"apply_patch verification failed: invalid patch: The first line of the patch must be '*** Begin Patch'\nPatch format: ..."
),
"✗ apply_patch: manca '*** Begin Patch' · riprovo"
);
assert_eq!(
tool_failure_notice(
"apply_patch",
"apply_patch verification failed: invalid patch: The last line of the patch must be '*** End Patch'"
),
"✗ apply_patch: manca '*** End Patch' · riprovo"
);
assert_eq!(
tool_failure_notice(
"write_stdin",
"write_stdin failed: Unknown process id 42. Running sessions: none."
),
"✗ write_stdin: la sessione 42 non esiste · riprovo"
);
assert_eq!(
tool_failure_notice("exec_command", "exec_command failed: boom\ndetails"),
"✗ exec_command: boom · riprovo"
);
let long = "x".repeat(300);
let notice = tool_failure_notice("tool", &long);
assert!(notice.ends_with("… · riprovo"));
assert!(notice.chars().count() < 160);
}
}

View File

@@ -1370,6 +1370,11 @@ fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, registry: &mut Tool
if let Some(tool_type) = context.model_info.apply_patch_tool_type.clone() {
let include_environment_id = matches!(environment_mode, ToolEnvironmentMode::Multiple);
registry.add(ApplyPatchHandler::new(include_environment_id, tool_type));
// aKode: a plain "write the whole file" tool, through the same apply_patch
// pipeline (sandbox, approvals, hooks, events). Single environment only.
if turn_context.config.write_file_tool_enabled && !include_environment_id {
registry.add(ApplyPatchHandler::write_file());
}
}
if context

View File

@@ -0,0 +1,175 @@
//! aKode: progress events while the model is still generating the arguments of
//! a function tool call (for example a whole file inside `apply_patch`).
//!
//! Local models need minutes to write a long file; without these events the
//! client shows nothing and the user thinks aKode is stuck.
use std::time::Duration;
use std::time::Instant;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::ToolCallInputProgressEvent;
use crate::session::turn_context::TurnContext;
use crate::tools::registry::ToolArgumentDiffConsumer;
/// Minimum interval between two progress events for the same call.
const PROGRESS_INTERVAL: Duration = Duration::from_millis(500);
/// Argument size (in estimated tokens) below which no event is sent: short
/// calls finish before the user could notice anything.
const MIN_TOKENS: u64 = 40;
/// Prefix of the argument text kept to recognize the target.
const TARGET_SCAN_BYTES: usize = 4096;
pub(crate) struct ToolCallProgressConsumer {
tool_name: String,
deltas: u64,
bytes: u64,
head: String,
target: Option<String>,
last_sent_at: Option<Instant>,
}
impl ToolCallProgressConsumer {
pub(crate) fn new(tool_name: impl Into<String>) -> Self {
Self {
tool_name: tool_name.into(),
deltas: 0,
bytes: 0,
head: String::new(),
target: None,
last_sent_at: None,
}
}
/// Estimated tokens: servers usually send one delta per generated token,
/// but some batch them, so fall back on the byte count (about 4 bytes per token).
fn tokens(&self) -> u64 {
self.deltas.max(self.bytes / 4)
}
fn push(&mut self, delta: &str) {
self.deltas += 1;
self.bytes += delta.len() as u64;
if self.target.is_none() && self.head.len() < TARGET_SCAN_BYTES {
self.head.push_str(delta);
self.target = find_target(&self.head);
}
}
fn progress_event(&mut self, call_id: String, now: Instant) -> Option<EventMsg> {
let tokens = self.tokens();
if tokens < MIN_TOKENS {
return None;
}
if self
.last_sent_at
.is_some_and(|last| now.duration_since(last) < PROGRESS_INTERVAL)
{
return None;
}
self.last_sent_at = Some(now);
Some(EventMsg::ToolCallInputProgress(ToolCallInputProgressEvent {
call_id,
tool_name: self.tool_name.clone(),
target: self.target.clone(),
tokens,
}))
}
}
impl ToolArgumentDiffConsumer for ToolCallProgressConsumer {
fn consume_diff(
&mut self,
_turn: &TurnContext,
call_id: String,
diff: &str,
) -> Option<EventMsg> {
self.push(diff);
self.progress_event(call_id, Instant::now())
}
}
/// Recognizes the file being written in partial JSON arguments: an
/// `apply_patch` header, a `"path"`/`"file_path"` field or a shell redirection
/// such as `cat > file << EOF`. Returns the file name without directories.
fn find_target(args: &str) -> Option<String> {
for marker in ["*** Add File: ", "*** Update File: ", "*** Delete File: "] {
if let Some(rest) = args.split(marker).nth(1) {
return complete_value(rest, &["\\n", "\n", "\""]);
}
}
for key in ["\"path\":", "\"file_path\":", "\"filename\":"] {
if let Some(rest) = args.split(key).nth(1) {
let rest = rest.trim_start().strip_prefix('"')?;
return complete_value(rest, &["\""]);
}
}
if let Some(rest) = args.split("cat > ").nth(1).or_else(|| args.split("cat >").nth(1)) {
return complete_value(rest.trim_start(), &[" ", "\\n", "<"]);
}
None
}
/// Returns the value up to the first terminator, only once a terminator has
/// arrived (so a half-streamed name is not shown).
fn complete_value(rest: &str, terminators: &[&str]) -> Option<String> {
let end = terminators
.iter()
.filter_map(|terminator| rest.find(terminator))
.min()?;
let value = rest[..end].trim().trim_matches(['\'', '"']);
if value.is_empty() {
return None;
}
let name = value.rsplit(['/', '\\']).next().unwrap_or(value);
(!name.is_empty()).then(|| name.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn finds_targets() {
assert_eq!(
find_target(r#"{"input":"*** Begin Patch\n*** Add File: /tmp/x/sovrapposizione_fourier.py\n+#!"#),
Some("sovrapposizione_fourier.py".to_string())
);
assert_eq!(find_target(r#"{"input":"*** Add File: /tmp/x/sovra"#), None);
assert_eq!(
find_target(r#"{"path": "src/main.rs", "content": "fn"#),
Some("main.rs".to_string())
);
assert_eq!(
find_target(r#"{"cmd":"cat > /tmp/p/fourier.py << 'EOF'\n"#),
Some("fourier.py".to_string())
);
assert_eq!(find_target(r#"{"cmd":"ls -la"}"#), None);
}
#[test]
fn throttles_and_skips_short_calls() {
let mut consumer = ToolCallProgressConsumer::new("apply_patch");
let start = Instant::now();
consumer.push(r#"{"input":"*** Add File: a.py\n"#);
assert!(consumer.progress_event("c".to_string(), start).is_none());
for _ in 0..100 {
consumer.push("x");
}
let Some(EventMsg::ToolCallInputProgress(event)) =
consumer.progress_event("c".to_string(), start)
else {
panic!("expected a progress event");
};
assert_eq!(event.target.as_deref(), Some("a.py"));
assert_eq!(event.tokens, 101);
assert!(consumer.progress_event("c".to_string(), start).is_none());
assert!(
consumer
.progress_event("c".to_string(), start + PROGRESS_INTERVAL)
.is_some()
);
}
}