1use std::collections::BTreeMap;
2use std::fmt;
3
4use serde_json::Value;
5
6pub const MAX_OPS: usize = 100;
8
9pub const MAX_OPS_INPUT_LEN: usize = 1024 * 1024;
13
14pub const NESTING_DEPTH_LIMIT: usize = 64;
18
19pub use khive_types::RESERVED_ENVELOPE_ARGS;
21
22pub fn value_nesting_within_limit(value: &Value, max_depth: usize) -> bool {
28 let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
29 while let Some((v, depth)) = stack.pop() {
30 match v {
31 Value::Array(items) => {
32 let next_depth = depth + 1;
33 if next_depth > max_depth {
34 return false;
35 }
36 stack.extend(items.iter().map(|item| (item, next_depth)));
37 }
38 Value::Object(map) => {
39 let next_depth = depth + 1;
40 if next_depth > max_depth {
41 return false;
42 }
43 stack.extend(map.values().map(|item| (item, next_depth)));
44 }
45 _ => {}
46 }
47 }
48 true
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum ExecutionMode {
54 Single,
56 Parallel,
58 Chain,
60}
61
62#[derive(Debug, Clone, PartialEq)]
66pub enum ArgValue {
67 Value(Value),
69 PrevRef { path: String },
71 Array(Vec<ArgValue>),
73 Object(Vec<(String, ArgValue)>),
75}
76
77impl ArgValue {
78 pub fn as_value(&self) -> Option<&Value> {
80 match self {
81 ArgValue::Value(v) => Some(v),
82 ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
83 }
84 }
85
86 pub fn is_prev_ref(&self) -> bool {
88 matches!(self, ArgValue::PrevRef { .. })
89 }
90
91 pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
96 let ArgValue::PrevRef { path } = self else {
97 return None;
98 };
99 if path.is_empty() {
100 return Some(prev_result);
101 }
102 let mut cur = prev_result;
103 for segment in crate::parser::split_path(path) {
104 cur = crate::parser::apply_path_segment(cur, segment)?;
105 }
106 Some(cur)
107 }
108
109 pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
111 match self {
112 ArgValue::Value(v) => Some(v.clone()),
113 ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
114 ArgValue::Array(elements) => {
115 let mut out = Vec::with_capacity(elements.len());
116 for el in elements {
117 out.push(el.resolve_all(prev_result)?);
118 }
119 Some(Value::Array(out))
120 }
121 ArgValue::Object(pairs) => {
122 let mut map = serde_json::Map::with_capacity(pairs.len());
123 for (key, val) in pairs {
124 map.insert(key.clone(), val.resolve_all(prev_result)?);
125 }
126 Some(Value::Object(map))
127 }
128 }
129 }
130
131 pub fn find_prev_failure(&self, prev_result: &Value) -> Option<PrevFailure> {
140 self.find_prev_failure_at("", prev_result)
141 }
142
143 fn find_prev_failure_at(&self, arg_path: &str, prev_result: &Value) -> Option<PrevFailure> {
144 match self {
145 ArgValue::Value(_) => None,
146 ArgValue::PrevRef { path } => {
147 if path.is_empty() {
151 return None;
152 }
153 let mut cur = prev_result;
154 let mut resolved_prefix = String::new();
155 for seg in crate::parser::split_path(path) {
156 match seg {
157 crate::parser::PathSegment::Field(key) => match cur {
158 Value::Object(map) => match map.get(key) {
159 Some(v) => {
160 cur = v;
161 if !resolved_prefix.is_empty() {
162 resolved_prefix.push('.');
163 }
164 resolved_prefix.push_str(key);
165 }
166 None => {
167 let mut available: Vec<String> = map.keys().cloned().collect();
168 available.sort_unstable();
169 return Some(PrevFailure::NotFound {
170 arg_path: arg_path.to_string(),
171 prev_path: render_prev_path(path),
172 resolved_prefix: prev_path_prefix(&resolved_prefix),
173 missing: key.to_string(),
174 available,
175 });
176 }
177 },
178 other => {
179 return Some(PrevFailure::WrongType {
180 arg_path: arg_path.to_string(),
181 prev_path: render_prev_path(path),
182 resolved_prefix: prev_path_prefix(&resolved_prefix),
183 segment: key.to_string(),
184 expected: "object",
185 found: json_type_name(other),
186 });
187 }
188 },
189 crate::parser::PathSegment::Index(idx) => match cur {
190 Value::Array(arr) => match arr.get(idx) {
191 Some(v) => {
192 cur = v;
193 resolved_prefix.push_str(&format!("[{idx}]"));
194 }
195 None => {
196 return Some(PrevFailure::NotFound {
197 arg_path: arg_path.to_string(),
198 prev_path: render_prev_path(path),
199 resolved_prefix: prev_path_prefix(&resolved_prefix),
200 missing: format!("[{idx}]"),
201 available: vec![format!(
202 "array has {} element(s)",
203 arr.len()
204 )],
205 });
206 }
207 },
208 other => {
209 return Some(PrevFailure::WrongType {
210 arg_path: arg_path.to_string(),
211 prev_path: render_prev_path(path),
212 resolved_prefix: prev_path_prefix(&resolved_prefix),
213 segment: format!("[{idx}]"),
214 expected: "array",
215 found: json_type_name(other),
216 });
217 }
218 },
219 crate::parser::PathSegment::Malformed(raw) => {
220 return Some(PrevFailure::Unsupported {
221 arg_path: arg_path.to_string(),
222 prev_path: render_prev_path(path),
223 segment: raw.to_string(),
224 });
225 }
226 }
227 }
228 None
229 }
230 ArgValue::Array(elements) => elements.iter().enumerate().find_map(|(i, el)| {
231 el.find_prev_failure_at(&format!("{arg_path}[{i}]"), prev_result)
232 }),
233 ArgValue::Object(pairs) => pairs.iter().find_map(|(k, v)| {
234 let sub = if arg_path.is_empty() {
235 k.clone()
236 } else {
237 format!("{arg_path}.{k}")
238 };
239 v.find_prev_failure_at(&sub, prev_result)
240 }),
241 }
242 }
243}
244
245fn render_prev_path(path: &str) -> String {
246 format!("$prev.{path}").replace(".[", "[")
247}
248
249fn prev_path_prefix(resolved_prefix: &str) -> String {
252 if resolved_prefix.is_empty() {
253 "$prev".to_string()
254 } else {
255 format!("$prev.{resolved_prefix}")
256 }
257}
258
259fn json_type_name(v: &Value) -> &'static str {
260 match v {
261 Value::Null => "null",
262 Value::Bool(_) => "boolean",
263 Value::Number(_) => "number",
264 Value::String(_) => "string",
265 Value::Array(_) => "array",
266 Value::Object(_) => "object",
267 }
268}
269
270#[derive(Debug, Clone, PartialEq)]
279pub enum PrevFailure {
280 NotFound {
283 arg_path: String,
286 prev_path: String,
288 resolved_prefix: String,
290 missing: String,
292 available: Vec<String>,
295 },
296 WrongType {
300 arg_path: String,
301 prev_path: String,
302 resolved_prefix: String,
305 segment: String,
307 expected: &'static str,
308 found: &'static str,
309 },
310 Unsupported {
312 arg_path: String,
313 prev_path: String,
314 segment: String,
316 },
317}
318
319impl fmt::Display for PrevFailure {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321 fn arg_ref(arg_path: &str) -> String {
322 if arg_path.is_empty() {
323 String::new()
324 } else {
325 format!(" (at {arg_path})")
326 }
327 }
328 match self {
329 PrevFailure::NotFound {
330 arg_path,
331 prev_path,
332 resolved_prefix,
333 missing,
334 available,
335 } => {
336 write!(
337 f,
338 "{prev_path}{arg}: {resolved_prefix} has no {missing:?}. \
339 Available top-level fields: [{}]",
340 available.join(", "),
341 arg = arg_ref(arg_path),
342 )
343 }
344 PrevFailure::WrongType {
345 arg_path,
346 prev_path,
347 resolved_prefix,
348 segment,
349 expected,
350 found,
351 } => {
352 write!(
353 f,
354 "{prev_path}{arg}: {resolved_prefix} is a {found}, not an {expected}, so \
355 {segment:?} cannot be applied to it",
356 arg = arg_ref(arg_path),
357 )
358 }
359 PrevFailure::Unsupported {
360 arg_path,
361 prev_path,
362 segment,
363 } => {
364 write!(
365 f,
366 "{prev_path}{arg}: {segment:?} is not a supported $prev path segment; \
367 array indices must be a plain non-negative integer, e.g. $prev.items[0]",
368 arg = arg_ref(arg_path),
369 )
370 }
371 }
372 }
373}
374
375#[derive(Debug, Clone, PartialEq)]
377pub struct ParsedOp {
378 pub tool: String,
379 pub args: BTreeMap<String, ArgValue>,
380}
381
382#[derive(Debug, Clone, PartialEq)]
384pub struct ParsedRequest {
385 pub ops: Vec<ParsedOp>,
386 pub mode: ExecutionMode,
387}
388
389#[derive(Debug, Clone, PartialEq)]
394pub struct TypedJsonOp {
395 pub tool: String,
396 pub args: serde_json::Map<String, Value>,
397}
398
399#[derive(Debug, Clone, PartialEq)]
406pub enum DslError {
407 Empty,
408 TooManyOps {
409 count: usize,
410 max: usize,
411 },
412 InputTooLarge {
414 len: usize,
415 max: usize,
416 },
417 NestingTooDeep {
419 pos: usize,
420 depth: usize,
421 max: usize,
422 },
423 UnexpectedChar {
424 pos: usize,
425 found: char,
426 expected: &'static str,
427 },
428 UnexpectedEof {
429 expected: &'static str,
430 },
431 InvalidIdentifier {
432 pos: usize,
433 },
434 DuplicateArg {
435 name: String,
436 },
437 InvalidValue {
438 pos: usize,
439 error: String,
440 },
441 InvalidJson {
442 error: String,
443 },
444 UnclosedString,
445 UnclosedBracket {
446 kind: char,
447 },
448 PrevRefOutsideChain {
450 pos: usize,
451 },
452 PrevRefInJsonForm {
454 arg_name: String,
455 },
456 MixedSeparators,
458 EmptyBatch,
460 UnsupportedVerbNesting {
462 pos: usize,
463 },
464 WriteKeyConflict {
466 id: String,
468 first_op: String,
470 second_op: String,
472 },
473 ReservedEnvelopeArg {
475 arg_name: String,
476 verb: String,
477 },
478 TrailingComma {
482 pos: usize,
483 },
484}
485
486impl fmt::Display for DslError {
487 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
488 match self {
489 DslError::Empty => write!(f, "request is empty"),
490 DslError::TooManyOps { count, max } => {
491 write!(f, "batch has {count} ops; max is {max}")
492 }
493 DslError::InputTooLarge { len, max } => {
494 write!(f, "ops input is {len} bytes; max is {max} bytes")
495 }
496 DslError::NestingTooDeep { pos, depth, max } => {
497 write!(
498 f,
499 "at position {pos}: container nesting depth {depth} exceeds max {max}"
500 )
501 }
502 DslError::UnexpectedChar {
503 pos,
504 found,
505 expected,
506 } => {
507 write!(f, "at position {pos}: expected {expected}, found {found:?}")
508 }
509 DslError::UnexpectedEof { expected } => {
510 write!(f, "unexpected end of input; expected {expected}")
511 }
512 DslError::InvalidIdentifier { pos } => {
513 write!(
514 f,
515 "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
516 )
517 }
518 DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
519 DslError::InvalidValue { pos, error } => {
520 write!(f, "at position {pos}: invalid value: {error}")
521 }
522 DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
523 DslError::UnclosedString => write!(f, "unterminated string literal"),
524 DslError::UnclosedBracket { kind } => {
525 write!(f, "unclosed bracket: {kind:?} has no matching close")
526 }
527 DslError::PrevRefOutsideChain { pos } => {
528 write!(
529 f,
530 "at position {pos}: $prev reference is only valid in chain (|) mode; \
531 use function-call form with '|' to chain ops"
532 )
533 }
534 DslError::PrevRefInJsonForm { arg_name } => {
535 write!(
536 f,
537 "argument {arg_name:?}: $prev substitution requires the function-call DSL \
538 with the chain (|) operator; JSON form does not support chains. \
539 Use: verb1(...) | verb2({arg_name}=$prev.id)"
540 )
541 }
542 DslError::MixedSeparators => {
543 write!(
544 f,
545 "cannot mix ',' (parallel) and '|' (chain) separators in one request; \
546 a parallel batch cannot contain a chain. Split the work into two `request` \
547 calls: put independent ops in one `[...]` batch and dependent ops in a \
548 separate `a() | b(arg=$prev.id)` chain"
549 )
550 }
551 DslError::EmptyBatch => {
552 write!(f, "empty batch not allowed; provide at least one op")
553 }
554 DslError::UnsupportedVerbNesting { pos } => {
555 write!(
556 f,
557 "at position {pos}: only single-level dotted verb names are supported \
558 (e.g. brain.state); use a shorter name or register a pack alias"
559 )
560 }
561 DslError::WriteKeyConflict {
562 id,
563 first_op,
564 second_op,
565 } => {
566 write!(
567 f,
568 "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
569 {second_op:?} in the same batch; split into separate requests"
570 )
571 }
572 DslError::ReservedEnvelopeArg { arg_name, verb } => {
573 write!(
574 f,
575 "argument {arg_name:?} in verb {verb:?} is reserved for the request \
576 envelope; pass it at the envelope level, not inside verb args"
577 )
578 }
579 DslError::TrailingComma { pos } => {
580 write!(
581 f,
582 "at position {pos}: trailing comma before ']' — a batch cannot end with \
583 an empty element; remove the comma or add another op after it"
584 )
585 }
586 }
587 }
588}
589
590impl std::error::Error for DslError {}