Skip to main content

oi_kit_agent/
machine.rs

1use std::{
2    collections::HashSet,
3    sync::{Arc, Mutex},
4};
5
6use anyhow::{anyhow, Result};
7use async_trait::async_trait;
8use tokio_util::sync::CancellationToken;
9
10use crate::command::Command;
11use crate::operation::{
12    messages_since_kickoff, ConversationEffect, Emitter, Inference, InferenceInput, MachineEffect,
13    Operation, OperationResult, RunStatus, StepResult,
14};
15use crate::tool_call_state::pending_tool_requests;
16use oi_kit_provider_types::conversation::message::Message;
17use oi_kit_provider_types::conversation::Conversation;
18use oi_kit_provider_types::maybe_send::{MaybeSend, MaybeSync};
19use oi_kit_provider_types::thinking::ThinkingEffort;
20
21pub trait MachineSession: MaybeSend + MaybeSync {
22    fn id(&self) -> &str;
23    fn conversation(&self) -> Option<&Conversation>;
24    fn thinking_effort(&self) -> Option<ThinkingEffort> {
25        None
26    }
27    /// The context size the provider reported for the latest request, when the
28    /// host tracks it. Compaction estimates the size itself otherwise.
29    fn reported_context_tokens(&self) -> Option<i64> {
30        None
31    }
32}
33
34#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
35#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
36pub trait SessionLoader<S>: MaybeSend + MaybeSync {
37    async fn load(&self, session_id: &str) -> Result<S>;
38}
39
40#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
41#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
42pub trait EffectHandler<S, E>: MaybeSend + MaybeSync {
43    async fn apply_effects(&self, session: &S, effects: &mut [E], emit: &Emitter) -> Result<()>;
44}
45
46pub trait EffectUsage<E>: MaybeSend + MaybeSync {
47    fn usage(
48        &self,
49        _effect: &E,
50    ) -> Option<oi_kit_provider_types::conversation::token_usage::Usage> {
51        None
52    }
53}
54
55pub enum Step<'a, S, E = ConversationEffect> {
56    Operation(Arc<dyn Operation<S, E> + 'a>),
57    Inference(Arc<dyn Inference<S, E> + 'a>),
58}
59
60impl<S, E: MaybeSend> Step<'_, S, E> {
61    fn operation(&self) -> &dyn Operation<S, E> {
62        match self {
63            Step::Operation(operation) => operation.as_ref(),
64            Step::Inference(inference) => inference.as_ref(),
65        }
66    }
67}
68
69pub struct StateMachine<'a, S, E = ConversationEffect> {
70    steps: Vec<Step<'a, S, E>>,
71    cancel: CancellationToken,
72    interrupted_step: Mutex<Option<usize>>,
73}
74
75fn empty_result<E>(status: RunStatus) -> StepResult<E> {
76    StepResult {
77        effects: Vec::new(),
78        applied_step: None,
79        status,
80    }
81}
82
83fn interrupted_tool_responses(messages: &[Message]) -> Option<Message> {
84    let mut tool_responses = Message::user();
85    for request in pending_tool_requests(messages) {
86        tool_responses.add_tool_response_with_metadata(
87            request.id.clone(),
88            Ok(rmcp::model::CallToolResult::error(vec![
89                rmcp::model::ContentBlock::text("Tool call was interrupted before completing"),
90            ])),
91            request.metadata.as_ref(),
92        );
93    }
94    (!tool_responses.content.is_empty()).then_some(tool_responses)
95}
96
97fn add_tools_to_inference_input(
98    input: &mut InferenceInput,
99    tool_names: &mut HashSet<String>,
100    tools: Vec<rmcp::model::Tool>,
101) -> Result<()> {
102    for tool in tools {
103        if !tool_names.insert(tool.name.to_string()) {
104            anyhow::bail!("multiple operations registered tool '{}'", tool.name);
105        }
106        input.tools.push(tool);
107    }
108    Ok(())
109}
110
111impl<'a, S, E> StateMachine<'a, S, E>
112where
113    S: MachineSession,
114    E: MachineEffect + From<Message> + MaybeSend + 'static,
115{
116    pub fn new(steps: Vec<Step<'a, S, E>>, cancel: CancellationToken) -> Self {
117        Self {
118            steps,
119            cancel,
120            interrupted_step: Mutex::new(None),
121        }
122    }
123
124    /// The tools and prompt contributions every operation adds to the next
125    /// request. Derived from the session and conversation, so this is safe to
126    /// call outside a turn to preview the request.
127    pub async fn collect_prompt_contributions(
128        &self,
129        session: &S,
130        conversation: &Conversation,
131    ) -> Result<InferenceInput> {
132        let mut input = InferenceInput::default();
133        let mut tool_names = HashSet::new();
134        for operation in self.steps.iter().map(|step| step.operation()) {
135            let tools = operation.inference_tools(session).await?;
136            add_tools_to_inference_input(&mut input, &mut tool_names, tools)?;
137            input
138                .prompt_parts
139                .extend(operation.prompt_parts(session, conversation).await?);
140        }
141        Ok(input)
142    }
143
144    pub async fn commands(&self, session: &S) -> Result<Vec<Command<'_, S, E>>> {
145        let mut commands = Vec::new();
146        for operation in self.steps.iter().map(|step| step.operation()) {
147            commands.extend(operation.commands(session).await?);
148        }
149        Ok(commands)
150    }
151
152    /// The prompt contributions plus the turn-context parts.
153    pub async fn collect_inference_input(
154        &self,
155        session: &S,
156        conversation: &Conversation,
157    ) -> Result<InferenceInput> {
158        let mut input = self
159            .collect_prompt_contributions(session, conversation)
160            .await?;
161        for operation in self.steps.iter().map(|step| step.operation()) {
162            input
163                .moim_parts
164                .extend(operation.moim_parts(session, conversation).await?);
165        }
166        Ok(input)
167    }
168
169    pub async fn step(&self, session: &S, emit: &Emitter) -> Result<StepResult<E>> {
170        let conversation = session
171            .conversation()
172            .ok_or_else(|| anyhow!("state-machine session loaded without conversation"))?;
173
174        for (index, step) in self.steps.iter().enumerate() {
175            let name = step.operation().name();
176            if self.cancel.is_cancelled() {
177                return Ok(empty_result(RunStatus::Cancelled));
178            }
179            let execution = async {
180                match step {
181                    Step::Operation(operation) => operation.run(session, conversation, emit).await,
182                    Step::Inference(inference) => {
183                        let prepared_session = inference.prepare_session(session).await?;
184                        let session = prepared_session.as_ref().unwrap_or(session);
185                        let conversation = session.conversation().ok_or_else(|| {
186                            anyhow!("state-machine session loaded without conversation")
187                        })?;
188                        if !inference.applies(conversation) {
189                            return Ok(OperationResult::NotApplicable);
190                        }
191                        let input = self.collect_inference_input(session, conversation).await?;
192                        inference.infer(session, conversation, input, emit).await
193                    }
194                }
195            };
196            let result = tokio::select! {
197                biased;
198                result = execution => Some(result),
199                _ = self.cancel.cancelled() => None,
200            };
201            let result = match result {
202                Some(Ok(result)) => result,
203                Some(Err(error)) if !self.cancel.is_cancelled() => return Err(error),
204                _ => {
205                    *self.interrupted_step.lock().unwrap() = Some(index);
206                    return Ok(empty_result(RunStatus::Cancelled));
207                }
208            };
209
210            match result {
211                OperationResult::NotApplicable => {}
212                OperationResult::Applied(mut result) => {
213                    tracing::debug!(step = name, "applied step");
214                    result.applied_step = Some(name);
215                    for effect in &mut result.effects {
216                        effect.ensure_message_ids();
217                    }
218                    if self.cancel.is_cancelled() {
219                        result.status = RunStatus::Cancelled;
220                    }
221                    return Ok(result);
222                }
223            }
224        }
225
226        Ok(empty_result(RunStatus::Yielded))
227    }
228
229    pub async fn apply<R>(
230        &self,
231        runtime: &R,
232        session: &S,
233        effects: &mut [E],
234        emit: &Emitter,
235    ) -> Result<()>
236    where
237        R: EffectHandler<S, E>,
238    {
239        if effects.is_empty() {
240            return Ok(());
241        }
242        for effect in effects.iter_mut() {
243            effect.ensure_message_ids();
244        }
245        runtime.apply_effects(session, effects, emit).await
246    }
247
248    pub async fn run<R>(&self, runtime: &R, session_id: &str, emit: &Emitter) -> Result<S>
249    where
250        R: SessionLoader<S> + EffectHandler<S, E>,
251    {
252        loop {
253            let session = runtime.load(session_id).await?;
254            let mut result = self.step(&session, emit).await?;
255            self.apply(runtime, &session, &mut result.effects, emit)
256                .await?;
257            match result.status {
258                RunStatus::Continuing => {}
259                RunStatus::Yielded | RunStatus::Cancelled => break,
260            }
261        }
262        self.finalize(runtime, session_id, emit).await
263    }
264
265    pub async fn finalize<R>(&self, runtime: &R, session_id: &str, emit: &Emitter) -> Result<S>
266    where
267        R: SessionLoader<S> + EffectHandler<S, E>,
268    {
269        let mut session = runtime.load(session_id).await?;
270        if !self.cancel.is_cancelled() {
271            return Ok(session);
272        }
273
274        let interrupted_step = self.interrupted_step.lock().unwrap().take();
275        if let Some(index) = interrupted_step {
276            session = self
277                .finalize_step_cancellation(runtime, session_id, session, &self.steps[index], emit)
278                .await?;
279        }
280
281        let interrupted = session
282            .conversation()
283            .and_then(|conversation| messages_since_kickoff(conversation).ok())
284            .and_then(interrupted_tool_responses);
285        if let Some(tool_responses) = interrupted {
286            let effects = vec![E::from(emit.message(tool_responses))];
287            session = self
288                .save(runtime, session_id, session, effects, emit)
289                .await?;
290        }
291
292        for (index, step) in self.steps.iter().enumerate() {
293            if Some(index) != interrupted_step {
294                session = self
295                    .finalize_step_cancellation(runtime, session_id, session, step, emit)
296                    .await?;
297            }
298        }
299        Ok(session)
300    }
301
302    async fn finalize_step_cancellation<R>(
303        &self,
304        runtime: &R,
305        session_id: &str,
306        session: S,
307        step: &Step<'a, S, E>,
308        emit: &Emitter,
309    ) -> Result<S>
310    where
311        R: SessionLoader<S> + EffectHandler<S, E>,
312    {
313        let conversation = session
314            .conversation()
315            .ok_or_else(|| anyhow!("state-machine session loaded without conversation"))?;
316        let effects = step
317            .operation()
318            .finalize_cancellation(&session, conversation, emit)
319            .await;
320        self.save(runtime, session_id, session, effects, emit).await
321    }
322
323    async fn save<R>(
324        &self,
325        runtime: &R,
326        session_id: &str,
327        session: S,
328        mut effects: Vec<E>,
329        emit: &Emitter,
330    ) -> Result<S>
331    where
332        R: SessionLoader<S> + EffectHandler<S, E>,
333    {
334        if effects.is_empty() {
335            return Ok(session);
336        }
337        self.apply(runtime, &session, &mut effects, emit).await?;
338        runtime.load(session_id).await
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345
346    #[test]
347    fn rejects_duplicate_tools_across_operations() {
348        let schema = Arc::new(serde_json::Map::new());
349        let mut input = InferenceInput::default();
350        let mut names = HashSet::new();
351
352        add_tools_to_inference_input(
353            &mut input,
354            &mut names,
355            vec![rmcp::model::Tool::new("duplicate", "first", schema.clone())],
356        )
357        .unwrap();
358        let error = add_tools_to_inference_input(
359            &mut input,
360            &mut names,
361            vec![rmcp::model::Tool::new("duplicate", "second", schema)],
362        )
363        .unwrap_err();
364
365        assert_eq!(
366            error.to_string(),
367            "multiple operations registered tool 'duplicate'"
368        );
369    }
370}