rig_core/conversation/turn.rs
1//! Turn records: where each turn of a conversation began and how it ended,
2//! kept as asides, so a saved session tells a stopped or failed turn from
3//! an answered one without the app that ran it.
4
5use std::fmt;
6
7use serde::{Deserialize, Serialize};
8
9use super::{Aside, AsideId, Author, CallRef, Conversation, MessageId};
10
11/// The kind of an aside holding a [`TurnRecord`].
12pub const TURN: &str = "rig.turn";
13
14/// One turn of a conversation, from the message that asked for it to how
15/// it ended. Kept as an aside of kind [`TURN`] by [`Author::rig`], put
16/// after the last entry when the turn begins and replaced when it ends.
17#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
18pub struct TurnRecord {
19 /// How many turns began before this one.
20 pub index: u64,
21 /// Where it begins ([`Conversation::turn_start`]):
22 /// [`asked`](Conversation::asked) is what it answers,
23 /// [`request`](Conversation::request) the message that asked for it.
24 pub start: MessageId,
25 /// How it ended; `None` while it runs, when a crash cut it short, and
26 /// when a plugin kept it running past an exit for the restart. An exit
27 /// otherwise stops it.
28 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub end: Option<TurnEnd>,
30}
31
32/// How a turn ended.
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(tag = "how", rename_all = "snake_case")]
35pub enum TurnEnd {
36 /// The model answered.
37 Answered {
38 /// The reply entry the turn ended on; `None` when the last entry was
39 /// no reply.
40 #[serde(default, rename = "by", skip_serializing_if = "Option::is_none")]
41 answer: Option<MessageId>,
42 },
43 /// The turn failed, for `why`.
44 Failed {
45 /// Why.
46 why: String,
47 },
48 /// The turn was stopped before an answer, for `by`.
49 Stopped {
50 /// Who or what stopped it. `None` only in a record saved before
51 /// the cause was recorded.
52 #[serde(default, skip_serializing_if = "Option::is_none")]
53 by: Option<StopCause>,
54 /// The turn's last entry when a stop cut it off, which a front draws
55 /// the stop under; `None` when the turn had no entry of its own yet,
56 /// or ended as stopped in its own course, such as a compaction
57 /// ending it.
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 at: Option<MessageId>,
60 /// The places of the tool calls the stop cut: those it answered,
61 /// which had no result of their own, and those of the reply it cut
62 /// off, which never ran and owe none. Empty in a record saved
63 /// before calls had places.
64 #[serde(default, rename = "cut", skip_serializing_if = "Vec::is_empty")]
65 calls: Vec<CallRef>,
66 },
67}
68
69/// Who or what stopped a turn before it answered.
70#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum StopCause {
73 /// The user stopped it.
74 User,
75 /// The app exited, for the reason given.
76 Exit(String),
77 /// A restart stopped the turn a crash left unfinished.
78 Restarted,
79 /// A plugin stopped it: `by` names the plugin, `why` says what for.
80 Plugin {
81 /// The plugin.
82 by: String,
83 /// What for.
84 why: String,
85 },
86}
87
88impl fmt::Display for StopCause {
89 /// Why the turn stopped, as its unfinished calls are told.
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 match self {
92 Self::User => f.write_str("the user stopped the turn"),
93 Self::Exit(why) | Self::Plugin { why, .. } => f.write_str(why),
94 Self::Restarted => f.write_str("the session restarted"),
95 }
96 }
97}
98
99impl TurnRecord {
100 /// The record `aside` holds, when it is one: of kind [`TURN`], its
101 /// value a record.
102 pub fn of(aside: &Aside) -> Option<Self> {
103 aside.read(TURN)
104 }
105}
106
107impl Conversation {
108 /// The turn records, oldest first, with their asides' ids; the newest
109 /// is `turns().next_back()`, found from the end.
110 pub fn turns(&self) -> impl DoubleEndedIterator<Item = (AsideId, TurnRecord)> + '_ {
111 self.asides()
112 .filter_map(|(id, aside)| Some((id, TurnRecord::of(aside)?)))
113 }
114
115 /// Records a turn that begins now, numbered after the last record and
116 /// starting at [`turn_start`](Self::turn_start). Returns the new record.
117 pub fn open_turn(&mut self) -> TurnRecord {
118 let last = self.turns().next_back().map(|(_, record)| record.index);
119 let record = TurnRecord {
120 index: last.map_or(0, |index| index.saturating_add(1)),
121 start: self.turn_start(),
122 end: None,
123 };
124 let after = self.entries().next_back().map(|entry| entry.id);
125 let value = serde_json::to_value(&record).unwrap_or_default();
126 self.add_aside(Aside::new(TURN, Author::rig(), value).after(after));
127 record
128 }
129
130 /// Ends the last turn record, when it is open, with `end`. Returns
131 /// whether it was open.
132 pub fn end_turn(&mut self, end: TurnEnd) -> bool {
133 let Some((id, record)) = self.turns().next_back() else {
134 return false;
135 };
136 let Some(aside) = self.aside(id).filter(|_| record.end.is_none()).cloned() else {
137 return false;
138 };
139 let ended = TurnRecord {
140 end: Some(end),
141 ..record
142 };
143 let value = serde_json::to_value(ended).unwrap_or_default();
144 self.replace_aside(id, Aside { value, ..aside })
145 }
146}