Skip to main content

rig_core/conversation/
pairing.rs

1//! The rules pairing a conversation's tool calls with their results:
2//! which result answers which call ([`answered_by`]), validation and repair
3//! of a message list, the same repair over entries that keeps their ids
4//! ([`normalize`]), the calls a cut-short conversation still owes, and
5//! where a window of it may start.
6//!
7//! ```
8//! use rig_core::{conversation::pairing, message::Message};
9//!
10//! pairing::validate(&[Message::user("Hello"), Message::assistant("Hi")])?;
11//! # Ok::<(), pairing::PairingError>(())
12//! ```
13
14use std::borrow::Borrow;
15use std::collections::HashSet;
16use std::sync::Arc;
17
18use serde::{Deserialize, Serialize};
19
20use super::{Author, Entry, MessageId, ResultFacts};
21use crate::message::{
22    AssistantMessage, CallId, Message, Origin, StopReason, ToolCall, ToolName, UserContent,
23};
24use crate::tool::feedback::tool_result_message;
25
26/// Why a history is not a canonical conversation, or what [`pair`] repaired.
27/// See [`validate`].
28#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
29pub enum PairingError {
30    /// Two assistant messages adjacent in the input that could merge (index
31    /// of the second). Two that cannot may stand side by side: a different
32    /// origin, or a different outcome.
33    #[error("consecutive assistant messages at index {index}")]
34    ConsecutiveAssistant {
35        /// Index of the offending (second) assistant message.
36        index: usize,
37    },
38    /// An assistant tool call nothing answered before the next assistant
39    /// message, a user message with more than results, or the end.
40    #[error("tool call `{call_id}` at index {index} has no result in the following message")]
41    UnansweredToolCall {
42        /// Index of the assistant message carrying the call.
43        index: usize,
44        /// The unanswered call id.
45        call_id: CallId,
46    },
47    /// A tool result that answers no call still waiting for one.
48    #[error(
49        "tool result `{call_id}` at index {index} answers no call from the preceding assistant message"
50    )]
51    OrphanToolResult {
52        /// Index of the user message carrying the result.
53        index: usize,
54        /// The orphan result's call id.
55        call_id: CallId,
56    },
57}
58
59/// A tool call's place: its reply's entry and its index among the reply's
60/// tool calls. Unlike a provider's call id, no two calls of one
61/// conversation share one; across agents, pair it with the agent.
62///
63/// ```
64/// use rig_core::conversation::{CallRef, Conversation};
65/// use rig_core::message::{AssistantContent, AssistantMessage, Message, ToolCall, ToolFunction, ToolName};
66///
67/// let look = ToolFunction::new(ToolName::new("look")?, serde_json::json!({}));
68/// let call = AssistantContent::ToolCall(ToolCall::from_wire("c1", look));
69/// let mut conversation = Conversation::new();
70/// let reply = conversation.push(Message::Assistant(AssistantMessage::new(vec![call.clone(), call])));
71/// let second = CallRef { reply, index: 1 };
72/// assert_eq!(second.wire(), format!("{reply}/1"));
73/// let pending = conversation.pending_calls();
74/// assert_eq!(pending.get(1).map(|(at, _)| *at), Some(second));
75/// # Ok::<(), Box<dyn std::error::Error>>(())
76/// ```
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
78pub struct CallRef {
79    pub reply: MessageId,
80    pub index: u32,
81}
82
83impl CallRef {
84    /// Its text form, such as `m4/1`.
85    pub fn wire(&self) -> String {
86        format!("{}/{}", self.reply, self.index)
87    }
88
89    /// The tool calls of `message`, the entry `reply`, with their places.
90    pub fn calls(
91        reply: MessageId,
92        message: &AssistantMessage,
93    ) -> impl Iterator<Item = (Self, &ToolCall)> {
94        (0..).zip(message.tool_calls()).map(move |(index, call)| {
95            let at = Self { reply, index };
96            (at, call)
97        })
98    }
99}
100
101/// The answer of each of `calls`, in call order: the n-th answer with an id
102/// answers the n-th call with that id, as [`pair`] pairs them. `None` for a
103/// call nothing answers; an answer no call waits for is dropped.
104///
105/// ```
106/// use rig_core::conversation::pairing::answered_by;
107/// use rig_core::message::CallId;
108///
109/// let id = CallId::from_wire("c1");
110/// let answers = [(&id, "first"), (&id, "second")];
111/// assert_eq!(answered_by([&id, &id, &id], answers), [Some("first"), Some("second"), None]);
112/// ```
113pub fn answered_by<'c, 'a, T>(
114    calls: impl IntoIterator<Item = &'c CallId>,
115    answers: impl IntoIterator<Item = (&'a CallId, T)>,
116) -> Vec<Option<T>> {
117    let mut waiting: Vec<(usize, &CallId)> = calls.into_iter().enumerate().collect();
118    let mut found: Vec<Option<T>> = waiting.iter().map(|_| None).collect();
119    for (id, answer) in answers {
120        if let Some((at, _)) = take(&mut waiting, id, |(_, id)| id)
121            && let Some(slot) = found.get_mut(at)
122        {
123            *slot = Some(answer);
124        }
125    }
126    found
127}
128
129/// The item of each of `calls`, in call order: the one kept at its place
130/// for its id, else one of the rest, kept elsewhere or without a place,
131/// that [`answered_by`] pairs with it. An edit that deletes a call moves
132/// the next into its place, so a place holds its item only for its call.
133pub fn placed<T: Copy>(
134    calls: &[(CallRef, &CallId)],
135    items: &[(&CallId, Option<CallRef>, T)],
136) -> Vec<Option<T>> {
137    let kept: Vec<Option<usize>> = calls
138        .iter()
139        .map(|(place, call)| {
140            let here =
141                |(id, at, _): &(&CallId, Option<CallRef>, T)| *at == Some(*place) && id == call;
142            items.iter().position(here)
143        })
144        .collect();
145    let rest = (0..)
146        .zip(items)
147        .filter(|(at, _)| !kept.contains(&Some(*at)));
148    let waiting = calls.iter().zip(&kept).filter(|(_, kept)| kept.is_none());
149    let mut paired = answered_by(
150        waiting.map(|((_, id), _)| *id),
151        rest.map(|(_, &(id, _, item))| (id, item)),
152    )
153    .into_iter();
154    kept.into_iter()
155        .map(|kept| match kept {
156            Some(at) => items.get(at).map(|&(.., item)| item),
157            None => paired.next().flatten(),
158        })
159        .collect()
160}
161
162/// Rejects what [`pair`] would repair: consecutive assistant messages, a
163/// call nothing answered, and a result no waiting call asked for.
164///
165/// Call ids are matched as a multiset in call order, so a turn that repeats
166/// an id is answered by one result per occurrence. A turn that ended in an
167/// error or was aborted owes no results. A turn's results may be split over
168/// adjacent user messages or around system messages, which reset the
169/// consecutive-assistant check but keep calls waiting.
170pub fn validate(messages: &[impl Borrow<Message>]) -> Result<(), PairingError> {
171    repair(
172        messages
173            .iter()
174            .map(|message| message.borrow().clone())
175            .collect(),
176    )
177    .repairs
178    .into_iter()
179    .next()
180    .map_or(Ok(()), Err)
181}
182
183/// The text of the result rig sends for a tool call nothing answered.
184pub const NO_RESULT_PROVIDED: &str = "No result provided";
185
186/// How [`pair`] reads a history.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub struct Pairing {
189    /// Results before the first assistant turn answer calls the provider
190    /// holds for a stored conversation, so they are kept, one per id.
191    pub stored: bool,
192    /// Every unanswered call gets a [`NO_RESULT_PROVIDED`] result. Without
193    /// it, as for a request that sends calls as text, none is made up.
194    pub answers: bool,
195}
196
197impl Pairing {
198    /// A history read on its own: nothing is stored, every call is answered.
199    pub const fn canonical() -> Self {
200        Self {
201            stored: false,
202            answers: true,
203        }
204    }
205}
206
207/// A history with its calls and results paired.
208#[derive(Debug, Clone, PartialEq)]
209pub struct Paired {
210    /// The paired history.
211    pub messages: Vec<Message>,
212    /// What was repaired, in order, by input index; empty for a canonical one.
213    pub repairs: Vec<PairingError>,
214}
215
216/// `messages` read as a canonical conversation and repaired into one
217/// [`validate`] accepts, losing no turn: the lenient load of a
218/// history from outside the protocol, such as a stored transcript, and the
219/// close of a run's history at cancellation. Beyond [`pair`], an assistant
220/// turn left directly after another is merged into it when the two can
221/// share an origin and ended the same way, and an empty turn before a tool
222/// result is left out; `repairs` reports the input as [`pair`] read it.
223pub fn repair(messages: Vec<Message>) -> Paired {
224    let shaped = shape(messages, true);
225    Paired {
226        messages: shaped.messages,
227        repairs: shaped.repairs,
228    }
229}
230
231/// `entries` repaired as [`repair`] repairs messages, keeping ids: what
232/// the conversation holds after [`Conversation::normalize`].
233///
234/// [`Conversation::normalize`]: super::Conversation::normalize
235#[derive(Debug, Clone, PartialEq)]
236pub struct Normalized {
237    /// The repaired entries, each with the id, author and made-time of the
238    /// first entry it holds anything of; made-up results that no user
239    /// entry follows to take them are a new entry by [`Author::rig`].
240    pub entries: Vec<Entry>,
241    /// What was repaired, as [`repair`] reports it.
242    pub repairs: Vec<PairingError>,
243    /// Each entry merged into another: the id kept, and the id merged into
244    /// it.
245    pub merged: Vec<(MessageId, MessageId)>,
246    /// The ids of entries nothing was kept of, such as one holding only
247    /// results no call asked for.
248    pub dropped: Vec<MessageId>,
249}
250
251/// `entries` repaired as [`repair`] repairs their messages, but that user
252/// entries side by side stay apart: an assistant entry directly after
253/// another is merged into it as [`repair`] says (the later stop
254/// standing) and keeps the first's id, author and made-time; a result no
255/// call waits for is dropped, and an entry left empty with it; a made-up
256/// result for a call nothing answered goes into the next user entry, else
257/// a new entry by [`Author::rig`]; a system entry arriving while calls wait
258/// moves after the entries that answer them. A list [`repair`] leaves as it
259/// is comes back unchanged.
260pub fn normalize(entries: Vec<Entry>) -> Normalized {
261    let (messages, metas): (Vec<Message>, Vec<Meta>) = entries
262        .into_iter()
263        .map(|entry| {
264            let message = Arc::unwrap_or_clone(entry.message);
265            (message, (entry.author, entry.id, entry.made, entry.facts))
266        })
267        .unzip();
268    let shaped = shape(messages, false);
269    let mut used = HashSet::new();
270    let mut merged = Vec::new();
271    let mut entries = Vec::with_capacity(shaped.messages.len());
272    for (message, sources) in shaped.messages.into_iter().zip(shaped.sources) {
273        // The facts of every entry it holds anything of, found by call.
274        let facts = sources
275            .iter()
276            .filter_map(|source| metas.get(*source))
277            .fold(ResultFacts::default(), |facts, (.., more)| facts.and(more));
278        let mut free = sources.iter().filter(|source| used.insert(**source));
279        let kept = free.next().and_then(|source| metas.get(*source));
280        let into = kept.and_then(|(_, id, ..)| *id);
281        for gone in free.filter_map(|source| metas.get(*source)?.1) {
282            if let Some(into) = into {
283                merged.push((into, gone));
284            }
285        }
286        let entry = match kept {
287            Some((author, id, made, _)) => Entry {
288                message: Arc::new(message),
289                author: author.clone(),
290                id: *id,
291                made: *made,
292                facts,
293            },
294            // Part of an entry already kept, by its author, or results
295            // made up, by rig.
296            None => {
297                let first = sources.first().and_then(|source| metas.get(*source));
298                Entry {
299                    message: Arc::new(message),
300                    author: first
301                        .map_or_else(|| Some(Author::rig()), |(author, ..)| author.clone()),
302                    id: None,
303                    made: None,
304                    facts,
305                }
306            }
307        };
308        entries.push(entry);
309    }
310    let dropped = metas.iter().enumerate();
311    let dropped = dropped.filter(|(source, _)| !used.contains(source));
312    Normalized {
313        entries,
314        repairs: shaped.repairs,
315        merged,
316        dropped: dropped.filter_map(|(_, (_, id, ..))| *id).collect(),
317    }
318}
319
320/// An entry without its message: author, id, made-time and facts.
321type Meta = (Option<Author>, Option<MessageId>, Option<u64>, ResultFacts);
322
323/// Messages after [`pair`]'s walk and [`merge_turns`], each with the input
324/// indices it holds anything of (the first is the one it stands for), and
325/// what the first walk repaired.
326struct Shaped {
327    messages: Vec<Message>,
328    sources: Vec<Vec<usize>>,
329    repairs: Vec<PairingError>,
330}
331
332/// `messages` read as a canonical conversation and paired, with adjacent
333/// user messages made one when `merge_users`, then adjacent turns merged,
334/// paired again until none is left.
335fn shape(messages: Vec<Message>, merge_users: bool) -> Shaped {
336    let canonical = |messages: Vec<Message>| {
337        let history = messages.into_iter().map(Some).collect();
338        walk(history, Pairing::canonical(), merge_users, true)
339    };
340    let mut shaped = canonical(messages);
341    // Each merge removes a turn, so this ends.
342    while merge_turns(&mut shaped) {
343        let again = canonical(std::mem::take(&mut shaped.messages));
344        let sources = again.sources.iter().map(|sources| {
345            let earlier = sources.iter().filter_map(|at| shaped.sources.get(*at));
346            earlier.flatten().copied().collect()
347        });
348        shaped.sources = sources.collect();
349        shaped.messages = again.messages;
350    }
351    shaped
352}
353
354/// Whether two assistant turns in a row can be one. Replay trusts a turn's
355/// one origin for every block, so the two must match on what replay
356/// compares, not on one reply's ids, or both have none. This is an
357/// equivalence, so the order merges happen in cannot change the result:
358/// a turn with no origin never joins one with, and each replays as it is.
359fn share_origin(first: Option<&Origin>, later: Option<&Origin>) -> bool {
360    match (first, later) {
361        (Some(first), Some(later)) => {
362            first.same_model(&later.api, &later.provider, &later.model)
363                && first.context == later.context
364        }
365        (None, None) => true,
366        _ => false,
367    }
368}
369
370/// What decides whether two assistant turns in a row merge.
371struct TurnKind {
372    empty: bool,
373    failed: bool,
374    aborted: bool,
375    origin: Option<Origin>,
376}
377
378impl TurnKind {
379    fn of(turn: &AssistantMessage) -> Self {
380        Self {
381            empty: turn.content.is_empty(),
382            failed: matches!(turn.stop, Some(StopReason::Error(_))),
383            aborted: matches!(turn.stop, Some(StopReason::Aborted(_))),
384            origin: turn.origin.clone(),
385        }
386    }
387
388    /// Whether `later`, directly after this turn, merges into it. An empty
389    /// turn has nothing to protect, so it always does. Turns with different
390    /// outcomes stay apart: one stop stands for a merged turn, and it decides
391    /// what the whole turn sends.
392    fn merges(&self, later: &Self) -> bool {
393        self.empty
394            || later.empty
395            || (self.failed == later.failed
396                && self.aborted == later.aborted
397                && share_origin(self.origin.as_ref(), later.origin.as_ref()))
398    }
399}
400
401/// Merge every assistant turn directly after another that
402/// [merges](TurnKind::merges) into it, the later turn's stop standing;
403/// whether any was merged. An empty turn changes nothing about the turn it
404/// merges with: an empty first turn gives way to the later's origin, and an
405/// empty later turn's stop is dropped.
406fn merge_turns(shaped: &mut Shaped) -> bool {
407    let before = shaped.messages.len();
408    let mut messages: Vec<Message> = Vec::with_capacity(before);
409    let mut sources: Vec<Vec<usize>> = Vec::with_capacity(before);
410    let all = shaped.messages.drain(..).zip(shaped.sources.drain(..));
411    for (mut message, mut from) in all {
412        if let Message::Assistant(turn) = &mut message
413            && let Some(Message::Assistant(previous)) = messages.last_mut()
414            && TurnKind::of(previous).merges(&TurnKind::of(turn))
415        {
416            let first_empty = previous.content.is_empty();
417            if first_empty {
418                previous.origin = turn.origin.take();
419            }
420            if first_empty || !turn.content.is_empty() {
421                previous.stop = turn.stop.take();
422            }
423            previous.content.append(&mut turn.content);
424            if let Some(into) = sources.last_mut() {
425                into.append(&mut from);
426            }
427            continue;
428        }
429        messages.push(message);
430        sources.push(from);
431    }
432    shaped.messages = messages;
433    shaped.sources = sources;
434    shaped.messages.len() < before
435}
436
437/// The one rule for when a tool call is answered.
438/// `None` is a turn the caller emptied; it ends waiting calls like a turn.
439///
440/// - A result answers the first call of the turn before it still waiting
441///   with its id; a result nothing waits for is dropped.
442/// - A turn that ended in an error or was aborted is kept; its calls wait
443///   for nothing.
444/// - A call still waiting at a user message with more than results, the
445///   next turn or the end gets a [`close_pending`] result, before the user
446///   message's own content.
447/// - Adjacent non-empty user messages become one, and a system message
448///   arriving while calls wait is held until they are answered.
449pub fn pair(history: Vec<Option<Message>>, pairing: Pairing) -> Paired {
450    let shaped = walk(history, pairing, true, false);
451    Paired {
452        messages: shaped.messages,
453        repairs: shaped.repairs,
454    }
455}
456
457/// [`pair`]'s walk, noting where each message came from when `sourced`.
458/// Without `merge_users`, the content of adjacent user messages answers
459/// calls as one but stays in the message it came from, and a held system
460/// message goes after them whole.
461fn walk(
462    history: Vec<Option<Message>>,
463    pairing: Pairing,
464    merge_users: bool,
465    sourced: bool,
466) -> Shaped {
467    // The ids results before the first turn took, when calls are stored.
468    let mut stored = pairing.stored.then(Vec::new);
469    let mut walk = Walk {
470        answers: pairing.answers,
471        merge_users,
472        sourced,
473        ..Walk::default()
474    };
475    let parting = if sourced {
476        parting_turns(&history)
477    } else {
478        Vec::new()
479    };
480    walk.repairs
481        .extend(parting.iter().map(|(_, why)| why.clone()));
482    for step in steps(history, &parting) {
483        match step {
484            Step::Turn(index, turn) => {
485                if let (Some(before), Some(turn)) = (&walk.after_turn, &turn)
486                    && before.merges(&TurnKind::of(turn))
487                {
488                    walk.repairs
489                        .push(PairingError::ConsecutiveAssistant { index });
490                }
491                walk.close();
492                stored = None;
493                walk.gap = turn.is_none();
494                walk.after_turn = match &turn {
495                    Some(turn) if turn.content.is_empty() && walk.after_turn.is_some() => {
496                        walk.after_turn.take()
497                    }
498                    turn => turn.as_ref().map(TurnKind::of),
499                };
500                let Some(turn) = turn else { continue };
501                if !turn.stop.as_ref().is_some_and(|stop| stop.is_failure()) {
502                    let calls = turn.tool_calls();
503                    let calls = calls.map(|call| (call.id.clone(), call.function.name.clone()));
504                    walk.waiting = calls.collect();
505                    walk.waiting_at = index;
506                }
507                walk.put(Message::Assistant(turn), [index]);
508            }
509            Step::System(index, system) => {
510                walk.after_turn = None;
511                if walk.waiting.is_empty() {
512                    walk.gap = false;
513                    walk.put(system, [index]);
514                } else {
515                    walk.held.push((index, system));
516                }
517            }
518            Step::User(first, parts) => {
519                walk.after_turn = None;
520                if parts.is_empty() {
521                    walk.close();
522                    let empty = Message::User {
523                        content: Vec::new(),
524                    };
525                    walk.put(empty, [first]);
526                    walk.gap = false;
527                    continue;
528                }
529                let mut content = Vec::with_capacity(parts.len());
530                for (index, part) in parts {
531                    let UserContent::ToolResult(result) = part else {
532                        content.push((Some(index), part));
533                        continue;
534                    };
535                    let answers = match &mut stored {
536                        Some(taken) if !taken.contains(&result.call) => {
537                            taken.push(result.call.clone());
538                            true
539                        }
540                        Some(_) => false,
541                        None => take(&mut walk.waiting, &result.call, |(id, _)| id).is_some(),
542                    };
543                    if answers {
544                        content.push((Some(index), UserContent::ToolResult(result)));
545                    } else {
546                        walk.repairs.push(PairingError::OrphanToolResult {
547                            index,
548                            call_id: result.call,
549                        });
550                    }
551                }
552                if content.is_empty() && walk.waiting.is_empty() {
553                    // Only results nothing waits for: the gap stays open.
554                    continue;
555                }
556                let only_results =
557                    !content.is_empty() && content.iter().all(|(_, part)| is_result(part));
558                if walk.pending.is_empty() {
559                    walk.pending_gap = walk.gap;
560                }
561                walk.pending.extend(content);
562                walk.gap = false;
563                // pi holds a system message while calls wait, so results
564                // split around one still answer the turn.
565                if only_results && !walk.waiting.is_empty() {
566                    continue;
567                }
568                walk.close();
569            }
570        }
571    }
572    walk.close();
573    Shaped {
574        messages: walk.shaped,
575        sources: walk.sources,
576        repairs: walk.repairs,
577    }
578}
579
580pub(crate) fn is_result(part: &UserContent) -> bool {
581    matches!(part, UserContent::ToolResult(_))
582}
583
584/// The user message closing `calls` nothing answered: a [`NO_RESULT_PROVIDED`]
585/// error result per occurrence, in call order, exactly as [`pair`] closes them.
586pub fn close_pending<'a>(calls: impl IntoIterator<Item = &'a ToolCall>) -> Message {
587    close_pending_with(calls, NO_RESULT_PROVIDED)
588}
589
590/// [`close_pending`], each error result saying `why`, such as why the
591/// calls never ran.
592pub fn close_pending_with<'a>(calls: impl IntoIterator<Item = &'a ToolCall>, why: &str) -> Message {
593    let calls = calls.into_iter();
594    Message::User {
595        content: unanswered(calls.map(|call| (&call.id, &call.function.name)), why),
596    }
597}
598
599fn unanswered<'a>(
600    calls: impl IntoIterator<Item = (&'a CallId, &'a ToolName)>,
601    why: &str,
602) -> Vec<UserContent> {
603    calls
604        .into_iter()
605        .map(|(id, name)| tool_result_message(id.clone(), name.clone(), why.to_owned()))
606        .collect()
607}
608
609/// Takes the first of `waiting` with the id `id`.
610fn take<T>(waiting: &mut Vec<T>, id: &CallId, id_of: impl Fn(&T) -> &CallId) -> Option<T> {
611    let at = waiting.iter().position(|call| id_of(call) == id)?;
612    Some(waiting.remove(at))
613}
614
615/// One step of [`pair`]'s walk, with indices into its input.
616enum Step {
617    /// An assistant turn, or `None` for one the caller emptied.
618    Turn(usize, Option<AssistantMessage>),
619    System(usize, Message),
620    /// A run of adjacent non-empty user messages, or one empty one: the
621    /// index of the first, and the index each part came from.
622    User(usize, Vec<(usize, UserContent)>),
623}
624
625/// The empty turns before a tool result, with no other turn between, and
626/// why each is left out of a repair. A result answers only a turn before
627/// it, so such a turn can only part it from its call; a result after it is
628/// an orphan as the input reads, so the history was never valid.
629fn parting_turns(history: &[Option<Message>]) -> Vec<(usize, PairingError)> {
630    let mut parting = Vec::new();
631    let mut result = None;
632    for (index, message) in history.iter().enumerate().rev() {
633        match message {
634            Some(Message::System { .. }) => {}
635            Some(Message::User { content }) => {
636                let found = content.iter().find_map(UserContent::as_tool_result);
637                let found = found.map(|found| (index, found.call.clone()));
638                result = found.or(result);
639            }
640            Some(Message::Assistant(turn)) if turn.content.is_empty() => {
641                if let Some((at, call_id)) = &result {
642                    let why = PairingError::OrphanToolResult {
643                        index: *at,
644                        call_id: call_id.clone(),
645                    };
646                    parting.push((index, why));
647                }
648            }
649            _ => result = None,
650        }
651    }
652    parting
653}
654
655/// `history` as steps, each run of adjacent non-empty user messages made
656/// one, so results split over several messages answer the turn before them.
657fn steps(history: Vec<Option<Message>>, left_out: &[(usize, PairingError)]) -> Vec<Step> {
658    let mut steps: Vec<Step> = Vec::with_capacity(history.len());
659    for (index, message) in history.into_iter().enumerate() {
660        if left_out.iter().any(|(at, _)| *at == index) {
661            continue;
662        }
663        match message {
664            None => steps.push(Step::Turn(index, None)),
665            Some(Message::Assistant(turn)) => steps.push(Step::Turn(index, Some(turn))),
666            Some(system @ Message::System { .. }) => steps.push(Step::System(index, system)),
667            Some(Message::User { content }) => {
668                let joins = !content.is_empty();
669                let parts = content.into_iter().map(|part| (index, part));
670                match steps.last_mut() {
671                    Some(Step::User(_, previous)) if joins && !previous.is_empty() => {
672                        previous.extend(parts)
673                    }
674                    _ => steps.push(Step::User(index, parts.collect())),
675                }
676            }
677        }
678    }
679    steps
680}
681
682/// The state of [`pair`]'s walk.
683#[derive(Default)]
684struct Walk {
685    answers: bool,
686    /// Whether the content of adjacent user messages becomes one message.
687    merge_users: bool,
688    /// Whether `sources` is kept.
689    sourced: bool,
690    shaped: Vec<Message>,
691    /// Parallel to `shaped` when `sourced`: the input indices each holds
692    /// anything of.
693    sources: Vec<Vec<usize>>,
694    repairs: Vec<PairingError>,
695    /// Every occurrence of the last turn's calls still waiting, in call
696    /// order, and the turn's index.
697    waiting: Vec<(CallId, ToolName)>,
698    waiting_at: usize,
699    /// System messages that arrived while calls waited, with their indices.
700    held: Vec<(usize, Message)>,
701    /// Whether a turn was emptied since the last message pushed.
702    gap: bool,
703    /// Results answering some waiting calls while others still wait, and
704    /// content after them, each with its index (none for one made up).
705    pending: Vec<(Option<usize>, UserContent)>,
706    pending_gap: bool,
707    /// The turn just walked, when the last step was a turn. An empty turn
708    /// after another leaves that one here.
709    after_turn: Option<TurnKind>,
710}
711
712impl Walk {
713    fn put(&mut self, message: Message, sources: impl IntoIterator<Item = usize>) {
714        self.shaped.push(message);
715        if self.sourced {
716            self.sources.push(sources.into_iter().collect());
717        }
718    }
719
720    /// Push the pending user content with a result added for each waiting
721    /// call, then the held system messages. The results go before its first
722    /// non-result part, in call order. Nothing is pushed for empty content,
723    /// and content after a gap is appended to a user message that ends
724    /// `shaped`. Without `merge_users`, each message's content stays its
725    /// own, the made-up results go into the first, and the held system
726    /// messages follow them all.
727    fn close(&mut self) {
728        let mut content = std::mem::take(&mut self.pending);
729        let merge = std::mem::take(&mut self.pending_gap);
730        let waiting = std::mem::take(&mut self.waiting);
731        let missing =
732            if self.answers {
733                let index = self.waiting_at;
734                self.repairs.extend(waiting.iter().map(|(id, _)| {
735                    PairingError::UnansweredToolCall {
736                        index,
737                        call_id: id.clone(),
738                    }
739                }));
740                unanswered(
741                    waiting.iter().map(|(id, name)| (id, name)),
742                    NO_RESULT_PROVIDED,
743                )
744            } else {
745                Vec::new()
746            };
747        if !self.merge_users {
748            self.close_apart(content, missing);
749            return;
750        }
751        let at = content
752            .iter()
753            .position(|(_, part)| !is_result(part))
754            .unwrap_or(content.len());
755        content.splice(at..at, missing.into_iter().map(|part| (None, part)));
756        // Results come first: Anthropic requires it, and Chat sends them as
757        // tool messages that must follow the turn directly.
758        content.sort_by_key(|(_, part)| !is_result(part));
759        // A held system message goes right after the results, before the
760        // user's own text, as pi places it.
761        let at = content
762            .iter()
763            .position(|(_, part)| !is_result(part))
764            .unwrap_or(content.len());
765        let text = if self.held.is_empty() {
766            Vec::new()
767        } else {
768            content.split_off(at)
769        };
770        if !content.is_empty() {
771            let (sources, content) = sourced(content);
772            match self.shaped.last_mut() {
773                // Only `pair` leaves a gap to merge across, and it keeps no
774                // sources.
775                Some(Message::User { content: previous }) if merge => previous.extend(content),
776                _ => self.put(Message::User { content }, sources),
777            }
778        }
779        for (index, system) in std::mem::take(&mut self.held) {
780            self.put(system, [index]);
781        }
782        if !text.is_empty() {
783            let (sources, content) = sourced(text);
784            self.put(Message::User { content }, sources);
785        }
786    }
787
788    /// [`close`](Self::close) without `merge_users`: each input message's
789    /// pending content as its own message, results first, the `missing`
790    /// results in the first (else a message of their own), then the held
791    /// system messages.
792    fn close_apart(
793        &mut self,
794        content: Vec<(Option<usize>, UserContent)>,
795        missing: Vec<UserContent>,
796    ) {
797        let mut messages: Vec<(Option<usize>, Vec<UserContent>)> = Vec::new();
798        for (source, part) in content {
799            match messages.last_mut() {
800                Some((last, parts)) if *last == source => parts.push(part),
801                _ => messages.push((source, vec![part])),
802            }
803        }
804        match messages.first_mut() {
805            Some((_, parts)) => {
806                let at = parts.iter().position(|part| !is_result(part));
807                let at = at.unwrap_or(parts.len());
808                parts.splice(at..at, missing);
809            }
810            None if !missing.is_empty() => messages.push((None, missing)),
811            None => {}
812        }
813        for (source, mut content) in messages {
814            content.sort_by_key(|part| !is_result(part));
815            self.put(Message::User { content }, source);
816        }
817        for (index, system) in std::mem::take(&mut self.held) {
818            self.put(system, [index]);
819        }
820    }
821}
822
823/// `content` without its indices, and the indices it holds, each once in
824/// the order first met.
825fn sourced(content: Vec<(Option<usize>, UserContent)>) -> (Vec<usize>, Vec<UserContent>) {
826    let mut sources: Vec<usize> = Vec::new();
827    let parts = content.into_iter().map(|(source, part)| {
828        if let Some(source) = source
829            && !sources.contains(&source)
830        {
831            sources.push(source);
832        }
833        part
834    });
835    let parts = parts.collect();
836    (sources, parts)
837}
838
839/// The tool calls of the last assistant message in `messages` that no
840/// later tool result answers, in call order: what a conversation cut short
841/// still owes the model. A turn that ended in an error or was aborted owes
842/// none, as its calls never run.
843pub fn pending_calls(messages: &[impl Borrow<Message>]) -> Vec<ToolCall> {
844    let pending = pending(messages);
845    let calls = pending.into_iter().flat_map(|(_, calls)| calls);
846    calls.map(|(_, call)| call.clone()).collect()
847}
848
849/// [`pending_calls`], with the index of the message asking for them and
850/// each call's place among its tool calls.
851pub(crate) fn pending<M: Borrow<Message>>(
852    messages: &[M],
853) -> Option<(usize, Vec<(u32, &ToolCall)>)> {
854    let (at, reply) = messages
855        .iter()
856        .map(Borrow::borrow)
857        .enumerate()
858        .rev()
859        .find_map(|(at, message)| match message {
860            Message::Assistant(reply) => Some((at, reply)),
861            _ => None,
862        })?;
863    if reply.stop.as_ref().is_some_and(|stop| stop.is_failure()) {
864        return None;
865    }
866    let results = messages
867        .iter()
868        .skip(at + 1)
869        .flat_map(|message| message.borrow().results())
870        .map(|result| (&result.call, ()));
871    let answered = answered_by(reply.tool_calls().map(|call| &call.id), results);
872    let calls = (0..).zip(reply.tool_calls()).zip(answered);
873    let calls = calls.filter_map(|(call, answer)| answer.is_none().then_some(call));
874    Some((at, calls.collect()))
875}
876
877/// The first index at or after `at` a request may start `messages` from:
878/// past every tool result before the first assistant turn from `at`, since
879/// its call is cut off, with any text or system message among them. Paired
880/// results later on are left alone. `at` past the end is the end.
881pub fn safe_start(messages: &[impl Borrow<Message>], at: usize) -> usize {
882    let mut start = at.min(messages.len());
883    for (index, message) in messages.iter().enumerate().skip(at) {
884        match message.borrow() {
885            Message::Assistant(_) => break,
886            Message::User { content }
887                if content
888                    .iter()
889                    .any(|item| matches!(item, UserContent::ToolResult(_))) =>
890            {
891                start = index + 1;
892            }
893            _ => {}
894        }
895    }
896    start
897}
898
899#[cfg(test)]
900mod tests;