tinyagents 1.0.0

A recursive language-model (RLM) harness for Rust.
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
//! Parser: turns a [`SpannedToken`] stream into a [`Program`] AST.
//!
//! Middle stage of the `.rag` pipeline. It gives a declarative (possibly
//! self-authored) plan its tree shape without granting it any power: the grammar
//! admits only graph/node/route/capability *declarations*, so there is no place
//! for arbitrary code to hide — the structural counterpart to the registry
//! binding that [`crate::language::compiler`] enforces later.
//!
//! The parser is a small hand-written recursive-descent parser over the
//! grammar described in `docs/modules/expressive-language/README.md`. It
//! performs *structural* validation only (expected-token checks, well-formed
//! blocks); *semantic* validation (duplicate names, unknown targets, …) is the
//! job of [`crate::language::compiler`].

use crate::error::{Result, TinyAgentsError};
use crate::language::diagnostic::Diagnostic;
use crate::language::source::SourceFile;
use crate::language::types::{
    ChannelDecl, CommandDecl, EdgeDecl, GraphDecl, IoFieldDecl, JoinDecl, Literal, NodeDecl,
    Program, RouteDecl, SendDecl, Span, SpannedToken, Token,
};

/// Tokenises and parses `source` in one step.
///
/// Parse errors carry a caret-underline rendering of the offending source.
///
/// # Errors
///
/// Returns [`TinyAgentsError::Parse`] for any lexical or structural error.
pub fn parse_str(source: &str) -> Result<Program> {
    let file = SourceFile::anonymous(source);
    let tokens = crate::language::lexer::tokenize(source)?;
    Parser {
        tokens: &tokens,
        pos: 0,
        source: Some(&file),
    }
    .parse_program()
}

/// Parses a token slice produced by [`crate::language::lexer::tokenize`].
///
/// Without the original source text, parse errors render a source-free
/// presentation (headline plus `line:column` anchor). Use [`parse_str`] to get
/// caret-underlined diagnostics.
///
/// # Errors
///
/// Returns [`TinyAgentsError::Parse`] when the token stream does not match the
/// grammar, with the span of the offending token.
pub fn parse(tokens: &[SpannedToken]) -> Result<Program> {
    Parser {
        tokens,
        pos: 0,
        source: None,
    }
    .parse_program()
}

struct Parser<'a> {
    tokens: &'a [SpannedToken],
    pos: usize,
    source: Option<&'a SourceFile>,
}

impl Parser<'_> {
    // ---- token cursor helpers -------------------------------------------

    fn current(&self) -> &SpannedToken {
        // The lexer always appends an `Eof`, so the last token is a valid
        // sentinel even once `pos` reaches the end.
        &self.tokens[self.pos.min(self.tokens.len() - 1)]
    }

    fn span(&self) -> Span {
        self.current().span
    }

    fn at_eof(&self) -> bool {
        matches!(self.current().token, Token::Eof)
    }

    fn advance(&mut self) -> SpannedToken {
        let tok = self.current().clone();
        if self.pos < self.tokens.len() - 1 {
            self.pos += 1;
        }
        tok
    }

    fn error(&self, message: impl Into<String>, span: Span) -> TinyAgentsError {
        Diagnostic::error(message, span)
            .with_primary_label("here")
            .into_parse_error(self.source)
    }

    /// Expects an exact punctuation/structural token.
    fn expect(&mut self, expected: &Token) -> Result<Span> {
        let tok = self.current().clone();
        if &tok.token == expected {
            self.advance();
            Ok(tok.span)
        } else {
            Err(self.error(
                format!(
                    "expected {}, found {}",
                    expected.describe(),
                    tok.token.describe()
                ),
                tok.span,
            ))
        }
    }

    /// Expects an identifier and returns its text.
    fn expect_ident(&mut self) -> Result<(String, Span)> {
        let tok = self.current().clone();
        match tok.token {
            Token::Ident(s) => {
                self.advance();
                Ok((s, tok.span))
            }
            other => Err(self.error(
                format!("expected identifier, found {}", other.describe()),
                tok.span,
            )),
        }
    }

    /// Expects a string literal and returns its value.
    fn expect_string(&mut self) -> Result<String> {
        let tok = self.current().clone();
        match tok.token {
            Token::Str(s) => {
                self.advance();
                Ok(s)
            }
            other => Err(self.error(
                format!("expected string, found {}", other.describe()),
                tok.span,
            )),
        }
    }

    /// Expects an identifier with a specific keyword spelling.
    fn expect_keyword(&mut self, keyword: &str) -> Result<Span> {
        let tok = self.current().clone();
        match &tok.token {
            Token::Ident(s) if s == keyword => {
                self.advance();
                Ok(tok.span)
            }
            other => Err(self.error(
                format!("expected `{keyword}`, found {}", other.describe()),
                tok.span,
            )),
        }
    }

    fn is_keyword(&self, keyword: &str) -> bool {
        matches!(&self.current().token, Token::Ident(s) if s == keyword)
    }

    // ---- grammar productions --------------------------------------------

    fn parse_program(&mut self) -> Result<Program> {
        let mut graphs = Vec::new();
        while !self.at_eof() {
            graphs.push(self.parse_graph()?);
        }
        Ok(Program { graphs })
    }

    fn parse_graph(&mut self) -> Result<GraphDecl> {
        let span = self.expect_keyword("graph")?;
        let (name, _) = self.expect_ident()?;
        self.expect(&Token::LBrace)?;

        let mut graph = GraphDecl {
            name,
            span,
            start: None,
            defaults: Vec::new(),
            input: Vec::new(),
            output: Vec::new(),
            checkpoint: None,
            interrupt: None,
            channels: Vec::new(),
            nodes: Vec::new(),
            edges: Vec::new(),
            joins: Vec::new(),
        };

        while !matches!(self.current().token, Token::RBrace) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside graph body", self.span()));
            }
            self.parse_graph_item(&mut graph)?;
        }
        self.expect(&Token::RBrace)?;
        Ok(graph)
    }

    fn parse_graph_item(&mut self, graph: &mut GraphDecl) -> Result<()> {
        if self.is_keyword("start") {
            self.advance();
            let (name, _) = self.expect_ident()?;
            graph.start = Some(name);
        } else if self.is_keyword("defaults") {
            self.advance();
            graph.defaults = self.parse_defaults_block()?;
        } else if self.is_keyword("input") {
            self.advance();
            graph.input = self.parse_io_shape_block()?;
        } else if self.is_keyword("output") {
            self.advance();
            graph.output = self.parse_io_shape_block()?;
        } else if self.is_keyword("checkpoint") {
            self.advance();
            let (policy, _) = self.expect_ident()?;
            graph.checkpoint = Some(policy);
        } else if self.is_keyword("interrupt") {
            self.advance();
            let (policy, _) = self.expect_ident()?;
            graph.interrupt = Some(policy);
        } else if self.is_keyword("channel") {
            graph.channels.push(self.parse_channel()?);
        } else if self.is_keyword("join") {
            graph.joins.push(self.parse_join()?);
        } else if self.is_keyword("node") {
            graph.nodes.push(self.parse_node()?);
        } else {
            // The only remaining production is an edge: `ident -> target`.
            graph.edges.push(self.parse_edge()?);
        }
        Ok(())
    }

    fn parse_defaults_block(&mut self) -> Result<Vec<(String, Literal)>> {
        self.expect(&Token::LBrace)?;
        let mut entries = Vec::new();
        while !matches!(self.current().token, Token::RBrace) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside `defaults`", self.span()));
            }
            let (key, _) = self.expect_ident()?;
            let value = self.parse_literal()?;
            entries.push((key, value));
        }
        self.expect(&Token::RBrace)?;
        Ok(entries)
    }

    fn parse_literal(&mut self) -> Result<Literal> {
        let tok = self.current().clone();
        match tok.token {
            Token::Str(s) => {
                self.advance();
                Ok(Literal::Str(s))
            }
            Token::Num(n) => {
                self.advance();
                Ok(Literal::Num(n))
            }
            Token::Ident(s) => {
                self.advance();
                Ok(Literal::Ident(s))
            }
            other => Err(self.error(
                format!("expected a literal value, found {}", other.describe()),
                tok.span,
            )),
        }
    }

    fn parse_channel(&mut self) -> Result<ChannelDecl> {
        let span = self.expect_keyword("channel")?;
        let (name, _) = self.expect_ident()?;
        let (reducer, _) = self.expect_ident()?;
        // Optional reducer policy arguments. Restricted to string/number
        // literals so they cannot be confused with the next declaration's
        // leading keyword (e.g. `node`, `channel`).
        let mut args = Vec::new();
        loop {
            match &self.current().token {
                Token::Str(s) => {
                    let s = s.clone();
                    self.advance();
                    args.push(Literal::Str(s));
                }
                Token::Num(n) => {
                    let n = *n;
                    self.advance();
                    args.push(Literal::Num(n));
                }
                _ => break,
            }
        }
        Ok(ChannelDecl {
            name,
            reducer,
            args,
            span,
        })
    }

    /// Parses a graph `input`/`output` shape block: `{ name type … }`.
    fn parse_io_shape_block(&mut self) -> Result<Vec<IoFieldDecl>> {
        self.expect(&Token::LBrace)?;
        let mut fields = Vec::new();
        while !matches!(self.current().token, Token::RBrace) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside shape block", self.span()));
            }
            let (name, span) = self.expect_ident()?;
            let (ty, _) = self.expect_ident()?;
            fields.push(IoFieldDecl { name, ty, span });
        }
        self.expect(&Token::RBrace)?;
        Ok(fields)
    }

    /// Parses a top-level `join [a, b] -> c` declaration.
    fn parse_join(&mut self) -> Result<JoinDecl> {
        let span = self.expect_keyword("join")?;
        let sources = self.parse_ident_list()?;
        self.expect(&Token::Arrow)?;
        let target = self.parse_node_ref()?;
        Ok(JoinDecl {
            sources,
            target,
            span,
        })
    }

    /// Parses a bracketed, comma-separated identifier list: `[a, b, c]`.
    fn parse_ident_list(&mut self) -> Result<Vec<String>> {
        self.expect(&Token::LBracket)?;
        let mut items = Vec::new();
        while !matches!(self.current().token, Token::RBracket) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside list", self.span()));
            }
            let (name, _) = self.expect_ident()?;
            items.push(name);
            if matches!(self.current().token, Token::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        self.expect(&Token::RBracket)?;
        Ok(items)
    }

    fn parse_edge(&mut self) -> Result<EdgeDecl> {
        let (from, span) = self.expect_ident()?;
        self.expect(&Token::Arrow)?;
        let to = self.parse_node_ref()?;
        Ok(EdgeDecl { from, to, span })
    }

    /// Parses a node reference: an identifier or the reserved `END`.
    fn parse_node_ref(&mut self) -> Result<String> {
        let (name, _) = self.expect_ident()?;
        Ok(name)
    }

    fn parse_node(&mut self) -> Result<NodeDecl> {
        let span = self.expect_keyword("node")?;
        let (name, _) = self.expect_ident()?;
        self.expect(&Token::LBrace)?;

        let mut node = NodeDecl::empty(name, span);

        while !matches!(self.current().token, Token::RBrace) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside node body", self.span()));
            }
            self.parse_node_item(&mut node)?;
        }
        self.expect(&Token::RBrace)?;
        Ok(node)
    }

    fn parse_node_item(&mut self, node: &mut NodeDecl) -> Result<()> {
        let tok = self.current().clone();
        let Token::Ident(keyword) = &tok.token else {
            return Err(self.error(
                format!(
                    "expected a node item keyword, found {}",
                    tok.token.describe()
                ),
                tok.span,
            ));
        };

        match keyword.as_str() {
            "kind" => {
                self.advance();
                let (k, _) = self.expect_ident()?;
                node.kind = Some(k);
            }
            "model" => {
                self.advance();
                node.model = Some(self.expect_string()?);
            }
            // `prompt` and `system` both populate the node prompt; `system`
            // is accepted as an alias for forward compatibility.
            "prompt" | "system" => {
                self.advance();
                node.prompt = Some(self.expect_string()?);
            }
            "tools" => {
                self.advance();
                node.tools = self.parse_string_list()?;
            }
            "next" => {
                self.advance();
                node.next = Some(self.parse_node_ref()?);
            }
            "routes" => {
                self.advance();
                node.routes = self.parse_routes_block()?;
            }
            "agent" => {
                self.advance();
                node.agent = Some(self.expect_string()?);
            }
            "graph" => {
                self.advance();
                node.graph = Some(self.expect_string()?);
            }
            "script" => {
                self.advance();
                node.script = Some(self.expect_string()?);
            }
            "input" => {
                self.advance();
                node.input = Some(self.expect_string()?);
            }
            "command" => {
                self.advance();
                node.command = Some(self.parse_command_block()?);
            }
            "sends" => {
                self.advance();
                node.sends = self.parse_sends_block()?;
            }
            "sources" => {
                self.advance();
                node.sources = self.parse_ident_list()?;
            }
            "options" => {
                self.advance();
                node.options = self.parse_string_list()?;
            }
            "checkpoint" => {
                self.advance();
                let (policy, _) = self.expect_ident()?;
                node.checkpoint = Some(policy);
            }
            "timeout" => {
                self.advance();
                node.timeout = Some(self.parse_literal()?);
            }
            "retry" => {
                self.advance();
                node.retry = self.parse_defaults_block()?;
            }
            "metadata" => {
                self.advance();
                node.metadata = self.parse_defaults_block()?;
            }
            other => {
                return Err(self.error(format!("unknown node item `{other}`"), tok.span));
            }
        }
        Ok(())
    }

    fn parse_string_list(&mut self) -> Result<Vec<String>> {
        self.expect(&Token::LBracket)?;
        let mut items = Vec::new();
        while !matches!(self.current().token, Token::RBracket) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside list", self.span()));
            }
            items.push(self.expect_string()?);
            // Optional comma separator.
            if matches!(self.current().token, Token::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        self.expect(&Token::RBracket)?;
        Ok(items)
    }

    /// Parses a `command { goto <target> update { … } }` block. The `command`
    /// keyword has already been consumed.
    fn parse_command_block(&mut self) -> Result<CommandDecl> {
        let span = self.span();
        self.expect(&Token::LBrace)?;
        let mut goto = None;
        let mut update = Vec::new();
        while !matches!(self.current().token, Token::RBrace) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside `command`", self.span()));
            }
            if self.is_keyword("goto") {
                self.advance();
                goto = Some(self.parse_node_ref()?);
            } else if self.is_keyword("update") {
                self.advance();
                update = self.parse_defaults_block()?;
            } else {
                return Err(self.error("expected `goto` or `update` inside `command`", self.span()));
            }
        }
        self.expect(&Token::RBrace)?;
        Ok(CommandDecl { goto, update, span })
    }

    /// Parses a `sends [ send <node> ["input"] … ]` block. The `sends` keyword
    /// has already been consumed.
    fn parse_sends_block(&mut self) -> Result<Vec<SendDecl>> {
        self.expect(&Token::LBracket)?;
        let mut sends = Vec::new();
        while !matches!(self.current().token, Token::RBracket) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside `sends`", self.span()));
            }
            let span = self.expect_keyword("send")?;
            let target = self.parse_node_ref()?;
            let input = if matches!(self.current().token, Token::Str(_)) {
                Some(self.expect_string()?)
            } else {
                None
            };
            sends.push(SendDecl {
                target,
                input,
                span,
            });
            if matches!(self.current().token, Token::Comma) {
                self.advance();
            }
        }
        self.expect(&Token::RBracket)?;
        Ok(sends)
    }

    fn parse_routes_block(&mut self) -> Result<Vec<RouteDecl>> {
        self.expect(&Token::LBrace)?;
        let mut routes = Vec::new();
        while !matches!(self.current().token, Token::RBrace) {
            if self.at_eof() {
                return Err(self.error("unexpected end of input inside `routes`", self.span()));
            }
            let (label, span) = self.expect_ident()?;
            self.expect(&Token::Arrow)?;
            let target = self.parse_node_ref()?;
            routes.push(RouteDecl {
                label,
                target,
                span,
            });
        }
        self.expect(&Token::RBrace)?;
        Ok(routes)
    }
}