Skip to main content

aidaemon_tools/
outcome.rs

1//! Tools that report a typed [`ToolCallOutcome`].
2//!
3//! An [`OutcomeTool`] is written once. An application with its own dispatcher
4//! calls [`OutcomeTool::execute`] and keeps the typed metadata; a plain
5//! [`aidaemon_core`] agent gets the same tool through [`aidaemon_core::Tool`].
6
7use std::sync::Arc;
8use std::time::Duration;
9
10use async_trait::async_trait;
11use serde_json::{Value, json};
12
13use aidaemon_core::{
14    AccessManifest, CallEffects, EffectClass, Outbound, SourceTrust, ToolAnnotations, ToolContext,
15    ToolOutput, ToolResult, ToolSpec,
16};
17
18use crate::semantics::{
19    ApprovalCall, ApprovalKind, ApprovalResponse, FileGuard, PermissionMode, ToolCallContext,
20    ToolCallOutcome, ToolSemantics, TrustRoots,
21};
22
23/// A tool could not reach its target at all, so nothing took effect and the
24/// call may run again.
25#[derive(Debug)]
26pub struct NothingSentError(pub String);
27
28impl std::fmt::Display for NothingSentError {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.write_str(&self.0)
31    }
32}
33
34impl std::error::Error for NothingSentError {}
35
36/// The path a call names does not exist, so the call took no effect. A
37/// call that names another path may succeed: a missed lookup while
38/// exploring is a retryable failure, not one that counts toward the
39/// tool's lockout. Raised by the file tools from the backend's own
40/// metadata failure, never inferred from an error's words.
41#[derive(Debug)]
42pub struct TargetNotFound(pub String);
43
44impl std::fmt::Display for TargetNotFound {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.write_str(&self.0)
47    }
48}
49
50impl std::error::Error for TargetNotFound {}
51
52/// A call ran out of time (a command or remote operation the tool waited
53/// on). Another call may succeed, so the failure is retryable and does not
54/// count toward the tool's lockout; the type says so, never the words
55/// "timed out".
56#[derive(Debug)]
57pub struct ToolTimedOut(pub String);
58
59impl std::fmt::Display for ToolTimedOut {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.write_str(&self.0)
62    }
63}
64
65impl std::error::Error for ToolTimedOut {}
66
67/// Whether a raised tool error is a typed [`ToolTimedOut`].
68pub fn timed_out(error: &anyhow::Error) -> bool {
69    error.downcast_ref::<ToolTimedOut>().is_some()
70}
71
72/// Whether a raised tool error says, by its type, that the call took no
73/// effect and another call may succeed ([`NothingSentError`],
74/// [`TargetNotFound`], and with checkpoints a checkpoint refused for an
75/// unbounded scope before the process started).
76pub fn failed_without_effect(error: &anyhow::Error) -> bool {
77    #[cfg(feature = "checkpoints")]
78    if error
79        .downcast_ref::<crate::checkpoints::UnboundedCheckpoint>()
80        .is_some()
81    {
82        return true;
83    }
84    error.downcast_ref::<NothingSentError>().is_some()
85        || error.downcast_ref::<TargetNotFound>().is_some()
86}
87
88/// A tool whose execution returns a typed outcome.
89#[async_trait]
90pub trait OutcomeTool: ToolSemantics {
91    fn name(&self) -> &str;
92    /// One-line description.
93    fn description(&self) -> &str;
94    /// The full function object: `name`, `description` and `parameters`.
95    fn schema(&self) -> Value;
96    /// Run one call. `Err` is a failed call whose message the model reads.
97    async fn execute(
98        &self,
99        arguments: &str,
100        facts: &ToolCallContext,
101    ) -> anyhow::Result<ToolCallOutcome>;
102    /// Checks made before a kernel agent runs the call.
103    fn validate_call(&self, _arguments: &Value) -> Result<(), String> {
104        Ok(())
105    }
106    /// Whether this exact call stays at most Medium in a run a device
107    /// capped at Medium started or steered (an e-ink reader), though its
108    /// declared effects alone could not show it: the tool itself holds what
109    /// the call starts to that ceiling (a coding agent launched in a checked
110    /// mode, each of its own requests coming back to the run's safeguards as
111    /// a nested call), or the call only reads or stops the tool's own work.
112    /// The tool must enforce what it claims here when the call runs. The
113    /// default is `false`: the call is judged from its effects.
114    fn holds_to_medium_ceiling(&self, _arguments: &str) -> bool {
115        false
116    }
117    /// The permission mode the owner's cards for this tool are sent with
118    /// (it picks the buttons offered). `None`: the default, Cautious.
119    fn approval_card_mode(&self) -> Option<PermissionMode> {
120        None
121    }
122    /// The kind of card the owner is asked `request` (from
123    /// [`ToolSemantics::owner_approval_request`]) with, which picks the
124    /// buttons offered: a one-time card or a goal confirmation offers no
125    /// session or persistent grant. The default is a standard command card.
126    fn approval_card_kind(&self, _request: &aidaemon_core::OwnerApprovalRequest) -> ApprovalKind {
127        ApprovalKind::Command
128    }
129    /// What the owner may grant on a card asked for `call` (from
130    /// [`ToolSemantics::owner_approval_request`]): the typed scope an
131    /// approval covers and the longest it may last. The runtime captures
132    /// the offer when it asks, so the answer is recorded for the scope the
133    /// card showed even if live state changed meanwhile; it sends the card
134    /// with no button beyond `max` and caps an answer to it. With a
135    /// reusable scope ([`crate::semantics::GrantScope::is_reusable`]) and a
136    /// tool that does not keep its own grants, a session answer is kept in
137    /// [`ToolCallContext::scoped_grants`] and later calls in that scope run
138    /// without a card. `None` (the default): the card covers the exact
139    /// call, as the tool's [`Self::approval_card_kind`] and
140    /// [`Self::approval_card_mode`] say.
141    async fn approval_grant(
142        &self,
143        _call: &ApprovalCall<'_>,
144        _facts: &ToolCallContext,
145    ) -> Option<crate::semantics::GrantOffer> {
146        None
147    }
148    /// Apply the owner's answer to a card asked for `call` (from
149    /// [`ToolSemantics::owner_approval_request`]) to the tool's own grant
150    /// stores. `None`: the card timed out or never reached the owner. The
151    /// default keeps nothing; the kernel's session grants are separate.
152    async fn record_owner_answer(
153        &self,
154        _call: &ApprovalCall<'_>,
155        _facts: &ToolCallContext,
156        _response: Option<ApprovalResponse>,
157    ) {
158    }
159}
160
161pub(crate) fn spec_of<T: OutcomeTool + ?Sized>(tool: &T) -> ToolSpec {
162    let schema = tool.schema();
163    ToolSpec {
164        name: tool.name().to_string(),
165        description: schema["description"]
166            .as_str()
167            .unwrap_or_else(|| tool.description())
168            .to_string(),
169        parameters: schema["parameters"].clone(),
170    }
171}
172
173/// The arguments must be an object holding every key the schema requires,
174/// and pass the tool's own checks.
175pub(crate) fn validate_for_core<T: OutcomeTool + ?Sized>(
176    tool: &T,
177    arguments: &Value,
178) -> Result<(), String> {
179    let Some(object) = arguments.as_object() else {
180        return Err("arguments must be a JSON object".into());
181    };
182    let schema = tool.schema();
183    let required = schema["parameters"]["required"].as_array();
184    for key in required.into_iter().flatten().filter_map(Value::as_str) {
185        if !object.contains_key(key) {
186            return Err(format!("`{key}` is required"));
187        }
188    }
189    check_argument_contract(tool, arguments)?;
190    tool.validate_call(arguments)
191}
192
193/// The tool's own argument contract (a shell's "run needs a command or a
194/// script"), checked where the kernel checks a call, so a call that cannot
195/// run goes back to the model as invalid before any hook could ask the
196/// owner to approve it.
197pub fn check_argument_contract<T: OutcomeTool + ?Sized>(
198    tool: &T,
199    arguments: &Value,
200) -> Result<(), String> {
201    let describe = |violation: crate::semantics::ToolArgumentContractViolation| match violation
202        .recovery_hint
203    {
204        Some(hint) => format!("{} ({hint})", violation.reason),
205        None => violation.reason,
206    };
207    let canonical = tool
208        .canonicalize_arguments(&arguments.to_string())
209        .map_err(describe)?;
210    tool.validate_arguments(&canonical).map_err(describe)
211}
212
213/// Run an [`OutcomeTool`] for a kernel agent. A failed or rejected call is an
214/// error result the model can react to.
215pub(crate) async fn run_as_core<T: OutcomeTool + ?Sized>(tool: &T, arguments: Value) -> ToolResult {
216    run_as_core_with(tool, arguments, &ToolCallContext::default()).await
217}
218
219/// [`run_as_core`] with the facts the host knows about the call.
220pub(crate) async fn run_as_core_with<T: OutcomeTool + ?Sized>(
221    tool: &T,
222    arguments: Value,
223    facts: &ToolCallContext,
224) -> ToolResult {
225    let raw = arguments.to_string();
226    let outcome = match tool.execute(&raw, facts).await {
227        Ok(outcome) => outcome,
228        Err(error) => return Ok(ToolOutput::error(error.to_string())),
229    };
230    let mut output = if outcome.metadata.contract_rejected {
231        ToolOutput::error(outcome.output)
232    } else {
233        ToolOutput::text(outcome.output)
234    };
235    if let Some(read) = &outcome.metadata.read_file {
236        output = output.with_details(json!({
237            "path": read.display_path,
238            "start_line": read.returned_start_line,
239            "end_line": read.returned_end_line,
240            "total_lines": read.total_lines,
241            "truncated": read.truncated,
242        }));
243    }
244    output.finish = outcome.finish;
245    Ok(output)
246}
247
248/// Runs one call of an adapted tool for a kernel agent, in place of the
249/// tool's own [`OutcomeTool::execute`]. An application with its own
250/// dispatcher (receipts, status lines, result fitting) supplies this.
251#[async_trait]
252pub trait OutcomeRunner: Send + Sync {
253    async fn run(&self, tool: &str, arguments: Value, ctx: &ToolContext) -> ToolResult;
254}
255
256/// Extra argument check for an adapted tool, replacing the schema check.
257pub type CallValidator = Arc<dyn Fn(&Value) -> Result<(), String> + Send + Sync>;
258
259/// Any [`OutcomeTool`] as a kernel tool: every description of a call
260/// (annotations, effects, access, outbound data) comes from the tool's
261/// [`ToolSemantics`].
262pub struct KernelAdapter<T: ?Sized> {
263    tool: Arc<T>,
264    spec: ToolSpec,
265    trust_roots: Arc<Vec<String>>,
266    owned: crate::semantics::OwnedFolders,
267    validator: Option<CallValidator>,
268    timeout: Option<Duration>,
269    runner: Option<Arc<dyn OutcomeRunner>>,
270    facts: ToolCallContext,
271}
272
273impl<T: OutcomeTool + ?Sized> KernelAdapter<T> {
274    pub fn new(tool: Arc<T>) -> Self {
275        let spec = spec_of(tool.as_ref());
276        Self {
277            tool,
278            spec,
279            trust_roots: Arc::new(Vec::new()),
280            owned: Default::default(),
281            validator: None,
282            timeout: None,
283            runner: None,
284            facts: ToolCallContext::default(),
285        }
286    }
287
288    /// Call the tool with these facts (who is asking, from which chat)
289    /// instead of none: what the host knows about the turn the tool is
290    /// offered in, such as its audience.
291    pub fn with_call_facts(mut self, facts: ToolCallContext) -> Self {
292        self.facts = facts;
293        self
294    }
295
296    /// Offer the tool under this spec instead of its own schema.
297    pub fn with_spec(mut self, spec: ToolSpec) -> Self {
298        self.spec = spec;
299        self
300    }
301
302    /// The run's trusted roots: where an effect lands can decide its class.
303    pub fn with_trust_roots(mut self, roots: Arc<Vec<String>>) -> Self {
304        self.trust_roots = roots;
305        self
306    }
307
308    /// The folders the request's work made for itself: an effect landing
309    /// there is the work's own, so its class is judged like one inside the
310    /// trusted roots (read live: a folder claimed mid-turn counts at once).
311    pub fn with_owned_folders(mut self, owned: crate::semantics::OwnedFolders) -> Self {
312        self.owned = owned;
313        self
314    }
315
316    /// Check arguments with this instead of the schema's `required` keys.
317    pub fn with_validator(mut self, validator: CallValidator) -> Self {
318        self.validator = Some(validator);
319        self
320    }
321
322    pub fn with_timeout(mut self, timeout: Duration) -> Self {
323        self.timeout = Some(timeout);
324        self
325    }
326
327    /// Run calls through `runner` instead of [`OutcomeTool::execute`].
328    pub fn with_runner(mut self, runner: Arc<dyn OutcomeRunner>) -> Self {
329        self.runner = Some(runner);
330        self
331    }
332
333    fn canonical(&self, arguments: &Value) -> String {
334        let raw = arguments.to_string();
335        self.tool.canonicalize_arguments(&raw).unwrap_or(raw)
336    }
337}
338
339/// How many sub-agents one batch may run at once.
340pub const MAX_CONCURRENT_CHILDREN: usize = 3;
341
342#[async_trait]
343impl<T: OutcomeTool + ?Sized + 'static> aidaemon_core::Tool for KernelAdapter<T> {
344    fn spec(&self) -> ToolSpec {
345        self.spec.clone()
346    }
347
348    /// Worst case for the tool as a whole: only a tool that is read-only
349    /// for every call says so; any other may be destructive and egress.
350    fn annotations(&self) -> ToolAnnotations {
351        if self.tool.capabilities().read_only {
352            ToolAnnotations::READ_ONLY
353        } else {
354            ToolAnnotations {
355                read_only: false,
356                destructive: true,
357                idempotent: false,
358                egress: true,
359            }
360        }
361    }
362
363    /// Sub-agents spawned in one batch run together, up to
364    /// [`MAX_CONCURRENT_CHILDREN`]: the coordination ledger arbitrates what
365    /// they write. Every other non-read-only tool runs alone.
366    fn concurrent_peers(&self) -> usize {
367        if self.tool.dispatch_facts().spawns_child_agents {
368            MAX_CONCURRENT_CHILDREN
369        } else {
370            0
371        }
372    }
373
374    /// Judged per call: a mixed tool such as a shell reads for `ls` and
375    /// writes for `rm`.
376    fn annotations_for(&self, arguments: &Value) -> ToolAnnotations {
377        let owned = self.owned.list();
378        self.tool.call_annotations_in(
379            &arguments.to_string(),
380            &TrustRoots::new(&self.trust_roots).with_owned(&owned),
381        )
382    }
383
384    fn outbound(&self, arguments: &Value) -> Outbound {
385        self.tool.call_outbound(&arguments.to_string())
386    }
387
388    /// The tool's own declaration for the arguments it will run with
389    /// (after its argument canonicalization).
390    fn effects(&self, arguments: &Value) -> CallEffects {
391        self.tool.call_effects(&self.canonical(arguments))
392    }
393
394    /// The declared effects as the kernel's access manifest: egress targets
395    /// as hosts, path effects as writes, a shell tool's command line given
396    /// as `command` or `script`, and a file tool's guarded paths.
397    fn access(&self, arguments: &Value) -> AccessManifest {
398        let mut manifest = AccessManifest::default();
399        let facts = self.tool.dispatch_facts();
400        if facts.shell_command_line {
401            for field in ["command", "script"] {
402                if let Some(text) = arguments
403                    .get(field)
404                    .and_then(Value::as_str)
405                    .filter(|text| !text.trim().is_empty())
406                {
407                    manifest.commands.push(text.to_string());
408                }
409            }
410        }
411        for key in self.effects(arguments).keys {
412            let list = match key.class {
413                EffectClass::Egress => &mut manifest.hosts,
414                EffectClass::Write | EffectClass::Delete | EffectClass::Configuration => {
415                    &mut manifest.writes
416                }
417                _ => continue,
418            };
419            if !list.contains(&key.target) {
420                list.push(key.target);
421            }
422        }
423        // Effects do not name reads, and name no writes on a remote backend.
424        if facts.file_guard != FileGuard::None {
425            let (reads, writes) = self.tool.guarded_paths(&self.canonical(arguments));
426            manifest.reads.extend(reads);
427            for write in writes {
428                if !manifest.writes.contains(&write) {
429                    manifest.writes.push(write);
430                }
431            }
432        }
433        manifest
434    }
435
436    /// Fallback only: a result that knows its trust says so itself.
437    fn source_trust(&self, _arguments: &Value) -> SourceTrust {
438        SourceTrust::Untrusted
439    }
440
441    fn validate(&self, arguments: &Value) -> Result<(), String> {
442        match &self.validator {
443            Some(validator) => validator(arguments),
444            None => validate_for_core(self.tool.as_ref(), arguments),
445        }
446    }
447
448    fn timeout(&self) -> Option<Duration> {
449        self.timeout
450    }
451
452    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
453        match &self.runner {
454            Some(runner) => runner.run(&self.spec.name, arguments, ctx).await,
455            None => run_as_core_with(self.tool.as_ref(), arguments, &self.facts).await,
456        }
457    }
458}
459
460/// Implement [`aidaemon_core::Tool`] for an [`OutcomeTool`].
461macro_rules! core_tool {
462    ($ty:ty, annotations: $annotations:expr, access: |$this:ident, $args:ident| $access:expr) => {
463        #[async_trait::async_trait]
464        impl aidaemon_core::Tool for $ty {
465            fn spec(&self) -> aidaemon_core::ToolSpec {
466                $crate::outcome::spec_of(self)
467            }
468
469            fn annotations(&self) -> aidaemon_core::ToolAnnotations {
470                $annotations
471            }
472
473            fn validate(&self, arguments: &serde_json::Value) -> Result<(), String> {
474                $crate::outcome::validate_for_core(self, arguments)
475            }
476
477            fn access(&self, $args: &serde_json::Value) -> aidaemon_core::AccessManifest {
478                let $this = self;
479                $access
480            }
481
482            async fn call(
483                &self,
484                arguments: serde_json::Value,
485                _ctx: &aidaemon_core::ToolContext,
486            ) -> aidaemon_core::ToolResult {
487                $crate::outcome::run_as_core(self, arguments).await
488            }
489        }
490    };
491}
492pub(crate) use core_tool;
493
494#[cfg(test)]
495mod timeout_tests {
496    use super::*;
497
498    #[test]
499    fn a_timeout_is_known_by_its_type_through_context_not_its_words() {
500        let typed = anyhow::Error::new(ToolTimedOut("Command timed out after 5s".into()))
501            .context("search failed");
502        assert!(timed_out(&typed));
503        // The same words in an untyped error are not a timeout.
504        assert!(!timed_out(&anyhow::anyhow!("Command timed out after 5s")));
505    }
506}