Skip to main content

khive_request/
types.rs

1use std::collections::BTreeMap;
2use std::fmt;
3
4use serde_json::Value;
5
6/// Maximum operations in a batch or chain.
7pub const MAX_OPS: usize = 100;
8
9/// Maximum raw `ops` byte length, checked before parsing.
10///
11/// See `crates/khive-request/docs/api/limits-and-errors.md` for the bulk-size rationale.
12pub const MAX_OPS_INPUT_LEN: usize = 1024 * 1024;
13
14/// Maximum array/object nesting in function and JSON forms.
15///
16/// See `crates/khive-request/docs/api/limits-and-errors.md` for stack-safety details.
17pub const NESTING_DEPTH_LIMIT: usize = 64;
18
19/// Names reserved at the request-envelope level; rejected if they appear inside verb args.
20pub use khive_types::RESERVED_ENVELOPE_ARGS;
21
22/// Returns whether every array/object in `value` is at most `max_depth` deep.
23///
24/// The walk is iterative, so checking an untrusted handler result cannot itself
25/// overflow the thread stack. Scalar roots have depth zero.
26/// See `crates/khive-request/docs/api/limits-and-errors.md` for usage with `$prev`.
27pub 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/// Execution mode: `Single` (one op), `Parallel` (`[...]`), or `Chain` (`op | op`).
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum ExecutionMode {
54    /// One operation, no batching or chaining.
55    Single,
56    /// `[op1(...), op2(...)]` — parallel, best-effort, independent results.
57    Parallel,
58    /// `op1(...) | op2(id=$prev.id)` — sequential, abort-on-failure.
59    Chain,
60}
61
62/// A concrete JSON argument or chain-time `$prev` expression.
63///
64/// See `crates/khive-request/docs/api/previous-result.md` for path semantics.
65#[derive(Debug, Clone, PartialEq)]
66pub enum ArgValue {
67    /// A concrete JSON value (no `$prev` references anywhere inside).
68    Value(Value),
69    /// A `$prev` or `$prev.field.path` back-reference (chain mode only); empty `path` = whole result.
70    PrevRef { path: String },
71    /// Array literal with at least one `$prev` element; pure-JSON arrays fold to `Value(Array)`.
72    Array(Vec<ArgValue>),
73    /// Object literal with at least one `$prev` value; pure-JSON objects fold to `Value(Object)`.
74    Object(Vec<(String, ArgValue)>),
75}
76
77impl ArgValue {
78    /// Returns the contained [`Value`] if this is `ArgValue::Value`.
79    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    /// Returns `true` if this is a `$prev` reference.
87    pub fn is_prev_ref(&self) -> bool {
88        matches!(self, ArgValue::PrevRef { .. })
89    }
90
91    /// Resolves this reference by borrowing from `prev_result`.
92    ///
93    /// Returns `None` for a non-reference, missing field, non-array index target,
94    /// or out-of-range index.
95    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    /// Materializes this argument, returning `None` if any nested reference misses.
110    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    /// Finds the first `$prev` reference within this argument that fails to
132    /// resolve against `prev_result`, and explains why. `None` means every
133    /// reference resolves (consistent with `resolve_all(prev_result).is_some()`)
134    /// or this argument holds no `$prev` reference at all.
135    ///
136    /// Walks the same segments as `resolve_prev`/`resolve_all` but never
137    /// changes what resolves — it exists purely to build an actionable error
138    /// message for a `resolve_all` miss.
139    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                // Empty path = whole-value reference; always resolves. Its
148                // downstream shape (bare $prev onto a map/array) is a
149                // separate, already-handled concern (UE4-H1), not a lookup miss.
150                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
249/// Renders the `$prev`-relative path successfully traversed before a failure,
250/// for messages like "`$prev.user` is a string, not an object".
251fn 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/// Explains why a `$prev` path failed to resolve, for error-message
271/// construction. Distinguishes three mistakes that a single generic
272/// "not found" message conflates:
273///
274/// - the field/index simply isn't there (`NotFound`);
275/// - a segment expects an object or array to index into, but the prior
276///   result holds a scalar at that point (`WrongType`);
277/// - the bracket syntax itself isn't a supported index form (`Unsupported`).
278#[derive(Debug, Clone, PartialEq)]
279pub enum PrevFailure {
280    /// A path segment names a field or index that does not exist on an
281    /// otherwise correctly-typed container.
282    NotFound {
283        /// Path to the offending `$prev` reference within the verb argument
284        /// it appears in (empty when the argument itself is the reference).
285        arg_path: String,
286        /// The full `$prev` path that was attempted, e.g. `$prev.user.id`.
287        prev_path: String,
288        /// The `$prev`-relative path successfully traversed before the miss.
289        resolved_prefix: String,
290        /// The field name or `[index]` that could not be found.
291        missing: String,
292        /// Sibling field names (object) or a length note (array) at the
293        /// point of failure.
294        available: Vec<String>,
295    },
296    /// A path segment expects an object (for a field) or an array (for an
297    /// index) to continue into, but the prior result holds a different JSON
298    /// type at that point.
299    WrongType {
300        arg_path: String,
301        prev_path: String,
302        /// The `$prev`-relative path successfully traversed before the type
303        /// mismatch — this is what actually holds `found`.
304        resolved_prefix: String,
305        /// The field name or `[index]` that could not be applied.
306        segment: String,
307        expected: &'static str,
308        found: &'static str,
309    },
310    /// Bracket syntax that is not a valid non-negative-integer index.
311    Unsupported {
312        arg_path: String,
313        prev_path: String,
314        /// The unsupported segment as written, e.g. `[bad]`.
315        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/// One parsed tool name and its deterministically ordered named arguments.
376#[derive(Debug, Clone, PartialEq)]
377pub struct ParsedOp {
378    pub tool: String,
379    pub args: BTreeMap<String, ArgValue>,
380}
381
382/// Parsed operations in input order plus their execution mode.
383#[derive(Debug, Clone, PartialEq)]
384pub struct ParsedRequest {
385    pub ops: Vec<ParsedOp>,
386    pub mode: ExecutionMode,
387}
388
389/// One already-decoded JSON operation for a bounded trusted transport.
390///
391/// This type does not imply semantic validity. Pass it through
392/// [`crate::parse_typed_json_batch`] before dispatch.
393#[derive(Debug, Clone, PartialEq)]
394pub struct TypedJsonOp {
395    pub tool: String,
396    pub args: serde_json::Map<String, Value>,
397}
398
399/// Request syntax or preflight error surfaced as MCP `invalid_params`.
400///
401/// No operation has executed when this error is returned. Resource, syntax,
402/// reference-placement, conflict, and envelope variants retain their relevant
403/// count, position, field, or tool names.
404/// See `crates/khive-request/docs/api/limits-and-errors.md` for the full taxonomy.
405#[derive(Debug, Clone, PartialEq)]
406pub enum DslError {
407    Empty,
408    TooManyOps {
409        count: usize,
410        max: usize,
411    },
412    /// Raw input exceeds [`MAX_OPS_INPUT_LEN`] before parsing begins.
413    InputTooLarge {
414        len: usize,
415        max: usize,
416    },
417    /// Array/object nesting exceeds [`NESTING_DEPTH_LIMIT`].
418    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    /// Function-form `$prev` appears outside chain mode.
449    PrevRefOutsideChain {
450        pos: usize,
451    },
452    /// `$prev` appears in JSON form, which cannot express chains.
453    PrevRefInJsonForm {
454        arg_name: String,
455    },
456    /// Mixing `,` and `|` at the top level.
457    MixedSeparators,
458    /// Empty batch `[]` — no ops provided.
459    EmptyBatch,
460    /// Tool name contains more than one namespace dot.
461    UnsupportedVerbNesting {
462        pos: usize,
463    },
464    /// Two parallel operations claim the same derived write key.
465    WriteKeyConflict {
466        /// Duplicated substrate-prefixed key.
467        id: String,
468        /// Name of the first op that claimed the key.
469        first_op: String,
470        /// Name of the second op that conflicts.
471        second_op: String,
472    },
473    /// An envelope-only field appears inside a verb argument list.
474    ReservedEnvelopeArg {
475        arg_name: String,
476        verb: String,
477    },
478    /// A batch element list has a `,` immediately before its closing `]`,
479    /// e.g. `[a(),]` — the slot between the comma and the bracket looks
480    /// like a missing element, not a second `,` mistake.
481    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 {}