Skip to main content

agent_base/engine/runtime/
mod.rs

1use std::sync::Arc;
2
3use tokio_util::sync::CancellationToken;
4
5use crate::engine::AgentSession;
6use crate::engine::session_store::SessionStore;
7use crate::types::{
8    AgentConfig, AgentError, AgentResult, CheckpointData, MessageRole, RunOutcome, RuntimeEvent,
9    SessionId, TurnContext,
10};
11
12use super::approval::ApprovalHandler;
13use crate::tool::ToolPolicy;
14
15mod event_bus;
16pub(crate) use event_bus::{EventBus, is_self_echo_user_event};
17mod llm_engine;
18mod message_queue;
19mod notify;
20mod plan_runner;
21mod react;
22mod session_manager;
23mod tool_engine;
24
25pub(super) const DEFAULT_MAX_TURNS: u32 = 160;
26
27pub use llm_engine::{LlmEngine, LlmTurnResult};
28pub use message_queue::QueueMode;
29pub use notify::NoticeHandle;
30pub(crate) use plan_runner::RuntimeCore;
31pub use session_manager::SessionManager;
32pub(crate) use tool_engine::ToolEngine;
33
34#[derive(Clone)]
35pub struct AgentRuntime {
36    pub(crate) runner: Arc<RuntimeCore>,
37}
38
39impl AgentRuntime {
40    pub async fn create_session(&self) -> SessionId {
41        let config = self.runner.config.read().await;
42        self.runner
43            .session_manager
44            .create_session(config.system_prompt.as_deref())
45            .await
46    }
47
48    pub async fn restore_session(&self, session_id: &SessionId) -> Option<AgentSession> {
49        self.runner
50            .session_manager
51            .restore_session(session_id)
52            .await
53    }
54
55    pub async fn session(&self, session_id: &SessionId) -> Option<AgentSession> {
56        self.runner.session_manager.session(session_id).await
57    }
58
59    pub async fn session_or_err(&self, session_id: &SessionId) -> AgentResult<AgentSession> {
60        self.runner.session_manager.session_or_err(session_id).await
61    }
62
63    pub async fn with_session_mut<F, R>(&self, session_id: &SessionId, f: F) -> AgentResult<R>
64    where
65        F: FnOnce(&mut AgentSession) -> R,
66    {
67        self.runner
68            .session_manager
69            .with_session_mut(session_id, f)
70            .await
71    }
72
73    /// Resume a run from a persisted checkpoint line (T5): the checkpoint's
74    /// backend pin decides which flow rebuilds history — the tool-call replay,
75    /// the mounted action backend's own protocol, or a refusal naming the
76    /// mismatch. This is the product-facing entry (crash-window recovery,
77    /// OV-11).
78    pub async fn resume_from_checkpoint<F>(
79        &self,
80        checkpoint: CheckpointData,
81        on_event: F,
82    ) -> AgentResult<RunOutcome>
83    where
84        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
85    {
86        self.runner
87            .resume_from_checkpoint(checkpoint, on_event)
88            .await
89    }
90
91    /// Publish an event on the internal event bus.
92    ///
93    /// Events land on the bus: external subscribers (`subscribe_runtime_events`)
94    /// receive them, and the run's own bus loopback delivers them to the
95    /// `on_event` callback — **except** `UserEvent`s with `agent_id: None`,
96    /// which are treated as self-echoes of events the run already rendered
97    /// (see [`is_self_echo_user_event`]). Run-local `UserEvent`s should be
98    /// published through the dual-write APIs (`PreLlmCtx::emit`,
99    /// `ToolContext::emit_user_event`, `NoticeHandle`/the notice pump) instead;
100    /// events bridged from a child agent (`with_agent_id`) reach the renderer
101    /// through this method and its loopback.
102    pub fn emit_event(&self, event: RuntimeEvent) {
103        self.runner.event_bus.emit(event);
104    }
105
106    /// Subscribe to runtime events from the internal broadcast channel.
107    ///
108    /// Events are delivered directly from the runtime's event bus (capacity 2048).
109    /// Slow consumers may receive `Lagged(n)` errors if they cannot keep up —
110    /// ensure the receiver loop processes events promptly or use a buffering
111    /// layer in the consumer if backpressure is a concern.
112    pub fn subscribe_runtime_events(&self) -> tokio::sync::broadcast::Receiver<RuntimeEvent> {
113        self.runner.event_bus.subscribe()
114    }
115
116    pub fn session_manager(&self) -> &SessionManager {
117        &self.runner.session_manager
118    }
119
120    pub fn llm_engine(&self) -> &LlmEngine {
121        &self.runner.llm_engine
122    }
123
124    pub fn provider(&self) -> Arc<dyn llm_trait::LlmProvider> {
125        self.runner.llm_engine.get_provider()
126    }
127
128    /// Replace the LLM provider at runtime (e.g., model switch).
129    /// Requires `&mut self` — obtain via `runtime.lock().await`.
130    pub fn set_client(&mut self, provider: Arc<dyn llm_trait::LlmProvider>) {
131        self.runner.llm_engine.set_provider(provider);
132    }
133
134    /// Get the model override, if set.
135    pub fn get_model_override(&self) -> Option<String> {
136        self.runner.llm_engine.get_model_override()
137    }
138
139    /// Set a model override for all requests.
140    ///
141    /// This is used by sub-agents to specify their model tier (e.g., "lite").
142    /// The override is applied to all ChatRequests before sending to the provider.
143    pub fn set_model_override(&self, model: Option<String>) {
144        self.runner.llm_engine.set_model_override(model);
145    }
146
147    pub fn tools_mut(&self) -> Arc<tokio::sync::RwLock<crate::tool::ToolRegistry>> {
148        self.runner.tool_engine.tools_arc()
149    }
150
151    pub fn config(&self) -> tokio::sync::RwLockReadGuard<'_, AgentConfig> {
152        self.runner.config.blocking_read()
153    }
154
155    /// Snapshot the configured system prompt (async — safe to call inside a
156    /// runtime, unlike [`Self::config`]).
157    pub async fn system_prompt(&self) -> Option<String> {
158        self.runner.config.read().await.system_prompt.clone()
159    }
160
161    /// Set the reasoning effort (async version)
162    pub async fn set_reasoning_effort(&self, effort: crate::llm::ReasoningEffort) {
163        let mut config = self.runner.config.write().await;
164        let mut reasoning = config.reasoning.take().unwrap_or_default();
165        reasoning.effort = Some(effort);
166        config.reasoning = Some(reasoning);
167    }
168
169    /// Set the reasoning effort (sync version, only for use in synchronous contexts)
170    pub fn set_reasoning_effort_sync(&self, effort: crate::llm::ReasoningEffort) {
171        let mut config = self.runner.config.blocking_write();
172        let mut reasoning = config.reasoning.take().unwrap_or_default();
173        reasoning.effort = Some(effort);
174        config.reasoning = Some(reasoning);
175    }
176
177    pub fn approval_handler(&self) -> Option<&Arc<dyn ApprovalHandler>> {
178        self.runner.tool_engine.approval_handler()
179    }
180
181    pub fn tool_policy(&self) -> Option<&Arc<dyn ToolPolicy>> {
182        self.runner.tool_engine.tool_policy()
183    }
184
185    pub async fn cached_approval(&self, session_id: &SessionId, action_key: &str) -> bool {
186        self.runner
187            .session_manager
188            .cached_approval(session_id, action_key)
189            .await
190    }
191
192    pub async fn cache_approval(&self, session_id: &SessionId, action_key: String) {
193        self.runner
194            .session_manager
195            .cache_approval(session_id, action_key)
196            .await
197    }
198
199    pub async fn save_checkpoint(
200        &self,
201        session_id: &SessionId,
202        checkpoint: CheckpointData,
203    ) -> AgentResult<()> {
204        self.emit_event(RuntimeEvent::Checkpoint {
205            session_id: session_id.clone(),
206            checkpoint: Box::new(checkpoint),
207            agent_id: None,
208            trace_id: None,
209        });
210        Ok(())
211    }
212
213    pub async fn load_checkpoint(
214        &self,
215        _session_id: &SessionId,
216        _checkpoint: &CheckpointData,
217    ) -> AgentResult<Option<CheckpointData>> {
218        Ok(None)
219    }
220
221    pub async fn run<F>(&self, session_id: SessionId, on_event: F) -> AgentResult<RunOutcome>
222    where
223        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
224    {
225        self.runner.run(session_id, on_event).await
226    }
227
228    pub async fn run_turn<F>(
229        &self,
230        session_id: SessionId,
231        user_input: &str,
232        on_event: F,
233    ) -> AgentResult<RunOutcome>
234    where
235        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
236    {
237        self.runner.run_turn(session_id, user_input, on_event).await
238    }
239
240    /// Like `run_turn`, but the user input is pushed as an ephemeral message:
241    /// visible to the LLM for this turn only, auto-removed at turn end.
242    pub async fn run_turn_ephemeral_input<F>(
243        &self,
244        session_id: SessionId,
245        user_input: &str,
246        on_event: F,
247    ) -> AgentResult<RunOutcome>
248    where
249        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
250    {
251        self.runner
252            .run_turn_ephemeral_input(session_id, user_input, on_event)
253            .await
254    }
255
256    pub async fn run_turn_collect(
257        &self,
258        session_id: SessionId,
259        user_input: &str,
260    ) -> AgentResult<(Vec<RuntimeEvent>, RunOutcome)> {
261        self.runner.run_turn_collect(session_id, user_input).await
262    }
263
264    pub async fn add_user_message(
265        &self,
266        session_id: &SessionId,
267        text: impl Into<String>,
268    ) -> AgentResult<()> {
269        let text = text.into();
270        self.with_session_mut(session_id, |session| {
271            session.push_message(MessageRole::User, &text);
272        })
273        .await
274    }
275
276    /// Replace the session's system prompt (the first non-ephemeral System
277    /// message). Hosts that own prompt composition re-bake through this.
278    pub async fn set_system_prompt(
279        &self,
280        session_id: &SessionId,
281        prompt: impl Into<String>,
282    ) -> AgentResult<()> {
283        let prompt = prompt.into();
284        self.with_session_mut(session_id, |session| {
285            session.set_system_prompt(prompt);
286        })
287        .await
288    }
289
290    pub async fn add_system_message(
291        &self,
292        session_id: &SessionId,
293        text: impl Into<String>,
294    ) -> AgentResult<()> {
295        let text = text.into();
296        self.with_session_mut(session_id, |session| {
297            session.push_message(MessageRole::System, &text);
298        })
299        .await
300    }
301
302    pub async fn add_tool_result(
303        &self,
304        session_id: &SessionId,
305        tool_call_id: &str,
306        summary: impl Into<String>,
307    ) -> AgentResult<()> {
308        let summary = summary.into();
309        self.with_session_mut(session_id, |session| {
310            session.push_tool_result(tool_call_id, summary.clone());
311        })
312        .await
313    }
314
315    pub async fn get_messages(
316        &self,
317        session_id: &SessionId,
318    ) -> AgentResult<Vec<crate::types::ChatMessage>> {
319        let session = self.session_or_err(session_id).await?;
320        Ok(session.chat_messages().to_vec())
321    }
322
323    /// Replace the chat messages for a session — only for persistence restore.
324    /// Validates message sequence before applying.
325    ///
326    /// For persistence restore use only.
327    pub async fn set_messages(
328        &self,
329        session_id: &SessionId,
330        messages: Vec<crate::types::ChatMessage>,
331    ) -> AgentResult<()> {
332        self.with_session_mut(session_id, |session| session.set_chat_messages(messages))
333            .await?
334            .map_err(AgentError::internal)
335    }
336
337    pub async fn validate_session(&self, session_id: &SessionId) -> AgentResult<()> {
338        if self
339            .runner
340            .session_manager
341            .session(session_id)
342            .await
343            .is_none()
344        {
345            return Err(AgentError::session_not_found(session_id.id));
346        }
347        Ok(())
348    }
349
350    pub fn session_store(&self) -> Arc<dyn SessionStore> {
351        self.runner.session_manager.session_store().clone()
352    }
353
354    // ── Observability hook ──
355
356    /// Register a turn-end callback. The callback receives a [`TurnContext`]
357    /// with raw data about the completed turn iteration. Consumers (e.g.
358    /// phi-telemetry) use this to build their own metrics without agent-base
359    /// knowing anything about metrics.
360    pub fn on_turn_end<F>(&self, f: F)
361    where
362        F: Fn(&TurnContext) + Send + Sync + 'static,
363    {
364        self.runner
365            .turn_end_callbacks
366            .write()
367            .unwrap()
368            .push(Arc::new(f));
369    }
370
371    // --- Cancellation support ---
372
373    /// Cancel the currently executing run_turn / run.
374    /// No-op if there is no current execution.
375    pub fn cancel(&self) {
376        self.runner.cancel();
377    }
378
379    /// Reset the cancel token (called automatically before each run_turn)
380    pub fn reset_cancel(&self) {
381        self.runner.reset_cancel();
382    }
383
384    /// Get a clone of the cancel token
385    pub fn cancel_token(&self) -> CancellationToken {
386        self.runner.cancel_token()
387    }
388
389    /// Check if cancellation has been requested
390    pub fn is_cancelled(&self) -> bool {
391        self.runner.is_cancelled()
392    }
393
394    // ── Message Queue (P2) ──
395
396    /// Push a steering message — will be processed at the start of the next turn
397    /// in the current `run_managed()` loop.
398    pub fn steer(&self, message: String) {
399        self.runner.message_queue.steer(message);
400    }
401
402    /// Snapshot the pending steering messages in FIFO order. A host UI's
403    /// source of truth for "what is still queued": display, take-back gating,
404    /// and turn-end flush all read the queue through here instead of keeping
405    /// a mirror that can drift from the real drains.
406    pub fn steering_snapshot(&self) -> Vec<String> {
407        self.runner.message_queue.snapshot_steering()
408    }
409
410    /// Drain **every** pending steering message and return them in FIFO
411    /// order. Used for take-back (back into the input box) and turn-end flush
412    /// (auto-send what never reached a tool boundary).
413    pub fn take_steering(&self) -> Vec<String> {
414        self.runner.message_queue.take_steering()
415    }
416
417    /// Push a follow-up message — will be processed after the inner turn loop
418    /// stops naturally (no tool calls or max turns).
419    pub fn follow_up(&self, message: String) {
420        self.runner.message_queue.follow_up(message);
421    }
422
423    /// Run the agent in managed mode with message queue support.
424    ///
425    /// This wraps `run_turn()` (or `run()`) in an outer loop: after the inner
426    /// turn loop completes, any follow-up messages are drained and a new inner
427    /// loop is started. Steering messages are drained automatically at each
428    /// iteration of the inner turn loop.
429    ///
430    /// The `on_event` callback receives all events from every inner run.
431    pub async fn run_managed<F>(
432        &self,
433        session_id: SessionId,
434        user_input: &str,
435        on_event: F,
436    ) -> AgentResult<RunOutcome>
437    where
438        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
439    {
440        self.runner
441            .run_managed(session_id, user_input, on_event)
442            .await
443    }
444
445    /// Set the drain mode for the message queues.
446    pub fn set_queue_mode(&self, mode: crate::engine::runtime::message_queue::QueueMode) {
447        self.runner.message_queue.set_mode(mode);
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454    use crate::llm::ReasoningEffort;
455    use crate::types::{ChatMessage, RuntimeEvent, SessionId};
456    use async_trait::async_trait;
457    use llm_trait::{Capabilities, ChatRequest, ChatResponse, ChatStream, LlmError, ProviderInfo};
458
459    struct StubProvider;
460
461    #[async_trait]
462    impl llm_trait::LlmProvider for StubProvider {
463        async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
464            Ok(ChatStream::new(Box::pin(futures_util::stream::empty())))
465        }
466
467        async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
468            Ok(ChatResponse {
469                content: String::new(),
470                reasoning_content: None,
471                tool_calls: vec![],
472                usage: Default::default(),
473                finish_reason: llm_trait::FinishReason::Stop,
474                raw: None,
475                thinking_signature: None,
476            })
477        }
478
479        fn capabilities(&self) -> Capabilities {
480            Capabilities::default()
481        }
482
483        fn info(&self) -> ProviderInfo {
484            ProviderInfo {
485                name: "stub".to_string(),
486                model: "stub".to_string(),
487                version: None,
488            }
489        }
490    }
491
492    fn runtime() -> AgentRuntime {
493        crate::engine::AgentBuilder::new(Arc::new(StubProvider))
494            .build()
495            .unwrap()
496    }
497
498    #[tokio::test]
499    async fn create_session_and_lookup() {
500        let rt = runtime();
501        let id = rt.create_session().await;
502        // Default numbering is process-global (a host and its sub-agents are
503        // several engines in one process; per-engine counters handed all of
504        // them a "1"), so the number itself is not the invariant — a runtime's
505        // own sessions are distinct and findable.
506        let other = rt.create_session().await;
507        assert_ne!(id.id, other.id);
508        assert!(rt.session(&id).await.is_some());
509        assert!(rt.session_or_err(&id).await.is_ok());
510    }
511
512    #[tokio::test]
513    async fn add_messages_and_get() {
514        let rt = runtime();
515        let id = rt.create_session().await;
516        rt.add_system_message(&id, "sys").await.unwrap();
517        rt.add_user_message(&id, "hello").await.unwrap();
518        let msgs = rt.get_messages(&id).await.unwrap();
519        assert_eq!(msgs.len(), 2);
520        assert!(matches!(msgs[0], ChatMessage::System { .. }));
521        assert!(matches!(msgs[1], ChatMessage::User { .. }));
522    }
523
524    #[tokio::test]
525    async fn add_tool_result_appends_tool_message() {
526        let rt = runtime();
527        let id = rt.create_session().await;
528        rt.add_tool_result(&id, "call_1", "done").await.unwrap();
529        let msgs = rt.get_messages(&id).await.unwrap();
530        assert_eq!(msgs.len(), 1);
531        assert!(matches!(msgs[0], ChatMessage::Tool { .. }));
532    }
533
534    #[tokio::test]
535    async fn set_messages_replaces_history() {
536        let rt = runtime();
537        let id = rt.create_session().await;
538        rt.add_user_message(&id, "old").await.unwrap();
539        rt.set_messages(
540            &id,
541            vec![ChatMessage::system("sys"), ChatMessage::user("new")],
542        )
543        .await
544        .unwrap();
545        let msgs = rt.get_messages(&id).await.unwrap();
546        assert_eq!(msgs.len(), 2);
547    }
548
549    #[tokio::test]
550    async fn validate_session_errors_for_unknown() {
551        let rt = runtime();
552        let id = rt.create_session().await;
553        assert!(rt.validate_session(&id).await.is_ok());
554        let err = rt.validate_session(&SessionId::new(999)).await.unwrap_err();
555        assert!(matches!(err, AgentError::SessionNotFound(_)));
556    }
557
558    #[test]
559    fn config_and_set_reasoning_effort() {
560        let rt = runtime();
561        assert!(rt.config().system_prompt.is_none());
562
563        rt.set_reasoning_effort_sync(ReasoningEffort::High);
564        let cfg = rt.config();
565        let effort = cfg.reasoning.as_ref().and_then(|r| r.effort.as_ref());
566        assert!(matches!(effort, Some(ReasoningEffort::High)));
567    }
568
569    #[tokio::test]
570    async fn session_store_is_available() {
571        let rt = runtime();
572        assert!(rt.session_store().list().await.unwrap().is_empty());
573    }
574
575    #[tokio::test]
576    async fn emit_and_subscribe_event() {
577        let rt = runtime();
578        let mut rx = rt.subscribe_runtime_events();
579        rt.emit_event(RuntimeEvent::TextDelta {
580            session_id: SessionId::new(1),
581            text: "hi".into(),
582            agent_id: None,
583            trace_id: None,
584        });
585        let ev = rx.recv().await.unwrap();
586        assert!(matches!(ev, RuntimeEvent::TextDelta { .. }));
587    }
588
589    #[tokio::test]
590    async fn cancel_reset_and_is_cancelled() {
591        let rt = runtime();
592        assert!(!rt.is_cancelled());
593        rt.cancel();
594        assert!(rt.is_cancelled());
595        rt.reset_cancel();
596        assert!(!rt.is_cancelled());
597    }
598}