use std::path::{Path, PathBuf};
pub use trusty_common::content::{ContentError, ContentSource, DevOverride, ResolvedContent};
use trusty_common::content::{ResolveOptions, default_cache_dir, resolve};
pub const AGENTS_CLASS: &str = "agents";
pub const FOUNDATION_FILE: &str = "BASE-AGENT.md";
pub const REMEDY: &str = "run `tm content update`, or install by hand: `gh release download \
<tag> --repo bobmatnyc/trusty-tools`, then `tm content install --from <dir>/<tag>.tar.gz`";
const DEV_ORIGIN: &str = "dev checkout ";
fn source_remedy(origin: &str) -> String {
match origin.strip_prefix(DEV_ORIGIN) {
Some(root) => format!(
"the trusty-tools checkout at {root} serves its working tree, not the installed \
release: run `git pull` in {root}, or run tm from outside that checkout"
),
None => "run `tm content update`".to_owned(),
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AgentContentError {
#[error("no instructional content is installed ({source}); {remedy}", remedy = REMEDY)]
NotInstalled {
#[source]
source: ContentError,
},
#[error("cannot locate the content cache (no home directory); {remedy}", remedy = REMEDY)]
NoCacheDir,
#[error(
"no instructional content is installed, and fetching the content release \
failed: {reason}; {remedy}",
remedy = REMEDY
)]
FetchFailed {
reason: String,
},
#[error("instructional content could not be loaded: {source}")]
Content {
#[source]
source: ContentError,
},
#[error("the content from {origin} holds no agents; {}", source_remedy(.origin))]
EmptyRoster {
origin: String,
},
#[error("the content from {origin} has no `{path}`; {}", source_remedy(.origin))]
Missing {
origin: String,
path: String,
},
#[error(
"the content from {origin} has an unusable `{path}` ({reason}); {}, or upgrade tm \
if that content is newer than this binary",
source_remedy(.origin)
)]
Invalid {
origin: String,
path: String,
reason: String,
},
#[error(
"the pinned content {tag} is older than {minimum}, the oldest content release \
this binary reads; {remedy}"
)]
BelowMinimum {
tag: String,
minimum: String,
remedy: String,
},
#[error("could not write {}: {source}", path.display())]
Write {
path: PathBuf,
#[source]
source: std::io::Error,
},
}
impl From<ContentError> for AgentContentError {
fn from(source: ContentError) -> Self {
match source {
ContentError::NotInstalled { .. } => Self::NotInstalled { source },
other => Self::Content { source: other },
}
}
}
impl AgentContentError {
pub fn is_not_installed(&self) -> bool {
matches!(
self,
Self::NotInstalled { .. } | Self::NoCacheDir | Self::FetchFailed { .. }
)
}
}
static NOT_INSTALLED_REPORTED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
pub fn report_not_installed(err: &AgentContentError, what: &str) -> bool {
if !err.is_not_installed() {
return false;
}
if NOT_INSTALLED_REPORTED.swap(true, std::sync::atomic::Ordering::Relaxed) {
tracing::debug!("{what}: {err}");
} else {
tracing::error!("{what}: {err}");
}
true
}
pub fn mark_not_installed_reported() {
NOT_INSTALLED_REPORTED.store(true, std::sync::atomic::Ordering::Relaxed);
}
pub fn describe_source(source: &ContentSource) -> String {
match source {
ContentSource::DevCheckout { root } => format!("{DEV_ORIGIN}{}", root.display()),
ContentSource::Installed { tag, .. } => tag.clone(),
other => format!("{other:?}"),
}
}
pub fn resolve_content(dev: DevOverride) -> Result<ResolvedContent, AgentContentError> {
let cache = default_cache_dir().ok_or(AgentContentError::NoCacheDir)?;
resolve_content_in(&cache, dev)
}
pub fn resolve_content_in(
cache_dir: &Path,
dev: DevOverride,
) -> Result<ResolvedContent, AgentContentError> {
Ok(resolve(&ResolveOptions::new(cache_dir, dev))?)
}
pub fn checkout_content(root: &Path) -> Result<ResolvedContent, AgentContentError> {
resolve_content_in(root, DevOverride::At(root.to_path_buf()))
}
#[derive(Debug, Clone)]
pub struct AgentRoster {
source: ContentSource,
files: Vec<(String, String)>,
}
impl AgentRoster {
pub fn load(content: &ResolvedContent) -> Result<Self, AgentContentError> {
let prefix = format!("{AGENTS_CLASS}/");
let mut files = Vec::new();
for key in content.list(AGENTS_CLASS)? {
let Some(name) = key.strip_prefix(&prefix) else {
continue;
};
if name.contains('/') || !name.ends_with(".md") {
continue;
}
files.push((name.to_string(), content.read_to_string(&key)?));
}
let origin = describe_source(content.source());
if files.is_empty() {
return Err(AgentContentError::EmptyRoster { origin });
}
if !files.iter().any(|(name, _)| name == FOUNDATION_FILE) {
return Err(AgentContentError::Missing {
origin,
path: format!("{prefix}{FOUNDATION_FILE}"),
});
}
files.sort_by(|(a, _), (b, _)| {
(!a.starts_with("BASE-"), a.as_str()).cmp(&(!b.starts_with("BASE-"), b.as_str()))
});
Ok(Self {
source: content.source().clone(),
files,
})
}
pub fn source(&self) -> &ContentSource {
&self.source
}
pub fn origin(&self) -> String {
describe_source(&self.source)
}
pub fn get(&self, file_name: &str) -> Option<&str> {
self.files
.iter()
.find(|(name, _)| name == file_name)
.map(|(_, body)| body.as_str())
}
pub fn require(&self, file_name: &str) -> Result<&str, AgentContentError> {
self.get(file_name)
.ok_or_else(|| AgentContentError::Missing {
origin: self.origin(),
path: format!("{AGENTS_CLASS}/{file_name}"),
})
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ {
self.files
.iter()
.map(|(name, body)| (name.as_str(), body.as_str()))
}
pub fn len(&self) -> usize {
self.files.len()
}
pub fn is_empty(&self) -> bool {
self.files.is_empty()
}
pub fn materialize(&self, dir: &Path) -> Result<Vec<String>, AgentContentError> {
std::fs::create_dir_all(dir).map_err(|source| AgentContentError::Write {
path: dir.to_path_buf(),
source,
})?;
let mut written = Vec::with_capacity(self.files.len());
for (name, body) in &self.files {
let path = dir.join(name);
trusty_common::atomic_file::write_atomic(&path, body.as_bytes())
.map_err(|source| AgentContentError::Write { path, source })?;
written.push(name.clone());
}
Ok(written)
}
}
#[cfg(test)]
#[path = "agent_content_tests.rs"]
pub(crate) mod tests;