Skip to main content

khive_request/
types.rs

1use std::collections::BTreeMap;
2use std::fmt;
3
4use serde_json::Value;
5
6/// Hard cap on operations per request.
7pub const MAX_OPS: usize = 100;
8
9/// Hard cap on the byte length of a raw `ops` input string, checked before any
10/// parsing begins. A cheap O(1) first line of defense against pathological
11/// input; does not by itself bound container-nesting depth (see
12/// [`NESTING_DEPTH_LIMIT`]), since a compact payload can still pack tens of
13/// thousands of nesting levels into a few KiB.
14///
15/// 1 MiB, not 256 KiB: ADR-038's bulk-operations contract promises up to 1000
16/// items per bulk `create` call (`crates/khive-pack-kg/src/handler_defs.rs`,
17/// `items` param). A realistic 1000-item batch with ~220-byte descriptions
18/// runs to roughly 276 KB once wrapped in the `request` DSL/JSON envelope,
19/// which already blows past a 256 KiB cap. 1 MiB gives that documented
20/// contract several times its observed size in headroom while still
21/// rejecting the multi-hundred-MB inputs this cap exists to stop.
22pub const MAX_OPS_INPUT_LEN: usize = 1024 * 1024;
23
24/// Hard cap on container-nesting depth (`[`/`{`) tracked through the DSL
25/// parser, the JSON-form pre-pass scan, and (by construction, since
26/// `ArgValue::Array` and `ArgValue::Object` are only ever built inside the
27/// depth-guarded parser functions) any `$prev` reference nested inside
28/// array/object literals.
29///
30/// 64 gives generous headroom over real khive `ops` payloads (observed at 2-4
31/// levels of nesting) while remaining far too shallow for a native recursive
32/// descent to threaten the thread stack (CWE-674).
33pub const NESTING_DEPTH_LIMIT: usize = 64;
34
35/// Names reserved at the request-envelope level; rejected if they appear inside verb args.
36pub const RESERVED_ENVELOPE_ARGS: &[&str] = &["presentation", "presentation_per_op"];
37
38/// Iteratively check container-nesting depth of a runtime [`Value`], returning
39/// `false` once nesting exceeds `max_depth`.
40///
41/// Unlike the parser guards above (which bound the DSL's own syntax tree),
42/// values checked here come from verb handler results, e.g. a `traverse` or
43/// `context` result about to be stored as `$prev` chain context, and are
44/// otherwise unbounded. Walks an explicit worklist on the heap instead of
45/// native recursion, so a pathologically deep result cannot overflow the
46/// thread stack via `Value::clone` or serialization (CWE-674) before this
47/// check has a chance to reject it.
48pub fn value_nesting_within_limit(value: &Value, max_depth: usize) -> bool {
49    let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
50    while let Some((v, depth)) = stack.pop() {
51        match v {
52            Value::Array(items) => {
53                let next_depth = depth + 1;
54                if next_depth > max_depth {
55                    return false;
56                }
57                stack.extend(items.iter().map(|item| (item, next_depth)));
58            }
59            Value::Object(map) => {
60                let next_depth = depth + 1;
61                if next_depth > max_depth {
62                    return false;
63                }
64                stack.extend(map.values().map(|item| (item, next_depth)));
65            }
66            _ => {}
67        }
68    }
69    true
70}
71
72/// Execution mode: `Single` (one op), `Parallel` (`[...]`), or `Chain` (`op | op`).
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum ExecutionMode {
75    /// One operation, no batching or chaining.
76    Single,
77    /// `[op1(...), op2(...)]` — parallel, best-effort, independent results.
78    Parallel,
79    /// `op1(...) | op2(id=$prev.id)` — sequential, abort-on-failure.
80    Chain,
81}
82
83/// An argument value in a [`ParsedOp`]: concrete JSON, a `$prev` path ref, or a nested container.
84#[derive(Debug, Clone, PartialEq)]
85pub enum ArgValue {
86    /// A concrete JSON value (no `$prev` references anywhere inside).
87    Value(Value),
88    /// A `$prev` or `$prev.field.path` back-reference (chain mode only); empty `path` = whole result.
89    PrevRef { path: String },
90    /// Array literal with at least one `$prev` element; pure-JSON arrays fold to `Value(Array)`.
91    Array(Vec<ArgValue>),
92    /// Object literal with at least one `$prev` value; pure-JSON objects fold to `Value(Object)`.
93    Object(Vec<(String, ArgValue)>),
94}
95
96impl ArgValue {
97    /// Returns the contained [`Value`] if this is `ArgValue::Value`.
98    pub fn as_value(&self) -> Option<&Value> {
99        match self {
100            ArgValue::Value(v) => Some(v),
101            ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
102        }
103    }
104
105    /// Returns `true` if this is a `$prev` reference.
106    pub fn is_prev_ref(&self) -> bool {
107        matches!(self, ArgValue::PrevRef { .. })
108    }
109
110    /// Resolve a `$prev` reference against a preceding op's result, returning `None` on miss.
111    pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
112        let ArgValue::PrevRef { path } = self else {
113            return None;
114        };
115        if path.is_empty() {
116            return Some(prev_result);
117        }
118        let mut cur = prev_result;
119        for segment in crate::parser::split_path(path) {
120            cur = crate::parser::apply_path_segment(cur, segment)?;
121        }
122        Some(cur)
123    }
124
125    /// Recursively resolve all `$prev` refs within this value; returns `None` if any path is absent.
126    pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
127        match self {
128            ArgValue::Value(v) => Some(v.clone()),
129            ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
130            ArgValue::Array(elements) => {
131                let mut out = Vec::with_capacity(elements.len());
132                for el in elements {
133                    out.push(el.resolve_all(prev_result)?);
134                }
135                Some(Value::Array(out))
136            }
137            ArgValue::Object(pairs) => {
138                let mut map = serde_json::Map::with_capacity(pairs.len());
139                for (key, val) in pairs {
140                    map.insert(key.clone(), val.resolve_all(prev_result)?);
141                }
142                Some(Value::Object(map))
143            }
144        }
145    }
146}
147
148/// A single parsed operation: tool name plus named argument bag.
149#[derive(Debug, Clone, PartialEq)]
150pub struct ParsedOp {
151    pub tool: String,
152    pub args: BTreeMap<String, ArgValue>,
153}
154
155/// Result of parsing a `request` input: a list of ops and their execution mode.
156#[derive(Debug, Clone, PartialEq)]
157pub struct ParsedRequest {
158    pub ops: Vec<ParsedOp>,
159    pub mode: ExecutionMode,
160}
161
162/// Parser error — surfaced as `invalid_params` at the MCP boundary.
163#[derive(Debug, Clone, PartialEq)]
164pub enum DslError {
165    Empty,
166    TooManyOps {
167        count: usize,
168        max: usize,
169    },
170    /// Raw `ops` input exceeds [`MAX_OPS_INPUT_LEN`], rejected before any parsing begins.
171    InputTooLarge {
172        len: usize,
173        max: usize,
174    },
175    /// Container nesting (`[`/`{`) exceeds [`NESTING_DEPTH_LIMIT`]. Covers the
176    /// function-call array/object parser, the JSON-form pre-pass scan, and any
177    /// `$prev` reference nested inside array/object literals (bounded at the
178    /// same construction sites).
179    NestingTooDeep {
180        pos: usize,
181        depth: usize,
182        max: usize,
183    },
184    UnexpectedChar {
185        pos: usize,
186        found: char,
187        expected: &'static str,
188    },
189    UnexpectedEof {
190        expected: &'static str,
191    },
192    InvalidIdentifier {
193        pos: usize,
194    },
195    DuplicateArg {
196        name: String,
197    },
198    InvalidValue {
199        pos: usize,
200        error: String,
201    },
202    InvalidJson {
203        error: String,
204    },
205    UnclosedString,
206    UnclosedBracket {
207        kind: char,
208    },
209    /// `$prev` reference used outside a chain context — emitted for Single-op
210    /// and Parallel-batch forms, and for JSON form.
211    ///
212    /// `$prev` references are only meaningful in chain (`|`) mode. If they
213    /// appear in a non-chain context the parser rejects the request here so
214    /// downstream consumers get a typed error rather than a runtime string.
215    PrevRefOutsideChain {
216        pos: usize,
217    },
218    /// `$prev` found in JSON-form input — JSON form does not support chains.
219    ///
220    /// JSON form (`[{"tool":"...","args":{...}},...]`) always runs in parallel.
221    /// To use `$prev` substitution, use the function-call DSL with the `|`
222    /// chain operator: `verb1(...) | verb2(id=$prev.id)`.
223    PrevRefInJsonForm {
224        arg_name: String,
225    },
226    /// Mixing `,` and `|` at the top level.
227    MixedSeparators,
228    /// Empty batch `[]` — no ops provided.
229    EmptyBatch,
230    /// Dotted verb name with more than one level (e.g. `a.b.c`). Only
231    /// single-level dotted names are supported (`a.b`).
232    UnsupportedVerbNesting {
233        pos: usize,
234    },
235    /// Two or more ops in a parallel batch write to the same UUID.
236    ///
237    /// Write-key conflict detection is a preflight check applied after parsing.
238    /// Write ops are: `update`, `delete`, `merge`, `link`. When two ops share
239    /// the same `id` (or `into_id` / `from_id` for `merge`,
240    /// `source_id`/`target_id` for `link`) the batch is rejected before any op
241    /// is dispatched.
242    WriteKeyConflict {
243        /// The duplicated UUID.
244        id: String,
245        /// Name of the first op that claimed the key.
246        first_op: String,
247        /// Name of the second op that conflicts.
248        second_op: String,
249    },
250    /// `presentation` and `presentation_per_op` are envelope-only fields and
251    /// must not appear inside individual verb argument lists.
252    ReservedEnvelopeArg {
253        arg_name: String,
254        verb: String,
255    },
256}
257
258impl fmt::Display for DslError {
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        match self {
261            DslError::Empty => write!(f, "request is empty"),
262            DslError::TooManyOps { count, max } => {
263                write!(f, "batch has {count} ops; max is {max}")
264            }
265            DslError::InputTooLarge { len, max } => {
266                write!(f, "ops input is {len} bytes; max is {max} bytes")
267            }
268            DslError::NestingTooDeep { pos, depth, max } => {
269                write!(
270                    f,
271                    "at position {pos}: container nesting depth {depth} exceeds max {max}"
272                )
273            }
274            DslError::UnexpectedChar {
275                pos,
276                found,
277                expected,
278            } => {
279                write!(f, "at position {pos}: expected {expected}, found {found:?}")
280            }
281            DslError::UnexpectedEof { expected } => {
282                write!(f, "unexpected end of input; expected {expected}")
283            }
284            DslError::InvalidIdentifier { pos } => {
285                write!(
286                    f,
287                    "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
288                )
289            }
290            DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
291            DslError::InvalidValue { pos, error } => {
292                write!(f, "at position {pos}: invalid value: {error}")
293            }
294            DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
295            DslError::UnclosedString => write!(f, "unterminated string literal"),
296            DslError::UnclosedBracket { kind } => {
297                write!(f, "unclosed bracket: {kind:?} has no matching close")
298            }
299            DslError::PrevRefOutsideChain { pos } => {
300                write!(
301                    f,
302                    "at position {pos}: $prev reference is only valid in chain (|) mode; \
303                     use function-call form with '|' to chain ops"
304                )
305            }
306            DslError::PrevRefInJsonForm { arg_name } => {
307                write!(
308                    f,
309                    "argument {arg_name:?}: $prev substitution requires the function-call DSL \
310                     with the chain (|) operator; JSON form does not support chains. \
311                     Use: verb1(...) | verb2({arg_name}=$prev.id)"
312                )
313            }
314            DslError::MixedSeparators => {
315                write!(
316                    f,
317                    "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
318                )
319            }
320            DslError::EmptyBatch => {
321                write!(f, "empty batch not allowed; provide at least one op")
322            }
323            DslError::UnsupportedVerbNesting { pos } => {
324                write!(
325                    f,
326                    "at position {pos}: only single-level dotted verb names are supported \
327                     (e.g. brain.state); use a shorter name or register a pack alias"
328                )
329            }
330            DslError::WriteKeyConflict {
331                id,
332                first_op,
333                second_op,
334            } => {
335                write!(
336                    f,
337                    "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
338                     {second_op:?} in the same batch; split into separate requests"
339                )
340            }
341            DslError::ReservedEnvelopeArg { arg_name, verb } => {
342                write!(
343                    f,
344                    "argument {arg_name:?} in verb {verb:?} is reserved for the request \
345                     envelope; pass it at the envelope level, not inside verb args"
346                )
347            }
348        }
349    }
350}
351
352impl std::error::Error for DslError {}