khive-request 0.18.0

Request DSL — parses verb-dispatch strings (function-call, JSON, and future LNDL / pipe / bash-style syntaxes) into a transport-agnostic ParsedRequest AST
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use std::collections::BTreeMap;
use std::fmt;
use std::ops::Range;

use khive_types::json_type_name;
use serde_json::Value;

/// Maximum operations in a batch or chain.
pub const MAX_OPS: usize = 100;

/// Maximum raw `ops` byte length, checked before parsing.
///
/// See `crates/khive-request/docs/api/limits-and-errors.md` for the bulk-size rationale.
pub const MAX_OPS_INPUT_LEN: usize = 1024 * 1024;

/// Maximum array/object nesting in function and JSON forms.
///
/// See `crates/khive-request/docs/api/limits-and-errors.md` for stack-safety details.
pub const NESTING_DEPTH_LIMIT: usize = 64;

/// Names reserved at the request-envelope level; rejected if they appear inside verb args.
pub use khive_types::RESERVED_ENVELOPE_ARGS;

/// Returns whether every array/object in `value` is at most `max_depth` deep.
///
/// The walk is iterative, so checking an untrusted handler result cannot itself
/// overflow the thread stack. Scalar roots have depth zero.
/// See `crates/khive-request/docs/api/limits-and-errors.md` for usage with `$prev`.
pub fn value_nesting_within_limit(value: &Value, max_depth: usize) -> bool {
    let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
    while let Some((v, depth)) = stack.pop() {
        match v {
            Value::Array(items) => {
                let next_depth = depth + 1;
                if next_depth > max_depth {
                    return false;
                }
                stack.extend(items.iter().map(|item| (item, next_depth)));
            }
            Value::Object(map) => {
                let next_depth = depth + 1;
                if next_depth > max_depth {
                    return false;
                }
                stack.extend(map.values().map(|item| (item, next_depth)));
            }
            _ => {}
        }
    }
    true
}

/// Execution mode: `Single` (one op), `Parallel` (`[...]`), or `Chain` (`op | op`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecutionMode {
    /// One operation, no batching or chaining.
    Single,
    /// `[op1(...), op2(...)]` — parallel, best-effort, independent results.
    Parallel,
    /// `op1(...) | op2(id=$prev.id)` — sequential, abort-on-failure.
    Chain,
}

/// A concrete JSON argument or chain-time `$prev` expression.
///
/// See `crates/khive-request/docs/api/previous-result.md` for path semantics.
#[derive(Debug, Clone, PartialEq)]
pub enum ArgValue {
    /// A concrete JSON value (no `$prev` references anywhere inside).
    Value(Value),
    /// A `$prev` or `$prev.field.path` back-reference (chain mode only); empty `path` = whole result.
    PrevRef { path: String },
    /// Array literal with at least one `$prev` element; pure-JSON arrays fold to `Value(Array)`.
    Array(Vec<ArgValue>),
    /// Object literal with at least one `$prev` value; pure-JSON objects fold to `Value(Object)`.
    Object(Vec<(String, ArgValue)>),
}

impl ArgValue {
    /// Returns the contained [`Value`] if this is `ArgValue::Value`.
    pub fn as_value(&self) -> Option<&Value> {
        match self {
            ArgValue::Value(v) => Some(v),
            ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
        }
    }

    /// Returns `true` if this is a `$prev` reference.
    pub fn is_prev_ref(&self) -> bool {
        matches!(self, ArgValue::PrevRef { .. })
    }

    /// Resolves this reference by borrowing from `prev_result`.
    ///
    /// Returns `None` for a non-reference, missing field, non-array index target,
    /// or out-of-range index.
    pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
        let ArgValue::PrevRef { path } = self else {
            return None;
        };
        if path.is_empty() {
            return Some(prev_result);
        }
        let mut cur = prev_result;
        for segment in crate::parser::split_path(path) {
            cur = crate::parser::apply_path_segment(cur, segment)?;
        }
        Some(cur)
    }

    /// Materializes this argument, returning `None` if any nested reference misses.
    pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
        match self {
            ArgValue::Value(v) => Some(v.clone()),
            ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
            ArgValue::Array(elements) => {
                let mut out = Vec::with_capacity(elements.len());
                for el in elements {
                    out.push(el.resolve_all(prev_result)?);
                }
                Some(Value::Array(out))
            }
            ArgValue::Object(pairs) => {
                let mut map = serde_json::Map::with_capacity(pairs.len());
                for (key, val) in pairs {
                    map.insert(key.clone(), val.resolve_all(prev_result)?);
                }
                Some(Value::Object(map))
            }
        }
    }

    /// Finds the first `$prev` reference within this argument that fails to
    /// resolve against `prev_result`, and explains why. `None` means every
    /// reference resolves (consistent with `resolve_all(prev_result).is_some()`)
    /// or this argument holds no `$prev` reference at all.
    ///
    /// Walks the same segments as `resolve_prev`/`resolve_all` but never
    /// changes what resolves — it exists purely to build an actionable error
    /// message for a `resolve_all` miss.
    pub fn find_prev_failure(&self, prev_result: &Value) -> Option<PrevFailure> {
        self.find_prev_failure_at("", prev_result)
    }

    fn find_prev_failure_at(&self, arg_path: &str, prev_result: &Value) -> Option<PrevFailure> {
        match self {
            ArgValue::Value(_) => None,
            ArgValue::PrevRef { path } => {
                // Empty path = whole-value reference; always resolves. Its
                // downstream shape (bare $prev onto a map/array) is a
                // separate, already-handled concern (UE4-H1), not a lookup miss.
                if path.is_empty() {
                    return None;
                }
                let mut cur = prev_result;
                let mut resolved_prefix = String::new();
                for seg in crate::parser::split_path(path) {
                    match seg {
                        crate::parser::PathSegment::Field(key) => match cur {
                            Value::Object(map) => match map.get(key) {
                                Some(v) => {
                                    cur = v;
                                    if !resolved_prefix.is_empty() {
                                        resolved_prefix.push('.');
                                    }
                                    resolved_prefix.push_str(key);
                                }
                                None => {
                                    let mut available: Vec<String> = map.keys().cloned().collect();
                                    available.sort_unstable();
                                    return Some(PrevFailure::NotFound {
                                        arg_path: arg_path.to_string(),
                                        prev_path: render_prev_path(path),
                                        resolved_prefix: prev_path_prefix(&resolved_prefix),
                                        missing: key.to_string(),
                                        available,
                                    });
                                }
                            },
                            other => {
                                return Some(PrevFailure::WrongType {
                                    arg_path: arg_path.to_string(),
                                    prev_path: render_prev_path(path),
                                    resolved_prefix: prev_path_prefix(&resolved_prefix),
                                    segment: key.to_string(),
                                    expected: "object",
                                    found: json_type_name(other),
                                });
                            }
                        },
                        crate::parser::PathSegment::Index(idx) => match cur {
                            Value::Array(arr) => match arr.get(idx) {
                                Some(v) => {
                                    cur = v;
                                    resolved_prefix.push_str(&format!("[{idx}]"));
                                }
                                None => {
                                    return Some(PrevFailure::NotFound {
                                        arg_path: arg_path.to_string(),
                                        prev_path: render_prev_path(path),
                                        resolved_prefix: prev_path_prefix(&resolved_prefix),
                                        missing: format!("[{idx}]"),
                                        available: vec![format!(
                                            "array has {} element(s)",
                                            arr.len()
                                        )],
                                    });
                                }
                            },
                            other => {
                                return Some(PrevFailure::WrongType {
                                    arg_path: arg_path.to_string(),
                                    prev_path: render_prev_path(path),
                                    resolved_prefix: prev_path_prefix(&resolved_prefix),
                                    segment: format!("[{idx}]"),
                                    expected: "array",
                                    found: json_type_name(other),
                                });
                            }
                        },
                        crate::parser::PathSegment::Malformed(raw) => {
                            return Some(PrevFailure::Unsupported {
                                arg_path: arg_path.to_string(),
                                prev_path: render_prev_path(path),
                                segment: raw.to_string(),
                            });
                        }
                    }
                }
                None
            }
            ArgValue::Array(elements) => elements.iter().enumerate().find_map(|(i, el)| {
                el.find_prev_failure_at(&format!("{arg_path}[{i}]"), prev_result)
            }),
            ArgValue::Object(pairs) => pairs.iter().find_map(|(k, v)| {
                let sub = if arg_path.is_empty() {
                    k.clone()
                } else {
                    format!("{arg_path}.{k}")
                };
                v.find_prev_failure_at(&sub, prev_result)
            }),
        }
    }
}

fn render_prev_path(path: &str) -> String {
    format!("$prev.{path}").replace(".[", "[")
}

/// Renders the `$prev`-relative path successfully traversed before a failure,
/// for messages like "`$prev.user` is a string, not an object".
fn prev_path_prefix(resolved_prefix: &str) -> String {
    if resolved_prefix.is_empty() {
        "$prev".to_string()
    } else {
        render_prev_path(resolved_prefix)
    }
}

/// Explains why a `$prev` path failed to resolve, for error-message
/// construction. Distinguishes three mistakes that a single generic
/// "not found" message conflates:
///
/// - the field/index simply isn't there (`NotFound`);
/// - a segment expects an object or array to index into, but the prior
///   result holds a scalar at that point (`WrongType`);
/// - the bracket syntax itself isn't a supported index form (`Unsupported`).
#[derive(Debug, Clone, PartialEq)]
pub enum PrevFailure {
    /// A path segment names a field or index that does not exist on an
    /// otherwise correctly-typed container.
    NotFound {
        /// Path to the offending `$prev` reference within the verb argument
        /// it appears in (empty when the argument itself is the reference).
        arg_path: String,
        /// The full `$prev` path that was attempted, e.g. `$prev.user.id`.
        prev_path: String,
        /// The `$prev`-relative path successfully traversed before the miss.
        resolved_prefix: String,
        /// The field name or `[index]` that could not be found.
        missing: String,
        /// Sibling field names (object) or a length note (array) at the
        /// point of failure.
        available: Vec<String>,
    },
    /// A path segment expects an object (for a field) or an array (for an
    /// index) to continue into, but the prior result holds a different JSON
    /// type at that point.
    WrongType {
        arg_path: String,
        prev_path: String,
        /// The `$prev`-relative path successfully traversed before the type
        /// mismatch — this is what actually holds `found`.
        resolved_prefix: String,
        /// The field name or `[index]` that could not be applied.
        segment: String,
        expected: &'static str,
        found: &'static str,
    },
    /// Bracket syntax that is not a valid non-negative-integer index.
    Unsupported {
        arg_path: String,
        prev_path: String,
        /// The unsupported segment as written, e.g. `[bad]`.
        segment: String,
    },
}

impl fmt::Display for PrevFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn arg_ref(arg_path: &str) -> String {
            if arg_path.is_empty() {
                String::new()
            } else {
                format!(" (at {arg_path})")
            }
        }
        match self {
            PrevFailure::NotFound {
                arg_path,
                prev_path,
                resolved_prefix,
                missing,
                available,
            } => {
                write!(
                    f,
                    "{prev_path}{arg}: {resolved_prefix} has no {missing:?}. \
                     Available top-level fields: [{}]",
                    available.join(", "),
                    arg = arg_ref(arg_path),
                )
            }
            PrevFailure::WrongType {
                arg_path,
                prev_path,
                resolved_prefix,
                segment,
                expected,
                found,
            } => {
                write!(
                    f,
                    "{prev_path}{arg}: {resolved_prefix} is a {found}, not an {expected}, so \
                     {segment:?} cannot be applied to it",
                    arg = arg_ref(arg_path),
                )
            }
            PrevFailure::Unsupported {
                arg_path,
                prev_path,
                segment,
            } => {
                write!(
                    f,
                    "{prev_path}{arg}: {segment:?} is not a supported $prev path segment; \
                     array indices must be a plain non-negative integer, e.g. $prev.items[0]",
                    arg = arg_ref(arg_path),
                )
            }
        }
    }
}

/// One parsed tool name and its deterministically ordered named arguments.
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedOp {
    pub tool: String,
    pub args: BTreeMap<String, ArgValue>,
}

/// Parsed operations in input order plus their execution mode.
///
/// `ranges` is a nonempty partition of `ops` into contiguous, non-overlapping
/// **units**: every leaf belongs to exactly one range, and ranges are listed
/// in source order with no gaps. `Single` carries one range of length one.
/// `Chain` carries one range covering every leaf. `Parallel` carries one
/// range per independent unit; length one for every range in an ordinary
/// flat batch (`[a(), b()]`), and possibly longer ranges for a bracketed
/// batch of linear chains (`[a() | b(), c()]`, ADR-016 Amendment 2), where a
/// range longer than one names a unit that is itself a chain: only its first
/// leaf is barred from `$prev`, and a failure inside it aborts only that
/// unit's own remaining leaves.
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedRequest {
    pub ops: Vec<ParsedOp>,
    pub mode: ExecutionMode,
    pub ranges: Vec<Range<usize>>,
}

/// One already-decoded JSON operation for a bounded trusted transport.
///
/// This type does not imply semantic validity. Pass it through
/// [`crate::parse_typed_json_batch`] before dispatch.
#[derive(Debug, Clone, PartialEq)]
pub struct TypedJsonOp {
    pub tool: String,
    pub args: serde_json::Map<String, Value>,
}

/// Request syntax or preflight error surfaced as MCP `invalid_params`.
///
/// No operation has executed when this error is returned. Resource, syntax,
/// reference-placement, conflict, and envelope variants retain their relevant
/// count, position, field, or tool names.
/// See `crates/khive-request/docs/api/limits-and-errors.md` for the full taxonomy.
#[derive(Debug, Clone, PartialEq)]
pub enum DslError {
    Empty,
    TooManyOps {
        count: usize,
        max: usize,
    },
    /// Raw input exceeds [`MAX_OPS_INPUT_LEN`] before parsing begins.
    InputTooLarge {
        len: usize,
        max: usize,
    },
    /// Array/object nesting exceeds [`NESTING_DEPTH_LIMIT`].
    NestingTooDeep {
        pos: usize,
        depth: usize,
        max: usize,
    },
    UnexpectedChar {
        pos: usize,
        found: char,
        expected: &'static str,
    },
    UnexpectedEof {
        expected: &'static str,
    },
    InvalidIdentifier {
        pos: usize,
    },
    DuplicateArg {
        name: String,
    },
    InvalidValue {
        pos: usize,
        error: String,
    },
    InvalidJson {
        error: String,
    },
    /// A quoted string reached end of input without a closing quote.
    UnclosedString {
        start: usize,
    },
    /// A function call reached end of input without its closing `)`.
    UnclosedCall {
        start: usize,
    },
    UnclosedBracket {
        kind: char,
    },
    /// Function-form `$prev` appears outside chain mode.
    PrevRefOutsideChain {
        pos: usize,
    },
    /// `$prev` appears in JSON form, which cannot express chains.
    PrevRefInJsonForm {
        arg_name: String,
    },
    /// Mixing `,` and `|` at the top level.
    MixedSeparators,
    /// Empty batch `[]` — no ops provided.
    EmptyBatch,
    /// Tool name contains more than one namespace dot.
    UnsupportedVerbNesting {
        pos: usize,
    },
    /// Two parallel operations claim the same derived write key.
    WriteKeyConflict {
        /// Duplicated substrate-prefixed key.
        id: String,
        /// Name of the first op that claimed the key.
        first_op: String,
        /// Name of the second op that conflicts.
        second_op: String,
        /// Sorted, unique global operation indexes claiming this key, including self.
        conflict_ops: Vec<usize>,
    },
    /// An envelope-only field appears inside a verb argument list.
    ReservedEnvelopeArg {
        arg_name: String,
        verb: String,
    },
    /// A batch element list has a `,` immediately before its closing `]`,
    /// e.g. `[a(),]` — the slot between the comma and the bracket looks
    /// like a missing element, not a second `,` mistake.
    TrailingComma {
        pos: usize,
    },
}

impl fmt::Display for DslError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DslError::Empty => write!(f, "request is empty"),
            DslError::TooManyOps { count, max } => {
                write!(f, "batch has {count} ops; max is {max}")
            }
            DslError::InputTooLarge { len, max } => {
                write!(f, "ops input is {len} bytes; max is {max} bytes")
            }
            DslError::NestingTooDeep { pos, depth, max } => {
                write!(
                    f,
                    "at byte {pos}: container nesting depth {depth} exceeds max {max}"
                )
            }
            DslError::UnexpectedChar {
                pos,
                found,
                expected,
            } => {
                write!(f, "at byte {pos}: expected {expected}, found {found:?}")
            }
            DslError::UnexpectedEof { expected } => {
                write!(f, "unexpected end of input; expected {expected}")
            }
            DslError::InvalidIdentifier { pos } => {
                write!(
                    f,
                    "at byte {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
                )
            }
            DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
            DslError::InvalidValue { pos, error } => {
                write!(f, "at byte {pos}: invalid value: {error}")
            }
            DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
            DslError::UnclosedString { start } => {
                write!(f, "unterminated string literal starting at byte {start}")
            }
            DslError::UnclosedCall { start } => {
                write!(f, "unclosed call starting at byte {start}; expected ')'")
            }
            DslError::UnclosedBracket { kind } => {
                write!(f, "unclosed bracket: {kind:?} has no matching close")
            }
            DslError::PrevRefOutsideChain { pos } => {
                write!(
                    f,
                    "at byte {pos}: $prev reference is only valid in chain (|) mode; \
                     use function-call form with '|' to chain ops"
                )
            }
            DslError::PrevRefInJsonForm { arg_name } => {
                write!(
                    f,
                    "argument {arg_name:?}: $prev substitution requires the function-call DSL \
                     with the chain (|) operator; JSON form does not support chains. \
                     Use: verb1(...) | verb2({arg_name}=$prev.id)"
                )
            }
            DslError::MixedSeparators => {
                write!(
                    f,
                    "cannot mix ',' (parallel) and '|' (chain) separators outside `[...]`; \
                     to run chains in parallel, wrap every unit in one bracketed batch, \
                     for example `[a() | b(arg=$prev.id), c()]`"
                )
            }
            DslError::EmptyBatch => {
                write!(f, "empty batch not allowed; provide at least one op")
            }
            DslError::UnsupportedVerbNesting { pos } => {
                write!(
                    f,
                    "at byte {pos}: only single-level dotted verb names are supported \
                     (e.g. brain.state); use a shorter name or register a pack alias"
                )
            }
            DslError::WriteKeyConflict {
                id,
                first_op,
                second_op,
                ..
            } => {
                write!(
                    f,
                    "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
                     {second_op:?} in the same batch; split into separate requests"
                )
            }
            DslError::ReservedEnvelopeArg { arg_name, verb } => {
                write!(
                    f,
                    "argument {arg_name:?} in verb {verb:?} is reserved for the request \
                     envelope; pass it at the envelope level, not inside verb args"
                )
            }
            DslError::TrailingComma { pos } => {
                write!(
                    f,
                    "at byte {pos}: trailing comma before ']' — a batch cannot end with \
                     an empty element; remove the comma or add another op after it"
                )
            }
        }
    }
}

impl std::error::Error for DslError {}

#[cfg(test)]
#[path = "types_prev_type_tests.rs"]
mod prev_type_tests;