use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
use tracing::warn;
use trusty_common::memory_rpc::call_memory_tool_at;
use crate::agent_loop::estimate_tokens;
use crate::events::RecalledMemory;
use crate::memory_envelope::{parse_tools_call_envelope, tools_call_params};
use crate::tools::telemetry::{RecallTelemetry, ToolTelemetry};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub const RECALL_SESSION_TOOL_NAME: &str = "recall_session";
pub const DEFAULT_TOP_K: usize = 5;
pub const MAX_TOP_K: usize = 10;
const OVER_FETCH_FACTOR: usize = 4;
const TOKEN_BUDGET: usize = 4000;
#[derive(Debug, Deserialize)]
struct RecallSessionArgs {
query: String,
#[serde(default)]
top_k: Option<usize>,
}
pub struct RecallSessionTool {
session_id: String,
socket: std::path::PathBuf,
palace: String,
}
impl RecallSessionTool {
pub fn new(
session_id: impl Into<String>,
socket: impl Into<std::path::PathBuf>,
palace: impl Into<String>,
) -> Self {
Self {
session_id: session_id.into(),
socket: socket.into(),
palace: palace.into(),
}
}
fn session_tag(&self) -> String {
format!("session:{}", self.session_id)
}
}
fn result_has_tag(result: &Value, tag: &str) -> bool {
result
.get("tags")
.and_then(|t| t.as_array())
.map(|tags| tags.iter().any(|t| t.as_str() == Some(tag)))
.unwrap_or(false)
}
fn filter_and_cap(results: &[Value], tag: &str, top_k: usize) -> Vec<Value> {
let mut filtered: Vec<Value> = results
.iter()
.filter(|r| result_has_tag(r, tag))
.cloned()
.collect();
filtered.truncate(top_k);
filtered
}
fn render_results(query: &str, results: &[Value]) -> (String, usize) {
let mut entries: Vec<String> = Vec::new();
let mut budget_used = 0usize;
for r in results {
let content = r.get("content").and_then(|c| c.as_str()).unwrap_or("");
let entry_tokens = estimate_tokens(content);
if !entries.is_empty() && budget_used + entry_tokens > TOKEN_BUDGET {
break;
}
budget_used += entry_tokens;
entries.push(content.to_string());
}
let dropped = results.len() - entries.len();
if dropped > 0 {
tracing::info!(
dropped,
included = entries.len(),
budget_tokens = TOKEN_BUDGET,
"recall_session: token budget exceeded — dropping lowest-scored result(s)"
);
}
let injected_count = entries.len();
(
format!(
"Session memory results for \"{query}\":\n\n{}",
entries.join("\n\n---\n\n")
),
injected_count,
)
}
fn recall_telemetry(query: &str, results: &[Value], injected_count: usize) -> RecallTelemetry {
RecallTelemetry {
query: query.to_string(),
results: results
.iter()
.enumerate()
.map(|(i, r)| RecalledMemory {
score: r.get("score").and_then(Value::as_f64).unwrap_or(0.0),
injected: i < injected_count,
text: r
.get("content")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
run_id: r.get("run_id").and_then(Value::as_str).map(str::to_string),
})
.collect(),
}
}
#[async_trait]
impl ToolExecutor for RecallSessionTool {
fn name(&self) -> &str {
RECALL_SESSION_TOOL_NAME
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": RECALL_SESSION_TOOL_NAME,
"description": "Search THIS session's own history stored in durable memory. Use when you need something from earlier in this session that is no longer visible in your current context (e.g. a decision, file path, or fact from many turns ago). Does not search other sessions or other projects.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "What to search for in this session's history."
},
"top_k": {
"type": "integer",
"description": "Maximum number of results to return (default 5, max 10)."
}
},
"required": ["query"],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
let parsed: RecallSessionArgs = match serde_json::from_value(args) {
Ok(p) => p,
Err(e) => {
return ToolResult::err(format!(
"recall_session arguments did not match the expected shape ({e}). \
'query' (string) is required."
));
}
};
let top_k = parsed.top_k.unwrap_or(DEFAULT_TOP_K).clamp(1, MAX_TOP_K);
let fetch_k = top_k * OVER_FETCH_FACTOR;
let rpc_params = tools_call_params(
"memory_recall",
json!({
"palace": self.palace,
"query": parsed.query,
"top_k": fetch_k,
}),
);
let envelope = match call_memory_tool_at(&self.socket, "tools/call", rpc_params).await {
Ok(v) => v,
Err(e) => {
warn!(
session_id = %self.session_id,
error = %e,
"recall_session: memory_recall RPC failed (fail-open)"
);
return ToolResult::ok(
"session memory unavailable (trusty-memory unreachable)".to_string(),
);
}
};
let Some(body) = parse_tools_call_envelope(&envelope) else {
warn!(
session_id = %self.session_id,
"recall_session: unexpected memory_recall response shape (fail-open)"
);
return ToolResult::ok(
"session memory unavailable (unexpected response shape)".to_string(),
);
};
let results = body
.get("results")
.and_then(|r| r.as_array())
.cloned()
.unwrap_or_default();
let filtered = filter_and_cap(&results, &self.session_tag(), top_k);
if filtered.is_empty() {
return ToolResult::ok(format!(
"No session memory found for query: {}",
parsed.query
));
}
let (text, injected_count) = render_results(&parsed.query, &filtered);
ToolResult::ok(text).with_telemetry(ToolTelemetry::Recall(recall_telemetry(
&parsed.query,
&filtered,
injected_count,
)))
}
}
#[cfg(test)]
#[path = "recall_session_tests.rs"]
mod tests;