eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! The `session_search` tool: read the archive that a compiled handoff cites.
//!
//! A compaction hands back a shorter conversation and cites the rows it summarised as `[#N]`.
//! That citation is only worth printing if a ref can be followed, and before this tool it could
//! not be: `eclipse sessions show` prints a whole transcript, there was no "read around row N",
//! and the agent had no way to look anything up. So the handoff promised something the agent
//! could not do — the one thing worse than losing the middle of a conversation.
//!
//! Three shapes, matching the three ways a ref is used:
//!
//! - `around_message_id` — the window a `[#N]` names, with a few rows either side.
//! - `query` — full-text search, in this session or across all of them, returning row refs so a
//!   match can be read in context with the first shape.
//! - neither — the newest rows, which is what "what were we doing" means.
//!
//! The store is the agent's own archive, so this is `allow`: reading a session it is already in
//! writes nothing and reveals nothing the model was not given minutes ago.

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,
    /// Rows either side of `around_message_id` when the caller does not say.
    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 {
                // `#421`: this said `messages.len()`, the size of the whole window, so a reader
                // that had already been shown four of six was told six were left and decided
                // wrongly whether to read on. What is left is what was not rendered.
                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
    }

    /// A keyword search: over the whole archive when no session is named, over one when it is.
    ///
    /// The archive shape is the one that makes "what did we do earlier" answerable: it lists
    /// the sessions that matched, with ids, so the model can read around any row it likes. A
    /// named session narrows the rows and still counts the others, naming them — a note that
    /// says "3 other sessions matched" without saying which is a dead end.
    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);
        // `#240`: the labels come from every session, archived ones included. A hit in an
        // archived session is still a hit and still gets a name — the flag decides what the list
        // shows, not what the archive answers.
        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() {
            // At most three rows from one session, so one chatty conversation cannot fill a
            // list that is meant to be a map of where a topic lives.
            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)
    }
}

/// A store failure is the tool's failure, and the message is the store's own: it names the
/// session and the row, which is what the reader needs to know.
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",
    }
}

/// A message's text, one safe line, with tool calls named: this is a transcript read, not a
/// summary, so a call has to show up as the call it was.
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> {
        // No run means no current session: the caller has to name one. A scope is built here
        // rather than shared, because a tool holding a registry that holds the tool is the
        // reference cycle `CallScope` exists to avoid.
        let registry = crate::tools::ToolRegistry::new(1024);
        let run = crate::tools::RunScope::default();
        let scope = CallScope {
            approver: &crate::tools::DenyAll,
            run: &run,
            registry: &registry,
            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;

        // A search with no session named goes over the whole archive. This is the shape that
        // makes cross-session recall reachable at all: a pointer to "other sessions" that never
        // names one is a dead end, and before this the model could only ask about a session it
        // already knew the id of.
        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: &registry,
            call_id: None,
        };
        tool.call_scoped(args, &scope).await
    }

    /// `#498`: a search that runs inside a session writes a call row and an answer row into the
    /// session it is searching, so the next search found the previous one first — four turns in a
    /// row on one real session, each showing the caller its own tail.
    #[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();
        // The fact the model was actually looking for, said by the user earlier in the session.
        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}"
        );
    }

    /// `#421`: the notice said `messages.len()`, the size of the whole window, so a reader that had
    /// already been shown four of six was told six were left — and a model decides whether to read
    /// further from exactly that number. What is left is what was not rendered.
    #[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();
        // Small enough that the budget runs out part-way through, which is the only case where the
        // notice exists at all.
        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:?}"
        );
    }

    /// The whole reason the tool exists: a ref printed by a handoff has to read back.
    #[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}");
    }

    /// A search with no session named goes over the whole archive and names every session it
    /// found — that is what makes "what did we do earlier" reachable; a hit it will not name
    /// is a hit the model cannot follow.
    #[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}"
        );

        // A hit in the session being written says so rather than pretending it is history.
        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}"
        );
    }

    /// Narrowing to one session still names the others: "3 other sessions matched" without
    /// saying which was a dead end before this.
    #[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}"
        );

        // Named, it answers from that session only.
        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();
        // A scope with no session: the caller has to say which session it means.
        let tool = SessionSearchTool::new(store.clone());
        let registry = ToolRegistry::new(1024);
        let run = RunScope::default();
        let scope = CallScope {
            approver: &Allow,
            run: &run,
            registry: &registry,
            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}");
        // And a session that is not there is named, not silently empty.
        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}");
    }
}