klieo 0.39.0

Open-source Rust agent framework — typed agents, durable inter-agent comms, local-first.
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
//! `App` — fluent assembler that collapses the 13-field `AgentContext`
//! into a one-call wiring surface.
//!
//! Use [`App::local`] for ephemeral dev (Ollama + sqlite + memory bus),
//! [`App::local_at`] for persistent dev,
//! [`App::builder`] for custom impls. All three produce an [`App`] that
//! mints fresh [`AgentContext`] per run via [`App::context`] and
//! shares a parent [`CancellationToken`] across runs.
//!
//! ```ignore
//! use klieo::{App, SimpleAgent};
//! let app = App::local().model("qwen2.5:14b").build().await?;
//! let agent = SimpleAgent::new("hello", "Be brief.", app.tools_catalogue().to_vec());
//! let answer = app.run(&agent, "hi".into()).await?;
//! ```
//!
//! Power users who need a port shape `App` does not surface can still
//! hand-build `AgentContext` directly — `App` is shortcut, not
//! replacement.

use klieo_core::{
    Agent, AgentContext, BusHandles, EpisodicMemory, Error, LlmClient, LongTermMemory,
    MemoryHandles, RunId, ShortTermMemory, ToolDef, ToolInvoker,
};
use std::sync::Arc;
use tokio_util::sync::CancellationToken;

#[cfg(feature = "tools")]
use klieo_core::Tool;

#[cfg(any(
    feature = "llm-openai",
    feature = "llm-anthropic",
    feature = "llm-gemini"
))]
use secrecy::SecretString;

/// Resolved klieo runtime. Holds every `Arc<dyn …>` port plus a parent
/// cancel token. Cheap to clone; expensive to construct (impl crates
/// open DB handles / pools during their `From` impls).
#[derive(Clone)]
pub struct App {
    llm: Arc<dyn LlmClient>,
    memory: MemoryHandles,
    bus: BusHandles,
    tools: Arc<dyn ToolInvoker>,
    catalogue: Vec<ToolDef>,
    parent_cancel: CancellationToken,
}

impl std::fmt::Debug for App {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("App")
            .field("llm", &self.llm.name())
            .field("tools", &self.catalogue.len())
            .field("cancelled", &self.parent_cancel.is_cancelled())
            .finish_non_exhaustive()
    }
}

impl App {
    /// Start a local-defaults builder: Ollama at
    /// `http://localhost:11434` + sqlite (`:memory:`) with the dummy
    /// embedder + in-process [`klieo_bus_memory::MemoryBus`]. Override
    /// any default by calling its setter on the returned builder.
    ///
    /// State is **ephemeral** — the in-memory SQLite database resets
    /// every run. Use this for tests, CI, and one-shot scripts. For
    /// iterative dev where memory should survive restarts use
    /// [`App::local_at`].
    ///
    /// Available only when the `llm-ollama`, `memory-sqlite`, and
    /// `bus-memory` features are all active. Without them, use
    /// [`App::builder`] and wire ports by hand.
    #[cfg(all(
        feature = "llm-ollama",
        feature = "memory-sqlite",
        feature = "bus-memory",
        feature = "tools",
    ))]
    pub fn local() -> AppBuilder {
        AppBuilder::new()
            .ollama("http://localhost:11434", "qwen2.5:14b")
            .sqlite(":memory:")
            .memory_bus()
    }

    /// Start a local-defaults builder that persists memory to `db_path`.
    ///
    /// Same as [`App::local`] except the SQLite database is written to
    /// the given path instead of `:memory:`. Memory (threads, episodic
    /// events) survives process restarts — the file is created on first
    /// run and reused on every subsequent run.
    ///
    /// Recommended for interactive dev:
    ///
    /// ```ignore
    /// let app = App::local_at("klieo.db").model("qwen2.5:14b").build().await?;
    /// ```
    ///
    /// Use [`App::local`] (`:memory:`) for tests and CI.
    #[cfg(all(
        feature = "llm-ollama",
        feature = "memory-sqlite",
        feature = "bus-memory",
        feature = "tools",
    ))]
    pub fn local_at(db_path: impl Into<std::path::PathBuf>) -> AppBuilder {
        AppBuilder::new()
            .ollama("http://localhost:11434", "qwen2.5:14b")
            .sqlite(db_path)
            .memory_bus()
    }

    /// Start an empty builder. Every port must be set explicitly.
    pub fn builder() -> AppBuilder {
        AppBuilder::new()
    }

    /// Mint a fresh [`AgentContext`] for one agent run. Each call
    /// produces a distinct [`RunId`] and a child cancel derived from
    /// `App`'s parent token — cancelling the parent cancels every
    /// in-flight run; per-run cancel does not affect siblings.
    pub fn context(&self, agent_name: impl Into<String>) -> AgentContext {
        AgentContext::new(
            self.llm.clone(),
            self.memory.short_term.clone(),
            self.memory.long_term.clone(),
            self.memory.episodic.clone(),
            self.bus.pubsub.clone(),
            self.bus.kv.clone(),
            self.bus.request_reply.clone(),
            self.bus.jobs.clone(),
            self.tools.clone(),
            RunId::new(),
            self.parent_cancel.child_token(),
            agent_name,
        )
    }

    /// Tool catalogue advertised to the LLM.
    pub fn tools_catalogue(&self) -> &[ToolDef] {
        &self.catalogue
    }

    /// Parent cancel token. Clone to share across runs (e.g.
    /// SIGINT-driven shutdown).
    pub fn cancel_token(&self) -> CancellationToken {
        self.parent_cancel.clone()
    }

    /// Convenience: mint a context with `agent.name()` as
    /// `agent_name`, then delegate to [`Agent::run`].
    ///
    /// Useful when the caller does not need to inspect or mutate the
    /// context between minting and run start. For composite agents
    /// that thread the same context through multiple `Agent::run`
    /// calls, mint via [`App::context`] and call [`Agent::run`]
    /// directly.
    pub async fn run<A: Agent>(&self, agent: &A, input: A::Input) -> Result<A::Output, A::Error> {
        let ctx = self.context(agent.name());
        agent.run(ctx, input).await
    }
}

/// Deferred-construction record for a provider chosen via shortcut.
///
/// Lets the builder hold provider-shaped config without instantiating
/// the client until [`AppBuilder::build`] runs (some providers do
/// async/fallible work in their ctors; recording the choice keeps the
/// chain sync until the final await point).
enum LlmShortcut {
    #[cfg(feature = "llm-ollama")]
    Ollama { base_url: String, model: String },
    #[cfg(feature = "llm-openai")]
    OpenAi {
        api_key: SecretString,
        model: String,
    },
    #[cfg(feature = "llm-anthropic")]
    Anthropic {
        api_key: SecretString,
        model: String,
    },
    #[cfg(feature = "llm-gemini")]
    Gemini {
        api_key: SecretString,
        model: String,
    },
}

/// Deferred-construction record for a bus chosen via shortcut.
enum BusShortcut {
    #[cfg(feature = "bus-memory")]
    Memory,
    #[cfg(feature = "bus-nats")]
    Nats(Box<klieo_bus_nats::NatsBusConfig>),
}

/// Fluent assembler for [`App`]. All setters consume `self` so the
/// chain reads top-to-bottom in user code.
#[derive(Default)]
pub struct AppBuilder {
    llm: Option<Arc<dyn LlmClient>>,
    memory: Option<MemoryHandles>,
    bus: Option<BusHandles>,
    tools_invoker: Option<Arc<dyn ToolInvoker>>,
    #[cfg(feature = "tools")]
    pending_tools: Vec<Arc<dyn Tool>>,
    parent_cancel: Option<CancellationToken>,

    llm_shortcut: Option<LlmShortcut>,
    bus_shortcut: Option<BusShortcut>,

    short_term: Option<Arc<dyn ShortTermMemory>>,
    long_term: Option<Arc<dyn LongTermMemory>>,
    episodic: Option<Arc<dyn EpisodicMemory>>,

    #[cfg(feature = "memory-sqlite")]
    sqlite_path: Option<std::path::PathBuf>,
}

impl AppBuilder {
    /// Construct an empty builder. Prefer [`App::builder`] or
    /// [`App::local`] at the call site.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the LLM port directly with an already-`Arc`-wrapped client.
    pub fn llm(mut self, llm: Arc<dyn LlmClient>) -> Self {
        self.llm = Some(llm);
        self
    }

    /// Set the three memory ports from any value convertible into
    /// [`MemoryHandles`] (e.g. `MemorySqlite::new(...).await?`).
    pub fn memory(mut self, memory: impl Into<MemoryHandles>) -> Self {
        self.memory = Some(memory.into());
        self
    }

    /// Set the four bus ports from any value convertible into
    /// [`BusHandles`] (e.g. `MemoryBus::new()` or
    /// `NatsBus::connect(cfg).await?`).
    pub fn bus(mut self, bus: impl Into<BusHandles>) -> Self {
        self.bus = Some(bus.into());
        self
    }

    /// Set the tool dispatcher directly. Mutually exclusive with
    /// [`AppBuilder::tool`] — calling both errors at `build()`.
    pub fn tools_invoker(mut self, tools: Arc<dyn ToolInvoker>) -> Self {
        self.tools_invoker = Some(tools);
        self
    }

    /// Register one tool. Repeated calls accumulate. The final
    /// `build()` consolidates them into a
    /// [`klieo_tools::ChainedInvoker`]. Mutually exclusive with
    /// [`AppBuilder::tools_invoker`].
    #[cfg(feature = "tools")]
    pub fn tool<T: Tool + 'static>(mut self, tool: T) -> Self {
        self.pending_tools.push(Arc::new(tool));
        self
    }

    /// Override the parent cancel token. Default: a fresh, uncancelled
    /// `CancellationToken::new()`.
    pub fn cancel_token(mut self, token: CancellationToken) -> Self {
        self.parent_cancel = Some(token);
        self
    }

    /// Set just the short-term-memory port. Composes with
    /// [`AppBuilder::long_term`] + [`AppBuilder::episodic`] to satisfy
    /// the memory triple. Useful for partial-shape impls like
    /// `MemoryNeo4j` (short + episodic) paired with `MemoryQdrant`
    /// (long).
    pub fn short_term(mut self, short_term: Arc<dyn ShortTermMemory>) -> Self {
        self.short_term = Some(short_term);
        self
    }

    /// Set just the long-term-memory port. See
    /// [`AppBuilder::short_term`] for composition semantics.
    pub fn long_term(mut self, long_term: Arc<dyn LongTermMemory>) -> Self {
        self.long_term = Some(long_term);
        self
    }

    /// Set just the episodic-memory port. See
    /// [`AppBuilder::short_term`] for composition semantics.
    pub fn episodic(mut self, episodic: Arc<dyn EpisodicMemory>) -> Self {
        self.episodic = Some(episodic);
        self
    }

    /// Configure Ollama as the LLM port. `base_url` accepts a
    /// scheme-prefixed URL (e.g. `"http://localhost:11434"`). Last
    /// provider shortcut wins; explicit [`AppBuilder::llm`] overrides
    /// every shortcut.
    ///
    /// Available with the `llm-ollama` feature.
    #[cfg(feature = "llm-ollama")]
    pub fn ollama(mut self, base_url: impl Into<String>, model: impl Into<String>) -> Self {
        self.llm_shortcut = Some(LlmShortcut::Ollama {
            base_url: base_url.into(),
            model: model.into(),
        });
        self
    }

    /// Override only the Ollama model on a builder already configured
    /// via [`AppBuilder::ollama`] (or [`App::local`]). Resets a
    /// non-Ollama provider shortcut to Ollama with the default base
    /// URL.
    #[cfg(feature = "llm-ollama")]
    pub fn model(mut self, model: impl Into<String>) -> Self {
        let base_url = match self.llm_shortcut.take() {
            Some(LlmShortcut::Ollama { base_url, .. }) => base_url,
            _ => "http://localhost:11434".to_string(),
        };
        self.llm_shortcut = Some(LlmShortcut::Ollama {
            base_url,
            model: model.into(),
        });
        self
    }

    /// Configure OpenAI Chat Completions as the LLM port.
    ///
    /// Available with the `llm-openai` feature.
    #[cfg(feature = "llm-openai")]
    pub fn openai(mut self, api_key: impl Into<SecretString>, model: impl Into<String>) -> Self {
        self.llm_shortcut = Some(LlmShortcut::OpenAi {
            api_key: api_key.into(),
            model: model.into(),
        });
        self
    }

    /// Configure Anthropic Messages as the LLM port.
    ///
    /// Available with the `llm-anthropic` feature.
    #[cfg(feature = "llm-anthropic")]
    pub fn anthropic(mut self, api_key: impl Into<SecretString>, model: impl Into<String>) -> Self {
        self.llm_shortcut = Some(LlmShortcut::Anthropic {
            api_key: api_key.into(),
            model: model.into(),
        });
        self
    }

    /// Configure Google Gemini as the LLM port.
    ///
    /// Available with the `llm-gemini` feature.
    #[cfg(feature = "llm-gemini")]
    pub fn gemini(mut self, api_key: impl Into<SecretString>, model: impl Into<String>) -> Self {
        self.llm_shortcut = Some(LlmShortcut::Gemini {
            api_key: api_key.into(),
            model: model.into(),
        });
        self
    }

    /// Use SQLite-backed memory with the dummy embedder. `path` may
    /// be `":memory:"` for an ephemeral DB or a file path for
    /// cross-run persistence.
    ///
    /// Available with the `memory-sqlite` feature.
    #[cfg(feature = "memory-sqlite")]
    pub fn sqlite(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.sqlite_path = Some(path.into());
        self
    }

    /// Use the in-process [`klieo_bus_memory::MemoryBus`]. Last bus
    /// shortcut wins; explicit [`AppBuilder::bus`] overrides every
    /// shortcut.
    ///
    /// Available with the `bus-memory` feature.
    #[cfg(feature = "bus-memory")]
    pub fn memory_bus(mut self) -> Self {
        self.bus_shortcut = Some(BusShortcut::Memory);
        self
    }

    /// Use a NATS JetStream bus. Resolves the connection during
    /// [`AppBuilder::build`].
    ///
    /// Available with the `bus-nats` feature.
    #[cfg(feature = "bus-nats")]
    pub fn nats(mut self, config: klieo_bus_nats::NatsBusConfig) -> Self {
        self.bus_shortcut = Some(BusShortcut::Nats(Box::new(config)));
        self
    }

    /// Assemble the [`App`]. Resolves feature-gated shortcuts into
    /// their typed equivalents, validates every required port, and
    /// fails with [`Error::AppBuildError`] if any are missing.
    pub async fn build(mut self) -> Result<App, Error> {
        self.resolve_shortcuts().await?;

        let llm = self.llm.ok_or(Error::AppBuildError { missing: "llm" })?;
        let memory = self
            .memory
            .ok_or(Error::AppBuildError { missing: "memory" })?;
        let bus = self.bus.ok_or(Error::AppBuildError { missing: "bus" })?;

        let (tools, catalogue) = resolve_tools(
            self.tools_invoker,
            #[cfg(feature = "tools")]
            self.pending_tools,
        )?;

        Ok(App {
            llm,
            memory,
            bus,
            tools,
            catalogue,
            parent_cancel: self.parent_cancel.unwrap_or_default(),
        })
    }

    async fn resolve_shortcuts(&mut self) -> Result<(), Error> {
        self.resolve_llm_shortcut();
        self.resolve_sqlite().await?;
        self.resolve_memory_partials()?;
        self.resolve_bus_shortcut().await?;
        Ok(())
    }

    fn resolve_llm_shortcut(&mut self) {
        if self.llm.is_some() {
            return;
        }
        match self.llm_shortcut.take() {
            None => {}
            #[cfg(feature = "llm-ollama")]
            Some(LlmShortcut::Ollama { base_url, model }) => {
                self.llm = Some(Arc::new(klieo_llm_ollama::OllamaClient::new(
                    base_url, model,
                )));
            }
            #[cfg(feature = "llm-openai")]
            Some(LlmShortcut::OpenAi { api_key, model }) => {
                self.llm = Some(Arc::new(klieo_llm_openai::OpenAiClient::new(
                    api_key, model,
                )));
            }
            #[cfg(feature = "llm-anthropic")]
            Some(LlmShortcut::Anthropic { api_key, model }) => {
                self.llm = Some(Arc::new(klieo_llm_anthropic::AnthropicClient::new(
                    api_key, model,
                )));
            }
            #[cfg(feature = "llm-gemini")]
            Some(LlmShortcut::Gemini { api_key, model }) => {
                self.llm = Some(Arc::new(klieo_llm_gemini::GeminiClient::new(
                    api_key, model,
                )));
            }
        }
    }

    #[cfg(feature = "memory-sqlite")]
    async fn resolve_sqlite(&mut self) -> Result<(), Error> {
        if self.memory.is_some() {
            return Ok(());
        }
        if let Some(path) = self.sqlite_path.take() {
            let mem = klieo_memory_sqlite::MemorySqlite::new(
                path,
                Arc::new(klieo_memory_sqlite::DummyEmbedder),
            )
            .await?;
            self.memory = Some(mem.into());
        }
        Ok(())
    }

    #[cfg(not(feature = "memory-sqlite"))]
    #[allow(clippy::unused_async)]
    async fn resolve_sqlite(&mut self) -> Result<(), Error> {
        Ok(())
    }

    /// Compose `short_term` + `long_term` + `episodic` partials into
    /// [`MemoryHandles`] when [`AppBuilder::memory`] and
    /// [`AppBuilder::sqlite`] were not set. Reports the first missing
    /// trait if some — but not all — partials are present.
    fn resolve_memory_partials(&mut self) -> Result<(), Error> {
        if self.memory.is_some() {
            return Ok(());
        }
        let any_partial =
            self.short_term.is_some() || self.long_term.is_some() || self.episodic.is_some();
        if !any_partial {
            return Ok(());
        }
        let short_term = self.short_term.take().ok_or(Error::AppBuildError {
            missing: "memory.short_term",
        })?;
        let long_term = self.long_term.take().ok_or(Error::AppBuildError {
            missing: "memory.long_term",
        })?;
        let episodic = self.episodic.take().ok_or(Error::AppBuildError {
            missing: "memory.episodic",
        })?;
        self.memory = Some(MemoryHandles::new(short_term, long_term, episodic));
        Ok(())
    }

    async fn resolve_bus_shortcut(&mut self) -> Result<(), Error> {
        if self.bus.is_some() {
            return Ok(());
        }
        match self.bus_shortcut.take() {
            None => {}
            #[cfg(feature = "bus-memory")]
            Some(BusShortcut::Memory) => {
                self.bus = Some(klieo_bus_memory::MemoryBus::new().into());
            }
            #[cfg(feature = "bus-nats")]
            Some(BusShortcut::Nats(config)) => {
                let bus = klieo_bus_nats::NatsBus::connect(*config).await?;
                self.bus = Some(bus.into());
            }
        }
        Ok(())
    }
}

fn resolve_tools(
    invoker: Option<Arc<dyn ToolInvoker>>,
    #[cfg(feature = "tools")] pending: Vec<Arc<dyn Tool>>,
) -> Result<(Arc<dyn ToolInvoker>, Vec<ToolDef>), Error> {
    #[cfg(feature = "tools")]
    {
        let has_pending = !pending.is_empty();
        match (invoker, has_pending) {
            (Some(_), true) => Err(Error::AppBuildError {
                missing: "tools (cannot combine .tool() with .tools_invoker())",
            }),
            (Some(inv), false) => {
                let cat = inv.catalogue();
                Ok((inv, cat))
            }
            (None, _) => {
                let mut chained = klieo_tools::ChainedInvoker::new();
                for t in pending {
                    chained
                        .add_tool(t)
                        .map_err(|e| Error::wrap("tool registration failed", e))?;
                }
                let cat = chained.catalogue();
                Ok((Arc::new(chained), cat))
            }
        }
    }
    #[cfg(not(feature = "tools"))]
    {
        let inv = invoker.ok_or(Error::AppBuildError { missing: "tools" })?;
        let cat = inv.catalogue();
        Ok((inv, cat))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use klieo_core::test_utils::{FakeLlmClient, FakeLlmStep, FakeToolInvoker};

    fn fake_llm() -> Arc<dyn LlmClient> {
        Arc::new(FakeLlmClient::new("fake"))
    }

    fn fake_tools() -> Arc<dyn ToolInvoker> {
        Arc::new(FakeToolInvoker::new())
    }

    #[tokio::test]
    async fn build_missing_llm_errors() {
        let err = App::builder()
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::AppBuildError { missing: "llm" }));
    }

    #[tokio::test]
    async fn build_missing_memory_errors() {
        let err = App::builder()
            .llm(fake_llm())
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::AppBuildError { missing: "memory" }));
    }

    #[tokio::test]
    async fn build_missing_bus_errors() {
        let err = App::builder()
            .llm(fake_llm())
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::AppBuildError { missing: "bus" }));
    }

    #[tokio::test]
    async fn build_local_with_only_model_succeeds() {
        let app = App::local().model("dummy-model").build().await.unwrap();
        assert!(app.tools_catalogue().is_empty());
        let ctx = app.context("test-agent");
        assert_eq!(ctx.agent_name, "test-agent");
    }

    #[tokio::test]
    async fn context_mints_fresh_run_id_per_call() {
        let app = App::local().model("dummy").build().await.unwrap();
        let a = app.context("agent");
        let b = app.context("agent");
        assert_ne!(a.run_id, b.run_id);
    }

    #[tokio::test]
    async fn cancel_token_propagates_to_minted_context() {
        let app = App::local().model("dummy").build().await.unwrap();
        let ctx = app.context("agent");
        assert!(!ctx.cancel.is_cancelled());
        app.cancel_token().cancel();
        assert!(ctx.cancel.is_cancelled());
    }

    #[tokio::test]
    async fn cannot_combine_tool_with_tools_invoker() {
        // Use klieo-tools' own Tool impl from a sibling crate. Manually
        // wire a pending tool via the builder field by going through
        // .tool() with an Arc-wrapped Tool object built via the
        // chained-invoker path.
        let mut builder = App::local().model("dummy");
        // Push a pending tool via the public API: a simple anonymous
        // Tool impl is overkill here — use the trivial fact that
        // .tools_invoker() + a non-empty pending list collides.
        builder.pending_tools.push(Arc::new(EchoTool));
        let err = builder
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            Error::AppBuildError {
                missing: "tools (cannot combine .tool() with .tools_invoker())"
            }
        ));
    }

    struct EchoTool;

    #[async_trait::async_trait]
    impl Tool for EchoTool {
        fn name(&self) -> &str {
            "echo"
        }
        fn description(&self) -> &str {
            "echo"
        }
        fn json_schema(&self) -> &serde_json::Value {
            static SCHEMA: std::sync::OnceLock<serde_json::Value> = std::sync::OnceLock::new();
            SCHEMA.get_or_init(|| serde_json::json!({"type": "object"}))
        }
        async fn invoke(
            &self,
            _args: serde_json::Value,
            _ctx: klieo_core::ToolCtx,
        ) -> Result<serde_json::Value, klieo_core::ToolError> {
            Ok(serde_json::Value::Null)
        }
    }

    #[tokio::test]
    async fn partial_memory_composes_into_handles() {
        let mem = klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap();
        let app = App::builder()
            .llm(fake_llm())
            .short_term(mem.short_term.clone())
            .long_term(mem.long_term.clone())
            .episodic(mem.episodic.clone())
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap();
        let ctx = app.context("partial");
        assert!(Arc::ptr_eq(&ctx.short_term, &mem.short_term));
        assert!(Arc::ptr_eq(&ctx.long_term, &mem.long_term));
        assert!(Arc::ptr_eq(&ctx.episodic, &mem.episodic));
    }

    #[tokio::test]
    async fn partial_memory_missing_long_term_errors() {
        let mem = klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap();
        let err = App::builder()
            .llm(fake_llm())
            .short_term(mem.short_term.clone())
            .episodic(mem.episodic.clone())
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            Error::AppBuildError {
                missing: "memory.long_term"
            }
        ));
    }

    #[tokio::test]
    async fn explicit_memory_overrides_partials() {
        let primary = klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap();
        let secondary = klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap();
        let primary_st = primary.short_term.clone();
        let app = App::builder()
            .llm(fake_llm())
            .memory(primary)
            .short_term(secondary.short_term)
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap();
        let ctx = app.context("override");
        assert!(Arc::ptr_eq(&ctx.short_term, &primary_st));
    }

    #[cfg(feature = "llm-openai")]
    #[tokio::test]
    async fn openai_shortcut_sets_llm() {
        let app = App::local()
            .openai("test-key".to_string(), "gpt-4o-mini")
            .build()
            .await
            .unwrap();
        let ctx = app.context("a");
        assert!(
            ctx.llm.name().starts_with("openai"),
            "got {}",
            ctx.llm.name()
        );
    }

    #[cfg(feature = "llm-anthropic")]
    #[tokio::test]
    async fn anthropic_shortcut_sets_llm() {
        let app = App::local()
            .anthropic("test-key".to_string(), "claude-3-5-haiku-latest")
            .build()
            .await
            .unwrap();
        let ctx = app.context("a");
        assert!(
            ctx.llm.name().starts_with("anthropic"),
            "got {}",
            ctx.llm.name()
        );
    }

    #[cfg(feature = "llm-gemini")]
    #[tokio::test]
    async fn gemini_shortcut_sets_llm() {
        let app = App::local()
            .gemini("test-key".to_string(), "gemini-2.0-flash")
            .build()
            .await
            .unwrap();
        let ctx = app.context("a");
        assert!(ctx.llm.name().contains("gemini"), "got {}", ctx.llm.name());
    }

    #[tokio::test]
    async fn last_llm_shortcut_wins() {
        let app = App::local()
            .ollama("http://localhost:11434", "qwen")
            .ollama("http://other:11434", "llama")
            .build()
            .await
            .unwrap();
        // Ollama client doesn't expose model via LlmClient; just verify
        // that build succeeded under the second config (no panic, no
        // error) which proves the second .ollama() call replaced the
        // first.
        let ctx = app.context("a");
        assert!(
            ctx.llm.name().starts_with("ollama"),
            "got {}",
            ctx.llm.name()
        );
    }

    #[cfg(feature = "bus-nats")]
    #[tokio::test]
    async fn nats_shortcut_errors_on_unreachable_server() {
        let cfg = klieo_bus_nats::NatsBusConfig {
            url: "nats://127.0.0.1:14223".to_string(),
            ..klieo_bus_nats::NatsBusConfig::default()
        };
        let err = App::builder()
            .llm(fake_llm())
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .nats(cfg)
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Bus(_)), "got {err:?}");
    }

    #[tokio::test]
    async fn run_delegates_to_agent_with_fresh_context() {
        let app = App::builder()
            .llm(Arc::new(
                FakeLlmClient::new("fake").with_steps(vec![FakeLlmStep::Text("done".into())]),
            ))
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap();
        let agent =
            klieo_core::SimpleAgent::new("greeter", "be brief", app.tools_catalogue().to_vec());
        let out = app.run(&agent, "hi".into()).await.unwrap();
        assert_eq!(out, "done");
    }

    #[cfg(all(
        feature = "llm-ollama",
        feature = "memory-sqlite",
        feature = "bus-memory",
        feature = "tools",
    ))]
    #[tokio::test]
    async fn build_local_at_file_path_succeeds() {
        let db_path = std::env::temp_dir().join("klieo_test_local_at.db");
        let _ = std::fs::remove_file(&db_path);
        let app = App::local_at(&db_path)
            .model("dummy-model")
            .build()
            .await
            .unwrap();
        assert!(app.tools_catalogue().is_empty());
        let ctx = app.context("test-agent");
        assert_eq!(ctx.agent_name, "test-agent");
        assert!(db_path.exists(), "sqlite file should have been created at {db_path:?}");
        let _ = std::fs::remove_file(&db_path);
    }
}