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, ProviderHandle};
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_with_images<F>(
243 &self,
244 session_id: SessionId,
245 user_input: &str,
246 images: Vec<crate::types::ImageAttachment>,
247 on_event: F,
248 ) -> AgentResult<RunOutcome>
249 where
250 F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
251 {
252 self.runner
253 .run_turn_with_images(session_id, user_input, images, on_event)
254 .await
255 }
256
257 pub async fn run_turn_ephemeral_input<F>(
260 &self,
261 session_id: SessionId,
262 user_input: &str,
263 on_event: F,
264 ) -> AgentResult<RunOutcome>
265 where
266 F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
267 {
268 self.runner
269 .run_turn_ephemeral_input(session_id, user_input, on_event)
270 .await
271 }
272
273 pub async fn run_turn_synthetic_input<F>(
277 &self,
278 session_id: SessionId,
279 user_input: &str,
280 on_event: F,
281 ) -> AgentResult<RunOutcome>
282 where
283 F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
284 {
285 self.runner
286 .run_turn_synthetic_input(session_id, user_input, on_event)
287 .await
288 }
289
290 pub async fn run_turn_collect(
291 &self,
292 session_id: SessionId,
293 user_input: &str,
294 ) -> AgentResult<(Vec<RuntimeEvent>, RunOutcome)> {
295 self.runner.run_turn_collect(session_id, user_input).await
296 }
297
298 pub async fn add_user_message(
299 &self,
300 session_id: &SessionId,
301 text: impl Into<String>,
302 ) -> AgentResult<()> {
303 let text = text.into();
304 self.with_session_mut(session_id, |session| {
305 session.push_message(MessageRole::User, &text);
306 })
307 .await
308 }
309
310 pub async fn set_system_prompt(
313 &self,
314 session_id: &SessionId,
315 prompt: impl Into<String>,
316 ) -> AgentResult<()> {
317 let prompt = prompt.into();
318 self.with_session_mut(session_id, |session| {
319 session.set_system_prompt(prompt);
320 })
321 .await
322 }
323
324 pub async fn add_system_message(
325 &self,
326 session_id: &SessionId,
327 text: impl Into<String>,
328 ) -> AgentResult<()> {
329 let text = text.into();
330 self.with_session_mut(session_id, |session| {
331 session.push_message(MessageRole::System, &text);
332 })
333 .await
334 }
335
336 pub async fn add_tool_result(
337 &self,
338 session_id: &SessionId,
339 tool_call_id: &str,
340 summary: impl Into<String>,
341 ) -> AgentResult<()> {
342 let summary = summary.into();
343 self.with_session_mut(session_id, |session| {
344 session.push_tool_result(tool_call_id, summary.clone());
345 })
346 .await
347 }
348
349 pub async fn get_messages(
350 &self,
351 session_id: &SessionId,
352 ) -> AgentResult<Vec<crate::types::ChatMessage>> {
353 let session = self.session_or_err(session_id).await?;
354 Ok(session.chat_messages().to_vec())
355 }
356
357 pub async fn set_messages(
362 &self,
363 session_id: &SessionId,
364 messages: Vec<crate::types::ChatMessage>,
365 ) -> AgentResult<()> {
366 self.with_session_mut(session_id, |session| session.set_chat_messages(messages))
367 .await?
368 .map_err(AgentError::internal)
369 }
370
371 pub async fn validate_session(&self, session_id: &SessionId) -> AgentResult<()> {
372 if self
373 .runner
374 .session_manager
375 .session(session_id)
376 .await
377 .is_none()
378 {
379 return Err(AgentError::session_not_found(session_id.id));
380 }
381 Ok(())
382 }
383
384 pub fn session_store(&self) -> Arc<dyn SessionStore> {
385 self.runner.session_manager.session_store().clone()
386 }
387
388 pub fn on_turn_end<F>(&self, f: F)
395 where
396 F: Fn(&TurnContext) + Send + Sync + 'static,
397 {
398 self.runner
399 .turn_end_callbacks
400 .write()
401 .unwrap()
402 .push(Arc::new(f));
403 }
404
405 pub fn cancel(&self) {
410 self.runner.cancel();
411 }
412
413 pub fn reset_cancel(&self) {
415 self.runner.reset_cancel();
416 }
417
418 pub fn cancel_token(&self) -> CancellationToken {
420 self.runner.cancel_token()
421 }
422
423 pub fn is_cancelled(&self) -> bool {
425 self.runner.is_cancelled()
426 }
427
428 pub fn steer(&self, message: String) {
433 self.runner.message_queue.steer(message);
434 }
435
436 pub fn steering_snapshot(&self) -> Vec<String> {
441 self.runner.message_queue.snapshot_steering()
442 }
443
444 pub fn take_steering(&self) -> Vec<String> {
448 self.runner.message_queue.take_steering()
449 }
450
451 pub fn follow_up(&self, message: String) {
454 self.runner.message_queue.follow_up(message);
455 }
456
457 pub async fn run_managed<F>(
466 &self,
467 session_id: SessionId,
468 user_input: &str,
469 on_event: F,
470 ) -> AgentResult<RunOutcome>
471 where
472 F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
473 {
474 self.runner
475 .run_managed(session_id, user_input, on_event)
476 .await
477 }
478
479 pub fn set_queue_mode(&self, mode: crate::engine::runtime::message_queue::QueueMode) {
481 self.runner.message_queue.set_mode(mode);
482 }
483}
484
485#[cfg(test)]
486mod tests {
487 use super::*;
488 use crate::llm::ReasoningEffort;
489 use crate::types::{ChatMessage, RuntimeEvent, SessionId};
490 use async_trait::async_trait;
491 use llm_trait::{Capabilities, ChatRequest, ChatResponse, ChatStream, LlmError, ProviderInfo};
492
493 struct StubProvider;
494
495 #[async_trait]
496 impl llm_trait::LlmProvider for StubProvider {
497 async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
498 Ok(ChatStream::new(Box::pin(futures_util::stream::empty())))
499 }
500
501 async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
502 Ok(ChatResponse {
503 content: String::new(),
504 reasoning_content: None,
505 tool_calls: vec![],
506 usage: Default::default(),
507 finish_reason: llm_trait::FinishReason::Stop,
508 raw: None,
509 thinking_signature: None,
510 })
511 }
512
513 fn capabilities(&self) -> Capabilities {
514 Capabilities::default()
515 }
516
517 fn info(&self) -> ProviderInfo {
518 ProviderInfo {
519 name: "stub".to_string(),
520 model: "stub".to_string(),
521 version: None,
522 }
523 }
524 }
525
526 fn runtime() -> AgentRuntime {
527 crate::engine::AgentBuilder::new(Arc::new(StubProvider))
528 .build()
529 .unwrap()
530 }
531
532 #[tokio::test]
533 async fn create_session_and_lookup() {
534 let rt = runtime();
535 let id = rt.create_session().await;
536 let other = rt.create_session().await;
541 assert_ne!(id.id, other.id);
542 assert!(rt.session(&id).await.is_some());
543 assert!(rt.session_or_err(&id).await.is_ok());
544 }
545
546 #[tokio::test]
547 async fn add_messages_and_get() {
548 let rt = runtime();
549 let id = rt.create_session().await;
550 rt.add_system_message(&id, "sys").await.unwrap();
551 rt.add_user_message(&id, "hello").await.unwrap();
552 let msgs = rt.get_messages(&id).await.unwrap();
553 assert_eq!(msgs.len(), 2);
554 assert!(matches!(msgs[0], ChatMessage::System { .. }));
555 assert!(matches!(msgs[1], ChatMessage::User { .. }));
556 }
557
558 #[tokio::test]
559 async fn add_tool_result_appends_tool_message() {
560 let rt = runtime();
561 let id = rt.create_session().await;
562 rt.add_tool_result(&id, "call_1", "done").await.unwrap();
563 let msgs = rt.get_messages(&id).await.unwrap();
564 assert_eq!(msgs.len(), 1);
565 assert!(matches!(msgs[0], ChatMessage::Tool { .. }));
566 }
567
568 #[tokio::test]
569 async fn set_messages_replaces_history() {
570 let rt = runtime();
571 let id = rt.create_session().await;
572 rt.add_user_message(&id, "old").await.unwrap();
573 rt.set_messages(
574 &id,
575 vec![ChatMessage::system("sys"), ChatMessage::user("new")],
576 )
577 .await
578 .unwrap();
579 let msgs = rt.get_messages(&id).await.unwrap();
580 assert_eq!(msgs.len(), 2);
581 }
582
583 #[tokio::test]
584 async fn validate_session_errors_for_unknown() {
585 let rt = runtime();
586 let id = rt.create_session().await;
587 assert!(rt.validate_session(&id).await.is_ok());
588 let err = rt.validate_session(&SessionId::new(999)).await.unwrap_err();
589 assert!(matches!(err, AgentError::SessionNotFound(_)));
590 }
591
592 #[test]
593 fn config_and_set_reasoning_effort() {
594 let rt = runtime();
595 assert!(rt.config().system_prompt.is_none());
596
597 rt.set_reasoning_effort_sync(ReasoningEffort::High);
598 let cfg = rt.config();
599 let effort = cfg.reasoning.as_ref().and_then(|r| r.effort.as_ref());
600 assert!(matches!(effort, Some(ReasoningEffort::High)));
601 }
602
603 #[tokio::test]
604 async fn session_store_is_available() {
605 let rt = runtime();
606 assert!(rt.session_store().list().await.unwrap().is_empty());
607 }
608
609 #[tokio::test]
610 async fn emit_and_subscribe_event() {
611 let rt = runtime();
612 let mut rx = rt.subscribe_runtime_events();
613 rt.emit_event(RuntimeEvent::TextDelta {
614 session_id: SessionId::new(1),
615 text: "hi".into(),
616 agent_id: None,
617 trace_id: None,
618 });
619 let ev = rx.recv().await.unwrap();
620 assert!(matches!(ev, RuntimeEvent::TextDelta { .. }));
621 }
622
623 #[tokio::test]
624 async fn cancel_reset_and_is_cancelled() {
625 let rt = runtime();
626 assert!(!rt.is_cancelled());
627 rt.cancel();
628 assert!(rt.is_cancelled());
629 rt.reset_cancel();
630 assert!(!rt.is_cancelled());
631 }
632}