aidaemon-sdk 0.29.0

Build agents in Rust on the aidaemon kernel: one crate, a feature per subsystem (providers, tools, policies, memory, channels)
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
//! A short start: an agent with a provider, the required safeguards, a run
//! store and, if you give it a workspace, the default tools, in a few lines.
//!
//! `preset(id)` returns a [`Preset`] builder; its `build().await` returns
//! `Result<Agent, PresetError>`, a plain [`Agent`].
//!
//! ```no_run
//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
//! let agent: aidaemon_sdk::Agent = aidaemon_sdk::preset("helper")
//!     .provider_from_env() // ANTHROPIC_API_KEY or OPENAI_API_KEY
//!     .instructions("You maintain this repository. Verify changes with tests.")
//!     .workspace(".") // the default file, search and shell tools, confined here
//!     .build()
//!     .await?;
//! let outcome = agent.run("cli:synthetic-user-1", "Fix the failing test").await?;
//! println!("{}", outcome.final_text.unwrap_or_default());
//! # Ok(())
//! # }
//! ```
//!
//! What the preset adds, and how to change each part. The rule behind the
//! defaults: the preset adds what keeps an agent safe and running (the
//! safeguards, a run store); what the model is offered (tools, memory) is
//! only what you name.
//!
//! | Part | Default | Change with |
//! |---|---|---|
//! | Provider | none: name one | [`Preset::provider`], [`Preset::provider_from_env`], [`Preset::provider_from_env_or`] |
//! | 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`] |
//! | 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`] |
//! | Tools | none; with a workspace, [`default_tools`](crate::tools::default_tools) | [`Preset::tool`], [`Preset::workspace`] |
//! | Run store | in memory ([`MemoryStore`]) | [`Preset::store`], [`Preset::sqlite`] |
//! | 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 |
//! | Anything else | | [`Preset::hook`], [`Preset::configure`] (the [`AgentBuilder`]) |
//!
//! A destructive call pauses the run for the owner
//! ([`RunStatus::Interrupted`](crate::RunStatus)): answer it with
//! [`Agent::resume`]. So does, without a workspace, any call that may
//! change things and declares no paths, since no scope check covers it;
//! with a workspace, a call that declares no paths is refused. A tool that
//! touches no files says so: by name with [`Preset::path_free_tool`], or,
//! for one that may change things, by declaring complete effects with no
//! path ([`CallEffects::none`](crate::CallEffects::none); sub-agents
//! (`aidaemon_agents::AgentTool`) do).

use std::path::PathBuf;
use std::sync::Arc;

use aidaemon_core::{
    Agent, AgentBuilder, Authority, AuthorityHook, BuildError, Hook, MemoryStore, Provider,
    RunStore, Tool,
};
use aidaemon_policies::{
    ApprovalMode, ApprovalPolicy, EgressGuard, MemorySystem, MemoryTurn, Redactor, ScopeGuard,
    UndeclaredAccess, UntrustedOutput,
};

/// The model used with `ANTHROPIC_API_KEY` when `AIDAEMON_MODEL` is unset
/// (the catalog's, kept in step by a test).
pub const DEFAULT_ANTHROPIC_MODEL: &str = "claude-sonnet-5-5";
/// The model used with `OPENAI_API_KEY` when `AIDAEMON_MODEL` is unset
/// (the catalog's).
pub const DEFAULT_OPENAI_MODEL: &str = "gpt-5";

/// Start a [`Preset`] for an agent with this id.
pub fn preset(id: impl Into<String>) -> Preset {
    Preset::new(id)
}

/// Why a preset could not build.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PresetError {
    #[error(
        "no provider: call .provider(..), or set a provider key (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, ...)"
    )]
    NoProvider,
    /// The provider names no default model and none was set.
    #[error(
        "no model: call .model(..) (or set AIDAEMON_MODEL); provider `{provider}` names no \
         default model"
    )]
    NoModel { provider: String },
    #[error("provider configuration: {0}")]
    Provider(String),
    #[error("workspace: {0}")]
    Workspace(String),
    #[error("run store: {0}")]
    Store(String),
    #[error("memory: {0}")]
    Memory(String),
    #[error(transparent)]
    Build(#[from] BuildError),
}

/// A provider read from the environment and its default model.
pub type EnvProvider = (Arc<dyn Provider>, &'static str);

/// A provider read from the environment, and its default model: the first
/// provider of [`aidaemon_providers::catalog`] whose key is set, in catalog
/// order (`ANTHROPIC_API_KEY`, then `OPENAI_API_KEY` with `OPENAI_BASE_URL`
/// for any OpenAI-compatible server, then `GEMINI_API_KEY` /
/// `GOOGLE_API_KEY`, `OPENROUTER_API_KEY`, `XAI_API_KEY`, ...). `None` when
/// none is set.
///
/// The preset reads it for you: [`Preset::provider_from_env`] fails the
/// build ([`PresetError::NoProvider`]) when no key is set, for an app that
/// needs a real model; [`Preset::provider_from_env_or`] uses the fallback
/// you give instead, for an example or a test that must run without a key.
pub fn provider_from_env() -> Result<Option<EnvProvider>, PresetError> {
    let config = |err: aidaemon_providers::ConfigError| PresetError::Provider(err.to_string());
    let Some(found) = aidaemon_providers::catalog::keys_in_env()
        .into_iter()
        .next()
    else {
        return Ok(None);
    };
    let base_url = if found.entry.id == "openai" {
        env("OPENAI_BASE_URL").unwrap_or_default()
    } else {
        String::new()
    };
    let provider = found
        .entry
        .provider(&found.key, &base_url)
        .map_err(config)?;
    Ok(Some((provider, found.entry.models.primary)))
}

/// The default memory's turn: the agent's owner, reading and writing one
/// memory.
#[cfg(feature = "memory")]
fn owner_turn(id: &str) -> MemoryTurn {
    MemoryTurn::owner(id)
}

#[cfg(feature = "memory")]
fn memory_error(err: impl std::fmt::Display) -> PresetError {
    PresetError::Memory(err.to_string())
}

/// How often the preset looks for due memory services.
#[cfg(feature = "memory")]
const SERVICE_TICK: std::time::Duration = std::time::Duration::from_secs(5);

/// Run a memory system's background services until the agent is dropped:
/// the returned hook goes with the agent and stops them on drop. `None`
/// when there are none, or no Tokio runtime to run them on.
#[cfg(feature = "memory")]
fn run_services(services: Vec<Arc<dyn aidaemon_core::Service>>) -> Option<Arc<dyn Hook>> {
    if services.is_empty() {
        return None;
    }
    let runtime = tokio::runtime::Handle::try_current().ok()?;
    let mut host = aidaemon_core::ServiceHost::new(SERVICE_TICK).max_concurrent(1);
    for service in services {
        host = host.service(service);
    }
    let token = aidaemon_core::CancellationToken::new();
    runtime.spawn(host.run(token.clone()));
    Some(Arc::new(ServicesRunning(token)))
}

/// Held by the agent's hooks; stops the memory services when dropped.
#[cfg(feature = "memory")]
struct ServicesRunning(aidaemon_core::CancellationToken);

#[cfg(feature = "memory")]
impl Drop for ServicesRunning {
    fn drop(&mut self) {
        self.0.cancel();
    }
}

#[cfg(feature = "memory")]
#[async_trait::async_trait]
impl Hook for ServicesRunning {
    fn name(&self) -> &'static str {
        "memory_services"
    }
}

fn env(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|v| !v.trim().is_empty())
}

enum ProviderChoice {
    None,
    Explicit(Arc<dyn Provider>),
    Env,
    EnvOr(Arc<dyn Provider>),
}

enum MemoryChoice {
    /// The full memory system, when built with the `memory` feature.
    #[cfg_attr(not(feature = "memory"), allow(dead_code))]
    Default(Option<PathBuf>),
    None,
    Given(Arc<dyn MemorySystem>, MemoryTurn),
}

enum StoreChoice {
    Memory,
    Given(Arc<dyn RunStore>),
    #[cfg(feature = "sqlite")]
    Sqlite(PathBuf),
}

/// A builder that starts from working defaults (see the [module](self)).
/// Every part can be replaced.
pub struct Preset {
    id: String,
    provider: ProviderChoice,
    model: Option<String>,
    instructions: String,
    tools: Vec<Arc<dyn Tool>>,
    hooks: Vec<Arc<dyn Hook>>,
    #[cfg_attr(not(feature = "tools"), allow(dead_code))]
    workspace: Option<PathBuf>,
    store: StoreChoice,
    authority: Authority,
    approvals: ApprovalMode,
    default_hooks: bool,
    undeclared_writes: Option<UndeclaredAccess>,
    undeclared_reads: Option<UndeclaredAccess>,
    path_free: Vec<String>,
    memory: MemoryChoice,
    configure: Vec<Box<dyn FnOnce(AgentBuilder) -> AgentBuilder + Send>>,
}

impl Preset {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            provider: ProviderChoice::None,
            model: None,
            instructions: String::new(),
            tools: Vec::new(),
            hooks: Vec::new(),
            workspace: None,
            store: StoreChoice::Memory,
            authority: Authority::full(),
            approvals: ApprovalMode::DestructiveOnly,
            default_hooks: true,
            undeclared_writes: None,
            undeclared_reads: None,
            path_free: Vec::new(),
            memory: MemoryChoice::None,
            configure: Vec::new(),
        }
    }

    /// Use this provider. The model is [`Preset::model`], else
    /// `AIDAEMON_MODEL`, else the provider's [`Provider::default_model`]
    /// (a [`ScriptedProvider`](crate::testing) names `"scripted"`).
    pub fn provider(mut self, provider: impl Provider + 'static) -> Self {
        self.provider = ProviderChoice::Explicit(Arc::new(provider));
        self
    }

    /// [`Preset::provider`] for a shared provider.
    pub fn provider_arc(mut self, provider: Arc<dyn Provider>) -> Self {
        self.provider = ProviderChoice::Explicit(provider);
        self
    }

    /// Read the provider from the environment at build time (see
    /// [`provider_from_env`]); building fails with
    /// [`PresetError::NoProvider`] if no key is set. Use it when the agent
    /// needs a real model; use [`Preset::provider_from_env_or`] when it
    /// should still run without a key (an example, a test, a demo).
    pub fn provider_from_env(mut self) -> Self {
        self.provider = ProviderChoice::Env;
        self
    }

    /// Read the provider from the environment, and use `fallback` (a
    /// scripted provider, a local server) when no key is set, so the build
    /// never fails for want of a key (unlike [`Preset::provider_from_env`]).
    /// A set key the provider cannot be built from (a malformed
    /// `OPENAI_BASE_URL`) still fails it; `AIDAEMON_MODEL` applies only to
    /// the env provider, never to the fallback. With the
    /// fallback and no [`Preset::model`], the model is the fallback's
    /// [`Provider::default_model`], else `"scripted"`.
    pub fn provider_from_env_or(mut self, fallback: impl Provider + 'static) -> Self {
        self.provider = ProviderChoice::EnvOr(Arc::new(fallback));
        self
    }

    /// The model id, overriding `AIDAEMON_MODEL` and the provider's default.
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// The system prompt.
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = instructions.into();
        self
    }

    pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
        self.tools.push(Arc::new(tool));
        self
    }

    pub fn tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
        self.tools.push(tool);
        self
    }

    pub fn tools(mut self, tools: impl IntoIterator<Item = Arc<dyn Tool>>) -> Self {
        self.tools.extend(tools);
        self
    }

    /// A hook of your own. It runs after the authority, scope and egress
    /// checks and before the approval policy, so a hook that refuses a call
    /// does so before the owner is asked.
    pub fn hook(mut self, hook: impl Hook + 'static) -> Self {
        self.hooks.push(Arc::new(hook));
        self
    }

    pub fn hook_arc(mut self, hook: Arc<dyn Hook>) -> Self {
        self.hooks.push(hook);
        self
    }

    /// Work in `dir`: add the default tools (files, search, sandboxed
    /// shell, web fetch, checklist) confined to it, and scope every path to
    /// it.
    #[cfg(feature = "tools")]
    pub fn workspace(mut self, dir: impl Into<PathBuf>) -> Self {
        self.workspace = Some(dir.into());
        self
    }

    /// Keep runs in this store (default: in memory).
    pub fn store(mut self, store: Arc<dyn RunStore>) -> Self {
        self.store = StoreChoice::Given(store);
        self
    }

    /// Keep runs in a SQLite file, so they survive a crash or restart.
    #[cfg(feature = "sqlite")]
    pub fn sqlite(mut self, path: impl Into<PathBuf>) -> Self {
        self.store = StoreChoice::Sqlite(path.into());
        self
    }

    /// What the agent may do (default: [`Authority::full`]).
    pub fn authority(mut self, authority: Authority) -> Self {
        self.authority = authority;
        self
    }

    /// When the owner is asked (default: [`ApprovalMode::DestructiveOnly`]).
    pub fn approvals(mut self, mode: ApprovalMode) -> Self {
        self.approvals = mode;
        self
    }

    /// What the scope guard does with a call that may change things but
    /// declares no access ([`Tool::access`]). Unset, it is `Deny` with a
    /// [`Preset::workspace`] (every file tool there declares its paths).
    /// Without one, no directory is in scope to check against, so the
    /// scope guard lets such a call through and the approval policy asks
    /// the owner before it runs, whatever [`Preset::approvals`] says short
    /// of [`ApprovalMode::Never`]: a refund tool reaches the owner instead
    /// of being refused, and a tool that writes files without declaring
    /// them never runs unseen. Setting `Allow` here runs such calls without
    /// that extra ask; mark tools that touch no files with
    /// [`Preset::path_free_tool`] instead.
    pub fn undeclared_writes(mut self, policy: UndeclaredAccess) -> Self {
        self.undeclared_writes = Some(policy);
        self
    }

    /// What the scope guard does with a read-only call that declares no
    /// access. Unset, it is `Deny` with a [`Preset::workspace`] (a read
    /// outside it cannot be ruled out) and `Allow` without one.
    pub fn undeclared_reads(mut self, policy: UndeclaredAccess) -> Self {
        self.undeclared_reads = Some(policy);
        self
    }

    /// A tool of yours that touches no files (a ticket, a refund, an order
    /// lookup): its empty access manifest means "nothing" to the scope
    /// guard and the approval policy, so it is neither refused for not
    /// declaring paths nor asked about for that reason. The approval mode
    /// still applies. The tools a [`Preset::memory`] system gives are
    /// marked this way.
    pub fn path_free_tool(mut self, name: impl Into<String>) -> Self {
        self.path_free.push(name.into());
        self
    }

    /// Leave out the default safeguard hooks. Your own hooks (or
    /// [`AgentBuilder::attest`] through [`Preset::configure`]) must then
    /// cover every required safeguard, or building fails.
    pub fn without_default_hooks(mut self) -> Self {
        self.default_hooks = false;
        self
    }

    /// Long-term memory: the hooks and tools `system` gives for `turn`,
    /// and its guidance appended to the instructions. Any [`MemorySystem`]
    /// works (`aidaemon-memory`'s or your own).
    pub fn memory(mut self, system: Arc<dyn MemorySystem>, turn: MemoryTurn) -> Self {
        self.memory = MemoryChoice::Given(system, turn);
        self
    }

    /// Long-term memory: aidaemon's full memory system, kept in memory for
    /// the life of the agent. It offers the model three tools
    /// (`remember_fact`, `manage_memories`, `manage_people`) and adds
    /// recall to every request.
    #[cfg(feature = "memory")]
    pub fn with_memory(mut self) -> Self {
        self.memory = MemoryChoice::Default(None);
        self
    }

    /// [`Preset::with_memory`], kept in this SQLite file so it survives a
    /// restart, and learning in the background.
    #[cfg(feature = "memory")]
    pub fn memory_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.memory = MemoryChoice::Default(Some(path.into()));
        self
    }

    /// No long-term memory (the default; undoes [`Preset::memory`] and its
    /// kin).
    pub fn without_memory(mut self) -> Self {
        self.memory = MemoryChoice::None;
        self
    }

    /// Change the underlying [`AgentBuilder`] after the preset has filled
    /// it (limits, event sinks, extensions, stop conditions...).
    pub fn configure(
        mut self,
        configure: impl FnOnce(AgentBuilder) -> AgentBuilder + Send + 'static,
    ) -> Self {
        self.configure.push(Box::new(configure));
        self
    }

    /// The agent: a plain [`Agent`], to run with [`Agent::run`] and
    /// [`Agent::resume`] (or to hand to a `ChannelRunner`, or to another
    /// agent with `AgentExt::as_tool`). Fails with a [`PresetError`] (no
    /// provider, no model, a store or memory that would not open, an
    /// invalid agent).
    pub async fn build(self) -> Result<Agent, PresetError> {
        let mut stand_in = false;
        let (provider, default_model) = match self.provider {
            ProviderChoice::None => return Err(PresetError::NoProvider),
            ProviderChoice::Explicit(provider) => {
                let model = provider.default_model().map(str::to_string);
                (provider, model)
            }
            ProviderChoice::Env => {
                let (provider, model) = provider_from_env()?.ok_or(PresetError::NoProvider)?;
                (provider, Some(model.to_string()))
            }
            ProviderChoice::EnvOr(fallback) => match provider_from_env()? {
                Some((provider, model)) => (provider, Some(model.to_string())),
                None => {
                    stand_in = true;
                    let model = fallback.default_model().unwrap_or("scripted").to_string();
                    (fallback, Some(model))
                }
            },
        };
        // An `AIDAEMON_MODEL` meant for the env providers is not the
        // stand-in's business.
        let model = match self
            .model
            .or_else(|| env("AIDAEMON_MODEL").filter(|_| !stand_in))
            .or(default_model)
        {
            Some(model) => model,
            None => {
                return Err(PresetError::NoModel {
                    provider: provider.name().to_string(),
                });
            }
        };

        let mut builder = Agent::builder(self.id.clone())
            .provider(provider.clone())
            .model(model.clone());

        let mut instructions = self.instructions;
        let mut tools = self.tools;
        let mut extra_hooks = Vec::new();
        let mut path_free = self.path_free;
        let memory: Option<(Arc<dyn MemorySystem>, MemoryTurn)> = match self.memory {
            MemoryChoice::None => None,
            MemoryChoice::Given(system, turn) => Some((system, turn)),
            #[cfg(feature = "memory")]
            MemoryChoice::Default(path) => {
                let mut system = aidaemon_memory::full::FullMemory::open(path.as_deref())
                    .await
                    .map_err(memory_error)?;
                // A memory kept in a file learns in the background too, on
                // the agent's own provider and model.
                if path.is_some() {
                    system = system
                        .with_background(provider.clone(), model.clone())
                        .await
                        .map_err(memory_error)?;
                }
                Some((Arc::new(system), owner_turn(&self.id)))
            }
            #[cfg(not(feature = "memory"))]
            MemoryChoice::Default(_) => None,
        };
        if let Some((system, turn)) = &memory {
            let parts = system.turn(turn).await;
            extra_hooks.extend(parts.hooks);
            // Memory tools keep the memory store, not workspace files.
            path_free.extend(parts.tools.iter().map(|tool| tool.spec().name));
            tools.extend(parts.tools);
            if let Some(guidance) = system.guidance() {
                if !instructions.is_empty() {
                    instructions.push_str("\n\n");
                }
                instructions.push_str(&guidance);
            }
            #[cfg(feature = "memory")]
            if let Some(running) = run_services(system.services()) {
                extra_hooks.push(running);
            }
        }

        #[cfg_attr(not(feature = "tools"), allow(unused_mut))]
        let mut roots: Vec<PathBuf> = Vec::new();
        #[cfg(feature = "tools")]
        if let Some(dir) = &self.workspace {
            let workspace = crate::tools::Workspace::new(dir)
                .map_err(|err| PresetError::Workspace(format!("{}: {err}", dir.display())))?;
            roots.push(workspace.root().to_path_buf());
            tools.extend(crate::tools::default_tools(workspace));
        }

        // With a workspace, a call that declares no access cannot be checked
        // against it, so it is refused. Without one, nothing is in scope:
        // reads run, and a call that may change things asks the owner.
        let confined = !roots.is_empty();
        let ask_undeclared = !confined && self.undeclared_writes.is_none();
        let undeclared_writes = self.undeclared_writes.unwrap_or(if confined {
            UndeclaredAccess::Deny
        } else {
            UndeclaredAccess::Allow
        });
        let undeclared_reads = self.undeclared_reads.unwrap_or(if confined {
            UndeclaredAccess::Deny
        } else {
            UndeclaredAccess::Allow
        });
        let mut scope = ScopeGuard::new(&roots)
            .undeclared_writer(undeclared_writes)
            .undeclared_read_only(undeclared_reads);
        let mut approval =
            ApprovalPolicy::new(self.approvals).ask_undeclared_writes(ask_undeclared);
        // Rules judge paths resolved against the same base as the guard.
        if let Some(base) = roots.first() {
            approval = approval.base_dir(base);
        }
        for name in &path_free {
            scope = scope.path_free_tool(name.clone());
            approval = approval.path_free_tool(name.clone());
        }
        builder = builder.instructions(instructions);
        for tool in tools {
            builder = builder.tool_arc(tool);
        }
        if self.default_hooks {
            builder = builder
                .hook(AuthorityHook::new(self.authority))
                .hook(scope)
                .hook(EgressGuard::new());
        }
        for hook in self.hooks.into_iter().chain(extra_hooks) {
            builder = builder.hook_arc(hook);
        }
        if self.default_hooks {
            builder = builder
                .hook(approval)
                .hook(Redactor::default())
                .hook(UntrustedOutput::default());
        }

        let store: Arc<dyn RunStore> = match self.store {
            StoreChoice::Memory => Arc::new(MemoryStore::new()),
            StoreChoice::Given(store) => store,
            #[cfg(feature = "sqlite")]
            StoreChoice::Sqlite(path) => Arc::new(
                crate::store::SqliteStore::open(&path)
                    .await
                    .map_err(|err| PresetError::Store(format!("{}: {err}", path.display())))?,
            ),
        };
        builder = builder.store(store);
        for configure in self.configure {
            builder = configure(builder);
        }
        Ok(builder.build()?)
    }
}

#[cfg(test)]
mod catalog_tests {
    /// The documented defaults are the catalog's.
    #[test]
    fn the_default_models_are_the_catalogs() {
        let model = |id| {
            aidaemon_providers::catalog::find(id)
                .unwrap()
                .models
                .primary
        };
        assert_eq!(super::DEFAULT_ANTHROPIC_MODEL, model("anthropic_native"));
        assert_eq!(super::DEFAULT_OPENAI_MODEL, model("openai"));
    }
}