1use std::collections::HashMap;
4
5use indexmap::IndexMap;
6use serde_json::{Map, Value};
7
8use crate::js;
9
10pub(crate) fn id_key(value: Option<&Value>) -> String {
12 value.map_or_else(|| "undefined".to_string(), jsrt::json::stringify)
13}
14
15pub(crate) fn str_key(id: &str) -> String {
16 jsrt::json::stringify(&Value::from(id))
17}
18
19pub(crate) fn field<'a>(entry: &'a Value, name: &str) -> Option<&'a Value> {
20 entry.get(name)
21}
22
23pub(crate) fn entry_type(entry: &Value) -> Option<&str> {
24 entry.get("type").and_then(Value::as_str)
25}
26
27fn message_role(entry: &Value) -> Option<&str> {
28 entry.get("message")?.get("role")?.as_str()
29}
30
31pub(crate) fn is_message_with_role(entry: &Value, role: &str) -> bool {
32 entry_type(entry) == Some("message") && message_role(entry) == Some(role)
33}
34
35pub(crate) fn object(pairs: Vec<(&str, Option<Value>)>) -> Value {
37 let mut map = Map::new();
38 for (key, value) in pairs {
39 if let Some(value) = value {
40 map.insert(key.to_string(), value);
41 }
42 }
43 Value::Object(map)
44}
45
46fn with_field(value: &Value, key: &str, new: Option<Value>) -> Value {
48 let mut out = value.clone();
49 if let Value::Object(map) = &mut out {
50 match new {
51 Some(new) => {
52 map.insert(key.to_string(), new);
53 }
54 None => {
55 map.shift_remove(key);
56 }
57 }
58 }
59 out
60}
61
62#[derive(Clone, Copy, Debug)]
64pub enum Leaf<'a> {
65 Last,
67 Root,
69 Id(&'a Value),
71}
72
73pub(crate) fn walk_to_root<'a>(
75 leaf: Option<&'a Value>,
76 limit: usize,
77 lookup: impl Fn(&str) -> Option<&'a Value>,
78) -> Vec<&'a Value> {
79 let mut path = Vec::new();
80 let mut current = leaf;
81 while let Some(entry) = current {
82 if path.len() > limit {
84 break;
85 }
86 path.push(entry);
87 current = entry
88 .get("parentId")
89 .filter(|p| jsrt::value::truthy(Some(p)))
90 .and_then(|p| lookup(&id_key(Some(p))));
91 }
92 path.reverse();
93 path
94}
95
96pub(crate) fn session_path<'a>(entries: &[&'a Value], leaf: Leaf<'_>) -> Vec<&'a Value> {
98 let by_id: HashMap<String, &Value> = entries.iter().map(|e| (id_key(e.get("id")), *e)).collect();
99 let start = match leaf {
100 Leaf::Root => return Vec::new(),
101 Leaf::Id(id) if jsrt::value::truthy(Some(id)) => {
102 by_id.get(&id_key(Some(id))).copied().or(entries.last().copied())
103 }
104 _ => entries.last().copied(),
105 };
106 walk_to_root(start, by_id.len(), |key| by_id.get(key).copied())
107}
108
109pub fn build_context_entries<'a>(entries: &'a [Value], leaf: Leaf<'_>) -> Vec<&'a Value> {
112 context_entries(&entries.iter().collect::<Vec<_>>(), leaf)
113}
114
115pub(crate) fn context_entries<'a>(entries: &[&'a Value], leaf: Leaf<'_>) -> Vec<&'a Value> {
116 context_entries_of_path(session_path(entries, leaf))
117}
118
119fn context_entries_of_path(path: Vec<&Value>) -> Vec<&Value> {
120 let Some(compaction) = path.iter().rev().copied().find(|e| entry_type(e) == Some("compaction")) else {
121 return path;
122 };
123 let Some(compaction_idx) = path.iter().position(|e| e.get("id") == compaction.get("id")) else {
124 return path;
125 };
126 let first_kept = compaction.get("firstKeptEntryId");
127 let mut out = vec![compaction];
128 let mut found = false;
129 for entry in &path[..compaction_idx] {
130 if entry.get("id") == first_kept {
131 found = true;
132 }
133 if found && !is_message_with_role(entry, "system") {
134 out.push(entry);
135 }
136 }
137 out.extend(&path[compaction_idx + 1..]);
138 out
139}
140
141fn custom_message(entry: &Value) -> Value {
142 let content = entry
143 .get("content")
144 .filter(|c| !c.is_null())
145 .cloned()
146 .unwrap_or(Value::Array(Vec::new()));
147 object(vec![
148 ("role", Some("custom".into())),
149 ("customType", entry.get("customType").cloned()),
150 ("content", Some(content)),
151 ("display", entry.get("display").cloned()),
152 ("details", entry.get("details").cloned()),
153 ("timestamp", Some(js::date_json(entry.get("timestamp")))),
154 ])
155}
156
157pub fn entry_messages(entry: &Value) -> Vec<Value> {
159 match entry_type(entry) {
160 Some("message") => {
161 let Some(message) = entry.get("message") else {
162 return Vec::new();
163 };
164 let role = message.get("role").and_then(Value::as_str);
165 let empty_content = js::nullish(message.get("content"));
166 match role {
167 Some("system") if empty_content => vec![with_field(message, "content", Some("".into()))],
168 Some("user" | "assistant" | "toolResult") if empty_content => {
169 vec![with_field(message, "content", Some(Value::Array(Vec::new())))]
170 }
171 _ => vec![message.clone()],
172 }
173 }
174 Some("custom_message") => vec![custom_message(entry)],
175 Some("branch_summary") if jsrt::value::truthy(entry.get("summary")) => vec![object(vec![
176 ("role", Some("branchSummary".into())),
177 ("summary", entry.get("summary").cloned()),
178 ("fromId", entry.get("fromId").cloned()),
179 ("timestamp", Some(js::date_json(entry.get("timestamp")))),
180 ])],
181 Some("compaction") => {
182 let summary = object(vec![
183 ("role", Some("compactionSummary".into())),
184 ("summary", entry.get("summary").cloned()),
185 ("tokensBefore", entry.get("tokensBefore").cloned()),
186 ("timestamp", Some(js::date_json(entry.get("timestamp")))),
187 ]);
188 match entry.get("systemMessage") {
189 Some(system) if jsrt::value::truthy(Some(system)) => vec![system.clone(), summary],
190 _ => vec![summary],
191 }
192 }
193 _ => Vec::new(),
194 }
195}
196
197fn project_entry(entry: &Value, edit: Option<&Value>) -> Vec<Value> {
198 let messages = entry_messages(entry);
199 let Some(edit) = edit else { return messages };
200 let replacement = match edit.get("replacement") {
201 Some(Value::Null) => return Vec::new(),
202 None => return messages,
204 Some(replacement) => replacement,
205 };
206 messages
207 .into_iter()
208 .map(|message| {
209 let role = message.get("role").and_then(Value::as_str);
210 if !matches!(role, Some("user" | "assistant" | "toolResult" | "custom")) {
211 return message;
212 }
213 let content = match replacement.get("content") {
214 Some(Value::String(text)) if matches!(role, Some("assistant" | "toolResult")) => {
215 Some(serde_json::json!([{ "type": "text", "text": text }]))
216 }
217 other => other.cloned(),
218 };
219 with_field(&message, "content", content)
220 })
221 .collect()
222}
223
224#[derive(Clone, Debug, PartialEq)]
226pub struct ProjectedEntry<'a> {
227 pub source: &'a Value,
228 pub messages: Vec<Value>,
229}
230
231#[derive(Clone, Debug, PartialEq)]
233pub struct SessionProjection<'a> {
234 pub entries: Vec<ProjectedEntry<'a>>,
235 pub messages: Vec<Value>,
236 pub thinking_level: Option<Value>,
238 pub model: Option<Value>,
240}
241
242#[derive(Clone, Debug, PartialEq)]
244pub struct SessionContext {
245 pub messages: Vec<Value>,
246 pub thinking_level: Option<Value>,
247 pub model: Option<Value>,
248}
249
250fn settings(path: &[&Value]) -> (Option<Value>, Option<Value>) {
251 let mut thinking = Some(Value::from("off"));
252 let mut model = None;
253 for entry in path {
254 match entry_type(entry) {
255 Some("thinking_level_change") => thinking = entry.get("thinkingLevel").cloned(),
256 Some("model_change") => {
257 model = Some(object(vec![
258 ("provider", entry.get("provider").cloned()),
259 ("modelId", entry.get("modelId").cloned()),
260 ]));
261 }
262 Some("message") if message_role(entry) == Some("assistant") => {
263 let message = &entry["message"];
264 model = Some(object(vec![
265 ("provider", message.get("provider").cloned()),
266 ("modelId", message.get("model").cloned()),
267 ]));
268 }
269 _ => {}
270 }
271 }
272 (thinking, model)
273}
274
275pub fn build_session_projection<'a>(entries: &'a [Value], leaf: Leaf<'_>) -> SessionProjection<'a> {
276 session_projection(&entries.iter().collect::<Vec<_>>(), leaf)
277}
278
279pub(crate) fn session_projection<'a>(entries: &[&'a Value], leaf: Leaf<'_>) -> SessionProjection<'a> {
280 let path = session_path(entries, leaf);
281 let (thinking_level, model) = settings(&path);
282 let context = context_entries_of_path(path);
283 let mut edits: HashMap<String, &Value> = HashMap::new();
284 for entry in &context {
285 if entry_type(entry) == Some("context_edit") {
286 edits.insert(id_key(entry.get("targetId")), entry);
287 }
288 }
289 let projected: Vec<ProjectedEntry> = context
290 .into_iter()
291 .enumerate()
292 .map(|(i, source)| ProjectedEntry {
293 source,
294 messages: if entry_type(source) == Some("compaction") && i > 0 {
297 Vec::new()
298 } else {
299 project_entry(source, edits.get(&id_key(source.get("id"))).copied())
300 },
301 })
302 .collect();
303 SessionProjection {
304 messages: projected.iter().flat_map(|e| e.messages.iter().cloned()).collect(),
305 entries: projected,
306 thinking_level,
307 model,
308 }
309}
310
311pub fn build_session_context(entries: &[Value], leaf: Leaf<'_>) -> SessionContext {
312 build_session_projection(entries, leaf).into()
313}
314
315impl From<SessionProjection<'_>> for SessionContext {
316 fn from(p: SessionProjection<'_>) -> Self {
317 SessionContext {
318 messages: p.messages,
319 thinking_level: p.thinking_level,
320 model: p.model,
321 }
322 }
323}
324
325fn content_text(content: Option<&Value>) -> String {
326 match content {
327 Some(Value::String(s)) => s.clone(),
328 Some(Value::Array(blocks)) => blocks
329 .iter()
330 .filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
331 .map(|b| js::join_string(b.get("text")))
332 .collect::<Vec<_>>()
333 .join("\n"),
334 _ => String::new(),
335 }
336}
337
338fn system_messages(messages: &[Value]) -> impl Iterator<Item = &Value> {
339 messages
340 .iter()
341 .filter(|m| m.get("role").and_then(Value::as_str) == Some("system"))
342}
343
344fn as_array(value: Option<&Value>) -> &[Value] {
345 value.and_then(Value::as_array).map_or(&[], Vec::as_slice)
346}
347
348pub fn current_tools(messages: &[Value]) -> Vec<Value> {
350 let mut tools: IndexMap<String, &Value> = IndexMap::new();
351 for message in system_messages(messages) {
352 for tool in as_array(message.get("toolsRemoved")) {
353 tools.shift_remove(&id_key(tool.get("name")));
354 }
355 for tool in as_array(message.get("toolsAdded")) {
356 tools.insert(id_key(tool.get("name")), tool);
357 }
358 }
359 tools.into_values().cloned().collect()
360}
361
362pub fn current_system_message(messages: &[Value]) -> Option<Value> {
365 let mut content = Vec::new();
366 let mut sections: IndexMap<String, Value> = IndexMap::new();
367 let mut timestamp: Option<Value> = None;
368 for message in system_messages(messages) {
369 if timestamp.is_none() && !js::nullish(message.get("timestamp")) {
370 timestamp = message.get("timestamp").cloned();
371 }
372 let text = content_text(message.get("content"));
373 if !text.is_empty() {
374 content.push(text);
375 }
376 if let Some(Value::Object(patch)) = message.get("sections") {
377 for (name, value) in jsrt::json::object_entries(patch) {
378 if value.is_null() {
379 sections.shift_remove(name);
380 } else {
381 sections.insert(name.clone(), value.clone());
382 }
383 }
384 }
385 }
386 let tools = current_tools(messages);
387 if timestamp.is_none() && tools.is_empty() {
388 return None;
389 }
390 Some(object(vec![
391 ("role", Some("system".into())),
392 ("content", Some(content.join("\n\n").into())),
393 (
394 "sections",
395 (!sections.is_empty()).then(|| Value::Object(sections.into_iter().collect())),
396 ),
397 ("toolsAdded", (!tools.is_empty()).then_some(Value::Array(tools))),
398 ("timestamp", Some(timestamp.unwrap_or_else(|| 0.into()))),
399 ]))
400}