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