aidaemon-tools 0.23.1

Ready-made tools for aidaemon agents (files, search, sandboxed shell, web, checklist); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
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
//! Tools that report a typed [`ToolCallOutcome`].
//!
//! An [`OutcomeTool`] is written once. An application with its own dispatcher
//! calls [`OutcomeTool::execute`] and keeps the typed metadata; a plain
//! [`aidaemon_core`] agent gets the same tool through [`aidaemon_core::Tool`].

use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use serde_json::{Value, json};

use aidaemon_core::{
    AccessManifest, CallEffects, EffectClass, Outbound, SourceTrust, ToolAnnotations, ToolContext,
    ToolOutput, ToolResult, ToolSpec,
};

use crate::semantics::{
    ApprovalCall, ApprovalKind, ApprovalResponse, FileGuard, PermissionMode, ToolCallContext,
    ToolCallOutcome, ToolSemantics, TrustRoots,
};

/// A tool could not reach its target at all, so nothing took effect and the
/// call may run again.
#[derive(Debug)]
pub struct NothingSentError(pub String);

impl std::fmt::Display for NothingSentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for NothingSentError {}

/// The path a call names does not exist, so the call took no effect. A
/// call that names another path may succeed: a missed lookup while
/// exploring is a retryable failure, not one that counts toward the
/// tool's lockout. Raised by the file tools from the backend's own
/// metadata failure, never inferred from an error's words.
#[derive(Debug)]
pub struct TargetNotFound(pub String);

impl std::fmt::Display for TargetNotFound {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for TargetNotFound {}

/// A call ran out of time (a command or remote operation the tool waited
/// on). Another call may succeed, so the failure is retryable and does not
/// count toward the tool's lockout; the type says so, never the words
/// "timed out".
#[derive(Debug)]
pub struct ToolTimedOut(pub String);

impl std::fmt::Display for ToolTimedOut {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for ToolTimedOut {}

/// Whether a raised tool error is a typed [`ToolTimedOut`].
pub fn timed_out(error: &anyhow::Error) -> bool {
    error.downcast_ref::<ToolTimedOut>().is_some()
}

/// Whether a raised tool error says, by its type, that the call took no
/// effect and another call may succeed ([`NothingSentError`],
/// [`TargetNotFound`], and with checkpoints a checkpoint refused for an
/// unbounded scope before the process started).
pub fn failed_without_effect(error: &anyhow::Error) -> bool {
    #[cfg(feature = "checkpoints")]
    if error
        .downcast_ref::<crate::checkpoints::UnboundedCheckpoint>()
        .is_some()
    {
        return true;
    }
    error.downcast_ref::<NothingSentError>().is_some()
        || error.downcast_ref::<TargetNotFound>().is_some()
}

/// A tool whose execution returns a typed outcome.
#[async_trait]
pub trait OutcomeTool: ToolSemantics {
    fn name(&self) -> &str;
    /// One-line description.
    fn description(&self) -> &str;
    /// The full function object: `name`, `description` and `parameters`.
    fn schema(&self) -> Value;
    /// Run one call. `Err` is a failed call whose message the model reads.
    async fn execute(
        &self,
        arguments: &str,
        facts: &ToolCallContext,
    ) -> anyhow::Result<ToolCallOutcome>;
    /// Checks made before a kernel agent runs the call.
    fn validate_call(&self, _arguments: &Value) -> Result<(), String> {
        Ok(())
    }
    /// The permission mode the owner's cards for this tool are sent with
    /// (it picks the buttons offered). `None`: the default, Cautious.
    fn approval_card_mode(&self) -> Option<PermissionMode> {
        None
    }
    /// The kind of card the owner is asked `request` (from
    /// [`ToolSemantics::owner_approval_request`]) with, which picks the
    /// buttons offered: a one-time card or a goal confirmation offers no
    /// session or persistent grant. The default is a standard command card.
    fn approval_card_kind(&self, _request: &aidaemon_core::OwnerApprovalRequest) -> ApprovalKind {
        ApprovalKind::Command
    }
    /// Apply the owner's answer to a card asked for `call` (from
    /// [`ToolSemantics::owner_approval_request`]) to the tool's own grant
    /// stores. `None`: the card timed out or never reached the owner. The
    /// default keeps nothing; the kernel's session grants are separate.
    async fn record_owner_answer(
        &self,
        _call: &ApprovalCall<'_>,
        _facts: &ToolCallContext,
        _response: Option<ApprovalResponse>,
    ) {
    }
}

pub(crate) fn spec_of<T: OutcomeTool + ?Sized>(tool: &T) -> ToolSpec {
    let schema = tool.schema();
    ToolSpec {
        name: tool.name().to_string(),
        description: schema["description"]
            .as_str()
            .unwrap_or_else(|| tool.description())
            .to_string(),
        parameters: schema["parameters"].clone(),
    }
}

/// The arguments must be an object holding every key the schema requires,
/// and pass the tool's own checks.
pub(crate) fn validate_for_core<T: OutcomeTool + ?Sized>(
    tool: &T,
    arguments: &Value,
) -> Result<(), String> {
    let Some(object) = arguments.as_object() else {
        return Err("arguments must be a JSON object".into());
    };
    let schema = tool.schema();
    let required = schema["parameters"]["required"].as_array();
    for key in required.into_iter().flatten().filter_map(Value::as_str) {
        if !object.contains_key(key) {
            return Err(format!("`{key}` is required"));
        }
    }
    check_argument_contract(tool, arguments)?;
    tool.validate_call(arguments)
}

/// The tool's own argument contract (a shell's "run needs a command or a
/// script"), checked where the kernel checks a call, so a call that cannot
/// run goes back to the model as invalid before any hook could ask the
/// owner to approve it.
pub fn check_argument_contract<T: OutcomeTool + ?Sized>(
    tool: &T,
    arguments: &Value,
) -> Result<(), String> {
    let describe = |violation: crate::semantics::ToolArgumentContractViolation| match violation
        .recovery_hint
    {
        Some(hint) => format!("{} ({hint})", violation.reason),
        None => violation.reason,
    };
    let canonical = tool
        .canonicalize_arguments(&arguments.to_string())
        .map_err(describe)?;
    tool.validate_arguments(&canonical).map_err(describe)
}

/// Run an [`OutcomeTool`] for a kernel agent. A failed or rejected call is an
/// error result the model can react to.
pub(crate) async fn run_as_core<T: OutcomeTool + ?Sized>(tool: &T, arguments: Value) -> ToolResult {
    run_as_core_with(tool, arguments, &ToolCallContext::default()).await
}

/// [`run_as_core`] with the facts the host knows about the call.
pub(crate) async fn run_as_core_with<T: OutcomeTool + ?Sized>(
    tool: &T,
    arguments: Value,
    facts: &ToolCallContext,
) -> ToolResult {
    let raw = arguments.to_string();
    let outcome = match tool.execute(&raw, facts).await {
        Ok(outcome) => outcome,
        Err(error) => return Ok(ToolOutput::error(error.to_string())),
    };
    let mut output = if outcome.metadata.contract_rejected {
        ToolOutput::error(outcome.output)
    } else {
        ToolOutput::text(outcome.output)
    };
    if let Some(read) = &outcome.metadata.read_file {
        output = output.with_details(json!({
            "path": read.display_path,
            "start_line": read.returned_start_line,
            "end_line": read.returned_end_line,
            "total_lines": read.total_lines,
            "truncated": read.truncated,
        }));
    }
    output.finish = outcome.finish;
    Ok(output)
}

/// Runs one call of an adapted tool for a kernel agent, in place of the
/// tool's own [`OutcomeTool::execute`]. An application with its own
/// dispatcher (receipts, status lines, result fitting) supplies this.
#[async_trait]
pub trait OutcomeRunner: Send + Sync {
    async fn run(&self, tool: &str, arguments: Value, ctx: &ToolContext) -> ToolResult;
}

/// Extra argument check for an adapted tool, replacing the schema check.
pub type CallValidator = Arc<dyn Fn(&Value) -> Result<(), String> + Send + Sync>;

/// Any [`OutcomeTool`] as a kernel tool: every description of a call
/// (annotations, effects, access, outbound data) comes from the tool's
/// [`ToolSemantics`].
pub struct KernelAdapter<T: ?Sized> {
    tool: Arc<T>,
    spec: ToolSpec,
    trust_roots: Arc<Vec<String>>,
    owned: crate::semantics::OwnedFolders,
    validator: Option<CallValidator>,
    timeout: Option<Duration>,
    runner: Option<Arc<dyn OutcomeRunner>>,
    facts: ToolCallContext,
}

impl<T: OutcomeTool + ?Sized> KernelAdapter<T> {
    pub fn new(tool: Arc<T>) -> Self {
        let spec = spec_of(tool.as_ref());
        Self {
            tool,
            spec,
            trust_roots: Arc::new(Vec::new()),
            owned: Default::default(),
            validator: None,
            timeout: None,
            runner: None,
            facts: ToolCallContext::default(),
        }
    }

    /// Call the tool with these facts (who is asking, from which chat)
    /// instead of none: what the host knows about the turn the tool is
    /// offered in, such as its audience.
    pub fn with_call_facts(mut self, facts: ToolCallContext) -> Self {
        self.facts = facts;
        self
    }

    /// Offer the tool under this spec instead of its own schema.
    pub fn with_spec(mut self, spec: ToolSpec) -> Self {
        self.spec = spec;
        self
    }

    /// The run's trusted roots: where an effect lands can decide its class.
    pub fn with_trust_roots(mut self, roots: Arc<Vec<String>>) -> Self {
        self.trust_roots = roots;
        self
    }

    /// The folders the request's work made for itself: an effect landing
    /// there is the work's own, so its class is judged like one inside the
    /// trusted roots (read live: a folder claimed mid-turn counts at once).
    pub fn with_owned_folders(mut self, owned: crate::semantics::OwnedFolders) -> Self {
        self.owned = owned;
        self
    }

    /// Check arguments with this instead of the schema's `required` keys.
    pub fn with_validator(mut self, validator: CallValidator) -> Self {
        self.validator = Some(validator);
        self
    }

    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Run calls through `runner` instead of [`OutcomeTool::execute`].
    pub fn with_runner(mut self, runner: Arc<dyn OutcomeRunner>) -> Self {
        self.runner = Some(runner);
        self
    }

    fn canonical(&self, arguments: &Value) -> String {
        let raw = arguments.to_string();
        self.tool.canonicalize_arguments(&raw).unwrap_or(raw)
    }
}

/// How many sub-agents one batch may run at once.
pub const MAX_CONCURRENT_CHILDREN: usize = 3;

#[async_trait]
impl<T: OutcomeTool + ?Sized + 'static> aidaemon_core::Tool for KernelAdapter<T> {
    fn spec(&self) -> ToolSpec {
        self.spec.clone()
    }

    /// Worst case for the tool as a whole: only a tool that is read-only
    /// for every call says so; any other may be destructive and egress.
    fn annotations(&self) -> ToolAnnotations {
        if self.tool.capabilities().read_only {
            ToolAnnotations::READ_ONLY
        } else {
            ToolAnnotations {
                read_only: false,
                destructive: true,
                idempotent: false,
                egress: true,
            }
        }
    }

    /// Sub-agents spawned in one batch run together, up to
    /// [`MAX_CONCURRENT_CHILDREN`]: the coordination ledger arbitrates what
    /// they write. Every other non-read-only tool runs alone.
    fn concurrent_peers(&self) -> usize {
        if self.tool.dispatch_facts().spawns_child_agents {
            MAX_CONCURRENT_CHILDREN
        } else {
            0
        }
    }

    /// Judged per call: a mixed tool such as a shell reads for `ls` and
    /// writes for `rm`.
    fn annotations_for(&self, arguments: &Value) -> ToolAnnotations {
        let owned = self.owned.list();
        self.tool.call_annotations_in(
            &arguments.to_string(),
            &TrustRoots::new(&self.trust_roots).with_owned(&owned),
        )
    }

    fn outbound(&self, arguments: &Value) -> Outbound {
        self.tool.call_outbound(&arguments.to_string())
    }

    /// The tool's own declaration for the arguments it will run with
    /// (after its argument canonicalization).
    fn effects(&self, arguments: &Value) -> CallEffects {
        self.tool.call_effects(&self.canonical(arguments))
    }

    /// The declared effects as the kernel's access manifest: egress targets
    /// as hosts, path effects as writes, a shell tool's command line given
    /// as `command` or `script`, and a file tool's guarded paths.
    fn access(&self, arguments: &Value) -> AccessManifest {
        let mut manifest = AccessManifest::default();
        let facts = self.tool.dispatch_facts();
        if facts.shell_command_line {
            for field in ["command", "script"] {
                if let Some(text) = arguments
                    .get(field)
                    .and_then(Value::as_str)
                    .filter(|text| !text.trim().is_empty())
                {
                    manifest.commands.push(text.to_string());
                }
            }
        }
        for key in self.effects(arguments).keys {
            let list = match key.class {
                EffectClass::Egress => &mut manifest.hosts,
                EffectClass::Write | EffectClass::Delete | EffectClass::Configuration => {
                    &mut manifest.writes
                }
                _ => continue,
            };
            if !list.contains(&key.target) {
                list.push(key.target);
            }
        }
        // Effects do not name reads, and name no writes on a remote backend.
        if facts.file_guard != FileGuard::None {
            let (reads, writes) = self.tool.guarded_paths(&self.canonical(arguments));
            manifest.reads.extend(reads);
            for write in writes {
                if !manifest.writes.contains(&write) {
                    manifest.writes.push(write);
                }
            }
        }
        manifest
    }

    /// Fallback only: a result that knows its trust says so itself.
    fn source_trust(&self, _arguments: &Value) -> SourceTrust {
        SourceTrust::Untrusted
    }

    fn validate(&self, arguments: &Value) -> Result<(), String> {
        match &self.validator {
            Some(validator) => validator(arguments),
            None => validate_for_core(self.tool.as_ref(), arguments),
        }
    }

    fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
        match &self.runner {
            Some(runner) => runner.run(&self.spec.name, arguments, ctx).await,
            None => run_as_core_with(self.tool.as_ref(), arguments, &self.facts).await,
        }
    }
}

/// Implement [`aidaemon_core::Tool`] for an [`OutcomeTool`].
macro_rules! core_tool {
    ($ty:ty, annotations: $annotations:expr, access: |$this:ident, $args:ident| $access:expr) => {
        #[async_trait::async_trait]
        impl aidaemon_core::Tool for $ty {
            fn spec(&self) -> aidaemon_core::ToolSpec {
                $crate::outcome::spec_of(self)
            }

            fn annotations(&self) -> aidaemon_core::ToolAnnotations {
                $annotations
            }

            fn validate(&self, arguments: &serde_json::Value) -> Result<(), String> {
                $crate::outcome::validate_for_core(self, arguments)
            }

            fn access(&self, $args: &serde_json::Value) -> aidaemon_core::AccessManifest {
                let $this = self;
                $access
            }

            async fn call(
                &self,
                arguments: serde_json::Value,
                _ctx: &aidaemon_core::ToolContext,
            ) -> aidaemon_core::ToolResult {
                $crate::outcome::run_as_core(self, arguments).await
            }
        }
    };
}
pub(crate) use core_tool;

#[cfg(test)]
mod timeout_tests {
    use super::*;

    #[test]
    fn a_timeout_is_known_by_its_type_through_context_not_its_words() {
        let typed = anyhow::Error::new(ToolTimedOut("Command timed out after 5s".into()))
            .context("search failed");
        assert!(timed_out(&typed));
        // The same words in an untyped error are not a timeout.
        assert!(!timed_out(&anyhow::anyhow!("Command timed out after 5s")));
    }
}