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 const RESERVED_ENVELOPE_ARGS: &[&str] = &["presentation", "presentation_per_op"];
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
132/// One parsed tool name and its deterministically ordered named arguments.
133#[derive(Debug, Clone, PartialEq)]
134pub struct ParsedOp {
135    pub tool: String,
136    pub args: BTreeMap<String, ArgValue>,
137}
138
139/// Parsed operations in input order plus their execution mode.
140#[derive(Debug, Clone, PartialEq)]
141pub struct ParsedRequest {
142    pub ops: Vec<ParsedOp>,
143    pub mode: ExecutionMode,
144}
145
146/// Request syntax or preflight error surfaced as MCP `invalid_params`.
147///
148/// No operation has executed when this error is returned. Resource, syntax,
149/// reference-placement, conflict, and envelope variants retain their relevant
150/// count, position, field, or tool names.
151/// See `crates/khive-request/docs/api/limits-and-errors.md` for the full taxonomy.
152#[derive(Debug, Clone, PartialEq)]
153pub enum DslError {
154    Empty,
155    TooManyOps {
156        count: usize,
157        max: usize,
158    },
159    /// Raw input exceeds [`MAX_OPS_INPUT_LEN`] before parsing begins.
160    InputTooLarge {
161        len: usize,
162        max: usize,
163    },
164    /// Array/object nesting exceeds [`NESTING_DEPTH_LIMIT`].
165    NestingTooDeep {
166        pos: usize,
167        depth: usize,
168        max: usize,
169    },
170    UnexpectedChar {
171        pos: usize,
172        found: char,
173        expected: &'static str,
174    },
175    UnexpectedEof {
176        expected: &'static str,
177    },
178    InvalidIdentifier {
179        pos: usize,
180    },
181    DuplicateArg {
182        name: String,
183    },
184    InvalidValue {
185        pos: usize,
186        error: String,
187    },
188    InvalidJson {
189        error: String,
190    },
191    UnclosedString,
192    UnclosedBracket {
193        kind: char,
194    },
195    /// Function-form `$prev` appears outside chain mode.
196    PrevRefOutsideChain {
197        pos: usize,
198    },
199    /// `$prev` appears in JSON form, which cannot express chains.
200    PrevRefInJsonForm {
201        arg_name: String,
202    },
203    /// Mixing `,` and `|` at the top level.
204    MixedSeparators,
205    /// Empty batch `[]` — no ops provided.
206    EmptyBatch,
207    /// Tool name contains more than one namespace dot.
208    UnsupportedVerbNesting {
209        pos: usize,
210    },
211    /// Two parallel operations claim the same derived write key.
212    WriteKeyConflict {
213        /// Duplicated substrate-prefixed key.
214        id: String,
215        /// Name of the first op that claimed the key.
216        first_op: String,
217        /// Name of the second op that conflicts.
218        second_op: String,
219    },
220    /// An envelope-only field appears inside a verb argument list.
221    ReservedEnvelopeArg {
222        arg_name: String,
223        verb: String,
224    },
225}
226
227impl fmt::Display for DslError {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        match self {
230            DslError::Empty => write!(f, "request is empty"),
231            DslError::TooManyOps { count, max } => {
232                write!(f, "batch has {count} ops; max is {max}")
233            }
234            DslError::InputTooLarge { len, max } => {
235                write!(f, "ops input is {len} bytes; max is {max} bytes")
236            }
237            DslError::NestingTooDeep { pos, depth, max } => {
238                write!(
239                    f,
240                    "at position {pos}: container nesting depth {depth} exceeds max {max}"
241                )
242            }
243            DslError::UnexpectedChar {
244                pos,
245                found,
246                expected,
247            } => {
248                write!(f, "at position {pos}: expected {expected}, found {found:?}")
249            }
250            DslError::UnexpectedEof { expected } => {
251                write!(f, "unexpected end of input; expected {expected}")
252            }
253            DslError::InvalidIdentifier { pos } => {
254                write!(
255                    f,
256                    "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
257                )
258            }
259            DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
260            DslError::InvalidValue { pos, error } => {
261                write!(f, "at position {pos}: invalid value: {error}")
262            }
263            DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
264            DslError::UnclosedString => write!(f, "unterminated string literal"),
265            DslError::UnclosedBracket { kind } => {
266                write!(f, "unclosed bracket: {kind:?} has no matching close")
267            }
268            DslError::PrevRefOutsideChain { pos } => {
269                write!(
270                    f,
271                    "at position {pos}: $prev reference is only valid in chain (|) mode; \
272                     use function-call form with '|' to chain ops"
273                )
274            }
275            DslError::PrevRefInJsonForm { arg_name } => {
276                write!(
277                    f,
278                    "argument {arg_name:?}: $prev substitution requires the function-call DSL \
279                     with the chain (|) operator; JSON form does not support chains. \
280                     Use: verb1(...) | verb2({arg_name}=$prev.id)"
281                )
282            }
283            DslError::MixedSeparators => {
284                write!(
285                    f,
286                    "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
287                )
288            }
289            DslError::EmptyBatch => {
290                write!(f, "empty batch not allowed; provide at least one op")
291            }
292            DslError::UnsupportedVerbNesting { pos } => {
293                write!(
294                    f,
295                    "at position {pos}: only single-level dotted verb names are supported \
296                     (e.g. brain.state); use a shorter name or register a pack alias"
297                )
298            }
299            DslError::WriteKeyConflict {
300                id,
301                first_op,
302                second_op,
303            } => {
304                write!(
305                    f,
306                    "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
307                     {second_op:?} in the same batch; split into separate requests"
308                )
309            }
310            DslError::ReservedEnvelopeArg { arg_name, verb } => {
311                write!(
312                    f,
313                    "argument {arg_name:?} in verb {verb:?} is reserved for the request \
314                     envelope; pass it at the envelope level, not inside verb args"
315                )
316            }
317        }
318    }
319}
320
321impl std::error::Error for DslError {}