Skip to main content

khive_request/
types.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use std::ops::Range;
4
5use serde_json::Value;
6
7/// Maximum operations in a batch or chain.
8pub const MAX_OPS: usize = 100;
9
10/// Maximum raw `ops` byte length, checked before parsing.
11///
12/// See `crates/khive-request/docs/api/limits-and-errors.md` for the bulk-size rationale.
13pub const MAX_OPS_INPUT_LEN: usize = 1024 * 1024;
14
15/// Maximum array/object nesting in function and JSON forms.
16///
17/// See `crates/khive-request/docs/api/limits-and-errors.md` for stack-safety details.
18pub const NESTING_DEPTH_LIMIT: usize = 64;
19
20/// Names reserved at the request-envelope level; rejected if they appear inside verb args.
21pub use khive_types::RESERVED_ENVELOPE_ARGS;
22
23/// Returns whether every array/object in `value` is at most `max_depth` deep.
24///
25/// The walk is iterative, so checking an untrusted handler result cannot itself
26/// overflow the thread stack. Scalar roots have depth zero.
27/// See `crates/khive-request/docs/api/limits-and-errors.md` for usage with `$prev`.
28pub fn value_nesting_within_limit(value: &Value, max_depth: usize) -> bool {
29    let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
30    while let Some((v, depth)) = stack.pop() {
31        match v {
32            Value::Array(items) => {
33                let next_depth = depth + 1;
34                if next_depth > max_depth {
35                    return false;
36                }
37                stack.extend(items.iter().map(|item| (item, next_depth)));
38            }
39            Value::Object(map) => {
40                let next_depth = depth + 1;
41                if next_depth > max_depth {
42                    return false;
43                }
44                stack.extend(map.values().map(|item| (item, next_depth)));
45            }
46            _ => {}
47        }
48    }
49    true
50}
51
52/// Execution mode: `Single` (one op), `Parallel` (`[...]`), or `Chain` (`op | op`).
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum ExecutionMode {
55    /// One operation, no batching or chaining.
56    Single,
57    /// `[op1(...), op2(...)]` — parallel, best-effort, independent results.
58    Parallel,
59    /// `op1(...) | op2(id=$prev.id)` — sequential, abort-on-failure.
60    Chain,
61}
62
63/// A concrete JSON argument or chain-time `$prev` expression.
64///
65/// See `crates/khive-request/docs/api/previous-result.md` for path semantics.
66#[derive(Debug, Clone, PartialEq)]
67pub enum ArgValue {
68    /// A concrete JSON value (no `$prev` references anywhere inside).
69    Value(Value),
70    /// A `$prev` or `$prev.field.path` back-reference (chain mode only); empty `path` = whole result.
71    PrevRef { path: String },
72    /// Array literal with at least one `$prev` element; pure-JSON arrays fold to `Value(Array)`.
73    Array(Vec<ArgValue>),
74    /// Object literal with at least one `$prev` value; pure-JSON objects fold to `Value(Object)`.
75    Object(Vec<(String, ArgValue)>),
76}
77
78impl ArgValue {
79    /// Returns the contained [`Value`] if this is `ArgValue::Value`.
80    pub fn as_value(&self) -> Option<&Value> {
81        match self {
82            ArgValue::Value(v) => Some(v),
83            ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
84        }
85    }
86
87    /// Returns `true` if this is a `$prev` reference.
88    pub fn is_prev_ref(&self) -> bool {
89        matches!(self, ArgValue::PrevRef { .. })
90    }
91
92    /// Resolves this reference by borrowing from `prev_result`.
93    ///
94    /// Returns `None` for a non-reference, missing field, non-array index target,
95    /// or out-of-range index.
96    pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
97        let ArgValue::PrevRef { path } = self else {
98            return None;
99        };
100        if path.is_empty() {
101            return Some(prev_result);
102        }
103        let mut cur = prev_result;
104        for segment in crate::parser::split_path(path) {
105            cur = crate::parser::apply_path_segment(cur, segment)?;
106        }
107        Some(cur)
108    }
109
110    /// Materializes this argument, returning `None` if any nested reference misses.
111    pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
112        match self {
113            ArgValue::Value(v) => Some(v.clone()),
114            ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
115            ArgValue::Array(elements) => {
116                let mut out = Vec::with_capacity(elements.len());
117                for el in elements {
118                    out.push(el.resolve_all(prev_result)?);
119                }
120                Some(Value::Array(out))
121            }
122            ArgValue::Object(pairs) => {
123                let mut map = serde_json::Map::with_capacity(pairs.len());
124                for (key, val) in pairs {
125                    map.insert(key.clone(), val.resolve_all(prev_result)?);
126                }
127                Some(Value::Object(map))
128            }
129        }
130    }
131
132    /// Finds the first `$prev` reference within this argument that fails to
133    /// resolve against `prev_result`, and explains why. `None` means every
134    /// reference resolves (consistent with `resolve_all(prev_result).is_some()`)
135    /// or this argument holds no `$prev` reference at all.
136    ///
137    /// Walks the same segments as `resolve_prev`/`resolve_all` but never
138    /// changes what resolves — it exists purely to build an actionable error
139    /// message for a `resolve_all` miss.
140    pub fn find_prev_failure(&self, prev_result: &Value) -> Option<PrevFailure> {
141        self.find_prev_failure_at("", prev_result)
142    }
143
144    fn find_prev_failure_at(&self, arg_path: &str, prev_result: &Value) -> Option<PrevFailure> {
145        match self {
146            ArgValue::Value(_) => None,
147            ArgValue::PrevRef { path } => {
148                // Empty path = whole-value reference; always resolves. Its
149                // downstream shape (bare $prev onto a map/array) is a
150                // separate, already-handled concern (UE4-H1), not a lookup miss.
151                if path.is_empty() {
152                    return None;
153                }
154                let mut cur = prev_result;
155                let mut resolved_prefix = String::new();
156                for seg in crate::parser::split_path(path) {
157                    match seg {
158                        crate::parser::PathSegment::Field(key) => match cur {
159                            Value::Object(map) => match map.get(key) {
160                                Some(v) => {
161                                    cur = v;
162                                    if !resolved_prefix.is_empty() {
163                                        resolved_prefix.push('.');
164                                    }
165                                    resolved_prefix.push_str(key);
166                                }
167                                None => {
168                                    let mut available: Vec<String> = map.keys().cloned().collect();
169                                    available.sort_unstable();
170                                    return Some(PrevFailure::NotFound {
171                                        arg_path: arg_path.to_string(),
172                                        prev_path: render_prev_path(path),
173                                        resolved_prefix: prev_path_prefix(&resolved_prefix),
174                                        missing: key.to_string(),
175                                        available,
176                                    });
177                                }
178                            },
179                            other => {
180                                return Some(PrevFailure::WrongType {
181                                    arg_path: arg_path.to_string(),
182                                    prev_path: render_prev_path(path),
183                                    resolved_prefix: prev_path_prefix(&resolved_prefix),
184                                    segment: key.to_string(),
185                                    expected: "object",
186                                    found: json_type_name(other),
187                                });
188                            }
189                        },
190                        crate::parser::PathSegment::Index(idx) => match cur {
191                            Value::Array(arr) => match arr.get(idx) {
192                                Some(v) => {
193                                    cur = v;
194                                    resolved_prefix.push_str(&format!("[{idx}]"));
195                                }
196                                None => {
197                                    return Some(PrevFailure::NotFound {
198                                        arg_path: arg_path.to_string(),
199                                        prev_path: render_prev_path(path),
200                                        resolved_prefix: prev_path_prefix(&resolved_prefix),
201                                        missing: format!("[{idx}]"),
202                                        available: vec![format!(
203                                            "array has {} element(s)",
204                                            arr.len()
205                                        )],
206                                    });
207                                }
208                            },
209                            other => {
210                                return Some(PrevFailure::WrongType {
211                                    arg_path: arg_path.to_string(),
212                                    prev_path: render_prev_path(path),
213                                    resolved_prefix: prev_path_prefix(&resolved_prefix),
214                                    segment: format!("[{idx}]"),
215                                    expected: "array",
216                                    found: json_type_name(other),
217                                });
218                            }
219                        },
220                        crate::parser::PathSegment::Malformed(raw) => {
221                            return Some(PrevFailure::Unsupported {
222                                arg_path: arg_path.to_string(),
223                                prev_path: render_prev_path(path),
224                                segment: raw.to_string(),
225                            });
226                        }
227                    }
228                }
229                None
230            }
231            ArgValue::Array(elements) => elements.iter().enumerate().find_map(|(i, el)| {
232                el.find_prev_failure_at(&format!("{arg_path}[{i}]"), prev_result)
233            }),
234            ArgValue::Object(pairs) => pairs.iter().find_map(|(k, v)| {
235                let sub = if arg_path.is_empty() {
236                    k.clone()
237                } else {
238                    format!("{arg_path}.{k}")
239                };
240                v.find_prev_failure_at(&sub, prev_result)
241            }),
242        }
243    }
244}
245
246fn render_prev_path(path: &str) -> String {
247    format!("$prev.{path}").replace(".[", "[")
248}
249
250/// Renders the `$prev`-relative path successfully traversed before a failure,
251/// for messages like "`$prev.user` is a string, not an object".
252fn prev_path_prefix(resolved_prefix: &str) -> String {
253    if resolved_prefix.is_empty() {
254        "$prev".to_string()
255    } else {
256        format!("$prev.{resolved_prefix}")
257    }
258}
259
260fn json_type_name(v: &Value) -> &'static str {
261    match v {
262        Value::Null => "null",
263        Value::Bool(_) => "boolean",
264        Value::Number(_) => "number",
265        Value::String(_) => "string",
266        Value::Array(_) => "array",
267        Value::Object(_) => "object",
268    }
269}
270
271/// Explains why a `$prev` path failed to resolve, for error-message
272/// construction. Distinguishes three mistakes that a single generic
273/// "not found" message conflates:
274///
275/// - the field/index simply isn't there (`NotFound`);
276/// - a segment expects an object or array to index into, but the prior
277///   result holds a scalar at that point (`WrongType`);
278/// - the bracket syntax itself isn't a supported index form (`Unsupported`).
279#[derive(Debug, Clone, PartialEq)]
280pub enum PrevFailure {
281    /// A path segment names a field or index that does not exist on an
282    /// otherwise correctly-typed container.
283    NotFound {
284        /// Path to the offending `$prev` reference within the verb argument
285        /// it appears in (empty when the argument itself is the reference).
286        arg_path: String,
287        /// The full `$prev` path that was attempted, e.g. `$prev.user.id`.
288        prev_path: String,
289        /// The `$prev`-relative path successfully traversed before the miss.
290        resolved_prefix: String,
291        /// The field name or `[index]` that could not be found.
292        missing: String,
293        /// Sibling field names (object) or a length note (array) at the
294        /// point of failure.
295        available: Vec<String>,
296    },
297    /// A path segment expects an object (for a field) or an array (for an
298    /// index) to continue into, but the prior result holds a different JSON
299    /// type at that point.
300    WrongType {
301        arg_path: String,
302        prev_path: String,
303        /// The `$prev`-relative path successfully traversed before the type
304        /// mismatch — this is what actually holds `found`.
305        resolved_prefix: String,
306        /// The field name or `[index]` that could not be applied.
307        segment: String,
308        expected: &'static str,
309        found: &'static str,
310    },
311    /// Bracket syntax that is not a valid non-negative-integer index.
312    Unsupported {
313        arg_path: String,
314        prev_path: String,
315        /// The unsupported segment as written, e.g. `[bad]`.
316        segment: String,
317    },
318}
319
320impl fmt::Display for PrevFailure {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        fn arg_ref(arg_path: &str) -> String {
323            if arg_path.is_empty() {
324                String::new()
325            } else {
326                format!(" (at {arg_path})")
327            }
328        }
329        match self {
330            PrevFailure::NotFound {
331                arg_path,
332                prev_path,
333                resolved_prefix,
334                missing,
335                available,
336            } => {
337                write!(
338                    f,
339                    "{prev_path}{arg}: {resolved_prefix} has no {missing:?}. \
340                     Available top-level fields: [{}]",
341                    available.join(", "),
342                    arg = arg_ref(arg_path),
343                )
344            }
345            PrevFailure::WrongType {
346                arg_path,
347                prev_path,
348                resolved_prefix,
349                segment,
350                expected,
351                found,
352            } => {
353                write!(
354                    f,
355                    "{prev_path}{arg}: {resolved_prefix} is a {found}, not an {expected}, so \
356                     {segment:?} cannot be applied to it",
357                    arg = arg_ref(arg_path),
358                )
359            }
360            PrevFailure::Unsupported {
361                arg_path,
362                prev_path,
363                segment,
364            } => {
365                write!(
366                    f,
367                    "{prev_path}{arg}: {segment:?} is not a supported $prev path segment; \
368                     array indices must be a plain non-negative integer, e.g. $prev.items[0]",
369                    arg = arg_ref(arg_path),
370                )
371            }
372        }
373    }
374}
375
376/// One parsed tool name and its deterministically ordered named arguments.
377#[derive(Debug, Clone, PartialEq)]
378pub struct ParsedOp {
379    pub tool: String,
380    pub args: BTreeMap<String, ArgValue>,
381}
382
383/// Parsed operations in input order plus their execution mode.
384///
385/// `ranges` is a nonempty partition of `ops` into contiguous, non-overlapping
386/// **units**: every leaf belongs to exactly one range, and ranges are listed
387/// in source order with no gaps. `Single` carries one range of length one.
388/// `Chain` carries one range covering every leaf. `Parallel` carries one
389/// range per independent unit; length one for every range in an ordinary
390/// flat batch (`[a(), b()]`), and possibly longer ranges for a bracketed
391/// batch of linear chains (`[a() | b(), c()]`, ADR-016 Amendment 2), where a
392/// range longer than one names a unit that is itself a chain: only its first
393/// leaf is barred from `$prev`, and a failure inside it aborts only that
394/// unit's own remaining leaves.
395#[derive(Debug, Clone, PartialEq)]
396pub struct ParsedRequest {
397    pub ops: Vec<ParsedOp>,
398    pub mode: ExecutionMode,
399    pub ranges: Vec<Range<usize>>,
400}
401
402/// One already-decoded JSON operation for a bounded trusted transport.
403///
404/// This type does not imply semantic validity. Pass it through
405/// [`crate::parse_typed_json_batch`] before dispatch.
406#[derive(Debug, Clone, PartialEq)]
407pub struct TypedJsonOp {
408    pub tool: String,
409    pub args: serde_json::Map<String, Value>,
410}
411
412/// Request syntax or preflight error surfaced as MCP `invalid_params`.
413///
414/// No operation has executed when this error is returned. Resource, syntax,
415/// reference-placement, conflict, and envelope variants retain their relevant
416/// count, position, field, or tool names.
417/// See `crates/khive-request/docs/api/limits-and-errors.md` for the full taxonomy.
418#[derive(Debug, Clone, PartialEq)]
419pub enum DslError {
420    Empty,
421    TooManyOps {
422        count: usize,
423        max: usize,
424    },
425    /// Raw input exceeds [`MAX_OPS_INPUT_LEN`] before parsing begins.
426    InputTooLarge {
427        len: usize,
428        max: usize,
429    },
430    /// Array/object nesting exceeds [`NESTING_DEPTH_LIMIT`].
431    NestingTooDeep {
432        pos: usize,
433        depth: usize,
434        max: usize,
435    },
436    UnexpectedChar {
437        pos: usize,
438        found: char,
439        expected: &'static str,
440    },
441    UnexpectedEof {
442        expected: &'static str,
443    },
444    InvalidIdentifier {
445        pos: usize,
446    },
447    DuplicateArg {
448        name: String,
449    },
450    InvalidValue {
451        pos: usize,
452        error: String,
453    },
454    InvalidJson {
455        error: String,
456    },
457    /// A quoted string reached end of input without a closing quote.
458    UnclosedString {
459        start: usize,
460    },
461    /// A function call reached end of input without its closing `)`.
462    UnclosedCall {
463        start: usize,
464    },
465    UnclosedBracket {
466        kind: char,
467    },
468    /// Function-form `$prev` appears outside chain mode.
469    PrevRefOutsideChain {
470        pos: usize,
471    },
472    /// `$prev` appears in JSON form, which cannot express chains.
473    PrevRefInJsonForm {
474        arg_name: String,
475    },
476    /// Mixing `,` and `|` at the top level.
477    MixedSeparators,
478    /// Empty batch `[]` — no ops provided.
479    EmptyBatch,
480    /// Tool name contains more than one namespace dot.
481    UnsupportedVerbNesting {
482        pos: usize,
483    },
484    /// Two parallel operations claim the same derived write key.
485    WriteKeyConflict {
486        /// Duplicated substrate-prefixed key.
487        id: String,
488        /// Name of the first op that claimed the key.
489        first_op: String,
490        /// Name of the second op that conflicts.
491        second_op: String,
492    },
493    /// An envelope-only field appears inside a verb argument list.
494    ReservedEnvelopeArg {
495        arg_name: String,
496        verb: String,
497    },
498    /// A batch element list has a `,` immediately before its closing `]`,
499    /// e.g. `[a(),]` — the slot between the comma and the bracket looks
500    /// like a missing element, not a second `,` mistake.
501    TrailingComma {
502        pos: usize,
503    },
504}
505
506impl fmt::Display for DslError {
507    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508        match self {
509            DslError::Empty => write!(f, "request is empty"),
510            DslError::TooManyOps { count, max } => {
511                write!(f, "batch has {count} ops; max is {max}")
512            }
513            DslError::InputTooLarge { len, max } => {
514                write!(f, "ops input is {len} bytes; max is {max} bytes")
515            }
516            DslError::NestingTooDeep { pos, depth, max } => {
517                write!(
518                    f,
519                    "at byte {pos}: container nesting depth {depth} exceeds max {max}"
520                )
521            }
522            DslError::UnexpectedChar {
523                pos,
524                found,
525                expected,
526            } => {
527                write!(f, "at byte {pos}: expected {expected}, found {found:?}")
528            }
529            DslError::UnexpectedEof { expected } => {
530                write!(f, "unexpected end of input; expected {expected}")
531            }
532            DslError::InvalidIdentifier { pos } => {
533                write!(
534                    f,
535                    "at byte {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
536                )
537            }
538            DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
539            DslError::InvalidValue { pos, error } => {
540                write!(f, "at byte {pos}: invalid value: {error}")
541            }
542            DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
543            DslError::UnclosedString { start } => {
544                write!(f, "unterminated string literal starting at byte {start}")
545            }
546            DslError::UnclosedCall { start } => {
547                write!(f, "unclosed call starting at byte {start}; expected ')'")
548            }
549            DslError::UnclosedBracket { kind } => {
550                write!(f, "unclosed bracket: {kind:?} has no matching close")
551            }
552            DslError::PrevRefOutsideChain { pos } => {
553                write!(
554                    f,
555                    "at byte {pos}: $prev reference is only valid in chain (|) mode; \
556                     use function-call form with '|' to chain ops"
557                )
558            }
559            DslError::PrevRefInJsonForm { arg_name } => {
560                write!(
561                    f,
562                    "argument {arg_name:?}: $prev substitution requires the function-call DSL \
563                     with the chain (|) operator; JSON form does not support chains. \
564                     Use: verb1(...) | verb2({arg_name}=$prev.id)"
565                )
566            }
567            DslError::MixedSeparators => {
568                write!(
569                    f,
570                    "cannot mix ',' (parallel) and '|' (chain) separators outside `[...]`; \
571                     to run chains in parallel, wrap every unit in one bracketed batch, \
572                     for example `[a() | b(arg=$prev.id), c()]`"
573                )
574            }
575            DslError::EmptyBatch => {
576                write!(f, "empty batch not allowed; provide at least one op")
577            }
578            DslError::UnsupportedVerbNesting { pos } => {
579                write!(
580                    f,
581                    "at byte {pos}: only single-level dotted verb names are supported \
582                     (e.g. brain.state); use a shorter name or register a pack alias"
583                )
584            }
585            DslError::WriteKeyConflict {
586                id,
587                first_op,
588                second_op,
589            } => {
590                write!(
591                    f,
592                    "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
593                     {second_op:?} in the same batch; split into separate requests"
594                )
595            }
596            DslError::ReservedEnvelopeArg { arg_name, verb } => {
597                write!(
598                    f,
599                    "argument {arg_name:?} in verb {verb:?} is reserved for the request \
600                     envelope; pass it at the envelope level, not inside verb args"
601                )
602            }
603            DslError::TrailingComma { pos } => {
604                write!(
605                    f,
606                    "at byte {pos}: trailing comma before ']' — a batch cannot end with \
607                     an empty element; remove the comma or add another op after it"
608                )
609            }
610        }
611    }
612}
613
614impl std::error::Error for DslError {}