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:
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