agent_base/engine/runtime/
mod.rs1use 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 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 pub fn emit_event(&self, event: RuntimeEvent) {
103 self.runner.event_bus.emit(event);
104 }
105
106 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 pub fn set_client(&mut self, provider: Arc<dyn llm_trait::LlmProvider>) {
131 self.runner.llm_engine.set_provider(provider);
132 }
133
134 pub fn get_model_override(&self) -> Option<String> {
136 self.runner.llm_engine.get_model_override()
137 }
138
139 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 pub async fn system_prompt(&self) -> Option<String> {
158 self.runner.config.read().await.system_prompt.clone()
159 }
160
161 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 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 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 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 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 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 pub fn cancel(&self) {
376 self.runner.cancel();
377 }
378
379 pub fn reset_cancel(&self) {
381 self.runner.reset_cancel();
382 }
383
384 pub fn cancel_token(&self) -> CancellationToken {
386 self.runner.cancel_token()
387 }
388
389 pub fn is_cancelled(&self) -> bool {
391 self.runner.is_cancelled()
392 }
393
394 pub fn steer(&self, message: String) {
399 self.runner.message_queue.steer(message);
400 }
401
402 pub fn steering_snapshot(&self) -> Vec<String> {
407 self.runner.message_queue.snapshot_steering()
408 }
409
410 pub fn take_steering(&self) -> Vec<String> {
414 self.runner.message_queue.take_steering()
415 }
416
417 pub fn follow_up(&self, message: String) {
420 self.runner.message_queue.follow_up(message);
421 }
422
423 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 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 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}