1use crate::session::SessionStore;
20use crate::tools::{CallScope, Tool, ToolError};
21use async_trait::async_trait;
22use serde_json::{json, Value};
23
24pub struct SessionSearchTool {
25 store: SessionStore,
26 default_window: usize,
28}
29
30impl SessionSearchTool {
31 pub fn new(store: SessionStore) -> Self {
32 Self {
33 store,
34 default_window: 4,
35 }
36 }
37
38 fn render(&self, messages: &[crate::message::Message], heading: &str, budget: usize) -> String {
39 let mut out = String::new();
40 out.push_str(heading);
41 let mut used = heading.len();
42 for (index, message) in messages.iter().enumerate() {
43 let reference = match message.seq {
44 Some(seq) => format!("[#{seq}]"),
45 None => "[#?]".to_string(),
46 };
47 let body = render_body(message, budget / 2);
48 let line = format!("\n{reference} {}: {body}", role_name(message));
49 if used + line.len() > budget {
50 out.push_str(&format!(
54 "\n… {} more message(s) here; narrow the window or read further.",
55 messages.len() - index
56 ));
57 break;
58 }
59 used += line.len();
60 out.push_str(&line);
61 }
62 out
63 }
64
65 fn search(
72 &self,
73 query: &str,
74 named: &str,
75 current: &str,
76 limit: usize,
77 children: bool,
78 ) -> Result<String, ToolError> {
79 let hits = self
80 .store
81 .search_with(query, limit.clamp(1, 10), children)
82 .map_err(store_error)?;
83 let clean = crate::compact::clean(query, 120);
84 let listed = self.store.list_with_archived().map_err(store_error)?;
88 let by_id: std::collections::HashMap<&str, &crate::session::SessionInfo> =
89 listed.iter().map(|s| (s.id.as_str(), s)).collect();
90
91 let label = |id: &str| -> String {
92 if !current.is_empty() && id == current {
93 return "this session".to_string();
94 }
95 let mut out = format!("session `{id}`");
96 if let Some(title) = by_id.get(id).and_then(|i| i.title.as_deref()) {
97 let title = title.trim();
98 if !title.is_empty() {
99 out.push_str(&format!(" \"{}\"", crate::compact::clean(title, 60)));
100 }
101 }
102 out
103 };
104
105 let mine: Vec<&crate::session::SearchHit> = if named.is_empty() {
106 let mut per_session: std::collections::HashMap<&str, usize> = Default::default();
109 hits.iter()
110 .filter(|h| {
111 let seen = per_session.entry(h.session_id.as_str()).or_insert(0);
112 *seen += 1;
113 *seen <= 3
114 })
115 .collect()
116 } else {
117 hits.iter().filter(|h| h.session_id == named).collect()
118 };
119
120 if mine.is_empty() {
121 let mut elsewhere: Vec<&str> = hits
122 .iter()
123 .map(|h| h.session_id.as_str())
124 .filter(|id| named.is_empty() || *id != named)
125 .collect();
126 elsewhere.sort_unstable();
127 elsewhere.dedup();
128 if elsewhere.is_empty() {
129 return Ok(format!(
130 "archive: no message in any session matches \"{clean}\"."
131 ));
132 }
133 let mut names: Vec<String> = elsewhere.iter().map(|id| label(id)).collect();
134 names.truncate(5);
135 return Ok(format!(
136 "session {named}: no message matches \"{clean}\". {} other session(s) had matches: {}. \
137 Repeat the search without `session` to see them.",
138 elsewhere.len(),
139 names.join(", ")
140 ));
141 }
142
143 let sessions: std::collections::HashSet<&str> =
144 mine.iter().map(|h| h.session_id.as_str()).collect();
145 let mut out = if named.is_empty() {
146 format!(
147 "archive: {} match(es) for \"{clean}\" in {} session(s)",
148 mine.len(),
149 sessions.len()
150 )
151 } else {
152 format!("session {named}: {} match(es) for \"{clean}\"", mine.len())
153 };
154 for hit in &mine {
155 let age = crate::session::ago_words(hit.at_ms);
156 let when = if age.is_empty() {
157 String::new()
158 } else {
159 format!(" · {age}")
160 };
161 out.push_str(&format!(
162 "\n{} · #{}{when} {}: {}",
163 label(&hit.session_id),
164 hit.seq,
165 crate::compact::clean(&hit.role, 12),
166 crate::compact::clean(&hit.snippet, 240)
167 ));
168 }
169 out.push_str(
170 "\nRead around any row with session_search(session=\"<id>\", around_message_id=<n>).",
171 );
172 Ok(out)
173 }
174}
175
176fn store_error(error: crate::error::Error) -> ToolError {
179 ToolError::Failed(error.to_string())
180}
181
182fn role_name(message: &crate::message::Message) -> &'static str {
183 match message.role {
184 crate::message::Role::System => "system",
185 crate::message::Role::User => "user",
186 crate::message::Role::Assistant => "assistant",
187 crate::message::Role::Tool => "tool",
188 }
189}
190
191fn render_body(message: &crate::message::Message, cap: usize) -> String {
194 let mut parts: Vec<String> = Vec::new();
195 let composed = message.text_with_pictures();
196 if !composed.is_empty() {
197 let text = crate::compact::clean(&composed, cap);
198 if !text.is_empty() {
199 parts.push(text);
200 }
201 }
202 for call in &message.tool_calls {
203 parts.push(format!(
204 "→ {}({})",
205 call.function.name,
206 crate::compact::clean(&call.function.arguments, 200)
207 ));
208 }
209 if parts.is_empty() {
210 parts.push("(empty)".to_string());
211 }
212 parts.join(" ")
213}
214
215#[async_trait]
216impl Tool for SessionSearchTool {
217 fn name(&self) -> &str {
218 "session_search"
219 }
220
221 fn description(&self) -> &str {
222 "Read the session archive: a keyword search across *every* session (or inside one, by \
223naming it), the rows a compaction cites as [#N], or the newest rows. Search first when the \
224user refers to something from earlier — in this session or a previous one — and read the hit \
225with `around_message_id`."
226 }
227
228 fn parameters(&self) -> Value {
229 json!({
230 "type": "object",
231 "properties": {
232 "around_message_id": {
233 "type": "integer",
234 "description": "Read the window a [#N] ref names (the N)."
235 },
236 "query": {
237 "type": "string",
238 "description": "Search every session for these words (all of them in one message). Name `session` to search only that one."
239 },
240 "session": {
241 "type": "string",
242 "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."
243 },
244 "window": {
245 "type": "integer",
246 "description": "Rows either side of `around_message_id` (default 4)."
247 },
248 "limit": {
249 "type": "integer",
250 "description": "Maximum rows (default 6; a search returns at most 10 matches)."
251 },
252 "children": {
253 "type": "boolean",
254 "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."
255 }
256 }
257 })
258 }
259
260 fn describe_call(&self, args: &Value) -> String {
261 if let Some(id) = args["around_message_id"].as_i64() {
262 let session = args["session"].as_str().unwrap_or("this session");
263 return format!(
264 "read #{id} ±{} in {session}",
265 args["window"].as_i64().unwrap_or(4)
266 );
267 }
268 if let Some(query) = args["query"].as_str() {
269 let where_ = match args["session"].as_str().filter(|s| !s.trim().is_empty()) {
270 Some(session) => format!(" in {session}"),
271 None => " across sessions".to_string(),
272 };
273 return format!("search \"{}\"{where_}", crate::compact::clean(query, 80));
274 }
275 "read the newest rows".to_string()
276 }
277
278 async fn call(&self, args: Value) -> Result<String, ToolError> {
279 let registry = crate::tools::ToolRegistry::new(1024);
283 let run = crate::tools::RunScope::default();
284 let scope = CallScope {
285 approver: &crate::tools::DenyAll,
286 run: &run,
287 registry: ®istry,
288 call_id: None,
289 };
290 self.call_scoped(args, &scope).await
291 }
292
293 async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
294 let named = args["session"]
295 .as_str()
296 .unwrap_or_default()
297 .trim()
298 .to_string();
299 let limit = args["limit"].as_u64().unwrap_or(6).clamp(1, 40) as usize;
300
301 if let Some(query) = args["query"].as_str().map(str::trim) {
306 if query.is_empty() {
307 return Err(ToolError::Failed("query is empty".into()));
308 }
309 let children = args["children"].as_bool().unwrap_or(false);
310 return self.search(query, &named, &scope.run.session, limit, children);
311 }
312
313 let session = if !named.is_empty() {
314 named
315 } else if !scope.run.session.is_empty() {
316 scope.run.session.clone()
317 } else {
318 return Err(ToolError::Failed(
319 "no session named and this call is not part of a session".into(),
320 ));
321 };
322 if !self.store.exists(&session) {
323 return Err(ToolError::Failed(format!("no such session {session:?}")));
324 }
325
326 if let Some(seq) = args["around_message_id"].as_i64() {
327 if seq < 0 {
328 return Err(ToolError::Failed(
329 "around_message_id is a row number from a [#N] ref, so it cannot be negative"
330 .into(),
331 ));
332 }
333 let window = args["window"]
334 .as_u64()
335 .map(|w| w as usize)
336 .unwrap_or(self.default_window)
337 .min(20);
338 let all = self.store.load(&session).map_err(store_error)?;
339 let total = all.len();
340 let centre = all
341 .iter()
342 .position(|m| m.seq == Some(seq as u64))
343 .ok_or_else(|| {
344 ToolError::Failed(format!(
345 "#{seq} is not a row of {session:?}; it has {} rows",
346 total
347 ))
348 })?;
349 let start = centre.saturating_sub(window);
350 let end = (centre + window + 1).min(total);
351 let slice = &all[start..end];
352 return Ok(self.render(
353 slice,
354 &format!(
355 "session {session}: rows {start}–{} of {} (a read of the transcript, not a summary)",
356 end - 1,
357 total
358 ),
359 8_000,
360 ));
361 }
362
363 let all = self.store.load(&session).map_err(store_error)?;
364 let start = all.len().saturating_sub(limit);
365 Ok(self.render(
366 &all[start..],
367 &format!(
368 "session {session}: the newest {} of {} rows",
369 all.len() - start,
370 all.len()
371 ),
372 8_000,
373 ))
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380 use crate::message::Message;
381 use crate::tools::{Approver, RunScope, ToolRegistry};
382 use async_trait::async_trait;
383 use serde_json::json;
384
385 struct Allow;
386
387 #[async_trait]
388 impl Approver for Allow {
389 async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
390 crate::approvals::Decision::Allow
391 }
392 }
393
394 fn fixture() -> SessionStore {
395 let dir = tempfile::tempdir().unwrap();
396 let path = dir.keep();
397 let store = SessionStore::new(path.join("sessions"));
398 store
399 .append("s1", &Message::user("read the config and fix the port"))
400 .unwrap();
401 store
402 .append(
403 "s1",
404 &Message::assistant("The port is 8080; I will change it."),
405 )
406 .unwrap();
407 store
408 .append("s1", &Message::user("careful, don't touch the default"))
409 .unwrap();
410 store
411 .append("s1", &Message::assistant("Noted. Next step is the reload."))
412 .unwrap();
413 store
414 .append("other", &Message::user("an unrelated session about ports"))
415 .unwrap();
416 store
417 }
418
419 async fn call(store: SessionStore, args: serde_json::Value) -> Result<String, ToolError> {
420 let tool = SessionSearchTool::new(store);
421 let registry = ToolRegistry::new(1024);
422 let run = RunScope::new("s1");
423 let scope = CallScope {
424 approver: &Allow,
425 run: &run,
426 registry: ®istry,
427 call_id: None,
428 };
429 tool.call_scoped(args, &scope).await
430 }
431
432 #[tokio::test]
436 async fn a_search_never_returns_the_search_that_made_it() {
437 let store = fixture();
438 let search_call = crate::message::ToolCall {
439 id: "call-1".to_string(),
440 kind: "function".to_string(),
441 function: crate::message::FunctionCall {
442 name: "session_search".to_string(),
443 arguments: "{\"query\":\"avatar_small\"}".to_string(),
444 },
445 };
446 store
447 .append(
448 "s1",
449 &Message::assistant_tool_calls(None, vec![search_call]),
450 )
451 .unwrap();
452 store
453 .append(
454 "s1",
455 &Message::tool_result("call-1", "archive: 0 match(es) for \"avatar_small\""),
456 )
457 .unwrap();
458 store
460 .append("s1", &Message::user("the avatar_small file lives here"))
461 .unwrap();
462
463 let out = call(store, json!({"query": "avatar_small"})).await.unwrap();
464 assert!(
465 out.contains("the avatar_small file lives here"),
466 "the user's own words are still a hit: {out}"
467 );
468 assert_eq!(
469 out.matches("match(es)").count(),
470 1,
471 "the user's row is the only match: {out}"
472 );
473 assert!(
474 !out.contains("assistant:"),
475 "neither the call nor its answer is listed: {out}"
476 );
477 }
478
479 #[test]
483 fn the_truncation_notice_counts_what_is_left_not_the_whole_window() {
484 let tool = SessionSearchTool::new(fixture());
485 let messages: Vec<Message> = (0..6)
486 .map(|i| Message::user(format!("row {i} {}", "x".repeat(24))))
487 .collect();
488 let out = tool.render(&messages, "window:", 120);
491 let shown = out.matches("[#").count();
492 let rest = out
493 .split("… ")
494 .nth(1)
495 .and_then(|tail| tail.split(' ').next())
496 .and_then(|n| n.parse::<usize>().ok())
497 .unwrap_or_else(|| panic!("no truncation notice in {out:?}"));
498 assert!(
499 shown > 0 && shown < messages.len(),
500 "the test needs a partial window; shown {shown} of {}",
501 messages.len()
502 );
503 assert_eq!(
504 rest,
505 messages.len() - shown,
506 "the notice counts the remainder, not the window's size: {out:?}"
507 );
508 }
509
510 #[tokio::test]
512 async fn a_ref_from_a_handoff_reads_the_row_it_names() {
513 let store = fixture();
514 let text = call(store, json!({"around_message_id": 1})).await.unwrap();
515 assert!(text.contains("[#1] assistant: The port is 8080"), "{text}");
516 assert!(
517 text.contains("[#0] user: read the config"),
518 "the window shows what led to it: {text}"
519 );
520 }
521
522 #[tokio::test]
523 async fn a_row_that_does_not_exist_is_an_error_that_names_the_size() {
524 let store = fixture();
525 let err = call(store, json!({"around_message_id": 99}))
526 .await
527 .unwrap_err()
528 .to_string();
529 assert!(err.contains("#99") && err.contains("4 rows"), "{err}");
530 }
531
532 #[tokio::test]
536 async fn a_search_without_a_session_covers_the_archive_and_names_where_it_matched() {
537 let store = fixture();
538
539 let text = call(store.clone(), json!({ "query": "unrelated" }))
540 .await
541 .unwrap();
542 assert!(
543 text.contains("archive: 1 match(es) for \"unrelated\" in 1 session(s)"),
544 "{text}"
545 );
546 assert!(
547 text.contains("session `other`"),
548 "the session is named: {text}"
549 );
550 assert!(
551 text.contains("an unrelated session about ports"),
552 "and comes with its text: {text}"
553 );
554
555 let mine = call(store, json!({ "query": "reload" })).await.unwrap();
557 assert!(mine.contains("this session"), "{mine}");
558 assert!(
559 mine.contains("#3") && mine.contains("Next step is the reload"),
560 "a match has to come with its row and its text: {mine}"
561 );
562 assert!(
563 mine.contains("session_search(session="),
564 "and with the way to read around it: {mine}"
565 );
566 }
567
568 #[tokio::test]
571 async fn a_search_named_to_one_session_still_says_which_others_matched() {
572 let store = fixture();
573 let miss = call(
574 store.clone(),
575 json!({ "query": "unrelated", "session": "s1" }),
576 )
577 .await
578 .unwrap();
579 assert!(miss.contains("no message matches"), "{miss}");
580 assert!(
581 miss.contains("1 other session(s) had matches") && miss.contains("session `other`"),
582 "{miss}"
583 );
584
585 let there = call(store, json!({ "query": "unrelated", "session": "other" }))
587 .await
588 .unwrap();
589 assert!(
590 there.contains("session other: 1 match(es)") && there.contains("about ports"),
591 "{there}"
592 );
593 assert!(!there.contains("this session"), "{there}");
594 }
595
596 #[tokio::test]
597 async fn with_neither_a_ref_nor_a_query_it_reads_the_newest_rows() {
598 let store = fixture();
599 let text = call(store, json!({"limit": 2})).await.unwrap();
600 assert!(text.contains("the newest 2 of 4 rows"), "{text}");
601 assert!(text.contains("Next step is the reload"), "{text}");
602 assert!(
603 !text.contains("read the config"),
604 "the oldest row is not the newest: {text}"
605 );
606 }
607
608 #[tokio::test]
609 async fn the_session_defaults_to_the_run_and_must_be_named_without_one() {
610 let store = fixture();
611 let tool = SessionSearchTool::new(store.clone());
613 let registry = ToolRegistry::new(1024);
614 let run = RunScope::default();
615 let scope = CallScope {
616 approver: &Allow,
617 run: &run,
618 registry: ®istry,
619 call_id: None,
620 };
621 let err = tool
622 .call_scoped(json!({"limit": 1}), &scope)
623 .await
624 .unwrap_err()
625 .to_string();
626 assert!(err.contains("not part of a session"), "{err}");
627 let err = call(store, json!({"session": "nope", "limit": 1}))
629 .await
630 .unwrap_err()
631 .to_string();
632 assert!(err.contains("no such session"), "{err}");
633 }
634
635 #[tokio::test]
636 async fn a_tool_call_in_the_window_shows_up_as_the_call_it_was() {
637 let store = fixture();
638 let call_struct = crate::message::ToolCall {
639 id: "c1".to_string(),
640 kind: "function".to_string(),
641 function: crate::message::FunctionCall {
642 name: "read_file".to_string(),
643 arguments: "{\"path\":\"/etc/eclipse/config.toml\"}".to_string(),
644 },
645 };
646 store
647 .append(
648 "s1",
649 &Message::assistant_tool_calls(None, vec![call_struct]),
650 )
651 .unwrap();
652 let text = call(store, json!({"limit": 1})).await.unwrap();
653 assert!(text.contains("→ read_file("), "{text}");
654 assert!(text.contains("/etc/eclipse/config.toml"), "{text}");
655 }
656}