aidaemon_core/tool.rs
1use std::any::{Any, TypeId};
2use std::collections::HashMap;
3use std::fmt;
4use std::future::Future;
5use std::marker::PhantomData;
6use std::sync::Arc;
7
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use tokio_util::sync::CancellationToken;
12
13use crate::agent::Resolution;
14use crate::approval::CallEffects;
15use crate::approval::SharedDeclines;
16use crate::authority::Authority;
17use crate::message::Image;
18use crate::outcome::FinishOutcome;
19use crate::provider::{ToolSpec, Usage};
20use crate::state::{RunId, RunState};
21
22/// Who authored the content a tool returned. `Untrusted` is content someone
23/// other than the owner wrote (a web page, an inbound message, a third-party
24/// file); it may carry instructions aimed at the model. The default is
25/// `Untrusted`, so a tool that does not say otherwise taints the run.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum SourceTrust {
29 Trusted,
30 #[default]
31 Untrusted,
32}
33
34/// Effect hints that drive scheduling and policy.
35///
36/// The default is the conservative one: an unannotated tool is treated as
37/// mutating and destructive, so it runs alone and policies may ask before it
38/// runs. Mirrors MCP tool annotations.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
40pub struct ToolAnnotations {
41 /// Never changes anything outside the agent. Read-only calls in the same
42 /// model turn run concurrently.
43 pub read_only: bool,
44 /// May destroy or overwrite data, or act externally (send, deploy, pay).
45 pub destructive: bool,
46 /// Safe to re-run with the same arguments (matters for resume/replay).
47 pub idempotent: bool,
48 /// Sends data or acts outside the owner's machine and workspace, or is
49 /// irreversible (send, post, HTTP write, credentialed request, delete,
50 /// standing-rule change, payment).
51 #[serde(default)]
52 pub egress: bool,
53}
54
55impl ToolAnnotations {
56 pub const READ_ONLY: Self = Self {
57 read_only: true,
58 destructive: false,
59 idempotent: true,
60 egress: false,
61 };
62 pub const WRITE: Self = Self {
63 read_only: false,
64 destructive: false,
65 idempotent: false,
66 egress: false,
67 };
68 pub const DESTRUCTIVE: Self = Self {
69 read_only: false,
70 destructive: true,
71 idempotent: false,
72 egress: true,
73 };
74}
75
76impl Default for ToolAnnotations {
77 fn default() -> Self {
78 Self::DESTRUCTIVE
79 }
80}
81
82/// What one call will touch, declared by the tool from its arguments.
83/// Policies use it for scope checks and sandboxes for confinement. Empty
84/// means "not declared", not "touches nothing".
85#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
86pub struct AccessManifest {
87 /// Paths read.
88 #[serde(default, skip_serializing_if = "Vec::is_empty")]
89 pub reads: Vec<String>,
90 /// Paths created, modified or deleted.
91 #[serde(default, skip_serializing_if = "Vec::is_empty")]
92 pub writes: Vec<String>,
93 /// Hosts contacted.
94 #[serde(default, skip_serializing_if = "Vec::is_empty")]
95 pub hosts: Vec<String>,
96 /// Commands executed (first word or full command line).
97 #[serde(default, skip_serializing_if = "Vec::is_empty")]
98 pub commands: Vec<String>,
99}
100
101impl AccessManifest {
102 pub fn is_empty(&self) -> bool {
103 self.reads.is_empty()
104 && self.writes.is_empty()
105 && self.hosts.is_empty()
106 && self.commands.is_empty()
107 }
108}
109
110/// What `before_tool` hooks know about the tool behind a call.
111#[derive(Debug, Clone, PartialEq)]
112pub struct ToolInfo {
113 pub annotations: ToolAnnotations,
114 pub access: AccessManifest,
115 /// What this call does, from [`Tool::effects`].
116 pub effects: CallEffects,
117 /// What a read carries out of the machine, from [`Tool::outbound`].
118 pub outbound: Outbound,
119}
120
121/// What a call carries out of the machine, for a call that only reads. A
122/// fetch changes nothing, yet its URL can carry private data to whoever runs
123/// the server, so it counts once the run has read untrusted content.
124#[derive(Debug, Clone, Default, PartialEq, Eq)]
125pub enum Outbound {
126 /// Nothing leaves.
127 #[default]
128 Nothing,
129 /// Exactly these strings leave. A string the user typed as a whole token
130 /// holds no data the run composed; one found only in a tool result does
131 /// not count, since an untrusted page could name it.
132 Exact(Vec<String>),
133 /// Text the model composed, such as a search query.
134 Composed,
135}
136
137/// Typed application values a tool can read from its [`ToolContext`],
138/// keyed by type: at most one value per type. The application sets them on
139/// the agent with [`crate::AgentBuilder::tool_extensions`]; every call's
140/// context carries them. Cloning is cheap (values are shared).
141#[derive(Clone, Default)]
142pub struct Extensions {
143 values: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
144}
145
146impl Extensions {
147 /// Store `value`, replacing any earlier value of the same type.
148 pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
149 self.values.insert(TypeId::of::<T>(), Arc::new(value));
150 }
151
152 /// The value of type `T`, if one was inserted.
153 pub fn get<T: 'static>(&self) -> Option<&T> {
154 self.values
155 .get(&TypeId::of::<T>())
156 .and_then(|value| value.downcast_ref::<T>())
157 }
158}
159
160impl fmt::Debug for Extensions {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 f.debug_struct("Extensions")
163 .field("len", &self.values.len())
164 .finish_non_exhaustive()
165 }
166}
167
168/// Trusted, harness-provided context for one call.
169///
170/// This is passed beside the model's arguments rather than injected into
171/// them, so a model can never spoof a session id or role by inventing a field.
172#[derive(Debug, Clone)]
173#[non_exhaustive]
174pub struct ToolContext {
175 pub run_id: RunId,
176 pub session_id: String,
177 pub call_id: String,
178 pub turn: u32,
179 /// Cancelled when the run is cancelled; long tools should watch it.
180 pub cancel: CancellationToken,
181 /// Application values set with [`crate::AgentBuilder::tool_extensions`].
182 pub extensions: Extensions,
183 /// The owner's declines in this run, live. A tool that starts another
184 /// run shares them with it.
185 pub declines: Option<SharedDeclines>,
186 /// What this run may do, when a hook enforces it. A tool that starts
187 /// another run must not let it do more.
188 pub authority: Option<Authority>,
189 /// Has a call the tool makes on its own (a program it drives asks to
190 /// act) judged by the run's safeguards; see [`crate::NestedCalls`].
191 /// `None` outside a running batch.
192 pub nested: Option<crate::NestedCalls>,
193}
194
195impl ToolContext {
196 /// A context with a fresh run id, turn 0 and a new cancel token. The
197 /// loop fills in the real values; tests and adapters use this directly.
198 pub fn new(session_id: impl Into<String>, call_id: impl Into<String>) -> Self {
199 Self {
200 run_id: RunId::new(),
201 session_id: session_id.into(),
202 call_id: call_id.into(),
203 turn: 0,
204 cancel: CancellationToken::new(),
205 extensions: Extensions::default(),
206 declines: None,
207 authority: None,
208 nested: None,
209 }
210 }
211
212 pub fn with_run(mut self, run_id: RunId, turn: u32) -> Self {
213 self.run_id = run_id;
214 self.turn = turn;
215 self
216 }
217
218 pub fn with_cancel(mut self, cancel: CancellationToken) -> Self {
219 self.cancel = cancel;
220 self
221 }
222
223 pub fn with_extensions(mut self, extensions: Extensions) -> Self {
224 self.extensions = extensions;
225 self
226 }
227
228 pub fn with_declines(mut self, declines: SharedDeclines) -> Self {
229 self.declines = Some(declines);
230 self
231 }
232
233 pub fn with_authority(mut self, authority: Option<Authority>) -> Self {
234 self.authority = authority;
235 self
236 }
237
238 pub fn with_nested(mut self, nested: Option<crate::NestedCalls>) -> Self {
239 self.nested = nested;
240 self
241 }
242}
243
244/// A tool's request to end the run once its batch completes. The run ends
245/// with [`crate::RunStatus::Finished`] and `reply` as its final text, without
246/// another model call and without consulting `on_stop` hooks.
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[non_exhaustive]
249pub struct Finish {
250 /// The run's final text, if the tool has one for the user.
251 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub reply: Option<String>,
253 pub outcome: FinishOutcome,
254}
255
256impl Finish {
257 pub fn new(outcome: FinishOutcome, reply: Option<String>) -> Self {
258 Self { reply, outcome }
259 }
260
261 /// The work is done; `reply` is the run's final text.
262 pub fn succeeded(reply: impl Into<String>) -> Self {
263 Self::new(FinishOutcome::Succeeded, Some(reply.into()))
264 }
265
266 /// Some of the work is done; `reply` says what is left.
267 pub fn partial(reply: impl Into<String>) -> Self {
268 Self::new(FinishOutcome::Partial, Some(reply.into()))
269 }
270
271 /// The work cannot go on without someone else; `reply` says why.
272 pub fn blocked(reply: impl Into<String>) -> Self {
273 Self::new(FinishOutcome::Blocked, Some(reply.into()))
274 }
275}
276
277/// What a tool hands back to the model, plus structured details for receipts.
278#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
279pub struct ToolOutput {
280 /// Text the model will read.
281 pub content: String,
282 /// Images the model will see with the text (a screenshot, a rendered
283 /// page, an image file the tool read).
284 #[serde(default, skip_serializing_if = "Vec::is_empty")]
285 pub images: Vec<Image>,
286 /// The tool ran but the outcome is a failure the model should react to
287 /// (non-zero exit, HTTP 4xx, no match). Recorded as a failed receipt.
288 pub is_error: bool,
289 /// Structured evidence copied into the receipt (exit code, paths, status).
290 #[serde(default, skip_serializing_if = "Value::is_null")]
291 pub details: Value,
292 /// Model usage spent inside the tool (for example a sub-agent). The loop
293 /// adds it to the run's usage, so budgets cover delegated work.
294 #[serde(default)]
295 pub usage: Usage,
296 /// Overrides [`Tool::source_trust`] for this result (for example a
297 /// fetch tool that knows this particular URL is the owner's own).
298 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub trust: Option<SourceTrust>,
300 /// End the run after this call's batch (see [`ToolOutput::finish`]).
301 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub finish: Option<Finish>,
303 /// A paused child run: this call has no result yet, and the run pauses
304 /// with it (see [`ToolOutput::suspended`]).
305 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub suspended: Option<Box<RunState>>,
307}
308
309impl ToolOutput {
310 pub fn text(content: impl Into<String>) -> Self {
311 Self {
312 content: content.into(),
313 images: Vec::new(),
314 is_error: false,
315 details: Value::Null,
316 usage: Usage::default(),
317 trust: None,
318 finish: None,
319 suspended: None,
320 }
321 }
322
323 pub fn error(content: impl Into<String>) -> Self {
324 Self {
325 content: content.into(),
326 images: Vec::new(),
327 is_error: true,
328 details: Value::Null,
329 usage: Usage::default(),
330 trust: None,
331 finish: None,
332 suspended: None,
333 }
334 }
335
336 /// The child this call started is interrupted: pause the calling run
337 /// too, with `child` saved in its [`crate::Pending`]. The answer reaches
338 /// the tool through [`Tool::resume_child`]. Only a tool whose
339 /// [`Tool::suspends`] is true may return this, and `child` must be
340 /// interrupted; anything else is a failed call.
341 pub fn suspended(child: RunState) -> Self {
342 Self {
343 suspended: Some(Box::new(child)),
344 ..Self::text("")
345 }
346 }
347
348 pub fn with_usage(mut self, usage: Usage) -> Self {
349 self.usage = usage;
350 self
351 }
352
353 pub fn with_images(mut self, images: impl IntoIterator<Item = Image>) -> Self {
354 self.images.extend(images);
355 self
356 }
357
358 pub fn with_details(mut self, details: Value) -> Self {
359 self.details = details;
360 self
361 }
362
363 pub fn with_trust(mut self, trust: SourceTrust) -> Self {
364 self.trust = Some(trust);
365 self
366 }
367
368 /// End the run once the batch this call belongs to completes. Every
369 /// call in the batch still runs and gets its receipt; if several calls
370 /// finish, the first in call order wins.
371 pub fn finish(mut self, finish: Finish) -> Self {
372 self.finish = Some(finish);
373 self
374 }
375}
376
377/// A tool failure the harness could not turn into normal output. The loop
378/// still reports it to the model as an error result; it never ends the run.
379#[derive(Debug, Clone, PartialEq, thiserror::Error)]
380#[error("{0}")]
381pub struct ToolError(pub String);
382
383impl ToolError {
384 /// A failure with this message, for the model and the receipt:
385 /// `Err(ToolError::new("order not found"))`. `?` on an `io::Error`,
386 /// and `.into()` on a `&str` or `String`, build one too.
387 pub fn new(message: impl Into<String>) -> Self {
388 Self(message.into())
389 }
390}
391
392impl From<String> for ToolError {
393 fn from(value: String) -> Self {
394 Self(value)
395 }
396}
397
398impl From<&str> for ToolError {
399 fn from(value: &str) -> Self {
400 Self(value.to_string())
401 }
402}
403
404impl From<std::io::Error> for ToolError {
405 fn from(value: std::io::Error) -> Self {
406 Self(value.to_string())
407 }
408}
409
410impl From<serde_json::Error> for ToolError {
411 fn from(value: serde_json::Error) -> Self {
412 Self(format!("invalid arguments: {value}"))
413 }
414}
415
416pub type ToolResult = Result<ToolOutput, ToolError>;
417
418/// An LLM-callable capability. Only `spec` and `call` are required.
419///
420/// Richer per-call semantics (annotations, access, typed effects) are
421/// optional methods with conservative defaults, so the simple case stays
422/// simple.
423#[async_trait]
424pub trait Tool: Send + Sync {
425 fn spec(&self) -> ToolSpec;
426
427 fn annotations(&self) -> ToolAnnotations {
428 ToolAnnotations::default()
429 }
430
431 /// Annotations for one call. Tools whose effect depends on the arguments
432 /// (a shell running `ls` versus `rm`) override this; the default is the
433 /// tool-wide [`Tool::annotations`].
434 ///
435 /// [`Tool::annotations`] must be the worst-case (most restrictive)
436 /// value for the tool; this may only relax it for a specific call. The
437 /// result is trusted as given by authority checks (and recorded in the
438 /// receipt), so it must be correct for those arguments. Concurrent
439 /// scheduling always uses [`Tool::annotations`], never this value.
440 /// Crash-recovery replay uses this per-call `idempotent`: a call
441 /// declared idempotent for its arguments is re-run, not marked
442 /// indeterminate.
443 fn annotations_for(&self, _arguments: &Value) -> ToolAnnotations {
444 self.annotations()
445 }
446
447 /// Who authored what this call returns. The default is `Untrusted`; a
448 /// tool whose output is the owner's own (a workspace file, the
449 /// kernel's bookkeeping) returns `Trusted`. A result may override this
450 /// with [`ToolOutput::with_trust`].
451 fn source_trust(&self, _arguments: &Value) -> SourceTrust {
452 SourceTrust::Untrusted
453 }
454
455 /// What this call carries out of the machine if it only reads. The
456 /// default says nothing does.
457 fn outbound(&self, _arguments: &Value) -> Outbound {
458 Outbound::Nothing
459 }
460
461 /// Deterministic argument checks, run before any policy or I/O. The
462 /// kernel checks the arguments against the declared schema
463 /// ([`check_arguments`]: required keys, types, enums, nested objects
464 /// and array items) before calling this, whatever a tool does here, so
465 /// an override only adds checks. The default is that schema check.
466 fn validate(&self, arguments: &Value) -> Result<(), String> {
467 check_arguments(&self.spec().parameters, arguments)
468 }
469
470 /// How long this tool may run, overriding `Limits::tool_timeout`. Tools
471 /// that take their own timeout argument (such as a shell) return a value
472 /// at least as long as their own maximum.
473 fn timeout(&self) -> Option<std::time::Duration> {
474 None
475 }
476
477 /// Declare what this call will touch. Optional; policies treat an empty
478 /// manifest as undeclared.
479 fn access(&self, _arguments: &Value) -> AccessManifest {
480 AccessManifest::default()
481 }
482
483 /// The typed effects of this call (effect class and normalized target).
484 /// The default is [`CallEffects::none`] for a call that is read-only and
485 /// not egress (per [`Tool::annotations_for`]). Otherwise it is what the
486 /// call's declared [`Tool::access`] implies ([`CallEffects::from_access`]:
487 /// a written path is a write effect, a host an egress effect), so an
488 /// owner's denial of the call binds the rest of the run; and
489 /// [`CallEffects::unknown`] when it declares no access: a read from
490 /// another host still sends the request off the machine, so a tool
491 /// annotated `egress` should declare its host or its
492 /// [`EffectKey::egress`](crate::EffectKey::egress) target. Recomputed
493 /// after a hook rewrites the arguments.
494 fn effects(&self, arguments: &Value) -> CallEffects {
495 let annotations = self.annotations_for(arguments);
496 if annotations.read_only && !annotations.egress {
497 CallEffects::none()
498 } else {
499 CallEffects::from_access(&self.access(arguments), annotations)
500 }
501 }
502
503 /// How many calls of this tool may run together in one batch although
504 /// the tool is not read-only: 0 (the default) runs each call alone. A
505 /// tool returns more only when it coordinates the shared state its
506 /// concurrent calls touch itself (sub-agents whose writes a coordination
507 /// ledger arbitrates). Calls queued this way still run after every
508 /// earlier call in the batch has been judged, and before any later call
509 /// that is not concurrent-safe.
510 fn concurrent_peers(&self) -> usize {
511 0
512 }
513
514 /// Whether this tool may answer with [`ToolOutput::suspended`]. A call
515 /// of such a tool always runs alone, because a run pauses on one call at
516 /// a time.
517 fn suspends(&self) -> bool {
518 false
519 }
520
521 /// Continue the child run this tool suspended, with the answer to its
522 /// interruption, and return what [`Tool::call`] would have returned: a
523 /// result, or [`ToolOutput::suspended`] if the child paused again.
524 ///
525 /// `ctx` is that of the delegating run as it is now, so its authority
526 /// and declines are the ones to apply: a resumed child answers to them
527 /// exactly as a child started by [`Tool::call`] does. `child` may come
528 /// from another process.
529 ///
530 /// A crash while this runs leaves the delegating call started with no
531 /// result, the same as a crash during [`Tool::call`]: on recovery it is
532 /// re-run if idempotent and marked indeterminate otherwise.
533 async fn resume_child(
534 &self,
535 _child: RunState,
536 _resolution: Resolution,
537 _ctx: &ToolContext,
538 ) -> ToolResult {
539 Err(ToolError(format!(
540 "`{}` cannot continue a paused run",
541 self.spec().name
542 )))
543 }
544
545 async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult;
546}
547
548/// Minimal schema check: the arguments must be an object containing every
549/// `required` key. Full JSON Schema validation is left to tools that need it.
550/// Drop every top-level argument key starting with `_`. Those keys are the
551/// dispatcher's (an application passes its own facts to a tool through
552/// [`ToolContext`], never through arguments), so a model that sends one is
553/// impersonating it. The kernel applies this to every call a model
554/// proposes before anything reads it, and the daemon's dispatcher uses the
555/// same function.
556pub fn strip_reserved_arguments(map: &mut serde_json::Map<String, Value>) {
557 map.retain(|key, _| !key.starts_with('_'));
558}
559
560/// Check `arguments` against a tool's declared JSON schema: an object when
561/// the schema says `"type": "object"`, every `required` key present and not
562/// null, and each present value of the declared `type` (`string`,
563/// `integer` (a whole number), `number`, `boolean`, `array`, `object`,
564/// `null`, or a list of these), within its `enum`, with nested objects and
565/// array items checked the same way. A `null` for a key that is not
566/// required counts as absent. Keywords beyond these are not enforced.
567pub fn check_arguments(schema: &Value, arguments: &Value) -> Result<(), String> {
568 check_value(schema, arguments, "arguments", true)
569}
570
571/// [`check_arguments`] without `required` keys (at any depth): what the
572/// kernel enforces for every call whatever the tool's own
573/// [`Tool::validate`] says. Which keys a call may leave out is the tool's
574/// contract (a dispatcher may fill defaults); what a present value is, is
575/// not.
576pub fn check_argument_types(schema: &Value, arguments: &Value) -> Result<(), String> {
577 check_value(schema, arguments, "arguments", false)
578}
579
580fn check_value(schema: &Value, value: &Value, at: &str, required_keys: bool) -> Result<(), String> {
581 if let Some(types) = schema.get("type") {
582 let allowed: Vec<&str> = match types {
583 Value::String(one) => vec![one.as_str()],
584 Value::Array(many) => many.iter().filter_map(Value::as_str).collect(),
585 _ => Vec::new(),
586 };
587 if !allowed.is_empty() && !allowed.iter().any(|t| is_type(value, t)) {
588 return Err(if at == "arguments" && allowed == ["object"] {
589 "arguments must be a JSON object".to_string()
590 } else {
591 format!(
592 "`{at}` must be {}, not {}",
593 allowed.join(" or "),
594 kind(value)
595 )
596 });
597 }
598 }
599 if let Some(options) = schema.get("enum").and_then(Value::as_array)
600 && !options.contains(value)
601 {
602 let listed: Vec<String> = options.iter().map(Value::to_string).collect();
603 return Err(format!("`{at}` must be one of {}", listed.join(", ")));
604 }
605 if let Value::Object(object) = value {
606 let required: Vec<&str> = schema
607 .get("required")
608 .and_then(Value::as_array)
609 .into_iter()
610 .flatten()
611 .filter_map(Value::as_str)
612 .collect();
613 let missing: Vec<&str> = required
614 .iter()
615 .filter(|_| required_keys)
616 .copied()
617 .filter(|key| object.get(*key).is_none_or(Value::is_null))
618 .filter(|key| {
619 // A required key whose own schema allows null may be null.
620 !object.contains_key(*key)
621 || !schema
622 .get("properties")
623 .and_then(|p| p.get(*key))
624 .is_some_and(allows_null)
625 })
626 .collect();
627 if !missing.is_empty() {
628 let prefix = if at == "arguments" {
629 String::new()
630 } else {
631 format!("`{at}`: ")
632 };
633 return Err(format!(
634 "{prefix}missing required argument(s): {}",
635 missing.join(", ")
636 ));
637 }
638 if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
639 for (key, property) in properties {
640 let Some(item) = object.get(key) else {
641 continue;
642 };
643 if item.is_null() && !required.contains(&key.as_str()) {
644 continue;
645 }
646 let path = if at == "arguments" {
647 key.clone()
648 } else {
649 format!("{at}.{key}")
650 };
651 check_value(property, item, &path, required_keys)?;
652 }
653 }
654 }
655 if let (Value::Array(items), Some(item_schema)) = (value, schema.get("items"))
656 && item_schema.is_object()
657 {
658 for (index, item) in items.iter().enumerate() {
659 check_value(item_schema, item, &format!("{at}[{index}]"), required_keys)?;
660 }
661 }
662 Ok(())
663}
664
665fn allows_null(schema: &Value) -> bool {
666 match schema.get("type") {
667 Some(Value::String(t)) => t == "null",
668 Some(Value::Array(ts)) => ts.iter().any(|t| t == "null"),
669 _ => true,
670 }
671}
672
673fn is_type(value: &Value, wanted: &str) -> bool {
674 match wanted {
675 "string" => value.is_string(),
676 "number" => value.is_number(),
677 "integer" => {
678 value.is_i64()
679 || value.is_u64()
680 || value
681 .as_f64()
682 .is_some_and(|n| n.fract() == 0.0 && n.is_finite())
683 }
684 "boolean" => value.is_boolean(),
685 "array" => value.is_array(),
686 "object" => value.is_object(),
687 "null" => value.is_null(),
688 // An unknown type name is not ours to enforce.
689 _ => true,
690 }
691}
692
693fn kind(value: &Value) -> &'static str {
694 match value {
695 Value::Null => "null",
696 Value::Bool(_) => "a boolean",
697 Value::Number(_) => "a number",
698 Value::String(_) => "a string",
699 Value::Array(_) => "an array",
700 Value::Object(_) => "an object",
701 }
702}
703
704/// Build a tool from a closure. Handy for tests and small integrations.
705///
706/// ```
707/// use aidaemon_core::{FnTool, ToolAnnotations, ToolOutput, ToolSpec};
708/// use serde_json::{json, Value};
709///
710/// let spec = ToolSpec {
711/// name: "echo".into(),
712/// description: "Echo the text back".into(),
713/// parameters: json!({"type": "object", "required": ["text"]}),
714/// };
715/// let echo = FnTool::new(spec, ToolAnnotations::READ_ONLY, |args: Value| async move {
716/// Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default().to_string()))
717/// });
718/// # let _ = echo;
719/// ```
720pub struct FnTool<F, Fut> {
721 spec: ToolSpec,
722 annotations: ToolAnnotations,
723 trust: SourceTrust,
724 func: F,
725 _fut: PhantomData<fn() -> Fut>,
726}
727
728impl<F, Fut> FnTool<F, Fut>
729where
730 F: Fn(Value) -> Fut + Send + Sync,
731 Fut: Future<Output = ToolResult> + Send,
732{
733 pub fn new(spec: ToolSpec, annotations: ToolAnnotations, func: F) -> Self {
734 Self {
735 spec,
736 annotations,
737 trust: SourceTrust::default(),
738 func,
739 _fut: PhantomData,
740 }
741 }
742
743 /// Declare the trust class of this tool's output (default `Untrusted`).
744 pub fn with_trust(mut self, trust: SourceTrust) -> Self {
745 self.trust = trust;
746 self
747 }
748}
749
750#[async_trait]
751impl<F, Fut> Tool for FnTool<F, Fut>
752where
753 F: Fn(Value) -> Fut + Send + Sync,
754 Fut: Future<Output = ToolResult> + Send,
755{
756 fn spec(&self) -> ToolSpec {
757 self.spec.clone()
758 }
759
760 fn annotations(&self) -> ToolAnnotations {
761 self.annotations
762 }
763
764 fn source_trust(&self, _arguments: &Value) -> SourceTrust {
765 self.trust
766 }
767
768 async fn call(&self, arguments: Value, _ctx: &ToolContext) -> ToolResult {
769 (self.func)(arguments).await
770 }
771}
772
773/// The consecutive-call allowance of a tool: how long a run may call it in a
774/// row before the same-tool guard treats the streak as a loop.
775#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
776pub enum SameToolStreak {
777 /// The default allowance.
778 #[default]
779 Standard,
780 /// A versatile or research tool whose calls naturally repeat (reading
781 /// files, searching, running commands): a longer allowance.
782 Versatile,
783 /// A step-wise tool driven one small action at a time (computer use):
784 /// the longest allowance, and no exemption for distinct arguments.
785 Stepwise,
786}
787
788#[cfg(test)]
789mod tests {
790 use super::*;
791 use serde_json::json;
792
793 #[test]
794 fn required_keys_are_checked() {
795 let schema = json!({"type": "object", "required": ["path", "text"]});
796 assert!(check_arguments(&schema, &json!({"path": "a", "text": "b"})).is_ok());
797 let err = check_arguments(&schema, &json!({"path": "a"})).unwrap_err();
798 assert!(err.contains("text"), "{err}");
799 assert!(check_arguments(&schema, &json!("not an object")).is_err());
800 }
801
802 #[test]
803 fn default_effects_of_a_read_only_egress_call_are_unknown() {
804 let tool = |annotations| {
805 FnTool::new(
806 ToolSpec {
807 name: "probe".into(),
808 description: "synthetic".into(),
809 parameters: json!({"type": "object"}),
810 },
811 annotations,
812 |_args: Value| async move { Ok(ToolOutput::text("ok")) },
813 )
814 };
815 let local_read = tool(ToolAnnotations::READ_ONLY);
816 assert_eq!(local_read.effects(&json!({})), CallEffects::none());
817 // Reading from another host still sends the request off the machine.
818 let remote_read = tool(ToolAnnotations {
819 egress: true,
820 ..ToolAnnotations::READ_ONLY
821 });
822 assert_eq!(remote_read.effects(&json!({})), CallEffects::unknown());
823 }
824
825 #[test]
826 fn unannotated_tools_are_conservative() {
827 let ann = ToolAnnotations::default();
828 assert!(!ann.read_only);
829 assert!(ann.destructive);
830 }
831}