aKode: integrazione della memoria di imeAI (plugin memoria)

- nuovo crate ext/memoria: aggiunge le istruzioni del plugin (instructions.md)
  come developer policy solo se il plugin memoria è abilitato e il suo server
  MCP è pronto; nessuna modifica alle istruzioni di base, [features] memories
  resta spento
- pollutes_memory configurabile per server MCP (predefinito true)
- project_header per i server HTTP: progetto ricavato dalla cartella della
  sessione (origin come host/owner/repo, altrimenti la cartella), connessioni
  separate per progetto
- token Bearer dei server MCP anche dal portachiavi di aKode, solo sotto
  mcp:<server> (mai le chiavi dei provider dei modelli)
- tool namespace (MCP, multi-agente) appiattiti in <namespace>__<tool> per i
  server compatibili OpenAI che accettano solo function tool (llama.cpp,
  ik_llama.cpp, vLLM li scartavano); capacità del provider tool_namespaces
- prove: parsing e propagazione, intestazione del progetto, iniezione solo se
  attivo e connesso, appiattimento e mappatura delle chiamate, chiavi dei
  provider mai consegnate ai server MCP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-14 17:55:21 +01:00
parent 2743e4c383
commit a005236bcb
55 changed files with 1183 additions and 14 deletions

View File

@@ -113,6 +113,8 @@ impl<C: Sync> McpServerContributor<C> for McpBoards {
vec![McpServerContribution::Set {
name: "codex_message_board".into(),
config: Box::new(McpServerConfig {
pollutes_memory: true,
project_header: None,
transport: McpServerTransportConfig::StreamableHttp {
url: server.url().into(),
bearer_token_env_var: None,

View File

@@ -184,6 +184,8 @@ async fn reads_declared_config_only_through_executor_file_system() {
(
"demo".to_string(),
McpServerConfig {
pollutes_memory: true,
project_header: None,
auth: Default::default(),
transport: McpServerTransportConfig::Stdio {
command: "demo-mcp".to_string(),
@@ -214,6 +216,8 @@ async fn reads_declared_config_only_through_executor_file_system() {
(
"hosted".to_string(),
McpServerConfig {
pollutes_memory: true,
project_header: None,
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://example.com/mcp".to_string(),
@@ -274,6 +278,8 @@ async fn reads_manifest_object_config_without_executor_file_system_access() {
vec![(
"counter".to_string(),
McpServerConfig {
pollutes_memory: true,
project_header: None,
auth: Default::default(),
transport: McpServerTransportConfig::Stdio {
command: "counter-mcp".to_string(),

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "memoria",
crate_name = "akode_memoria_extension",
)

View File

@@ -0,0 +1,31 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-memoria-extension"
version.workspace = true
[lib]
name = "akode_memoria_extension"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
akode-config = { workspace = true }
akode-core = { workspace = true }
akode-core-plugins = { workspace = true }
akode-extension-api = { workspace = true }
akode-features = { workspace = true }
akode-mcp = { workspace = true }
akode-plugin = { workspace = true }
tokio = { workspace = true, features = ["fs"] }
tracing = { workspace = true }
[dev-dependencies]
akode-protocol = { workspace = true }
pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["fs", "macros", "rt"] }

View File

@@ -0,0 +1,175 @@
//! Injects the instructions of the `memoria` plugin (long-term memory served over MCP).
//!
//! Plugin manifests have no instructions field, so this extension reads `instructions.md` from
//! the installed plugin and adds it as developer policy, but only while the plugin is enabled and
//! its `memoria` MCP server is ready for the thread.
use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use akode_config::types::PluginConfig;
use akode_config::types::PluginsConfigToml;
use akode_core::config::Config;
use akode_core_plugins::configured_plugins_from_stack;
use akode_core_plugins::store::PluginStore;
use akode_extension_api::ConfigContributor;
use akode_extension_api::ContentItemKind;
use akode_extension_api::ContextContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::PromptFragment;
use akode_extension_api::ThreadLifecycleContributor;
use akode_extension_api::ThreadStartInput;
use akode_features::Feature;
use akode_mcp::McpResourceClient;
use akode_plugin::PluginId;
/// Plugin name, regardless of the marketplace it was installed from.
pub const PLUGIN_NAME: &str = "memoria";
/// MCP server that must be ready before the instructions are injected.
pub const SERVER_NAME: &str = "memoria";
/// Instructions file at the root of the installed plugin.
pub const INSTRUCTIONS_FILE: &str = "instructions.md";
/// Content kind of the injected developer policy.
pub const CONTENT_KIND: &str = "memoria.instructions";
/// Bounds the wait for server startup; the first turn waits for MCP startup anyway.
const SERVER_READY_TIMEOUT: Duration = Duration::from_secs(10);
type ReadyFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
/// Answers whether an MCP server is ready for the thread.
trait ServerReadiness: Send + Sync {
fn is_ready<'a>(&'a self, server: &'a str) -> ReadyFuture<'a>;
}
impl ServerReadiness for McpResourceClient {
fn is_ready<'a>(&'a self, server: &'a str) -> ReadyFuture<'a> {
Box::pin(self.wait_for_server_ready(server, SERVER_READY_TIMEOUT))
}
}
/// Thread state: where the enabled plugin keeps its instructions, and how to reach the server.
#[derive(Clone)]
struct MemoriaThreadState {
instructions_path: Option<PathBuf>,
servers: Option<Arc<dyn ServerReadiness>>,
}
#[derive(Clone, Copy, Default)]
struct MemoriaExtension;
/// Returns `instructions.md` of the enabled, installed `memoria` plugin.
fn instructions_path(config: &Config) -> Option<PathBuf> {
if !config.features.enabled(Feature::Plugins) {
return None;
}
let configured =
configured_plugins_from_stack(&config.config_layer_stack, config.codex_home.as_path());
let store = PluginStore::try_new(config.codex_home.to_path_buf()).ok()?;
instructions_path_from(&configured, &config.plugins, &store)
}
/// Mirrors the plugin loader: configured, not disabled, allowed by policy and installed.
fn instructions_path_from(
configured: &HashMap<String, PluginConfig>,
policy: &PluginsConfigToml,
store: &PluginStore,
) -> Option<PathBuf> {
let mut keys = configured
.iter()
.filter(|(key, plugin)| plugin.enabled.unwrap_or(true) && policy.allows_plugin(key))
.map(|(key, _)| key)
.collect::<Vec<_>>();
keys.sort_unstable();
keys.into_iter()
.filter_map(|key| PluginId::parse(key).ok())
.filter(|plugin_id| plugin_id.plugin_name == PLUGIN_NAME)
.find_map(|plugin_id| store.active_plugin_root(&plugin_id))
.map(|root| root.join(INSTRUCTIONS_FILE).to_path_buf())
}
impl ContextContributor for MemoriaExtension {
fn contribute_thread_context<'a>(
&'a self,
_session_store: &'a ExtensionData,
thread_store: &'a ExtensionData,
) -> Pin<Box<dyn Future<Output = Vec<PromptFragment>> + Send + 'a>> {
Box::pin(async move {
let Some(state) = thread_store.get::<MemoriaThreadState>() else {
return Vec::new();
};
let (Some(path), Some(servers)) = (&state.instructions_path, &state.servers) else {
return Vec::new();
};
if !servers.is_ready(SERVER_NAME).await {
tracing::debug!("memoria MCP server is not ready; instructions not injected");
return Vec::new();
}
let instructions = match tokio::fs::read_to_string(path).await {
Ok(instructions) => instructions,
Err(error) => {
tracing::warn!(path = %path.display(), %error, "cannot read memoria instructions");
return Vec::new();
}
};
let instructions = instructions.trim();
if instructions.is_empty() {
return Vec::new();
}
vec![PromptFragment::developer_policy(
instructions,
ContentItemKind(CONTENT_KIND.to_string()),
)]
})
}
}
impl ThreadLifecycleContributor<Config> for MemoriaExtension {
fn on_thread_start<'a>(
&'a self,
input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.thread_store.insert(MemoriaThreadState {
instructions_path: instructions_path(input.config),
servers: input
.mcp_resource_client
.map(|client| client as Arc<dyn ServerReadiness>),
});
})
}
}
impl ConfigContributor<Config> for MemoriaExtension {
fn on_config_changed(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
_previous_config: &Config,
new_config: &Config,
) {
if let Some(state) = thread_store.get::<MemoriaThreadState>() {
thread_store.insert(MemoriaThreadState {
instructions_path: instructions_path(new_config),
servers: state.servers.clone(),
});
}
}
}
/// Installs the memoria instructions contributor into the extension registry.
pub fn install(registry: &mut ExtensionRegistryBuilder<Config>) {
let extension = Arc::new(MemoriaExtension);
registry.thread_lifecycle_contributor(extension.clone());
registry.config_contributor(extension.clone());
registry.prompt_contributor(extension);
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,158 @@
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use akode_config::types::PluginConfig;
use akode_config::types::PluginsConfigToml;
use akode_core_plugins::store::PluginStore;
use akode_extension_api::ContextContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::PromptSlot;
use akode_protocol::models::ContentItem;
use pretty_assertions::assert_eq;
use super::CONTENT_KIND;
use super::INSTRUCTIONS_FILE;
use super::MemoriaExtension;
use super::MemoriaThreadState;
use super::ReadyFuture;
use super::ServerReadiness;
use super::instructions_path_from;
const INSTRUCTIONS: &str = "## Long-term memory (memoria)\n\nCall `memory_recall` first.";
/// Fake MCP catalog: only the listed servers are ready.
struct ReadyServers(Vec<&'static str>);
impl ServerReadiness for ReadyServers {
fn is_ready<'a>(&'a self, server: &'a str) -> ReadyFuture<'a> {
let ready = self.0.contains(&server);
Box::pin(async move { ready })
}
}
fn plugin_config(enabled: Option<bool>) -> PluginConfig {
serde_json::from_value(serde_json::json!({ "enabled": enabled }))
.expect("plugin config should deserialize")
}
/// Installs `memoria@imeai` in a temporary AKODE_HOME and returns its instructions path.
fn install_plugin(codex_home: &Path, with_instructions: bool) -> std::path::PathBuf {
let root = codex_home.join("plugins/cache/imeai/memoria/0.1.0");
std::fs::create_dir_all(root.join(".codex-plugin")).expect("create plugin root");
let path = root.join(INSTRUCTIONS_FILE);
if with_instructions {
std::fs::write(&path, format!("\n{INSTRUCTIONS}\n")).expect("write instructions");
}
path
}
fn thread_store(
instructions_path: Option<std::path::PathBuf>,
ready: Option<Vec<&'static str>>,
) -> ExtensionData {
let store = ExtensionData::new("thread");
store.insert(MemoriaThreadState {
instructions_path,
servers: ready.map(|ready| Arc::new(ReadyServers(ready)) as Arc<dyn ServerReadiness>),
});
store
}
async fn fragments(thread_store: &ExtensionData) -> Vec<akode_extension_api::PromptFragment> {
MemoriaExtension
.contribute_thread_context(&ExtensionData::new("session"), thread_store)
.await
}
#[test]
fn instructions_path_requires_an_enabled_installed_plugin() {
let codex_home = tempfile::tempdir().expect("tempdir");
let store = PluginStore::new(codex_home.path().to_path_buf());
let policy = PluginsConfigToml::default();
let enabled = HashMap::from([("memoria@imeai".to_string(), plugin_config(Some(true)))]);
// Configured but not installed yet.
assert_eq!(instructions_path_from(&enabled, &policy, &store), None);
let expected = install_plugin(codex_home.path(), /*with_instructions*/ true);
assert_eq!(
instructions_path_from(&enabled, &policy, &store),
Some(expected.clone())
);
// Omitting `enabled` keeps an installed plugin active, like the plugin loader.
let inherited = HashMap::from([("memoria@imeai".to_string(), plugin_config(None))]);
assert_eq!(
instructions_path_from(&inherited, &policy, &store),
Some(expected)
);
let disabled = HashMap::from([("memoria@imeai".to_string(), plugin_config(Some(false)))]);
assert_eq!(instructions_path_from(&disabled, &policy, &store), None);
let other = HashMap::from([("other@imeai".to_string(), plugin_config(Some(true)))]);
assert_eq!(instructions_path_from(&other, &policy, &store), None);
assert_eq!(
instructions_path_from(&HashMap::new(), &policy, &store),
None
);
}
#[tokio::test]
async fn injects_instructions_when_plugin_enabled_and_server_ready() {
let codex_home = tempfile::tempdir().expect("tempdir");
let path = install_plugin(codex_home.path(), /*with_instructions*/ true);
let fragments = fragments(&thread_store(Some(path), Some(vec!["memoria"]))).await;
assert_eq!(fragments.len(), 1);
assert_eq!(fragments[0].slot(), PromptSlot::DeveloperPolicy);
assert_eq!(fragments[0].content_kind().0, CONTENT_KIND);
assert_eq!(
fragments[0].content(),
&ContentItem::InputText {
text: INSTRUCTIONS.to_string()
}
);
}
#[tokio::test]
async fn skips_instructions_when_plugin_disabled() {
assert!(
fragments(&thread_store(
/*instructions_path*/ None,
Some(vec!["memoria"])
))
.await
.is_empty()
);
assert!(fragments(&ExtensionData::new("thread")).await.is_empty());
}
#[tokio::test]
async fn skips_instructions_when_server_not_connected() {
let codex_home = tempfile::tempdir().expect("tempdir");
let path = install_plugin(codex_home.path(), /*with_instructions*/ true);
assert!(
fragments(&thread_store(Some(path.clone()), Some(vec!["other"])))
.await
.is_empty()
);
assert!(
fragments(&thread_store(Some(path), /*ready*/ None))
.await
.is_empty()
);
}
#[tokio::test]
async fn skips_instructions_when_file_missing() {
let codex_home = tempfile::tempdir().expect("tempdir");
let path = install_plugin(codex_home.path(), /*with_instructions*/ false);
assert!(
fragments(&thread_store(Some(path), Some(vec!["memoria"])))
.await
.is_empty()
);
}