ed-agent 1.5.0

Embeddable local-LLM-first chat agent: engine lifecycle, history, and status over the Onde inference SDK.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
//! The agent handle.

use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use log::{error, info};
use onde::inference::types::{format_duration, ChatMessage};
use onde::inference::{
    ChatEngine, EngineInfo, EngineStatus, GgufModelConfig, InferenceError, SamplingConfig,
    ToolCallingSupport, ToolDefinition, ToolResult,
};
use web_time::Instant;

use crate::{
    stream::chunk_error, tool::truncate_output, AgentConfig, AgentError, AgentReply,
    AgentToolDefinition, ApprovalDecision, ApprovalHandler, ApprovalRequest, ChatReply,
    DenyApprovals, EventSink, NoopSink, RejectingExecutor, TextStream, ToolCall,
    ToolExecutionResult, ToolExecutor, ToolRisk,
};

/// An embeddable chat agent over a single [`ChatEngine`].
///
/// Hold one per application. Ed is `Send + Sync` and every method takes
/// `&self`, so it can live behind a `OnceLock`, a framework's managed state,
/// or an `Arc` — whichever the host prefers. It is not cloneable by design:
/// one Ed owns one engine owns one loaded model, and copying that handle
/// around tends to mean two parts of an app disagree about which model is up.
pub struct Ed<S = NoopSink> {
    engine: ChatEngine,
    sink: S,
    tools: tokio::sync::RwLock<HashMap<String, AgentToolDefinition>>,
    executor: Arc<dyn ToolExecutor>,
    approvals: Arc<dyn ApprovalHandler>,
    session_grants: tokio::sync::Mutex<HashSet<String>>,
    turn: tokio::sync::Mutex<()>,
    cancelled: AtomicBool,
    agent_config: AgentConfig,
}

impl Ed<NoopSink> {
    /// An agent that reports nothing. Poll [`info`](Ed::info) for state.
    pub fn new() -> Self {
        Self::with_sink(NoopSink)
    }
}

impl Default for Ed<NoopSink> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S: EventSink> Ed<S> {
    /// An agent that reports transitions and replies to `sink`.
    pub fn with_sink(sink: S) -> Self {
        Self::with_agent(
            sink,
            Arc::new(RejectingExecutor),
            Arc::new(DenyApprovals),
            AgentConfig::default(),
        )
    }

    /// Build an agent with host-defined tool execution and approval handling.
    pub fn with_agent(
        sink: S,
        executor: Arc<dyn ToolExecutor>,
        approvals: Arc<dyn ApprovalHandler>,
        config: AgentConfig,
    ) -> Self {
        Self::with_agent_and_app_id(sink, executor, approvals, config, None)
    }

    /// Associate telemetry with an Onde app id. See [`ChatEngine::with_app_id`].
    pub fn with_app_id(sink: S, onde_app_id: Option<String>) -> Self {
        Self::with_agent_and_app_id(
            sink,
            Arc::new(RejectingExecutor),
            Arc::new(DenyApprovals),
            AgentConfig::default(),
            onde_app_id,
        )
    }

    /// The full constructor: tools, approvals, and an Onde app id together.
    ///
    /// The narrower constructors each fill in defaults for what they don't
    /// take. Use this one when you need both host tools and telemetry, which
    /// the others cannot express between them.
    pub fn with_agent_and_app_id(
        sink: S,
        executor: Arc<dyn ToolExecutor>,
        approvals: Arc<dyn ApprovalHandler>,
        config: AgentConfig,
        onde_app_id: Option<String>,
    ) -> Self {
        Self {
            engine: ChatEngine::with_app_id(onde_app_id),
            sink,
            tools: tokio::sync::RwLock::new(HashMap::new()),
            executor,
            approvals,
            session_grants: tokio::sync::Mutex::new(HashSet::new()),
            turn: tokio::sync::Mutex::new(()),
            cancelled: AtomicBool::new(false),
            agent_config: config.validated(),
        }
    }

    /// The underlying engine.
    ///
    /// An escape hatch for the parts of `onde` Ed deliberately doesn't wrap —
    /// system prompts, alternative load paths, tool calling. Reach for it when
    /// you need them; anything you find yourself writing here for a second
    /// application is a candidate to move into Ed.
    pub fn engine(&self) -> &ChatEngine {
        &self.engine
    }

    /// Run any load, reporting the transitions around it.
    ///
    /// Emits [`EngineStatus::Loading`] before `load` starts and then either
    /// [`Ready`](EngineStatus::Ready) or [`Error`](EngineStatus::Error). That
    /// sequence is the whole reason this method exists: calling a
    /// [`ChatEngine`] load path directly leaves the UI with no way to know a
    /// multi-minute download has begun.
    ///
    /// Ed takes a closure rather than wrapping each load path by name because
    /// `onde`'s load APIs take types Ed has no business in its public
    /// signature — `ChatEngine::load_assigned_model` takes an `Environment`
    /// from the smbCloud SDK, and *which* crate that type comes from changed
    /// between `onde` releases. Naming it here would drag that dependency into
    /// every host and pin them all to Ed's version of it. Passing a closure
    /// keeps Ed's dependency surface to `onde` alone and works for load paths
    /// that don't exist yet.
    ///
    /// ```no_run
    /// # use ed_agent::{Ed, GgufModelConfig};
    /// # async fn example(ed: Ed) {
    /// ed.load_with("Qwen 2.5", |engine| {
    ///     engine.load_gguf_model(GgufModelConfig::qwen25_1_5b(), None, None)
    /// })
    /// .await
    /// .expect("load");
    /// # }
    /// ```
    ///
    /// `model_name` is what the host wants the UI to show while loading; it is
    /// reported with each transition and needn't match what the engine ends up
    /// calling the model.
    pub async fn load_with<'a, F, Fut>(
        &'a self,
        model_name: &str,
        load: F,
    ) -> Result<Duration, InferenceError>
    where
        F: FnOnce(&'a ChatEngine) -> Fut,
        Fut: Future<Output = Result<Duration, InferenceError>>,
    {
        info!("ed: loading model {model_name}");
        self.sink
            .status_changed(EngineStatus::Loading, Some(model_name), None);

        match load(&self.engine).await {
            Ok(elapsed) => {
                info!("ed: loaded {model_name} in {}", format_duration(elapsed));
                self.sink
                    .status_changed(EngineStatus::Ready, Some(model_name), None);
                Ok(elapsed)
            }
            Err(err) => {
                error!("ed: failed to load {model_name}: {err}");
                let message = err.to_string();
                self.sink
                    .status_changed(EngineStatus::Error, Some(model_name), Some(&message));
                Err(err)
            }
        }
    }

    /// Load a GGUF model, reporting each transition.
    ///
    /// A convenience over [`load_with`](Ed::load_with) for the most common
    /// path. Downloads the weights first if they aren't in the local cache, so
    /// the `Loading` state can last a long time on a cold start.
    pub async fn load(
        &self,
        config: GgufModelConfig,
        system_prompt: Option<String>,
        sampling: Option<SamplingConfig>,
    ) -> Result<Duration, InferenceError> {
        let model_name = config.display_name.clone();
        self.load_with(&model_name, |engine| {
            engine.load_gguf_model(config, system_prompt, sampling)
        })
        .await
    }

    /// Unload the current model, returning its display name if one was loaded.
    pub async fn unload(&self) -> Option<String> {
        let unloaded = self.engine.unload_model().await;
        if let Some(name) = &unloaded {
            info!("ed: unloaded {name}");
        }
        self.sink
            .status_changed(EngineStatus::Unloaded, unloaded.as_deref(), None);
        unloaded
    }

    /// Run one inference turn.
    ///
    /// Never returns an error: a failure is reported in
    /// [`ChatReply::error`] so a caller has one shape to render either way.
    /// The reply also goes to the sink, so a host can render it from an event
    /// instead of awaiting this call — see [`EventSink::replied`].
    pub async fn send(&self, message: impl Into<String>) -> ChatReply {
        let reply = match self.engine.send_message(message).await {
            Ok(result) => ChatReply::ok(result.text, result.duration_display),
            Err(err) => {
                error!("ed: inference failed: {err}");
                ChatReply::failed(err)
            }
        };
        self.sink.replied(&reply);
        reply
    }

    /// Stream the reply to one message, for plain chat without tools.
    ///
    /// Returns once generation has started; the stream yields text deltas as
    /// they are produced. Unlike [`run`](Ed::run) this takes no turn lock and
    /// reports nothing to the sink, so don't overlap it with another turn.
    /// Drop the stream to cancel; a [`cancel`](Ed::cancel) call is not needed.
    pub async fn stream(&self, message: impl Into<String>) -> Result<TextStream, InferenceError> {
        Ok(TextStream::new(self.engine.stream_message(message).await?))
    }

    /// One-shot generation over explicit messages.
    ///
    /// Leaves the conversation history untouched; the engine's system prompt
    /// is still applied. `sampling` overrides the engine's for this call only.
    pub async fn generate(
        &self,
        messages: Vec<ChatMessage>,
        sampling: Option<SamplingConfig>,
    ) -> Result<String, InferenceError> {
        Ok(self.engine.generate(messages, sampling).await?.text)
    }

    /// Set the system prompt used for every later turn.
    ///
    /// Like the other engine setters below, and `restore_history`, this does
    /// nothing until a model is loaded: `onde` keeps these on the loaded model.
    pub async fn set_system_prompt(&self, prompt: impl Into<String>) {
        self.engine.set_system_prompt(prompt).await;
    }

    pub async fn clear_system_prompt(&self) {
        self.engine.clear_system_prompt().await;
    }

    /// Change the default sampling parameters.
    pub async fn set_sampling(&self, sampling: SamplingConfig) {
        self.engine.set_sampling(sampling).await;
    }

    /// Replace the conversation with `messages`.
    ///
    /// For switching to a saved session or restoring one at launch. Clears
    /// the current history first, and with it every `AllowForSession` grant,
    /// exactly as [`clear_history`](Ed::clear_history) does: a restored
    /// conversation starts without consent from the previous one.
    pub async fn restore_history(&self, messages: Vec<ChatMessage>) {
        self.clear_history().await;
        let count = messages.len();
        for message in messages {
            self.engine.push_history(message).await;
        }
        info!("ed: restored {count} messages");
    }

    /// Register a host capability that the model may request.
    pub async fn register_tool(&self, tool: AgentToolDefinition) -> Result<(), AgentError> {
        tool.validate()?;
        let mut tools = self.tools.write().await;
        if tools.contains_key(&tool.name) {
            return Err(AgentError::DuplicateTool {
                name: tool.name.clone(),
            });
        }
        tools.insert(tool.name.clone(), tool);
        Ok(())
    }

    pub async fn unregister_tool(&self, name: &str) -> bool {
        self.tools.write().await.remove(name).is_some()
    }

    pub async fn remove_all_tools(&self) {
        self.tools.write().await.clear();
        self.session_grants.lock().await.clear();
    }

    /// Request cancellation of the active agent turn.
    pub fn cancel(&self) {
        self.cancelled.store(true, Ordering::Release);
    }

    async fn execute_tool_call(
        &self,
        call: &ToolCall,
        registered: &HashMap<String, AgentToolDefinition>,
    ) -> ToolExecutionResult {
        let Some(definition) = registered.get(&call.name) else {
            return ToolExecutionResult {
                tool_call_id: call.id.clone(),
                content: format!("tool {:?} is not registered", call.name),
                is_error: true,
            };
        };

        if !matches!(
            serde_json::from_str::<serde_json::Value>(&call.arguments),
            Ok(serde_json::Value::Object(_))
        ) {
            return ToolExecutionResult {
                tool_call_id: call.id.clone(),
                content: "tool arguments must be a valid JSON object".to_string(),
                is_error: true,
            };
        }

        let approved = if definition.risk == ToolRisk::ReadOnly
            || self.session_grants.lock().await.contains(&call.name)
        {
            true
        } else {
            let request = ApprovalRequest {
                call: call.clone(),
                risk: definition.risk,
            };
            self.sink.approval_requested(&request);
            match self.approvals.approve(request).await {
                ApprovalDecision::AllowOnce => true,
                ApprovalDecision::AllowForSession => {
                    self.session_grants.lock().await.insert(call.name.clone());
                    true
                }
                ApprovalDecision::Deny => false,
            }
        };

        if !approved {
            return ToolExecutionResult {
                tool_call_id: call.id.clone(),
                content: format!("tool {:?} was denied by the user", call.name),
                is_error: true,
            };
        }

        self.sink.tool_started(call);
        match self.executor.execute(&call.name, &call.arguments).await {
            Ok(content) => ToolExecutionResult {
                tool_call_id: call.id.clone(),
                content: truncate_output(content, self.agent_config.max_tool_output_chars),
                is_error: false,
            },
            Err(error) => ToolExecutionResult {
                tool_call_id: call.id.clone(),
                content: truncate_output(
                    format!("tool execution failed: {error}"),
                    self.agent_config.max_tool_output_chars,
                ),
                is_error: true,
            },
        }
    }

    /// Run a complete local agent turn, including any requested host tools.
    ///
    /// With no tools registered this is one inference call. Otherwise Ed
    /// alternates between the model and the host's executor until the model
    /// answers in text, or until
    /// [`max_tool_rounds`](AgentConfig::max_tool_rounds) is spent, whichever
    /// comes first. Reaching the budget is reported to the sink as a warning,
    /// and yields [`AgentError::ToolRoundsExhausted`] if there is no usable
    /// text by then.
    ///
    /// Reports [`EventSink::agent_replied`] on success. It does *not* report
    /// [`EventSink::replied`]; that belongs to [`send`](Ed::send).
    pub async fn run(&self, message: impl Into<String>) -> Result<AgentReply, AgentError> {
        let _turn = self.turn.lock().await;
        self.cancelled.store(false, Ordering::Release);

        let registered = self.tools.read().await.clone();
        if registered.is_empty() {
            // Deliberately not routed through `send`: that reports a
            // `ChatReply` to the sink, and a host listening for both events
            // would render this turn's answer twice. An agent turn reports
            // `agent_replied` and nothing else.
            let started = Instant::now();
            let mut rx = self.engine.stream_message(message).await.map_err(|error| {
                AgentError::Inference {
                    reason: error.to_string(),
                }
            })?;
            let mut text = String::new();
            while let Some(chunk) = rx.recv().await {
                if self.cancelled.load(Ordering::Acquire) {
                    // Dropping the receiver stops generation.
                    return Err(AgentError::Cancelled);
                }
                if chunk.done {
                    if let Some(error) = chunk_error(&chunk) {
                        return Err(AgentError::Inference {
                            reason: error.to_string(),
                        });
                    }
                    break;
                }
                if !chunk.delta.is_empty() {
                    self.sink.text_delta(&chunk.delta);
                    text.push_str(&chunk.delta);
                }
            }
            if text.trim().is_empty() {
                return Err(AgentError::EmptyReply);
            }
            let elapsed = started.elapsed();
            let agent_reply = AgentReply {
                text,
                duration_seconds: elapsed.as_secs_f64(),
                duration: format_duration(elapsed),
                tool_rounds: 0,
            };
            self.sink.agent_replied(&agent_reply);
            return Ok(agent_reply);
        }

        match self.engine.tool_calling_support().await {
            ToolCallingSupport::Unsupported => return Err(AgentError::UnsupportedModel),
            ToolCallingSupport::Unknown => self
                .sink
                .warning("the loaded model has not been verified for tool calling"),
            ToolCallingSupport::Supported => {}
        }

        let mut definitions: Vec<ToolDefinition> = registered
            .values()
            .map(|tool| ToolDefinition {
                name: tool.name.clone(),
                description: tool.description.clone(),
                parameters_schema: tool.parameters_schema.clone(),
            })
            .collect();
        definitions.sort_by(|left, right| left.name.cmp(&right.name));

        let mut result = self
            .engine
            .send_message_with_tools(message.into(), &definitions)
            .await
            .map_err(|error| AgentError::Inference {
                reason: error.to_string(),
            })?;
        let mut duration_seconds = result.duration_secs;
        let mut rounds = 0_u8;
        let max_rounds = self.agent_config.max_tool_rounds;
        let mut exhausted = false;

        while !result.tool_calls.is_empty() {
            if !self.agent_config.allows_round(rounds) {
                // The budget only stops Ed *offering* tools; it cannot stop the
                // model asking. `onde` parses tool calls out of every response
                // whether or not tools were sent, so a model that keeps
                // emitting tool-call syntax would loop here until `rounds`
                // overflowed and wrapped back under the limit. This is the
                // loop's only hard exit.
                //
                // The model's last turn is already in history carrying these
                // calls. Leaving them unanswered would make the next turn's
                // message sequence invalid, so close them out the way
                // cancelling does.
                let unanswered = result
                    .tool_calls
                    .iter()
                    .map(|pending| ToolResult {
                        tool_call_id: pending.id.clone(),
                        content: "tool was not executed: the agent ran out of tool rounds"
                            .to_string(),
                    })
                    .collect();
                self.engine.record_tool_results(unanswered).await;
                self.sink.warning(&format!(
                    "the agent stopped after {max_rounds} tool rounds; the model kept requesting tools"
                ));
                exhausted = true;
                break;
            }
            rounds += 1;
            let mut tool_results = Vec::with_capacity(result.tool_calls.len());

            for (index, requested) in result.tool_calls.iter().enumerate() {
                if self.cancelled.load(Ordering::Acquire) {
                    for pending in &result.tool_calls[index..] {
                        tool_results.push(ToolResult {
                            tool_call_id: pending.id.clone(),
                            content: "tool was not executed because the user cancelled the turn"
                                .to_string(),
                        });
                    }
                    self.engine.record_tool_results(tool_results).await;
                    return Err(AgentError::Cancelled);
                }

                let call = ToolCall {
                    id: requested.id.clone(),
                    name: requested.function_name.clone(),
                    arguments: requested.arguments.clone(),
                };
                self.sink.tool_requested(&call);

                let execution = self.execute_tool_call(&call, &registered).await;
                self.sink.tool_finished(&execution);
                tool_results.push(ToolResult {
                    tool_call_id: execution.tool_call_id,
                    content: execution.content,
                });
            }

            if self.cancelled.load(Ordering::Acquire) {
                self.engine.record_tool_results(tool_results).await;
                return Err(AgentError::Cancelled);
            }

            let next_tools = if self.agent_config.allows_round(rounds) {
                Some(definitions.as_slice())
            } else {
                None
            };
            result = self
                .engine
                .send_tool_results(tool_results, next_tools)
                .await
                .map_err(|error| AgentError::Inference {
                    reason: error.to_string(),
                })?;
            duration_seconds += result.duration_secs;
        }

        if result.text.trim().is_empty() {
            return Err(if exhausted {
                AgentError::ToolRoundsExhausted { rounds: max_rounds }
            } else {
                AgentError::EmptyReply
            });
        }
        // Tool rounds are not streamed: `onde` only parses tool calls out of a
        // complete response, so the answer arrives whole. Report it as one
        // delta so a host rendering deltas sees every turn the same way.
        self.sink.text_delta(&result.text);
        let reply = AgentReply {
            text: result.text,
            duration_seconds,
            duration: format_duration(Duration::from_secs_f64(duration_seconds)),
            tool_rounds: rounds,
        };
        self.sink.agent_replied(&reply);
        Ok(reply)
    }

    /// Current status, loaded model, footprint, and history length.
    pub async fn info(&self) -> EngineInfo {
        self.engine.info().await
    }

    /// Whether a model is loaded and ready.
    pub async fn is_loaded(&self) -> bool {
        self.engine.is_loaded().await
    }

    /// The conversation so far.
    pub async fn history(&self) -> Vec<ChatMessage> {
        self.engine.history().await
    }

    /// Clear the conversation, returning how many messages were dropped.
    ///
    /// Leaves the model loaded — this starts a new conversation, it doesn't
    /// tear down the engine.
    ///
    /// Also drops every `AllowForSession` grant. The user approved those
    /// mutating tools for a conversation, and this ends the conversation;
    /// carrying the grants into the next one would keep consent alive past the
    /// thing it was given for.
    pub async fn clear_history(&self) -> usize {
        let cleared = self.engine.clear_history().await;
        self.session_grants.lock().await.clear();
        info!("ed: cleared {cleared} messages");
        cleared
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Mutex;

    use super::*;

    /// Records everything Ed reports, so a test can assert on the sequence of
    /// transitions rather than only the final state.
    #[derive(Default)]
    struct RecordingSink {
        statuses: Mutex<Vec<(EngineStatus, Option<String>)>>,
        errors: Mutex<Vec<Option<String>>>,
        replies: Mutex<Vec<ChatReply>>,
    }

    impl RecordingSink {
        fn statuses(&self) -> Vec<(EngineStatus, Option<String>)> {
            self.statuses.lock().unwrap().clone()
        }

        fn errors(&self) -> Vec<Option<String>> {
            self.errors.lock().unwrap().clone()
        }
    }

    impl EventSink for &'static RecordingSink {
        fn status_changed(
            &self,
            status: EngineStatus,
            model_name: Option<&str>,
            error: Option<&str>,
        ) {
            self.statuses
                .lock()
                .unwrap()
                .push((status, model_name.map(str::to_owned)));
            self.errors.lock().unwrap().push(error.map(str::to_owned));
        }

        fn replied(&self, reply: &ChatReply) {
            self.replies.lock().unwrap().push(reply.clone());
        }
    }

    fn sink() -> &'static RecordingSink {
        Box::leak(Box::new(RecordingSink::default()))
    }

    struct CountingExecutor(AtomicUsize);

    #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), async_trait::async_trait(?Send))]
    #[cfg_attr(
        not(all(target_arch = "wasm32", target_os = "unknown")),
        async_trait::async_trait
    )]
    impl ToolExecutor for CountingExecutor {
        async fn execute(&self, tool_name: &str, _: &str) -> Result<String, String> {
            self.0.fetch_add(1, Ordering::Relaxed);
            Ok(format!("{tool_name} completed"))
        }
    }

    struct FixedApproval(ApprovalDecision);

    #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), async_trait::async_trait(?Send))]
    #[cfg_attr(
        not(all(target_arch = "wasm32", target_os = "unknown")),
        async_trait::async_trait
    )]
    impl ApprovalHandler for FixedApproval {
        async fn approve(&self, _: ApprovalRequest) -> ApprovalDecision {
            self.0
        }
    }

    fn call(name: &str) -> ToolCall {
        ToolCall {
            id: "call-1".to_owned(),
            name: name.to_owned(),
            arguments: "{}".to_owned(),
        }
    }

    #[tokio::test]
    async fn a_fresh_agent_reports_itself_unloaded_and_empty() {
        let ed = Ed::new();
        let info = ed.info().await;

        assert_eq!(info.status, EngineStatus::Unloaded);
        assert_eq!(info.model_name, None);
        assert_eq!(info.history_length, 0);
        assert!(!ed.is_loaded().await);
        assert!(ed.history().await.is_empty());
    }

    #[tokio::test]
    async fn unloading_reports_the_transition_even_with_nothing_loaded() {
        // The status still has to reach the host: a UI that asked to unload
        // needs to see `Unloaded` regardless of whether work was done, or the
        // view sits on a stale "ready" forever.
        let sink = sink();
        let ed = Ed::with_sink(sink);

        assert_eq!(ed.unload().await, None);
        assert_eq!(sink.statuses(), vec![(EngineStatus::Unloaded, None)]);
    }

    #[tokio::test]
    async fn clearing_an_empty_history_drops_nothing() {
        let ed = Ed::new();
        assert_eq!(ed.clear_history().await, 0);
    }

    #[tokio::test]
    async fn the_default_sink_swallows_reports_without_panicking() {
        // `Ed::new()` is the no-sink path; exercising it guards against a
        // future notification being added that assumes a real sink exists.
        let ed = Ed::default();
        ed.unload().await;
        assert_eq!(ed.info().await.status, EngineStatus::Unloaded);
    }

    #[tokio::test]
    async fn a_successful_load_reports_loading_then_ready() {
        // The ordering is the feature: a UI that only ever sees the final
        // state has no way to put up a spinner for a load that can take
        // minutes.
        let sink = sink();
        let ed = Ed::with_sink(sink);

        let elapsed = ed
            .load_with("Test model", |_| async { Ok(Duration::from_secs(2)) })
            .await
            .expect("the closure succeeded");

        assert_eq!(elapsed, Duration::from_secs(2));
        assert_eq!(
            sink.statuses(),
            vec![
                (EngineStatus::Loading, Some("Test model".to_owned())),
                (EngineStatus::Ready, Some("Test model".to_owned())),
            ]
        );
    }

    #[tokio::test]
    async fn a_failed_load_reports_loading_then_error_with_the_reason() {
        let sink = sink();
        let ed = Ed::with_sink(sink);

        let err = ed
            .load_with("Test model", |_| async {
                Err(InferenceError::Other {
                    reason: "no weights".to_owned(),
                })
            })
            .await
            .expect_err("the closure failed");

        assert!(err.to_string().contains("no weights"));
        assert_eq!(
            sink.statuses(),
            vec![
                (EngineStatus::Loading, Some("Test model".to_owned())),
                (EngineStatus::Error, Some("Test model".to_owned())),
            ]
        );
        assert_eq!(sink.errors(), vec![None, Some("no weights".to_owned())]);
    }

    #[tokio::test]
    async fn read_only_tools_run_without_an_approval_round_trip() {
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let ed = Ed::with_agent(
            NoopSink,
            executor.clone(),
            Arc::new(FixedApproval(ApprovalDecision::Deny)),
            AgentConfig::default(),
        );
        ed.register_tool(AgentToolDefinition::read_only(
            "clock",
            "Read the clock",
            r#"{"type":"object"}"#,
        ))
        .await
        .unwrap();
        let tools = ed.tools.read().await.clone();

        let result = ed.execute_tool_call(&call("clock"), &tools).await;

        assert!(!result.is_error);
        assert_eq!(executor.0.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn denied_mutating_tools_never_reach_the_executor() {
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let ed = Ed::with_agent(
            NoopSink,
            executor.clone(),
            Arc::new(FixedApproval(ApprovalDecision::Deny)),
            AgentConfig::default(),
        );
        ed.register_tool(AgentToolDefinition::mutating(
            "save_note",
            "Save a note",
            r#"{"type":"object"}"#,
        ))
        .await
        .unwrap();
        let tools = ed.tools.read().await.clone();

        let result = ed.execute_tool_call(&call("save_note"), &tools).await;

        assert!(result.is_error);
        assert!(result.content.contains("denied"));
        assert_eq!(executor.0.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn a_session_grant_applies_to_later_calls_of_the_same_tool() {
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let ed = Ed::with_agent(
            NoopSink,
            executor.clone(),
            Arc::new(FixedApproval(ApprovalDecision::AllowForSession)),
            AgentConfig::default(),
        );
        ed.register_tool(AgentToolDefinition::mutating(
            "save_note",
            "Save a note",
            r#"{"type":"object"}"#,
        ))
        .await
        .unwrap();
        let tools = ed.tools.read().await.clone();

        ed.execute_tool_call(&call("save_note"), &tools).await;
        ed.execute_tool_call(&call("save_note"), &tools).await;

        assert_eq!(executor.0.load(Ordering::Relaxed), 2);
        assert!(ed.session_grants.lock().await.contains("save_note"));
    }

    #[tokio::test]
    async fn clearing_the_conversation_revokes_session_grants() {
        // The grant was given for a conversation. Clearing the history ends
        // that conversation, so the next one has to ask again.
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let ed = Ed::with_agent(
            NoopSink,
            executor.clone(),
            Arc::new(FixedApproval(ApprovalDecision::AllowForSession)),
            AgentConfig::default(),
        );
        ed.register_tool(AgentToolDefinition::mutating(
            "save_note",
            "Save a note",
            r#"{"type":"object"}"#,
        ))
        .await
        .unwrap();
        let tools = ed.tools.read().await.clone();
        ed.execute_tool_call(&call("save_note"), &tools).await;
        assert!(ed.session_grants.lock().await.contains("save_note"));

        ed.clear_history().await;

        assert!(ed.session_grants.lock().await.is_empty());
    }

    #[tokio::test]
    async fn unknown_tools_return_an_error_result_instead_of_executing() {
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let ed = Ed::with_agent(
            NoopSink,
            executor.clone(),
            Arc::new(FixedApproval(ApprovalDecision::AllowOnce)),
            AgentConfig::default(),
        );

        let result = ed
            .execute_tool_call(&call("missing"), &HashMap::new())
            .await;

        assert!(result.is_error);
        assert!(result.content.contains("not registered"));
        assert_eq!(executor.0.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn tool_arguments_must_be_a_json_object() {
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let ed = Ed::with_agent(
            NoopSink,
            executor.clone(),
            Arc::new(FixedApproval(ApprovalDecision::AllowOnce)),
            AgentConfig::default(),
        );
        ed.register_tool(AgentToolDefinition::read_only(
            "clock",
            "Read the clock",
            r#"{"type":"object"}"#,
        ))
        .await
        .unwrap();
        let tools = ed.tools.read().await.clone();
        let mut invalid = call("clock");
        invalid.arguments = "[]".to_owned();

        let result = ed.execute_tool_call(&invalid, &tools).await;

        assert!(result.is_error);
        assert!(result.content.contains("JSON object"));
        assert_eq!(executor.0.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn restoring_history_revokes_session_grants() {
        let ed = Ed::with_agent(
            NoopSink,
            Arc::new(CountingExecutor(AtomicUsize::new(0))),
            Arc::new(FixedApproval(ApprovalDecision::AllowForSession)),
            AgentConfig::default(),
        );
        ed.register_tool(AgentToolDefinition::mutating(
            "save_note",
            "Save a note",
            r#"{"type":"object"}"#,
        ))
        .await
        .unwrap();
        let tools = ed.tools.read().await.clone();
        ed.execute_tool_call(&call("save_note"), &tools).await;
        assert!(ed.session_grants.lock().await.contains("save_note"));

        ed.restore_history(Vec::new()).await;

        assert!(ed.session_grants.lock().await.is_empty());
    }

    #[tokio::test]
    async fn generation_and_streaming_need_a_loaded_model() {
        let ed = Ed::new();
        assert!(matches!(
            ed.generate(vec![ChatMessage::user("hi")], None).await,
            Err(InferenceError::NoModelLoaded)
        ));
        assert!(matches!(
            ed.stream("hi").await,
            Err(InferenceError::NoModelLoaded)
        ));
    }
}