rig_agent/run/committed.rs
1//! The run's append-only history, and the one pure projection of its tool
2//! calls and results that the engine and a foreign host both stream.
3
4use std::sync::Arc;
5
6use rig_core::completion::Message;
7use rig_core::message::{AssistantContent, ToolCall, ToolResult, UserContent};
8use serde::{Deserialize, Serialize};
9
10/// The run's history: the prompt and every message a turn commits after it.
11/// Only appends; the single in-place edit is the not-yet-sent prompt.
12#[derive(Debug, Clone, Serialize, Deserialize)]
13#[serde(transparent)]
14pub(crate) struct CommittedLog(Vec<Arc<Message>>);
15
16impl CommittedLog {
17 pub(crate) fn new(prompt: Message) -> Self {
18 Self(vec![Arc::new(prompt)])
19 }
20
21 pub(crate) fn commit(&mut self, messages: impl IntoIterator<Item = Message>) {
22 self.0.extend(messages.into_iter().map(Arc::new));
23 }
24
25 /// The prompt while it is the only message, before any turn committed
26 /// anything after it.
27 pub(crate) fn unstarted_prompt(&mut self) -> Option<&mut Arc<Message>> {
28 match self.0.as_mut_slice() {
29 [slot] => Some(slot),
30 _ => None,
31 }
32 }
33}
34
35impl std::ops::Deref for CommittedLog {
36 type Target = [Arc<Message>];
37
38 fn deref(&self) -> &[Arc<Message>] {
39 &self.0
40 }
41}
42
43/// A tool call or result committed to a run's history, in commit order.
44#[derive(Debug, Clone, Copy, PartialEq)]
45#[non_exhaustive]
46pub enum CommittedItem<'a> {
47 /// An assistant tool call.
48 ToolCall(&'a ToolCall),
49 /// A user tool result answering a call.
50 ToolResult(&'a ToolResult),
51}
52
53/// Every tool call and tool result in `committed`, in message order; all
54/// other content yields nothing.
55///
56/// Pure and sans-IO. A driver keeps a cursor, starting at
57/// [`AgentRun::projection_start`](super::AgentRun::projection_start), and
58/// after each protocol call projects the messages past it and moves it to the
59/// end. Outside a pending
60/// [`CallTools`](super::AgentRunStep::CallTools) batch every projected call
61/// has a projected result: a final output-tool turn is committed without its
62/// call, and an output reprompt commits the call with its feedback result.
63///
64/// ```
65/// use rig_agent::run::{AgentRun, CommittedItem, project};
66/// let run = AgentRun::new("hi");
67/// let cursor = run.projection_start(); // then drive one protocol call
68/// for item in project(&run.messages()[cursor..]) {
69/// if let CommittedItem::ToolResult(result) = item {
70/// println!("result for {}", result.call);
71/// }
72/// }
73/// ```
74pub fn project(committed: &[Arc<Message>]) -> impl Iterator<Item = CommittedItem<'_>> {
75 committed.iter().flat_map(|message| {
76 let (calls, results): (&[AssistantContent], &[UserContent]) = match &**message {
77 Message::Assistant(assistant) => (&assistant.content, &[]),
78 Message::User { content } => (&[], content),
79 Message::System { .. } => (&[], &[]),
80 };
81 let calls = calls
82 .iter()
83 .filter_map(AssistantContent::as_tool_call)
84 .map(CommittedItem::ToolCall);
85 let results = results.iter().filter_map(UserContent::as_tool_result);
86 calls.chain(results.map(CommittedItem::ToolResult))
87 })
88}
89
90#[cfg(test)]
91mod tests;