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    /// Apply the owner's answer to a card asked for `call` (from
130    /// [`ToolSemantics::owner_approval_request`]) to the tool's own grant
131    /// stores. `None`: the card timed out or never reached the owner. The
132    /// default keeps nothing; the kernel's session grants are separate.
133    async fn record_owner_answer(
134        &self,
135        _call: &ApprovalCall<'_>,
136        _facts: &ToolCallContext,
137        _response: Option<ApprovalResponse>,
138    ) {
139    }
140}
141
142pub(crate) fn spec_of<T: OutcomeTool + ?Sized>(tool: &T) -> ToolSpec {
143    let schema = tool.schema();
144    ToolSpec {
145        name: tool.name().to_string(),
146        description: schema["description"]
147            .as_str()
148            .unwrap_or_else(|| tool.description())
149            .to_string(),
150        parameters: schema["parameters"].clone(),
151    }
152}
153
154/// The arguments must be an object holding every key the schema requires,
155/// and pass the tool's own checks.
156pub(crate) fn validate_for_core<T: OutcomeTool + ?Sized>(
157    tool: &T,
158    arguments: &Value,
159) -> Result<(), String> {
160    let Some(object) = arguments.as_object() else {
161        return Err("arguments must be a JSON object".into());
162    };
163    let schema = tool.schema();
164    let required = schema["parameters"]["required"].as_array();
165    for key in required.into_iter().flatten().filter_map(Value::as_str) {
166        if !object.contains_key(key) {
167            return Err(format!("`{key}` is required"));
168        }
169    }
170    check_argument_contract(tool, arguments)?;
171    tool.validate_call(arguments)
172}
173
174/// The tool's own argument contract (a shell's "run needs a command or a
175/// script"), checked where the kernel checks a call, so a call that cannot
176/// run goes back to the model as invalid before any hook could ask the
177/// owner to approve it.
178pub fn check_argument_contract<T: OutcomeTool + ?Sized>(
179    tool: &T,
180    arguments: &Value,
181) -> Result<(), String> {
182    let describe = |violation: crate::semantics::ToolArgumentContractViolation| match violation
183        .recovery_hint
184    {
185        Some(hint) => format!("{} ({hint})", violation.reason),
186        None => violation.reason,
187    };
188    let canonical = tool
189        .canonicalize_arguments(&arguments.to_string())
190        .map_err(describe)?;
191    tool.validate_arguments(&canonical).map_err(describe)
192}
193
194/// Run an [`OutcomeTool`] for a kernel agent. A failed or rejected call is an
195/// error result the model can react to.
196pub(crate) async fn run_as_core<T: OutcomeTool + ?Sized>(tool: &T, arguments: Value) -> ToolResult {
197    run_as_core_with(tool, arguments, &ToolCallContext::default()).await
198}
199
200/// [`run_as_core`] with the facts the host knows about the call.
201pub(crate) async fn run_as_core_with<T: OutcomeTool + ?Sized>(
202    tool: &T,
203    arguments: Value,
204    facts: &ToolCallContext,
205) -> ToolResult {
206    let raw = arguments.to_string();
207    let outcome = match tool.execute(&raw, facts).await {
208        Ok(outcome) => outcome,
209        Err(error) => return Ok(ToolOutput::error(error.to_string())),
210    };
211    let mut output = if outcome.metadata.contract_rejected {
212        ToolOutput::error(outcome.output)
213    } else {
214        ToolOutput::text(outcome.output)
215    };
216    if let Some(read) = &outcome.metadata.read_file {
217        output = output.with_details(json!({
218            "path": read.display_path,
219            "start_line": read.returned_start_line,
220            "end_line": read.returned_end_line,
221            "total_lines": read.total_lines,
222            "truncated": read.truncated,
223        }));
224    }
225    output.finish = outcome.finish;
226    Ok(output)
227}
228
229/// Runs one call of an adapted tool for a kernel agent, in place of the
230/// tool's own [`OutcomeTool::execute`]. An application with its own
231/// dispatcher (receipts, status lines, result fitting) supplies this.
232#[async_trait]
233pub trait OutcomeRunner: Send + Sync {
234    async fn run(&self, tool: &str, arguments: Value, ctx: &ToolContext) -> ToolResult;
235}
236
237/// Extra argument check for an adapted tool, replacing the schema check.
238pub type CallValidator = Arc<dyn Fn(&Value) -> Result<(), String> + Send + Sync>;
239
240/// Any [`OutcomeTool`] as a kernel tool: every description of a call
241/// (annotations, effects, access, outbound data) comes from the tool's
242/// [`ToolSemantics`].
243pub struct KernelAdapter<T: ?Sized> {
244    tool: Arc<T>,
245    spec: ToolSpec,
246    trust_roots: Arc<Vec<String>>,
247    owned: crate::semantics::OwnedFolders,
248    validator: Option<CallValidator>,
249    timeout: Option<Duration>,
250    runner: Option<Arc<dyn OutcomeRunner>>,
251    facts: ToolCallContext,
252}
253
254impl<T: OutcomeTool + ?Sized> KernelAdapter<T> {
255    pub fn new(tool: Arc<T>) -> Self {
256        let spec = spec_of(tool.as_ref());
257        Self {
258            tool,
259            spec,
260            trust_roots: Arc::new(Vec::new()),
261            owned: Default::default(),
262            validator: None,
263            timeout: None,
264            runner: None,
265            facts: ToolCallContext::default(),
266        }
267    }
268
269    /// Call the tool with these facts (who is asking, from which chat)
270    /// instead of none: what the host knows about the turn the tool is
271    /// offered in, such as its audience.
272    pub fn with_call_facts(mut self, facts: ToolCallContext) -> Self {
273        self.facts = facts;
274        self
275    }
276
277    /// Offer the tool under this spec instead of its own schema.
278    pub fn with_spec(mut self, spec: ToolSpec) -> Self {
279        self.spec = spec;
280        self
281    }
282
283    /// The run's trusted roots: where an effect lands can decide its class.
284    pub fn with_trust_roots(mut self, roots: Arc<Vec<String>>) -> Self {
285        self.trust_roots = roots;
286        self
287    }
288
289    /// The folders the request's work made for itself: an effect landing
290    /// there is the work's own, so its class is judged like one inside the
291    /// trusted roots (read live: a folder claimed mid-turn counts at once).
292    pub fn with_owned_folders(mut self, owned: crate::semantics::OwnedFolders) -> Self {
293        self.owned = owned;
294        self
295    }
296
297    /// Check arguments with this instead of the schema's `required` keys.
298    pub fn with_validator(mut self, validator: CallValidator) -> Self {
299        self.validator = Some(validator);
300        self
301    }
302
303    pub fn with_timeout(mut self, timeout: Duration) -> Self {
304        self.timeout = Some(timeout);
305        self
306    }
307
308    /// Run calls through `runner` instead of [`OutcomeTool::execute`].
309    pub fn with_runner(mut self, runner: Arc<dyn OutcomeRunner>) -> Self {
310        self.runner = Some(runner);
311        self
312    }
313
314    fn canonical(&self, arguments: &Value) -> String {
315        let raw = arguments.to_string();
316        self.tool.canonicalize_arguments(&raw).unwrap_or(raw)
317    }
318}
319
320/// How many sub-agents one batch may run at once.
321pub const MAX_CONCURRENT_CHILDREN: usize = 3;
322
323#[async_trait]
324impl<T: OutcomeTool + ?Sized + 'static> aidaemon_core::Tool for KernelAdapter<T> {
325    fn spec(&self) -> ToolSpec {
326        self.spec.clone()
327    }
328
329    /// Worst case for the tool as a whole: only a tool that is read-only
330    /// for every call says so; any other may be destructive and egress.
331    fn annotations(&self) -> ToolAnnotations {
332        if self.tool.capabilities().read_only {
333            ToolAnnotations::READ_ONLY
334        } else {
335            ToolAnnotations {
336                read_only: false,
337                destructive: true,
338                idempotent: false,
339                egress: true,
340            }
341        }
342    }
343
344    /// Sub-agents spawned in one batch run together, up to
345    /// [`MAX_CONCURRENT_CHILDREN`]: the coordination ledger arbitrates what
346    /// they write. Every other non-read-only tool runs alone.
347    fn concurrent_peers(&self) -> usize {
348        if self.tool.dispatch_facts().spawns_child_agents {
349            MAX_CONCURRENT_CHILDREN
350        } else {
351            0
352        }
353    }
354
355    /// Judged per call: a mixed tool such as a shell reads for `ls` and
356    /// writes for `rm`.
357    fn annotations_for(&self, arguments: &Value) -> ToolAnnotations {
358        let owned = self.owned.list();
359        self.tool.call_annotations_in(
360            &arguments.to_string(),
361            &TrustRoots::new(&self.trust_roots).with_owned(&owned),
362        )
363    }
364
365    fn outbound(&self, arguments: &Value) -> Outbound {
366        self.tool.call_outbound(&arguments.to_string())
367    }
368
369    /// The tool's own declaration for the arguments it will run with
370    /// (after its argument canonicalization).
371    fn effects(&self, arguments: &Value) -> CallEffects {
372        self.tool.call_effects(&self.canonical(arguments))
373    }
374
375    /// The declared effects as the kernel's access manifest: egress targets
376    /// as hosts, path effects as writes, a shell tool's command line given
377    /// as `command` or `script`, and a file tool's guarded paths.
378    fn access(&self, arguments: &Value) -> AccessManifest {
379        let mut manifest = AccessManifest::default();
380        let facts = self.tool.dispatch_facts();
381        if facts.shell_command_line {
382            for field in ["command", "script"] {
383                if let Some(text) = arguments
384                    .get(field)
385                    .and_then(Value::as_str)
386                    .filter(|text| !text.trim().is_empty())
387                {
388                    manifest.commands.push(text.to_string());
389                }
390            }
391        }
392        for key in self.effects(arguments).keys {
393            let list = match key.class {
394                EffectClass::Egress => &mut manifest.hosts,
395                EffectClass::Write | EffectClass::Delete | EffectClass::Configuration => {
396                    &mut manifest.writes
397                }
398                _ => continue,
399            };
400            if !list.contains(&key.target) {
401                list.push(key.target);
402            }
403        }
404        // Effects do not name reads, and name no writes on a remote backend.
405        if facts.file_guard != FileGuard::None {
406            let (reads, writes) = self.tool.guarded_paths(&self.canonical(arguments));
407            manifest.reads.extend(reads);
408            for write in writes {
409                if !manifest.writes.contains(&write) {
410                    manifest.writes.push(write);
411                }
412            }
413        }
414        manifest
415    }
416
417    /// Fallback only: a result that knows its trust says so itself.
418    fn source_trust(&self, _arguments: &Value) -> SourceTrust {
419        SourceTrust::Untrusted
420    }
421
422    fn validate(&self, arguments: &Value) -> Result<(), String> {
423        match &self.validator {
424            Some(validator) => validator(arguments),
425            None => validate_for_core(self.tool.as_ref(), arguments),
426        }
427    }
428
429    fn timeout(&self) -> Option<Duration> {
430        self.timeout
431    }
432
433    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
434        match &self.runner {
435            Some(runner) => runner.run(&self.spec.name, arguments, ctx).await,
436            None => run_as_core_with(self.tool.as_ref(), arguments, &self.facts).await,
437        }
438    }
439}
440
441/// Implement [`aidaemon_core::Tool`] for an [`OutcomeTool`].
442macro_rules! core_tool {
443    ($ty:ty, annotations: $annotations:expr, access: |$this:ident, $args:ident| $access:expr) => {
444        #[async_trait::async_trait]
445        impl aidaemon_core::Tool for $ty {
446            fn spec(&self) -> aidaemon_core::ToolSpec {
447                $crate::outcome::spec_of(self)
448            }
449
450            fn annotations(&self) -> aidaemon_core::ToolAnnotations {
451                $annotations
452            }
453
454            fn validate(&self, arguments: &serde_json::Value) -> Result<(), String> {
455                $crate::outcome::validate_for_core(self, arguments)
456            }
457
458            fn access(&self, $args: &serde_json::Value) -> aidaemon_core::AccessManifest {
459                let $this = self;
460                $access
461            }
462
463            async fn call(
464                &self,
465                arguments: serde_json::Value,
466                _ctx: &aidaemon_core::ToolContext,
467            ) -> aidaemon_core::ToolResult {
468                $crate::outcome::run_as_core(self, arguments).await
469            }
470        }
471    };
472}
473pub(crate) use core_tool;
474
475#[cfg(test)]
476mod timeout_tests {
477    use super::*;
478
479    #[test]
480    fn a_timeout_is_known_by_its_type_through_context_not_its_words() {
481        let typed = anyhow::Error::new(ToolTimedOut("Command timed out after 5s".into()))
482            .context("search failed");
483        assert!(timed_out(&typed));
484        // The same words in an untyped error are not a timeout.
485        assert!(!timed_out(&anyhow::anyhow!("Command timed out after 5s")));
486    }
487}