use std::collections::BTreeMap;
use std::fmt;
use serde_json::Value;
pub const MAX_OPS: usize = 100;
pub const RESERVED_ENVELOPE_ARGS: &[&str] = &["presentation", "presentation_per_op"];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecutionMode {
Single,
Parallel,
Chain,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ArgValue {
Value(Value),
PrevRef { path: String },
Array(Vec<ArgValue>),
Object(Vec<(String, ArgValue)>),
}
impl ArgValue {
pub fn as_value(&self) -> Option<&Value> {
match self {
ArgValue::Value(v) => Some(v),
ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
}
}
pub fn is_prev_ref(&self) -> bool {
matches!(self, ArgValue::PrevRef { .. })
}
pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
let ArgValue::PrevRef { path } = self else {
return None;
};
if path.is_empty() {
return Some(prev_result);
}
let mut cur = prev_result;
for segment in crate::parser::split_path(path) {
cur = crate::parser::apply_path_segment(cur, segment)?;
}
Some(cur)
}
pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
match self {
ArgValue::Value(v) => Some(v.clone()),
ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
ArgValue::Array(elements) => {
let mut out = Vec::with_capacity(elements.len());
for el in elements {
out.push(el.resolve_all(prev_result)?);
}
Some(Value::Array(out))
}
ArgValue::Object(pairs) => {
let mut map = serde_json::Map::with_capacity(pairs.len());
for (key, val) in pairs {
map.insert(key.clone(), val.resolve_all(prev_result)?);
}
Some(Value::Object(map))
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedOp {
pub tool: String,
pub args: BTreeMap<String, ArgValue>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedRequest {
pub ops: Vec<ParsedOp>,
pub mode: ExecutionMode,
}
#[derive(Debug, Clone, PartialEq)]
pub enum DslError {
Empty,
TooManyOps {
count: usize,
max: usize,
},
UnexpectedChar {
pos: usize,
found: char,
expected: &'static str,
},
UnexpectedEof {
expected: &'static str,
},
InvalidIdentifier {
pos: usize,
},
DuplicateArg {
name: String,
},
InvalidValue {
pos: usize,
error: String,
},
InvalidJson {
error: String,
},
UnclosedString,
UnclosedBracket {
kind: char,
},
PrevRefOutsideChain {
pos: usize,
},
PrevRefInJsonForm {
arg_name: String,
},
MixedSeparators,
EmptyBatch,
UnsupportedVerbNesting {
pos: usize,
},
WriteKeyConflict {
id: String,
first_op: String,
second_op: String,
},
ReservedEnvelopeArg {
arg_name: String,
verb: String,
},
}
impl fmt::Display for DslError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DslError::Empty => write!(f, "request is empty"),
DslError::TooManyOps { count, max } => {
write!(f, "batch has {count} ops; max is {max}")
}
DslError::UnexpectedChar {
pos,
found,
expected,
} => {
write!(f, "at position {pos}: expected {expected}, found {found:?}")
}
DslError::UnexpectedEof { expected } => {
write!(f, "unexpected end of input; expected {expected}")
}
DslError::InvalidIdentifier { pos } => {
write!(
f,
"at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
)
}
DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
DslError::InvalidValue { pos, error } => {
write!(f, "at position {pos}: invalid value: {error}")
}
DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
DslError::UnclosedString => write!(f, "unterminated string literal"),
DslError::UnclosedBracket { kind } => {
write!(f, "unclosed bracket: {kind:?} has no matching close")
}
DslError::PrevRefOutsideChain { pos } => {
write!(
f,
"at position {pos}: $prev reference is only valid in chain (|) mode; \
use function-call form with '|' to chain ops"
)
}
DslError::PrevRefInJsonForm { arg_name } => {
write!(
f,
"argument {arg_name:?}: $prev substitution requires the function-call DSL \
with the chain (|) operator; JSON form does not support chains. \
Use: verb1(...) | verb2({arg_name}=$prev.id)"
)
}
DslError::MixedSeparators => {
write!(
f,
"cannot mix ',' (parallel) and '|' (chain) separators at the top level"
)
}
DslError::EmptyBatch => {
write!(f, "empty batch not allowed; provide at least one op")
}
DslError::UnsupportedVerbNesting { pos } => {
write!(
f,
"at position {pos}: only single-level dotted verb names are supported \
(e.g. brain.state); use a shorter name or register a pack alias"
)
}
DslError::WriteKeyConflict {
id,
first_op,
second_op,
} => {
write!(
f,
"write-key conflict: id {id:?} is targeted by both {first_op:?} and \
{second_op:?} in the same batch; split into separate requests"
)
}
DslError::ReservedEnvelopeArg { arg_name, verb } => {
write!(
f,
"argument {arg_name:?} in verb {verb:?} is reserved for the request \
envelope; pass it at the envelope level, not inside verb args"
)
}
}
}
}
impl std::error::Error for DslError {}