Skip to main content

kernel_apis/
sessions.rs

1//! `sessions.list` / `sessions.search` / `sessions.read` (`sessions` of sessions_api.py): the stored sessions of
2//! this project, or of every project, listed, grepped and read read-only through [`session_journal::search`]. A
3//! finding cites its turns as a span, `session://<id>#<from>..<to>`, which `sessions.read` reads back.
4
5use crate::util::Clock;
6use crate::{ApiModule, Request};
7use serde_json::{Map, Value, json};
8use session_journal::search::{self, Branch, EntryText, Matcher, Query, ReadQuery, SpanRef};
9use std::path::PathBuf;
10
11const DEFAULT_LIMIT: usize = 50;
12/// The most hits a search returns.
13const MAX_LIMIT: usize = 1000;
14const DEFAULT_PER_SESSION: usize = 10;
15const DEFAULT_SNIPPET: usize = 300;
16const DEFAULT_READ_LIMIT: usize = 200;
17const DEFAULT_TOOL_CHARS: usize = 2000;
18/// `cwd="all"`: every project's sessions.
19const ALL: &str = "all";
20
21pub struct SessionsModule {
22    /// Where sessions are stored, searched in order (the first holding an id wins).
23    roots: Vec<PathBuf>,
24    /// This session: `sessions.read` reads it by default, and listings mark it.
25    session_id: String,
26    /// This session's cwd, the default scope.
27    cwd: String,
28    now: Clock,
29}
30
31impl SessionsModule {
32    pub fn new(roots: Vec<PathBuf>, session_id: &str, cwd: &str, now: Clock) -> Self {
33        let mut unique: Vec<PathBuf> = Vec::new();
34        for root in roots {
35            if !unique.contains(&root) {
36                unique.push(root);
37            }
38        }
39        Self {
40            roots: unique,
41            session_id: session_id.into(),
42            cwd: cwd.into(),
43            now,
44        }
45    }
46
47    /// `cwd`: absent for this session's cwd, "all" for every cwd, else an absolute path.
48    fn scope(&self, payload: &Map<String, Value>) -> Result<Option<String>, String> {
49        match payload.get("cwd") {
50            None | Some(Value::Null) => Ok(Some(self.cwd.clone())),
51            Some(Value::String(cwd)) if cwd == ALL => Ok(None),
52            Some(Value::String(cwd)) if cwd.starts_with('/') => Ok(Some(cwd.clone())),
53            _ => Err("sessions cwd must be an absolute path or \"all\"".into()),
54        }
55    }
56
57    fn since(&self, payload: &Map<String, Value>) -> Result<Option<f64>, String> {
58        match payload.get("days") {
59            None | Some(Value::Null) => Ok(None),
60            Some(days) => match days.as_f64() {
61                Some(days) if days > 0.0 => Ok(Some((self.now)() as f64 - days * 86_400_000.0)),
62                _ => Err("sessions days must be a positive number".into()),
63            },
64        }
65    }
66
67    fn list(&self, payload: &Map<String, Value>) -> Result<Value, String> {
68        let limit = count(payload, "limit", DEFAULT_LIMIT, 1)?.min(MAX_LIMIT);
69        let sessions: Vec<Value> = search::list(&self.roots, self.scope(payload)?.as_deref(), self.since(payload)?)
70            .into_iter()
71            .take(limit)
72            .map(|metadata| {
73                let listing = session_journal::names::listing(metadata);
74                let m = &listing.metadata;
75                json!({
76                    "id": m.id,
77                    "cwd": m.cwd,
78                    "path": m.path.display().to_string(),
79                    "created": m.created_at,
80                    "modified": m.modified_at as i64,
81                    "parent": m.parent_session_id,
82                    "name": listing.name,
83                    "first_message": listing.first_message,
84                    "messages": listing.message_count,
85                    "current": m.id == self.session_id,
86                })
87            })
88            .collect();
89        Ok(json!({"sessions": sessions, "current": self.session_id}))
90    }
91
92    fn search(&self, payload: &Map<String, Value>, request: &Request<'_>) -> Result<Value, String> {
93        let ignore_case = match payload.get("ignore_case") {
94            None => true,
95            Some(Value::Bool(yes)) => *yes,
96            _ => return Err("sessions.search ignore_case must be True or False".into()),
97        };
98        let matcher = match (payload.get("pattern"), payload.get("terms")) {
99            (Some(Value::String(pattern)), None) if !pattern.is_empty() => Matcher::pattern(pattern, ignore_case)?,
100            (None, Some(terms)) => Matcher::terms(&strings(Some(terms), "terms")?)?,
101            _ => return Err("sessions.search takes a pattern or terms".into()),
102        };
103        let query = Query {
104            matcher,
105            cwd: self.scope(payload)?,
106            sessions: strings(payload.get("sessions"), "sessions")?,
107            since_ms: self.since(payload)?,
108            branch: branch(payload)?,
109            roles: strings(payload.get("roles"), "roles")?,
110            limit: count(payload, "limit", DEFAULT_LIMIT, 1)?.min(MAX_LIMIT),
111            per_session: count(payload, "per_session", DEFAULT_PER_SESSION, 1)?.min(MAX_LIMIT),
112            snippet: count(payload, "snippet", DEFAULT_SNIPPET, 1)?,
113        };
114        let found = search::grep(&self.roots, &query, &|| request.signal.is_aborted());
115        let hits: Vec<Value> = found
116            .hits
117            .into_iter()
118            .map(|hit| {
119                json!({
120                    "session": hit.session,
121                    "cwd": hit.cwd,
122                    "entry": hit.entry,
123                    "seq": hit.seq,
124                    "timestamp": hit.timestamp,
125                    "role": hit.role,
126                    "tool": hit.tool,
127                    "snippet": hit.snippet,
128                    "matches": hit.matches,
129                    "span": hit.span.to_string(),
130                })
131            })
132            .collect();
133        Ok(json!({
134            "hits": hits,
135            "searched": found.searched,
136            "truncated": found.truncated,
137            "errors": found.errors,
138            "current": self.session_id,
139        }))
140    }
141
142    fn read(&self, payload: &Map<String, Value>) -> Result<Value, String> {
143        let text = |key: &str| match payload.get(key) {
144            None | Some(Value::Null) => Ok(None),
145            Some(Value::String(text)) if !text.is_empty() => Ok(Some(text.clone())),
146            _ => Err(format!("sessions.read {key} must be a nonempty string")),
147        };
148        let span = match text("span")? {
149            Some(span) => {
150                if ["session", "from_entry", "to_entry"]
151                    .iter()
152                    .any(|k| payload.contains_key(*k))
153                {
154                    return Err("sessions.read takes a span or session/from_entry/to_entry, not both".into());
155                }
156                SpanRef::parse(&span)?
157            }
158            None => SpanRef {
159                session: text("session")?.unwrap_or_else(|| self.session_id.clone()),
160                from: text("from_entry")?,
161                to: text("to_entry")?,
162            },
163        };
164        let lane = match branch(payload)? {
165            Branch::Lane(lane) => lane,
166            Branch::All => return Err("sessions.read reads one branch: a lane name, not \"all\"".into()),
167        };
168        let read = search::read(
169            &self.roots,
170            &ReadQuery {
171                span,
172                lane,
173                around: count(payload, "around", 0, 0)?,
174                limit: count(payload, "limit", DEFAULT_READ_LIMIT, 1)?,
175                tool_chars: count(payload, "tool_chars", DEFAULT_TOOL_CHARS, 1)?,
176            },
177        )?;
178        let m = &read.metadata;
179        Ok(json!({
180            "session": {
181                "id": m.id,
182                "cwd": m.cwd,
183                "path": m.path.display().to_string(),
184                "created": m.created_at,
185                "modified": m.modified_at as i64,
186                "parent": m.parent_session_id,
187                "name": read.name,
188                "current": m.id == self.session_id,
189            },
190            "span": read.span.to_string(),
191            "entries": read.entries.iter().map(entry).collect::<Vec<_>>(),
192            "truncated": read.truncated,
193        }))
194    }
195}
196
197fn entry(text: &EntryText) -> Value {
198    json!({
199        "id": text.id,
200        "seq": text.seq,
201        "timestamp": text.timestamp,
202        "type": text.kind,
203        "role": text.role,
204        "tool": text.tool,
205        "text": text.text,
206    })
207}
208
209/// An integer field of at least `min`, else `default`.
210fn count(payload: &Map<String, Value>, key: &str, default: usize, min: u64) -> Result<usize, String> {
211    match payload.get(key) {
212        None | Some(Value::Null) => Ok(default),
213        Some(value) => match value.as_u64() {
214            Some(n) if n >= min => Ok(n as usize),
215            _ => Err(format!("sessions {key} must be an integer of at least {min}")),
216        },
217    }
218}
219
220fn strings(value: Option<&Value>, name: &str) -> Result<Vec<String>, String> {
221    match value {
222        None | Some(Value::Null) => Ok(Vec::new()),
223        Some(Value::Array(items)) => items
224            .iter()
225            .map(|item| {
226                item.as_str()
227                    .filter(|s| !s.is_empty())
228                    .map(str::to_string)
229                    .ok_or_else(|| format!("sessions {name} must be nonempty strings"))
230            })
231            .collect(),
232        _ => Err(format!("sessions {name} must be a list of strings")),
233    }
234}
235
236/// `branch`: a lane's branch (default `main`), or "all" for every entry.
237fn branch(payload: &Map<String, Value>) -> Result<Branch, String> {
238    match payload.get("branch") {
239        None | Some(Value::Null) => Ok(Branch::Lane(search::MAIN_LANE.into())),
240        Some(Value::String(all)) if all == ALL => Ok(Branch::All),
241        Some(Value::String(lane)) if !lane.is_empty() => Ok(Branch::Lane(lane.clone())),
242        _ => Err("sessions branch must be a lane name or \"all\"".into()),
243    }
244}
245
246impl ApiModule for SessionsModule {
247    fn prefixes(&self) -> &[&str] {
248        &["sessions."]
249    }
250
251    fn handle(&self, request: &Request<'_>) -> Result<Value, String> {
252        let payload = request.payload;
253        if kernel::ops::find(request.kind).is_none() {
254            return Err(kernel::ops::not_wired(request.kind));
255        }
256        kernel::ops::fields(request.kind, payload)?;
257        match request.kind {
258            "sessions.list" => self.list(payload),
259            "sessions.search" => self.search(payload, request),
260            "sessions.read" => self.read(payload),
261            other => Err(kernel::ops::not_wired(other)),
262        }
263    }
264}