Skip to main content

oi_kit_agent/
operation.rs

1use anyhow::{anyhow, Result};
2use async_trait::async_trait;
3use futures::Stream;
4use std::future::Future;
5use std::pin::Pin;
6use tokio::sync::mpsc;
7use tokio_util::sync::CancellationToken;
8
9use crate::command::Command;
10use crate::events::AgentEvent;
11use oi_kit_provider_types::conversation::message::{Message, MessageContent, MessageErrorKind};
12use oi_kit_provider_types::conversation::{effective_role, Conversation, EffectiveRole};
13use oi_kit_provider_types::maybe_send::{MaybeSend, MaybeSync};
14use rmcp::model::Tool;
15
16#[cfg(not(target_arch = "wasm32"))]
17pub type OperationFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
18
19#[cfg(target_arch = "wasm32")]
20pub type OperationFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
21
22#[cfg(not(target_arch = "wasm32"))]
23pub type OperationStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
24
25#[cfg(target_arch = "wasm32")]
26pub type OperationStream<'a, T> = Pin<Box<dyn Stream<Item = T> + 'a>>;
27
28pub const CLIENT_LOG: &str = "client_log";
29
30pub fn messages_since_kickoff(conversation: &Conversation) -> Result<&[Message]> {
31    let messages = conversation.messages();
32    let is_kickoff = |msg: &Message| msg.role == rmcp::model::Role::User && !msg.is_tool_response();
33    let start = messages
34        .iter()
35        .rposition(|msg| is_kickoff(msg) && msg.is_user_visible())
36        .or_else(|| {
37            messages
38                .iter()
39                .rposition(|msg| is_kickoff(msg) && msg.is_agent_visible())
40        })
41        .ok_or_else(|| anyhow!("state machine conversation has no kickoff message"))?;
42    Ok(&messages[start..])
43}
44
45pub fn trailing_error(conversation: &Conversation) -> Option<MessageErrorKind> {
46    conversation.last().and_then(Message::error_kind)
47}
48
49pub fn last_effective_role(messages: &[Message]) -> Result<EffectiveRole> {
50    messages
51        .last()
52        .map(effective_role)
53        .ok_or_else(|| anyhow!("cannot determine the role of an empty conversation"))
54}
55
56/// Messages hidden from both audiences (an archived in-band compaction
57/// exchange) have left the conversation and are not actions the agent took.
58pub fn assistant_turn_count(messages: &[Message]) -> u32 {
59    let mut turns = 0;
60    let mut in_assistant_block = false;
61    for message in messages
62        .iter()
63        .rev()
64        .filter(|message| message.is_user_visible() || message.is_agent_visible())
65    {
66        if message.role == rmcp::model::Role::Assistant {
67            if !in_assistant_block {
68                turns += 1;
69                in_assistant_block = true;
70            }
71        } else {
72            in_assistant_block = false;
73        }
74    }
75    turns
76}
77
78pub fn ends_turn(messages: &[Message]) -> bool {
79    messages.last().is_some_and(|last| {
80        last.role == rmcp::model::Role::Assistant
81            && last.error_kind().is_none()
82            && !last.content.iter().any(|content| {
83                matches!(
84                    content,
85                    MessageContent::ToolRequest(_) | MessageContent::ActionRequired(_)
86                )
87            })
88    })
89}
90
91#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
92#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
93pub trait Operation<S, E: MaybeSend + 'static = ConversationEffect>: MaybeSend + MaybeSync {
94    fn name(&self) -> &'static str;
95
96    /// Note on a message something this operation did, so that a pipeline rebuilt
97    /// from the persisted conversation reaches the same conclusion. Notes record
98    /// past actions only — anything an operation would have to compute again does
99    /// not belong here.
100    fn set_message_meta(&self, message: &mut Message, key: &str, value: serde_json::Value) {
101        message.metadata.set_operation_note(self.name(), key, value);
102    }
103
104    fn message_meta<'a>(&self, message: &'a Message, key: &str) -> Option<&'a serde_json::Value> {
105        message.metadata.operation_note(self.name(), key)
106    }
107
108    async fn finalize_cancellation(
109        &self,
110        _session: &S,
111        _conversation: &Conversation,
112        _emit: &Emitter,
113    ) -> Vec<E> {
114        Vec::new()
115    }
116
117    async fn commands(&self, _session: &S) -> Result<Vec<Command<'_, S, E>>> {
118        Ok(Vec::new())
119    }
120
121    async fn inference_tools(&self, _session: &S) -> Result<Vec<Tool>> {
122        Ok(Vec::new())
123    }
124
125    async fn prompt_parts(
126        &self,
127        _session: &S,
128        _conversation: &Conversation,
129    ) -> Result<Vec<(String, String)>> {
130        Ok(Vec::new())
131    }
132
133    async fn moim_parts(&self, _session: &S, _conversation: &Conversation) -> Result<Vec<String>> {
134        Ok(Vec::new())
135    }
136
137    async fn run(
138        &self,
139        _session: &S,
140        _conversation: &Conversation,
141        _emit: &Emitter,
142    ) -> Result<OperationResult<E>> {
143        not_applicable()
144    }
145}
146
147#[derive(Default)]
148pub struct InferenceInput {
149    pub tools: Vec<Tool>,
150    pub prompt_parts: Vec<(String, String)>,
151    pub moim_parts: Vec<String>,
152}
153
154#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
155#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
156pub trait Inference<S, E: MaybeSend + 'static = ConversationEffect>: Operation<S, E> {
157    /// Whether the next step would reach the provider. When it would not, the
158    /// machine skips inference and moves on to the next step.
159    fn applies(&self, conversation: &Conversation) -> bool;
160
161    async fn prepare_session(&self, _session: &S) -> Result<Option<S>> {
162        Ok(None)
163    }
164
165    async fn infer(
166        &self,
167        session: &S,
168        conversation: &Conversation,
169        input: InferenceInput,
170        emit: &Emitter,
171    ) -> Result<OperationResult<E>>;
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub enum RunStatus {
176    Continuing,
177    Yielded,
178    Cancelled,
179}
180
181pub struct StepResult<E = ConversationEffect> {
182    pub effects: Vec<E>,
183    pub applied_step: Option<&'static str>,
184    pub status: RunStatus,
185}
186
187pub enum OperationResult<E = ConversationEffect> {
188    NotApplicable,
189    Applied(StepResult<E>),
190}
191
192pub fn not_applicable<E>() -> Result<OperationResult<E>> {
193    Ok(OperationResult::NotApplicable)
194}
195
196pub fn applied<E>(effects: impl IntoIterator<Item = E>) -> Result<OperationResult<E>> {
197    Ok(OperationResult::Applied(StepResult {
198        effects: effects.into_iter().collect(),
199        applied_step: None,
200        status: RunStatus::Continuing,
201    }))
202}
203
204pub fn yielded<E>() -> Result<OperationResult<E>> {
205    Ok(OperationResult::Applied(StepResult {
206        effects: Vec::new(),
207        applied_step: None,
208        status: RunStatus::Yielded,
209    }))
210}
211
212pub fn yielded_with<E>(effects: impl IntoIterator<Item = E>) -> Result<OperationResult<E>> {
213    Ok(OperationResult::Applied(StepResult {
214        effects: effects.into_iter().collect(),
215        applied_step: None,
216        status: RunStatus::Yielded,
217    }))
218}
219
220pub trait MachineEffect {
221    fn ensure_message_ids(&mut self);
222}
223
224pub enum ConversationEffect {
225    AppendMessage(Message),
226    ReplaceConversation(Conversation),
227    PatchToolRequestMeta {
228        tool_call_id: String,
229        patch: serde_json::Value,
230    },
231    SetMessageOperationNote {
232        message_id: String,
233        operation: String,
234        key: String,
235        value: serde_json::Value,
236    },
237    SetMessageVisibility {
238        message_id: String,
239        user_visible: bool,
240        agent_visible: bool,
241    },
242}
243
244impl MachineEffect for ConversationEffect {
245    fn ensure_message_ids(&mut self) {
246        let messages = match self {
247            ConversationEffect::AppendMessage(message) => std::slice::from_mut(message),
248            ConversationEffect::ReplaceConversation(conversation) => {
249                conversation.messages_mut().as_mut_slice()
250            }
251            _ => return,
252        };
253        for message in messages {
254            if message.id.is_none() {
255                message.id = Some(format!("msg_{}", uuid::Uuid::new_v4()));
256            }
257        }
258    }
259}
260
261impl From<Message> for ConversationEffect {
262    fn from(message: Message) -> Self {
263        ConversationEffect::AppendMessage(message)
264    }
265}
266
267impl From<Conversation> for ConversationEffect {
268    fn from(conversation: Conversation) -> Self {
269        ConversationEffect::ReplaceConversation(conversation)
270    }
271}
272
273pub struct Emitter {
274    tx: mpsc::UnboundedSender<AgentEvent>,
275    cancel: CancellationToken,
276}
277
278impl Emitter {
279    pub fn new(tx: mpsc::UnboundedSender<AgentEvent>, cancel: CancellationToken) -> Self {
280        Self { tx, cancel }
281    }
282
283    pub fn emit(&self, event: AgentEvent) {
284        let _ = self.tx.send(event);
285    }
286
287    pub fn message(&self, message: Message) -> Message {
288        let message = message.with_generated_id_if_missing();
289        self.emit(AgentEvent::Message(message.clone()));
290        message
291    }
292
293    pub fn cancel_token(&self) -> &CancellationToken {
294        &self.cancel
295    }
296
297    pub async fn cancelled(&self) {
298        self.cancel.cancelled().await
299    }
300}