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