oino-session 1.0.0

Session format v3 for Oino: entries, migration, context projection, SessionManager
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
//! Context building and projection (`buildContextEntries`, `buildSessionProjection`,
//! `buildSessionContext`). Pure functions over an [`EntryIndex`].
//!
//! Leaf convention: `leaf = None` is the `null` leaf (empty path, e.g. after `resetLeaf`);
//! an id that is not in the index falls back to the last entry. Use
//! [`EntryIndex::last_id`] for the "default leaf".

use std::collections::{HashMap, HashSet};

use oino_ai::transcript::SystemState;
use oino_ai::{
    AgentMessage, AssistantContent, SystemMessage, TextContent, UserContent, UserContentField,
};
use serde::{Deserialize, Serialize};

use crate::entry::{ContextReplacement, EditableContent, EntryId, EntryKind, SessionEntry};
use crate::messages::{branch_summary_message, compaction_summary_message, custom_message};

/// Entries in file order plus an id index (latest entry wins on duplicate ids).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EntryIndex {
    entries: Vec<SessionEntry>,
    by_id: HashMap<EntryId, usize>,
}

impl EntryIndex {
    /// Indexes `entries` (file order).
    #[must_use]
    pub fn new(entries: Vec<SessionEntry>) -> Self {
        let by_id = entries
            .iter()
            .enumerate()
            .map(|(index, entry)| (entry.id.clone(), index))
            .collect();
        Self { entries, by_id }
    }

    /// Appends an entry.
    pub fn push(&mut self, entry: SessionEntry) {
        self.by_id.insert(entry.id.clone(), self.entries.len());
        self.entries.push(entry);
    }

    /// Entry by id.
    #[must_use]
    pub fn get(&self, id: &EntryId) -> Option<&SessionEntry> {
        self.by_id.get(id).map(|&index| &self.entries[index])
    }

    /// Whether `id` is present.
    #[must_use]
    pub fn contains(&self, id: &EntryId) -> bool {
        self.by_id.contains_key(id)
    }

    /// Whether the id text is present.
    #[must_use]
    pub fn contains_str(&self, id: &str) -> bool {
        self.by_id.contains_key(&EntryId::new(id))
    }

    /// All entries in file order.
    #[must_use]
    pub fn entries(&self) -> &[SessionEntry] {
        &self.entries
    }

    /// Consumes the index.
    #[must_use]
    pub fn into_entries(self) -> Vec<SessionEntry> {
        self.entries
    }

    /// Number of distinct ids.
    #[must_use]
    pub fn id_count(&self) -> usize {
        self.by_id.len()
    }

    /// Number of entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether there are no entries.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Id of the last entry in file order (the default leaf).
    #[must_use]
    pub fn last_id(&self) -> Option<&EntryId> {
        self.entries.last().map(|entry| &entry.id)
    }
}

impl FromIterator<SessionEntry> for EntryIndex {
    fn from_iter<I: IntoIterator<Item = SessionEntry>>(iter: I) -> Self {
        Self::new(iter.into_iter().collect())
    }
}

/// `{provider, modelId}` selection.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelRef {
    /// Provider id.
    pub provider: String,
    /// Model id.
    pub model_id: String,
}

/// One selected entry and the messages it contributes.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectedEntry {
    /// Selected raw entry.
    pub source_entry: SessionEntry,
    /// Model-visible messages after context edits.
    pub messages: Vec<AgentMessage>,
}

/// The session projection record.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionProjection {
    /// Selected entries with provenance.
    pub entries: Vec<ProjectedEntry>,
    /// Flattened messages.
    pub messages: Vec<AgentMessage>,
    /// Thinking level string (default `"off"`).
    pub thinking_level: String,
    /// Current model.
    pub model: Option<ModelRef>,
}

/// The session context record.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionContext {
    /// Messages for the agent.
    pub messages: Vec<AgentMessage>,
    /// Thinking level string (default `"off"`).
    pub thinking_level: String,
    /// Current model.
    pub model: Option<ModelRef>,
}

/// Latest explicit selections on a path (input to virtual-model aware resolution).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BranchSelection {
    /// Latest `model_change`.
    pub model: Option<ModelRef>,
    /// Id of that `model_change` entry.
    pub model_entry_id: Option<EntryId>,
    /// Latest `thinking_level_change`.
    pub thinking_level: Option<String>,
}

/// Root → leaf path. Stops at a missing parent (orphans become roots)
/// and at cycles.
#[must_use]
pub fn path_to<'a>(entries: &'a EntryIndex, leaf: Option<&EntryId>) -> Vec<&'a SessionEntry> {
    let Some(leaf) = leaf else {
        return Vec::new();
    };
    let Some(start) = entries.get(leaf).or_else(|| entries.entries.last()) else {
        return Vec::new();
    };
    walk_up(entries, start)
}

pub(crate) fn walk_up<'a>(
    entries: &'a EntryIndex,
    start: &'a SessionEntry,
) -> Vec<&'a SessionEntry> {
    let mut path = Vec::new();
    let mut seen = HashSet::new();
    let mut current = Some(start);
    while let Some(entry) = current {
        if !seen.insert(&entry.id) {
            break;
        }
        path.push(entry);
        current = entry
            .parent_id
            .as_ref()
            .and_then(|parent| entries.get(parent));
    }
    path.reverse();
    path
}

/// Latest `compaction` entry on `path`.
#[must_use]
pub fn latest_compaction<'a>(path: &[&'a SessionEntry]) -> Option<&'a SessionEntry> {
    path.iter()
        .rev()
        .find(|entry| matches!(entry.kind, EntryKind::Compaction(_)))
        .copied()
}

/// Latest explicit `model_change` and `thinking_level_change` on `path`.
#[must_use]
pub fn branch_selection(path: &[&SessionEntry]) -> BranchSelection {
    let mut selection = BranchSelection::default();
    for entry in path {
        match &entry.kind {
            EntryKind::ModelChange { provider, model_id } => {
                selection.model = Some(ModelRef {
                    provider: provider.clone(),
                    model_id: model_id.clone(),
                });
                selection.model_entry_id = Some(entry.id.clone());
            }
            EntryKind::ThinkingLevelChange { thinking_level } => {
                selection.thinking_level = Some(thinking_level.clone());
            }
            _ => {}
        }
    }
    selection
}

/// Thinking level (default `"off"`) and model from the full
/// path; assistant messages also update the model (the physical model that answered).
fn context_settings(path: &[&SessionEntry]) -> (String, Option<ModelRef>) {
    let mut thinking_level = "off".to_owned();
    let mut model = None;
    for entry in path {
        match &entry.kind {
            EntryKind::ThinkingLevelChange {
                thinking_level: level,
            } => {
                thinking_level.clone_from(level);
            }
            EntryKind::ModelChange { provider, model_id } => {
                model = Some(ModelRef {
                    provider: provider.clone(),
                    model_id: model_id.clone(),
                });
            }
            EntryKind::Message {
                message: AgentMessage::Assistant(assistant),
            } => {
                model = Some(ModelRef {
                    provider: assistant.provider.clone(),
                    model_id: assistant.model.clone(),
                });
            }
            _ => {}
        }
    }
    (thinking_level, model)
}

/// Honours the latest compaction on the path.
#[must_use]
pub fn build_context_entries(entries: &EntryIndex, leaf: Option<&EntryId>) -> Vec<SessionEntry> {
    select_context(&path_to(entries, leaf))
        .into_iter()
        .cloned()
        .collect()
}

fn select_context<'a>(path: &[&'a SessionEntry]) -> Vec<&'a SessionEntry> {
    let Some(compaction_index) = path
        .iter()
        .rposition(|entry| matches!(entry.kind, EntryKind::Compaction(_)))
    else {
        return path.to_vec();
    };
    let compaction = path[compaction_index];
    let EntryKind::Compaction(data) = &compaction.kind else {
        return path.to_vec();
    };
    let mut selected = vec![compaction];
    let mut found_first_kept = false;
    for entry in &path[..compaction_index] {
        if entry.id == data.first_kept_entry_id {
            found_first_kept = true;
        }
        if found_first_kept && !entry.is_system_message() {
            selected.push(entry);
        }
    }
    selected.extend_from_slice(&path[compaction_index + 1..]);
    selected
}

/// Converts entries to context messages. `compaction_system` is the checkpoint used when a
/// compaction entry has no `systemMessage` (projection passes `None`).
#[must_use]
pub fn entry_to_context_messages(
    entry: &SessionEntry,
    compaction_system: Option<&SystemMessage>,
) -> Vec<AgentMessage> {
    let timestamp = entry.timestamp.to_ms().unwrap_or(0);
    match &entry.kind {
        EntryKind::Message { message } => vec![message.clone()],
        EntryKind::CustomMessage {
            custom_type,
            content,
            display,
            details,
        } => vec![custom_message(
            custom_type,
            content.clone(),
            *display,
            details.clone(),
            timestamp,
        )],
        EntryKind::BranchSummary(summary) if !summary.summary.is_empty() => {
            vec![branch_summary_message(
                &summary.summary,
                Some(summary.from_id.as_str()),
                timestamp,
            )]
        }
        EntryKind::Compaction(compaction) => {
            let system = compaction.system_message.as_ref().or(compaction_system);
            system
                .cloned()
                .map(AgentMessage::System)
                .into_iter()
                .chain(std::iter::once(compaction_summary_message(
                    &compaction.summary,
                    compaction.tokens_before,
                    timestamp,
                )))
                .collect()
        }
        _ => Vec::new(),
    }
}

fn user_blocks(content: &EditableContent) -> UserContentField {
    match content {
        EditableContent::Text(text) => UserContentField::Text(text.clone()),
        EditableContent::User(blocks) => UserContentField::Blocks(blocks.clone()),
        EditableContent::Assistant(blocks) => UserContentField::Blocks(
            blocks
                .iter()
                .filter_map(|block| match block {
                    AssistantContent::Text(text) => Some(UserContent::Text(text.clone())),
                    _ => None,
                })
                .collect(),
        ),
    }
}

fn result_blocks(content: &EditableContent) -> Vec<UserContent> {
    match user_blocks(content) {
        UserContentField::Text(text) => vec![UserContent::Text(TextContent::new(text))],
        UserContentField::Blocks(blocks) => blocks,
    }
}

fn assistant_blocks(content: &EditableContent) -> Vec<AssistantContent> {
    match content {
        EditableContent::Text(text) => vec![AssistantContent::Text(TextContent::new(text.clone()))],
        EditableContent::Assistant(blocks) => blocks.clone(),
        EditableContent::User(blocks) => blocks
            .iter()
            .filter_map(|block| match block {
                UserContent::Text(text) => Some(AssistantContent::Text(text.clone())),
                UserContent::Image(_) => None,
            })
            .collect(),
    }
}

/// Applies a replacement to one message, keeping role and metadata.
/// Blocks that the target role cannot hold (images on assistants, thinking on users) are
/// dropped.
fn replace_content(message: AgentMessage, replacement: &ContextReplacement) -> AgentMessage {
    let content = &replacement.content;
    match message {
        AgentMessage::User(mut user) => {
            user.content = user_blocks(content);
            AgentMessage::User(user)
        }
        AgentMessage::Custom(mut custom) => {
            custom.content = user_blocks(content);
            AgentMessage::Custom(custom)
        }
        AgentMessage::Assistant(mut assistant) => {
            assistant.content = assistant_blocks(content);
            AgentMessage::Assistant(assistant)
        }
        AgentMessage::ToolResult(mut result) => {
            result.content = result_blocks(content);
            AgentMessage::ToolResult(result)
        }
        other => other,
    }
}

fn project_entry(
    entry: &SessionEntry,
    edit: Option<&Option<ContextReplacement>>,
) -> Vec<AgentMessage> {
    let messages = entry_to_context_messages(entry, None);
    match edit {
        None => messages,
        Some(None) => Vec::new(),
        Some(Some(replacement)) => messages
            .into_iter()
            .map(|message| replace_content(message, replacement))
            .collect(),
    }
}

/// Context selection, latest context edit per target (among the
/// selected entries), entry → messages.
#[must_use]
pub fn build_session_projection(entries: &EntryIndex, leaf: Option<&EntryId>) -> SessionProjection {
    let path = path_to(entries, leaf);
    let (thinking_level, model) = context_settings(&path);
    let selected = select_context(&path);
    let mut edits: HashMap<&EntryId, &Option<ContextReplacement>> = HashMap::new();
    for entry in &selected {
        if let EntryKind::ContextEdit {
            target_id,
            replacement,
        } = &entry.kind
        {
            edits.insert(target_id, replacement);
        }
    }
    let projected: Vec<ProjectedEntry> = selected
        .iter()
        .enumerate()
        .map(|(index, entry)| ProjectedEntry {
            source_entry: (*entry).clone(),
            messages: if index > 0 && matches!(entry.kind, EntryKind::Compaction(_)) {
                Vec::new()
            } else {
                project_entry(entry, edits.get(&entry.id).copied())
            },
        })
        .collect();
    let messages = projected
        .iter()
        .flat_map(|entry| entry.messages.iter().cloned())
        .collect();
    SessionProjection {
        entries: projected,
        messages,
        thinking_level,
        model,
    }
}

/// B u i l d   S e s s i o n   C o n t e x t.
#[must_use]
pub fn build_session_context(entries: &EntryIndex, leaf: Option<&EntryId>) -> SessionContext {
    let SessionProjection {
        messages,
        thinking_level,
        model,
        ..
    } = build_session_projection(entries, leaf);
    SessionContext {
        messages,
        thinking_level,
        model,
    }
}

/// Folded system checkpoint of a projection.
#[must_use]
pub fn current_system_message(messages: &[AgentMessage]) -> Option<SystemMessage> {
    SystemState::fold(messages.iter().filter_map(AgentMessage::as_system)).into_message()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn index(lines: &serde_json::Value) -> EntryIndex {
        serde_json::from_value::<Vec<SessionEntry>>(lines.clone())
            .unwrap()
            .into_iter()
            .collect()
    }

    fn user(id: &str, parent: Option<&str>, text: &str) -> serde_json::Value {
        json!({"type":"message","id":id,"parentId":parent,"timestamp":"2024-01-01T00:00:00.000Z",
            "message":{"role":"user","content":text,"timestamp":1}})
    }

    fn texts(context: &SessionContext) -> Vec<String> {
        context
            .messages
            .iter()
            .map(|m| match m {
                AgentMessage::User(u) => u.content.text(""),
                other => other.role().to_owned(),
            })
            .collect()
    }

    #[test]
    fn compaction_keeps_range_and_drops_system() {
        let entries = index(&json!([
            {"type":"message","id":"s","parentId":null,"timestamp":"2024-01-01T00:00:00.000Z",
             "message":{"role":"system","content":"sys","timestamp":0}},
            user("a", Some("s"), "a"),
            user("b", Some("a"), "b"),
            {"type":"message","id":"s2","parentId":"b","timestamp":"2024-01-01T00:00:00.000Z",
             "message":{"role":"system","content":"patch","timestamp":0}},
            {"type":"compaction","id":"c","parentId":"s2","timestamp":"2024-01-01T00:00:01.000Z",
             "summary":"sum","firstKeptEntryId":"b","tokensBefore":5,
             "systemMessage":{"role":"system","content":"sys\n\npatch","timestamp":1000}},
            user("d", Some("c"), "d"),
        ]));
        let context = build_session_context(&entries, entries.last_id());
        assert_eq!(texts(&context), ["system", "compactionSummary", "b", "d"]);
        let selected: Vec<_> = build_context_entries(&entries, Some(&"d".into()))
            .into_iter()
            .map(|e| e.id.to_string())
            .collect();
        assert_eq!(selected, ["c", "b", "d"]);
        assert_eq!(build_session_context(&entries, None).messages, []);
    }

    #[test]
    fn context_edits_are_branch_relative() {
        let entries = index(&json!([
            user("a", None, "a"),
            {"type":"context_edit","id":"e","parentId":"a","timestamp":"2024-01-01T00:00:00.000Z","targetId":"a",
             "replacement":{"content":"edited"}},
            {"type":"context_edit","id":"f","parentId":"e","timestamp":"2024-01-01T00:00:00.000Z","targetId":"a","replacement":null},
        ]));
        assert_eq!(
            texts(&build_session_context(&entries, Some(&"e".into()))),
            ["edited"]
        );
        assert_eq!(
            build_session_context(&entries, Some(&"f".into())).messages,
            []
        );
        assert_eq!(
            texts(&build_session_context(&entries, Some(&"a".into()))),
            ["a"]
        );
    }

    #[test]
    fn settings_come_from_full_path() {
        let entries = index(&json!([
            {"type":"model_change","id":"m","parentId":null,"timestamp":"t","provider":"p","modelId":"x"},
            {"type":"thinking_level_change","id":"t","parentId":"m","timestamp":"t","thinkingLevel":"high"},
        ]));
        let context = build_session_context(&entries, entries.last_id());
        assert_eq!(context.thinking_level, "high");
        assert_eq!(context.model.map(|m| m.model_id), Some("x".to_owned()));
        let path = path_to(&entries, entries.last_id());
        assert_eq!(branch_selection(&path).model_entry_id, Some("m".into()));
    }

    #[test]
    fn cycles_terminate() {
        let entries = index(&json!([
            user("a", Some("b"), "a"),
            user("b", Some("a"), "b")
        ]));
        assert_eq!(path_to(&entries, Some(&"b".into())).len(), 2);
    }
}