Skip to main content

aidaemon_core/
agent.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use tokio_util::sync::CancellationToken;
6
7use crate::error::{BuildError, CoreError};
8use crate::event::EventSink;
9use crate::hook::Hook;
10use crate::limits::{Limits, StopCondition};
11use crate::message::Message;
12use crate::outcome::{RunOutcome, RunStatus};
13use crate::provider::{Provider, ToolSpec};
14use crate::run_loop::Driver;
15use crate::safeguard::Safeguard;
16use crate::state::{Interruption, RUN_STATE_SCHEMA, RunState};
17use crate::store::RunStore;
18use crate::stuck::StuckConfig;
19use crate::tool::{Extensions, Tool};
20
21/// Settles interruptions inside [`Agent::run_resolving`]: a clean-check
22/// verifier, an approval UI, a policy. `None` leaves the run interrupted.
23///
24/// It is offered every interruption, whichever hook raised it: return `None`
25/// for interruptions you do not own (check the reason, for example with
26/// [`crate::is_untrusted_egress`]).
27#[async_trait]
28pub trait InterruptResolver: Send + Sync {
29    async fn resolve(&self, state: &RunState, interruption: &Interruption) -> Option<Resolution>;
30}
31
32/// How to settle the call an interrupted run is waiting on.
33#[derive(Debug, Clone, PartialEq)]
34pub enum Resolution {
35    /// Run the call. The hook that interrupted is not asked again; hooks
36    /// registered after it still are, and may deny or interrupt.
37    Approve,
38    /// Refuse it. The reason goes back to the model as the tool result.
39    Deny { reason: String },
40    /// The owner refused a call that was interrupted for another reason and
41    /// put to them by the resolver. Binds the run exactly as a denied
42    /// [`InterruptKind::OwnerApproval`](crate::InterruptKind) does.
43    OwnerDeclined {
44        request: crate::approval::OwnerApprovalRequest,
45        reason: String,
46    },
47    /// Nobody answered the owner's card: it expired, could not be
48    /// delivered, or the turn was cancelled while it waited. The call is
49    /// not run, but nothing is remembered as declined, and the reason goes
50    /// back to the model marked as no answer, never as the owner's refusal.
51    Unanswered { reason: String },
52}
53
54#[derive(Clone)]
55pub(crate) struct AgentInner {
56    pub id: String,
57    pub model: String,
58    pub instructions: String,
59    pub provider: Arc<dyn Provider>,
60    pub tools: HashMap<String, Arc<dyn Tool>>,
61    /// Specs in registration order, computed once so the tool block of the
62    /// prompt is byte-stable across turns (cache friendly). Deferred tools'
63    /// specs come last, name-sorted, after `load_tools`.
64    pub specs: Vec<ToolSpec>,
65    /// Tools whose spec is sent only once loaded (see [`crate::LOAD_TOOLS`]
66    /// and [`crate::LoadedTools`]).
67    pub deferred: std::collections::HashSet<String>,
68    /// Tools that no longer exist, each with the note a call to one gets
69    /// (where its work went).
70    pub retired: HashMap<String, String>,
71    pub loaded: crate::tool_loading::LoadedTools,
72    pub hooks: Vec<Arc<dyn Hook>>,
73    pub limits: Limits,
74    pub stuck: StuckConfig,
75    pub stop_conditions: Vec<Arc<dyn StopCondition>>,
76    pub sinks: Vec<Arc<dyn EventSink>>,
77    pub store: Option<Arc<dyn RunStore>>,
78    pub max_output_tokens: Option<u32>,
79    /// Carried by every call's [`crate::ToolContext`].
80    pub extensions: Extensions,
81    /// Keys approval digests; `None` uses the process's random key.
82    pub approval_key: Option<[u8; 32]>,
83    /// The registered secrets every run redacts.
84    pub redaction: crate::redaction::RedactionScope,
85}
86
87/// An agent is configuration: a stable id, a model, instructions, tools and
88/// hooks. It holds no per-run state, is cheap to clone, and can run many
89/// sessions concurrently.
90#[derive(Clone)]
91pub struct Agent {
92    inner: Arc<AgentInner>,
93}
94
95impl Agent {
96    pub fn builder(id: impl Into<String>) -> AgentBuilder {
97        AgentBuilder::new(id)
98    }
99
100    pub fn id(&self) -> &str {
101        &self.inner.id
102    }
103
104    pub fn tool_specs(&self) -> &[ToolSpec] {
105        &self.inner.specs
106    }
107
108    pub fn limits(&self) -> &Limits {
109        &self.inner.limits
110    }
111
112    /// The registered secrets this agent's runs redact
113    /// ([`AgentBuilder::redaction_scope`]).
114    pub fn redaction_scope(&self) -> &crate::redaction::RedactionScope {
115        &self.inner.redaction
116    }
117
118    /// A copy of this agent with different limits (same id, tools, hooks).
119    /// Used to give a child agent its own budget.
120    pub fn with_limits(&self, limits: Limits) -> Agent {
121        let mut inner = (*self.inner).clone();
122        inner.limits = limits;
123        Agent {
124            inner: Arc::new(inner),
125        }
126    }
127
128    /// A copy of this agent with one more hook, run after the existing ones.
129    pub fn with_hook(&self, hook: impl Hook + 'static) -> Agent {
130        let mut inner = (*self.inner).clone();
131        inner.hooks.push(Arc::new(hook));
132        Agent {
133            inner: Arc::new(inner),
134        }
135    }
136
137    /// Start a new run in `session_id` with one user message: text, or a
138    /// [`crate::Message`] built with `Message::user(..).with_images(..)`.
139    pub async fn run(
140        &self,
141        session_id: &str,
142        input: impl Into<Message>,
143    ) -> Result<RunOutcome, CoreError> {
144        self.run_with_cancel(session_id, input, CancellationToken::new())
145            .await
146    }
147
148    pub async fn run_with_cancel(
149        &self,
150        session_id: &str,
151        input: impl Into<Message>,
152        cancel: CancellationToken,
153    ) -> Result<RunOutcome, CoreError> {
154        let state = RunState::new(&self.inner.id, session_id, input);
155        Driver::new(&self.inner, state, cancel).drive(None).await
156    }
157
158    /// Continue from saved state that is not interrupted, typically
159    /// `previous.state.with_user_message("next question")`.
160    pub async fn run_from(
161        &self,
162        state: RunState,
163        cancel: CancellationToken,
164    ) -> Result<RunOutcome, CoreError> {
165        self.check_owner(&state)?;
166        if state.pending.is_some() {
167            return Err(CoreError::PendingInterruption);
168        }
169        Driver::new(&self.inner, state, cancel).drive(None).await
170    }
171
172    /// Like [`Agent::run_from`], but settles each interruption with
173    /// `resolver` and continues, until the run ends or the resolver returns
174    /// `None` (the interrupted outcome is then returned as is). It has no
175    /// iteration cap of its own: a resolver that keeps resolving is bounded
176    /// by the run's limits (turns, tool calls, tokens).
177    ///
178    /// Hooks see one run end (`Hook::on_run_end`), for the final outcome;
179    /// the interruptions settled on the way are not run ends.
180    pub async fn run_resolving(
181        &self,
182        state: RunState,
183        cancel: CancellationToken,
184        resolver: &dyn InterruptResolver,
185    ) -> Result<RunOutcome, CoreError> {
186        self.check_owner(&state)?;
187        if state.pending.is_some() {
188            return Err(CoreError::PendingInterruption);
189        }
190        let outcome = Driver::new(&self.inner, state, cancel.clone())
191            .without_run_end()
192            .with_resolver(resolver)
193            .drive(None)
194            .await?;
195        self.settle_interruptions(outcome, cancel, resolver).await
196    }
197
198    /// End a run a crash or restart left mid tool batch without running
199    /// anything more: unlike [`Agent::run_from`], no call is re-run and no
200    /// model call is made. A call that had started gets an
201    /// [`crate::ReceiptStatus::Indeterminate`] receipt, one that never
202    /// started a [`crate::ReceiptStatus::Cancelled`] one, and the run ends
203    /// [`RunStatus::Cancelled`]. A state that is not in flight just ends.
204    pub async fn end_in_flight(&self, state: RunState) -> Result<RunOutcome, CoreError> {
205        self.check_owner(&state)?;
206        if state.pending.is_some() {
207            return Err(CoreError::PendingInterruption);
208        }
209        Driver::new(&self.inner, state, CancellationToken::new())
210            .end_in_flight()
211            .await
212    }
213
214    /// Like [`Agent::resume_with_cancel`], but settles each later
215    /// interruption with `resolver`, as [`Agent::run_resolving`] does.
216    pub async fn resume_resolving(
217        &self,
218        state: RunState,
219        resolution: Resolution,
220        cancel: CancellationToken,
221        resolver: &dyn InterruptResolver,
222    ) -> Result<RunOutcome, CoreError> {
223        self.check_owner(&state)?;
224        if state.pending.is_none() {
225            return Err(CoreError::NotInterrupted);
226        }
227        let outcome = Driver::new(&self.inner, state, cancel.clone())
228            .without_run_end()
229            .with_resolver(resolver)
230            .drive(Some(resolution))
231            .await?;
232        self.settle_interruptions(outcome, cancel, resolver).await
233    }
234
235    async fn settle_interruptions(
236        &self,
237        mut outcome: RunOutcome,
238        cancel: CancellationToken,
239        resolver: &dyn InterruptResolver,
240    ) -> Result<RunOutcome, CoreError> {
241        while let RunStatus::Interrupted { interruption } = &outcome.status {
242            let Some(resolution) = resolver.resolve(&outcome.state, interruption).await else {
243                break;
244            };
245            self.check_owner(&outcome.state)?;
246            outcome = Driver::new(&self.inner, outcome.state, cancel.clone())
247                .without_run_end()
248                .with_resolver(resolver)
249                .drive(Some(resolution))
250                .await?;
251        }
252        crate::run_loop::report_run_end(&self.inner, &outcome).await;
253        Ok(outcome)
254    }
255
256    /// Settle the interruption in `state` and keep going. `state` may come
257    /// from another process: it is plain data. A run paused for a child
258    /// ([`crate::Pending::child`]) passes the answer down to the run that is
259    /// waiting, at any depth; [`RunState::waiting_run`] says which that is.
260    pub async fn resume(
261        &self,
262        state: RunState,
263        resolution: Resolution,
264    ) -> Result<RunOutcome, CoreError> {
265        self.resume_with_cancel(state, resolution, CancellationToken::new())
266            .await
267    }
268
269    pub async fn resume_with_cancel(
270        &self,
271        state: RunState,
272        resolution: Resolution,
273        cancel: CancellationToken,
274    ) -> Result<RunOutcome, CoreError> {
275        self.check_owner(&state)?;
276        if state.pending.is_none() {
277            return Err(CoreError::NotInterrupted);
278        }
279        Driver::new(&self.inner, state, cancel)
280            .drive(Some(resolution))
281            .await
282    }
283
284    fn check_owner(&self, state: &RunState) -> Result<(), CoreError> {
285        let mut run = Some(state);
286        while let Some(current) = run {
287            if current.schema > RUN_STATE_SCHEMA {
288                return Err(CoreError::UnsupportedRunState {
289                    found: current.schema,
290                    supported: RUN_STATE_SCHEMA,
291                });
292            }
293            run = current.pending.as_ref().and_then(|p| p.child.as_deref());
294        }
295        if state.agent_id != self.inner.id {
296            return Err(CoreError::AgentMismatch {
297                expected: self.inner.id.clone(),
298                found: state.agent_id.clone(),
299            });
300        }
301        Ok(())
302    }
303}
304
305/// Builder for [`Agent`]. `provider` and `model` are required, and an agent
306/// with tools must cover every [`Safeguard::REQUIRED`] safeguard (see
307/// [`AgentBuilder::attest`] and [`AgentBuilder::allow_unguarded`]).
308pub struct AgentBuilder {
309    id: String,
310    model: Option<String>,
311    instructions: String,
312    provider: Option<Arc<dyn Provider>>,
313    tools: Vec<Arc<dyn Tool>>,
314    deferred_tools: Vec<Arc<dyn Tool>>,
315    retired: HashMap<String, String>,
316    loaded: crate::tool_loading::LoadedTools,
317    hooks: Vec<Arc<dyn Hook>>,
318    attested: Vec<Safeguard>,
319    unguarded: bool,
320    limits: Limits,
321    stuck: StuckConfig,
322    stop_conditions: Vec<Arc<dyn StopCondition>>,
323    sinks: Vec<Arc<dyn EventSink>>,
324    store: Option<Arc<dyn RunStore>>,
325    max_output_tokens: Option<u32>,
326    extensions: Extensions,
327    approval_key: Option<[u8; 32]>,
328    redaction: crate::redaction::RedactionScope,
329}
330
331impl AgentBuilder {
332    pub fn new(id: impl Into<String>) -> Self {
333        Self {
334            id: id.into(),
335            model: None,
336            instructions: String::new(),
337            provider: None,
338            tools: Vec::new(),
339            deferred_tools: Vec::new(),
340            retired: HashMap::new(),
341            loaded: crate::tool_loading::LoadedTools::default(),
342            hooks: Vec::new(),
343            attested: Vec::new(),
344            unguarded: false,
345            limits: Limits::default(),
346            stuck: StuckConfig::default(),
347            stop_conditions: Vec::new(),
348            sinks: Vec::new(),
349            store: None,
350            max_output_tokens: None,
351            extensions: Extensions::default(),
352            approval_key: None,
353            redaction: crate::redaction::RedactionScope::process(),
354        }
355    }
356
357    /// The model id sent with every request. Unset, the provider's
358    /// [`Provider::default_model`] is used, and building fails with
359    /// [`BuildError::MissingModel`] when it has none.
360    pub fn model(mut self, model: impl Into<String>) -> Self {
361        self.model = Some(model.into());
362        self
363    }
364
365    /// The system prompt. Sent first on every request and never compacted.
366    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
367        self.instructions = instructions.into();
368        self
369    }
370
371    pub fn provider(mut self, provider: impl Provider + 'static) -> Self {
372        self.provider = Some(Arc::new(provider));
373        self
374    }
375
376    pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
377        self.tools.push(Arc::new(tool));
378        self
379    }
380
381    pub fn tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
382        self.tools.push(tool);
383        self
384    }
385
386    /// Register a tool whose schema is sent only once loaded: until then
387    /// the built-in `load_tools` lists it by name and one line. Calling it
388    /// directly loads it too. See [`crate::LOAD_TOOLS`] and
389    /// [`crate::LoadedTools`].
390    pub fn deferred_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
391        self.deferred_tools.push(tool);
392        self
393    }
394
395    /// A tool that no longer exists: a call to `name` is refused as an
396    /// unknown tool, with `note` (where its work went) in the refusal.
397    pub fn retired_tool(mut self, name: impl Into<String>, note: impl Into<String>) -> Self {
398        self.retired.insert(name.into(), note.into());
399        self
400    }
401
402    /// The set of loaded deferred tools. Share one across a session's runs
403    /// so a tool loaded once stays loaded (and the tool block stable).
404    pub fn loaded_tools(mut self, loaded: crate::tool_loading::LoadedTools) -> Self {
405        self.loaded = loaded;
406        self
407    }
408
409    /// Hooks run in registration order. Register a hook that interrupts
410    /// (such as [`crate::UntrustedHook`]) last so a human or verifier sees
411    /// only calls the other hooks already allowed.
412    pub fn hook(mut self, hook: impl Hook + 'static) -> Self {
413        self.hooks.push(Arc::new(hook));
414        self
415    }
416
417    pub fn hook_arc(mut self, hook: Arc<dyn Hook>) -> Self {
418        self.hooks.push(hook);
419        self
420    }
421
422    /// Declare that `safeguard` is enforced outside the hooks, for example
423    /// by the application's own tool adapter. This is a statement the
424    /// composition root makes on purpose, so it is reviewable in one place.
425    pub fn attest(mut self, safeguard: Safeguard) -> Self {
426        self.attested.push(safeguard);
427        self
428    }
429
430    /// Build without the [`Safeguard::REQUIRED`] check: for tests, demos
431    /// and tools that only touch data the agent fully controls.
432    pub fn allow_unguarded(mut self) -> Self {
433        self.unguarded = true;
434        self
435    }
436
437    pub fn limits(mut self, limits: Limits) -> Self {
438        self.limits = limits;
439        self
440    }
441
442    pub fn stuck_detection(mut self, config: StuckConfig) -> Self {
443        self.stuck = config;
444        self
445    }
446
447    pub fn stop_when(mut self, condition: impl StopCondition + 'static) -> Self {
448        self.stop_conditions.push(Arc::new(condition));
449        self
450    }
451
452    pub fn event_sink(mut self, sink: impl EventSink + 'static) -> Self {
453        self.sinks.push(Arc::new(sink));
454        self
455    }
456
457    /// [`AgentBuilder::event_sink`] for a sink that is shared.
458    pub fn event_sink_arc(mut self, sink: Arc<dyn EventSink>) -> Self {
459        self.sinks.push(sink);
460        self
461    }
462
463    pub fn store(mut self, store: Arc<dyn RunStore>) -> Self {
464        self.store = Some(store);
465        self
466    }
467
468    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
469        self.max_output_tokens = Some(tokens);
470        self
471    }
472
473    /// Application values every tool call can read from
474    /// [`crate::ToolContext::extensions`]. Replaces any earlier set.
475    /// The key approval digests are made with
476    /// ([`crate::Interruption::digest`]). Without one each process uses its
477    /// own random key, so an approval saved by one process and resumed by
478    /// another is not honored: its call is judged again and the owner asked
479    /// again. Give every process that resumes the same runs the same secret
480    /// key to honor approvals across them.
481    pub fn approval_key(mut self, key: [u8; 32]) -> Self {
482        self.approval_key = Some(key);
483        self
484    }
485
486    /// The registered secrets this agent's runs redact (see
487    /// [`crate::redaction`]). The default is the process-wide set
488    /// ([`RedactionScope::process`](crate::redaction::RedactionScope::process)),
489    /// where every secret store registers what it hands out. Give an agent
490    /// [`RedactionScope::isolated`](crate::redaction::RedactionScope::isolated)
491    /// to keep its secrets from other agents' runs and theirs from its own,
492    /// as a test should, and register its secrets there (its secret store
493    /// and `Redactor` take the same scope).
494    pub fn redaction_scope(mut self, scope: crate::redaction::RedactionScope) -> Self {
495        self.redaction = scope;
496        self
497    }
498
499    pub fn tool_extensions(mut self, extensions: Extensions) -> Self {
500        self.extensions = extensions;
501        self
502    }
503
504    pub fn build(self) -> Result<Agent, BuildError> {
505        if self.id.trim().is_empty() {
506            return Err(BuildError::EmptyAgentId);
507        }
508        let provider = self.provider.ok_or(BuildError::MissingProvider)?;
509        let model = match self.model {
510            Some(model) => model,
511            None => provider
512                .default_model()
513                .map(str::to_string)
514                .ok_or(BuildError::MissingModel)?,
515        };
516
517        let mut tools = HashMap::new();
518        let mut specs = Vec::with_capacity(self.tools.len() + self.deferred_tools.len() + 1);
519        let mut deferred = std::collections::HashSet::new();
520        let mut deferred_specs = Vec::new();
521        for tool in self.deferred_tools {
522            let spec = tool.spec();
523            if !valid_tool_name(&spec.name) {
524                return Err(BuildError::InvalidToolName(spec.name));
525            }
526            if tools.insert(spec.name.clone(), tool).is_some() {
527                return Err(BuildError::DuplicateTool(spec.name));
528            }
529            deferred.insert(spec.name.clone());
530            deferred_specs.push(spec);
531        }
532        let mut core_tools = self.tools;
533        if !deferred_specs.is_empty() {
534            let entries = deferred_specs
535                .iter()
536                .map(|spec| crate::tool_loading::DeferredEntry {
537                    name: spec.name.clone(),
538                    summary: crate::tool_loading::one_line(&spec.description),
539                })
540                .collect();
541            core_tools.push(Arc::new(crate::tool_loading::LoadToolsTool::new(
542                entries,
543                self.loaded.clone(),
544            )));
545        }
546        for tool in core_tools {
547            let spec = tool.spec();
548            if !valid_tool_name(&spec.name) {
549                return Err(BuildError::InvalidToolName(spec.name));
550            }
551            if tools.insert(spec.name.clone(), tool).is_some() {
552                return Err(BuildError::DuplicateTool(spec.name));
553            }
554            specs.push(spec);
555        }
556        deferred_specs.sort_by(|a, b| a.name.cmp(&b.name));
557        specs.extend(deferred_specs);
558        if !specs.is_empty() && !self.unguarded {
559            for required in Safeguard::REQUIRED {
560                let covered = self.attested.contains(&required)
561                    || self
562                        .hooks
563                        .iter()
564                        .any(|h| h.safeguards().contains(&required));
565                if !covered {
566                    return Err(BuildError::MissingSafeguard(required));
567                }
568            }
569        }
570
571        Ok(Agent {
572            inner: Arc::new(AgentInner {
573                id: self.id,
574                model,
575                instructions: self.instructions,
576                provider,
577                tools,
578                specs,
579                deferred,
580                retired: self.retired,
581                loaded: self.loaded,
582                hooks: self.hooks,
583                limits: self.limits,
584                stuck: self.stuck,
585                stop_conditions: self.stop_conditions,
586                sinks: self.sinks,
587                store: self.store,
588                max_output_tokens: self.max_output_tokens,
589                extensions: self.extensions,
590                approval_key: self.approval_key,
591                redaction: self.redaction,
592            }),
593        })
594    }
595}
596
597fn valid_tool_name(name: &str) -> bool {
598    (1..=64).contains(&name.len())
599        && name
600            .bytes()
601            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
602}