use async_trait::async_trait;
use tokio::sync::mpsc;
use serde_json::Value;
use crate::OutcomeTool;
use crate::semantics::{ApprovalResponse, ToolCallContext, ToolCallOutcome};
use crate::status::{StatusUpdate, with_status};
#[async_trait]
pub trait ToolCalls: OutcomeTool {
async fn call(&self, arguments: &str) -> anyhow::Result<String> {
Ok(self
.execute(arguments, &ToolCallContext::default())
.await?
.output)
}
async fn call_with_status_outcome(
&self,
arguments: &str,
status_tx: Option<mpsc::Sender<StatusUpdate>>,
) -> anyhow::Result<ToolCallOutcome> {
self.execute(
arguments,
&with_status(ToolCallContext::default(), status_tx),
)
.await
}
async fn call_with_execution_context(
&self,
arguments: &str,
status_tx: Option<mpsc::Sender<StatusUpdate>>,
facts: ToolCallContext,
) -> anyhow::Result<ToolCallOutcome> {
self.execute(arguments, &with_status(facts, status_tx))
.await
}
}
impl<T: OutcomeTool + ?Sized> ToolCalls for T {}
pub fn call_facts(session_id: &str) -> ToolCallContext {
ToolCallContext {
session_id: session_id.to_string(),
..Default::default()
}
}
pub async fn call_with_facts<T: OutcomeTool + ?Sized>(
tool: &T,
arguments: &str,
facts: ToolCallContext,
) -> anyhow::Result<String> {
tool.call_with_execution_context(arguments, None, facts)
.await
.map(|outcome| outcome.output)
}
pub struct KernelCall {
pub output: String,
pub asked: Option<aidaemon_core::OwnerApprovalRequest>,
pub offer: Option<crate::semantics::GrantOffer>,
}
pub async fn call_through_kernel<T: OutcomeTool + ?Sized>(
tool: &T,
arguments: &str,
facts: ToolCallContext,
answer: Option<ApprovalResponse>,
) -> anyhow::Result<KernelCall> {
let parsed: Value = serde_json::from_str(arguments).unwrap_or(Value::Null);
let call = crate::semantics::ApprovalCall::as_sent(&parsed);
let asked = match tool.owner_approval_request(&call, &facts).await {
crate::semantics::OwnerApprovalNeed::Ask(request) => Some(request),
_ => None,
};
let offer = match asked {
Some(_) => tool.approval_grant(&call, &facts).await,
None => None,
};
if asked.is_some() {
let answer = match (&offer, answer) {
(Some(offer), Some(answer)) => Some(answer.capped_to(offer)),
(_, answer) => answer,
};
tool.record_owner_answer(&call, &facts, answer.clone())
.await;
match answer {
Some(ApprovalResponse::Deny) => {
return Ok(KernelCall {
output: "Error: Denied by user.".to_string(),
asked,
offer,
});
}
None => {
return Ok(KernelCall {
output: "Error: no answer from the owner. Action denied.".to_string(),
asked,
offer,
});
}
Some(_) => {}
}
}
let output = call_with_facts(tool, arguments, facts).await?;
Ok(KernelCall {
output,
asked,
offer,
})
}
#[async_trait]
pub trait CallWithFacts {
async fn call_with(&self, arguments: &str, facts: ToolCallContext) -> anyhow::Result<String>;
}
#[async_trait]
impl<T: OutcomeTool + ?Sized> CallWithFacts for T {
async fn call_with(&self, arguments: &str, facts: ToolCallContext) -> anyhow::Result<String> {
call_with_facts(self, arguments, facts).await
}
}
pub fn active_execution_backend() -> crate::backend::SharedExecutionBackend {
static BACKEND: std::sync::OnceLock<crate::backend::SharedExecutionBackend> =
std::sync::OnceLock::new();
BACKEND
.get_or_init(|| {
std::sync::Arc::new(crate::local_backend::LocalBackend::current_unrestricted())
})
.clone()
}
static DELETE_AT_EXIT: std::sync::Mutex<Vec<std::path::PathBuf>> =
std::sync::Mutex::new(Vec::new());
static DELETE_AT_EXIT_REGISTERED: std::sync::Once = std::sync::Once::new();
unsafe extern "C" {
fn atexit(callback: extern "C" fn()) -> std::ffi::c_int;
}
extern "C" fn delete_registered_files() {
let Ok(mut paths) = DELETE_AT_EXIT.try_lock() else {
return;
};
for path in paths.drain(..) {
let _ = std::fs::remove_file(&path);
for suffix in ["-wal", "-shm", "-journal"] {
let mut sidecar = path.clone().into_os_string();
sidecar.push(suffix);
let _ = std::fs::remove_file(sidecar);
}
}
}
pub fn delete_at_exit(path: impl Into<std::path::PathBuf>) -> std::path::PathBuf {
let path = path.into();
DELETE_AT_EXIT_REGISTERED.call_once(|| {
unsafe {
atexit(delete_registered_files);
}
});
DELETE_AT_EXIT
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.push(path.clone());
path
}