Skip to main content

artifactize_core/agent/session/transcript/
fold.rs

1//! Fold stored session events and live delivery into stable transcript patches.
2
3use super::super::{Delivery, DeliveryKind, DeliveryState, Event, Kind};
4use super::{
5    BlockId, Patch,
6    candidate::{Candidate, candidate},
7    render::{
8        Activity, Group, State, Target, failure_reason, header, markdown, result_text, target,
9    },
10};
11use rig_core::message::{AssistantContent, Message, ToolCall, ToolResult, UserContent};
12use std::collections::{BTreeMap, BTreeSet};
13
14struct LiveBlock {
15    id: BlockId,
16    text: String,
17}
18
19/// The id a tool call and its result share on the wire, which links the two: built only
20/// from a recorded call identity.
21#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
22struct Correlation(String);
23
24impl Correlation {
25    fn of(id: &rig_core::message::CallId) -> Self {
26        Self(id.wire().into_owned())
27    }
28}
29
30#[derive(Default)]
31pub struct Transcript {
32    blocks: usize,
33    groups: BTreeMap<BlockId, Group>,
34    calls: BTreeMap<(Option<usize>, Correlation), (BlockId, usize)>,
35    active: Option<BlockId>,
36    expanded: BTreeSet<BlockId>,
37    assistant: Option<crate::types::Sha256Bytes>,
38    question: Option<(Option<usize>, crate::types::Sha256Bytes)>,
39    /// A JSON-looking assistant message is unchanged until its authoritative End arrives.
40    result_candidate: Option<(BlockId, Candidate)>,
41    deliveries: BTreeMap<
42        (
43            Option<usize>,
44            usize,
45            usize,
46            DeliveryKind,
47            crate::types::DeliveryBlock,
48        ),
49        LiveBlock,
50    >,
51    delivered_turns: BTreeSet<(Option<usize>, usize)>,
52    thinking: BTreeSet<BlockId>,
53}
54
55impl Transcript {
56    fn slot(&mut self) -> BlockId {
57        let id = BlockId(self.blocks);
58        self.blocks += 1;
59        id
60    }
61    fn prose(&mut self, text: &str, user: bool, patches: &mut Vec<Patch>) {
62        if text.trim().is_empty() {
63            return;
64        }
65        self.active = None;
66        let candidate = if !user { candidate(text) } else { None };
67        let text = markdown(text);
68        if !user {
69            self.assistant = Some(crate::types::Sha256Bytes::of(text.trim().as_bytes()));
70        }
71        let id = self.slot();
72        self.result_candidate = candidate.map(|value| (id, value));
73        patches.push(Patch {
74            id,
75            text: format!("{}{text}\n\n", if user { "You\n" } else { "" }),
76        });
77    }
78    fn group(&mut self) -> BlockId {
79        if let Some(id) = self.active {
80            return id;
81        }
82        let id = self.slot();
83        self.groups.insert(id, Group::default());
84        self.active = Some(id);
85        id
86    }
87    fn call(
88        &mut self,
89        send: Option<usize>,
90        call: &ToolCall,
91        call_target: Target<'_>,
92        dirty: &mut BTreeSet<BlockId>,
93    ) {
94        let key = (send, Correlation::of(&call.id));
95        // Repeated recorded IDs do not invent another execution or attach to a later call.
96        if self.calls.contains_key(&key) {
97            return;
98        }
99        let id = self.group();
100        let group = self.groups.get_mut(&id).expect("active group exists");
101        let index = group.activities.len();
102        group.activities.push(Activity {
103            name: header(call.function.name.as_str()),
104            target: target(call_target),
105            state: State::Running,
106            orphan: false,
107        });
108        self.calls.insert(key, (id, index));
109        dirty.insert(id);
110    }
111    fn result(
112        &mut self,
113        send: Option<usize>,
114        result: &ToolResult,
115        failed: Option<bool>,
116        dirty: &mut BTreeSet<BlockId>,
117    ) {
118        let key = (send, Correlation::of(&result.call));
119        let state = match failed {
120            Some(true) => State::Failed(failure_reason(result)),
121            Some(false) => State::Succeeded,
122            None => State::CompletedUnknown,
123        };
124        let (id, index) = match self.calls.get(&key).copied() {
125            Some(link) => link,
126            None => {
127                let id = self.group();
128                let group = self.groups.get_mut(&id).expect("active group exists");
129                let index = group.activities.len();
130                group.activities.push(Activity {
131                    name: header(result.name.as_str()),
132                    target: "target not recorded".into(),
133                    state: state.clone(),
134                    orphan: true,
135                });
136                self.calls.insert(key, (id, index));
137                (id, index)
138            }
139        };
140        self.groups
141            .get_mut(&id)
142            .expect("linked group exists")
143            .activities[index]
144            .state = state;
145        dirty.insert(id);
146    }
147    fn stopped(&mut self, dirty: &mut BTreeSet<BlockId>) {
148        for (id, group) in &mut self.groups {
149            for activity in &mut group.activities {
150                if activity.state == State::Running {
151                    activity.state = State::Unfinished;
152                    dirty.insert(*id);
153                }
154            }
155        }
156        self.active = None;
157    }
158    fn delivery(&mut self, send: Option<usize>, delivery: &Delivery) -> Vec<Patch> {
159        if delivery.block.is_attempt() && delivery.state == DeliveryState::Interrupted {
160            return self
161                .deliveries
162                .iter()
163                .filter(|((follow, turn, attempt, _, _), block)| {
164                    (*follow, *turn, *attempt) == (send, delivery.turn, delivery.attempt)
165                        && !block.text.is_empty()
166                })
167                .map(|((_, _, _, kind, _), block)| {
168                    let label = if *kind == DeliveryKind::Summary {
169                        "Thinking ยท partial"
170                    } else {
171                        "Partial response"
172                    };
173                    Patch {
174                        id: block.id,
175                        text: format!("{label} (interrupted)\n{}\n\n", block.text),
176                    }
177                })
178                .collect();
179        }
180        self.active = None;
181        let key = (
182            send,
183            delivery.turn,
184            delivery.attempt,
185            delivery.kind,
186            delivery.block.clone(),
187        );
188        let id = if let Some(block) = self.deliveries.get(&key) {
189            block.id
190        } else {
191            let id = self.slot();
192            self.deliveries.insert(
193                key.clone(),
194                LiveBlock {
195                    id,
196                    text: String::new(),
197                },
198            );
199            id
200        };
201        let block = self
202            .deliveries
203            .get_mut(&key)
204            .expect("delivery block exists");
205        match delivery.state {
206            DeliveryState::Delta => block.text.push_str(&delivery.text),
207            DeliveryState::Complete | DeliveryState::Interrupted => {
208                block.text = delivery.text.clone()
209            }
210        }
211        let text = block.text.clone();
212        if delivery.kind == DeliveryKind::Summary {
213            self.thinking.insert(id);
214        }
215        if delivery.kind == DeliveryKind::Text {
216            self.delivered_turns.insert((send, delivery.turn));
217        }
218        if delivery.kind == DeliveryKind::Text && delivery.state == DeliveryState::Complete {
219            self.result_candidate = candidate(&text).map(|value| (id, value));
220            self.assistant = Some(crate::types::Sha256Bytes::of(
221                markdown(&text).trim().as_bytes(),
222            ));
223        }
224        if delivery.state == DeliveryState::Complete {
225            self.deliveries
226                .get_mut(&key)
227                .expect("delivery exists")
228                .text
229                .clear();
230        }
231        vec![Patch {
232            id,
233            text: format!(
234                "{}{}{}\n\n",
235                if delivery.kind == DeliveryKind::Summary {
236                    "Thinking\n"
237                } else {
238                    ""
239                },
240                markdown(&text),
241                if delivery.state == DeliveryState::Interrupted {
242                    "\n[partial, interrupted]"
243                } else {
244                    ""
245                }
246            ),
247        }]
248    }
249    pub fn is_thinking(&self, id: BlockId) -> bool {
250        self.thinking.contains(&id)
251    }
252    pub fn apply(&mut self, event: &Event) -> Vec<Patch> {
253        let mut patches = Vec::new();
254        let mut dirty = BTreeSet::new();
255        match &event.kind {
256            Kind::Delivery(delivery) => return self.delivery(event.send, delivery),
257            Kind::Review(_) | Kind::Attempt(_) => {}
258            Kind::Send(send) => {
259                self.active = None;
260                self.assistant = None;
261                if let Some(text) = &send.text {
262                    self.prose(text, true, &mut patches);
263                    self.question = Some((
264                        event.send,
265                        crate::types::Sha256Bytes::of(text.trim().as_bytes()),
266                    ));
267                }
268            }
269            Kind::Message(message) => {
270                if let Some(question) = &message.question {
271                    let identity = (
272                        event.send,
273                        crate::types::Sha256Bytes::of(question.trim().as_bytes()),
274                    );
275                    if self.question.as_ref() != Some(&identity) {
276                        self.prose(question, true, &mut patches);
277                    }
278                    self.question = None;
279                } else {
280                    match message.message() {
281                        Message::System { .. } => {}
282                        Message::Assistant { content, .. } => {
283                            for (index, part) in content.iter().enumerate() {
284                                match part {
285                                    AssistantContent::Text(text) => {
286                                        if !self
287                                            .delivered_turns
288                                            .contains(&(event.send, message.turn))
289                                        {
290                                            self.prose(&text.text, false, &mut patches);
291                                        }
292                                    }
293                                    AssistantContent::ToolCall(call) => {
294                                        let target = message.builtin_target(index).map_or(
295                                            Target::Unrecorded,
296                                            |target| Target::Builtin {
297                                                path: target.path.as_deref(),
298                                                pattern: target.pattern.as_deref(),
299                                            },
300                                        );
301                                        self.call(event.send, call, target, &mut dirty);
302                                    }
303                                    AssistantContent::Reasoning(_) | AssistantContent::Image(_) => {
304                                    }
305                                }
306                            }
307                        }
308                        Message::User { content } => {
309                            let mut result_index = 0;
310                            for part in content {
311                                match part {
312                                    UserContent::Text(text) => {
313                                        self.prose(&text.text, true, &mut patches)
314                                    }
315                                    UserContent::ToolResult(result) => {
316                                        self.result(
317                                            event.send,
318                                            result,
319                                            message.is_error.get(result_index).copied(),
320                                            &mut dirty,
321                                        );
322                                        result_index += 1;
323                                    }
324                                    _ => {}
325                                }
326                            }
327                        }
328                    }
329                }
330            }
331            Kind::End(end) => {
332                self.stopped(&mut dirty);
333                if let Some(result) = end.result() {
334                    let text = result_text(result);
335                    if let Some((id, candidate)) = self.result_candidate.take()
336                        && candidate.matches(result)
337                    {
338                        patches.push(Patch {
339                            id,
340                            text: format!("{text}\n\n"),
341                        });
342                    } else {
343                        self.prose(&text, false, &mut patches);
344                    }
345                }
346                if let Some((code, error)) = end.failure() {
347                    self.prose(
348                        &format!(
349                            "Review failed: {}\n{error}",
350                            code.map(crate::agent::error::Code::as_str)
351                                .unwrap_or_default()
352                        ),
353                        false,
354                        &mut patches,
355                    );
356                }
357            }
358            Kind::Answer(answer) => {
359                if let Some(text) = answer.text() {
360                    let digest = crate::types::Sha256Bytes::of(markdown(text).trim().as_bytes());
361                    if self.assistant != Some(digest) {
362                        self.prose(text, false, &mut patches);
363                    }
364                }
365                if let Some((code, error)) = answer.failure() {
366                    self.stopped(&mut dirty);
367                    self.prose(
368                        &format!(
369                            "Follow-up failed: {}\n{error}",
370                            code.map(crate::agent::error::Code::as_str)
371                                .unwrap_or_default()
372                        ),
373                        false,
374                        &mut patches,
375                    );
376                }
377            }
378        }
379        for id in dirty {
380            patches.push(Patch {
381                id,
382                text: self.groups[&id].text(self.expanded.contains(&id)),
383            });
384        }
385        patches.sort_by_key(|patch| patch.id);
386        patches
387    }
388    pub fn expansion(&mut self, expanded: &BTreeSet<BlockId>) -> Vec<Patch> {
389        let changed = self
390            .expanded
391            .symmetric_difference(expanded)
392            .copied()
393            .collect::<Vec<_>>();
394        self.expanded = expanded.clone();
395        changed
396            .into_iter()
397            .filter_map(|id| {
398                self.groups.get(&id).map(|group| Patch {
399                    id,
400                    text: group.text(self.expanded.contains(&id)),
401                })
402            })
403            .collect()
404    }
405    pub fn is_group(&self, id: BlockId) -> bool {
406        self.groups.contains_key(&id)
407    }
408}