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
//! Runtime store facade.
//!
//! Provides a unified interface for runtime persistence operations,
//! composing session, execution, and run stores.
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use behest_provider::Message;
use behest_store::{
ArtifactStore, EmbeddingStore, ExecutionStore, MessageRecord, MessageRole, SessionStore,
};
use super::error::{RuntimeError, RuntimeResult};
use super::event::AgentEvent;
use super::extension::ExtensionPoint;
use super::extensions::Extensions;
use super::run::{RunId, RunRecord, RunStatus};
use super::state::RunState;
/// Persistent record of a run event with sequence number ordering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunEventRecord {
/// Monotonically increasing event sequence number within the run.
pub sequence: u64,
/// Run this event belongs to.
pub run_id: RunId,
/// The event payload.
pub event: AgentEvent,
/// When the event was recorded.
pub timestamp: DateTime<Utc>,
}
impl RunEventRecord {
/// Creates a new run event record with the current timestamp.
#[must_use]
pub fn new(sequence: u64, run_id: RunId, event: AgentEvent) -> Self {
Self {
sequence,
run_id,
event,
timestamp: Utc::now(),
}
}
}
/// Store for run lifecycle and events.
///
/// Implementations provide persistence for run metadata and the
/// event-sourced event log. Default implementations are provided for
/// [`get_run_state`](Self::get_run_state) and
/// [`list_runs_filtered`](Self::list_runs_filtered), which backends
/// may override with native projections for efficiency.
#[async_trait]
pub trait RunStore: Send + Sync {
/// Persists a new run record.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] on persistence failure.
async fn create_run(&self, record: RunRecord) -> RuntimeResult<()>;
/// Loads a run record by its identifier.
///
/// Returns `None` when no run with the given ID exists.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] on persistence failure.
async fn get_run(&self, run_id: RunId) -> RuntimeResult<Option<RunRecord>>;
/// Gets the event-sourced state of a run by replaying its event log.
///
/// Default implementation calls [`Self::get_run`] + [`Self::list_events`] and
/// folds them into a [`RunState`]. Backends may override with a
/// native projection for better performance.
async fn get_run_state(&self, run_id: RunId) -> RuntimeResult<Option<RunState>> {
let Some(record) = self.get_run(run_id).await? else {
return Ok(None);
};
let events = self.list_events(run_id).await?;
Ok(Some(RunState::create(&record, &events)))
}
/// Updates the status of an existing run.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] on persistence failure.
async fn update_run_status(&self, run_id: RunId, status: RunStatus) -> RuntimeResult<()>;
/// Appends an event to a run's event log.
///
/// The event is stored as a [`RunEventRecord`] with a monotonically
/// increasing sequence number.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] on persistence failure.
async fn append_event(&self, record: RunEventRecord) -> RuntimeResult<()>;
/// Returns the full event log for a run, ordered by sequence number.
///
/// # Errors
///
/// Returns [`RuntimeError::RunNotFound`] when the run does not exist,
/// or [`RuntimeError::Storage`] on persistence failure.
async fn list_events(&self, run_id: RunId) -> RuntimeResult<Vec<RunEventRecord>>;
/// Lists all runs belonging to a session.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] on persistence failure.
async fn list_runs(&self, session_id: Uuid) -> RuntimeResult<Vec<RunRecord>>;
/// Lists runs with optional filters and pagination.
///
/// Default implementation iterates all sessions; backends should override
/// with a native query for efficiency.
async fn list_runs_filtered(
&self,
session_id: Option<Uuid>,
status: Option<RunStatus>,
limit: usize,
offset: usize,
) -> RuntimeResult<Vec<RunRecord>> {
let _ = (session_id, status, limit, offset);
Err(RuntimeError::Storage(
behest_core::error::StorageError::BackendError {
backend: "run".to_owned(),
message: "list_runs_filtered not implemented".to_owned(),
source: None,
},
))
}
/// Deletes a run and all its associated events.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] on persistence failure.
async fn delete_run(&self, run_id: RunId) -> RuntimeResult<()>;
/// Performs a health check against the underlying storage backend.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] when the backend is unhealthy.
async fn health_check(&self) -> RuntimeResult<()>;
}
/// Runtime store facade composing session, execution, run, embedding, and artifact stores.
///
/// Provides a unified interface for all runtime persistence operations.
/// Individual sub-stores are accessed via their respective accessor methods.
pub struct RuntimeStore {
sessions: Box<dyn SessionStore>,
executions: Box<dyn ExecutionStore>,
runs: Box<dyn RunStore>,
embeddings: Option<Box<dyn EmbeddingStore>>,
artifacts: Option<Box<dyn ArtifactStore>>,
sessions_ep: ExtensionPoint<dyn SessionStore>,
executions_ep: ExtensionPoint<dyn ExecutionStore>,
runs_ep: ExtensionPoint<dyn RunStore>,
embeddings_ep: ExtensionPoint<dyn EmbeddingStore>,
artifacts_ep: ExtensionPoint<dyn ArtifactStore>,
}
impl RuntimeStore {
/// Creates a new runtime store with session, execution, and run stores.
///
/// Embedding and artifact stores are optional — attach them with
/// [`with_embeddings`](Self::with_embeddings) and
/// [`with_artifacts`](Self::with_artifacts).
#[must_use]
pub fn new(
sessions: Box<dyn SessionStore>,
executions: Box<dyn ExecutionStore>,
runs: Box<dyn RunStore>,
) -> Self {
Self {
sessions,
executions,
runs,
embeddings: None,
artifacts: None,
sessions_ep: ExtensionPoint::new(),
executions_ep: ExtensionPoint::new(),
runs_ep: ExtensionPoint::new(),
embeddings_ep: ExtensionPoint::new(),
artifacts_ep: ExtensionPoint::new(),
}
}
/// Attaches an optional embedding store for vector search operations.
#[must_use]
pub fn with_embeddings(mut self, store: Box<dyn EmbeddingStore>) -> Self {
self.embeddings = Some(store);
self
}
/// Attaches an optional artifact store for file/blob storage.
#[must_use]
pub fn with_artifacts(mut self, store: Box<dyn ArtifactStore>) -> Self {
self.artifacts = Some(store);
self
}
/// Returns the session store.
#[must_use]
pub fn sessions(&self) -> &dyn SessionStore {
&*self.sessions
}
/// Returns the execution store.
#[must_use]
pub fn executions(&self) -> &dyn ExecutionStore {
&*self.executions
}
/// Returns the run store.
#[must_use]
pub fn runs(&self) -> &dyn RunStore {
&*self.runs
}
/// Returns the embedding store, if configured.
#[must_use]
pub fn embeddings(&self) -> Option<&dyn EmbeddingStore> {
self.embeddings.as_deref()
}
/// Returns the artifact store, if configured.
#[must_use]
pub fn artifacts(&self) -> Option<&dyn ArtifactStore> {
self.artifacts.as_deref()
}
/// Creates a `RuntimeStore` from an [`Extensions`] facade, cloning its
/// store extension points. Backed by default in-memory stores when no
/// entries are registered.
#[must_use]
pub fn from_extensions(exts: &Extensions) -> Self {
Self {
sessions: Box::new(behest_store::memory::MemorySessionStore::new()),
executions: Box::new(behest_store::memory::MemoryExecutionStore::new()),
runs: Box::new(super::memory::MemoryRunStore::new()),
embeddings: None,
artifacts: None,
sessions_ep: exts.session_stores.clone(),
executions_ep: exts.execution_stores.clone(),
runs_ep: exts.run_stores.clone(),
embeddings_ep: exts.embedding_stores.clone(),
artifacts_ep: exts.artifact_stores.clone(),
}
}
/// Returns the session store extension point.
#[must_use]
pub fn sessions_ep(&self) -> &ExtensionPoint<dyn SessionStore> {
&self.sessions_ep
}
/// Returns the execution store extension point.
#[must_use]
pub fn executions_ep(&self) -> &ExtensionPoint<dyn ExecutionStore> {
&self.executions_ep
}
/// Returns the run store extension point.
#[must_use]
pub fn runs_ep(&self) -> &ExtensionPoint<dyn RunStore> {
&self.runs_ep
}
/// Returns the embedding store extension point.
#[must_use]
pub fn embeddings_ep(&self) -> &ExtensionPoint<dyn EmbeddingStore> {
&self.embeddings_ep
}
/// Returns the artifact store extension point.
#[must_use]
pub fn artifacts_ep(&self) -> &ExtensionPoint<dyn ArtifactStore> {
&self.artifacts_ep
}
/// Creates or loads a session.
///
/// # Errors
///
/// Returns [`RuntimeError::SessionNotFound`] when `session_id` is provided
/// but does not exist, or [`RuntimeError::Storage`] on persistence failure.
pub async fn ensure_session(&self, session_id: Option<Uuid>) -> RuntimeResult<Uuid> {
if let Some(id) = session_id {
self.sessions
.get_session(&id)
.await
.map_err(RuntimeError::from)?
.ok_or(RuntimeError::SessionNotFound(id))?;
Ok(id)
} else {
let session =
behest_store::Session::new("Agent Run", behest_provider::ModelName::new("default"));
self.sessions
.create_session(session.clone())
.await
.map_err(RuntimeError::from)?;
Ok(session.id)
}
}
/// Appends a message to a session.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] on persistence failure.
pub async fn append_message(&self, session_id: Uuid, message: &Message) -> RuntimeResult<Uuid> {
let record = message_to_record(session_id, message);
let result = self
.sessions
.append_message(record)
.await
.map_err(RuntimeError::from)?;
Ok(result.id)
}
/// Lists messages for a session.
///
/// # Errors
///
/// Returns [`RuntimeError::Storage`] on persistence failure.
pub async fn list_messages(&self, session_id: Uuid) -> RuntimeResult<Vec<Message>> {
let records = self
.sessions
.list_messages(&session_id)
.await
.map_err(RuntimeError::from)?;
Ok(records.into_iter().filter_map(record_to_message).collect())
}
}
/// Converts a provider [`Message`] to a persisted [`MessageRecord`].
///
/// Maps message role variants to their corresponding store representations,
/// preserving tool call metadata for assistant and tool messages.
fn message_to_record(session_id: Uuid, message: &Message) -> MessageRecord {
match message {
Message::System { content } => {
MessageRecord::new(session_id, MessageRole::System, content.clone())
}
Message::User { content } => {
MessageRecord::new(session_id, MessageRole::User, content.clone())
}
Message::Assistant {
content,
tool_calls,
} => MessageRecord::new(session_id, MessageRole::Assistant, content.clone())
.with_tool_calls(tool_calls.clone()),
Message::Tool {
tool_call_id,
name,
content,
} => MessageRecord::new(session_id, MessageRole::Tool, content.clone())
.with_tool_result(tool_call_id.clone(), name.clone()),
_ => MessageRecord::new(session_id, MessageRole::User, vec![]),
}
}
/// Converts a stored [`MessageRecord`] back to a provider [`Message`].
///
/// Returns `None` for unrecognized role variants. Preserves tool call IDs
/// and names for tool role messages.
#[must_use]
pub fn record_to_message(record: MessageRecord) -> Option<Message> {
match record.role {
MessageRole::System => Some(Message::System {
content: record.content,
}),
MessageRole::User => Some(Message::User {
content: record.content,
}),
MessageRole::Assistant => Some(Message::Assistant {
content: record.content,
tool_calls: record.tool_calls,
}),
MessageRole::Tool => Some(Message::Tool {
tool_call_id: record.tool_call_id.unwrap_or_default(),
name: record.tool_name.unwrap_or_default(),
content: record.content,
}),
_ => None,
}
}