From 4e1f551b84aa40b2e712b4957d948d28926942c8 Mon Sep 17 00:00:00 2001 From: "andrea.difonzo" Date: Mon, 16 Nov 2026 17:59:12 +0100 Subject: [PATCH] =?UTF-8?q?aKode:=20cache=20del=20prompt=20pi=C3=B9=20stab?= =?UTF-8?q?ile=20e=20attese=20lunghe=20dei=20server=20locali=20(punto=204,?= =?UTF-8?q?=20blocco=20A)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Ordine fisso dei blocchi di contesto: le sezioni uguali in ogni sessione (skill, permessi) vengono prima, quelle delle estensioni (, riepilogo della memoria) dopo; prima stava subito dopo le istruzioni di sistema e cambiava da un repository all'altro. - Strumenti in ordine stabile (per nome, namespace dopo); nella sessione resta l'ordine della prima richiesta e i nuovi strumenti vanno in coda, mai in mezzo. - La prima richiesta aspetta fino a 5 s (prima 1 s) i server MCP in avvio. - Ogni byte ricevuto azzera il timer di inattività: commenti SSE ed eventi imeai.queue/imeai.prefill compresi. Il timeout vale anche per l'attesa delle intestazioni ed è di 30 minuti per i server locali (5 per gli altri). - Niente keepalive TCP nel client HTTP: reqwest sonda dopo 15 s e chiude dopo 3 sonde senza risposta; attraverso NetBird le sonde non passano e ogni risposta partita dopo 60 s veniva tagliata e richiesta da capo. - Test adattati al nuovo ordine degli strumenti (snapshot con soli riordini) e alla nuova attesa dei server MCP. Co-Authored-By: Claude Opus 5.5 --- akode-rs/akode-api/src/endpoint/responses.rs | 22 ++- akode-rs/akode-api/src/sse/responses.rs | 108 ++++++++++- .../akode-mcp/src/connection_manager_tests.rs | 12 +- akode-rs/akode-mcp/src/mcp/mod.rs | 7 +- akode-rs/core/config.schema.json | 2 +- akode-rs/core/src/client.rs | 18 +- akode-rs/core/src/lib.rs | 1 + akode-rs/core/src/responses_metadata.rs | 19 +- akode-rs/core/src/session/mod.rs | 10 +- akode-rs/core/src/tool_order.rs | 172 ++++++++++++++++++ akode-rs/core/tests/suite/code_mode.rs | 6 +- .../tests/suite/model_runtime_selectors.rs | 6 +- akode-rs/core/tests/suite/prompt_caching.rs | 17 +- akode-rs/core/tests/suite/rmcp_client.rs | 4 +- ...ol_definitions_follow_captured_models.snap | 18 +- ...ves_pending_calls_and_survives_resume.snap | 42 +++-- ...narios__guardian_checkpoint_migration.snap | 10 +- ..._extra_policy_reaches_guardian_review.snap | 10 +- ...g_refresh_preserves_tools_and_history.snap | 6 +- ...inator_catalog_instructions_and_tools.snap | 12 +- ...og_dedup__repository_skill_turn_grant.snap | 13 +- ...ite__scenarios__subagent_browser_auth.snap | 10 +- ...eb_search__literature_search_and_open.snap | 10 +- akode-rs/http-client/src/client_builder.rs | 10 +- akode-rs/model-provider-info/src/lib.rs | 46 ++++- .../src/model_provider_info_tests.rs | 27 +++ 26 files changed, 504 insertions(+), 114 deletions(-) create mode 100644 akode-rs/core/src/tool_order.rs diff --git a/akode-rs/akode-api/src/endpoint/responses.rs b/akode-rs/akode-api/src/endpoint/responses.rs index 3932750b..e40c04bb 100644 --- a/akode-rs/akode-api/src/endpoint/responses.rs +++ b/akode-rs/akode-api/src/endpoint/responses.rs @@ -132,9 +132,12 @@ impl ResponsesClient { Compression::Zstd => RequestCompression::Zstd, }; - let stream_response = self - .session - .stream_encoded_json_with( + let idle_timeout = self.session.provider().stream_idle_timeout; + // Local servers may send the headers only with the first token, after reading the whole + // prompt: the wait is bounded by the same (generous, configurable) idle timeout. + let stream_response = tokio::time::timeout( + idle_timeout, + self.session.stream_encoded_json_with( Method::POST, "/responses", extra_headers, @@ -146,12 +149,19 @@ impl ResponsesClient { ); req.compression = request_compression; }, - ) - .await?; + ), + ) + .await + .map_err(|_| { + ApiError::Stream(format!( + "nessuna risposta dal server entro {} s (stream_idle_timeout_ms)", + idle_timeout.as_secs() + )) + })??; Ok(spawn_response_stream( stream_response, - self.session.provider().stream_idle_timeout, + idle_timeout, self.sse_telemetry.clone(), turn_state, )) diff --git a/akode-rs/akode-api/src/sse/responses.rs b/akode-rs/akode-api/src/sse/responses.rs index a996be29..b146c6d7 100644 --- a/akode-rs/akode-api/src/sse/responses.rs +++ b/akode-rs/akode-api/src/sse/responses.rs @@ -25,7 +25,6 @@ use std::sync::OnceLock; use std::time::Duration; use tokio::sync::mpsc; use tokio::time::Instant; -use tokio::time::timeout; use tracing::debug; use tracing::trace; @@ -536,6 +535,16 @@ async fn process_sse_with_treatment( telemetry: Option>, safety_buffering_treatment: SafetyBufferingTreatment, ) { + // Any bytes from the server are a sign of life: SSE comments (`: ...`) and events this + // client does not use (`imeai.queue`, `imeai.prefill` while the server waits or reads the + // prompt) restart the idle timer, even though the parser yields no event for comments. + let last_activity = Arc::new(std::sync::Mutex::new(Instant::now())); + let activity = Arc::clone(&last_activity); + let stream = stream.inspect(move |chunk| { + if chunk.is_ok() { + *activity.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Instant::now(); + } + }); let mut stream = stream.eventsource(); let mut response_error: Option = None; let mut last_server_model: Option = None; @@ -545,7 +554,7 @@ async fn process_sse_with_treatment( let response = tokio::select! { biased; _ = tx_event.closed() => return, - response = timeout(idle_timeout, stream.next()) => response, + response = next_with_activity_timeout(&mut stream, &last_activity, idle_timeout) => response, }; if let Some(t) = telemetry.as_ref() { t.on_sse_poll(&response, start.elapsed()); @@ -580,6 +589,11 @@ async fn process_sse_with_treatment( trace!("SSE event: {}", &sse.data); + if is_server_progress_event(&sse.event) { + // Queue position and prompt-reading progress: only signs of life for this client. + continue; + } + let event: ResponsesStreamEvent = match serde_json::from_str(&sse.data) { Ok(event) => event, Err(e) => { @@ -656,6 +670,40 @@ async fn process_sse_with_treatment( } } +/// Progress events of local servers (imeAI gateway): `imeai.queue`, `imeai.prefill`, ... +fn is_server_progress_event(event: &str) -> bool { + event.starts_with("imeai.") +} + +/// Waits for the next SSE event; fails only after `idle_timeout` without any bytes at all, so +/// keep-alive comments and progress events keep a long prompt read alive. +async fn next_with_activity_timeout( + stream: &mut S, + last_activity: &std::sync::Mutex, + idle_timeout: Duration, +) -> Result, tokio::time::error::Elapsed> +where + S: futures::Stream + Unpin, +{ + loop { + let since = *last_activity + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let deadline = since + idle_timeout; + match tokio::time::timeout_at(deadline, stream.next()).await { + Ok(item) => return Ok(item), + Err(elapsed) => { + let latest = *last_activity + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if latest == since { + return Err(elapsed); + } + } + } + } +} + #[cfg(test)] #[path = "responses_error_tests.rs"] mod error_tests; @@ -1049,6 +1097,62 @@ mod tests { } } + /// Byte stream that sends `chunks` with `gap` of silence before each one, then waits forever. + fn paced_stream(chunks: Vec<&'static str>, gap: Duration) -> ByteStream { + let stream = stream::iter(chunks).then(move |chunk| async move { + tokio::time::sleep(gap).await; + Ok::(Bytes::from(chunk)) + }); + Box::pin(stream.chain(stream::pending())) + } + + async fn collect_until_closed(stream: ByteStream) -> Vec> { + let (tx, mut rx) = mpsc::channel::>(16); + tokio::spawn(process_sse(stream, tx, idle_timeout(), /*telemetry*/ None)); + let mut events = Vec::new(); + while let Some(ev) = rx.recv().await { + events.push(ev); + } + events + } + + #[tokio::test(start_paused = true)] + async fn keepalive_comments_and_progress_events_reset_the_idle_timer() { + // 4 s of waiting and prompt reading with the 1 s idle timeout: each chunk arrives + // after 600 ms, so only the bytes themselves keep the stream alive. + let completed = r#"event: response.completed +data: {"type":"response.completed","response":{"id":"resp1"}} + +"#; + let stream = paced_stream( + vec![ + ": in coda\n\n", + "event: imeai.queue\ndata: {\"queued\":true,\"ahead\":1,\"position\":2}\n\n", + ": in coda\n\n", + "event: imeai.prefill\ndata: {\"percent\":40,\"eta_s\":3.0}\n\n", + "event: imeai.prefill\ndata: {\"percent\":90,\"eta_s\":0.5}\n\n", + ": attesa\n\n", + completed, + ], + Duration::from_millis(600), + ); + + let events = collect_until_closed(stream).await; + + assert_eq!(events.len(), 1, "{events:?}"); + assert_matches!(&events[0], Ok(ResponseEvent::Completed { response_id, .. }) if response_id == "resp1"); + } + + #[tokio::test(start_paused = true)] + async fn silence_longer_than_idle_timeout_still_fails() { + let stream = paced_stream(vec![": in coda\n\n"], Duration::from_millis(200)); + + let events = collect_until_closed(stream).await; + + assert_eq!(events.len(), 1, "{events:?}"); + assert_matches!(&events[0], Err(ApiError::Stream(message)) if message.contains("idle timeout")); + } + #[tokio::test(start_paused = true)] async fn rate_limit_error_preserves_retry_delay() { let raw_error = r#"{"type":"response.failed","sequence_number":3,"response":{"id":"resp_689bcf18d7f08194bf3440ba62fe05d803fee0cdac429894","object":"response","created_at":1755041560,"status":"failed","background":false,"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.1 in organization org-AAA on tokens per min (TPM): Limit 30000, Used 22999, Requested 12528. Please try again in 11.054s. Visit https://platform.openai.com/account/rate-limits to learn more."}, "usage":null,"user":null,"metadata":{}}}"#; diff --git a/akode-rs/akode-mcp/src/connection_manager_tests.rs b/akode-rs/akode-mcp/src/connection_manager_tests.rs index b3eebf7e..660274a9 100644 --- a/akode-rs/akode-mcp/src/connection_manager_tests.rs +++ b/akode-rs/akode-mcp/src/connection_manager_tests.rs @@ -2455,13 +2455,13 @@ async fn capture_binding_shares_optional_startup_grace_across_connection_sets() let first_started = tokio::time::Instant::now(); let first = tokio::time::timeout( - Duration::from_millis(1500), + crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE + Duration::from_millis(500), capture_binding(&create_connection_set()), ) .await .expect("the first thread should receive the optional startup grace"); assert!(first.tools().is_empty()); - assert_eq!(first_started.elapsed(), Duration::from_secs(1)); + assert_eq!(first_started.elapsed(), crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE); let second = tokio::time::timeout( Duration::from_millis(1), @@ -2491,13 +2491,13 @@ async fn capture_binding_shares_optional_startup_grace_across_connection_sets() let restored_started = tokio::time::Instant::now(); let restored = tokio::time::timeout( - Duration::from_millis(1500), + crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE + Duration::from_millis(500), capture_binding(&create_connection_set()), ) .await .expect("restoring the startup grace should create a fresh deadline"); assert!(restored.tools().is_empty()); - assert_eq!(restored_started.elapsed(), Duration::from_secs(1)); + assert_eq!(restored_started.elapsed(), crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE); let mut updated_config = crate::mcp::tests::test_mcp_config(std::env::temp_dir()); updated_config.optional_mcp_startup_grace = Duration::from_millis(250); @@ -2553,13 +2553,13 @@ async fn capture_binding_shares_optional_startup_grace_across_connection_sets() for _ in 0..2 { let started = tokio::time::Instant::now(); let binding = tokio::time::timeout( - Duration::from_millis(1500), + crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE + Duration::from_millis(500), capture_binding(&create_connection_set()), ) .await .expect("non-cacheable servers should keep their per-thread startup grace"); assert!(binding.tools().is_empty()); - assert_eq!(started.elapsed(), Duration::from_secs(1)); + assert_eq!(started.elapsed(), crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE); } } diff --git a/akode-rs/akode-mcp/src/mcp/mod.rs b/akode-rs/akode-mcp/src/mcp/mod.rs index e56a66fc..2b8b3403 100644 --- a/akode-rs/akode-mcp/src/mcp/mod.rs +++ b/akode-rs/akode-mcp/src/mcp/mod.rs @@ -186,8 +186,11 @@ pub struct McpConfig { pub mcp_server_catalog: ResolvedMcpCatalog, } -/// Default amount of time a tool catalog capture waits for optional MCP servers. -pub const DEFAULT_OPTIONAL_MCP_STARTUP_GRACE: Duration = Duration::from_secs(1); +/// Default amount of time the first tool catalog capture of a session waits for optional MCP +/// servers. The wait happens once per session: with the complete tool list in the first +/// request, the prompt prefix cached by local servers stays valid (tools that still arrive +/// later are appended at the end of the list). +pub const DEFAULT_OPTIONAL_MCP_STARTUP_GRACE: Duration = Duration::from_secs(5); impl McpConfig { /// Resolves enabled runtime servers against the exact attachment permissions being published. diff --git a/akode-rs/core/config.schema.json b/akode-rs/core/config.schema.json index 99cda959..c881b9a9 100644 --- a/akode-rs/core/config.schema.json +++ b/akode-rs/core/config.schema.json @@ -3234,7 +3234,7 @@ "type": "boolean" }, "stream_idle_timeout_ms": { - "description": "Idle timeout (in milliseconds) to wait for activity on a streaming response before treating the connection as lost.", + "description": "Idle timeout (in milliseconds) to wait for activity on a streaming response before treating the connection as lost. It also bounds the wait for the first response (headers). Any bytes count as activity, including SSE comments and progress events. Defaults to 5 minutes, or 30 minutes for local servers.", "format": "uint64", "minimum": 0.0, "type": "integer" diff --git a/akode-rs/core/src/client.rs b/akode-rs/core/src/client.rs index f8ceca20..f6c7df88 100644 --- a/akode-rs/core/src/client.rs +++ b/akode-rs/core/src/client.rs @@ -205,6 +205,8 @@ struct ModelClientState { cached_websocket_session: StdMutex, /// Last full tool list used for sampling, retained across turns and connection resets. last_inference_tools: StdMutex>>, + /// Order of the tool definitions sent in this session (stable for the prompt cache). + tool_order: crate::tool_order::ToolOrder, /// Per-model settings of the provider (sampling values), refreshed with the user config. model_settings: StdMutex< std::collections::BTreeMap, @@ -591,6 +593,7 @@ impl ModelClient { disable_websockets: AtomicBool::new(false), cached_websocket_session: StdMutex::new(WebsocketSession::default()), last_inference_tools: StdMutex::new(None), + tool_order: crate::tool_order::ToolOrder::default(), model_settings, }), prompt_cache_key_policy: PromptCacheKey::default(), @@ -1100,8 +1103,10 @@ impl ModelClient { // aKode talks only to OpenAI-compatible servers, which accept function tools only: // namespaces (MCP servers, multi-agent tools) are flattened to `__`, // and past calls are replayed with the same flat names. - if self.state.provider.capabilities().tool_namespaces { - Some(create_tools_raw_json_for_responses_api(&prompt.tools)?.into()) + // The tool list is sent in a stable order (see `tool_order`): local servers cache + // the prompt prefix, and templates render the tools near its top. + let raw = if self.state.provider.capabilities().tool_namespaces { + create_tools_raw_json_for_responses_api(&prompt.tools)? } else { for item in &mut input { if let ResponseItem::FunctionCall { name, namespace, .. } = item @@ -1110,8 +1115,13 @@ impl ModelClient { *name = format!("{ns}{FLAT_NAMESPACE_SEPARATOR}{name}"); } } - Some(create_flat_tools_raw_json_for_responses_api(&prompt.tools)?.into()) - } + create_flat_tools_raw_json_for_responses_api(&prompt.tools)? + }; + let mut tools: Vec = serde_json::from_str(raw.get())?; + self.state.tool_order.apply(&mut tools); + let raw: Arc = + serde_json::value::to_raw_value(&tools).map(Arc::from)?; + Some(raw.into()) }; if !prompt.base_instructions.text.is_empty() { let mut instructions = ContextualUserFragment::into(BaseInstructionsFragment( diff --git a/akode-rs/core/src/lib.rs b/akode-rs/core/src/lib.rs index bd9dbe37..4bc58cda 100644 --- a/akode-rs/core/src/lib.rs +++ b/akode-rs/core/src/lib.rs @@ -41,6 +41,7 @@ mod compact_retained_tool_outputs; mod compact_token_budget; pub mod compaction_metadata; mod merge_system_messages; +mod tool_order; mod thread_startup_metadata; pub use akode_network_proxy::EnvironmentNetworkPolicy; pub use akode_network_proxy::NetworkDomainPermission; diff --git a/akode-rs/core/src/responses_metadata.rs b/akode-rs/core/src/responses_metadata.rs index af387da8..d2a51934 100644 --- a/akode-rs/core/src/responses_metadata.rs +++ b/akode-rs/core/src/responses_metadata.rs @@ -503,24 +503,7 @@ impl CodexResponsesMetadata { /// (`localhost`, 127.0.0.0/8, `::1`), private IPv4 (10/8, 172.16/12, 192.168/16) and /// `.local`/`.lan` hosts. Remote services (OpenRouter and similar) and an unset base URL do not. pub(crate) fn provider_shares_client_identity(base_url: Option<&str>) -> bool { - let Some(base_url) = base_url else { - return false; - }; - let Ok(url) = url::Url::parse(base_url.trim()) else { - return false; - }; - match url.host() { - Some(url::Host::Ipv4(ip)) => ip.is_loopback() || ip.is_private(), - Some(url::Host::Ipv6(ip)) => ip.is_loopback(), - Some(url::Host::Domain(host)) => { - let host = host.trim_end_matches('.').to_ascii_lowercase(); - host == "localhost" - || host.ends_with(".localhost") - || host.ends_with(".local") - || host.ends_with(".lan") - } - None => false, - } + base_url.is_some_and(akode_model_provider_info::is_local_base_url) } pub(crate) fn subagent_header_value(session_source: &SessionSource) -> Option { diff --git a/akode-rs/core/src/session/mod.rs b/akode-rs/core/src/session/mod.rs index 1205b1a2..b002da53 100644 --- a/akode-rs/core/src/session/mod.rs +++ b/akode-rs/core/src/session/mod.rs @@ -4800,6 +4800,11 @@ impl Session { developer_sections .push(DeveloperInstructions::new(developer_instructions).render_fragment()); } + // Extension blocks (``, memory briefing, ...) depend on the repository and the + // session, so they go after the built-in sections (skills, permissions, ...) that are the + // same for every session: the cached prompt prefix stays reusable across sessions and + // the block order is fixed. + let mut extension_sections = Vec::::new(); let context_contributors = self.services.extensions.context_contributors().to_vec(); for contributor in &context_contributors { for fragment in contributor @@ -4814,7 +4819,7 @@ impl Session { context_window_hints.push(fragment.into_content()); } PromptSlot::DeveloperPolicy | PromptSlot::DeveloperCapabilities => { - developer_sections.push(fragment.into()); + extension_sections.push(fragment.into()); } } } @@ -4831,7 +4836,7 @@ impl Session { }) .await { - developer_sections.push(fragment.into()); + extension_sections.push(fragment.into()); } } // This is full-context metadata. Steady-state context diffs should not re-emit it. @@ -4940,6 +4945,7 @@ impl Session { } } + developer_sections.append(&mut extension_sections); if let Some(developer_message) = crate::context_manager::updates::build_rendered_message( std::mem::take(&mut developer_sections), ) { diff --git a/akode-rs/core/src/tool_order.rs b/akode-rs/core/src/tool_order.rs new file mode 100644 index 00000000..53475974 --- /dev/null +++ b/akode-rs/core/src/tool_order.rs @@ -0,0 +1,172 @@ +//! Stable order of the tool definitions sent to the provider. +//! +//! Local servers cache the prompt prefix, and chat templates render the tool list near the top +//! of the prompt: a different order, or a tool inserted in the middle, invalidates the cached +//! prompt from that point on. The list is therefore sorted (top-level tools first, then +//! namespaced ones such as MCP servers, each by name), and within a session the order of the +//! first request is kept: tools that appear later (an MCP server that finished starting after +//! the first request) are appended at the end, never in the middle. + +use akode_tools::FLAT_NAMESPACE_SEPARATOR; +use serde_json::Value; +use std::collections::HashMap; +use std::sync::Mutex; + +/// Order memory of one session: tool keys in the order they were first sent. +#[derive(Debug, Default)] +pub(crate) struct ToolOrder { + seen: Mutex>, +} + +impl ToolOrder { + /// Reorders `tools` (JSON tool definitions) in place: known tools in their first-seen order, + /// new tools after them in canonical order. Namespace members are sorted by name. + pub(crate) fn apply(&self, tools: &mut Vec) { + for tool in tools.iter_mut() { + if let Some(members) = tool.get_mut("tools").and_then(Value::as_array_mut) { + members.sort_by(|a, b| tool_key(a).cmp(&tool_key(b))); + } + } + tools.sort_by(|a, b| canonical_key(a).cmp(&canonical_key(b))); + + let mut seen = self + .seen + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let position: HashMap = seen + .iter() + .enumerate() + .map(|(index, key)| (key.clone(), index)) + .collect(); + let (mut known, new): (Vec, Vec) = std::mem::take(tools) + .into_iter() + .partition(|tool| position.contains_key(&tool_key(tool))); + known.sort_by_key(|tool| position.get(&tool_key(tool)).copied().unwrap_or(usize::MAX)); + for tool in &new { + seen.push(tool_key(tool)); + } + known.extend(new); + *tools = known; + } +} + +/// Name of a tool definition (`name`, or `type` for hosted tools such as `web_search`). +fn tool_key(tool: &Value) -> String { + match tool.get("name").and_then(Value::as_str) { + Some(name) => name.to_string(), + None => tool + .get("type") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + } +} + +/// Top-level tools first, then namespaces and flattened namespace members, each by name. +fn canonical_key(tool: &Value) -> (bool, String) { + let key = tool_key(tool); + let namespaced = tool.get("type").and_then(Value::as_str) == Some("namespace") + || key.contains(FLAT_NAMESPACE_SEPARATOR); + (namespaced, key) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use serde_json::json; + + fn names(tools: &[Value]) -> Vec { + tools.iter().map(tool_key).collect() + } + + fn function(name: &str) -> Value { + json!({"type": "function", "name": name, "parameters": {}}) + } + + #[test] + fn same_tools_in_any_order_give_the_same_list() { + let first = ToolOrder::default(); + let second = ToolOrder::default(); + let mut a = vec![ + function("exec_command"), + function("memoria__memory_search"), + function("apply_patch"), + json!({"type": "web_search"}), + function("request_user_input"), + ]; + let mut b = a.clone(); + b.reverse(); + + first.apply(&mut a); + second.apply(&mut b); + + assert_eq!(a, b); + assert_eq!( + names(&a), + vec![ + "apply_patch", + "exec_command", + "request_user_input", + "web_search", + "memoria__memory_search", + ] + ); + } + + #[test] + fn tools_that_appear_later_go_at_the_end() { + let order = ToolOrder::default(); + let mut first = vec![function("exec_command"), function("apply_patch")]; + order.apply(&mut first); + assert_eq!(names(&first), vec!["apply_patch", "exec_command"]); + + // An MCP server finished starting, and a built-in tool that sorts first appeared too. + let mut later = vec![ + function("memoria__memory_search"), + function("exec_command"), + function("apply_patch"), + function("aaa_new_builtin"), + function("list_mcp_resources"), + ]; + order.apply(&mut later); + assert_eq!( + names(&later), + vec![ + "apply_patch", + "exec_command", + "aaa_new_builtin", + "list_mcp_resources", + "memoria__memory_search", + ] + ); + + // The next request keeps that order exactly. + let mut again = later.clone(); + again.reverse(); + order.apply(&mut again); + assert_eq!(again, later); + } + + #[test] + fn removed_tools_do_not_move_the_others() { + let order = ToolOrder::default(); + let mut first = vec![function("a"), function("b"), function("c")]; + order.apply(&mut first); + let mut without_b = vec![function("c"), function("a")]; + order.apply(&mut without_b); + assert_eq!(names(&without_b), vec!["a", "c"]); + } + + #[test] + fn namespace_members_are_sorted() { + let order = ToolOrder::default(); + let mut tools = vec![json!({ + "type": "namespace", + "name": "memoria", + "tools": [function("z_tool"), function("a_tool")], + })]; + order.apply(&mut tools); + assert_eq!(names(tools[0]["tools"].as_array().unwrap()), vec!["a_tool", "z_tool"]); + } +} diff --git a/akode-rs/core/tests/suite/code_mode.rs b/akode-rs/core/tests/suite/code_mode.rs index ac9ac959..7c73b650 100644 --- a/akode-rs/core/tests/suite/code_mode.rs +++ b/akode-rs/core/tests/suite/code_mode.rs @@ -940,10 +940,11 @@ async fn code_mode_only_restricts_prompt_tools() -> Result<()> { let first_body = resp_mock.single_request().body_json(); assert_eq!( tool_names(&first_body), + // Sorted by name: aKode keeps the tool list in a stable order. vec![ "exec".to_string(), - "wait".to_string(), "request_user_input".to_string(), + "wait".to_string(), "web_search".to_string() ] ); @@ -3107,10 +3108,11 @@ if (!tool) { let first_body = resp_mock.single_request().body_json(); assert_eq!( tool_names(&first_body), + // Sorted by name: aKode keeps the tool list in a stable order. vec![ "exec".to_string(), - "wait".to_string(), "request_user_input".to_string(), + "wait".to_string(), "web_search".to_string() ] ); diff --git a/akode-rs/core/tests/suite/model_runtime_selectors.rs b/akode-rs/core/tests/suite/model_runtime_selectors.rs index 229b6364..31d97046 100644 --- a/akode-rs/core/tests/suite/model_runtime_selectors.rs +++ b/akode-rs/core/tests/suite/model_runtime_selectors.rs @@ -196,11 +196,13 @@ async fn remote_tool_mode_selector_overrides_feature_flags() -> Result<()> { let code_mode_only_body = response_body_for_remote_model(code_mode_only_model, |_| {}).await?; assert_eq!( tool_names(&code_mode_only_body), + // aKode sends the tools sorted by name for a stable prompt prefix. vec![ - // Code-mode entrypoints. + // Code-mode entrypoint. akode_code_mode::PUBLIC_TOOL_NAME.to_string(), - akode_code_mode::WAIT_TOOL_NAME.to_string(), "request_user_input".to_string(), + // Code-mode entrypoint. + akode_code_mode::WAIT_TOOL_NAME.to_string(), // Hosted Responses tool. "web_search".to_string(), ] diff --git a/akode-rs/core/tests/suite/prompt_caching.rs b/akode-rs/core/tests/suite/prompt_caching.rs index 57034dce..f6b2b236 100644 --- a/akode-rs/core/tests/suite/prompt_caching.rs +++ b/akode-rs/core/tests/suite/prompt_caching.rs @@ -267,17 +267,18 @@ async fn prompt_tools_are_consistent_across_requests( .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - let mut expected_tools_names = vec!["exec_command", "write_stdin"]; + // aKode sends the tools sorted by name (top-level tools before namespaced ones), so the + // cached prompt prefix does not depend on the registration order. + let mut expected_tools_names = vec![ + "apply_patch", + "exec_command", + "request_user_input", + "tool_search", + ]; if expected_update_plan_enabled { expected_tools_names.push("update_plan"); } - expected_tools_names.extend([ - "request_user_input", - "apply_patch", - "view_image", - "tool_search", - "web_search", - ]); + expected_tools_names.extend(["view_image", "web_search", "write_stdin"]); let body0 = req1.single_request().body_json(); assert_eq!(req1.single_request().instructions_text(), base_instructions); diff --git a/akode-rs/core/tests/suite/rmcp_client.rs b/akode-rs/core/tests/suite/rmcp_client.rs index 0f9a3045..96863e34 100644 --- a/akode-rs/core/tests/suite/rmcp_client.rs +++ b/akode-rs/core/tests/suite/rmcp_client.rs @@ -1779,7 +1779,9 @@ async fn ready_mcp_turn_skips_pending_optional_mcp_without_cached_tools() -> any .await .context("the calendar MCP server should finish starting before the first turn")??; - tokio::time::timeout(Duration::from_secs(5), fixture.submit_turn("hello")) + // The first turn waits for pending optional servers at most for the startup grace + // (5 s in aKode, so the first request has the complete tool list), never longer. + tokio::time::timeout(Duration::from_secs(15), fixture.submit_turn("hello")) .await .context("a pending optional MCP must not block the first turn")??; let body = response_mock.single_request().body_json(); diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__context_management_tools__catalog_context_tool_definitions_follow_captured_models.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__context_management_tools__catalog_context_tool_definitions_follow_captured_models.snap index a5761d54..d867846a 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__context_management_tools__catalog_context_tool_definitions_follow_captured_models.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__context_management_tools__catalog_context_tool_definitions_follow_captured_models.snap @@ -15,16 +15,16 @@ Settings: stream: true text: {"verbosity":"low"} tool_choice: "auto" - tools (9; hash=5edab7fdbfe2dd93): - - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - - function/new_context: Catalog context guidance.; args=[]; hash=8d300f346fb11d84 - - function/get_context_remaining: Catalog context guidance.; args=[]; hash=802b1cf4a796b439 + tools (9; hash=f33c03d87ec35581): - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba - - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a + - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 + - function/get_context_remaining: Catalog context guidance.; args=[]; hash=802b1cf4a796b439 + - function/new_context: Catalog context guidance.; args=[]; hash=8d300f346fb11d84 + - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7 + - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a - web_search; hash=f103e327c6870a46 + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 -- request 1 (turn) -- 00:message/developer: @@ -50,9 +50,9 @@ Settings: ## Window 2 (after request 1) Settings: relative to window 1 model: "context-tools-updated" - tools (9; hash=829060c0abfc8021): - ~ function/new_context; args=[]; hash=b9263827b0adbb78 + tools (9; hash=07305d52033debdd): ~ function/get_context_remaining; args=[]; hash=3e96d66806c56bdd + ~ function/new_context; args=[]; hash=b9263827b0adbb78 -- request 2 (turn) -- 00:message/developer: diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__dynamic_tools__dynamic_tools_update_preserves_pending_calls_and_survives_resume.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__dynamic_tools__dynamic_tools_update_preserves_pending_calls_and_survives_resume.snap index 24e08bae..3380b95e 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__dynamic_tools__dynamic_tools_update_preserves_pending_calls_and_survives_resume.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__dynamic_tools__dynamic_tools_update_preserves_pending_calls_and_survives_resume.snap @@ -1,6 +1,5 @@ --- source: core/tests/suite/scenarios_dynamic_tools.rs -assertion_line: 173 expression: "context_snapshot::format_request_history_snapshot(\"A pending release call survives replacement with deployment. The next step uses deployment. Replacement and clearing each survive restart.\",\n&requests,\n&ContextSnapshotOptions::default().rewrite_known_segments().include_request_settings(),)" --- Scenario: A pending release call survives replacement with deployment. The next step uses deployment. Replacement and clearing each survive restart. @@ -16,16 +15,18 @@ Settings: stream: true text: {"verbosity":"low"} tool_choice: "auto" - tools (10; hash=b0582dd610604bdb): + tools (10; hash=99b5ba849261f041): + - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 + - function/release: Check release.; args=[]; hash=4c6f91a1a21d2a65 - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - function/request_user_input_async: Ask the user one or more questions during ongoing work. Use this tool only to request missing inf...; args=[questions]; hash=d6d74f33db330162 + - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a + - web_search; hash=f103e327c6870a46 + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - namespace/clock: Tools for reading and waiting on time.; hash=a80435c7a3a3943f - function/curr_time - function/sleep - - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba - - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=2c8d6295978dbe63 - function/followup_task - function/interrupt_agent @@ -33,8 +34,6 @@ Settings: - function/send_message - function/spawn_agent - function/wait_agent - - function/release: Check release.; args=[]; hash=4c6f91a1a21d2a65 - - web_search; hash=f103e327c6870a46 -- request 1 (turn) -- 00:message/developer: @@ -51,7 +50,7 @@ Settings: ## Window 2 (after request 1) Settings: relative to window 1 - tools (10; hash=d346da81584ec2d3): + tools (10; hash=2f34710828e791df): - removed function/release + function/deployment: Check deployment.; args=[]; hash=2e9a71e9a20e43ad -- request 2 (turn) -- @@ -72,16 +71,37 @@ Settings: relative to window 1 -- request 3 (turn) -- 08:function_call/deployment:{} 09:function_call_output:Deployment ready. + +## Window 3 (after request 3) +Settings: relative to window 2 + tools (10; hash=966235d04fff4485): + - order changed -- request 4 (turn) -- +00:message/developer: + +01:message/developer[2]: + [01] + [02] +02:message/developer: + +03:message/developer: + +04:message/user: + Check the release and deployment. +05:configuration_update:reasoning={"effort":"low"} +06:function_call/release:{} +07:function_call_output:Release ready. +08:function_call/deployment:{} +09:function_call_output:Deployment ready. 10:message/assistant: Both checks passed. 11:message/user: Which check is available now? 12:configuration_update:reasoning={"effort":"low"} -## Window 3 (after request 4) -Settings: relative to window 2 - tools (9; hash=79c1c8bb10577e35): +## Window 4 (after request 4) +Settings: relative to window 3 + tools (9; hash=653a7a527be8666f): - removed function/deployment -- request 5 (turn) -- 00:message/developer: diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_checkpoint_migration.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_checkpoint_migration.snap index b239c40c..72f7a28f 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_checkpoint_migration.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_checkpoint_migration.snap @@ -15,14 +15,14 @@ Settings: stream: true text: {"verbosity":"low"} tool_choice: "auto" - tools (7; hash=c8fad8866d479502): - - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=7c8f464569dbaa9c + tools (7; hash=ce2e8d0c67677152): - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba - - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a + - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 + - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=7c8f464569dbaa9c - tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7 + - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a - web_search; hash=f103e327c6870a46 + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 -- request 1 (turn) -- 00:message/developer: diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_extra_policy__extra_policy_reaches_guardian_review.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_extra_policy__extra_policy_reaches_guardian_review.snap index c06a0ff3..fdd284c5 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_extra_policy__extra_policy_reaches_guardian_review.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_extra_policy__extra_policy_reaches_guardian_review.snap @@ -15,14 +15,14 @@ Settings: stream: true text: {"verbosity":"low"} tool_choice: "auto" - tools (7; hash=4bc85f667bb09668): - - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 + tools (7; hash=764c6164350ee754): - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba - - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a + - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 + - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7 + - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a - web_search; hash=f103e327c6870a46 + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 -- request 1 (turn) -- 00:message/developer: You are Codex, a coding agent based on GPT-5. You and the user share one workspace, and your job is to c...rate with them until their goal is genuinely handled. [hash=2a3efec66e7f8963] diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__model_catalog_refresh_preserves_tools_and_history.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__model_catalog_refresh_preserves_tools_and_history.snap index e7d2ffa5..128d3c6d 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__model_catalog_refresh_preserves_tools_and_history.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__model_catalog_refresh_preserves_tools_and_history.snap @@ -14,18 +14,18 @@ Settings: store: false stream: true tool_choice: "auto" - tools (6; hash=1ea0fa9abde186d4): + tools (6; hash=8cd55cc11303929a): - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a + - web_search; hash=8586237e354ee5ed + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - namespace/multi_agent_v1: Tools for spawning and managing sub-agents.; hash=94c598b3c6ca141b - function/close_agent - function/resume_agent - function/send_input - function/spawn_agent - function/wait_agent - - web_search; hash=8586237e354ee5ed -- request 1 (turn) -- 00:message/developer: Test model instructions. diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__model_instructions__originator_catalog_instructions_and_tools.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__model_instructions__originator_catalog_instructions_and_tools.snap index 1f977eea..3773d19b 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__model_instructions__originator_catalog_instructions_and_tools.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__model_instructions__originator_catalog_instructions_and_tools.snap @@ -14,18 +14,18 @@ Settings: store: false stream: true tool_choice: "auto" - tools (6; hash=d558f97965d6db2b): + tools (6; hash=7a20be349fb5986f): - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a + - web_search; hash=8586237e354ee5ed + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - namespace/multi_agent_v1: Tools for spawning and managing sub-agents.; hash=6ac4ec60e68e50c0 - function/close_agent - function/resume_agent - function/send_input - function/spawn_agent - function/wait_agent - - web_search; hash=8586237e354ee5ed -- request 1 (turn) -- 00:message/developer: @@ -39,7 +39,7 @@ Settings: ## Window 2 (after request 1: input diverged at item 00) Settings: relative to window 1 prompt_cache_key: "" - tools (7; hash=7cc079a7a7aa5604): + tools (7; hash=4cb623b0b7a8ea0a): + custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba -- request 2 (turn) -- 00:message/developer: @@ -54,7 +54,7 @@ Settings: relative to window 1 ## Window 3 (after request 2: input diverged at item 00) Settings: relative to window 2 prompt_cache_key: "" - tools (6; hash=d558f97965d6db2b): + tools (6; hash=7a20be349fb5986f): - removed custom/apply_patch -- request 3 (turn) -- 00:message/developer: @@ -82,7 +82,7 @@ Settings: relative to window 3 ## Window 5 (after request 4: input diverged at item 00) Settings: relative to window 4 prompt_cache_key: "" - tools (7; hash=7cc079a7a7aa5604): + tools (7; hash=4cb623b0b7a8ea0a): + custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba -- request 5 (turn) -- 00:message/developer: diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__skill_catalog_dedup__repository_skill_turn_grant.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__skill_catalog_dedup__repository_skill_turn_grant.snap index 07da9ca5..a50c215e 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__skill_catalog_dedup__repository_skill_turn_grant.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__skill_catalog_dedup__repository_skill_turn_grant.snap @@ -1,6 +1,5 @@ --- source: core/tests/suite/scenarios_skill_catalog_dedup.rs -assertion_line: 518 expression: "context_snapshot::format_context_snapshot(\"A repository skill appears after approval. The next turn withdraws it, then restores it after reapproval.\",\n&bodies.iter().map(context_snapshot::SnapshotEntry::body).collect::>(),\n&ContextSnapshotOptions::default().include_request_settings(),)" --- Scenario: A repository skill appears after approval. The next turn withdraws it, then restores it after reapproval. @@ -16,15 +15,15 @@ Settings: stream: true text: {"verbosity":"low"} tool_choice: "auto" - tools (8; hash=b8620d538c3808d4): - - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - - function/request_permissions: Request additional filesystem or network permissions from the user and wait for the client to gra...; args=[environment_id, permissions, reason]; hash=2ed084e2fc688abd + tools (8; hash=9fd6c407aefab802): - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba - - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a + - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 + - function/request_permissions: Request additional filesystem or network permissions from the user and wait for the client to gra...; args=[environment_id, permissions, reason]; hash=2ed084e2fc688abd + - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7 + - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a - web_search; hash=f103e327c6870a46 + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 -- request 1 (request) -- 00:message/developer: You are Codex, a coding agent based on GPT-5. You and the user share one workspace, and your job is to c...rate with them until their goal is genuinely handled. [hash=2a3efec66e7f8963] diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__subagent_browser_auth.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__subagent_browser_auth.snap index abd084ce..5474b9c8 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__subagent_browser_auth.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__subagent_browser_auth.snap @@ -15,17 +15,17 @@ Settings: stream: true text: {"verbosity":"low"} tool_choice: "auto" - tools (10; hash=9f8074d045f3bd93): + tools (10; hash=e36030ebe33fb877): + - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - - function/list_mcp_resources: Lists resources provided by MCP servers. Resources allow servers to share data that provides cont...; args=[cursor, server]; hash=6792edaff13561bd - function/list_mcp_resource_templates: Lists resource templates provided by MCP servers. Parameterized resource templates allow servers ...; args=[cursor, server]; hash=60f17c90ef7a4ebb + - function/list_mcp_resources: Lists resources provided by MCP servers. Resources allow servers to share data that provides cont...; args=[cursor, server]; hash=6792edaff13561bd - function/read_mcp_resource: Read a specific resource from an MCP server given the server name and resource URI.; args=[server, uri]; hash=24246896b39008ae - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 - - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba - - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a - tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7 + - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a - web_search; hash=f103e327c6870a46 + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 -- request 1 (turn) -- 00:message/developer: diff --git a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__web_search__literature_search_and_open.snap b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__web_search__literature_search_and_open.snap index 6ad0ade7..219ffedb 100644 --- a/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__web_search__literature_search_and_open.snap +++ b/akode-rs/core/tests/suite/snapshots/all__suite__scenarios__web_search__literature_search_and_open.snap @@ -15,15 +15,15 @@ Settings: stream: true text: {"verbosity":"low"} tool_choice: "auto" - tools (7; hash=4be6331020d8f43a): - - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 - - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 + tools (7; hash=09449514b073027c): - custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba + - function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5 + - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6 + - tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7 - function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a + - function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2 - namespace/web: Tools in the web namespace.; hash=dd6e98ab1f4ddce6 - function/run - - tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7 -- request 1 (turn) -- 00:message/developer: diff --git a/akode-rs/http-client/src/client_builder.rs b/akode-rs/http-client/src/client_builder.rs index 83415516..fa8f1da0 100644 --- a/akode-rs/http-client/src/client_builder.rs +++ b/akode-rs/http-client/src/client_builder.rs @@ -370,7 +370,15 @@ impl HttpClientBuilder { } fn base_reqwest_builder(self) -> reqwest::ClientBuilder { - let mut builder = reqwest::Client::builder(); + // No TCP keepalive: reqwest probes after 15 s of silence, 3 times every 15 s, and drops + // the connection when nobody answers. Some VPNs (NetBird towards the imeAI server) do + // not pass the probes, so every response that started after more than 60 s (a local + // model reading a long prompt) was cut and sent again from scratch. Dead streams are + // detected by the provider's idle timeout instead. + let mut builder = reqwest::Client::builder() + .tcp_keepalive(None) + .tcp_keepalive_interval(None) + .tcp_keepalive_retries(None); #[cfg(windows)] if let Some(path) = self.windows_proxy_pipe_path { builder = builder.windows_named_pipe(path); diff --git a/akode-rs/model-provider-info/src/lib.rs b/akode-rs/model-provider-info/src/lib.rs index 95c842c5..71b9ea1e 100644 --- a/akode-rs/model-provider-info/src/lib.rs +++ b/akode-rs/model-provider-info/src/lib.rs @@ -79,6 +79,10 @@ pub fn read_managed_residency_requirement() -> Option { } const DEFAULT_STREAM_IDLE_TIMEOUT_MS: u64 = 300_000; +/// Local servers (loopback, private network, `.local`/`.lan`) read long prompts on CPU: a cold +/// prompt of 15k tokens took more than 3 minutes before the first byte. They get a generous +/// default, still overridable with `stream_idle_timeout_ms`. +const DEFAULT_LOCAL_STREAM_IDLE_TIMEOUT_MS: u64 = 1_800_000; const DEFAULT_STREAM_MAX_RETRIES: u64 = 5; const DEFAULT_REQUEST_MAX_RETRIES: u64 = 4; const DEFAULT_CREDENTIAL_EXPORT_TIMEOUT_MS: u64 = 30_000; @@ -198,7 +202,9 @@ pub struct ModelProviderInfo { /// Number of times to retry reconnecting a dropped streaming response before failing. pub stream_max_retries: Option, /// Idle timeout (in milliseconds) to wait for activity on a streaming response before treating - /// the connection as lost. + /// the connection as lost. It also bounds the wait for the first response (headers). Any + /// bytes count as activity, including SSE comments and progress events. Defaults to 5 + /// minutes, or 30 minutes for local servers. pub stream_idle_timeout_ms: Option, /// Maximum time (in milliseconds) to wait for a websocket connection attempt before treating /// it as failed. @@ -521,11 +527,23 @@ impl ModelProviderInfo { .min(MAX_STREAM_MAX_RETRIES) } - /// Effective idle timeout for streaming responses. + /// Effective idle timeout for streaming responses (and for the first response). pub fn stream_idle_timeout(&self) -> Duration { self.stream_idle_timeout_ms .map(Duration::from_millis) - .unwrap_or(Duration::from_millis(DEFAULT_STREAM_IDLE_TIMEOUT_MS)) + .unwrap_or_else(|| { + Duration::from_millis(if self.is_local_endpoint() { + DEFAULT_LOCAL_STREAM_IDLE_TIMEOUT_MS + } else { + DEFAULT_STREAM_IDLE_TIMEOUT_MS + }) + }) + } + + /// Whether `base_url` points to this machine or the local network: loopback, private IPv4, + /// `localhost`, `.localhost`, `.local`, `.lan`. + pub fn is_local_endpoint(&self) -> bool { + self.base_url.as_deref().is_some_and(is_local_base_url) } /// Effective timeout for websocket connect attempts. @@ -656,3 +674,25 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M #[cfg(test)] #[path = "model_provider_info_tests.rs"] mod tests; + +/// See [`ModelProviderInfo::is_local_endpoint`]. +pub fn is_local_base_url(base_url: &str) -> bool { + let Ok(uri) = base_url.trim().parse::() else { + return false; + }; + let Some(host) = uri.host() else { + return false; + }; + let host = host.trim_start_matches('[').trim_end_matches(']'); + if let Ok(ip) = host.parse::() { + return match ip { + std::net::IpAddr::V4(ip) => ip.is_loopback() || ip.is_private(), + std::net::IpAddr::V6(ip) => ip.is_loopback(), + }; + } + let host = host.trim_end_matches('.').to_ascii_lowercase(); + host == "localhost" + || host.ends_with(".localhost") + || host.ends_with(".local") + || host.ends_with(".lan") +} diff --git a/akode-rs/model-provider-info/src/model_provider_info_tests.rs b/akode-rs/model-provider-info/src/model_provider_info_tests.rs index 9aedfbb5..91d7fa01 100644 --- a/akode-rs/model-provider-info/src/model_provider_info_tests.rs +++ b/akode-rs/model-provider-info/src/model_provider_info_tests.rs @@ -505,3 +505,30 @@ display_name = "Flint" assert_eq!(settings.display_name.as_deref(), Some("Flint")); assert!(provider.model_settings("other").is_none()); } + +#[test] +fn local_providers_get_a_generous_idle_timeout() { + let provider = |base_url: &str| -> ModelProviderInfo { + toml::from_str(&format!("name = \"x\"\nbase_url = \"{base_url}\"\n")).expect("provider") + }; + for local in [ + "http://192.168.40.25:8080/v1", + "http://127.0.0.1:8080/v1", + "http://localhost:11434/v1", + "http://[::1]:1234/v1", + "http://imeai.lan/v1", + ] { + assert_eq!( + provider(local).stream_idle_timeout(), + Duration::from_secs(30 * 60), + "{local}" + ); + } + assert_eq!( + provider("https://openrouter.ai/api/v1").stream_idle_timeout(), + Duration::from_secs(5 * 60) + ); + let mut configured = provider("http://192.168.40.25:8080/v1"); + configured.stream_idle_timeout_ms = Some(90_000); + assert_eq!(configured.stream_idle_timeout(), Duration::from_secs(90)); +}