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 holds_to_medium_ceiling(&self, _arguments: &str) -> bool {
115 false
116 }
117 fn approval_card_mode(&self) -> Option<PermissionMode> {
120 None
121 }
122 fn approval_card_kind(&self, _request: &aidaemon_core::OwnerApprovalRequest) -> ApprovalKind {
127 ApprovalKind::Command
128 }
129 async fn approval_grant(
142 &self,
143 _call: &ApprovalCall<'_>,
144 _facts: &ToolCallContext,
145 ) -> Option<crate::semantics::GrantOffer> {
146 None
147 }
148 async fn record_owner_answer(
153 &self,
154 _call: &ApprovalCall<'_>,
155 _facts: &ToolCallContext,
156 _response: Option<ApprovalResponse>,
157 ) {
158 }
159}
160
161pub(crate) fn spec_of<T: OutcomeTool + ?Sized>(tool: &T) -> ToolSpec {
162 let schema = tool.schema();
163 ToolSpec {
164 name: tool.name().to_string(),
165 description: schema["description"]
166 .as_str()
167 .unwrap_or_else(|| tool.description())
168 .to_string(),
169 parameters: schema["parameters"].clone(),
170 }
171}
172
173pub(crate) fn validate_for_core<T: OutcomeTool + ?Sized>(
176 tool: &T,
177 arguments: &Value,
178) -> Result<(), String> {
179 let Some(object) = arguments.as_object() else {
180 return Err("arguments must be a JSON object".into());
181 };
182 let schema = tool.schema();
183 let required = schema["parameters"]["required"].as_array();
184 for key in required.into_iter().flatten().filter_map(Value::as_str) {
185 if !object.contains_key(key) {
186 return Err(format!("`{key}` is required"));
187 }
188 }
189 check_argument_contract(tool, arguments)?;
190 tool.validate_call(arguments)
191}
192
193pub fn check_argument_contract<T: OutcomeTool + ?Sized>(
198 tool: &T,
199 arguments: &Value,
200) -> Result<(), String> {
201 let describe = |violation: crate::semantics::ToolArgumentContractViolation| match violation
202 .recovery_hint
203 {
204 Some(hint) => format!("{} ({hint})", violation.reason),
205 None => violation.reason,
206 };
207 let canonical = tool
208 .canonicalize_arguments(&arguments.to_string())
209 .map_err(describe)?;
210 tool.validate_arguments(&canonical).map_err(describe)
211}
212
213pub(crate) async fn run_as_core<T: OutcomeTool + ?Sized>(tool: &T, arguments: Value) -> ToolResult {
216 run_as_core_with(tool, arguments, &ToolCallContext::default()).await
217}
218
219pub(crate) async fn run_as_core_with<T: OutcomeTool + ?Sized>(
221 tool: &T,
222 arguments: Value,
223 facts: &ToolCallContext,
224) -> ToolResult {
225 let raw = arguments.to_string();
226 let outcome = match tool.execute(&raw, facts).await {
227 Ok(outcome) => outcome,
228 Err(error) => return Ok(ToolOutput::error(error.to_string())),
229 };
230 let mut output = if outcome.metadata.contract_rejected {
231 ToolOutput::error(outcome.output)
232 } else {
233 ToolOutput::text(outcome.output)
234 };
235 if let Some(read) = &outcome.metadata.read_file {
236 output = output.with_details(json!({
237 "path": read.display_path,
238 "start_line": read.returned_start_line,
239 "end_line": read.returned_end_line,
240 "total_lines": read.total_lines,
241 "truncated": read.truncated,
242 }));
243 }
244 output.finish = outcome.finish;
245 Ok(output)
246}
247
248#[async_trait]
252pub trait OutcomeRunner: Send + Sync {
253 async fn run(&self, tool: &str, arguments: Value, ctx: &ToolContext) -> ToolResult;
254}
255
256pub type CallValidator = Arc<dyn Fn(&Value) -> Result<(), String> + Send + Sync>;
258
259pub struct KernelAdapter<T: ?Sized> {
263 tool: Arc<T>,
264 spec: ToolSpec,
265 trust_roots: Arc<Vec<String>>,
266 owned: crate::semantics::OwnedFolders,
267 validator: Option<CallValidator>,
268 timeout: Option<Duration>,
269 runner: Option<Arc<dyn OutcomeRunner>>,
270 facts: ToolCallContext,
271}
272
273impl<T: OutcomeTool + ?Sized> KernelAdapter<T> {
274 pub fn new(tool: Arc<T>) -> Self {
275 let spec = spec_of(tool.as_ref());
276 Self {
277 tool,
278 spec,
279 trust_roots: Arc::new(Vec::new()),
280 owned: Default::default(),
281 validator: None,
282 timeout: None,
283 runner: None,
284 facts: ToolCallContext::default(),
285 }
286 }
287
288 pub fn with_call_facts(mut self, facts: ToolCallContext) -> Self {
292 self.facts = facts;
293 self
294 }
295
296 pub fn with_spec(mut self, spec: ToolSpec) -> Self {
298 self.spec = spec;
299 self
300 }
301
302 pub fn with_trust_roots(mut self, roots: Arc<Vec<String>>) -> Self {
304 self.trust_roots = roots;
305 self
306 }
307
308 pub fn with_owned_folders(mut self, owned: crate::semantics::OwnedFolders) -> Self {
312 self.owned = owned;
313 self
314 }
315
316 pub fn with_validator(mut self, validator: CallValidator) -> Self {
318 self.validator = Some(validator);
319 self
320 }
321
322 pub fn with_timeout(mut self, timeout: Duration) -> Self {
323 self.timeout = Some(timeout);
324 self
325 }
326
327 pub fn with_runner(mut self, runner: Arc<dyn OutcomeRunner>) -> Self {
329 self.runner = Some(runner);
330 self
331 }
332
333 fn canonical(&self, arguments: &Value) -> String {
334 let raw = arguments.to_string();
335 self.tool.canonicalize_arguments(&raw).unwrap_or(raw)
336 }
337}
338
339pub const MAX_CONCURRENT_CHILDREN: usize = 3;
341
342#[async_trait]
343impl<T: OutcomeTool + ?Sized + 'static> aidaemon_core::Tool for KernelAdapter<T> {
344 fn spec(&self) -> ToolSpec {
345 self.spec.clone()
346 }
347
348 fn annotations(&self) -> ToolAnnotations {
351 if self.tool.capabilities().read_only {
352 ToolAnnotations::READ_ONLY
353 } else {
354 ToolAnnotations {
355 read_only: false,
356 destructive: true,
357 idempotent: false,
358 egress: true,
359 }
360 }
361 }
362
363 fn concurrent_peers(&self) -> usize {
367 if self.tool.dispatch_facts().spawns_child_agents {
368 MAX_CONCURRENT_CHILDREN
369 } else {
370 0
371 }
372 }
373
374 fn annotations_for(&self, arguments: &Value) -> ToolAnnotations {
377 let owned = self.owned.list();
378 self.tool.call_annotations_in(
379 &arguments.to_string(),
380 &TrustRoots::new(&self.trust_roots).with_owned(&owned),
381 )
382 }
383
384 fn outbound(&self, arguments: &Value) -> Outbound {
385 self.tool.call_outbound(&arguments.to_string())
386 }
387
388 fn effects(&self, arguments: &Value) -> CallEffects {
391 self.tool.call_effects(&self.canonical(arguments))
392 }
393
394 fn access(&self, arguments: &Value) -> AccessManifest {
398 let mut manifest = AccessManifest::default();
399 let facts = self.tool.dispatch_facts();
400 if facts.shell_command_line {
401 for field in ["command", "script"] {
402 if let Some(text) = arguments
403 .get(field)
404 .and_then(Value::as_str)
405 .filter(|text| !text.trim().is_empty())
406 {
407 manifest.commands.push(text.to_string());
408 }
409 }
410 }
411 for key in self.effects(arguments).keys {
412 let list = match key.class {
413 EffectClass::Egress => &mut manifest.hosts,
414 EffectClass::Write | EffectClass::Delete | EffectClass::Configuration => {
415 &mut manifest.writes
416 }
417 _ => continue,
418 };
419 if !list.contains(&key.target) {
420 list.push(key.target);
421 }
422 }
423 if facts.file_guard != FileGuard::None {
425 let (reads, writes) = self.tool.guarded_paths(&self.canonical(arguments));
426 manifest.reads.extend(reads);
427 for write in writes {
428 if !manifest.writes.contains(&write) {
429 manifest.writes.push(write);
430 }
431 }
432 }
433 manifest
434 }
435
436 fn source_trust(&self, _arguments: &Value) -> SourceTrust {
438 SourceTrust::Untrusted
439 }
440
441 fn validate(&self, arguments: &Value) -> Result<(), String> {
442 match &self.validator {
443 Some(validator) => validator(arguments),
444 None => validate_for_core(self.tool.as_ref(), arguments),
445 }
446 }
447
448 fn timeout(&self) -> Option<Duration> {
449 self.timeout
450 }
451
452 async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
453 match &self.runner {
454 Some(runner) => runner.run(&self.spec.name, arguments, ctx).await,
455 None => run_as_core_with(self.tool.as_ref(), arguments, &self.facts).await,
456 }
457 }
458}
459
460macro_rules! core_tool {
462 ($ty:ty, annotations: $annotations:expr, access: |$this:ident, $args:ident| $access:expr) => {
463 #[async_trait::async_trait]
464 impl aidaemon_core::Tool for $ty {
465 fn spec(&self) -> aidaemon_core::ToolSpec {
466 $crate::outcome::spec_of(self)
467 }
468
469 fn annotations(&self) -> aidaemon_core::ToolAnnotations {
470 $annotations
471 }
472
473 fn validate(&self, arguments: &serde_json::Value) -> Result<(), String> {
474 $crate::outcome::validate_for_core(self, arguments)
475 }
476
477 fn access(&self, $args: &serde_json::Value) -> aidaemon_core::AccessManifest {
478 let $this = self;
479 $access
480 }
481
482 async fn call(
483 &self,
484 arguments: serde_json::Value,
485 _ctx: &aidaemon_core::ToolContext,
486 ) -> aidaemon_core::ToolResult {
487 $crate::outcome::run_as_core(self, arguments).await
488 }
489 }
490 };
491}
492pub(crate) use core_tool;
493
494#[cfg(test)]
495mod timeout_tests {
496 use super::*;
497
498 #[test]
499 fn a_timeout_is_known_by_its_type_through_context_not_its_words() {
500 let typed = anyhow::Error::new(ToolTimedOut("Command timed out after 5s".into()))
501 .context("search failed");
502 assert!(timed_out(&typed));
503 assert!(!timed_out(&anyhow::anyhow!("Command timed out after 5s")));
505 }
506}