use crate::session::SessionStore;
use crate::tools::{CallScope, Tool, ToolError};
use async_trait::async_trait;
use serde_json::{json, Value};
pub struct SessionSearchTool {
store: SessionStore,
default_window: usize,
}
impl SessionSearchTool {
pub fn new(store: SessionStore) -> Self {
Self {
store,
default_window: 4,
}
}
fn render(&self, messages: &[crate::message::Message], heading: &str, budget: usize) -> String {
let mut out = String::new();
out.push_str(heading);
let mut used = heading.len();
for (index, message) in messages.iter().enumerate() {
let reference = match message.seq {
Some(seq) => format!("[#{seq}]"),
None => "[#?]".to_string(),
};
let body = render_body(message, budget / 2);
let line = format!("\n{reference} {}: {body}", role_name(message));
if used + line.len() > budget {
out.push_str(&format!(
"\n… {} more message(s) here; narrow the window or read further.",
messages.len() - index
));
break;
}
used += line.len();
out.push_str(&line);
}
out
}
fn search(
&self,
query: &str,
named: &str,
current: &str,
limit: usize,
children: bool,
) -> Result<String, ToolError> {
let hits = self
.store
.search_with(query, limit.clamp(1, 10), children)
.map_err(store_error)?;
let clean = crate::compact::clean(query, 120);
let listed = self.store.list_with_archived().map_err(store_error)?;
let by_id: std::collections::HashMap<&str, &crate::session::SessionInfo> =
listed.iter().map(|s| (s.id.as_str(), s)).collect();
let label = |id: &str| -> String {
if !current.is_empty() && id == current {
return "this session".to_string();
}
let mut out = format!("session `{id}`");
if let Some(title) = by_id.get(id).and_then(|i| i.title.as_deref()) {
let title = title.trim();
if !title.is_empty() {
out.push_str(&format!(" \"{}\"", crate::compact::clean(title, 60)));
}
}
out
};
let mine: Vec<&crate::session::SearchHit> = if named.is_empty() {
let mut per_session: std::collections::HashMap<&str, usize> = Default::default();
hits.iter()
.filter(|h| {
let seen = per_session.entry(h.session_id.as_str()).or_insert(0);
*seen += 1;
*seen <= 3
})
.collect()
} else {
hits.iter().filter(|h| h.session_id == named).collect()
};
if mine.is_empty() {
let mut elsewhere: Vec<&str> = hits
.iter()
.map(|h| h.session_id.as_str())
.filter(|id| named.is_empty() || *id != named)
.collect();
elsewhere.sort_unstable();
elsewhere.dedup();
if elsewhere.is_empty() {
return Ok(format!(
"archive: no message in any session matches \"{clean}\"."
));
}
let mut names: Vec<String> = elsewhere.iter().map(|id| label(id)).collect();
names.truncate(5);
return Ok(format!(
"session {named}: no message matches \"{clean}\". {} other session(s) had matches: {}. \
Repeat the search without `session` to see them.",
elsewhere.len(),
names.join(", ")
));
}
let sessions: std::collections::HashSet<&str> =
mine.iter().map(|h| h.session_id.as_str()).collect();
let mut out = if named.is_empty() {
format!(
"archive: {} match(es) for \"{clean}\" in {} session(s)",
mine.len(),
sessions.len()
)
} else {
format!("session {named}: {} match(es) for \"{clean}\"", mine.len())
};
for hit in &mine {
let age = crate::session::ago_words(hit.at_ms);
let when = if age.is_empty() {
String::new()
} else {
format!(" · {age}")
};
out.push_str(&format!(
"\n{} · #{}{when} {}: {}",
label(&hit.session_id),
hit.seq,
crate::compact::clean(&hit.role, 12),
crate::compact::clean(&hit.snippet, 240)
));
}
out.push_str(
"\nRead around any row with session_search(session=\"<id>\", around_message_id=<n>).",
);
Ok(out)
}
}
fn store_error(error: crate::error::Error) -> ToolError {
ToolError::Failed(error.to_string())
}
fn role_name(message: &crate::message::Message) -> &'static str {
match message.role {
crate::message::Role::System => "system",
crate::message::Role::User => "user",
crate::message::Role::Assistant => "assistant",
crate::message::Role::Tool => "tool",
}
}
fn render_body(message: &crate::message::Message, cap: usize) -> String {
let mut parts: Vec<String> = Vec::new();
let composed = message.text_with_pictures();
if !composed.is_empty() {
let text = crate::compact::clean(&composed, cap);
if !text.is_empty() {
parts.push(text);
}
}
for call in &message.tool_calls {
parts.push(format!(
"→ {}({})",
call.function.name,
crate::compact::clean(&call.function.arguments, 200)
));
}
if parts.is_empty() {
parts.push("(empty)".to_string());
}
parts.join(" ")
}
#[async_trait]
impl Tool for SessionSearchTool {
fn name(&self) -> &str {
"session_search"
}
fn description(&self) -> &str {
"Read the session archive: a keyword search across *every* session (or inside one, by \
naming it), the rows a compaction cites as [#N], or the newest rows. Search first when the \
user refers to something from earlier — in this session or a previous one — and read the hit \
with `around_message_id`."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"around_message_id": {
"type": "integer",
"description": "Read the window a [#N] ref names (the N)."
},
"query": {
"type": "string",
"description": "Search every session for these words (all of them in one message). Name `session` to search only that one."
},
"session": {
"type": "string",
"description": "Session to read or to narrow a search to. Defaults to the one this run is writing to for a read; a search without it covers the whole archive."
},
"window": {
"type": "integer",
"description": "Rows either side of `around_message_id` (default 4)."
},
"limit": {
"type": "integer",
"description": "Maximum rows (default 6; a search returns at most 10 matches)."
},
"children": {
"type": "boolean",
"description": "Include child conversations in a search: a bot's own transcript, and the sessions a flare run's workers wrote. Off by default \u{2014} those are somebody else's work, and the human's discovery results do not carry them unless asked."
}
}
})
}
fn describe_call(&self, args: &Value) -> String {
if let Some(id) = args["around_message_id"].as_i64() {
let session = args["session"].as_str().unwrap_or("this session");
return format!(
"read #{id} ±{} in {session}",
args["window"].as_i64().unwrap_or(4)
);
}
if let Some(query) = args["query"].as_str() {
let where_ = match args["session"].as_str().filter(|s| !s.trim().is_empty()) {
Some(session) => format!(" in {session}"),
None => " across sessions".to_string(),
};
return format!("search \"{}\"{where_}", crate::compact::clean(query, 80));
}
"read the newest rows".to_string()
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let registry = crate::tools::ToolRegistry::new(1024);
let run = crate::tools::RunScope::default();
let scope = CallScope {
approver: &crate::tools::DenyAll,
run: &run,
registry: ®istry,
call_id: None,
};
self.call_scoped(args, &scope).await
}
async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
let named = args["session"]
.as_str()
.unwrap_or_default()
.trim()
.to_string();
let limit = args["limit"].as_u64().unwrap_or(6).clamp(1, 40) as usize;
if let Some(query) = args["query"].as_str().map(str::trim) {
if query.is_empty() {
return Err(ToolError::Failed("query is empty".into()));
}
let children = args["children"].as_bool().unwrap_or(false);
return self.search(query, &named, &scope.run.session, limit, children);
}
let session = if !named.is_empty() {
named
} else if !scope.run.session.is_empty() {
scope.run.session.clone()
} else {
return Err(ToolError::Failed(
"no session named and this call is not part of a session".into(),
));
};
if !self.store.exists(&session) {
return Err(ToolError::Failed(format!("no such session {session:?}")));
}
if let Some(seq) = args["around_message_id"].as_i64() {
if seq < 0 {
return Err(ToolError::Failed(
"around_message_id is a row number from a [#N] ref, so it cannot be negative"
.into(),
));
}
let window = args["window"]
.as_u64()
.map(|w| w as usize)
.unwrap_or(self.default_window)
.min(20);
let all = self.store.load(&session).map_err(store_error)?;
let total = all.len();
let centre = all
.iter()
.position(|m| m.seq == Some(seq as u64))
.ok_or_else(|| {
ToolError::Failed(format!(
"#{seq} is not a row of {session:?}; it has {} rows",
total
))
})?;
let start = centre.saturating_sub(window);
let end = (centre + window + 1).min(total);
let slice = &all[start..end];
return Ok(self.render(
slice,
&format!(
"session {session}: rows {start}–{} of {} (a read of the transcript, not a summary)",
end - 1,
total
),
8_000,
));
}
let all = self.store.load(&session).map_err(store_error)?;
let start = all.len().saturating_sub(limit);
Ok(self.render(
&all[start..],
&format!(
"session {session}: the newest {} of {} rows",
all.len() - start,
all.len()
),
8_000,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::message::Message;
use crate::tools::{Approver, RunScope, ToolRegistry};
use async_trait::async_trait;
use serde_json::json;
struct Allow;
#[async_trait]
impl Approver for Allow {
async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
crate::approvals::Decision::Allow
}
}
fn fixture() -> SessionStore {
let dir = tempfile::tempdir().unwrap();
let path = dir.keep();
let store = SessionStore::new(path.join("sessions"));
store
.append("s1", &Message::user("read the config and fix the port"))
.unwrap();
store
.append(
"s1",
&Message::assistant("The port is 8080; I will change it."),
)
.unwrap();
store
.append("s1", &Message::user("careful, don't touch the default"))
.unwrap();
store
.append("s1", &Message::assistant("Noted. Next step is the reload."))
.unwrap();
store
.append("other", &Message::user("an unrelated session about ports"))
.unwrap();
store
}
async fn call(store: SessionStore, args: serde_json::Value) -> Result<String, ToolError> {
let tool = SessionSearchTool::new(store);
let registry = ToolRegistry::new(1024);
let run = RunScope::new("s1");
let scope = CallScope {
approver: &Allow,
run: &run,
registry: ®istry,
call_id: None,
};
tool.call_scoped(args, &scope).await
}
#[tokio::test]
async fn a_search_never_returns_the_search_that_made_it() {
let store = fixture();
let search_call = crate::message::ToolCall {
id: "call-1".to_string(),
kind: "function".to_string(),
function: crate::message::FunctionCall {
name: "session_search".to_string(),
arguments: "{\"query\":\"avatar_small\"}".to_string(),
},
};
store
.append(
"s1",
&Message::assistant_tool_calls(None, vec![search_call]),
)
.unwrap();
store
.append(
"s1",
&Message::tool_result("call-1", "archive: 0 match(es) for \"avatar_small\""),
)
.unwrap();
store
.append("s1", &Message::user("the avatar_small file lives here"))
.unwrap();
let out = call(store, json!({"query": "avatar_small"})).await.unwrap();
assert!(
out.contains("the avatar_small file lives here"),
"the user's own words are still a hit: {out}"
);
assert_eq!(
out.matches("match(es)").count(),
1,
"the user's row is the only match: {out}"
);
assert!(
!out.contains("assistant:"),
"neither the call nor its answer is listed: {out}"
);
}
#[test]
fn the_truncation_notice_counts_what_is_left_not_the_whole_window() {
let tool = SessionSearchTool::new(fixture());
let messages: Vec<Message> = (0..6)
.map(|i| Message::user(format!("row {i} {}", "x".repeat(24))))
.collect();
let out = tool.render(&messages, "window:", 120);
let shown = out.matches("[#").count();
let rest = out
.split("… ")
.nth(1)
.and_then(|tail| tail.split(' ').next())
.and_then(|n| n.parse::<usize>().ok())
.unwrap_or_else(|| panic!("no truncation notice in {out:?}"));
assert!(
shown > 0 && shown < messages.len(),
"the test needs a partial window; shown {shown} of {}",
messages.len()
);
assert_eq!(
rest,
messages.len() - shown,
"the notice counts the remainder, not the window's size: {out:?}"
);
}
#[tokio::test]
async fn a_ref_from_a_handoff_reads_the_row_it_names() {
let store = fixture();
let text = call(store, json!({"around_message_id": 1})).await.unwrap();
assert!(text.contains("[#1] assistant: The port is 8080"), "{text}");
assert!(
text.contains("[#0] user: read the config"),
"the window shows what led to it: {text}"
);
}
#[tokio::test]
async fn a_row_that_does_not_exist_is_an_error_that_names_the_size() {
let store = fixture();
let err = call(store, json!({"around_message_id": 99}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("#99") && err.contains("4 rows"), "{err}");
}
#[tokio::test]
async fn a_search_without_a_session_covers_the_archive_and_names_where_it_matched() {
let store = fixture();
let text = call(store.clone(), json!({ "query": "unrelated" }))
.await
.unwrap();
assert!(
text.contains("archive: 1 match(es) for \"unrelated\" in 1 session(s)"),
"{text}"
);
assert!(
text.contains("session `other`"),
"the session is named: {text}"
);
assert!(
text.contains("an unrelated session about ports"),
"and comes with its text: {text}"
);
let mine = call(store, json!({ "query": "reload" })).await.unwrap();
assert!(mine.contains("this session"), "{mine}");
assert!(
mine.contains("#3") && mine.contains("Next step is the reload"),
"a match has to come with its row and its text: {mine}"
);
assert!(
mine.contains("session_search(session="),
"and with the way to read around it: {mine}"
);
}
#[tokio::test]
async fn a_search_named_to_one_session_still_says_which_others_matched() {
let store = fixture();
let miss = call(
store.clone(),
json!({ "query": "unrelated", "session": "s1" }),
)
.await
.unwrap();
assert!(miss.contains("no message matches"), "{miss}");
assert!(
miss.contains("1 other session(s) had matches") && miss.contains("session `other`"),
"{miss}"
);
let there = call(store, json!({ "query": "unrelated", "session": "other" }))
.await
.unwrap();
assert!(
there.contains("session other: 1 match(es)") && there.contains("about ports"),
"{there}"
);
assert!(!there.contains("this session"), "{there}");
}
#[tokio::test]
async fn with_neither_a_ref_nor_a_query_it_reads_the_newest_rows() {
let store = fixture();
let text = call(store, json!({"limit": 2})).await.unwrap();
assert!(text.contains("the newest 2 of 4 rows"), "{text}");
assert!(text.contains("Next step is the reload"), "{text}");
assert!(
!text.contains("read the config"),
"the oldest row is not the newest: {text}"
);
}
#[tokio::test]
async fn the_session_defaults_to_the_run_and_must_be_named_without_one() {
let store = fixture();
let tool = SessionSearchTool::new(store.clone());
let registry = ToolRegistry::new(1024);
let run = RunScope::default();
let scope = CallScope {
approver: &Allow,
run: &run,
registry: ®istry,
call_id: None,
};
let err = tool
.call_scoped(json!({"limit": 1}), &scope)
.await
.unwrap_err()
.to_string();
assert!(err.contains("not part of a session"), "{err}");
let err = call(store, json!({"session": "nope", "limit": 1}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("no such session"), "{err}");
}
#[tokio::test]
async fn a_tool_call_in_the_window_shows_up_as_the_call_it_was() {
let store = fixture();
let call_struct = crate::message::ToolCall {
id: "c1".to_string(),
kind: "function".to_string(),
function: crate::message::FunctionCall {
name: "read_file".to_string(),
arguments: "{\"path\":\"/etc/eclipse/config.toml\"}".to_string(),
},
};
store
.append(
"s1",
&Message::assistant_tool_calls(None, vec![call_struct]),
)
.unwrap();
let text = call(store, json!({"limit": 1})).await.unwrap();
assert!(text.contains("→ read_file("), "{text}");
assert!(text.contains("/etc/eclipse/config.toml"), "{text}");
}
}