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 let raw = arguments.to_string();
187 let outcome = match tool.execute(&raw, &ToolCallContext::default()).await {
188 Ok(outcome) => outcome,
189 Err(error) => return Ok(ToolOutput::error(error.to_string())),
190 };
191 let mut output = if outcome.metadata.contract_rejected {
192 ToolOutput::error(outcome.output)
193 } else {
194 ToolOutput::text(outcome.output)
195 };
196 if let Some(read) = &outcome.metadata.read_file {
197 output = output.with_details(json!({
198 "path": read.display_path,
199 "start_line": read.returned_start_line,
200 "end_line": read.returned_end_line,
201 "total_lines": read.total_lines,
202 "truncated": read.truncated,
203 }));
204 }
205 output.finish = outcome.finish;
206 Ok(output)
207}
208
209#[async_trait]
213pub trait OutcomeRunner: Send + Sync {
214 async fn run(&self, tool: &str, arguments: Value, ctx: &ToolContext) -> ToolResult;
215}
216
217pub type CallValidator = Arc<dyn Fn(&Value) -> Result<(), String> + Send + Sync>;
219
220pub struct KernelAdapter<T: ?Sized> {
224 tool: Arc<T>,
225 spec: ToolSpec,
226 trust_roots: Arc<Vec<String>>,
227 owned: crate::semantics::OwnedFolders,
228 validator: Option<CallValidator>,
229 timeout: Option<Duration>,
230 runner: Option<Arc<dyn OutcomeRunner>>,
231}
232
233impl<T: OutcomeTool + ?Sized> KernelAdapter<T> {
234 pub fn new(tool: Arc<T>) -> Self {
235 let spec = spec_of(tool.as_ref());
236 Self {
237 tool,
238 spec,
239 trust_roots: Arc::new(Vec::new()),
240 owned: Default::default(),
241 validator: None,
242 timeout: None,
243 runner: None,
244 }
245 }
246
247 pub fn with_spec(mut self, spec: ToolSpec) -> Self {
249 self.spec = spec;
250 self
251 }
252
253 pub fn with_trust_roots(mut self, roots: Arc<Vec<String>>) -> Self {
255 self.trust_roots = roots;
256 self
257 }
258
259 pub fn with_owned_folders(mut self, owned: crate::semantics::OwnedFolders) -> Self {
263 self.owned = owned;
264 self
265 }
266
267 pub fn with_validator(mut self, validator: CallValidator) -> Self {
269 self.validator = Some(validator);
270 self
271 }
272
273 pub fn with_timeout(mut self, timeout: Duration) -> Self {
274 self.timeout = Some(timeout);
275 self
276 }
277
278 pub fn with_runner(mut self, runner: Arc<dyn OutcomeRunner>) -> Self {
280 self.runner = Some(runner);
281 self
282 }
283
284 fn canonical(&self, arguments: &Value) -> String {
285 let raw = arguments.to_string();
286 self.tool.canonicalize_arguments(&raw).unwrap_or(raw)
287 }
288}
289
290pub const MAX_CONCURRENT_CHILDREN: usize = 3;
292
293#[async_trait]
294impl<T: OutcomeTool + ?Sized + 'static> aidaemon_core::Tool for KernelAdapter<T> {
295 fn spec(&self) -> ToolSpec {
296 self.spec.clone()
297 }
298
299 fn annotations(&self) -> ToolAnnotations {
302 if self.tool.capabilities().read_only {
303 ToolAnnotations::READ_ONLY
304 } else {
305 ToolAnnotations {
306 read_only: false,
307 destructive: true,
308 idempotent: false,
309 egress: true,
310 }
311 }
312 }
313
314 fn concurrent_peers(&self) -> usize {
318 if self.tool.dispatch_facts().spawns_child_agents {
319 MAX_CONCURRENT_CHILDREN
320 } else {
321 0
322 }
323 }
324
325 fn annotations_for(&self, arguments: &Value) -> ToolAnnotations {
328 let owned = self.owned.list();
329 self.tool.call_annotations_in(
330 &arguments.to_string(),
331 &TrustRoots::new(&self.trust_roots).with_owned(&owned),
332 )
333 }
334
335 fn outbound(&self, arguments: &Value) -> Outbound {
336 self.tool.call_outbound(&arguments.to_string())
337 }
338
339 fn effects(&self, arguments: &Value) -> CallEffects {
342 self.tool.call_effects(&self.canonical(arguments))
343 }
344
345 fn access(&self, arguments: &Value) -> AccessManifest {
349 let mut manifest = AccessManifest::default();
350 let facts = self.tool.dispatch_facts();
351 if facts.shell_command_line {
352 for field in ["command", "script"] {
353 if let Some(text) = arguments
354 .get(field)
355 .and_then(Value::as_str)
356 .filter(|text| !text.trim().is_empty())
357 {
358 manifest.commands.push(text.to_string());
359 }
360 }
361 }
362 for key in self.effects(arguments).keys {
363 let list = match key.class {
364 EffectClass::Egress => &mut manifest.hosts,
365 EffectClass::Write | EffectClass::Delete | EffectClass::Configuration => {
366 &mut manifest.writes
367 }
368 _ => continue,
369 };
370 if !list.contains(&key.target) {
371 list.push(key.target);
372 }
373 }
374 if facts.file_guard != FileGuard::None {
376 let (reads, writes) = self.tool.guarded_paths(&self.canonical(arguments));
377 manifest.reads.extend(reads);
378 for write in writes {
379 if !manifest.writes.contains(&write) {
380 manifest.writes.push(write);
381 }
382 }
383 }
384 manifest
385 }
386
387 fn source_trust(&self, _arguments: &Value) -> SourceTrust {
389 SourceTrust::Untrusted
390 }
391
392 fn validate(&self, arguments: &Value) -> Result<(), String> {
393 match &self.validator {
394 Some(validator) => validator(arguments),
395 None => validate_for_core(self.tool.as_ref(), arguments),
396 }
397 }
398
399 fn timeout(&self) -> Option<Duration> {
400 self.timeout
401 }
402
403 async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
404 match &self.runner {
405 Some(runner) => runner.run(&self.spec.name, arguments, ctx).await,
406 None => run_as_core(self.tool.as_ref(), arguments).await,
407 }
408 }
409}
410
411macro_rules! core_tool {
413 ($ty:ty, annotations: $annotations:expr, access: |$this:ident, $args:ident| $access:expr) => {
414 #[async_trait::async_trait]
415 impl aidaemon_core::Tool for $ty {
416 fn spec(&self) -> aidaemon_core::ToolSpec {
417 $crate::outcome::spec_of(self)
418 }
419
420 fn annotations(&self) -> aidaemon_core::ToolAnnotations {
421 $annotations
422 }
423
424 fn validate(&self, arguments: &serde_json::Value) -> Result<(), String> {
425 $crate::outcome::validate_for_core(self, arguments)
426 }
427
428 fn access(&self, $args: &serde_json::Value) -> aidaemon_core::AccessManifest {
429 let $this = self;
430 $access
431 }
432
433 async fn call(
434 &self,
435 arguments: serde_json::Value,
436 _ctx: &aidaemon_core::ToolContext,
437 ) -> aidaemon_core::ToolResult {
438 $crate::outcome::run_as_core(self, arguments).await
439 }
440 }
441 };
442}
443pub(crate) use core_tool;
444
445#[cfg(test)]
446mod timeout_tests {
447 use super::*;
448
449 #[test]
450 fn a_timeout_is_known_by_its_type_through_context_not_its_words() {
451 let typed = anyhow::Error::new(ToolTimedOut("Command timed out after 5s".into()))
452 .context("search failed");
453 assert!(timed_out(&typed));
454 assert!(!timed_out(&anyhow::anyhow!("Command timed out after 5s")));
456 }
457}