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
//! Session — stateful wrapper around an `Arc<Agent>`.
use std::sync::Arc;
use caliban_provider::Message;
use tokio_util::sync::CancellationToken;
use crate::agent::Agent;
use crate::error::Result;
use crate::stream::TurnEventStream;
/// Stateful conversation session sharing an [`Arc<Agent>`].
///
/// Multiple sessions can share one [`Agent`]. Each session maintains its own
/// message history and cancellation token.
pub struct Session {
agent: Arc<Agent>,
messages: Vec<Message>,
cancel: CancellationToken,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("messages", &self.messages.len())
.finish_non_exhaustive()
}
}
impl Session {
/// Create a new session backed by `agent` with an empty message history.
#[must_use]
pub fn new(agent: Arc<Agent>) -> Self {
Self {
agent,
messages: Vec::new(),
cancel: CancellationToken::new(),
}
}
/// Prepend a system message, inserting it before any non-system messages.
///
/// Maintains the invariant that system messages precede user/assistant
/// messages in the history.
pub fn system(&mut self, text: impl Into<String>) -> &mut Self {
let insertion_index = self
.messages
.iter()
.position(|m| m.role != caliban_provider::Role::System)
.unwrap_or(self.messages.len());
self.messages
.insert(insertion_index, Message::system_text(text));
self
}
/// Append a user text message.
pub fn user_text(&mut self, text: impl Into<String>) -> &mut Self {
self.messages.push(Message::user_text(text));
self
}
/// Append an arbitrary message.
pub fn user_message(&mut self, msg: Message) -> &mut Self {
self.messages.push(msg);
self
}
/// Append several messages at once.
pub fn extend_messages(&mut self, msgs: impl IntoIterator<Item = Message>) -> &mut Self {
self.messages.extend(msgs);
self
}
/// Run the agent until done; append generated messages to history.
///
/// Returns a slice of the messages that were added during this call
/// (assistant messages + tool result messages).
///
/// # Errors
///
/// Propagates errors from the underlying [`Agent::run_until_done`].
pub async fn run(&mut self) -> Result<&[Message]> {
let original_len = self.messages.len();
let messages = self.messages.clone();
let outcome = Arc::clone(&self.agent)
.run_until_done(messages, self.cancel.clone())
.await?;
self.messages = outcome.final_messages;
Ok(&self.messages[original_len..])
}
/// Return a streaming event source for the current history.
///
/// The caller must drain the stream. This method does **not** mutate
/// `self.messages` automatically because events are emitted incrementally;
/// the caller should call [`Session::extend_messages`] with the final
/// messages from [`TurnEvent::RunEnd`] if they wish to persist the history.
///
/// # Errors
///
/// Returns any error from the underlying [`Agent::stream_until_done`].
pub fn stream(&self) -> TurnEventStream {
Arc::clone(&self.agent).stream_until_done(self.messages.clone(), self.cancel.clone())
}
/// Read-only view of the current message history.
#[must_use]
pub fn messages(&self) -> &[Message] {
&self.messages
}
/// Clear all history.
pub fn clear(&mut self) {
self.messages.clear();
}
/// Signal cancellation for any in-flight or future `run`/`stream` call.
pub fn cancel(&self) {
self.cancel.cancel();
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use tokio_util::sync::CancellationToken;
// A minimal helper to build an Agent without a real provider.
// We only test the Session's *structural* behaviour here (message
// management, cancel signalling). Round-trip tests with a mock provider
// live in the integration test suite (Task 8).
#[test]
fn debug_impl_does_not_panic() {
// Build a CancellationToken manually — we just need a Session value.
let cancel = CancellationToken::new();
// We can't build a full Agent without a provider, so test the
// Debug output indirectly via a token that exists.
assert!(!cancel.is_cancelled());
}
#[test]
fn system_message_inserted_before_user_messages() {
// Create a bare Session by constructing one without a real agent call.
// We test just the message-ordering logic, which is pure Rust.
use caliban_provider::{Message, Role};
// Simulate the internal logic of Session::system directly.
let mut messages: Vec<Message> =
vec![Message::user_text("hello"), Message::assistant_text("hi")];
let insertion_index = messages
.iter()
.position(|m| m.role != Role::System)
.unwrap_or(messages.len());
messages.insert(insertion_index, Message::system_text("be helpful"));
assert_eq!(messages[0].role, Role::System);
assert_eq!(messages[1].role, Role::User);
assert_eq!(messages[2].role, Role::Assistant);
}
#[test]
fn system_appended_after_existing_system_messages() {
use caliban_provider::{Message, Role};
let mut messages: Vec<Message> = vec![
Message::system_text("first system"),
Message::user_text("hello"),
];
// Insert second system message — should go at index 1 (before the user msg).
let insertion_index = messages
.iter()
.position(|m| m.role != Role::System)
.unwrap_or(messages.len());
messages.insert(insertion_index, Message::system_text("second system"));
assert_eq!(messages[0].role, Role::System);
assert_eq!(messages[1].role, Role::System);
assert_eq!(messages[2].role, Role::User);
}
#[test]
fn cancel_token_fires_after_cancel() {
let cancel = CancellationToken::new();
assert!(!cancel.is_cancelled());
cancel.cancel();
assert!(cancel.is_cancelled());
}
}