use core::fmt;
use core::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use oneharness_core::domain::report::RunReport;
use oneharness_core::io::run::RunRequest;
use oneharness_core::io::runner::ProcessSupervisor;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
HarnessIdentityEmpty,
TurnTimeoutZero,
EnvAssignmentMalformed {
text: String,
detail: &'static str,
},
ModelNameEmpty,
AssessmentSchemaInvalid {
path: String,
detail: String,
},
AgentCommandInvalid {
text: String,
detail: &'static str,
},
}
impl fmt::Display for ConfigError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::HarnessIdentityEmpty => {
write!(formatter, "the harness identity is empty")
}
Self::TurnTimeoutZero => {
write!(
formatter,
"a turn timeout of zero seconds is a turn that has expired before it starts"
)
}
Self::EnvAssignmentMalformed { text, detail } => {
write!(
formatter,
"`{text}` is not a KEY=VALUE environment assignment: {detail}"
)
}
Self::ModelNameEmpty => write!(formatter, "the model is named as nothing"),
Self::AssessmentSchemaInvalid { path, detail } => {
write!(formatter, "`{path}` does not constrain an answer: {detail}")
}
Self::AgentCommandInvalid { text, detail } => {
write!(
formatter,
"`{text}` cannot be allowed as an agent command: {detail}"
)
}
}
}
}
impl core::error::Error for ConfigError {}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HarnessIdentity(String);
impl HarnessIdentity {
pub fn new(name: &str) -> Result<Self, ConfigError> {
let trimmed = name.trim();
if trimmed.is_empty() {
return Err(ConfigError::HarnessIdentityEmpty);
}
Ok(Self(trimmed.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for HarnessIdentity {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AgentCommand(String);
const RULE_SYNTAX: [char; 4] = ['(', ')', '*', ':'];
impl AgentCommand {
pub fn new(text: &str) -> Result<Self, ConfigError> {
let trimmed = text.trim();
let refuse = |detail| ConfigError::AgentCommandInvalid {
text: text.to_owned(),
detail,
};
if trimmed.is_empty() {
return Err(refuse("it is empty"));
}
if trimmed.contains(['\n', '\r']) {
return Err(refuse("it spans more than one line"));
}
if trimmed.contains(RULE_SYNTAX) {
return Err(refuse(
"it carries `(`, `)`, `*` or `:`, which a permission rule interprets",
));
}
Ok(Self(trimmed.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for AgentCommand {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TurnTimeout(NonZeroU64);
impl TurnTimeout {
pub const DEFAULT: Self = Self(NonZeroU64::new(900).expect("900 is not zero"));
pub fn new(seconds: u64) -> Result<Self, ConfigError> {
NonZeroU64::new(seconds)
.map(Self)
.ok_or(ConfigError::TurnTimeoutZero)
}
#[must_use]
pub fn seconds(self) -> u64 {
self.0.get()
}
}
impl fmt::Display for TurnTimeout {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}s", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EnvAssignment {
name: String,
value: String,
}
impl EnvAssignment {
pub fn new(text: &str) -> Result<Self, ConfigError> {
let malformed = |detail| ConfigError::EnvAssignmentMalformed {
text: text.to_owned(),
detail,
};
let (name, value) = text
.split_once('=')
.ok_or_else(|| malformed("it carries no `=`"))?;
let mut characters = name.chars();
let first = characters
.next()
.ok_or_else(|| malformed("it names no variable before the `=`"))?;
if !(first.is_ascii_alphabetic() || first == '_')
|| !characters.all(|character| character.is_ascii_alphanumeric() || character == '_')
{
return Err(malformed(
"a variable name is a letter or an underscore followed by \
letters, digits and underscores",
));
}
Ok(Self {
name: name.to_owned(),
value: value.to_owned(),
})
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn value(&self) -> &str {
&self.value
}
}
impl fmt::Display for EnvAssignment {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}={}", self.name, self.value)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModelName(String);
impl ModelName {
pub fn new(name: &str) -> Result<Self, ConfigError> {
let trimmed = name.trim();
if trimmed.is_empty() {
return Err(ConfigError::ModelNameEmpty);
}
Ok(Self(trimmed.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for ModelName {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssessmentSchema(PathBuf);
const DIALECT_KEY: &str = "$schema";
impl AssessmentSchema {
#[must_use]
pub fn as_handed(mut schema: serde_json::Value) -> serde_json::Value {
if let Some(object) = schema.as_object_mut() {
object.remove(DIALECT_KEY);
object.remove("title");
object.remove("description");
if let Some(types) = object
.get_mut("$defs")
.and_then(|types| types.as_object_mut())
{
for declared in types
.values_mut()
.filter_map(|declared| declared.as_object_mut())
{
declared.remove("description");
}
}
}
schema
}
pub fn at(path: impl Into<PathBuf>) -> Result<Self, ConfigError> {
let path = path.into();
let invalid = |detail: String| ConfigError::AssessmentSchemaInvalid {
path: path.display().to_string(),
detail,
};
let text = std::fs::read_to_string(&path).map_err(|error| invalid(error.to_string()))?;
let document: serde_json::Value =
serde_json::from_str(&text).map_err(|error| invalid(error.to_string()))?;
match document.as_object() {
None => return Err(invalid("it is JSON, but not a schema document".to_owned())),
Some(declarations) if declarations.is_empty() => {
return Err(invalid("it is a schema that declares nothing".to_owned()));
}
Some(_) => {}
}
jsonschema::validator_for(&document).map_err(|error| invalid(error.to_string()))?;
Ok(Self(path))
}
#[must_use]
pub fn path(&self) -> &Path {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SupervisorConfig {
pub state_dir: PathBuf,
pub skill_path: PathBuf,
pub prompt_template_path: PathBuf,
pub assessment_schema: AssessmentSchema,
pub harness: HarnessIdentity,
pub model: Option<ModelName>,
pub working_dir: PathBuf,
pub turn_timeout: TurnTimeout,
pub harness_bin: Option<PathBuf>,
pub harness_env: Vec<EnvAssignment>,
pub agent_commands: Vec<AgentCommand>,
pub withheld_beside_an_image: Vec<AgentCommand>,
pub command_usage: Vec<String>,
pub auto_compact_tokens: Option<NonZeroU64>,
pub idle_compact_tokens: Option<NonZeroU64>,
}
pub trait RunRequestObserver: Send + Sync {
fn built(&self, request: &RunRequest);
}
pub trait RunReportObserver: Send + Sync {
fn answered(&self, report: &RunReport);
}
#[derive(Clone, Default)]
pub struct TurnSeam {
pub requests: Option<Arc<dyn RunRequestObserver>>,
pub processes: Option<Arc<dyn ProcessSupervisor + Send + Sync>>,
pub reports: Option<Arc<dyn RunReportObserver>>,
}
impl core::fmt::Debug for TurnSeam {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("TurnSeam")
.field("requests", &self.requests.is_some())
.field("processes", &self.processes.is_some())
.field("reports", &self.reports.is_some())
.finish()
}
}