aKode: cache del prompt più stabile e attese lunghe dei server locali (punto 4, blocco A)
- Ordine fisso dei blocchi di contesto: le sezioni uguali in ogni sessione (skill, permessi) vengono prima, quelle delle estensioni (<code_map>, riepilogo della memoria) dopo; prima <code_map> 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 <noreply@anthropic.com>
This commit is contained in:
@@ -205,6 +205,8 @@ struct ModelClientState {
|
||||
cached_websocket_session: StdMutex<WebsocketSession>,
|
||||
/// Last full tool list used for sampling, retained across turns and connection resets.
|
||||
last_inference_tools: StdMutex<Option<Arc<[ToolSpec]>>>,
|
||||
/// 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<String, akode_model_provider_info::ProviderModelSettings>,
|
||||
@@ -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 `<namespace>__<tool>`,
|
||||
// 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::Value> = serde_json::from_str(raw.get())?;
|
||||
self.state.tool_order.apply(&mut tools);
|
||||
let raw: Arc<serde_json::value::RawValue> =
|
||||
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(
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String> {
|
||||
|
||||
@@ -4800,6 +4800,11 @@ impl Session {
|
||||
developer_sections
|
||||
.push(DeveloperInstructions::new(developer_instructions).render_fragment());
|
||||
}
|
||||
// Extension blocks (`<code_map>`, 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::<RenderedFragment>::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),
|
||||
) {
|
||||
|
||||
172
akode-rs/core/src/tool_order.rs
Normal file
172
akode-rs/core/src/tool_order.rs
Normal file
@@ -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<Vec<String>>,
|
||||
}
|
||||
|
||||
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<Value>) {
|
||||
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<String, usize> = seen
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, key)| (key.clone(), index))
|
||||
.collect();
|
||||
let (mut known, new): (Vec<Value>, Vec<Value>) = 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<String> {
|
||||
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"]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user