Skip to main content

khive_request/parser/
dispatch.rs

1//! Top-level DSL dispatch: single op, batch, chain, and JSON form routing.
2
3use std::collections::BTreeMap;
4
5use serde_json::{Map, Value};
6
7use crate::types::{
8    ArgValue, DslError, ExecutionMode, ParsedOp, ParsedRequest, TypedJsonOp, MAX_OPS,
9    MAX_OPS_INPUT_LEN, NESTING_DEPTH_LIMIT, RESERVED_ENVELOPE_ARGS,
10};
11
12use super::parser_impl::Parser;
13use super::scan::{check_json_nesting_depth, find_prev_ref_pos, json_value_contains_prev_ref};
14
15/// Parses function-call, batch, chain, or JSON request syntax.
16///
17/// The returned operations preserve input order and are not executed.
18///
19/// # Errors
20///
21/// Returns [`DslError`] for empty/oversized/deep input, malformed syntax or
22/// JSON shape, too many operations, illegal `$prev` placement, mixed execution
23/// separators, duplicate args, nested tool namespaces, or envelope-only args.
24/// See `crates/khive-request/docs/api/parsing.md` for routing and form contracts.
25pub fn parse_request(input: &str) -> Result<ParsedRequest, DslError> {
26    let trimmed = input.trim();
27    if trimmed.is_empty() {
28        return Err(DslError::Empty);
29    }
30    if trimmed.len() > MAX_OPS_INPUT_LEN {
31        return Err(DslError::InputTooLarge {
32            len: trimmed.len(),
33            max: MAX_OPS_INPUT_LEN,
34        });
35    }
36
37    let first = trimmed.as_bytes()[0];
38    let looks_like_json = first == b'{'
39        || (first == b'['
40            && trimmed
41                .as_bytes()
42                .iter()
43                .skip(1)
44                .find(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
45                .is_some_and(|b| *b == b'{'));
46    if looks_like_json {
47        return parse_json_form(trimmed);
48    }
49
50    if first == b'[' {
51        return parse_fn_batch(trimmed);
52    }
53
54    let mut p = Parser::new(trimmed);
55    let first_op = p.parse_op()?;
56    p.skip_ws();
57
58    if p.eof() {
59        if let Some(pos) = find_prev_ref_pos(&first_op) {
60            return Err(DslError::PrevRefOutsideChain { pos });
61        }
62        reject_reserved_args(&first_op)?;
63        return Ok(ParsedRequest {
64            ops: vec![first_op],
65            mode: ExecutionMode::Single,
66        });
67    }
68
69    if p.peek() == Some('|') {
70        return parse_chain_tail(p, first_op);
71    }
72
73    // A top-level `,` here means the caller wrote `a(), b()` without the
74    // `[...]` a parallel batch requires — the same top-level-separator
75    // mistake `parse_fn_batch` and `parse_chain_tail` already name via
76    // `MixedSeparators`, just hit before either of them ran.
77    if p.peek() == Some(',') {
78        return Err(DslError::MixedSeparators);
79    }
80
81    Err(DslError::UnexpectedChar {
82        pos: p.pos,
83        found: p.peek().unwrap(),
84        expected: "'|' or end of input",
85    })
86}
87
88/// Validates an already-decoded JSON batch without reapplying the raw DSL byte cap.
89///
90/// This is the typed seam for bounded trusted transports such as
91/// `kkernel exec --ops-file`. The caller must bound the source bytes before
92/// decoding; agent-facing and HTTP/MCP inputs must continue to use
93/// [`parse_request`], which enforces [`MAX_OPS_INPUT_LEN`]. All JSON-form
94/// structural rules remain in force: 1–100 independent operations, bounded
95/// nesting, no `$prev`, and no request-envelope fields inside verb args.
96pub fn parse_typed_json_batch(ops: Vec<TypedJsonOp>) -> Result<ParsedRequest, DslError> {
97    if ops.is_empty() {
98        return Err(DslError::EmptyBatch);
99    }
100    if ops.len() > MAX_OPS {
101        return Err(DslError::TooManyOps {
102            count: ops.len(),
103            max: MAX_OPS,
104        });
105    }
106
107    let mut parsed_ops = Vec::with_capacity(ops.len());
108    for TypedJsonOp { tool, args } in ops {
109        let args_value = Value::Object(args);
110        if !crate::value_nesting_within_limit(&args_value, NESTING_DEPTH_LIMIT - 2) {
111            return Err(DslError::NestingTooDeep {
112                pos: 0,
113                depth: NESTING_DEPTH_LIMIT + 1,
114                max: NESTING_DEPTH_LIMIT,
115            });
116        }
117        let Value::Object(args) = args_value else {
118            unreachable!("typed JSON op args are constructed as an object")
119        };
120        let mut parsed_args = BTreeMap::new();
121        for (name, value) in args {
122            if json_value_contains_prev_ref(&value) {
123                return Err(DslError::PrevRefInJsonForm { arg_name: name });
124            }
125            parsed_args.insert(name, ArgValue::Value(value));
126        }
127        let op = ParsedOp {
128            tool,
129            args: parsed_args,
130        };
131        reject_reserved_args(&op)?;
132        parsed_ops.push(op);
133    }
134
135    Ok(ParsedRequest {
136        ops: parsed_ops,
137        mode: ExecutionMode::Parallel,
138    })
139}
140
141/// Parses a chain tail after its first operation.
142fn parse_chain_tail(mut p: Parser<'_>, first_op: ParsedOp) -> Result<ParsedRequest, DslError> {
143    reject_reserved_args(&first_op)?;
144    let mut ops = vec![first_op];
145    while p.peek() == Some('|') {
146        if ops.len() >= MAX_OPS {
147            return Err(DslError::TooManyOps {
148                count: ops.len() + 1,
149                max: MAX_OPS,
150            });
151        }
152        p.advance(1);
153        p.skip_ws();
154        let op = p.parse_op()?;
155        reject_reserved_args(&op)?;
156        ops.push(op);
157        p.skip_ws();
158    }
159    if !p.eof() {
160        if p.peek() == Some(',') {
161            return Err(DslError::MixedSeparators);
162        }
163        return Err(DslError::UnexpectedChar {
164            pos: p.pos,
165            found: p.peek().unwrap(),
166            expected: "'|' or end of input",
167        });
168    }
169    Ok(ParsedRequest {
170        ops,
171        mode: ExecutionMode::Chain,
172    })
173}
174
175fn parse_json_form(input: &str) -> Result<ParsedRequest, DslError> {
176    // `serde_json::Value` exposes no depth knob, so bound native recursion first.
177    check_json_nesting_depth(input)?;
178    let v: Value = serde_json::from_str(input).map_err(|e| DslError::InvalidJson {
179        error: e.to_string(),
180    })?;
181    let (arr, is_single) = match v {
182        Value::Array(arr) => (arr, false),
183        Value::Object(_) => (vec![v], true),
184        other => {
185            return Err(DslError::InvalidJson {
186                error: format!("expected object or array of objects, got {other}"),
187            })
188        }
189    };
190    if arr.is_empty() && !is_single {
191        return Err(DslError::EmptyBatch);
192    }
193    if arr.len() > MAX_OPS {
194        return Err(DslError::TooManyOps {
195            count: arr.len(),
196            max: MAX_OPS,
197        });
198    }
199    let mut ops = Vec::with_capacity(arr.len());
200    for entry in arr {
201        let obj = entry.as_object().ok_or_else(|| DslError::InvalidJson {
202            error: "each batch entry must be an object".into(),
203        })?;
204        let tool = obj
205            .get("tool")
206            .and_then(Value::as_str)
207            .ok_or_else(|| DslError::InvalidJson {
208                error: "each entry needs a \"tool\" string".into(),
209            })?
210            .to_owned();
211        let args = obj
212            .get("args")
213            .cloned()
214            .unwrap_or_else(|| Value::Object(Map::new()));
215        let args_map = match args {
216            Value::Object(m) => m,
217            other => {
218                return Err(DslError::InvalidJson {
219                    error: format!("\"args\" must be an object, got {other}"),
220                })
221            }
222        };
223        let mut args: BTreeMap<String, ArgValue> = BTreeMap::new();
224        for (k, v) in args_map {
225            if json_value_contains_prev_ref(&v) {
226                return Err(DslError::PrevRefInJsonForm { arg_name: k });
227            }
228            args.insert(k, ArgValue::Value(v));
229        }
230        let op = ParsedOp { tool, args };
231        reject_reserved_args(&op)?;
232        ops.push(op);
233    }
234    let mode = if is_single {
235        ExecutionMode::Single
236    } else {
237        ExecutionMode::Parallel
238    };
239    Ok(ParsedRequest { ops, mode })
240}
241
242fn parse_fn_batch(input: &str) -> Result<ParsedRequest, DslError> {
243    let mut p = Parser::new(input);
244    p.expect_char('[')?;
245    p.skip_ws();
246    let mut ops = Vec::new();
247    if p.peek() == Some(']') {
248        p.advance(1);
249        return Err(DslError::EmptyBatch);
250    }
251    loop {
252        if ops.len() >= MAX_OPS {
253            return Err(DslError::TooManyOps {
254                count: ops.len() + 1,
255                max: MAX_OPS,
256            });
257        }
258        let op = p.parse_op()?;
259        ops.push(op);
260        p.skip_ws();
261        match p.peek() {
262            Some(',') => {
263                let comma_pos = p.pos;
264                p.advance(1);
265                p.skip_ws();
266                if p.peek() == Some(']') {
267                    return Err(DslError::TrailingComma { pos: comma_pos });
268                }
269            }
270            Some(']') => {
271                p.advance(1);
272                break;
273            }
274            Some('|') => return Err(DslError::MixedSeparators),
275            Some(c) => {
276                return Err(DslError::UnexpectedChar {
277                    pos: p.pos,
278                    found: c,
279                    expected: "',' or ']'",
280                });
281            }
282            None => return Err(DslError::UnexpectedEof { expected: "']'" }),
283        }
284    }
285    p.skip_ws();
286    if !p.eof() {
287        return Err(DslError::UnexpectedChar {
288            pos: p.pos,
289            found: p.peek().unwrap(),
290            expected: "end of input",
291        });
292    }
293    for op in &ops {
294        if let Some(pos) = find_prev_ref_pos(op) {
295            return Err(DslError::PrevRefOutsideChain { pos });
296        }
297        reject_reserved_args(op)?;
298    }
299    Ok(ParsedRequest {
300        ops,
301        mode: ExecutionMode::Parallel,
302    })
303}
304
305/// Rejects envelope-only fields inside a verb argument list.
306pub(super) fn reject_reserved_args(op: &ParsedOp) -> Result<(), DslError> {
307    for reserved in RESERVED_ENVELOPE_ARGS {
308        if op.args.contains_key(*reserved) {
309            return Err(DslError::ReservedEnvelopeArg {
310                arg_name: (*reserved).to_owned(),
311                verb: op.tool.clone(),
312            });
313        }
314    }
315    Ok(())
316}