aidaemon-core 0.27.0

The aidaemon agent kernel: a small, hook-driven agent loop with tools, providers, receipts and resumable state
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
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use tokio_util::sync::CancellationToken;

use crate::error::{BuildError, CoreError};
use crate::event::EventSink;
use crate::hook::Hook;
use crate::limits::{Limits, StopCondition};
use crate::message::Message;
use crate::outcome::{RunOutcome, RunStatus};
use crate::provider::{Provider, ToolSpec};
use crate::run_loop::Driver;
use crate::safeguard::Safeguard;
use crate::state::{Interruption, RUN_STATE_SCHEMA, RunState};
use crate::store::RunStore;
use crate::stuck::StuckConfig;
use crate::tool::{Extensions, Tool};

/// Settles interruptions inside [`Agent::run_resolving`]: a clean-check
/// verifier, an approval UI, a policy. `None` leaves the run interrupted.
///
/// It is offered every interruption, whichever hook raised it: return `None`
/// for interruptions you do not own (check the reason, for example with
/// [`crate::is_untrusted_egress`]).
#[async_trait]
pub trait InterruptResolver: Send + Sync {
    async fn resolve(&self, state: &RunState, interruption: &Interruption) -> Option<Resolution>;
}

/// How to settle the call an interrupted run is waiting on.
#[derive(Debug, Clone, PartialEq)]
pub enum Resolution {
    /// Run the call. The hook that interrupted is not asked again; hooks
    /// registered after it still are, and may deny or interrupt.
    Approve,
    /// Refuse it. The reason goes back to the model as the tool result.
    Deny { reason: String },
    /// The owner refused a call that was interrupted for another reason and
    /// put to them by the resolver. Binds the run exactly as a denied
    /// [`InterruptKind::OwnerApproval`](crate::InterruptKind) does.
    OwnerDeclined {
        request: crate::approval::OwnerApprovalRequest,
        reason: String,
    },
    /// Nobody answered the owner's card: it expired, could not be
    /// delivered, or the turn was cancelled while it waited. The call is
    /// not run, but nothing is remembered as declined, and the reason goes
    /// back to the model marked as no answer, never as the owner's refusal.
    Unanswered { reason: String },
}

#[derive(Clone)]
pub(crate) struct AgentInner {
    pub id: String,
    pub model: String,
    pub instructions: String,
    pub provider: Arc<dyn Provider>,
    pub tools: HashMap<String, Arc<dyn Tool>>,
    /// Specs in registration order, computed once so the tool block of the
    /// prompt is byte-stable across turns (cache friendly). Deferred tools'
    /// specs come last, name-sorted, after `load_tools`.
    pub specs: Vec<ToolSpec>,
    /// Tools whose spec is sent only once loaded (see [`crate::LOAD_TOOLS`]
    /// and [`crate::LoadedTools`]).
    pub deferred: std::collections::HashSet<String>,
    /// Tools that no longer exist, each with the note a call to one gets
    /// (where its work went).
    pub retired: HashMap<String, String>,
    pub loaded: crate::tool_loading::LoadedTools,
    pub hooks: Vec<Arc<dyn Hook>>,
    pub limits: Limits,
    pub stuck: StuckConfig,
    pub stop_conditions: Vec<Arc<dyn StopCondition>>,
    pub sinks: Vec<Arc<dyn EventSink>>,
    pub store: Option<Arc<dyn RunStore>>,
    pub max_output_tokens: Option<u32>,
    /// Carried by every call's [`crate::ToolContext`].
    pub extensions: Extensions,
    /// Keys approval digests; `None` uses the process's random key.
    pub approval_key: Option<[u8; 32]>,
    /// The registered secrets every run redacts.
    pub redaction: crate::redaction::RedactionScope,
}

/// An agent is configuration: a stable id, a model, instructions, tools and
/// hooks. It holds no per-run state, is cheap to clone, and can run many
/// sessions concurrently.
#[derive(Clone)]
pub struct Agent {
    inner: Arc<AgentInner>,
}

impl Agent {
    pub fn builder(id: impl Into<String>) -> AgentBuilder {
        AgentBuilder::new(id)
    }

    pub fn id(&self) -> &str {
        &self.inner.id
    }

    pub fn tool_specs(&self) -> &[ToolSpec] {
        &self.inner.specs
    }

    pub fn limits(&self) -> &Limits {
        &self.inner.limits
    }

    /// The registered secrets this agent's runs redact
    /// ([`AgentBuilder::redaction_scope`]).
    pub fn redaction_scope(&self) -> &crate::redaction::RedactionScope {
        &self.inner.redaction
    }

    /// A copy of this agent with different limits (same id, tools, hooks).
    /// Used to give a child agent its own budget.
    pub fn with_limits(&self, limits: Limits) -> Agent {
        let mut inner = (*self.inner).clone();
        inner.limits = limits;
        Agent {
            inner: Arc::new(inner),
        }
    }

    /// A copy of this agent with one more hook, run after the existing ones.
    pub fn with_hook(&self, hook: impl Hook + 'static) -> Agent {
        let mut inner = (*self.inner).clone();
        inner.hooks.push(Arc::new(hook));
        Agent {
            inner: Arc::new(inner),
        }
    }

    /// Start a new run in `session_id` with one user message: text, or a
    /// [`crate::Message`] built with `Message::user(..).with_images(..)`.
    pub async fn run(
        &self,
        session_id: &str,
        input: impl Into<Message>,
    ) -> Result<RunOutcome, CoreError> {
        self.run_with_cancel(session_id, input, CancellationToken::new())
            .await
    }

    pub async fn run_with_cancel(
        &self,
        session_id: &str,
        input: impl Into<Message>,
        cancel: CancellationToken,
    ) -> Result<RunOutcome, CoreError> {
        let state = RunState::new(&self.inner.id, session_id, input);
        Driver::new(&self.inner, state, cancel).drive(None).await
    }

    /// Continue from saved state that is not interrupted, typically
    /// `previous.state.with_user_message("next question")`.
    pub async fn run_from(
        &self,
        state: RunState,
        cancel: CancellationToken,
    ) -> Result<RunOutcome, CoreError> {
        self.check_owner(&state)?;
        if state.pending.is_some() {
            return Err(CoreError::PendingInterruption);
        }
        Driver::new(&self.inner, state, cancel).drive(None).await
    }

    /// Like [`Agent::run_from`], but settles each interruption with
    /// `resolver` and continues, until the run ends or the resolver returns
    /// `None` (the interrupted outcome is then returned as is). It has no
    /// iteration cap of its own: a resolver that keeps resolving is bounded
    /// by the run's limits (turns, tool calls, tokens).
    ///
    /// Hooks see one run end (`Hook::on_run_end`), for the final outcome;
    /// the interruptions settled on the way are not run ends.
    pub async fn run_resolving(
        &self,
        state: RunState,
        cancel: CancellationToken,
        resolver: &dyn InterruptResolver,
    ) -> Result<RunOutcome, CoreError> {
        self.check_owner(&state)?;
        if state.pending.is_some() {
            return Err(CoreError::PendingInterruption);
        }
        let outcome = Driver::new(&self.inner, state, cancel.clone())
            .without_run_end()
            .with_resolver(resolver)
            .drive(None)
            .await?;
        self.settle_interruptions(outcome, cancel, resolver).await
    }

    /// End a run a crash or restart left mid tool batch without running
    /// anything more: unlike [`Agent::run_from`], no call is re-run and no
    /// model call is made. A call that had started gets an
    /// [`crate::ReceiptStatus::Indeterminate`] receipt, one that never
    /// started a [`crate::ReceiptStatus::Cancelled`] one, and the run ends
    /// [`RunStatus::Cancelled`]. A state that is not in flight just ends.
    pub async fn end_in_flight(&self, state: RunState) -> Result<RunOutcome, CoreError> {
        self.check_owner(&state)?;
        if state.pending.is_some() {
            return Err(CoreError::PendingInterruption);
        }
        Driver::new(&self.inner, state, CancellationToken::new())
            .end_in_flight()
            .await
    }

    /// Like [`Agent::resume_with_cancel`], but settles each later
    /// interruption with `resolver`, as [`Agent::run_resolving`] does.
    pub async fn resume_resolving(
        &self,
        state: RunState,
        resolution: Resolution,
        cancel: CancellationToken,
        resolver: &dyn InterruptResolver,
    ) -> Result<RunOutcome, CoreError> {
        self.check_owner(&state)?;
        if state.pending.is_none() {
            return Err(CoreError::NotInterrupted);
        }
        let outcome = Driver::new(&self.inner, state, cancel.clone())
            .without_run_end()
            .with_resolver(resolver)
            .drive(Some(resolution))
            .await?;
        self.settle_interruptions(outcome, cancel, resolver).await
    }

    async fn settle_interruptions(
        &self,
        mut outcome: RunOutcome,
        cancel: CancellationToken,
        resolver: &dyn InterruptResolver,
    ) -> Result<RunOutcome, CoreError> {
        while let RunStatus::Interrupted { interruption } = &outcome.status {
            let Some(resolution) = resolver.resolve(&outcome.state, interruption).await else {
                break;
            };
            self.check_owner(&outcome.state)?;
            outcome = Driver::new(&self.inner, outcome.state, cancel.clone())
                .without_run_end()
                .with_resolver(resolver)
                .drive(Some(resolution))
                .await?;
        }
        crate::run_loop::report_run_end(&self.inner, &outcome).await;
        Ok(outcome)
    }

    /// Settle the interruption in `state` and keep going. `state` may come
    /// from another process: it is plain data. A run paused for a child
    /// ([`crate::Pending::child`]) passes the answer down to the run that is
    /// waiting, at any depth; [`RunState::waiting_run`] says which that is.
    pub async fn resume(
        &self,
        state: RunState,
        resolution: Resolution,
    ) -> Result<RunOutcome, CoreError> {
        self.resume_with_cancel(state, resolution, CancellationToken::new())
            .await
    }

    pub async fn resume_with_cancel(
        &self,
        state: RunState,
        resolution: Resolution,
        cancel: CancellationToken,
    ) -> Result<RunOutcome, CoreError> {
        self.check_owner(&state)?;
        if state.pending.is_none() {
            return Err(CoreError::NotInterrupted);
        }
        Driver::new(&self.inner, state, cancel)
            .drive(Some(resolution))
            .await
    }

    fn check_owner(&self, state: &RunState) -> Result<(), CoreError> {
        let mut run = Some(state);
        while let Some(current) = run {
            if current.schema > RUN_STATE_SCHEMA {
                return Err(CoreError::UnsupportedRunState {
                    found: current.schema,
                    supported: RUN_STATE_SCHEMA,
                });
            }
            run = current.pending.as_ref().and_then(|p| p.child.as_deref());
        }
        if state.agent_id != self.inner.id {
            return Err(CoreError::AgentMismatch {
                expected: self.inner.id.clone(),
                found: state.agent_id.clone(),
            });
        }
        Ok(())
    }
}

/// Builder for [`Agent`]. `provider` and `model` are required, and an agent
/// with tools must cover every [`Safeguard::REQUIRED`] safeguard (see
/// [`AgentBuilder::attest`] and [`AgentBuilder::allow_unguarded`]).
pub struct AgentBuilder {
    id: String,
    model: Option<String>,
    instructions: String,
    provider: Option<Arc<dyn Provider>>,
    tools: Vec<Arc<dyn Tool>>,
    deferred_tools: Vec<Arc<dyn Tool>>,
    retired: HashMap<String, String>,
    loaded: crate::tool_loading::LoadedTools,
    hooks: Vec<Arc<dyn Hook>>,
    attested: Vec<Safeguard>,
    unguarded: bool,
    limits: Limits,
    stuck: StuckConfig,
    stop_conditions: Vec<Arc<dyn StopCondition>>,
    sinks: Vec<Arc<dyn EventSink>>,
    store: Option<Arc<dyn RunStore>>,
    max_output_tokens: Option<u32>,
    extensions: Extensions,
    approval_key: Option<[u8; 32]>,
    redaction: crate::redaction::RedactionScope,
}

impl AgentBuilder {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            model: None,
            instructions: String::new(),
            provider: None,
            tools: Vec::new(),
            deferred_tools: Vec::new(),
            retired: HashMap::new(),
            loaded: crate::tool_loading::LoadedTools::default(),
            hooks: Vec::new(),
            attested: Vec::new(),
            unguarded: false,
            limits: Limits::default(),
            stuck: StuckConfig::default(),
            stop_conditions: Vec::new(),
            sinks: Vec::new(),
            store: None,
            max_output_tokens: None,
            extensions: Extensions::default(),
            approval_key: None,
            redaction: crate::redaction::RedactionScope::process(),
        }
    }

    /// The model id sent with every request. Unset, the provider's
    /// [`Provider::default_model`] is used, and building fails with
    /// [`BuildError::MissingModel`] when it has none.
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// The system prompt. Sent first on every request and never compacted.
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = instructions.into();
        self
    }

    pub fn provider(mut self, provider: impl Provider + 'static) -> Self {
        self.provider = Some(Arc::new(provider));
        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
    }

    /// Register a tool whose schema is sent only once loaded: until then
    /// the built-in `load_tools` lists it by name and one line. Calling it
    /// directly loads it too. See [`crate::LOAD_TOOLS`] and
    /// [`crate::LoadedTools`].
    pub fn deferred_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
        self.deferred_tools.push(tool);
        self
    }

    /// A tool that no longer exists: a call to `name` is refused as an
    /// unknown tool, with `note` (where its work went) in the refusal.
    pub fn retired_tool(mut self, name: impl Into<String>, note: impl Into<String>) -> Self {
        self.retired.insert(name.into(), note.into());
        self
    }

    /// The set of loaded deferred tools. Share one across a session's runs
    /// so a tool loaded once stays loaded (and the tool block stable).
    pub fn loaded_tools(mut self, loaded: crate::tool_loading::LoadedTools) -> Self {
        self.loaded = loaded;
        self
    }

    /// Hooks run in registration order. Register a hook that interrupts
    /// (such as [`crate::UntrustedHook`]) last so a human or verifier sees
    /// only calls the other hooks already allowed.
    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
    }

    /// Declare that `safeguard` is enforced outside the hooks, for example
    /// by the application's own tool adapter. This is a statement the
    /// composition root makes on purpose, so it is reviewable in one place.
    pub fn attest(mut self, safeguard: Safeguard) -> Self {
        self.attested.push(safeguard);
        self
    }

    /// Build without the [`Safeguard::REQUIRED`] check: for tests, demos
    /// and tools that only touch data the agent fully controls.
    pub fn allow_unguarded(mut self) -> Self {
        self.unguarded = true;
        self
    }

    pub fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    pub fn stuck_detection(mut self, config: StuckConfig) -> Self {
        self.stuck = config;
        self
    }

    pub fn stop_when(mut self, condition: impl StopCondition + 'static) -> Self {
        self.stop_conditions.push(Arc::new(condition));
        self
    }

    pub fn event_sink(mut self, sink: impl EventSink + 'static) -> Self {
        self.sinks.push(Arc::new(sink));
        self
    }

    /// [`AgentBuilder::event_sink`] for a sink that is shared.
    pub fn event_sink_arc(mut self, sink: Arc<dyn EventSink>) -> Self {
        self.sinks.push(sink);
        self
    }

    pub fn store(mut self, store: Arc<dyn RunStore>) -> Self {
        self.store = Some(store);
        self
    }

    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
        self.max_output_tokens = Some(tokens);
        self
    }

    /// Application values every tool call can read from
    /// [`crate::ToolContext::extensions`]. Replaces any earlier set.
    /// The key approval digests are made with
    /// ([`crate::Interruption::digest`]). Without one each process uses its
    /// own random key, so an approval saved by one process and resumed by
    /// another is not honored: its call is judged again and the owner asked
    /// again. Give every process that resumes the same runs the same secret
    /// key to honor approvals across them.
    pub fn approval_key(mut self, key: [u8; 32]) -> Self {
        self.approval_key = Some(key);
        self
    }

    /// The registered secrets this agent's runs redact (see
    /// [`crate::redaction`]). The default is the process-wide set
    /// ([`RedactionScope::process`](crate::redaction::RedactionScope::process)),
    /// where every secret store registers what it hands out. Give an agent
    /// [`RedactionScope::isolated`](crate::redaction::RedactionScope::isolated)
    /// to keep its secrets from other agents' runs and theirs from its own,
    /// as a test should, and register its secrets there (its secret store
    /// and `Redactor` take the same scope).
    pub fn redaction_scope(mut self, scope: crate::redaction::RedactionScope) -> Self {
        self.redaction = scope;
        self
    }

    pub fn tool_extensions(mut self, extensions: Extensions) -> Self {
        self.extensions = extensions;
        self
    }

    pub fn build(self) -> Result<Agent, BuildError> {
        if self.id.trim().is_empty() {
            return Err(BuildError::EmptyAgentId);
        }
        let provider = self.provider.ok_or(BuildError::MissingProvider)?;
        let model = match self.model {
            Some(model) => model,
            None => provider
                .default_model()
                .map(str::to_string)
                .ok_or(BuildError::MissingModel)?,
        };

        let mut tools = HashMap::new();
        let mut specs = Vec::with_capacity(self.tools.len() + self.deferred_tools.len() + 1);
        let mut deferred = std::collections::HashSet::new();
        let mut deferred_specs = Vec::new();
        for tool in self.deferred_tools {
            let spec = tool.spec();
            if !valid_tool_name(&spec.name) {
                return Err(BuildError::InvalidToolName(spec.name));
            }
            if tools.insert(spec.name.clone(), tool).is_some() {
                return Err(BuildError::DuplicateTool(spec.name));
            }
            deferred.insert(spec.name.clone());
            deferred_specs.push(spec);
        }
        let mut core_tools = self.tools;
        if !deferred_specs.is_empty() {
            let entries = deferred_specs
                .iter()
                .map(|spec| crate::tool_loading::DeferredEntry {
                    name: spec.name.clone(),
                    summary: crate::tool_loading::one_line(&spec.description),
                })
                .collect();
            core_tools.push(Arc::new(crate::tool_loading::LoadToolsTool::new(
                entries,
                self.loaded.clone(),
            )));
        }
        for tool in core_tools {
            let spec = tool.spec();
            if !valid_tool_name(&spec.name) {
                return Err(BuildError::InvalidToolName(spec.name));
            }
            if tools.insert(spec.name.clone(), tool).is_some() {
                return Err(BuildError::DuplicateTool(spec.name));
            }
            specs.push(spec);
        }
        deferred_specs.sort_by(|a, b| a.name.cmp(&b.name));
        specs.extend(deferred_specs);
        if !specs.is_empty() && !self.unguarded {
            for required in Safeguard::REQUIRED {
                let covered = self.attested.contains(&required)
                    || self
                        .hooks
                        .iter()
                        .any(|h| h.safeguards().contains(&required));
                if !covered {
                    return Err(BuildError::MissingSafeguard(required));
                }
            }
        }

        Ok(Agent {
            inner: Arc::new(AgentInner {
                id: self.id,
                model,
                instructions: self.instructions,
                provider,
                tools,
                specs,
                deferred,
                retired: self.retired,
                loaded: self.loaded,
                hooks: self.hooks,
                limits: self.limits,
                stuck: self.stuck,
                stop_conditions: self.stop_conditions,
                sinks: self.sinks,
                store: self.store,
                max_output_tokens: self.max_output_tokens,
                extensions: self.extensions,
                approval_key: self.approval_key,
                redaction: self.redaction,
            }),
        })
    }
}

fn valid_tool_name(name: &str) -> bool {
    (1..=64).contains(&name.len())
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}