1use 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#[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#[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#[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
67pub fn timed_out(error: &anyhow::Error) -> bool {
69 error.downcast_ref::<ToolTimedOut>().is_some()
70}
71
72pub 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#[async_trait]
90pub trait OutcomeTool: ToolSemantics {
91 fn name(&self) -> &str;
92 fn description(&self) -> &str;
94 fn schema(&self) -> Value;
96 async fn execute(
98 &self,
99 arguments: &str,
100 facts: &ToolCallContext,
101 ) -> anyhow::Result<ToolCallOutcome>;
102 fn validate_call(&self, _arguments: &Value) -> Result<(), String> {
104 Ok(())
105 }
106 fn approval_card_mode(&self) -> Option<PermissionMode> {
109 None
110 }
111 fn approval_card_kind(&self, _request: &aidaemon_core::OwnerApprovalRequest) -> ApprovalKind {
116 ApprovalKind::Command
117 }
118 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
143pub(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
163pub 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
183pub(crate) async fn run_as_core<T: OutcomeTool + ?Sized>(tool: &T, arguments: Value) -> ToolResult {
186 run_as_core_with(tool, arguments, &ToolCallContext::default()).await
187}
188
189pub(crate) async fn run_as_core_with<T: OutcomeTool + ?Sized>(
191 tool: &T,
192 arguments: Value,
193 facts: &ToolCallContext,
194) -> ToolResult {
195 let raw = arguments.to_string();
196 let outcome = match tool.execute(&raw, facts).await {
197 Ok(outcome) => outcome,
198 Err(error) => return Ok(ToolOutput::error(error.to_string())),
199 };
200 let mut output = if outcome.metadata.contract_rejected {
201 ToolOutput::error(outcome.output)
202 } else {
203 ToolOutput::text(outcome.output)
204 };
205 if let Some(read) = &outcome.metadata.read_file {
206 output = output.with_details(json!({
207 "path": read.display_path,
208 "start_line": read.returned_start_line,
209 "end_line": read.returned_end_line,
210 "total_lines": read.total_lines,
211 "truncated": read.truncated,
212 }));
213 }
214 output.finish = outcome.finish;
215 Ok(output)
216}
217
218#[async_trait]
222pub trait OutcomeRunner: Send + Sync {
223 async fn run(&self, tool: &str, arguments: Value, ctx: &ToolContext) -> ToolResult;
224}
225
226pub type CallValidator = Arc<dyn Fn(&Value) -> Result<(), String> + Send + Sync>;
228
229pub struct KernelAdapter<T: ?Sized> {
233 tool: Arc<T>,
234 spec: ToolSpec,
235 trust_roots: Arc<Vec<String>>,
236 owned: crate::semantics::OwnedFolders,
237 validator: Option<CallValidator>,
238 timeout: Option<Duration>,
239 runner: Option<Arc<dyn OutcomeRunner>>,
240 facts: ToolCallContext,
241}
242
243impl<T: OutcomeTool + ?Sized> KernelAdapter<T> {
244 pub fn new(tool: Arc<T>) -> Self {
245 let spec = spec_of(tool.as_ref());
246 Self {
247 tool,
248 spec,
249 trust_roots: Arc::new(Vec::new()),
250 owned: Default::default(),
251 validator: None,
252 timeout: None,
253 runner: None,
254 facts: ToolCallContext::default(),
255 }
256 }
257
258 pub fn with_call_facts(mut self, facts: ToolCallContext) -> Self {
262 self.facts = facts;
263 self
264 }
265
266 pub fn with_spec(mut self, spec: ToolSpec) -> Self {
268 self.spec = spec;
269 self
270 }
271
272 pub fn with_trust_roots(mut self, roots: Arc<Vec<String>>) -> Self {
274 self.trust_roots = roots;
275 self
276 }
277
278 pub fn with_owned_folders(mut self, owned: crate::semantics::OwnedFolders) -> Self {
282 self.owned = owned;
283 self
284 }
285
286 pub fn with_validator(mut self, validator: CallValidator) -> Self {
288 self.validator = Some(validator);
289 self
290 }
291
292 pub fn with_timeout(mut self, timeout: Duration) -> Self {
293 self.timeout = Some(timeout);
294 self
295 }
296
297 pub fn with_runner(mut self, runner: Arc<dyn OutcomeRunner>) -> Self {
299 self.runner = Some(runner);
300 self
301 }
302
303 fn canonical(&self, arguments: &Value) -> String {
304 let raw = arguments.to_string();
305 self.tool.canonicalize_arguments(&raw).unwrap_or(raw)
306 }
307}
308
309pub const MAX_CONCURRENT_CHILDREN: usize = 3;
311
312#[async_trait]
313impl<T: OutcomeTool + ?Sized + 'static> aidaemon_core::Tool for KernelAdapter<T> {
314 fn spec(&self) -> ToolSpec {
315 self.spec.clone()
316 }
317
318 fn annotations(&self) -> ToolAnnotations {
321 if self.tool.capabilities().read_only {
322 ToolAnnotations::READ_ONLY
323 } else {
324 ToolAnnotations {
325 read_only: false,
326 destructive: true,
327 idempotent: false,
328 egress: true,
329 }
330 }
331 }
332
333 fn concurrent_peers(&self) -> usize {
337 if self.tool.dispatch_facts().spawns_child_agents {
338 MAX_CONCURRENT_CHILDREN
339 } else {
340 0
341 }
342 }
343
344 fn annotations_for(&self, arguments: &Value) -> ToolAnnotations {
347 let owned = self.owned.list();
348 self.tool.call_annotations_in(
349 &arguments.to_string(),
350 &TrustRoots::new(&self.trust_roots).with_owned(&owned),
351 )
352 }
353
354 fn outbound(&self, arguments: &Value) -> Outbound {
355 self.tool.call_outbound(&arguments.to_string())
356 }
357
358 fn effects(&self, arguments: &Value) -> CallEffects {
361 self.tool.call_effects(&self.canonical(arguments))
362 }
363
364 fn access(&self, arguments: &Value) -> AccessManifest {
368 let mut manifest = AccessManifest::default();
369 let facts = self.tool.dispatch_facts();
370 if facts.shell_command_line {
371 for field in ["command", "script"] {
372 if let Some(text) = arguments
373 .get(field)
374 .and_then(Value::as_str)
375 .filter(|text| !text.trim().is_empty())
376 {
377 manifest.commands.push(text.to_string());
378 }
379 }
380 }
381 for key in self.effects(arguments).keys {
382 let list = match key.class {
383 EffectClass::Egress => &mut manifest.hosts,
384 EffectClass::Write | EffectClass::Delete | EffectClass::Configuration => {
385 &mut manifest.writes
386 }
387 _ => continue,
388 };
389 if !list.contains(&key.target) {
390 list.push(key.target);
391 }
392 }
393 if facts.file_guard != FileGuard::None {
395 let (reads, writes) = self.tool.guarded_paths(&self.canonical(arguments));
396 manifest.reads.extend(reads);
397 for write in writes {
398 if !manifest.writes.contains(&write) {
399 manifest.writes.push(write);
400 }
401 }
402 }
403 manifest
404 }
405
406 fn source_trust(&self, _arguments: &Value) -> SourceTrust {
408 SourceTrust::Untrusted
409 }
410
411 fn validate(&self, arguments: &Value) -> Result<(), String> {
412 match &self.validator {
413 Some(validator) => validator(arguments),
414 None => validate_for_core(self.tool.as_ref(), arguments),
415 }
416 }
417
418 fn timeout(&self) -> Option<Duration> {
419 self.timeout
420 }
421
422 async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
423 match &self.runner {
424 Some(runner) => runner.run(&self.spec.name, arguments, ctx).await,
425 None => run_as_core_with(self.tool.as_ref(), arguments, &self.facts).await,
426 }
427 }
428}
429
430macro_rules! core_tool {
432 ($ty:ty, annotations: $annotations:expr, access: |$this:ident, $args:ident| $access:expr) => {
433 #[async_trait::async_trait]
434 impl aidaemon_core::Tool for $ty {
435 fn spec(&self) -> aidaemon_core::ToolSpec {
436 $crate::outcome::spec_of(self)
437 }
438
439 fn annotations(&self) -> aidaemon_core::ToolAnnotations {
440 $annotations
441 }
442
443 fn validate(&self, arguments: &serde_json::Value) -> Result<(), String> {
444 $crate::outcome::validate_for_core(self, arguments)
445 }
446
447 fn access(&self, $args: &serde_json::Value) -> aidaemon_core::AccessManifest {
448 let $this = self;
449 $access
450 }
451
452 async fn call(
453 &self,
454 arguments: serde_json::Value,
455 _ctx: &aidaemon_core::ToolContext,
456 ) -> aidaemon_core::ToolResult {
457 $crate::outcome::run_as_core(self, arguments).await
458 }
459 }
460 };
461}
462pub(crate) use core_tool;
463
464#[cfg(test)]
465mod timeout_tests {
466 use super::*;
467
468 #[test]
469 fn a_timeout_is_known_by_its_type_through_context_not_its_words() {
470 let typed = anyhow::Error::new(ToolTimedOut("Command timed out after 5s".into()))
471 .context("search failed");
472 assert!(timed_out(&typed));
473 assert!(!timed_out(&anyhow::anyhow!("Command timed out after 5s")));
475 }
476}