artifactize-core 0.25.2

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
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
//! Fold stored session events and live delivery into stable transcript patches.

use super::super::{Delivery, DeliveryKind, DeliveryState, Event, Kind};
use super::{
    BlockId, Patch,
    candidate::{Candidate, candidate},
    render::{
        Activity, Group, State, Target, failure_reason, header, markdown, result_text, target,
    },
};
use rig_core::message::{AssistantContent, Message, ToolCall, ToolResult, UserContent};
use std::collections::{BTreeMap, BTreeSet};

struct LiveBlock {
    id: BlockId,
    text: String,
}

/// The id a tool call and its result share on the wire, which links the two: built only
/// from a recorded call identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Correlation(String);

impl Correlation {
    fn of(id: &rig_core::message::CallId) -> Self {
        Self(id.wire().into_owned())
    }
}

#[derive(Default)]
pub struct Transcript {
    blocks: usize,
    groups: BTreeMap<BlockId, Group>,
    calls: BTreeMap<(Option<usize>, Correlation), (BlockId, usize)>,
    active: Option<BlockId>,
    expanded: BTreeSet<BlockId>,
    assistant: Option<crate::types::Sha256Bytes>,
    question: Option<(Option<usize>, crate::types::Sha256Bytes)>,
    /// A JSON-looking assistant message is unchanged until its authoritative End arrives.
    result_candidate: Option<(BlockId, Candidate)>,
    deliveries: BTreeMap<
        (
            Option<usize>,
            usize,
            usize,
            DeliveryKind,
            crate::types::DeliveryBlock,
        ),
        LiveBlock,
    >,
    delivered_turns: BTreeSet<(Option<usize>, usize)>,
    thinking: BTreeSet<BlockId>,
}

impl Transcript {
    fn slot(&mut self) -> BlockId {
        let id = BlockId(self.blocks);
        self.blocks += 1;
        id
    }
    fn prose(&mut self, text: &str, user: bool, patches: &mut Vec<Patch>) {
        if text.trim().is_empty() {
            return;
        }
        self.active = None;
        let candidate = if !user { candidate(text) } else { None };
        let text = markdown(text);
        if !user {
            self.assistant = Some(crate::types::Sha256Bytes::of(text.trim().as_bytes()));
        }
        let id = self.slot();
        self.result_candidate = candidate.map(|value| (id, value));
        patches.push(Patch {
            id,
            text: format!("{}{text}\n\n", if user { "You\n" } else { "" }),
        });
    }
    fn group(&mut self) -> BlockId {
        if let Some(id) = self.active {
            return id;
        }
        let id = self.slot();
        self.groups.insert(id, Group::default());
        self.active = Some(id);
        id
    }
    fn call(
        &mut self,
        send: Option<usize>,
        call: &ToolCall,
        call_target: Target<'_>,
        dirty: &mut BTreeSet<BlockId>,
    ) {
        let key = (send, Correlation::of(&call.id));
        // Repeated recorded IDs do not invent another execution or attach to a later call.
        if self.calls.contains_key(&key) {
            return;
        }
        let id = self.group();
        let group = self.groups.get_mut(&id).expect("active group exists");
        let index = group.activities.len();
        group.activities.push(Activity {
            name: header(call.function.name.as_str()),
            target: target(call_target),
            state: State::Running,
            orphan: false,
        });
        self.calls.insert(key, (id, index));
        dirty.insert(id);
    }
    fn result(
        &mut self,
        send: Option<usize>,
        result: &ToolResult,
        failed: Option<bool>,
        dirty: &mut BTreeSet<BlockId>,
    ) {
        let key = (send, Correlation::of(&result.call));
        let state = match failed {
            Some(true) => State::Failed(failure_reason(result)),
            Some(false) => State::Succeeded,
            None => State::CompletedUnknown,
        };
        let (id, index) = match self.calls.get(&key).copied() {
            Some(link) => link,
            None => {
                let id = self.group();
                let group = self.groups.get_mut(&id).expect("active group exists");
                let index = group.activities.len();
                group.activities.push(Activity {
                    name: header(result.name.as_str()),
                    target: "target not recorded".into(),
                    state: state.clone(),
                    orphan: true,
                });
                self.calls.insert(key, (id, index));
                (id, index)
            }
        };
        self.groups
            .get_mut(&id)
            .expect("linked group exists")
            .activities[index]
            .state = state;
        dirty.insert(id);
    }
    fn stopped(&mut self, dirty: &mut BTreeSet<BlockId>) {
        for (id, group) in &mut self.groups {
            for activity in &mut group.activities {
                if activity.state == State::Running {
                    activity.state = State::Unfinished;
                    dirty.insert(*id);
                }
            }
        }
        self.active = None;
    }
    fn delivery(&mut self, send: Option<usize>, delivery: &Delivery) -> Vec<Patch> {
        if delivery.block.is_attempt() && delivery.state == DeliveryState::Interrupted {
            return self
                .deliveries
                .iter()
                .filter(|((follow, turn, attempt, _, _), block)| {
                    (*follow, *turn, *attempt) == (send, delivery.turn, delivery.attempt)
                        && !block.text.is_empty()
                })
                .map(|((_, _, _, kind, _), block)| {
                    let label = if *kind == DeliveryKind::Summary {
                        "Thinking · partial"
                    } else {
                        "Partial response"
                    };
                    Patch {
                        id: block.id,
                        text: format!("{label} (interrupted)\n{}\n\n", block.text),
                    }
                })
                .collect();
        }
        self.active = None;
        let key = (
            send,
            delivery.turn,
            delivery.attempt,
            delivery.kind,
            delivery.block.clone(),
        );
        let id = if let Some(block) = self.deliveries.get(&key) {
            block.id
        } else {
            let id = self.slot();
            self.deliveries.insert(
                key.clone(),
                LiveBlock {
                    id,
                    text: String::new(),
                },
            );
            id
        };
        let block = self
            .deliveries
            .get_mut(&key)
            .expect("delivery block exists");
        match delivery.state {
            DeliveryState::Delta => block.text.push_str(&delivery.text),
            DeliveryState::Complete | DeliveryState::Interrupted => {
                block.text = delivery.text.clone()
            }
        }
        let text = block.text.clone();
        if delivery.kind == DeliveryKind::Summary {
            self.thinking.insert(id);
        }
        if delivery.kind == DeliveryKind::Text {
            self.delivered_turns.insert((send, delivery.turn));
        }
        if delivery.kind == DeliveryKind::Text && delivery.state == DeliveryState::Complete {
            self.result_candidate = candidate(&text).map(|value| (id, value));
            self.assistant = Some(crate::types::Sha256Bytes::of(
                markdown(&text).trim().as_bytes(),
            ));
        }
        if delivery.state == DeliveryState::Complete {
            self.deliveries
                .get_mut(&key)
                .expect("delivery exists")
                .text
                .clear();
        }
        vec![Patch {
            id,
            text: format!(
                "{}{}{}\n\n",
                if delivery.kind == DeliveryKind::Summary {
                    "Thinking\n"
                } else {
                    ""
                },
                markdown(&text),
                if delivery.state == DeliveryState::Interrupted {
                    "\n[partial, interrupted]"
                } else {
                    ""
                }
            ),
        }]
    }
    pub fn is_thinking(&self, id: BlockId) -> bool {
        self.thinking.contains(&id)
    }
    pub fn apply(&mut self, event: &Event) -> Vec<Patch> {
        let mut patches = Vec::new();
        let mut dirty = BTreeSet::new();
        match &event.kind {
            Kind::Delivery(delivery) => return self.delivery(event.send, delivery),
            Kind::Review(_)
            | Kind::Attempt(_)
            | Kind::RunReference { .. }
            | Kind::ToolOutcome(_) => {}
            Kind::Send(send) => {
                self.active = None;
                self.assistant = None;
                if let Some(text) = &send.text {
                    self.prose(text, true, &mut patches);
                    self.question = Some((
                        event.send,
                        crate::types::Sha256Bytes::of(text.trim().as_bytes()),
                    ));
                }
            }
            Kind::Message(message) => {
                if let Some(question) = &message.question {
                    let identity = (
                        event.send,
                        crate::types::Sha256Bytes::of(question.trim().as_bytes()),
                    );
                    if self.question.as_ref() != Some(&identity) {
                        self.prose(question, true, &mut patches);
                    }
                    self.question = None;
                } else {
                    match message.message() {
                        Message::System { .. } => {}
                        Message::Assistant { content, .. } => {
                            for (index, part) in content.iter().enumerate() {
                                match part {
                                    AssistantContent::Text(text) => {
                                        if !self
                                            .delivered_turns
                                            .contains(&(event.send, message.turn))
                                        {
                                            self.prose(&text.text, false, &mut patches);
                                        }
                                    }
                                    AssistantContent::ToolCall(call) => {
                                        let target = message.builtin_target(index).map_or(
                                            Target::Unrecorded,
                                            |target| Target::Builtin {
                                                path: target.path.as_deref(),
                                                pattern: target.pattern.as_deref(),
                                            },
                                        );
                                        self.call(event.send, call, target, &mut dirty);
                                    }
                                    AssistantContent::Reasoning(_) | AssistantContent::Image(_) => {
                                    }
                                }
                            }
                        }
                        Message::User { content } => {
                            let mut result_index = 0;
                            for part in content {
                                match part {
                                    UserContent::Text(text) => {
                                        self.prose(&text.text, true, &mut patches)
                                    }
                                    UserContent::ToolResult(result) => {
                                        self.result(
                                            event.send,
                                            result,
                                            message.is_error.get(result_index).copied(),
                                            &mut dirty,
                                        );
                                        result_index += 1;
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                }
            }
            Kind::End(end) => {
                self.stopped(&mut dirty);
                if let Some(result) = end.result() {
                    let text = result_text(result);
                    if let Some((id, candidate)) = self.result_candidate.take()
                        && candidate.matches(result)
                    {
                        patches.push(Patch {
                            id,
                            text: format!("{text}\n\n"),
                        });
                    } else {
                        self.prose(&text, false, &mut patches);
                    }
                }
                if let Some((code, error)) = end.failure() {
                    self.prose(
                        &format!(
                            "Review failed: {}\n{error}",
                            code.map(crate::agent::error::Code::as_str)
                                .unwrap_or_default()
                        ),
                        false,
                        &mut patches,
                    );
                }
            }
            Kind::Answer(answer) => {
                if let Some(text) = answer.text() {
                    let digest = crate::types::Sha256Bytes::of(markdown(text).trim().as_bytes());
                    if self.assistant != Some(digest) {
                        self.prose(text, false, &mut patches);
                    }
                }
                if let Some((code, error)) = answer.failure() {
                    self.stopped(&mut dirty);
                    self.prose(
                        &format!(
                            "Follow-up failed: {}\n{error}",
                            code.map(crate::agent::error::Code::as_str)
                                .unwrap_or_default()
                        ),
                        false,
                        &mut patches,
                    );
                }
            }
        }
        for id in dirty {
            patches.push(Patch {
                id,
                text: self.groups[&id].text(self.expanded.contains(&id)),
            });
        }
        patches.sort_by_key(|patch| patch.id);
        patches
    }
    pub fn expansion(&mut self, expanded: &BTreeSet<BlockId>) -> Vec<Patch> {
        let changed = self
            .expanded
            .symmetric_difference(expanded)
            .copied()
            .collect::<Vec<_>>();
        self.expanded = expanded.clone();
        changed
            .into_iter()
            .filter_map(|id| {
                self.groups.get(&id).map(|group| Patch {
                    id,
                    text: group.text(self.expanded.contains(&id)),
                })
            })
            .collect()
    }
    pub fn is_group(&self, id: BlockId) -> bool {
        self.groups.contains_key(&id)
    }
}