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(_)
258            | Kind::Attempt(_)
259            | Kind::RunReference { .. }
260            | Kind::ToolOutcome(_)
261            | Kind::AcpToolCall(_)
262            | Kind::AcpToolUpdate(_)
263            | Kind::AcpPlan(_)
264            | Kind::AcpPermission(_)
265            | Kind::Handoff(_)
266            | Kind::Notice { .. } => {}
267            Kind::Send(send) => {
268                self.active = None;
269                self.assistant = None;
270                if let Some(text) = &send.text {
271                    self.prose(text, true, &mut patches);
272                    self.question = Some((
273                        event.send,
274                        crate::types::Sha256Bytes::of(text.trim().as_bytes()),
275                    ));
276                }
277            }
278            Kind::Message(message) => {
279                if let Some(question) = &message.question {
280                    let identity = (
281                        event.send,
282                        crate::types::Sha256Bytes::of(question.trim().as_bytes()),
283                    );
284                    if self.question.as_ref() != Some(&identity) {
285                        self.prose(question, true, &mut patches);
286                    }
287                    self.question = None;
288                } else {
289                    match message.message() {
290                        Message::System { .. } => {}
291                        Message::Assistant { content, .. } => {
292                            for (index, part) in content.iter().enumerate() {
293                                match part {
294                                    AssistantContent::Text(text) => {
295                                        if !self
296                                            .delivered_turns
297                                            .contains(&(event.send, message.turn))
298                                        {
299                                            self.prose(&text.text, false, &mut patches);
300                                        }
301                                    }
302                                    AssistantContent::ToolCall(call) => {
303                                        let target = message.builtin_target(index).map_or(
304                                            Target::Unrecorded,
305                                            |target| Target::Builtin {
306                                                path: target.path.as_deref(),
307                                                pattern: target.pattern.as_deref(),
308                                            },
309                                        );
310                                        self.call(event.send, call, target, &mut dirty);
311                                    }
312                                    AssistantContent::Reasoning(_) | AssistantContent::Image(_) => {
313                                    }
314                                }
315                            }
316                        }
317                        Message::User { content } => {
318                            let mut result_index = 0;
319                            for part in content {
320                                match part {
321                                    UserContent::Text(text) => {
322                                        self.prose(&text.text, true, &mut patches)
323                                    }
324                                    UserContent::ToolResult(result) => {
325                                        self.result(
326                                            event.send,
327                                            result,
328                                            message.is_error.get(result_index).copied(),
329                                            &mut dirty,
330                                        );
331                                        result_index += 1;
332                                    }
333                                    _ => {}
334                                }
335                            }
336                        }
337                    }
338                }
339            }
340            Kind::End(end) => {
341                self.stopped(&mut dirty);
342                if let Some(result) = end.result() {
343                    let text = result_text(result);
344                    if let Some((id, candidate)) = self.result_candidate.take()
345                        && candidate.matches(result)
346                    {
347                        patches.push(Patch {
348                            id,
349                            text: format!("{text}\n\n"),
350                        });
351                    } else {
352                        self.prose(&text, false, &mut patches);
353                    }
354                }
355                if let Some((code, error)) = end.failure() {
356                    self.prose(
357                        &format!(
358                            "Review failed: {}\n{error}",
359                            code.map(crate::agent::error::Code::as_str)
360                                .unwrap_or_default()
361                        ),
362                        false,
363                        &mut patches,
364                    );
365                }
366            }
367            Kind::Answer(answer) => {
368                if let Some(text) = answer.text() {
369                    let digest = crate::types::Sha256Bytes::of(markdown(text).trim().as_bytes());
370                    if self.assistant != Some(digest) {
371                        self.prose(text, false, &mut patches);
372                    }
373                }
374                if let Some((code, error)) = answer.failure() {
375                    self.stopped(&mut dirty);
376                    self.prose(
377                        &format!(
378                            "Follow-up failed: {}\n{error}",
379                            code.map(crate::agent::error::Code::as_str)
380                                .unwrap_or_default()
381                        ),
382                        false,
383                        &mut patches,
384                    );
385                }
386            }
387        }
388        for id in dirty {
389            patches.push(Patch {
390                id,
391                text: self.groups[&id].text(self.expanded.contains(&id)),
392            });
393        }
394        patches.sort_by_key(|patch| patch.id);
395        patches
396    }
397    pub fn expansion(&mut self, expanded: &BTreeSet<BlockId>) -> Vec<Patch> {
398        let changed = self
399            .expanded
400            .symmetric_difference(expanded)
401            .copied()
402            .collect::<Vec<_>>();
403        self.expanded = expanded.clone();
404        changed
405            .into_iter()
406            .filter_map(|id| {
407                self.groups.get(&id).map(|group| Patch {
408                    id,
409                    text: group.text(self.expanded.contains(&id)),
410                })
411            })
412            .collect()
413    }
414    pub fn is_group(&self, id: BlockId) -> bool {
415        self.groups.contains_key(&id)
416    }
417}