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