1use std::collections::{HashMap, HashSet};
4use std::future::Future;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::Arc;
7use std::time::Duration;
8
9use log::{error, info};
10use onde::inference::types::{format_duration, ChatMessage};
11use onde::inference::{
12 ChatEngine, EngineInfo, EngineStatus, GgufModelConfig, InferenceError, SamplingConfig,
13 ToolCallingSupport, ToolDefinition, ToolResult,
14};
15
16use crate::{
17 tool::truncate_output, AgentConfig, AgentError, AgentReply, AgentToolDefinition,
18 ApprovalDecision, ApprovalHandler, ApprovalRequest, ChatReply, DenyApprovals, EventSink,
19 NoopSink, RejectingExecutor, ToolCall, ToolExecutionResult, ToolExecutor, ToolRisk,
20};
21
22pub struct Ed<S = NoopSink> {
30 engine: ChatEngine,
31 sink: S,
32 tools: tokio::sync::RwLock<HashMap<String, AgentToolDefinition>>,
33 executor: Arc<dyn ToolExecutor>,
34 approvals: Arc<dyn ApprovalHandler>,
35 session_grants: tokio::sync::Mutex<HashSet<String>>,
36 turn: tokio::sync::Mutex<()>,
37 cancelled: AtomicBool,
38 agent_config: AgentConfig,
39}
40
41impl Ed<NoopSink> {
42 pub fn new() -> Self {
44 Self::with_sink(NoopSink)
45 }
46}
47
48impl Default for Ed<NoopSink> {
49 fn default() -> Self {
50 Self::new()
51 }
52}
53
54impl<S: EventSink> Ed<S> {
55 pub fn with_sink(sink: S) -> Self {
57 Self::with_agent(
58 sink,
59 Arc::new(RejectingExecutor),
60 Arc::new(DenyApprovals),
61 AgentConfig::default(),
62 )
63 }
64
65 pub fn with_agent(
67 sink: S,
68 executor: Arc<dyn ToolExecutor>,
69 approvals: Arc<dyn ApprovalHandler>,
70 config: AgentConfig,
71 ) -> Self {
72 Self::with_agent_and_app_id(sink, executor, approvals, config, None)
73 }
74
75 pub fn with_app_id(sink: S, onde_app_id: Option<String>) -> Self {
77 Self::with_agent_and_app_id(
78 sink,
79 Arc::new(RejectingExecutor),
80 Arc::new(DenyApprovals),
81 AgentConfig::default(),
82 onde_app_id,
83 )
84 }
85
86 pub fn with_agent_and_app_id(
92 sink: S,
93 executor: Arc<dyn ToolExecutor>,
94 approvals: Arc<dyn ApprovalHandler>,
95 config: AgentConfig,
96 onde_app_id: Option<String>,
97 ) -> Self {
98 Self {
99 engine: ChatEngine::with_app_id(onde_app_id),
100 sink,
101 tools: tokio::sync::RwLock::new(HashMap::new()),
102 executor,
103 approvals,
104 session_grants: tokio::sync::Mutex::new(HashSet::new()),
105 turn: tokio::sync::Mutex::new(()),
106 cancelled: AtomicBool::new(false),
107 agent_config: config.validated(),
108 }
109 }
110
111 pub fn engine(&self) -> &ChatEngine {
118 &self.engine
119 }
120
121 pub async fn load_with<'a, F, Fut>(
153 &'a self,
154 model_name: &str,
155 load: F,
156 ) -> Result<Duration, InferenceError>
157 where
158 F: FnOnce(&'a ChatEngine) -> Fut,
159 Fut: Future<Output = Result<Duration, InferenceError>>,
160 {
161 info!("ed: loading model {model_name}");
162 self.sink
163 .status_changed(EngineStatus::Loading, Some(model_name), None);
164
165 match load(&self.engine).await {
166 Ok(elapsed) => {
167 info!("ed: loaded {model_name} in {}", format_duration(elapsed));
168 self.sink
169 .status_changed(EngineStatus::Ready, Some(model_name), None);
170 Ok(elapsed)
171 }
172 Err(err) => {
173 error!("ed: failed to load {model_name}: {err}");
174 let message = err.to_string();
175 self.sink
176 .status_changed(EngineStatus::Error, Some(model_name), Some(&message));
177 Err(err)
178 }
179 }
180 }
181
182 pub async fn load(
188 &self,
189 config: GgufModelConfig,
190 system_prompt: Option<String>,
191 sampling: Option<SamplingConfig>,
192 ) -> Result<Duration, InferenceError> {
193 let model_name = config.display_name.clone();
194 self.load_with(&model_name, |engine| {
195 engine.load_gguf_model(config, system_prompt, sampling)
196 })
197 .await
198 }
199
200 pub async fn unload(&self) -> Option<String> {
202 let unloaded = self.engine.unload_model().await;
203 if let Some(name) = &unloaded {
204 info!("ed: unloaded {name}");
205 }
206 self.sink
207 .status_changed(EngineStatus::Unloaded, unloaded.as_deref(), None);
208 unloaded
209 }
210
211 pub async fn send(&self, message: impl Into<String>) -> ChatReply {
218 let reply = match self.engine.send_message(message).await {
219 Ok(result) => ChatReply::ok(result.text, result.duration_display),
220 Err(err) => {
221 error!("ed: inference failed: {err}");
222 ChatReply::failed(err)
223 }
224 };
225 self.sink.replied(&reply);
226 reply
227 }
228
229 pub async fn register_tool(&self, tool: AgentToolDefinition) -> Result<(), AgentError> {
231 tool.validate()?;
232 let mut tools = self.tools.write().await;
233 if tools.contains_key(&tool.name) {
234 return Err(AgentError::DuplicateTool {
235 name: tool.name.clone(),
236 });
237 }
238 tools.insert(tool.name.clone(), tool);
239 Ok(())
240 }
241
242 pub async fn unregister_tool(&self, name: &str) -> bool {
243 self.tools.write().await.remove(name).is_some()
244 }
245
246 pub async fn remove_all_tools(&self) {
247 self.tools.write().await.clear();
248 self.session_grants.lock().await.clear();
249 }
250
251 pub fn cancel(&self) {
253 self.cancelled.store(true, Ordering::Release);
254 }
255
256 async fn execute_tool_call(
257 &self,
258 call: &ToolCall,
259 registered: &HashMap<String, AgentToolDefinition>,
260 ) -> ToolExecutionResult {
261 let Some(definition) = registered.get(&call.name) else {
262 return ToolExecutionResult {
263 tool_call_id: call.id.clone(),
264 content: format!("tool {:?} is not registered", call.name),
265 is_error: true,
266 };
267 };
268
269 if !matches!(
270 serde_json::from_str::<serde_json::Value>(&call.arguments),
271 Ok(serde_json::Value::Object(_))
272 ) {
273 return ToolExecutionResult {
274 tool_call_id: call.id.clone(),
275 content: "tool arguments must be a valid JSON object".to_string(),
276 is_error: true,
277 };
278 }
279
280 let approved = if definition.risk == ToolRisk::ReadOnly
281 || self.session_grants.lock().await.contains(&call.name)
282 {
283 true
284 } else {
285 let request = ApprovalRequest {
286 call: call.clone(),
287 risk: definition.risk,
288 };
289 self.sink.approval_requested(&request);
290 match self.approvals.approve(request).await {
291 ApprovalDecision::AllowOnce => true,
292 ApprovalDecision::AllowForSession => {
293 self.session_grants.lock().await.insert(call.name.clone());
294 true
295 }
296 ApprovalDecision::Deny => false,
297 }
298 };
299
300 if !approved {
301 return ToolExecutionResult {
302 tool_call_id: call.id.clone(),
303 content: format!("tool {:?} was denied by the user", call.name),
304 is_error: true,
305 };
306 }
307
308 self.sink.tool_started(call);
309 match self.executor.execute(&call.name, &call.arguments).await {
310 Ok(content) => ToolExecutionResult {
311 tool_call_id: call.id.clone(),
312 content: truncate_output(content, self.agent_config.max_tool_output_chars),
313 is_error: false,
314 },
315 Err(error) => ToolExecutionResult {
316 tool_call_id: call.id.clone(),
317 content: truncate_output(
318 format!("tool execution failed: {error}"),
319 self.agent_config.max_tool_output_chars,
320 ),
321 is_error: true,
322 },
323 }
324 }
325
326 pub async fn run(&self, message: impl Into<String>) -> Result<AgentReply, AgentError> {
339 let _turn = self.turn.lock().await;
340 self.cancelled.store(false, Ordering::Release);
341
342 let registered = self.tools.read().await.clone();
343 if registered.is_empty() {
344 let result =
349 self.engine
350 .send_message(message)
351 .await
352 .map_err(|error| AgentError::Inference {
353 reason: error.to_string(),
354 })?;
355 if result.text.trim().is_empty() {
356 return Err(AgentError::EmptyReply);
357 }
358 let agent_reply = AgentReply {
359 text: result.text,
360 duration_seconds: result.duration_secs,
361 duration: result.duration_display,
362 tool_rounds: 0,
363 };
364 self.sink.agent_replied(&agent_reply);
365 return Ok(agent_reply);
366 }
367
368 match self.engine.tool_calling_support().await {
369 ToolCallingSupport::Unsupported => return Err(AgentError::UnsupportedModel),
370 ToolCallingSupport::Unknown => self
371 .sink
372 .warning("the loaded model has not been verified for tool calling"),
373 ToolCallingSupport::Supported => {}
374 }
375
376 let mut definitions: Vec<ToolDefinition> = registered
377 .values()
378 .map(|tool| ToolDefinition {
379 name: tool.name.clone(),
380 description: tool.description.clone(),
381 parameters_schema: tool.parameters_schema.clone(),
382 })
383 .collect();
384 definitions.sort_by(|left, right| left.name.cmp(&right.name));
385
386 let mut result = self
387 .engine
388 .send_message_with_tools(message.into(), &definitions)
389 .await
390 .map_err(|error| AgentError::Inference {
391 reason: error.to_string(),
392 })?;
393 let mut duration_seconds = result.duration_secs;
394 let mut rounds = 0_u8;
395 let max_rounds = self.agent_config.max_tool_rounds;
396 let mut exhausted = false;
397
398 while !result.tool_calls.is_empty() {
399 if !self.agent_config.allows_round(rounds) {
400 let unanswered = result
412 .tool_calls
413 .iter()
414 .map(|pending| ToolResult {
415 tool_call_id: pending.id.clone(),
416 content: "tool was not executed: the agent ran out of tool rounds"
417 .to_string(),
418 })
419 .collect();
420 self.engine.record_tool_results(unanswered).await;
421 self.sink.warning(&format!(
422 "the agent stopped after {max_rounds} tool rounds; the model kept requesting tools"
423 ));
424 exhausted = true;
425 break;
426 }
427 rounds += 1;
428 let mut tool_results = Vec::with_capacity(result.tool_calls.len());
429
430 for (index, requested) in result.tool_calls.iter().enumerate() {
431 if self.cancelled.load(Ordering::Acquire) {
432 for pending in &result.tool_calls[index..] {
433 tool_results.push(ToolResult {
434 tool_call_id: pending.id.clone(),
435 content: "tool was not executed because the user cancelled the turn"
436 .to_string(),
437 });
438 }
439 self.engine.record_tool_results(tool_results).await;
440 return Err(AgentError::Cancelled);
441 }
442
443 let call = ToolCall {
444 id: requested.id.clone(),
445 name: requested.function_name.clone(),
446 arguments: requested.arguments.clone(),
447 };
448 self.sink.tool_requested(&call);
449
450 let execution = self.execute_tool_call(&call, ®istered).await;
451 self.sink.tool_finished(&execution);
452 tool_results.push(ToolResult {
453 tool_call_id: execution.tool_call_id,
454 content: execution.content,
455 });
456 }
457
458 if self.cancelled.load(Ordering::Acquire) {
459 self.engine.record_tool_results(tool_results).await;
460 return Err(AgentError::Cancelled);
461 }
462
463 let next_tools = if self.agent_config.allows_round(rounds) {
464 Some(definitions.as_slice())
465 } else {
466 None
467 };
468 result = self
469 .engine
470 .send_tool_results(tool_results, next_tools)
471 .await
472 .map_err(|error| AgentError::Inference {
473 reason: error.to_string(),
474 })?;
475 duration_seconds += result.duration_secs;
476 }
477
478 if result.text.trim().is_empty() {
479 return Err(if exhausted {
480 AgentError::ToolRoundsExhausted { rounds: max_rounds }
481 } else {
482 AgentError::EmptyReply
483 });
484 }
485 let reply = AgentReply {
486 text: result.text,
487 duration_seconds,
488 duration: format_duration(Duration::from_secs_f64(duration_seconds)),
489 tool_rounds: rounds,
490 };
491 self.sink.agent_replied(&reply);
492 Ok(reply)
493 }
494
495 pub async fn info(&self) -> EngineInfo {
497 self.engine.info().await
498 }
499
500 pub async fn is_loaded(&self) -> bool {
502 self.engine.is_loaded().await
503 }
504
505 pub async fn history(&self) -> Vec<ChatMessage> {
507 self.engine.history().await
508 }
509
510 pub async fn clear_history(&self) -> usize {
520 let cleared = self.engine.clear_history().await;
521 self.session_grants.lock().await.clear();
522 info!("ed: cleared {cleared} messages");
523 cleared
524 }
525}
526
527#[cfg(test)]
528mod tests {
529 use std::sync::atomic::{AtomicUsize, Ordering};
530 use std::sync::Mutex;
531
532 use super::*;
533
534 #[derive(Default)]
537 struct RecordingSink {
538 statuses: Mutex<Vec<(EngineStatus, Option<String>)>>,
539 errors: Mutex<Vec<Option<String>>>,
540 replies: Mutex<Vec<ChatReply>>,
541 }
542
543 impl RecordingSink {
544 fn statuses(&self) -> Vec<(EngineStatus, Option<String>)> {
545 self.statuses.lock().unwrap().clone()
546 }
547
548 fn errors(&self) -> Vec<Option<String>> {
549 self.errors.lock().unwrap().clone()
550 }
551 }
552
553 impl EventSink for &'static RecordingSink {
554 fn status_changed(
555 &self,
556 status: EngineStatus,
557 model_name: Option<&str>,
558 error: Option<&str>,
559 ) {
560 self.statuses
561 .lock()
562 .unwrap()
563 .push((status, model_name.map(str::to_owned)));
564 self.errors.lock().unwrap().push(error.map(str::to_owned));
565 }
566
567 fn replied(&self, reply: &ChatReply) {
568 self.replies.lock().unwrap().push(reply.clone());
569 }
570 }
571
572 fn sink() -> &'static RecordingSink {
573 Box::leak(Box::new(RecordingSink::default()))
574 }
575
576 struct CountingExecutor(AtomicUsize);
577
578 #[async_trait::async_trait]
579 impl ToolExecutor for CountingExecutor {
580 async fn execute(&self, tool_name: &str, _: &str) -> Result<String, String> {
581 self.0.fetch_add(1, Ordering::Relaxed);
582 Ok(format!("{tool_name} completed"))
583 }
584 }
585
586 struct FixedApproval(ApprovalDecision);
587
588 #[async_trait::async_trait]
589 impl ApprovalHandler for FixedApproval {
590 async fn approve(&self, _: ApprovalRequest) -> ApprovalDecision {
591 self.0
592 }
593 }
594
595 fn call(name: &str) -> ToolCall {
596 ToolCall {
597 id: "call-1".to_owned(),
598 name: name.to_owned(),
599 arguments: "{}".to_owned(),
600 }
601 }
602
603 #[tokio::test]
604 async fn a_fresh_agent_reports_itself_unloaded_and_empty() {
605 let ed = Ed::new();
606 let info = ed.info().await;
607
608 assert_eq!(info.status, EngineStatus::Unloaded);
609 assert_eq!(info.model_name, None);
610 assert_eq!(info.history_length, 0);
611 assert!(!ed.is_loaded().await);
612 assert!(ed.history().await.is_empty());
613 }
614
615 #[tokio::test]
616 async fn unloading_reports_the_transition_even_with_nothing_loaded() {
617 let sink = sink();
621 let ed = Ed::with_sink(sink);
622
623 assert_eq!(ed.unload().await, None);
624 assert_eq!(sink.statuses(), vec![(EngineStatus::Unloaded, None)]);
625 }
626
627 #[tokio::test]
628 async fn clearing_an_empty_history_drops_nothing() {
629 let ed = Ed::new();
630 assert_eq!(ed.clear_history().await, 0);
631 }
632
633 #[tokio::test]
634 async fn the_default_sink_swallows_reports_without_panicking() {
635 let ed = Ed::default();
638 ed.unload().await;
639 assert_eq!(ed.info().await.status, EngineStatus::Unloaded);
640 }
641
642 #[tokio::test]
643 async fn a_successful_load_reports_loading_then_ready() {
644 let sink = sink();
648 let ed = Ed::with_sink(sink);
649
650 let elapsed = ed
651 .load_with("Test model", |_| async { Ok(Duration::from_secs(2)) })
652 .await
653 .expect("the closure succeeded");
654
655 assert_eq!(elapsed, Duration::from_secs(2));
656 assert_eq!(
657 sink.statuses(),
658 vec![
659 (EngineStatus::Loading, Some("Test model".to_owned())),
660 (EngineStatus::Ready, Some("Test model".to_owned())),
661 ]
662 );
663 }
664
665 #[tokio::test]
666 async fn a_failed_load_reports_loading_then_error_with_the_reason() {
667 let sink = sink();
668 let ed = Ed::with_sink(sink);
669
670 let err = ed
671 .load_with("Test model", |_| async {
672 Err(InferenceError::Other {
673 reason: "no weights".to_owned(),
674 })
675 })
676 .await
677 .expect_err("the closure failed");
678
679 assert!(err.to_string().contains("no weights"));
680 assert_eq!(
681 sink.statuses(),
682 vec![
683 (EngineStatus::Loading, Some("Test model".to_owned())),
684 (EngineStatus::Error, Some("Test model".to_owned())),
685 ]
686 );
687 assert_eq!(sink.errors(), vec![None, Some("no weights".to_owned())]);
688 }
689
690 #[tokio::test]
691 async fn read_only_tools_run_without_an_approval_round_trip() {
692 let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
693 let ed = Ed::with_agent(
694 NoopSink,
695 executor.clone(),
696 Arc::new(FixedApproval(ApprovalDecision::Deny)),
697 AgentConfig::default(),
698 );
699 ed.register_tool(AgentToolDefinition::read_only(
700 "clock",
701 "Read the clock",
702 r#"{"type":"object"}"#,
703 ))
704 .await
705 .unwrap();
706 let tools = ed.tools.read().await.clone();
707
708 let result = ed.execute_tool_call(&call("clock"), &tools).await;
709
710 assert!(!result.is_error);
711 assert_eq!(executor.0.load(Ordering::Relaxed), 1);
712 }
713
714 #[tokio::test]
715 async fn denied_mutating_tools_never_reach_the_executor() {
716 let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
717 let ed = Ed::with_agent(
718 NoopSink,
719 executor.clone(),
720 Arc::new(FixedApproval(ApprovalDecision::Deny)),
721 AgentConfig::default(),
722 );
723 ed.register_tool(AgentToolDefinition::mutating(
724 "save_note",
725 "Save a note",
726 r#"{"type":"object"}"#,
727 ))
728 .await
729 .unwrap();
730 let tools = ed.tools.read().await.clone();
731
732 let result = ed.execute_tool_call(&call("save_note"), &tools).await;
733
734 assert!(result.is_error);
735 assert!(result.content.contains("denied"));
736 assert_eq!(executor.0.load(Ordering::Relaxed), 0);
737 }
738
739 #[tokio::test]
740 async fn a_session_grant_applies_to_later_calls_of_the_same_tool() {
741 let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
742 let ed = Ed::with_agent(
743 NoopSink,
744 executor.clone(),
745 Arc::new(FixedApproval(ApprovalDecision::AllowForSession)),
746 AgentConfig::default(),
747 );
748 ed.register_tool(AgentToolDefinition::mutating(
749 "save_note",
750 "Save a note",
751 r#"{"type":"object"}"#,
752 ))
753 .await
754 .unwrap();
755 let tools = ed.tools.read().await.clone();
756
757 ed.execute_tool_call(&call("save_note"), &tools).await;
758 ed.execute_tool_call(&call("save_note"), &tools).await;
759
760 assert_eq!(executor.0.load(Ordering::Relaxed), 2);
761 assert!(ed.session_grants.lock().await.contains("save_note"));
762 }
763
764 #[tokio::test]
765 async fn clearing_the_conversation_revokes_session_grants() {
766 let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
769 let ed = Ed::with_agent(
770 NoopSink,
771 executor.clone(),
772 Arc::new(FixedApproval(ApprovalDecision::AllowForSession)),
773 AgentConfig::default(),
774 );
775 ed.register_tool(AgentToolDefinition::mutating(
776 "save_note",
777 "Save a note",
778 r#"{"type":"object"}"#,
779 ))
780 .await
781 .unwrap();
782 let tools = ed.tools.read().await.clone();
783 ed.execute_tool_call(&call("save_note"), &tools).await;
784 assert!(ed.session_grants.lock().await.contains("save_note"));
785
786 ed.clear_history().await;
787
788 assert!(ed.session_grants.lock().await.is_empty());
789 }
790
791 #[tokio::test]
792 async fn unknown_tools_return_an_error_result_instead_of_executing() {
793 let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
794 let ed = Ed::with_agent(
795 NoopSink,
796 executor.clone(),
797 Arc::new(FixedApproval(ApprovalDecision::AllowOnce)),
798 AgentConfig::default(),
799 );
800
801 let result = ed
802 .execute_tool_call(&call("missing"), &HashMap::new())
803 .await;
804
805 assert!(result.is_error);
806 assert!(result.content.contains("not registered"));
807 assert_eq!(executor.0.load(Ordering::Relaxed), 0);
808 }
809
810 #[tokio::test]
811 async fn tool_arguments_must_be_a_json_object() {
812 let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
813 let ed = Ed::with_agent(
814 NoopSink,
815 executor.clone(),
816 Arc::new(FixedApproval(ApprovalDecision::AllowOnce)),
817 AgentConfig::default(),
818 );
819 ed.register_tool(AgentToolDefinition::read_only(
820 "clock",
821 "Read the clock",
822 r#"{"type":"object"}"#,
823 ))
824 .await
825 .unwrap();
826 let tools = ed.tools.read().await.clone();
827 let mut invalid = call("clock");
828 invalid.arguments = "[]".to_owned();
829
830 let result = ed.execute_tool_call(&invalid, &tools).await;
831
832 assert!(result.is_error);
833 assert!(result.content.contains("JSON object"));
834 assert_eq!(executor.0.load(Ordering::Relaxed), 0);
835 }
836}