aKode: consegna delle sessioni al server memoria (memory_ingest_session)

- ext/memoria: trascrizione compatta e cumulativa del thread (utente, risposte
  finali senza commentary, comandi con output troncato a ~1500 caratteri,
  file modificati, ricerche web, altri server MCP; le chiamate al server
  memoria sono ignorate), limite di ~150k caratteri tenendo il primo
  messaggio e i turni più recenti, external_context (web, other_mcp).
- Consegna con reason "idle" dopo `[memoria] deliver_idle_minutes` minuti di
  inattività (predefinito 10, il timer si annulla a ogni nuovo turno) e con
  reason "end" alla chiusura del thread (al massimo 5 s, poi rinuncia).
  Solo se ci sono turni nuovi dall'ultima consegna accettata (queued,
  duplicate, skipped); `[memoria] deliver_sessions = false` la spegne. Solo
  thread dell'utente, con il plugin memoria attivo e il server pronto.
- akode-mcp: McpResourceClient::call_tool e McpConnectionSet::call_host_tool
  per le chiamate dell'host a strumenti non elencati e fuori dal filtro
  enabled_tools (il filtro resta per il modello).
- extension-api: on_thread_closing, chiamato a inizio chiusura quando i server
  MCP sono ancora connessi (on_thread_stop arriva dopo il loro arresto).
- Test sul modello di ext/memoria/src/tests.rs: ruoli, compattazione,
  esclusione del server memoria, external_context, nessuna consegna senza
  turni nuovi, errori, timer di inattività; test del percorso host in
  akode-mcp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-15 00:49:51 +01:00
parent 854c7a66c9
commit 6d4c830805
9 changed files with 1233 additions and 10 deletions

View File

@@ -1088,11 +1088,51 @@ impl McpConnectionSet {
tool: &str, tool: &str,
environment_id: Option<&str>, environment_id: Option<&str>,
arguments: Option<serde_json::Value>, arguments: Option<serde_json::Value>,
mut meta: Option<serde_json::Value>, meta: Option<serde_json::Value>,
requested_timeout: Option<Duration>, requested_timeout: Option<Duration>,
wait_for_server: bool, wait_for_server: bool,
) -> Result<CallToolResult> { ) -> Result<CallToolResult> {
self.validate_tool_call(server, tool, environment_id)?; 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<serde_json::Value>,
requested_timeout: Option<Duration>,
) -> Result<CallToolResult> {
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<serde_json::Value>,
mut meta: Option<serde_json::Value>,
requested_timeout: Option<Duration>,
wait_for_server: bool,
) -> Result<CallToolResult> {
let view = &self.servers[server]; let view = &self.servers[server];
let client = if wait_for_server { let client = if wait_for_server {
view.connection view.connection

View File

@@ -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); 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}");
}

View File

@@ -2,6 +2,7 @@ use std::sync::Arc;
use std::sync::Weak; use std::sync::Weak;
use std::time::Duration; use std::time::Duration;
use akode_protocol::mcp::CallToolResult;
use akode_protocol::mcp::Resource; use akode_protocol::mcp::Resource;
use akode_protocol::mcp::ResourceContent; use akode_protocol::mcp::ResourceContent;
use anyhow::Context; 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<CallToolResult> {
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. /// Reads one resource from the named server.
pub async fn read_resource(&self, server: &str, uri: &str) -> Result<McpResourceReadResult> { pub async fn read_resource(&self, server: &str, uri: &str) -> Result<McpResourceReadResult> {
let params = ReadResourceRequestParams::new(uri.to_string()); let params = ReadResourceRequestParams::new(uri.to_string());

View File

@@ -353,6 +353,8 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc<Session>) {
); );
warn!("failed to shutdown code mode session: {err}"); 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; sess.stop_mcp_prewarm_worker().await;
{ {
let _refresh = sess.mcp_refresh.acquire().await; let _refresh = sess.mcp_refresh.acquire().await;
@@ -366,6 +368,17 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc<Session>) {
emit_thread_stop_lifecycle(sess).await; 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) { async fn emit_thread_stop_lifecycle(sess: &Session) {
for contributor in sess.services.extensions.thread_lifecycle_contributors() { for contributor in sess.services.extensions.thread_lifecycle_contributors() {
contributor contributor

View File

@@ -195,6 +195,16 @@ pub trait ThreadLifecycleContributor<C: Sync>: 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. /// Called during runtime teardown, before the host closes persistent history.
/// Contributors must cancel and join their background work before returning. /// Contributors must cancel and join their background work before returning.
fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> { fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> {

View File

@@ -20,13 +20,16 @@ akode-extension-api = { workspace = true }
akode-features = { workspace = true } akode-features = { workspace = true }
akode-mcp = { workspace = true } akode-mcp = { workspace = true }
akode-plugin = { workspace = true } akode-plugin = { workspace = true }
akode-extension-items = { workspace = true }
akode-protocol = { 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 } tracing = { workspace = true }
urlencoding = { workspace = true } urlencoding = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
[dev-dependencies] [dev-dependencies]
pretty_assertions = { workspace = true } pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true } tempfile = { workspace = true }
tokio = { workspace = true, features = ["fs", "macros", "rt"] } tokio = { workspace = true, features = ["fs", "macros", "rt"] }

View File

@@ -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<String>,
pub(crate) text: String,
}
impl TranscriptTurn {
fn new(role: &'static str, name: Option<String>, 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<TranscriptTurn>,
turns: VecDeque<TranscriptTurn>,
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::<Vec<_>>()
.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::<String>();
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::<Vec<_>>();
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::<Vec<_>>()
.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<String>,
) -> 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<String> {
(!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::<Vec<_>>().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<String> {
let line = text.split_whitespace().collect::<Vec<_>>().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<Arc<dyn ServerReadiness>>,
pub(crate) transcript: Mutex<Transcript>,
timer: Mutex<Option<tokio::task::JoinHandle<()>>>,
/// 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<Arc<dyn ServerReadiness>>,
) -> 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>) {
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<String, String> {
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)),
}
}

View File

@@ -11,6 +11,9 @@
//! in the thread store, so every later prompt assembly (for example after compaction) reuses the //! 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 //! same bytes and the model's prompt cache stays valid. Only a block that starts with the
//! `<memoria_briefing` data tag is accepted. //! `<memoria_briefing` data tag is accepted.
//!
//! Finished sessions are delivered to the server (tool `memory_ingest_session`, called by aKode
//! and never shown to the model): see [`delivery`].
use std::collections::HashMap; use std::collections::HashMap;
use std::future::Future; use std::future::Future;
@@ -21,6 +24,7 @@ use std::time::Duration;
use akode_config::types::PluginConfig; use akode_config::types::PluginConfig;
use akode_core::config::MemoriaBriefingConfig; use akode_core::config::MemoriaBriefingConfig;
use akode_core::config::MemoriaDeliveryConfig;
use akode_config::types::PluginsConfigToml; use akode_config::types::PluginsConfigToml;
use akode_core::config::Config; use akode_core::config::Config;
use akode_core_plugins::configured_plugins_from_stack; use akode_core_plugins::configured_plugins_from_stack;
@@ -32,13 +36,26 @@ use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture; use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder; use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::PromptFragment; use akode_extension_api::PromptFragment;
use akode_extension_api::ThreadIdleInput;
use akode_extension_api::ThreadLifecycleContributor; use akode_extension_api::ThreadLifecycleContributor;
use akode_extension_api::ThreadStartInput; use akode_extension_api::ThreadStartInput;
use akode_extension_api::ThreadStopInput;
use akode_extension_api::TurnLifecycleContributor;
use akode_extension_api::TurnStartInput;
use akode_features::Feature; use akode_features::Feature;
use akode_mcp::McpResourceClient; use akode_mcp::McpResourceClient;
use akode_protocol::items::TurnItem;
use akode_protocol::mcp::ResourceContent; use akode_protocol::mcp::ResourceContent;
use akode_protocol::protocol::SessionSource;
use akode_plugin::PluginId; use akode_plugin::PluginId;
pub mod delivery;
use delivery::DeliveryReason;
use delivery::DeliverySettings;
use delivery::DeliveryState;
use delivery::IngestResponse;
/// Plugin name, regardless of the marketplace it was installed from. /// Plugin name, regardless of the marketplace it was installed from.
pub const PLUGIN_NAME: &str = "memoria"; pub const PLUGIN_NAME: &str = "memoria";
/// MCP server that must be ready before the instructions are injected. /// MCP server that must be ready before the instructions are injected.
@@ -63,11 +80,23 @@ const SERVER_READY_TIMEOUT: Duration = Duration::from_secs(10);
type ReadyFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>; type ReadyFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
type ReadFuture<'a> = Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>>; type ReadFuture<'a> = Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>>;
type CallFuture<'a> = Pin<Box<dyn Future<Output = Result<IngestResponse, String>> + 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 { trait ServerReadiness: Send + Sync {
fn is_ready<'a>(&'a self, server: &'a str) -> ReadyFuture<'a>; fn is_ready<'a>(&'a self, server: &'a str) -> ReadyFuture<'a>;
fn read_text<'a>(&'a self, server: &'a str, uri: String) -> ReadFuture<'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 { impl ServerReadiness for McpResourceClient {
@@ -92,6 +121,30 @@ impl ServerReadiness for McpResourceClient {
.join("\n")) .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::<Vec<_>>()
.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 /// 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<Config> for MemoriaExtension { impl ThreadLifecycleContributor<Config> for MemoriaExtension {
fn on_thread_start<'a>( fn on_thread_start<'a>(
&'a self, &'a self,
input: ThreadStartInput<'a, Config>, input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> { ) -> ExtensionFuture<'a, ()> {
Box::pin(async move { Box::pin(async move {
input.thread_store.insert(MemoriaThreadState { let instructions_path = instructions_path(input.config);
instructions_path: instructions_path(input.config), let servers = input
servers: input
.mcp_resource_client .mcp_resource_client
.map(|client| client as Arc<dyn ServerReadiness>), .map(|client| client as Arc<dyn ServerReadiness>);
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,
servers,
briefing: BriefingSettings::from_config( briefing: BriefingSettings::from_config(
&input.config.memoria_briefing, &input.config.memoria_briefing,
Some(input.config.cwd.to_path_buf()), Some(input.config.cwd.to_path_buf()),
@@ -329,6 +415,57 @@ impl ThreadLifecycleContributor<Config> 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::<DeliveryState>() {
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::<DeliveryState>() {
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::<DeliveryState>() {
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::<DeliveryState>() {
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::<DeliveryState>() {
state.record(item);
}
})
}
} }
impl ConfigContributor<Config> for MemoriaExtension { impl ConfigContributor<Config> for MemoriaExtension {
@@ -339,10 +476,17 @@ impl ConfigContributor<Config> for MemoriaExtension {
_previous_config: &Config, _previous_config: &Config,
new_config: &Config, new_config: &Config,
) { ) {
let new_instructions_path = instructions_path(new_config);
if let Some(delivery) = thread_store.get::<DeliveryState>() {
delivery.plugin_active.store(
new_instructions_path.is_some(),
std::sync::atomic::Ordering::Relaxed,
);
}
if let Some(state) = thread_store.get::<MemoriaThreadState>() { if let Some(state) = thread_store.get::<MemoriaThreadState>() {
// The briefing already fetched stays: the prompt prefix must not change mid-thread. // The briefing already fetched stays: the prompt prefix must not change mid-thread.
thread_store.insert(MemoriaThreadState { thread_store.insert(MemoriaThreadState {
instructions_path: instructions_path(new_config), instructions_path: new_instructions_path,
servers: state.servers.clone(), servers: state.servers.clone(),
briefing: state.briefing.clone(), briefing: state.briefing.clone(),
briefing_text: state.briefing_text.clone(), briefing_text: state.briefing_text.clone(),
@@ -351,10 +495,11 @@ impl ConfigContributor<Config> 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<Config>) { pub fn install(registry: &mut ExtensionRegistryBuilder<Config>) {
let extension = Arc::new(MemoriaExtension); let extension = Arc::new(MemoriaExtension);
registry.thread_lifecycle_contributor(extension.clone()); registry.thread_lifecycle_contributor(extension.clone());
registry.turn_lifecycle_contributor(extension.clone());
registry.config_contributor(extension.clone()); registry.config_contributor(extension.clone());
registry.prompt_contributor(extension); registry.prompt_contributor(extension);
} }

View File

@@ -332,3 +332,381 @@ async fn reads_changed_files_from_git_status() {
let plain = tempfile::tempdir().expect("tempdir"); let plain = tempfile::tempdir().expect("tempdir");
assert!(super::changed_files(plain.path()).await.is_empty()); 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::<Vec<_>>();
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<Option<(String, String, Value)>>,
}
impl IngestServer {
fn new(ready: bool, reply: IngestResponse) -> Arc<Self> {
Arc::new(Self {
ready,
reply,
calls: AtomicUsize::new(0),
last: Mutex::new(None),
})
}
fn queued() -> Arc<Self> {
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<IngestServer>, enabled: bool, plugin_active: bool) -> Arc<DeliveryState> {
Arc::new(DeliveryState::new(
DeliverySettings {
enabled,
idle: Duration::from_millis(30),
},
"thread-42".to_string(),
plugin_active,
Some(server as Arc<dyn ServerReadiness>),
))
}
#[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");
}
}