use std::cmp::Ordering;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler};
use async_trait::async_trait;
use awp_types::CapabilityV2;
use serde_json::Value;
use super::Pack;
use super::builtin::is_builtin_test_key;
use super::bundle::{HandlerConfig, PackBundle, PackError, VerifiedPack};
use super::trust::{TrustList, TrustedKey};
use crate::kinds::KindTemplate;
use crate::team::AgentRole;
pub const BUNDLE_EXTENSION: &str = ".pack.json";
fn io(path: &Path, error: impl std::fmt::Display) -> PackError {
PackError::Io(format!("{}: {error}", path.display()))
}
pub(crate) fn write_atomically(path: &Path, bytes: &[u8]) -> Result<(), PackError> {
let parent = path.parent().unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent).map_err(|error| io(parent, error))?;
let name = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
let temporary = parent.join(format!(".{name}.tmp"));
std::fs::write(&temporary, bytes).map_err(|error| io(&temporary, error))?;
std::fs::rename(&temporary, path).map_err(|error| io(path, error))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PackOrigin {
BuiltIn,
Installed {
file: PathBuf,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct LoadedPack {
pub pack: VerifiedPack,
pub origin: PackOrigin,
}
impl LoadedPack {
pub fn name(&self) -> &str {
&self.pack.bundle.name
}
pub fn bundle(&self) -> &PackBundle {
&self.pack.bundle
}
pub fn is_builtin_name(&self) -> bool {
Pack::ALL.iter().any(|pack| pack.as_str() == self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
New,
Upgrade {
from: String,
},
Unchanged,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefusedPack {
pub file: PathBuf,
pub error: PackError,
}
#[derive(Debug, Clone, Default)]
pub struct PackSet {
packs: Vec<Arc<LoadedPack>>,
refused: Vec<RefusedPack>,
}
impl PackSet {
pub fn builtin() -> Result<Self, PackError> {
static BUILTIN: OnceLock<Result<PackSet, PackError>> = OnceLock::new();
BUILTIN
.get_or_init(|| {
let mut set = Self::default();
for pack in Pack::ALL {
set.packs.push(Arc::new(LoadedPack {
pack: pack.bundle()?,
origin: PackOrigin::BuiltIn,
}));
}
Ok(set)
})
.clone()
}
pub fn packs(&self) -> &[Arc<LoadedPack>] {
&self.packs
}
pub fn get(&self, name: &str) -> Option<&LoadedPack> {
self.packs.iter().find(|pack| pack.name() == name).map(AsRef::as_ref)
}
pub fn refused(&self) -> &[RefusedPack] {
&self.refused
}
pub fn admit(&self, candidate: &VerifiedPack) -> Result<Admission, PackError> {
let bundle = &candidate.bundle;
let mut admission = Admission::New;
if let Some(held) = self.get(&bundle.name) {
if held.bundle().publisher.id != bundle.publisher.id {
return Err(PackError::Conflict(format!(
"pack `{}` is published by `{}`, and a pack of `{}` cannot take its name",
bundle.name,
held.bundle().publisher.id,
bundle.publisher.id
)));
}
admission = match candidate.version().cmp(&held.pack.version()) {
Ordering::Less => {
return Err(PackError::Downgrade {
name: bundle.name.clone(),
installed: held.bundle().version.clone(),
offered: bundle.version.clone(),
});
}
Ordering::Equal if held.pack.digest == candidate.digest => Admission::Unchanged,
Ordering::Equal => {
return Err(PackError::Republished {
name: bundle.name.clone(),
version: bundle.version.clone(),
});
}
Ordering::Greater => Admission::Upgrade { from: held.bundle().version.clone() },
};
}
for other in self.packs.iter().filter(|pack| pack.name() != bundle.name) {
let held = other.bundle();
let taken = |what: &str, name: &str| {
Err(PackError::Conflict(format!(
"{what} `{name}` belongs to pack `{}`",
other.name()
)))
};
if let Some(capability) = bundle
.capabilities
.iter()
.find(|c| held.capabilities.iter().any(|h| h.name == c.name))
{
return taken("capability", &capability.name);
}
if let Some(playbook) =
bundle.playbooks.iter().find(|p| held.playbooks.iter().any(|h| h.id == p.id))
{
return taken("playbook", &playbook.id);
}
if let Some(driver) =
bundle.drivers.iter().find(|d| held.drivers.iter().any(|h| h.id == d.id))
{
return taken("driver", &driver.id);
}
}
Ok(admission)
}
pub fn with(mut self, pack: LoadedPack) -> Result<(Self, Admission), PackError> {
let admission = self.admit(&pack.pack)?;
match self.packs.iter().position(|held| held.name() == pack.name()) {
Some(index) => self.packs[index] = Arc::new(pack),
None => self.packs.push(Arc::new(pack)),
}
Ok((self, admission))
}
pub fn declaration(&self, name: &str) -> Option<(CapabilityV2, HandlerConfig)> {
self.packs.iter().find_map(|pack| {
let bundle = pack.bundle();
let declaration = bundle.capabilities.iter().find(|c| c.name == name)?;
Some((declaration.clone(), *bundle.handlers.get(name)?))
})
}
pub fn served(&self, template: &KindTemplate) -> Vec<(CapabilityV2, HandlerConfig)> {
let mut names = BTreeSet::new();
let mut served = Vec::new();
for name in &template.capabilities {
match self.declaration(name) {
Some(found) => {
names.insert(name.to_string());
served.push(found);
}
None => tracing::warn!(
capability = name,
"no loaded pack declares this capability; it is not served"
),
}
}
for pack in self.packs.iter().filter(|pack| !pack.is_builtin_name()) {
let bundle = pack.bundle();
for declaration in &bundle.capabilities {
if let Some(handler) = bundle.handlers.get(&declaration.name)
&& names.insert(declaration.name.clone())
{
served.push((declaration.clone(), *handler));
}
}
}
served
}
pub async fn install_playbooks(&self, root: &Path) -> adk_core::Result<Vec<PathBuf>> {
let failed = |path: &Path, error: std::io::Error| {
adk_core::AdkError::config(format!("{}: {error}", path.display()))
};
let mut written = Vec::new();
for role in AgentRole::ALL {
let dir = root.join(role.as_str()).join(".skills").join("packs");
match tokio::fs::remove_dir_all(&dir).await {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(failed(&dir, error)),
}
for pack in &self.packs {
for playbook in pack.bundle().playbooks.iter().filter(|p| p.agents.contains(&role))
{
let folder = dir.join(pack.name());
tokio::fs::create_dir_all(&folder).await.map_err(|e| failed(&folder, e))?;
let path = folder.join(format!("{}.md", playbook.id));
tokio::fs::write(&path, &playbook.text).await.map_err(|e| failed(&path, e))?;
written.push(path);
}
}
}
Ok(written)
}
}
pub struct Dispatched {
capability: &'static str,
inner: Arc<dyn CapabilityHandler>,
}
impl Dispatched {
pub fn new(capability: &'static str, inner: Arc<dyn CapabilityHandler>) -> Self {
Self { capability, inner }
}
}
#[async_trait]
impl CapabilityHandler for Dispatched {
async fn handle(&self, mut call: CapabilityCall) -> Result<Value, CapabilityError> {
call.capability = self.capability.to_string();
self.inner.handle(call).await
}
fn call_amount(&self, input: &Value) -> Option<u64> {
self.inner.call_amount(input)
}
async fn amount(&self, input: &Value) -> Option<u64> {
self.inner.amount(input).await
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Installation {
pub pack: VerifiedPack,
pub admission: Admission,
pub drivers: Vec<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackDir {
dir: PathBuf,
}
impl PackDir {
pub fn new(project: impl AsRef<Path>) -> Self {
Self { dir: project.as_ref().join("packs") }
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn trust_file(&self) -> PathBuf {
self.dir.join("trust.json")
}
pub fn bundle_file(&self, name: &str) -> PathBuf {
self.dir.join(format!("{name}{BUNDLE_EXTENSION}"))
}
pub fn drivers_dir(&self, name: &str) -> PathBuf {
self.dir.join("drivers").join(name)
}
pub fn trust(&self) -> Result<TrustList, PackError> {
TrustList::read(&self.trust_file())
}
pub fn trust_key(&self, key: TrustedKey) -> Result<bool, PackError> {
if is_builtin_test_key(&key.public_key) {
return Err(PackError::Invalid(
"that is the built-in packs' test key, whose seed is public in adk-website's \
source; anyone can sign with it, so no site trusts it"
.into(),
));
}
if !super::bundle::is_valid_publisher_id(&key.publisher) || key.kid.trim().is_empty() {
return Err(PackError::Invalid(format!(
"publisher `{}` with key id `{}`: a publisher id is lowercase letters, digits, \
`.` and `-`, and a key needs an id",
key.publisher, key.kid
)));
}
adk_awp::signing::jws::public_key_bytes(&key.public_key).map_err(|error| {
PackError::Invalid(format!("the key is not an Ed25519 public key: {error}"))
})?;
let mut trust = self.trust()?;
let added = trust.add(key);
if added {
trust.write(&self.trust_file())?;
}
Ok(added)
}
pub fn load(&self) -> Result<PackSet, PackError> {
let mut set = PackSet::builtin()?;
let files = self.bundle_files()?;
if files.is_empty() {
return Ok(set);
}
let trust = match self.trust() {
Ok(trust) => trust,
Err(error) => {
set.refused.extend(
files.into_iter().map(|file| RefusedPack { file, error: error.clone() }),
);
return Ok(set);
}
};
for file in files {
match self.load_file(&file, &trust) {
Ok(pack) => {
let pack =
LoadedPack { pack, origin: PackOrigin::Installed { file: file.clone() } };
match set.clone().with(pack) {
Ok((next, _)) => set = next,
Err(error) => set.refused.push(RefusedPack { file, error }),
}
}
Err(error) => set.refused.push(RefusedPack { file, error }),
}
}
for refused in &set.refused {
tracing::error!(
file = %refused.file.display(),
error = %refused.error,
"an installed capability pack is not loaded"
);
}
Ok(set)
}
fn bundle_files(&self) -> Result<Vec<PathBuf>, PackError> {
let entries = match std::fs::read_dir(&self.dir) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(io(&self.dir, error)),
};
let mut files = Vec::new();
for entry in entries {
let path = entry.map_err(|error| io(&self.dir, error))?.path();
let name =
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
if path.is_file() && !name.starts_with('.') && name.ends_with(BUNDLE_EXTENSION) {
files.push(path);
}
}
files.sort();
Ok(files)
}
fn load_file(&self, file: &Path, trust: &TrustList) -> Result<VerifiedPack, PackError> {
let bytes = std::fs::read(file).map_err(|error| io(file, error))?;
let pack = PackBundle::verify(&bytes, trust)?;
if *file != self.bundle_file(&pack.bundle.name) {
return Err(PackError::Invalid(format!(
"{} holds pack `{}`; an installed pack's file is named after it",
file.display(),
pack.bundle.name
)));
}
Ok(pack)
}
pub fn plan(&self, bytes: &[u8]) -> Result<Installation, PackError> {
let pack = PackBundle::verify(bytes, &self.trust()?)?;
let admission = self.load()?.admit(&pack)?;
let drivers = pack
.bundle
.drivers
.iter()
.map(|driver| self.drivers_dir(&pack.bundle.name).join(format!("{}.toml", driver.id)))
.collect();
Ok(Installation { pack, admission, drivers })
}
pub fn install(&self, bytes: &[u8]) -> Result<Installation, PackError> {
let installation = self.plan(bytes)?;
if installation.admission == Admission::Unchanged {
return Ok(installation);
}
let name = &installation.pack.bundle.name;
let drivers = self.drivers_dir(name);
match std::fs::remove_dir_all(&drivers) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(io(&drivers, error)),
}
for (driver, file) in installation.pack.bundle.drivers.iter().zip(&installation.drivers) {
write_atomically(file, driver.manifest.as_bytes())?;
}
write_atomically(&self.bundle_file(name), bytes)?;
tracing::info!(
pack = %name,
version = %installation.pack.bundle.version,
publisher = %installation.pack.bundle.publisher.id,
digest = %installation.pack.digest,
"capability pack installed"
);
Ok(installation)
}
pub fn remove(&self, name: &str) -> Result<(), PackError> {
let file = self.bundle_file(name);
if !super::bundle::is_valid_pack_name(name) || !file.is_file() {
if Pack::ALL.iter().any(|pack| pack.as_str() == name) {
return Err(PackError::BuiltIn(name.to_string()));
}
return Err(PackError::NotInstalled(name.to_string()));
}
std::fs::remove_file(&file).map_err(|error| io(&file, error))?;
let drivers = self.drivers_dir(name);
match std::fs::remove_dir_all(&drivers) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(io(&drivers, error)),
}
tracing::info!(pack = %name, "capability pack removed");
Ok(())
}
}