diff --git a/akode-rs/akode-mcp/src/connection_manager.rs b/akode-rs/akode-mcp/src/connection_manager.rs index b54a44ac..f86a32a2 100644 --- a/akode-rs/akode-mcp/src/connection_manager.rs +++ b/akode-rs/akode-mcp/src/connection_manager.rs @@ -1088,11 +1088,51 @@ impl McpConnectionSet { tool: &str, environment_id: Option<&str>, arguments: Option, - mut meta: Option, + meta: Option, requested_timeout: Option, wait_for_server: bool, ) -> Result { self.validate_tool_call(server, tool, environment_id)?; + self.call_validated_tool(server, tool, arguments, meta, requested_timeout, wait_for_server) + .await + } + + /// Calls a tool on behalf of the host (an extension), never on behalf of the model. + /// + /// Host calls may target tools the server does not list and tools outside the server's + /// `enabled_tools`/`disabled_tools` filter: that filter shapes what the model can see and + /// call, while host calls are fixed in code (for example the `memoria` session delivery). + /// The server must still exist; no entitlement metadata is attached. + pub async fn call_host_tool( + &self, + server: &str, + tool: &str, + arguments: Option, + requested_timeout: Option, + ) -> Result { + if !self.servers.contains_key(server) { + bail!("unknown MCP server '{server}'"); + } + self.call_validated_tool( + server, + tool, + arguments, + /*meta*/ None, + requested_timeout, + /*wait_for_server*/ true, + ) + .await + } + + async fn call_validated_tool( + &self, + server: &str, + tool: &str, + arguments: Option, + mut meta: Option, + requested_timeout: Option, + wait_for_server: bool, + ) -> Result { let view = &self.servers[server]; let client = if wait_for_server { view.connection diff --git a/akode-rs/akode-mcp/src/connection_manager_tests.rs b/akode-rs/akode-mcp/src/connection_manager_tests.rs index 7839de47..b3eebf7e 100644 --- a/akode-rs/akode-mcp/src/connection_manager_tests.rs +++ b/akode-rs/akode-mcp/src/connection_manager_tests.rs @@ -5122,3 +5122,54 @@ async fn view_only_changes_reuse_connection_and_preserve_the_old_step() { ); assert_eq!(new_call.tool_approval_mode(), AppToolApproval::Approve); } + +#[tokio::test] +async fn host_tool_calls_bypass_the_model_tool_filter_but_not_unknown_servers() { + let approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + let permission_profile = Constrained::allow_any(PermissionProfile::default()); + let mut manager = McpConnectionSet::new_uninitialized( + &approval_policy, + &permission_profile, + /*prefix_mcp_tool_names*/ true, + ); + manager.insert_test_client( + "memoria".to_string(), + create_ready_async_managed_client(vec![create_test_tool("memoria", "memory_recall")]) + .await, + ); + manager + .servers + .get_mut("memoria") + .expect("test server exists") + .tool_filter = ToolFilter { + enabled: Some(HashSet::from(["memory_recall".to_string()])), + disabled: HashSet::new(), + }; + + // The model path refuses tools outside the server's filter. + let error = manager + .validate_tool_call("memoria", "memory_ingest_session", /*environment_id*/ None) + .expect_err("filtered tool must be rejected for the model"); + assert!(error.to_string().contains("disabled"), "{error}"); + + // The host path is not stopped by the filter (the fake transport then fails or stalls). + let host_call = tokio::time::timeout( + Duration::from_millis(500), + manager.call_host_tool( + "memoria", + "memory_ingest_session", + Some(serde_json::json!({})), + Some(Duration::from_millis(200)), + ), + ) + .await; + if let Ok(Err(error)) = host_call { + assert!(!error.to_string().contains("disabled"), "{error}"); + } + + let error = manager + .call_host_tool("other", "memory_ingest_session", None, None) + .await + .expect_err("unknown server"); + assert!(error.to_string().contains("unknown MCP server"), "{error}"); +} diff --git a/akode-rs/akode-mcp/src/resource_client.rs b/akode-rs/akode-mcp/src/resource_client.rs index da86bed4..c85b8c11 100644 --- a/akode-rs/akode-mcp/src/resource_client.rs +++ b/akode-rs/akode-mcp/src/resource_client.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use std::sync::Weak; use std::time::Duration; +use akode_protocol::mcp::CallToolResult; use akode_protocol::mcp::Resource; use akode_protocol::mcp::ResourceContent; use anyhow::Context; @@ -153,6 +154,32 @@ impl McpResourceClient { }) } + /// Calls a tool of the named server for the host (an extension), not for the model. + /// + /// The tool may be unlisted and outside the server's tool filter (see + /// `McpConnectionSet::call_host_tool`). `timeout` bounds the call, including server startup. + pub async fn call_tool( + &self, + server: &str, + tool: &str, + arguments: serde_json::Value, + timeout: Duration, + ) -> Result { + let connections = self.runtime.latest_connections(); + match tokio::time::timeout( + timeout, + connections.call_host_tool(server, tool, Some(arguments), Some(timeout)), + ) + .await + { + Ok(result) => result, + Err(_) => Err(anyhow::anyhow!( + "tool call `{server}/{tool}` timed out after {} ms", + timeout.as_millis() + )), + } + } + /// Reads one resource from the named server. pub async fn read_resource(&self, server: &str, uri: &str) -> Result { let params = ReadResourceRequestParams::new(uri.to_string()); diff --git a/akode-rs/core/src/session/handlers.rs b/akode-rs/core/src/session/handlers.rs index 281be540..ef5cebc7 100644 --- a/akode-rs/core/src/session/handlers.rs +++ b/akode-rs/core/src/session/handlers.rs @@ -353,6 +353,8 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc) { ); warn!("failed to shutdown code mode session: {err}"); } + // Extensions may still need MCP (for example to deliver the session): before shutdown. + emit_thread_closing_lifecycle(sess).await; sess.stop_mcp_prewarm_worker().await; { let _refresh = sess.mcp_refresh.acquire().await; @@ -366,6 +368,17 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc) { emit_thread_stop_lifecycle(sess).await; } +async fn emit_thread_closing_lifecycle(sess: &Session) { + for contributor in sess.services.extensions.thread_lifecycle_contributors() { + contributor + .on_thread_closing(akode_extension_api::ThreadStopInput { + session_store: &sess.services.session_extension_data, + thread_store: &sess.services.thread_extension_data, + }) + .await; + } +} + async fn emit_thread_stop_lifecycle(sess: &Session) { for contributor in sess.services.extensions.thread_lifecycle_contributors() { contributor diff --git a/akode-rs/ext/extension-api/src/contributors.rs b/akode-rs/ext/extension-api/src/contributors.rs index 17986811..cb0f17c3 100644 --- a/akode-rs/ext/extension-api/src/contributors.rs +++ b/akode-rs/ext/extension-api/src/contributors.rs @@ -195,6 +195,16 @@ pub trait ThreadLifecycleContributor: Send + Sync { }) } + /// Called at the start of runtime teardown, after running turns were aborted and while the + /// MCP servers are still connected (they are shut down before [`Self::on_thread_stop`]). + /// The host waits for the callback, so implementations must bound their work. + fn on_thread_closing<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> { + Box::pin(async move { + let _self = self; + let _input = input; + }) + } + /// Called during runtime teardown, before the host closes persistent history. /// Contributors must cancel and join their background work before returning. fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> { diff --git a/akode-rs/ext/memoria/Cargo.toml b/akode-rs/ext/memoria/Cargo.toml index 20508c64..9a0b80de 100644 --- a/akode-rs/ext/memoria/Cargo.toml +++ b/akode-rs/ext/memoria/Cargo.toml @@ -20,13 +20,16 @@ akode-extension-api = { workspace = true } akode-features = { workspace = true } akode-mcp = { workspace = true } akode-plugin = { workspace = true } +akode-extension-items = { workspace = true } akode-protocol = { workspace = true } -tokio = { workspace = true, features = ["fs", "process", "sync", "time"] } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["fs", "process", "rt", "sync", "time"] } tracing = { workspace = true } urlencoding = { workspace = true } +uuid = { workspace = true, features = ["v4"] } [dev-dependencies] pretty_assertions = { workspace = true } -serde_json = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["fs", "macros", "rt"] } diff --git a/akode-rs/ext/memoria/src/delivery.rs b/akode-rs/ext/memoria/src/delivery.rs new file mode 100644 index 00000000..94fa677f --- /dev/null +++ b/akode-rs/ext/memoria/src/delivery.rs @@ -0,0 +1,556 @@ +//! Delivery of finished sessions to the memoria server. +//! +//! While the `memoria` plugin is active, the extension keeps a compact transcript of the thread +//! (user messages, final assistant answers, short tool/web/MCP results) and hands it to the +//! server tool `memory_ingest_session`. The tool is not listed in `tools/list` and the model never +//! sees it: aKode calls it directly, through the host path of the MCP client. +//! +//! Delivery happens when the thread has been idle for `[memoria] deliver_idle_minutes` (reason +//! `idle`, the timer is cancelled by a new turn) and when the thread closes (reason `end`, bounded +//! by a short timeout so closing never blocks). Only transcripts with turns that were not +//! delivered yet are sent; the transcript is cumulative, so the server can replace the previous +//! copy of the same `session_id`. Calls to the memoria server itself are never recorded. + +use std::collections::BTreeSet; +use std::collections::VecDeque; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use akode_protocol::items::AgentMessageContent; +use akode_protocol::items::TurnItem; +use akode_protocol::models::MessagePhase; +use akode_protocol::user_input::UserInput; +use serde::Serialize; +use serde_json::Value; + +use crate::SERVER_NAME; +use crate::ServerReadiness; + +/// Server tool that receives the transcript (not listed in `tools/list`). +pub const INGEST_TOOL: &str = "memory_ingest_session"; +/// Maximum characters of one tool, web or MCP result kept in the transcript. +pub(crate) const MAX_TOOL_OUTPUT_CHARS: usize = 1500; +/// Maximum characters of the whole transcript (most recent turns plus the first user message). +pub(crate) const MAX_TRANSCRIPT_CHARS: usize = 150_000; +/// Maximum characters of the session title (first user message on one line). +const TITLE_MAX_CHARS: usize = 36; +/// Maximum characters of an abbreviated command used as a tool name. +const COMMAND_NAME_MAX_CHARS: usize = 120; +/// Bound for the delivery when the thread closes: after this the extension gives up. +pub(crate) const END_TIMEOUT: Duration = Duration::from_secs(5); +/// Bound for the idle delivery (runs in the background). +const IDLE_TIMEOUT: Duration = Duration::from_secs(60); + +/// Why the transcript is delivered. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DeliveryReason { + Idle, + End, +} + +impl DeliveryReason { + fn as_str(self) -> &'static str { + match self { + Self::Idle => "idle", + Self::End => "end", + } + } +} + +/// One entry of the transcript sent to the server. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub(crate) struct TranscriptTurn { + pub(crate) role: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) name: Option, + pub(crate) text: String, +} + +impl TranscriptTurn { + fn new(role: &'static str, name: Option, text: String) -> Self { + Self { role, name, text } + } + + fn chars(&self) -> usize { + self.text.chars().count() + self.name.as_deref().map_or(0, |name| name.chars().count()) + } +} + +/// Cumulative, bounded transcript of one thread. +#[derive(Debug, Default)] +pub(crate) struct Transcript { + /// The first user message is always kept, even when older turns are dropped. + first_user: Option, + turns: VecDeque, + chars: usize, + external_context: BTreeSet<&'static str>, + /// Incremented for every recorded turn. + revision: u64, + /// Revision acknowledged by the server. + delivered_revision: u64, +} + +impl Transcript { + /// Records a completed item; returns whether it added a turn. + pub(crate) fn record(&mut self, item: &TurnItem) -> bool { + let Some((turn, external)) = turn_from_item(item) else { + return false; + }; + if let Some(external) = external { + self.external_context.insert(external); + } + if turn.role == "user" && self.first_user.is_none() { + self.chars += turn.chars(); + self.first_user = Some(turn); + } else { + self.chars += turn.chars(); + self.turns.push_back(turn); + } + self.revision += 1; + self.compact(); + true + } + + /// Drops the oldest turns (never the first user message) until the transcript fits. + fn compact(&mut self) { + while self.chars > MAX_TRANSCRIPT_CHARS { + let Some(oldest) = self.turns.pop_front() else { + break; + }; + self.chars -= oldest.chars(); + } + } + + pub(crate) fn has_undelivered_turns(&self) -> bool { + self.revision > self.delivered_revision + } + + pub(crate) fn revision(&self) -> u64 { + self.revision + } + + pub(crate) fn mark_delivered(&mut self, revision: u64) { + self.delivered_revision = self.delivered_revision.max(revision); + } + + pub(crate) fn turns(&self) -> Vec<&TranscriptTurn> { + self.first_user.iter().chain(self.turns.iter()).collect() + } + + #[cfg(test)] + pub(crate) fn total_chars(&self) -> usize { + self.chars + } + + /// Arguments of `memory_ingest_session`. + pub(crate) fn payload(&self, session_id: &str, reason: DeliveryReason) -> Value { + let mut payload = serde_json::json!({ + "session_id": session_id, + "reason": reason.as_str(), + "turns": self.turns(), + "client_version": env!("CARGO_PKG_VERSION"), + }); + if let Some(title) = self + .first_user + .as_ref() + .and_then(|turn| one_line_title(&turn.text)) + { + payload["title"] = Value::String(title); + } + if !self.external_context.is_empty() { + payload["external_context"] = serde_json::json!(self.external_context); + } + payload + } +} + +/// Converts a completed item into a transcript turn and, for external sources, its context tag. +pub(crate) fn turn_from_item(item: &TurnItem) -> Option<(TranscriptTurn, Option<&'static str>)> { + match item { + TurnItem::UserMessage(message) => { + let text = message + .content + .iter() + .filter_map(|input| match input { + UserInput::Text { text, .. } => Some(text.clone()), + UserInput::Image { .. } | UserInput::LocalImage { .. } => { + Some("[immagine]".to_string()) + } + _ => None, + }) + .collect::>() + .join("\n"); + non_empty(text).map(|text| (TranscriptTurn::new("user", None, text), None)) + } + TurnItem::AgentMessage(message) => { + // Only answers: mid-turn commentary is not part of the final text. + if matches!(message.phase, Some(MessagePhase::Commentary)) { + return None; + } + let text = message + .content + .iter() + .map(|content| match content { + AgentMessageContent::Text { text } => text.as_str(), + }) + .collect::(); + non_empty(text).map(|text| (TranscriptTurn::new("assistant", None, text), None)) + } + TurnItem::CommandExecution(command) => { + let name = abbreviate_command(&command.command); + let mut text = match command.exit_code { + Some(code) => format!("exit {code}"), + None => String::new(), + }; + if let Some(output) = command + .aggregated_output + .as_deref() + .filter(|output| !output.trim().is_empty()) + { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(&truncate_output(output)); + } + Some((TranscriptTurn::new("tool", Some(name), text), None)) + } + TurnItem::FileChange(change) => { + let mut files = change + .changes + .keys() + .map(|path| path.display().to_string()) + .collect::>(); + if files.is_empty() { + return None; + } + files.sort(); + Some(( + TranscriptTurn::new( + "tool", + Some("apply_patch".to_string()), + truncate_output(&files.join("\n")), + ), + None, + )) + } + TurnItem::WebSearch(search) => { + let results = search + .results + .as_ref() + .map(|results| serde_json::to_string(results).unwrap_or_default()); + web_turn(&search.query, &format!("{:?}", search.action), results) + } + TurnItem::Extension(akode_extension_items::ExtensionItem::WebSearch(search)) => { + let action = search + .action + .as_ref() + .map(|action| match action { + akode_extension_items::web_search::WebSearchAction::Search { + query, + queries, + } => query + .clone() + .or_else(|| queries.as_ref().map(|queries| queries.join(" | "))) + .unwrap_or_default(), + akode_extension_items::web_search::WebSearchAction::OpenPage { url } => { + format!("apre {}", url.as_deref().unwrap_or_default()) + } + akode_extension_items::web_search::WebSearchAction::FindInPage { + url, + pattern, + } => format!( + "cerca {} in {}", + pattern.as_deref().unwrap_or_default(), + url.as_deref().unwrap_or_default() + ), + akode_extension_items::web_search::WebSearchAction::Other => String::new(), + }) + .unwrap_or_default(); + let results = search + .results + .as_ref() + .map(|results| serde_json::to_string(results).unwrap_or_default()); + web_turn(&search.query, &action, results) + } + TurnItem::McpToolCall(call) => { + // The memoria server's own tools never feed the memory back into itself. + if call.server == SERVER_NAME { + return None; + } + let output = match (&call.result, &call.error) { + (_, Some(error)) => format!("errore: {}", error.message), + (Some(result), None) => result + .content + .iter() + .filter_map(|content| content.get("text").and_then(Value::as_str)) + .collect::>() + .join("\n"), + (None, None) => String::new(), + }; + Some(( + TranscriptTurn::new( + "mcp", + Some(format!("{}/{}", call.server, call.tool)), + truncate_output(&output), + ), + Some("other_mcp"), + )) + } + _ => None, + } +} + +fn web_turn( + query: &str, + action: &str, + results: Option, +) -> Option<(TranscriptTurn, Option<&'static str>)> { + let mut text = query.trim().to_string(); + let action = action.trim(); + if !action.is_empty() && action != text { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(action); + } + if let Some(results) = results.filter(|results| !results.is_empty() && results != "[]") { + text.push('\n'); + text.push_str(&results); + } + let text = non_empty(text)?; + Some(( + TranscriptTurn::new("web", Some("web_search".to_string()), truncate_output(&text)), + Some("web"), + )) +} + +fn non_empty(text: String) -> Option { + (!text.trim().is_empty()).then_some(text) +} + +/// `bash -lc "cmd"` becomes `cmd`; the result is on one line and bounded. +pub(crate) fn abbreviate_command(command: &[String]) -> String { + let script = match command { + [shell, flag, script] if matches!(flag.as_str(), "-c" | "-lc") && !shell.is_empty() => { + script.clone() + } + _ => command.join(" "), + }; + let line = script.split_whitespace().collect::>().join(" "); + truncate_chars(&line, COMMAND_NAME_MAX_CHARS) +} + +/// Keeps the beginning and the end of a long output. +pub(crate) fn truncate_output(output: &str) -> String { + let count = output.chars().count(); + if count <= MAX_TOOL_OUTPUT_CHARS { + return output.to_string(); + } + let head = MAX_TOOL_OUTPUT_CHARS * 2 / 3; + let tail = MAX_TOOL_OUTPUT_CHARS - head; + let start: String = output.chars().take(head).collect(); + let end: String = output.chars().skip(count - tail).collect(); + format!("{start}\n…[{} caratteri omessi]…\n{end}", count - head - tail) +} + +fn truncate_chars(text: &str, max: usize) -> String { + if text.chars().count() <= max { + return text.to_string(); + } + let mut truncated: String = text.chars().take(max.saturating_sub(1)).collect(); + truncated.push('…'); + truncated +} + +/// First user message on one line, truncated. +fn one_line_title(text: &str) -> Option { + let line = text.split_whitespace().collect::>().join(" "); + (!line.is_empty()).then(|| truncate_chars(&line, TITLE_MAX_CHARS)) +} + +/// Delivery settings resolved at thread start. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct DeliverySettings { + pub(crate) enabled: bool, + pub(crate) idle: Duration, +} + +/// Thread-scoped delivery state, shared with the idle timer. +pub(crate) struct DeliveryState { + pub(crate) settings: DeliverySettings, + pub(crate) session_id: String, + /// The plugin is enabled and installed (updated on config changes). + pub(crate) plugin_active: AtomicBool, + pub(crate) servers: Option>, + pub(crate) transcript: Mutex, + timer: Mutex>>, + /// Serializes deliveries of the same thread. + deliver_lock: tokio::sync::Mutex<()>, +} + +impl DeliveryState { + pub(crate) fn new( + settings: DeliverySettings, + session_id: String, + plugin_active: bool, + servers: Option>, + ) -> Self { + Self { + settings, + session_id, + plugin_active: AtomicBool::new(plugin_active), + servers, + transcript: Mutex::new(Transcript::default()), + timer: Mutex::new(None), + deliver_lock: tokio::sync::Mutex::new(()), + } + } + + /// Delivery is configured, the plugin is active and an MCP client is available. + pub(crate) fn active(&self) -> bool { + self.settings.enabled && self.plugin_active.load(Ordering::Relaxed) && self.servers.is_some() + } + + pub(crate) fn record(&self, item: &TurnItem) { + if !self.active() { + return; + } + self.transcript + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .record(item); + } + + pub(crate) fn has_undelivered_turns(&self) -> bool { + self.transcript + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .has_undelivered_turns() + } + + /// Cancels the pending idle delivery, if any. + pub(crate) fn cancel_timer(&self) { + if let Some(timer) = self + .timer + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + { + timer.abort(); + } + } + + /// Starts (or restarts) the idle timer; it delivers with reason `idle` when it fires. + pub(crate) fn schedule_idle(self: &Arc) { + self.cancel_timer(); + if !self.active() || !self.has_undelivered_turns() { + return; + } + let state = Arc::clone(self); + let idle = self.settings.idle; + let handle = tokio::spawn(async move { + tokio::time::sleep(idle).await; + state.deliver(DeliveryReason::Idle, IDLE_TIMEOUT).await; + }); + *self + .timer + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(handle); + } + + /// Sends the transcript if it has new turns; gives up after `timeout`. Returns whether the + /// server accepted it. + pub(crate) async fn deliver(&self, reason: DeliveryReason, timeout: Duration) -> bool { + if !self.active() { + return false; + } + match tokio::time::timeout(timeout, self.deliver_inner(reason, timeout)).await { + Ok(delivered) => delivered, + Err(_) => { + tracing::debug!( + session_id = %self.session_id, + reason = reason.as_str(), + timeout_ms = timeout.as_millis() as u64, + "memoria session delivery timed out; giving up" + ); + false + } + } + } + + async fn deliver_inner(&self, reason: DeliveryReason, timeout: Duration) -> bool { + let Some(servers) = self.servers.as_ref() else { + return false; + }; + let _guard = self.deliver_lock.lock().await; + let (payload, revision) = { + let transcript = self + .transcript + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if !transcript.has_undelivered_turns() { + return false; + } + ( + transcript.payload(&self.session_id, reason), + transcript.revision(), + ) + }; + if !servers.is_ready(SERVER_NAME).await { + tracing::debug!("memoria MCP server is not ready; session not delivered"); + return false; + } + match servers + .call_tool(SERVER_NAME, INGEST_TOOL, payload, timeout) + .await + { + Ok(response) => match parse_response(&response) { + Ok(status) => { + tracing::info!( + session_id = %self.session_id, + reason = reason.as_str(), + %status, + "memoria session delivered" + ); + self.transcript + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .mark_delivered(revision); + true + } + Err(error) => { + tracing::debug!(%error, "memoria session delivery rejected"); + false + } + }, + Err(error) => { + tracing::debug!(%error, "memoria session delivery failed"); + false + } + } + } +} + +/// Reply of `memory_ingest_session` as seen by the extension. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IngestResponse { + pub is_error: bool, + pub text: String, +} + +/// Accepts `queued`, `duplicate` and `skipped`; anything else (or `isError`) is an error. +pub(crate) fn parse_response(response: &IngestResponse) -> Result { + if response.is_error { + return Err(response.text.clone()); + } + let value: Value = serde_json::from_str(response.text.trim()) + .map_err(|error| format!("invalid response ({error}): {}", response.text))?; + match value.get("status").and_then(Value::as_str) { + Some(status @ ("queued" | "duplicate" | "skipped")) => Ok(status.to_string()), + Some(status) => Err(format!("unexpected status `{status}`")), + None => Err(format!("response without status: {}", response.text)), + } +} diff --git a/akode-rs/ext/memoria/src/lib.rs b/akode-rs/ext/memoria/src/lib.rs index f4b1322e..8d07c3ad 100644 --- a/akode-rs/ext/memoria/src/lib.rs +++ b/akode-rs/ext/memoria/src/lib.rs @@ -11,6 +11,9 @@ //! in the thread store, so every later prompt assembly (for example after compaction) reuses the //! same bytes and the model's prompt cache stays valid. Only a block that starts with the //! ` = Pin + Send + 'a>>; type ReadFuture<'a> = Pin> + Send + 'a>>; +type CallFuture<'a> = Pin> + Send + 'a>>; -/// Answers whether an MCP server is ready for the thread, and reads its text resources. +/// Answers whether an MCP server is ready for the thread, reads its text resources and calls +/// host-only tools. trait ServerReadiness: Send + Sync { fn is_ready<'a>(&'a self, server: &'a str) -> ReadyFuture<'a>; fn read_text<'a>(&'a self, server: &'a str, uri: String) -> ReadFuture<'a>; + /// Calls a tool for the host (it may be unlisted); returns the text of the result. + fn call_tool<'a>( + &'a self, + _server: &'a str, + _tool: &'a str, + _arguments: serde_json::Value, + _timeout: Duration, + ) -> CallFuture<'a> { + Box::pin(async { Err("tool calls are not supported".to_string()) }) + } } impl ServerReadiness for McpResourceClient { @@ -92,6 +121,30 @@ impl ServerReadiness for McpResourceClient { .join("\n")) }) } + + fn call_tool<'a>( + &'a self, + server: &'a str, + tool: &'a str, + arguments: serde_json::Value, + timeout: Duration, + ) -> CallFuture<'a> { + Box::pin(async move { + let result = McpResourceClient::call_tool(self, server, tool, arguments, timeout) + .await + .map_err(|error| error.to_string())?; + let text = result + .content + .iter() + .filter_map(|content| content.get("text").and_then(serde_json::Value::as_str)) + .collect::>() + .join("\n"); + Ok(IngestResponse { + is_error: result.is_error.unwrap_or(false), + text, + }) + }) + } } /// Thread state: where the enabled plugin keeps its instructions, how to reach the server, and @@ -310,17 +363,50 @@ impl ContextContributor for MemoriaExtension { } } +/// Only sessions started by the user are delivered (not sub-agents or internal threads). +fn delivers_session_source(source: &SessionSource) -> bool { + !matches!( + source, + SessionSource::SubAgent(_) | SessionSource::Internal(_) + ) +} + +fn delivery_settings(config: &MemoriaDeliveryConfig, source: &SessionSource) -> DeliverySettings { + DeliverySettings { + enabled: config.enabled && delivers_session_source(source), + idle: Duration::from_secs(config.idle_minutes.saturating_mul(60)), + } +} + +/// `session_id` sent to the server: the thread id, or a per-runtime id if it is missing. +fn session_id_for(thread_store: &ExtensionData) -> String { + let level_id = thread_store.level_id().trim(); + if level_id.is_empty() { + uuid::Uuid::new_v4().to_string() + } else { + level_id.to_string() + } +} + impl ThreadLifecycleContributor for MemoriaExtension { fn on_thread_start<'a>( &'a self, input: ThreadStartInput<'a, Config>, ) -> ExtensionFuture<'a, ()> { Box::pin(async move { + let instructions_path = instructions_path(input.config); + let servers = input + .mcp_resource_client + .map(|client| client as Arc); + input.thread_store.insert(DeliveryState::new( + delivery_settings(&input.config.memoria_delivery, input.session_source), + session_id_for(input.thread_store), + instructions_path.is_some(), + servers.clone(), + )); input.thread_store.insert(MemoriaThreadState { - instructions_path: instructions_path(input.config), - servers: input - .mcp_resource_client - .map(|client| client as Arc), + instructions_path, + servers, briefing: BriefingSettings::from_config( &input.config.memoria_briefing, Some(input.config.cwd.to_path_buf()), @@ -329,6 +415,57 @@ impl ThreadLifecycleContributor for MemoriaExtension { }); }) } + + fn on_thread_idle<'a>(&'a self, input: ThreadIdleInput<'a>) -> ExtensionFuture<'a, ()> { + Box::pin(async move { + if let Some(state) = input.thread_store.get::() { + state.schedule_idle(); + } + }) + } + + fn on_thread_closing<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> { + Box::pin(async move { + if let Some(state) = input.thread_store.get::() { + state.cancel_timer(); + state + .deliver(DeliveryReason::End, delivery::END_TIMEOUT) + .await; + } + }) + } + + fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> { + Box::pin(async move { + if let Some(state) = input.thread_store.get::() { + state.cancel_timer(); + } + }) + } +} + +impl TurnLifecycleContributor for MemoriaExtension { + fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> { + Box::pin(async move { + // A new turn cancels the pending idle delivery. + if let Some(state) = input.thread_store.get::() { + state.cancel_timer(); + } + }) + } + + fn on_item_completed<'a>( + &'a self, + thread_store: &'a ExtensionData, + _turn_store: &'a ExtensionData, + item: &'a TurnItem, + ) -> ExtensionFuture<'a, ()> { + Box::pin(async move { + if let Some(state) = thread_store.get::() { + state.record(item); + } + }) + } } impl ConfigContributor for MemoriaExtension { @@ -339,10 +476,17 @@ impl ConfigContributor for MemoriaExtension { _previous_config: &Config, new_config: &Config, ) { + let new_instructions_path = instructions_path(new_config); + if let Some(delivery) = thread_store.get::() { + delivery.plugin_active.store( + new_instructions_path.is_some(), + std::sync::atomic::Ordering::Relaxed, + ); + } if let Some(state) = thread_store.get::() { // The briefing already fetched stays: the prompt prefix must not change mid-thread. thread_store.insert(MemoriaThreadState { - instructions_path: instructions_path(new_config), + instructions_path: new_instructions_path, servers: state.servers.clone(), briefing: state.briefing.clone(), briefing_text: state.briefing_text.clone(), @@ -351,10 +495,11 @@ impl ConfigContributor for MemoriaExtension { } } -/// Installs the memoria instructions contributor into the extension registry. +/// Installs the memoria contributors (instructions, briefing, session delivery). pub fn install(registry: &mut ExtensionRegistryBuilder) { let extension = Arc::new(MemoriaExtension); registry.thread_lifecycle_contributor(extension.clone()); + registry.turn_lifecycle_contributor(extension.clone()); registry.config_contributor(extension.clone()); registry.prompt_contributor(extension); } diff --git a/akode-rs/ext/memoria/src/tests.rs b/akode-rs/ext/memoria/src/tests.rs index 97418acb..6c1b3047 100644 --- a/akode-rs/ext/memoria/src/tests.rs +++ b/akode-rs/ext/memoria/src/tests.rs @@ -332,3 +332,381 @@ async fn reads_changed_files_from_git_status() { let plain = tempfile::tempdir().expect("tempdir"); assert!(super::changed_files(plain.path()).await.is_empty()); } + +// --------------------------------------------------------------------------------------------- +// Session delivery (`memory_ingest_session`). +// --------------------------------------------------------------------------------------------- + +mod delivery_tests { + use std::sync::Arc; + use std::sync::Mutex; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use std::time::Duration; + + use akode_protocol::items::TurnItem; + use pretty_assertions::assert_eq; + use serde_json::Value; + use serde_json::json; + + use super::super::CallFuture; + use super::super::ReadFuture; + use super::super::ReadyFuture; + use super::super::ServerReadiness; + use super::super::delivery::DeliveryReason; + use super::super::delivery::DeliverySettings; + use super::super::delivery::DeliveryState; + use super::super::delivery::INGEST_TOOL; + use super::super::delivery::IngestResponse; + use super::super::delivery::MAX_TOOL_OUTPUT_CHARS; + use super::super::delivery::MAX_TRANSCRIPT_CHARS; + use super::super::delivery::Transcript; + use super::super::delivery::abbreviate_command; + use super::super::delivery::parse_response; + use super::super::delivery::turn_from_item; + + fn item(value: Value) -> TurnItem { + serde_json::from_value(value).expect("valid turn item") + } + + fn user(text: &str) -> TurnItem { + item(json!({"type": "UserMessage", "id": "u", "content": [{"type": "text", "text": text}]})) + } + + fn assistant(text: &str, phase: Option<&str>) -> TurnItem { + let mut value = json!({ + "type": "AgentMessage", + "id": "a", + "content": [{"type": "Text", "text": text}], + }); + if let Some(phase) = phase { + value["phase"] = json!(phase); + } + item(value) + } + + fn command(script: &str, output: &str) -> TurnItem { + item(json!({ + "type": "CommandExecution", + "id": "c", + "command": ["bash", "-lc", script], + "cwd": "file:///tmp/progetto", + "parsed_cmd": [], + "source": "agent", + "status": "completed", + "aggregated_output": output, + "exit_code": 0, + })) + } + + fn mcp_call(server: &str, tool: &str, text: &str) -> TurnItem { + item(json!({ + "type": "McpToolCall", + "id": "m", + "server": server, + "tool": tool, + "arguments": {}, + "status": "completed", + "result": {"content": [{"type": "text", "text": text}]}, + })) + } + + fn web_search(query: &str) -> TurnItem { + item(json!({ + "type": "Extension", + "kind": "web.search", + "id": "w", + "query": query, + "action": {"type": "search", "query": query, "queries": null}, + "results": null, + })) + } + + #[test] + fn items_map_to_transcript_roles() { + let (turn, external) = turn_from_item(&user("Correggi il login")).expect("user turn"); + assert_eq!((turn.role, turn.text.as_str(), external), ("user", "Correggi il login", None)); + + let (turn, _) = + turn_from_item(&assistant("Fatto.", Some("final_answer"))).expect("assistant turn"); + assert_eq!((turn.role, turn.text.as_str()), ("assistant", "Fatto.")); + assert!( + turn_from_item(&assistant("Ora lancio i test", Some("commentary"))).is_none(), + "commentary is not the final text" + ); + + let long_output = "x".repeat(MAX_TOOL_OUTPUT_CHARS * 3); + let (turn, external) = + turn_from_item(&command("cargo test\n -p foo", &long_output)).expect("tool turn"); + assert_eq!(turn.role, "tool"); + assert_eq!(turn.name.as_deref(), Some("cargo test -p foo")); + assert!(turn.text.starts_with("exit 0\n")); + assert!(turn.text.chars().count() < MAX_TOOL_OUTPUT_CHARS + 100); + assert!(turn.text.contains("caratteri omessi")); + assert_eq!(external, None); + + let change = item(json!({ + "type": "FileChange", + "id": "f", + "changes": { + "/tmp/progetto/src/b.rs": {"type": "update", "unified_diff": "", "move_path": null}, + "/tmp/progetto/src/a.rs": {"type": "add", "content": "fn a() {}"}, + }, + })); + let (turn, _) = turn_from_item(&change).expect("file change turn"); + assert_eq!(turn.role, "tool"); + assert_eq!(turn.text, "/tmp/progetto/src/a.rs\n/tmp/progetto/src/b.rs"); + + let (turn, external) = turn_from_item(&web_search("rust tokio timeout")).expect("web"); + assert_eq!(turn.role, "web"); + assert!(turn.text.contains("rust tokio timeout")); + assert_eq!(external, Some("web")); + + let (turn, external) = + turn_from_item(&mcp_call("github", "search_issues", "3 issue")).expect("mcp"); + assert_eq!(turn.role, "mcp"); + assert_eq!(turn.name.as_deref(), Some("github/search_issues")); + assert_eq!(turn.text, "3 issue"); + assert_eq!(external, Some("other_mcp")); + } + + #[test] + fn calls_to_the_memoria_server_are_ignored() { + assert!(turn_from_item(&mcp_call("memoria", "memory_recall", "ricordi")).is_none()); + let mut transcript = Transcript::default(); + assert!(!transcript.record(&mcp_call("memoria", "memory_save", "ok"))); + assert!(!transcript.has_undelivered_turns()); + } + + #[test] + fn payload_has_session_reason_title_and_external_context() { + let mut transcript = Transcript::default(); + transcript.record(&user("Correggi il timeout del login quando la sessione scade")); + transcript.record(&web_search("timeout login")); + transcript.record(&mcp_call("github", "get_issue", "issue #3")); + transcript.record(&assistant("Corretto.", None)); + let payload = transcript.payload("thread-1", DeliveryReason::Idle); + assert_eq!(payload["session_id"], "thread-1"); + assert_eq!(payload["reason"], "idle"); + assert_eq!(payload["client_version"], env!("CARGO_PKG_VERSION")); + assert_eq!(payload["title"].as_str().map(|t| t.chars().count()), Some(36)); + assert_eq!(payload["external_context"], json!(["other_mcp", "web"])); + let roles = payload["turns"] + .as_array() + .expect("turns") + .iter() + .map(|turn| turn["role"].as_str().unwrap_or_default().to_string()) + .collect::>(); + assert_eq!(roles, ["user", "web", "mcp", "assistant"]); + assert!(payload["turns"][0].get("name").is_none()); + + let mut quiet = Transcript::default(); + quiet.record(&user("ciao")); + let payload = quiet.payload("thread-2", DeliveryReason::End); + assert_eq!(payload["reason"], "end"); + assert!(payload.get("external_context").is_none()); + } + + #[test] + fn compaction_keeps_first_user_message_and_latest_turns() { + let mut transcript = Transcript::default(); + transcript.record(&user("primo messaggio")); + let chunk = "y".repeat(10_000); + for index in 0..40 { + transcript.record(&assistant(&format!("{index}:{chunk}"), None)); + } + assert!(transcript.total_chars() <= MAX_TRANSCRIPT_CHARS); + let turns = transcript.turns(); + assert_eq!(turns[0].text, "primo messaggio"); + assert!(turns.last().expect("last").text.starts_with("39:")); + assert!(!turns.iter().any(|turn| turn.text.starts_with("0:"))); + } + + #[test] + fn abbreviates_shell_commands() { + let command = vec!["zsh".to_string(), "-lc".to_string(), "ls -la\n".to_string()]; + assert_eq!(abbreviate_command(&command), "ls -la"); + let command = vec!["git".to_string(), "status".to_string()]; + assert_eq!(abbreviate_command(&command), "git status"); + } + + #[test] + fn responses_are_accepted_only_with_known_status() { + let ok = |text: &str| IngestResponse { + is_error: false, + text: text.to_string(), + }; + for status in ["queued", "duplicate", "skipped"] { + assert_eq!( + parse_response(&ok(&format!(r#"{{"status":"{status}","job_id":"j1"}}"#))), + Ok(status.to_string()) + ); + } + assert!(parse_response(&ok(r#"{"status":"boh"}"#)).is_err()); + assert!(parse_response(&ok("non json")).is_err()); + assert!( + parse_response(&IngestResponse { + is_error: true, + text: r#"{"status":"queued"}"#.to_string(), + }) + .is_err() + ); + } + + /// Fake memoria server recording `memory_ingest_session` calls. + struct IngestServer { + ready: bool, + reply: IngestResponse, + calls: AtomicUsize, + last: Mutex>, + } + + impl IngestServer { + fn new(ready: bool, reply: IngestResponse) -> Arc { + Arc::new(Self { + ready, + reply, + calls: AtomicUsize::new(0), + last: Mutex::new(None), + }) + } + + fn queued() -> Arc { + Self::new( + /*ready*/ true, + IngestResponse { + is_error: false, + text: r#"{"status":"queued","job_id":"j1","message":"ok"}"#.to_string(), + }, + ) + } + } + + impl ServerReadiness for IngestServer { + fn is_ready<'a>(&'a self, server: &'a str) -> ReadyFuture<'a> { + let ready = self.ready && server == "memoria"; + Box::pin(async move { ready }) + } + + fn read_text<'a>(&'a self, _server: &'a str, _uri: String) -> ReadFuture<'a> { + Box::pin(async { Err("no resources".to_string()) }) + } + + fn call_tool<'a>( + &'a self, + server: &'a str, + tool: &'a str, + arguments: Value, + _timeout: Duration, + ) -> CallFuture<'a> { + Box::pin(async move { + self.calls.fetch_add(1, Ordering::SeqCst); + *self.last.lock().expect("lock") = + Some((server.to_string(), tool.to_string(), arguments)); + Ok(self.reply.clone()) + }) + } + } + + fn state(server: Arc, enabled: bool, plugin_active: bool) -> Arc { + Arc::new(DeliveryState::new( + DeliverySettings { + enabled, + idle: Duration::from_millis(30), + }, + "thread-42".to_string(), + plugin_active, + Some(server as Arc), + )) + } + + #[tokio::test] + async fn delivers_only_when_there_are_new_turns() { + let server = IngestServer::queued(); + let state = state(Arc::clone(&server), /*enabled*/ true, /*plugin_active*/ true); + + assert!(!state.deliver(DeliveryReason::End, Duration::from_secs(1)).await); + assert_eq!(server.calls.load(Ordering::SeqCst), 0, "empty transcript"); + + state.record(&user("ciao")); + state.record(&assistant("Ciao!", None)); + assert!(state.deliver(DeliveryReason::Idle, Duration::from_secs(1)).await); + assert_eq!(server.calls.load(Ordering::SeqCst), 1); + let (server_name, tool, arguments) = + server.last.lock().expect("lock").clone().expect("call"); + assert_eq!((server_name.as_str(), tool.as_str()), ("memoria", INGEST_TOOL)); + assert_eq!(arguments["session_id"], "thread-42"); + assert_eq!(arguments["reason"], "idle"); + assert_eq!(arguments["turns"].as_array().map(Vec::len), Some(2)); + + assert!(!state.deliver(DeliveryReason::End, Duration::from_secs(1)).await); + assert_eq!(server.calls.load(Ordering::SeqCst), 1, "nothing new since last delivery"); + + state.record(&user("altro")); + assert!(state.deliver(DeliveryReason::End, Duration::from_secs(1)).await); + assert_eq!(server.calls.load(Ordering::SeqCst), 2); + let (_, _, arguments) = server.last.lock().expect("lock").clone().expect("call"); + assert_eq!(arguments["reason"], "end"); + assert_eq!( + arguments["turns"].as_array().map(Vec::len), + Some(3), + "the transcript is cumulative" + ); + } + + #[tokio::test] + async fn errors_keep_turns_for_a_later_delivery() { + let server = IngestServer::new( + /*ready*/ true, + IngestResponse { + is_error: true, + text: "server down".to_string(), + }, + ); + let state = state(Arc::clone(&server), /*enabled*/ true, /*plugin_active*/ true); + state.record(&user("ciao")); + assert!(!state.deliver(DeliveryReason::End, Duration::from_secs(1)).await); + assert!(state.has_undelivered_turns()); + } + + #[tokio::test] + async fn nothing_is_sent_when_disabled_inactive_or_not_ready() { + for (enabled, plugin_active, ready) in + [(false, true, true), (true, false, true), (true, true, false)] + { + let server = IngestServer::new( + ready, + IngestResponse { + is_error: false, + text: r#"{"status":"queued"}"#.to_string(), + }, + ); + let state = state(Arc::clone(&server), enabled, plugin_active); + state.record(&user("ciao")); + assert!(!state.deliver(DeliveryReason::End, Duration::from_secs(1)).await); + assert_eq!(server.calls.load(Ordering::SeqCst), 0); + } + } + + #[tokio::test] + async fn idle_timer_delivers_and_a_new_turn_cancels_it() { + let server = IngestServer::queued(); + let state = state(Arc::clone(&server), /*enabled*/ true, /*plugin_active*/ true); + + state.schedule_idle(); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(server.calls.load(Ordering::SeqCst), 0, "no turns, no timer"); + + state.record(&user("ciao")); + state.schedule_idle(); + state.cancel_timer(); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(server.calls.load(Ordering::SeqCst), 0, "cancelled by a new turn"); + + state.schedule_idle(); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(server.calls.load(Ordering::SeqCst), 1); + let (_, _, arguments) = server.last.lock().expect("lock").clone().expect("call"); + assert_eq!(arguments["reason"], "idle"); + } +}