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/// Names reserved at the request-envelope level; rejected if they appear inside verb args.
10pub const RESERVED_ENVELOPE_ARGS: &[&str] = &["presentation", "presentation_per_op"];
11
12/// Execution mode: `Single` (one op), `Parallel` (`[...]`), or `Chain` (`op | op`).
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum ExecutionMode {
15    /// One operation, no batching or chaining.
16    Single,
17    /// `[op1(...), op2(...)]` — parallel, best-effort, independent results.
18    Parallel,
19    /// `op1(...) | op2(id=$prev.id)` — sequential, abort-on-failure.
20    Chain,
21}
22
23/// An argument value in a [`ParsedOp`]: concrete JSON, a `$prev` path ref, or a nested container.
24#[derive(Debug, Clone, PartialEq)]
25pub enum ArgValue {
26    /// A concrete JSON value (no `$prev` references anywhere inside).
27    Value(Value),
28    /// A `$prev` or `$prev.field.path` back-reference (chain mode only); empty `path` = whole result.
29    PrevRef { path: String },
30    /// Array literal with at least one `$prev` element; pure-JSON arrays fold to `Value(Array)`.
31    Array(Vec<ArgValue>),
32    /// Object literal with at least one `$prev` value; pure-JSON objects fold to `Value(Object)`.
33    Object(Vec<(String, ArgValue)>),
34}
35
36impl ArgValue {
37    /// Returns the contained [`Value`] if this is `ArgValue::Value`.
38    pub fn as_value(&self) -> Option<&Value> {
39        match self {
40            ArgValue::Value(v) => Some(v),
41            ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
42        }
43    }
44
45    /// Returns `true` if this is a `$prev` reference.
46    pub fn is_prev_ref(&self) -> bool {
47        matches!(self, ArgValue::PrevRef { .. })
48    }
49
50    /// Resolve a `$prev` reference against a preceding op's result, returning `None` on miss.
51    pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
52        let ArgValue::PrevRef { path } = self else {
53            return None;
54        };
55        if path.is_empty() {
56            return Some(prev_result);
57        }
58        let mut cur = prev_result;
59        for segment in crate::parser::split_path(path) {
60            cur = crate::parser::apply_path_segment(cur, segment)?;
61        }
62        Some(cur)
63    }
64
65    /// Recursively resolve all `$prev` refs within this value; returns `None` if any path is absent.
66    pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
67        match self {
68            ArgValue::Value(v) => Some(v.clone()),
69            ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
70            ArgValue::Array(elements) => {
71                let mut out = Vec::with_capacity(elements.len());
72                for el in elements {
73                    out.push(el.resolve_all(prev_result)?);
74                }
75                Some(Value::Array(out))
76            }
77            ArgValue::Object(pairs) => {
78                let mut map = serde_json::Map::with_capacity(pairs.len());
79                for (key, val) in pairs {
80                    map.insert(key.clone(), val.resolve_all(prev_result)?);
81                }
82                Some(Value::Object(map))
83            }
84        }
85    }
86}
87
88/// A single parsed operation: tool name plus named argument bag.
89#[derive(Debug, Clone, PartialEq)]
90pub struct ParsedOp {
91    pub tool: String,
92    pub args: BTreeMap<String, ArgValue>,
93}
94
95/// Result of parsing a `request` input: a list of ops and their execution mode.
96#[derive(Debug, Clone, PartialEq)]
97pub struct ParsedRequest {
98    pub ops: Vec<ParsedOp>,
99    pub mode: ExecutionMode,
100}
101
102/// Parser error — surfaced as `invalid_params` at the MCP boundary.
103#[derive(Debug, Clone, PartialEq)]
104pub enum DslError {
105    Empty,
106    TooManyOps {
107        count: usize,
108        max: usize,
109    },
110    UnexpectedChar {
111        pos: usize,
112        found: char,
113        expected: &'static str,
114    },
115    UnexpectedEof {
116        expected: &'static str,
117    },
118    InvalidIdentifier {
119        pos: usize,
120    },
121    DuplicateArg {
122        name: String,
123    },
124    InvalidValue {
125        pos: usize,
126        error: String,
127    },
128    InvalidJson {
129        error: String,
130    },
131    UnclosedString,
132    UnclosedBracket {
133        kind: char,
134    },
135    /// `$prev` reference used outside a chain context — emitted for Single-op
136    /// and Parallel-batch forms, and for JSON form.
137    ///
138    /// `$prev` references are only meaningful in chain (`|`) mode. If they
139    /// appear in a non-chain context the parser rejects the request here so
140    /// downstream consumers get a typed error rather than a runtime string.
141    PrevRefOutsideChain {
142        pos: usize,
143    },
144    /// `$prev` found in JSON-form input — JSON form does not support chains.
145    ///
146    /// JSON form (`[{"tool":"...","args":{...}},...]`) always runs in parallel.
147    /// To use `$prev` substitution, use the function-call DSL with the `|`
148    /// chain operator: `verb1(...) | verb2(id=$prev.id)`.
149    PrevRefInJsonForm {
150        arg_name: String,
151    },
152    /// Mixing `,` and `|` at the top level.
153    MixedSeparators,
154    /// Empty batch `[]` — no ops provided.
155    EmptyBatch,
156    /// Dotted verb name with more than one level (e.g. `a.b.c`). Only
157    /// single-level dotted names are supported (`a.b`).
158    UnsupportedVerbNesting {
159        pos: usize,
160    },
161    /// Two or more ops in a parallel batch write to the same UUID.
162    ///
163    /// Write-key conflict detection is a preflight check applied after parsing.
164    /// Write ops are: `update`, `delete`, `merge`, `link`. When two ops share
165    /// the same `id` (or `into_id` / `from_id` for `merge`,
166    /// `source_id`/`target_id` for `link`) the batch is rejected before any op
167    /// is dispatched.
168    WriteKeyConflict {
169        /// The duplicated UUID.
170        id: String,
171        /// Name of the first op that claimed the key.
172        first_op: String,
173        /// Name of the second op that conflicts.
174        second_op: String,
175    },
176    /// `presentation` and `presentation_per_op` are envelope-only fields and
177    /// must not appear inside individual verb argument lists.
178    ReservedEnvelopeArg {
179        arg_name: String,
180        verb: String,
181    },
182}
183
184impl fmt::Display for DslError {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        match self {
187            DslError::Empty => write!(f, "request is empty"),
188            DslError::TooManyOps { count, max } => {
189                write!(f, "batch has {count} ops; max is {max}")
190            }
191            DslError::UnexpectedChar {
192                pos,
193                found,
194                expected,
195            } => {
196                write!(f, "at position {pos}: expected {expected}, found {found:?}")
197            }
198            DslError::UnexpectedEof { expected } => {
199                write!(f, "unexpected end of input; expected {expected}")
200            }
201            DslError::InvalidIdentifier { pos } => {
202                write!(
203                    f,
204                    "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
205                )
206            }
207            DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
208            DslError::InvalidValue { pos, error } => {
209                write!(f, "at position {pos}: invalid value: {error}")
210            }
211            DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
212            DslError::UnclosedString => write!(f, "unterminated string literal"),
213            DslError::UnclosedBracket { kind } => {
214                write!(f, "unclosed bracket: {kind:?} has no matching close")
215            }
216            DslError::PrevRefOutsideChain { pos } => {
217                write!(
218                    f,
219                    "at position {pos}: $prev reference is only valid in chain (|) mode; \
220                     use function-call form with '|' to chain ops"
221                )
222            }
223            DslError::PrevRefInJsonForm { arg_name } => {
224                write!(
225                    f,
226                    "argument {arg_name:?}: $prev substitution requires the function-call DSL \
227                     with the chain (|) operator; JSON form does not support chains. \
228                     Use: verb1(...) | verb2({arg_name}=$prev.id)"
229                )
230            }
231            DslError::MixedSeparators => {
232                write!(
233                    f,
234                    "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
235                )
236            }
237            DslError::EmptyBatch => {
238                write!(f, "empty batch not allowed; provide at least one op")
239            }
240            DslError::UnsupportedVerbNesting { pos } => {
241                write!(
242                    f,
243                    "at position {pos}: only single-level dotted verb names are supported \
244                     (e.g. brain.state); use a shorter name or register a pack alias"
245                )
246            }
247            DslError::WriteKeyConflict {
248                id,
249                first_op,
250                second_op,
251            } => {
252                write!(
253                    f,
254                    "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
255                     {second_op:?} in the same batch; split into separate requests"
256                )
257            }
258            DslError::ReservedEnvelopeArg { arg_name, verb } => {
259                write!(
260                    f,
261                    "argument {arg_name:?} in verb {verb:?} is reserved for the request \
262                     envelope; pass it at the envelope level, not inside verb args"
263                )
264            }
265        }
266    }
267}
268
269impl std::error::Error for DslError {}