1use std::collections::BTreeMap;
2use std::fmt;
3
4use serde_json::Value;
5
6pub const MAX_OPS: usize = 100;
8
9pub const RESERVED_ENVELOPE_ARGS: &[&str] = &["presentation", "presentation_per_op"];
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum ExecutionMode {
15 Single,
17 Parallel,
19 Chain,
21}
22
23#[derive(Debug, Clone, PartialEq)]
25pub enum ArgValue {
26 Value(Value),
28 PrevRef { path: String },
30 Array(Vec<ArgValue>),
32 Object(Vec<(String, ArgValue)>),
34}
35
36impl ArgValue {
37 pub fn as_value(&self) -> Option<&Value> {
39 match self {
40 ArgValue::Value(v) => Some(v),
41 ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
42 }
43 }
44
45 pub fn is_prev_ref(&self) -> bool {
47 matches!(self, ArgValue::PrevRef { .. })
48 }
49
50 pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
52 let ArgValue::PrevRef { path } = self else {
53 return None;
54 };
55 if path.is_empty() {
56 return Some(prev_result);
57 }
58 let mut cur = prev_result;
59 for segment in crate::parser::split_path(path) {
60 cur = crate::parser::apply_path_segment(cur, segment)?;
61 }
62 Some(cur)
63 }
64
65 pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
67 match self {
68 ArgValue::Value(v) => Some(v.clone()),
69 ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
70 ArgValue::Array(elements) => {
71 let mut out = Vec::with_capacity(elements.len());
72 for el in elements {
73 out.push(el.resolve_all(prev_result)?);
74 }
75 Some(Value::Array(out))
76 }
77 ArgValue::Object(pairs) => {
78 let mut map = serde_json::Map::with_capacity(pairs.len());
79 for (key, val) in pairs {
80 map.insert(key.clone(), val.resolve_all(prev_result)?);
81 }
82 Some(Value::Object(map))
83 }
84 }
85 }
86}
87
88#[derive(Debug, Clone, PartialEq)]
90pub struct ParsedOp {
91 pub tool: String,
92 pub args: BTreeMap<String, ArgValue>,
93}
94
95#[derive(Debug, Clone, PartialEq)]
97pub struct ParsedRequest {
98 pub ops: Vec<ParsedOp>,
99 pub mode: ExecutionMode,
100}
101
102#[derive(Debug, Clone, PartialEq)]
104pub enum DslError {
105 Empty,
106 TooManyOps {
107 count: usize,
108 max: usize,
109 },
110 UnexpectedChar {
111 pos: usize,
112 found: char,
113 expected: &'static str,
114 },
115 UnexpectedEof {
116 expected: &'static str,
117 },
118 InvalidIdentifier {
119 pos: usize,
120 },
121 DuplicateArg {
122 name: String,
123 },
124 InvalidValue {
125 pos: usize,
126 error: String,
127 },
128 InvalidJson {
129 error: String,
130 },
131 UnclosedString,
132 UnclosedBracket {
133 kind: char,
134 },
135 PrevRefOutsideChain {
142 pos: usize,
143 },
144 PrevRefInJsonForm {
150 arg_name: String,
151 },
152 MixedSeparators,
154 EmptyBatch,
156 UnsupportedVerbNesting {
159 pos: usize,
160 },
161 WriteKeyConflict {
169 id: String,
171 first_op: String,
173 second_op: String,
175 },
176 ReservedEnvelopeArg {
179 arg_name: String,
180 verb: String,
181 },
182}
183
184impl fmt::Display for DslError {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 match self {
187 DslError::Empty => write!(f, "request is empty"),
188 DslError::TooManyOps { count, max } => {
189 write!(f, "batch has {count} ops; max is {max}")
190 }
191 DslError::UnexpectedChar {
192 pos,
193 found,
194 expected,
195 } => {
196 write!(f, "at position {pos}: expected {expected}, found {found:?}")
197 }
198 DslError::UnexpectedEof { expected } => {
199 write!(f, "unexpected end of input; expected {expected}")
200 }
201 DslError::InvalidIdentifier { pos } => {
202 write!(
203 f,
204 "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
205 )
206 }
207 DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
208 DslError::InvalidValue { pos, error } => {
209 write!(f, "at position {pos}: invalid value: {error}")
210 }
211 DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
212 DslError::UnclosedString => write!(f, "unterminated string literal"),
213 DslError::UnclosedBracket { kind } => {
214 write!(f, "unclosed bracket: {kind:?} has no matching close")
215 }
216 DslError::PrevRefOutsideChain { pos } => {
217 write!(
218 f,
219 "at position {pos}: $prev reference is only valid in chain (|) mode; \
220 use function-call form with '|' to chain ops"
221 )
222 }
223 DslError::PrevRefInJsonForm { arg_name } => {
224 write!(
225 f,
226 "argument {arg_name:?}: $prev substitution requires the function-call DSL \
227 with the chain (|) operator; JSON form does not support chains. \
228 Use: verb1(...) | verb2({arg_name}=$prev.id)"
229 )
230 }
231 DslError::MixedSeparators => {
232 write!(
233 f,
234 "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
235 )
236 }
237 DslError::EmptyBatch => {
238 write!(f, "empty batch not allowed; provide at least one op")
239 }
240 DslError::UnsupportedVerbNesting { pos } => {
241 write!(
242 f,
243 "at position {pos}: only single-level dotted verb names are supported \
244 (e.g. brain.state); use a shorter name or register a pack alias"
245 )
246 }
247 DslError::WriteKeyConflict {
248 id,
249 first_op,
250 second_op,
251 } => {
252 write!(
253 f,
254 "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
255 {second_op:?} in the same batch; split into separate requests"
256 )
257 }
258 DslError::ReservedEnvelopeArg { arg_name, verb } => {
259 write!(
260 f,
261 "argument {arg_name:?} in verb {verb:?} is reserved for the request \
262 envelope; pass it at the envelope level, not inside verb args"
263 )
264 }
265 }
266 }
267}
268
269impl std::error::Error for DslError {}