Skip to main content

aidaemon_sdk/
preset.rs

1//! A short start: an agent with a provider, the required safeguards, a run
2//! store and, if you give it a workspace, the default tools, in a few lines.
3//!
4//! `preset(id)` returns a [`Preset`] builder; its `build().await` returns
5//! `Result<Agent, PresetError>`, a plain [`Agent`].
6//!
7//! ```no_run
8//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
9//! let agent: aidaemon_sdk::Agent = aidaemon_sdk::preset("helper")
10//!     .provider_from_env() // ANTHROPIC_API_KEY or OPENAI_API_KEY
11//!     .instructions("You maintain this repository. Verify changes with tests.")
12//!     .workspace(".") // the default file, search and shell tools, confined here
13//!     .build()
14//!     .await?;
15//! let outcome = agent.run("cli:synthetic-user-1", "Fix the failing test").await?;
16//! println!("{}", outcome.final_text.unwrap_or_default());
17//! # Ok(())
18//! # }
19//! ```
20//!
21//! What the preset adds, and how to change each part. The rule behind the
22//! defaults: the preset adds what keeps an agent safe and running (the
23//! safeguards, a run store); what the model is offered (tools, memory) is
24//! only what you name.
25//!
26//! | Part | Default | Change with |
27//! |---|---|---|
28//! | Provider | none: name one | [`Preset::provider`], [`Preset::provider_from_env`], [`Preset::provider_from_env_or`] |
29//! | Model | [`Preset::model`]; else `AIDAEMON_MODEL`; else the provider's default (the env provider's starting model in [`aidaemon_providers::catalog`] ([`DEFAULT_ANTHROPIC_MODEL`], [`DEFAULT_OPENAI_MODEL`], ...), or [`Provider::default_model`], `"scripted"` for a [`ScriptedProvider`](crate::testing)). A provider with no default needs [`Preset::model`]: building fails with [`PresetError::NoModel`] | [`Preset::model`] |
30//! | Safeguards | [`AuthorityHook`] (full authority), [`ScopeGuard`] over the workspace, [`EgressGuard`], [`ApprovalPolicy`] (`DestructiveOnly`), [`Redactor`], [`UntrustedOutput`] | [`Preset::authority`], [`Preset::approvals`], [`Preset::undeclared_writes`], [`Preset::undeclared_reads`], [`Preset::path_free_tool`], [`Preset::without_default_hooks`] |
31//! | Tools | none; with a workspace, [`default_tools`](crate::tools::default_tools) | [`Preset::tool`], [`Preset::workspace`] |
32//! | Run store | in memory ([`MemoryStore`]) | [`Preset::store`], [`Preset::sqlite`] |
33//! | Memory | none | [`Preset::with_memory`] (feature `memory`, on by default): aidaemon's full memory system (`aidaemon_memory::full::FullMemory`: recall plus the `remember_fact`, `manage_memories` and `manage_people` tools), kept in memory; [`Preset::memory_path`]: the same in a SQLite file, where it also learns in the background (episodes, fact consolidation, decay, on the agent's provider); [`Preset::memory`]: any [`MemorySystem`]. A memory system's `services()` run while the agent lives |
34//! | Anything else | | [`Preset::hook`], [`Preset::configure`] (the [`AgentBuilder`]) |
35//!
36//! A destructive call pauses the run for the owner
37//! ([`RunStatus::Interrupted`](crate::RunStatus)): answer it with
38//! [`Agent::resume`]. So does, without a workspace, any call that may
39//! change things and declares no paths, since no scope check covers it;
40//! with a workspace, a call that declares no paths is refused. A tool that
41//! touches no files says so: by name with [`Preset::path_free_tool`], or,
42//! for one that may change things, by declaring complete effects with no
43//! path ([`CallEffects::none`](crate::CallEffects::none); sub-agents
44//! (`aidaemon_agents::AgentTool`) do).
45
46use std::path::PathBuf;
47use std::sync::Arc;
48
49use aidaemon_core::{
50    Agent, AgentBuilder, Authority, AuthorityHook, BuildError, Hook, MemoryStore, Provider,
51    RunStore, Tool,
52};
53use aidaemon_policies::{
54    ApprovalMode, ApprovalPolicy, EgressGuard, MemorySystem, MemoryTurn, Redactor, ScopeGuard,
55    UndeclaredAccess, UntrustedOutput,
56};
57
58/// The model used with `ANTHROPIC_API_KEY` when `AIDAEMON_MODEL` is unset
59/// (the catalog's, kept in step by a test).
60pub const DEFAULT_ANTHROPIC_MODEL: &str = "claude-sonnet-5-5";
61/// The model used with `OPENAI_API_KEY` when `AIDAEMON_MODEL` is unset
62/// (the catalog's).
63pub const DEFAULT_OPENAI_MODEL: &str = "gpt-5";
64
65/// Start a [`Preset`] for an agent with this id.
66pub fn preset(id: impl Into<String>) -> Preset {
67    Preset::new(id)
68}
69
70/// Why a preset could not build.
71#[derive(Debug, thiserror::Error)]
72#[non_exhaustive]
73pub enum PresetError {
74    #[error(
75        "no provider: call .provider(..), or set a provider key (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, ...)"
76    )]
77    NoProvider,
78    /// The provider names no default model and none was set.
79    #[error(
80        "no model: call .model(..) (or set AIDAEMON_MODEL); provider `{provider}` names no \
81         default model"
82    )]
83    NoModel { provider: String },
84    #[error("provider configuration: {0}")]
85    Provider(String),
86    #[error("workspace: {0}")]
87    Workspace(String),
88    #[error("run store: {0}")]
89    Store(String),
90    #[error("memory: {0}")]
91    Memory(String),
92    #[error(transparent)]
93    Build(#[from] BuildError),
94}
95
96/// A provider read from the environment and its default model.
97pub type EnvProvider = (Arc<dyn Provider>, &'static str);
98
99/// A provider read from the environment, and its default model: the first
100/// provider of [`aidaemon_providers::catalog`] whose key is set, in catalog
101/// order (`ANTHROPIC_API_KEY`, then `OPENAI_API_KEY` with `OPENAI_BASE_URL`
102/// for any OpenAI-compatible server, then `GEMINI_API_KEY` /
103/// `GOOGLE_API_KEY`, `OPENROUTER_API_KEY`, `XAI_API_KEY`, ...). `None` when
104/// none is set.
105///
106/// The preset reads it for you: [`Preset::provider_from_env`] fails the
107/// build ([`PresetError::NoProvider`]) when no key is set, for an app that
108/// needs a real model; [`Preset::provider_from_env_or`] uses the fallback
109/// you give instead, for an example or a test that must run without a key.
110pub fn provider_from_env() -> Result<Option<EnvProvider>, PresetError> {
111    let config = |err: aidaemon_providers::ConfigError| PresetError::Provider(err.to_string());
112    let Some(found) = aidaemon_providers::catalog::keys_in_env()
113        .into_iter()
114        .next()
115    else {
116        return Ok(None);
117    };
118    let base_url = if found.entry.id == "openai" {
119        env("OPENAI_BASE_URL").unwrap_or_default()
120    } else {
121        String::new()
122    };
123    let provider = found
124        .entry
125        .provider(&found.key, &base_url)
126        .map_err(config)?;
127    Ok(Some((provider, found.entry.models.primary)))
128}
129
130/// The default memory's turn: the agent's owner, reading and writing one
131/// memory.
132#[cfg(feature = "memory")]
133fn owner_turn(id: &str) -> MemoryTurn {
134    MemoryTurn::owner(id)
135}
136
137#[cfg(feature = "memory")]
138fn memory_error(err: impl std::fmt::Display) -> PresetError {
139    PresetError::Memory(err.to_string())
140}
141
142/// How often the preset looks for due memory services.
143#[cfg(feature = "memory")]
144const SERVICE_TICK: std::time::Duration = std::time::Duration::from_secs(5);
145
146/// Run a memory system's background services until the agent is dropped:
147/// the returned hook goes with the agent and stops them on drop. `None`
148/// when there are none, or no Tokio runtime to run them on.
149#[cfg(feature = "memory")]
150fn run_services(services: Vec<Arc<dyn aidaemon_core::Service>>) -> Option<Arc<dyn Hook>> {
151    if services.is_empty() {
152        return None;
153    }
154    let runtime = tokio::runtime::Handle::try_current().ok()?;
155    let mut host = aidaemon_core::ServiceHost::new(SERVICE_TICK).max_concurrent(1);
156    for service in services {
157        host = host.service(service);
158    }
159    let token = aidaemon_core::CancellationToken::new();
160    runtime.spawn(host.run(token.clone()));
161    Some(Arc::new(ServicesRunning(token)))
162}
163
164/// Held by the agent's hooks; stops the memory services when dropped.
165#[cfg(feature = "memory")]
166struct ServicesRunning(aidaemon_core::CancellationToken);
167
168#[cfg(feature = "memory")]
169impl Drop for ServicesRunning {
170    fn drop(&mut self) {
171        self.0.cancel();
172    }
173}
174
175#[cfg(feature = "memory")]
176#[async_trait::async_trait]
177impl Hook for ServicesRunning {
178    fn name(&self) -> &'static str {
179        "memory_services"
180    }
181}
182
183fn env(name: &str) -> Option<String> {
184    std::env::var(name).ok().filter(|v| !v.trim().is_empty())
185}
186
187enum ProviderChoice {
188    None,
189    Explicit(Arc<dyn Provider>),
190    Env,
191    EnvOr(Arc<dyn Provider>),
192}
193
194enum MemoryChoice {
195    /// The full memory system, when built with the `memory` feature.
196    #[cfg_attr(not(feature = "memory"), allow(dead_code))]
197    Default(Option<PathBuf>),
198    None,
199    Given(Arc<dyn MemorySystem>, MemoryTurn),
200}
201
202enum StoreChoice {
203    Memory,
204    Given(Arc<dyn RunStore>),
205    #[cfg(feature = "sqlite")]
206    Sqlite(PathBuf),
207}
208
209/// A builder that starts from working defaults (see the [module](self)).
210/// Every part can be replaced.
211pub struct Preset {
212    id: String,
213    provider: ProviderChoice,
214    model: Option<String>,
215    instructions: String,
216    tools: Vec<Arc<dyn Tool>>,
217    hooks: Vec<Arc<dyn Hook>>,
218    #[cfg_attr(not(feature = "tools"), allow(dead_code))]
219    workspace: Option<PathBuf>,
220    store: StoreChoice,
221    authority: Authority,
222    approvals: ApprovalMode,
223    default_hooks: bool,
224    undeclared_writes: Option<UndeclaredAccess>,
225    undeclared_reads: Option<UndeclaredAccess>,
226    path_free: Vec<String>,
227    memory: MemoryChoice,
228    configure: Vec<Box<dyn FnOnce(AgentBuilder) -> AgentBuilder + Send>>,
229}
230
231impl Preset {
232    pub fn new(id: impl Into<String>) -> Self {
233        Self {
234            id: id.into(),
235            provider: ProviderChoice::None,
236            model: None,
237            instructions: String::new(),
238            tools: Vec::new(),
239            hooks: Vec::new(),
240            workspace: None,
241            store: StoreChoice::Memory,
242            authority: Authority::full(),
243            approvals: ApprovalMode::DestructiveOnly,
244            default_hooks: true,
245            undeclared_writes: None,
246            undeclared_reads: None,
247            path_free: Vec::new(),
248            memory: MemoryChoice::None,
249            configure: Vec::new(),
250        }
251    }
252
253    /// Use this provider. The model is [`Preset::model`], else
254    /// `AIDAEMON_MODEL`, else the provider's [`Provider::default_model`]
255    /// (a [`ScriptedProvider`](crate::testing) names `"scripted"`).
256    pub fn provider(mut self, provider: impl Provider + 'static) -> Self {
257        self.provider = ProviderChoice::Explicit(Arc::new(provider));
258        self
259    }
260
261    /// [`Preset::provider`] for a shared provider.
262    pub fn provider_arc(mut self, provider: Arc<dyn Provider>) -> Self {
263        self.provider = ProviderChoice::Explicit(provider);
264        self
265    }
266
267    /// Read the provider from the environment at build time (see
268    /// [`provider_from_env`]); building fails with
269    /// [`PresetError::NoProvider`] if no key is set. Use it when the agent
270    /// needs a real model; use [`Preset::provider_from_env_or`] when it
271    /// should still run without a key (an example, a test, a demo).
272    pub fn provider_from_env(mut self) -> Self {
273        self.provider = ProviderChoice::Env;
274        self
275    }
276
277    /// Read the provider from the environment, and use `fallback` (a
278    /// scripted provider, a local server) when no key is set, so the build
279    /// never fails for want of a key (unlike [`Preset::provider_from_env`]).
280    /// A set key the provider cannot be built from (a malformed
281    /// `OPENAI_BASE_URL`) still fails it; `AIDAEMON_MODEL` applies only to
282    /// the env provider, never to the fallback. With the
283    /// fallback and no [`Preset::model`], the model is the fallback's
284    /// [`Provider::default_model`], else `"scripted"`.
285    pub fn provider_from_env_or(mut self, fallback: impl Provider + 'static) -> Self {
286        self.provider = ProviderChoice::EnvOr(Arc::new(fallback));
287        self
288    }
289
290    /// The model id, overriding `AIDAEMON_MODEL` and the provider's default.
291    pub fn model(mut self, model: impl Into<String>) -> Self {
292        self.model = Some(model.into());
293        self
294    }
295
296    /// The system prompt.
297    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
298        self.instructions = instructions.into();
299        self
300    }
301
302    pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
303        self.tools.push(Arc::new(tool));
304        self
305    }
306
307    pub fn tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
308        self.tools.push(tool);
309        self
310    }
311
312    pub fn tools(mut self, tools: impl IntoIterator<Item = Arc<dyn Tool>>) -> Self {
313        self.tools.extend(tools);
314        self
315    }
316
317    /// A hook of your own. It runs after the authority, scope and egress
318    /// checks and before the approval policy, so a hook that refuses a call
319    /// does so before the owner is asked.
320    pub fn hook(mut self, hook: impl Hook + 'static) -> Self {
321        self.hooks.push(Arc::new(hook));
322        self
323    }
324
325    pub fn hook_arc(mut self, hook: Arc<dyn Hook>) -> Self {
326        self.hooks.push(hook);
327        self
328    }
329
330    /// Work in `dir`: add the default tools (files, search, sandboxed
331    /// shell, web fetch, checklist) confined to it, and scope every path to
332    /// it.
333    #[cfg(feature = "tools")]
334    pub fn workspace(mut self, dir: impl Into<PathBuf>) -> Self {
335        self.workspace = Some(dir.into());
336        self
337    }
338
339    /// Keep runs in this store (default: in memory).
340    pub fn store(mut self, store: Arc<dyn RunStore>) -> Self {
341        self.store = StoreChoice::Given(store);
342        self
343    }
344
345    /// Keep runs in a SQLite file, so they survive a crash or restart.
346    #[cfg(feature = "sqlite")]
347    pub fn sqlite(mut self, path: impl Into<PathBuf>) -> Self {
348        self.store = StoreChoice::Sqlite(path.into());
349        self
350    }
351
352    /// What the agent may do (default: [`Authority::full`]).
353    pub fn authority(mut self, authority: Authority) -> Self {
354        self.authority = authority;
355        self
356    }
357
358    /// When the owner is asked (default: [`ApprovalMode::DestructiveOnly`]).
359    pub fn approvals(mut self, mode: ApprovalMode) -> Self {
360        self.approvals = mode;
361        self
362    }
363
364    /// What the scope guard does with a call that may change things but
365    /// declares no access ([`Tool::access`]). Unset, it is `Deny` with a
366    /// [`Preset::workspace`] (every file tool there declares its paths).
367    /// Without one, no directory is in scope to check against, so the
368    /// scope guard lets such a call through and the approval policy asks
369    /// the owner before it runs, whatever [`Preset::approvals`] says short
370    /// of [`ApprovalMode::Never`]: a refund tool reaches the owner instead
371    /// of being refused, and a tool that writes files without declaring
372    /// them never runs unseen. Setting `Allow` here runs such calls without
373    /// that extra ask; mark tools that touch no files with
374    /// [`Preset::path_free_tool`] instead.
375    pub fn undeclared_writes(mut self, policy: UndeclaredAccess) -> Self {
376        self.undeclared_writes = Some(policy);
377        self
378    }
379
380    /// What the scope guard does with a read-only call that declares no
381    /// access. Unset, it is `Deny` with a [`Preset::workspace`] (a read
382    /// outside it cannot be ruled out) and `Allow` without one.
383    pub fn undeclared_reads(mut self, policy: UndeclaredAccess) -> Self {
384        self.undeclared_reads = Some(policy);
385        self
386    }
387
388    /// A tool of yours that touches no files (a ticket, a refund, an order
389    /// lookup): its empty access manifest means "nothing" to the scope
390    /// guard and the approval policy, so it is neither refused for not
391    /// declaring paths nor asked about for that reason. The approval mode
392    /// still applies. The tools a [`Preset::memory`] system gives are
393    /// marked this way.
394    pub fn path_free_tool(mut self, name: impl Into<String>) -> Self {
395        self.path_free.push(name.into());
396        self
397    }
398
399    /// Leave out the default safeguard hooks. Your own hooks (or
400    /// [`AgentBuilder::attest`] through [`Preset::configure`]) must then
401    /// cover every required safeguard, or building fails.
402    pub fn without_default_hooks(mut self) -> Self {
403        self.default_hooks = false;
404        self
405    }
406
407    /// Long-term memory: the hooks and tools `system` gives for `turn`,
408    /// and its guidance appended to the instructions. Any [`MemorySystem`]
409    /// works (`aidaemon-memory`'s or your own).
410    pub fn memory(mut self, system: Arc<dyn MemorySystem>, turn: MemoryTurn) -> Self {
411        self.memory = MemoryChoice::Given(system, turn);
412        self
413    }
414
415    /// Long-term memory: aidaemon's full memory system, kept in memory for
416    /// the life of the agent. It offers the model three tools
417    /// (`remember_fact`, `manage_memories`, `manage_people`) and adds
418    /// recall to every request.
419    #[cfg(feature = "memory")]
420    pub fn with_memory(mut self) -> Self {
421        self.memory = MemoryChoice::Default(None);
422        self
423    }
424
425    /// [`Preset::with_memory`], kept in this SQLite file so it survives a
426    /// restart, and learning in the background.
427    #[cfg(feature = "memory")]
428    pub fn memory_path(mut self, path: impl Into<PathBuf>) -> Self {
429        self.memory = MemoryChoice::Default(Some(path.into()));
430        self
431    }
432
433    /// No long-term memory (the default; undoes [`Preset::memory`] and its
434    /// kin).
435    pub fn without_memory(mut self) -> Self {
436        self.memory = MemoryChoice::None;
437        self
438    }
439
440    /// Change the underlying [`AgentBuilder`] after the preset has filled
441    /// it (limits, event sinks, extensions, stop conditions...).
442    pub fn configure(
443        mut self,
444        configure: impl FnOnce(AgentBuilder) -> AgentBuilder + Send + 'static,
445    ) -> Self {
446        self.configure.push(Box::new(configure));
447        self
448    }
449
450    /// The agent: a plain [`Agent`], to run with [`Agent::run`] and
451    /// [`Agent::resume`] (or to hand to a `ChannelRunner`, or to another
452    /// agent with `AgentExt::as_tool`). Fails with a [`PresetError`] (no
453    /// provider, no model, a store or memory that would not open, an
454    /// invalid agent).
455    pub async fn build(self) -> Result<Agent, PresetError> {
456        let mut stand_in = false;
457        let (provider, default_model) = match self.provider {
458            ProviderChoice::None => return Err(PresetError::NoProvider),
459            ProviderChoice::Explicit(provider) => {
460                let model = provider.default_model().map(str::to_string);
461                (provider, model)
462            }
463            ProviderChoice::Env => {
464                let (provider, model) = provider_from_env()?.ok_or(PresetError::NoProvider)?;
465                (provider, Some(model.to_string()))
466            }
467            ProviderChoice::EnvOr(fallback) => match provider_from_env()? {
468                Some((provider, model)) => (provider, Some(model.to_string())),
469                None => {
470                    stand_in = true;
471                    let model = fallback.default_model().unwrap_or("scripted").to_string();
472                    (fallback, Some(model))
473                }
474            },
475        };
476        // An `AIDAEMON_MODEL` meant for the env providers is not the
477        // stand-in's business.
478        let model = match self
479            .model
480            .or_else(|| env("AIDAEMON_MODEL").filter(|_| !stand_in))
481            .or(default_model)
482        {
483            Some(model) => model,
484            None => {
485                return Err(PresetError::NoModel {
486                    provider: provider.name().to_string(),
487                });
488            }
489        };
490
491        let mut builder = Agent::builder(self.id.clone())
492            .provider(provider.clone())
493            .model(model.clone());
494
495        let mut instructions = self.instructions;
496        let mut tools = self.tools;
497        let mut extra_hooks = Vec::new();
498        let mut path_free = self.path_free;
499        let memory: Option<(Arc<dyn MemorySystem>, MemoryTurn)> = match self.memory {
500            MemoryChoice::None => None,
501            MemoryChoice::Given(system, turn) => Some((system, turn)),
502            #[cfg(feature = "memory")]
503            MemoryChoice::Default(path) => {
504                let mut system = aidaemon_memory::full::FullMemory::open(path.as_deref())
505                    .await
506                    .map_err(memory_error)?;
507                // A memory kept in a file learns in the background too, on
508                // the agent's own provider and model.
509                if path.is_some() {
510                    system = system
511                        .with_background(provider.clone(), model.clone())
512                        .await
513                        .map_err(memory_error)?;
514                }
515                Some((Arc::new(system), owner_turn(&self.id)))
516            }
517            #[cfg(not(feature = "memory"))]
518            MemoryChoice::Default(_) => None,
519        };
520        if let Some((system, turn)) = &memory {
521            let parts = system.turn(turn).await;
522            extra_hooks.extend(parts.hooks);
523            // Memory tools keep the memory store, not workspace files.
524            path_free.extend(parts.tools.iter().map(|tool| tool.spec().name));
525            tools.extend(parts.tools);
526            if let Some(guidance) = system.guidance() {
527                if !instructions.is_empty() {
528                    instructions.push_str("\n\n");
529                }
530                instructions.push_str(&guidance);
531            }
532            #[cfg(feature = "memory")]
533            if let Some(running) = run_services(system.services()) {
534                extra_hooks.push(running);
535            }
536        }
537
538        #[cfg_attr(not(feature = "tools"), allow(unused_mut))]
539        let mut roots: Vec<PathBuf> = Vec::new();
540        #[cfg(feature = "tools")]
541        if let Some(dir) = &self.workspace {
542            let workspace = crate::tools::Workspace::new(dir)
543                .map_err(|err| PresetError::Workspace(format!("{}: {err}", dir.display())))?;
544            roots.push(workspace.root().to_path_buf());
545            tools.extend(crate::tools::default_tools(workspace));
546        }
547
548        // With a workspace, a call that declares no access cannot be checked
549        // against it, so it is refused. Without one, nothing is in scope:
550        // reads run, and a call that may change things asks the owner.
551        let confined = !roots.is_empty();
552        let ask_undeclared = !confined && self.undeclared_writes.is_none();
553        let undeclared_writes = self.undeclared_writes.unwrap_or(if confined {
554            UndeclaredAccess::Deny
555        } else {
556            UndeclaredAccess::Allow
557        });
558        let undeclared_reads = self.undeclared_reads.unwrap_or(if confined {
559            UndeclaredAccess::Deny
560        } else {
561            UndeclaredAccess::Allow
562        });
563        let mut scope = ScopeGuard::new(&roots)
564            .undeclared_writer(undeclared_writes)
565            .undeclared_read_only(undeclared_reads);
566        let mut approval =
567            ApprovalPolicy::new(self.approvals).ask_undeclared_writes(ask_undeclared);
568        // Rules judge paths resolved against the same base as the guard.
569        if let Some(base) = roots.first() {
570            approval = approval.base_dir(base);
571        }
572        for name in &path_free {
573            scope = scope.path_free_tool(name.clone());
574            approval = approval.path_free_tool(name.clone());
575        }
576        builder = builder.instructions(instructions);
577        for tool in tools {
578            builder = builder.tool_arc(tool);
579        }
580        if self.default_hooks {
581            builder = builder
582                .hook(AuthorityHook::new(self.authority))
583                .hook(scope)
584                .hook(EgressGuard::new());
585        }
586        for hook in self.hooks.into_iter().chain(extra_hooks) {
587            builder = builder.hook_arc(hook);
588        }
589        if self.default_hooks {
590            builder = builder
591                .hook(approval)
592                .hook(Redactor::default())
593                .hook(UntrustedOutput::default());
594        }
595
596        let store: Arc<dyn RunStore> = match self.store {
597            StoreChoice::Memory => Arc::new(MemoryStore::new()),
598            StoreChoice::Given(store) => store,
599            #[cfg(feature = "sqlite")]
600            StoreChoice::Sqlite(path) => Arc::new(
601                crate::store::SqliteStore::open(&path)
602                    .await
603                    .map_err(|err| PresetError::Store(format!("{}: {err}", path.display())))?,
604            ),
605        };
606        builder = builder.store(store);
607        for configure in self.configure {
608            builder = configure(builder);
609        }
610        Ok(builder.build()?)
611    }
612}
613
614#[cfg(test)]
615mod catalog_tests {
616    /// The documented defaults are the catalog's.
617    #[test]
618    fn the_default_models_are_the_catalogs() {
619        let model = |id| {
620            aidaemon_providers::catalog::find(id)
621                .unwrap()
622                .models
623                .primary
624        };
625        assert_eq!(super::DEFAULT_ANTHROPIC_MODEL, model("anthropic_native"));
626        assert_eq!(super::DEFAULT_OPENAI_MODEL, model("openai"));
627    }
628}