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:
@@ -242,7 +242,7 @@ async fn failed_spawn_edge_publication_cleanup() {
|
||||
.expect_err("lost commit acknowledgement rejects spawn");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"Fatal error: failed to persist spawned agent relationship"
|
||||
"Errore fatale: failed to persist spawned agent relationship"
|
||||
);
|
||||
assert_publication_closed(&harness, &graph, parent).await;
|
||||
}
|
||||
|
||||
@@ -1961,6 +1961,9 @@ async fn network_requirements_start_proxy_for_legacy_and_permission_configs() ->
|
||||
"[{table}]\nenabled = true\n[{table}.domains]\n'api.example.com' = 'allow'\n"
|
||||
);
|
||||
let codex_home = tempdir()?;
|
||||
// aKode: the packaged defaults enable `network_proxy`; this test checks
|
||||
// requirements without the feature, so turn it off explicitly.
|
||||
let config_toml = format!("{config_toml}\n[features]\nnetwork_proxy = false\n");
|
||||
tokio::fs::write(codex_home.path().join(CONFIG_TOML_FILE), config_toml).await?;
|
||||
let config = ConfigBuilder::without_managed_config_for_tests()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
@@ -2040,7 +2043,9 @@ auth = ["bearer"]"#,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"credential_masking = true",
|
||||
// aKode: the packaged defaults enable `network_proxy`; keep this row
|
||||
// about requirements without the feature.
|
||||
"credential_masking = true\nnetwork_proxy = false",
|
||||
"[experimental_network]\nallow_local_binding = true",
|
||||
false,
|
||||
false,
|
||||
|
||||
@@ -2164,6 +2164,12 @@ respect_system_proxy = false
|
||||
#[tokio::test]
|
||||
async fn experimental_network_requirements_enable_proxy_without_feature() -> std::io::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
// aKode: the packaged defaults enable `network_proxy`; this test is about
|
||||
// requirements without the feature.
|
||||
std::fs::write(
|
||||
codex_home.path().join(CONFIG_TOML_FILE),
|
||||
"[features]\nnetwork_proxy = false\n",
|
||||
)?;
|
||||
let config = ConfigBuilder::without_managed_config_for_tests()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
@@ -3463,7 +3469,9 @@ async fn explicit_builtin_workspace_profile_ignores_legacy_workspace_write_setti
|
||||
default_permissions: Some(BUILT_IN_PERMISSION_PROFILE_WORKSPACE.to_string()),
|
||||
sandbox_workspace_write: Some(SandboxWorkspaceWrite {
|
||||
writable_roots: vec![extra_root.path().abs()],
|
||||
network_access: true,
|
||||
// aKode: the built-in workspace profile has network (through the
|
||||
// managed proxy) by default; the legacy `false` must be ignored too.
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: true,
|
||||
exclude_slash_tmp: true,
|
||||
}),
|
||||
@@ -3480,7 +3488,7 @@ async fn explicit_builtin_workspace_profile_ignores_legacy_workspace_write_setti
|
||||
let policy = config.permissions.file_system_sandbox_policy();
|
||||
assert_eq!(
|
||||
config.permissions.network_sandbox_policy(),
|
||||
NetworkSandboxPolicy::Restricted
|
||||
NetworkSandboxPolicy::Enabled
|
||||
);
|
||||
assert!(
|
||||
!policy.entries.iter().any(|entry| matches!(
|
||||
@@ -11260,10 +11268,34 @@ async fn permission_profile_override_falls_back_when_disallowed_by_requirements(
|
||||
PermissionProfile::read_only()
|
||||
);
|
||||
// Prepare the proxy while the candidate permits network, before fallback.
|
||||
// aKode: the packaged defaults add the package registries to the allowlist.
|
||||
let packaged_registries = [
|
||||
"codeload.github.com",
|
||||
"crates.io",
|
||||
"files.pythonhosted.org",
|
||||
"github.com",
|
||||
"index.crates.io",
|
||||
"objects.githubusercontent.com",
|
||||
"pub.dev",
|
||||
"pypi.org",
|
||||
"registry.npmjs.org",
|
||||
"registry.yarnpkg.com",
|
||||
"static.crates.io",
|
||||
"storage.googleapis.com",
|
||||
];
|
||||
let expected_network = NetworkProxySpec::from_config_and_constraints(
|
||||
NetworkProxyConfig {
|
||||
enabled: true,
|
||||
proxy_url: "http://127.0.0.1:43128".to_string(),
|
||||
domains: Some(akode_network_proxy::NetworkDomainPermissions {
|
||||
entries: packaged_registries
|
||||
.iter()
|
||||
.map(|pattern| akode_network_proxy::NetworkDomainPermissionEntry {
|
||||
pattern: (*pattern).to_string(),
|
||||
permission: akode_network_proxy::NetworkDomainPermission::Allow,
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
/*requirements*/ None,
|
||||
|
||||
@@ -251,7 +251,8 @@ const MIXED_DOMAINS: &str = r#"
|
||||
"[::1]" = "allow"
|
||||
"#;
|
||||
|
||||
#[test_case("domains = { 'allowed.example' = 'allow' }", "outside.invalid", true, &["allowed.example"]; "allowlist miss")]
|
||||
// aKode: the packaged defaults add the package registries to the proxy allowlist.
|
||||
#[test_case("domains = { 'allowed.example' = 'allow' }", "outside.invalid", true, &["allowed.example", "codeload.github.com", "crates.io", "files.pythonhosted.org", "github.com", "index.crates.io", "objects.githubusercontent.com", "pub.dev", "pypi.org", "registry.npmjs.org", "registry.yarnpkg.com", "static.crates.io", "storage.googleapis.com"]; "allowlist miss")]
|
||||
#[test_case(MIXED_DOMAINS, "127.0.0.1", false, &["192.168.0.2", "[::1]"]; "wildcard cannot grant loopback")]
|
||||
#[test_case(MIXED_DOMAINS, "192.168.0.1", false, &["192.168.0.2", "[::1]"]; "wildcard cannot grant private address")]
|
||||
#[tokio::test]
|
||||
|
||||
@@ -215,6 +215,7 @@ pub use permission_profile_selection::ResolvedPermissionProfileSelection;
|
||||
pub use permission_profile_selection::resolve_permission_profile_selection;
|
||||
pub use permissions::CompiledPermissionProfile;
|
||||
pub use permissions::WorkspaceWriteSettings;
|
||||
pub use permissions::akode_default_workspace_profile;
|
||||
pub use permissions::compile_permission_profile;
|
||||
pub(crate) use permissions::is_builtin_permission_profile_name;
|
||||
pub use permissions::network_proxy_config_from_profile_network;
|
||||
@@ -1271,6 +1272,9 @@ pub struct Config {
|
||||
/// Whether to register the update_plan tool.
|
||||
pub update_plan_enabled: bool,
|
||||
|
||||
/// aKode: whether to register the `write_file` tool (`[tools] write_file`).
|
||||
pub write_file_tool_enabled: bool,
|
||||
|
||||
/// Policy for collecting and validating tool runtimes.
|
||||
pub tool_registry: ToolRegistryConfig,
|
||||
|
||||
@@ -2980,6 +2984,14 @@ fn resolve_experimental_request_user_input_enabled(config_toml: &ConfigToml) ->
|
||||
.is_none_or(|config| config.enabled)
|
||||
}
|
||||
|
||||
fn resolve_write_file_tool_enabled(config_toml: &ConfigToml) -> bool {
|
||||
config_toml
|
||||
.tools
|
||||
.as_ref()
|
||||
.and_then(|tools| tools.write_file)
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
fn resolve_update_plan_enabled(config_toml: &ConfigToml) -> bool {
|
||||
config_toml
|
||||
.tools
|
||||
@@ -4140,6 +4152,7 @@ impl Config {
|
||||
let experimental_request_user_input_enabled =
|
||||
resolve_experimental_request_user_input_enabled(&cfg);
|
||||
let update_plan_enabled = resolve_update_plan_enabled(&cfg);
|
||||
let write_file_tool_enabled = resolve_write_file_tool_enabled(&cfg);
|
||||
let tool_registry = ToolRegistryConfig {
|
||||
error_on_tool_collisions: cfg
|
||||
.features
|
||||
@@ -4954,6 +4967,7 @@ impl Config {
|
||||
web_search_backend,
|
||||
experimental_request_user_input_enabled,
|
||||
update_plan_enabled,
|
||||
write_file_tool_enabled,
|
||||
tool_registry,
|
||||
code_mode,
|
||||
background_terminal_max_timeout,
|
||||
|
||||
@@ -113,13 +113,28 @@ fn builtin_permission_profile(
|
||||
*exclude_tmpdir_env_var,
|
||||
*exclude_slash_tmp,
|
||||
),
|
||||
None => PermissionProfile::workspace_write(),
|
||||
// aKode 0.9.1: without explicit `[sandbox_workspace_write]` settings the
|
||||
// built-in workspace profile has network access, routed through the managed
|
||||
// proxy and its package-registry allowlist (`[features.network_proxy]` in the
|
||||
// packaged defaults). Filesystem access is unchanged.
|
||||
None => akode_default_workspace_profile(),
|
||||
}),
|
||||
BUILT_IN_DANGER_FULL_ACCESS_PROFILE => Some(PermissionProfile::Disabled),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// aKode: the default workspace-write profile, with network access enabled (filtered
|
||||
/// by the managed network proxy allowlist when the `network_proxy` feature is on).
|
||||
pub fn akode_default_workspace_profile() -> PermissionProfile {
|
||||
PermissionProfile::workspace_write_with(
|
||||
&[],
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*exclude_tmpdir_env_var*/ false,
|
||||
/*exclude_slash_tmp*/ false,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_user_permission_profile_names(
|
||||
permissions: Option<&PermissionsToml>,
|
||||
) -> io::Result<()> {
|
||||
|
||||
@@ -73,6 +73,7 @@ impl ResponseResampling {
|
||||
ResponseEvent::OutputItemAdded(_)
|
||||
| ResponseEvent::OutputTextDelta(_)
|
||||
| ResponseEvent::ToolCallInputDelta { .. }
|
||||
| ResponseEvent::ServerProgress { .. }
|
||||
| ResponseEvent::ReasoningSummaryDelta { .. }
|
||||
| ResponseEvent::ReasoningSummaryDone { .. }
|
||||
| ResponseEvent::ReasoningContentDelta { .. }
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
---
|
||||
source: core/src/guardian/tests.rs
|
||||
assertion_line: 2296
|
||||
expression: "format!(\"{}\\n\\nshared_prompt_cache_key: {}\\nfollowup_contains_first_rationale: {}\",\nnormalize_guardian_snapshot_paths(format_guardian_requests_snapshot(\"Guardian follow-up review request layout\",\n&[(\"Initial Guardian Review Request\", &requests[0]),\n(\"Follow-up Guardian Review Request\", &requests[1]),],)),\nfirst_body[\"prompt_cache_key\"] == second_body[\"prompt_cache_key\"],\nsecond_body.to_string().contains(first_rationale),)"
|
||||
---
|
||||
Scenario: Guardian follow-up review request layout
|
||||
|
||||
## Window 1
|
||||
-- request 1 (request; Initial Guardian Review Request) --
|
||||
00:additional_tools/developer (1; hash=7758f662cd124827):
|
||||
- namespace/functions; hash=70d14ec929ba5cd7
|
||||
00:additional_tools/developer (1; hash=633c75daaa992024):
|
||||
- namespace/functions; hash=84d701b5b5f9f8fc
|
||||
- custom/exec
|
||||
- function/wait
|
||||
01:message/developer:
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
---
|
||||
source: core/src/guardian/tests.rs
|
||||
assertion_line: 1843
|
||||
expression: "normalize_guardian_snapshot_paths(format_guardian_requests_snapshot(\"Guardian review request layout\",\n&[(\"Guardian Review Request\", &request)],))"
|
||||
---
|
||||
Scenario: Guardian review request layout
|
||||
|
||||
## Window 1
|
||||
-- request 1 (request; Guardian Review Request) --
|
||||
00:additional_tools/developer (1; hash=7758f662cd124827):
|
||||
- namespace/functions; hash=70d14ec929ba5cd7
|
||||
00:additional_tools/developer (1; hash=633c75daaa992024):
|
||||
- namespace/functions; hash=84d701b5b5f9f8fc
|
||||
- custom/exec
|
||||
- function/wait
|
||||
01:message/developer:
|
||||
|
||||
@@ -13,6 +13,11 @@ 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.";
|
||||
/// aKode: before stopping the turn, the model gets one warning (as a harness message).
|
||||
pub(crate) const LOOP_NUDGE_ID: &str = "akode-loop-guard";
|
||||
pub(crate) const LOOP_NUDGE_TEXT: &str = "[aKode] You repeated the same tool call and got the same result each time. Repeating it again will not work and the turn will be stopped. Read the last error message carefully and change approach: use a different tool or different arguments (for example exec_command to run commands, write_file or apply_patch to create files).";
|
||||
pub(crate) const LOOP_NUDGE_NOTICE: &str =
|
||||
"Il modello ripete la stessa chiamata: aKode lo avvisa una volta prima di fermare il turno.";
|
||||
pub(crate) const SANDBOX_HINT: &str =
|
||||
"Sembra un blocco della sandbox: usa /permissions per concedere più accesso.";
|
||||
|
||||
|
||||
@@ -500,6 +500,8 @@ pub(crate) async fn run_turn(
|
||||
let mut stop_hook_active = false;
|
||||
// Reminders sent this turn for announced-but-not-executed actions (`[agent] announce_nudges`).
|
||||
let mut announce_nudges_sent: u32 = 0;
|
||||
// aKode: the loop guard first warns the model once, then stops the turn.
|
||||
let mut loop_nudge_sent = false;
|
||||
// Although from the perspective of codex.rs, TurnDiffTracker has the lifecycle of a Task which contains
|
||||
// many turns, from the perspective of the user, it is a single turn.
|
||||
let turn_diff_tracker = Arc::new(tokio::sync::Mutex::new(
|
||||
@@ -727,6 +729,37 @@ pub(crate) async fn run_turn(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if loop_message.is_some()
|
||||
&& !loop_nudge_sent
|
||||
&& let Some(nudge) = build_hook_prompt_message(
|
||||
&[akode_protocol::items::HookPromptFragment {
|
||||
text: super::loop_guard::LOOP_NUDGE_TEXT.to_string(),
|
||||
hook_run_id: super::loop_guard::LOOP_NUDGE_ID.to_string(),
|
||||
metadata: akode_protocol::models::ContentItemMetadata::harness(),
|
||||
}],
|
||||
&sess.item_id_generator,
|
||||
)
|
||||
{
|
||||
loop_nudge_sent = true;
|
||||
tracing::info!(
|
||||
turn_id = %turn_context.sub_id,
|
||||
"akode: repeated tool call; warning the model once before stopping"
|
||||
);
|
||||
sess.send_event(
|
||||
&turn_context,
|
||||
EventMsg::Warning(WarningEvent {
|
||||
message: super::loop_guard::LOOP_NUDGE_NOTICE.to_string(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
sess.record_response_item_and_emit_turn_item(
|
||||
&turn_context,
|
||||
&step_context.settings.model_info,
|
||||
nudge,
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
if let Some(message) = loop_message {
|
||||
let event = EventMsg::Error(ErrorEvent {
|
||||
misalignment: None,
|
||||
@@ -2238,6 +2271,8 @@ pub(super) fn realtime_text_for_event(msg: &EventMsg) -> Option<RealtimeEventTex
|
||||
| EventMsg::ExecCommandEnd(_)
|
||||
| EventMsg::PatchApplyBegin(_)
|
||||
| EventMsg::PatchApplyUpdated(_)
|
||||
| EventMsg::ToolCallInputProgress(_)
|
||||
| EventMsg::ServerProgress(_)
|
||||
| EventMsg::PatchApplyEnd(_)
|
||||
| EventMsg::ImageGenerationBegin(_)
|
||||
| EventMsg::ImageGenerationEnd(_)
|
||||
@@ -3105,8 +3140,16 @@ async fn try_run_sampling_request(
|
||||
active_tool_argument_diff_consumer = tool_runtime
|
||||
.create_diff_consumer(&tool_name)
|
||||
.map(|consumer| (call_id.clone(), consumer));
|
||||
} else if matches!(&item, ResponseItem::FunctionCall { .. }) {
|
||||
active_tool_argument_diff_consumer = None;
|
||||
} else if let ResponseItem::FunctionCall { call_id, name, .. } = &item {
|
||||
// aKode: progress events while a long function call is generated.
|
||||
active_tool_argument_diff_consumer = (!*draining_for_mailbox).then(|| {
|
||||
(
|
||||
call_id.clone(),
|
||||
Box::new(crate::tools::tool_call_progress::ToolCallProgressConsumer::new(
|
||||
name.as_str(),
|
||||
)) as Box<dyn ToolArgumentDiffConsumer>,
|
||||
)
|
||||
});
|
||||
}
|
||||
if let Some(turn_item) = handle_non_tool_response_item(
|
||||
sess.as_ref(),
|
||||
@@ -3326,6 +3369,23 @@ async fn try_run_sampling_request(
|
||||
error_or_panic("OutputTextDelta without active item".to_string());
|
||||
}
|
||||
}
|
||||
ResponseEvent::ServerProgress {
|
||||
kind,
|
||||
percent,
|
||||
eta_s,
|
||||
ahead,
|
||||
} => {
|
||||
sess.send_event(
|
||||
&turn_context,
|
||||
EventMsg::ServerProgress(akode_protocol::protocol::ServerProgressEvent {
|
||||
kind,
|
||||
percent,
|
||||
eta_s,
|
||||
ahead,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
ResponseEvent::ToolCallInputDelta {
|
||||
item_id: _,
|
||||
call_id,
|
||||
|
||||
@@ -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:?}");
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(¬e);
|
||||
}
|
||||
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(¬e);
|
||||
}
|
||||
}
|
||||
|
||||
fn one_shot_exec_command_spec(spec: ToolSpec) -> ToolSpec {
|
||||
let ToolSpec::Function(mut spec) = spec else {
|
||||
unreachable!("exec_command has a function schema");
|
||||
|
||||
124
akode-rs/core/src/tools/handlers/unified_exec/network_note.rs
Normal file
124
akode-rs/core/src/tools/handlers/unified_exec/network_note.rs
Normal 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"));
|
||||
}
|
||||
}
|
||||
@@ -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)) => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
175
akode-rs/core/src/tools/tool_call_progress.rs
Normal file
175
akode-rs/core/src/tools/tool_call_progress.rs
Normal 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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -534,6 +534,7 @@ fn response_event_records_turn_ttft(event: &ResponseEvent) -> bool {
|
||||
| ResponseEvent::SafetyBuffering(_)
|
||||
| ResponseEvent::ServerReasoningIncluded(_)
|
||||
| ResponseEvent::ToolCallInputDelta { .. }
|
||||
| ResponseEvent::ServerProgress { .. }
|
||||
| ResponseEvent::Completed { .. }
|
||||
| ResponseEvent::ReasoningSummaryPartAdded { .. }
|
||||
| ResponseEvent::RateLimits(_)
|
||||
|
||||
Reference in New Issue
Block a user