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
//! What a session's stream said of a turn's reply, so the turn's answer
//! can fill in the text that never arrived in chunks.
//!
//! The daemon streams `AgentMessageChunk`s only from the provider's output
//! deltas. A reply a provider returns whole, with no deltas, reaches clients
//! only as the `text` of the turn's `TurnEnded` outcome, which
//! [`rho_protocol::TurnOutcome::Answered`] says clients reconcile with. The
//! TUI and the ACP adapter both feed a [`StreamedReply`] every event their
//! session stream delivers, shown or not (ACP never echoes a host its own
//! prompt), and it tells them at the turn's end what is missing.
use rho_protocol::{AnswerStop, MessageId, SessionEvent, TurnOutcome};
/// The agent message a session's stream last showed, as far as its turn's
/// answer goes.
#[derive(Debug, Default)]
pub(crate) struct StreamedReply {
/// The message the last agent chunk extended, while nothing else came
/// between it and the next chunk.
open: Option<MessageId>,
/// The last agent message's id and its text so far.
reply: Option<(MessageId, String)>,
/// Whether the step that streamed `reply` went on: it called tools, or
/// the model was given a result. A turn's answer is its last agent
/// message, so after either an answer other than `reply` is a later
/// step's whose text never arrived in chunks.
stepped: bool,
}
/// Answer text a turn's end carried that its chunks did not show.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct MissingReply {
pub(crate) text: String,
/// The streamed message `text` finishes, or `None` when it is a message
/// of its own.
pub(crate) continues: Option<MessageId>,
}
impl StreamedReply {
/// Takes `event`, the stream's next. At a turn's end, returns the text
/// of its answer the stream did not show: the whole answer when nothing
/// of it was streamed since the last tool call, result card or user
/// message, the rest when the streamed reply begins it, and nothing when
/// they differ, as after a provider restarted its response, or when a
/// host command answered ([`AnswerStop::Command`]).
pub(crate) fn observe(&mut self, event: &SessionEvent) -> Option<MissingReply> {
match event {
SessionEvent::AgentMessageChunk { message, text } => {
if self.open.as_ref() != Some(message) {
self.reply = Some((message.clone(), String::new()));
self.stepped = false;
}
if let Some((_, reply)) = self.reply.as_mut() {
reply.push_str(text);
}
self.open = Some(message.clone());
}
SessionEvent::ThoughtChunk { .. } => self.open = None,
// The step's text ends at its calls, and a result the model was
// given starts a later step.
SessionEvent::ToolCall(_) | SessionEvent::Card { .. } => {
self.open = None;
self.stepped = true;
}
// What follows a user message or a restarted response is new.
SessionEvent::UserMessage { .. } | SessionEvent::ResponseDiscarded => {
*self = Self::default();
}
SessionEvent::TurnEnded { outcome, .. } => {
let missing = self.missing(outcome);
*self = Self::default();
return missing;
}
_ => {}
}
None
}
fn missing(&self, outcome: &TurnOutcome) -> Option<MissingReply> {
let text = match outcome {
// A host command showed its result as it ran; a replay need not
// hold that message, so nothing streamed says what is missing.
TurnOutcome::Answered {
stop: AnswerStop::Command,
..
} => return None,
TurnOutcome::Answered { text, .. } | TurnOutcome::MaxSteps { text } => text,
_ => return None,
};
let (message, streamed) = match &self.reply {
Some((message, streamed)) => (Some(message), streamed.as_str()),
None => (None, ""),
};
// An empty answer: the last step only called tools.
if self.stepped && !text.is_empty() && text != streamed {
return Some(MissingReply {
text: text.clone(),
continues: None,
});
}
match text.strip_prefix(streamed) {
// The stream showed it all, or showed another reply, as when a
// provider's retry restarted it without saying so.
None | Some("") => None,
Some(rest) => Some(MissingReply {
text: rest.to_owned(),
continues: message.filter(|_| !streamed.is_empty()).cloned(),
}),
}
}
}
#[cfg(test)]
#[path = "streamed_reply_tests.rs"]
mod tests;