rig 0.46.0

An opinionated library for building LLM powered applications.
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
//! `plugins.toml`: the plugin list. The file is a small TOML subset:
//! comments and `[[plugin]]` tables whose keys hold a string.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use super::Result;
use super::project::PACKAGE;

/// Written when `plugins.toml` does not exist yet.
pub(super) const TEMPLATE: &str = include_str!("plugins.toml");

/// The parsed plugin list.
pub struct PluginList {
    /// The plugins, in file order.
    pub plugins: Vec<PluginEntry>,
}

/// One `[[plugin]]` table.
pub struct PluginEntry {
    /// The plugin type's path, such as `rig_hello::HelloPlugin`.
    pub type_path: String,
    /// The package that provides it.
    pub package: Package,
}

/// A plugin package.
pub struct Package {
    /// The package name.
    pub name: String,
    /// Where it comes from.
    pub source: Source,
}

/// Where a plugin package comes from.
#[derive(PartialEq, Eq, Debug)]
pub enum Source {
    /// A local directory, made absolute against the directory of
    /// `plugins.toml`.
    Path(PathBuf),
    /// A git repository, optionally at a branch or revision.
    Git {
        /// The repository URL.
        url: String,
        /// The branch.
        branch: Option<String>,
        /// The revision.
        rev: Option<String>,
    },
    /// A crates.io version requirement.
    Version(String),
    /// One of rig's own crates, such as `rig-tui`, from where the agent's
    /// rig crates come from: the rig checkout, else crates.io at this
    /// launcher's version.
    Rig,
}

impl fmt::Display for Source {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Path(path) => write!(f, "path {}", path.display()),
            Self::Git { url, branch, rev } => {
                write!(f, "git {url}")?;
                if let Some(branch) = branch {
                    write!(f, ", branch {branch}")?;
                }
                if let Some(rev) = rev {
                    write!(f, ", rev {rev}")?;
                }
                Ok(())
            }
            Self::Version(version) => write!(f, "version {version}"),
            Self::Rig => write!(f, "rig"),
        }
    }
}

impl PluginList {
    /// Reads `path`, writing a commented template first when it does not
    /// exist. Errors name the file and line.
    pub fn load(path: &Path) -> Result<Self> {
        let text = match fs::read_to_string(path) {
            Ok(text) => text,
            Err(failure) if failure.kind() == ErrorKind::NotFound => {
                if let Some(parent) = path.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::write(path, TEMPLATE)?;
                TEMPLATE.to_owned()
            }
            Err(failure) => return Err(format!("{}: {failure}", path.display()).into()),
        };
        parse_file(path, &text)
    }
}

/// The crates of the plugins rig ships, which the default list names.
pub fn shipped() -> BTreeSet<String> {
    entries(TEMPLATE, Path::new("/"))
        .unwrap_or_default()
        .into_iter()
        .map(|listed| listed.entry.package.name)
        .collect()
}

/// Parses `text` as the plugin list at `path`: relative plugin paths are
/// relative to its directory, and errors name it.
fn parse_file(path: &Path, text: &str) -> Result<PluginList> {
    let base = path.parent().unwrap_or(Path::new("."));
    parse(text, base).map_err(|failure| format!("{}: {failure}", path.display()).into())
}

/// Adds `entry`, the text of one `[[plugin]]` table, at the end of the
/// plugin list at `path` (made from the template when missing), and
/// checks the result, then with `check`; nothing is written when either
/// fails.
pub fn append(
    path: &Path,
    entry: &str,
    check: impl FnOnce(&PluginList) -> Result<()>,
) -> Result<PluginList> {
    PluginList::load(path)?;
    let mut text = fs::read_to_string(path)?;
    if !text.is_empty() && !text.ends_with('\n') {
        text.push('\n');
    }
    text.push('\n');
    text.push_str(entry);
    let list = parse_file(path, &text)?;
    check(&list).map_err(|failure| format!("{}: {failure}", path.display()))?;
    fs::write(path, text)?;
    Ok(list)
}

/// Takes the `[[plugin]]` table whose `plugin` is `type_path` out of the
/// plugin list at `path`, with the comment lines right above it, and checks
/// the result; nothing is written when it is not valid.
pub fn remove(path: &Path, type_path: &str) -> Result<()> {
    let text =
        fs::read_to_string(path).map_err(|failure| format!("{}: {failure}", path.display()))?;
    let base = path.parent().unwrap_or(Path::new("."));
    let kept = without_table(&text, type_path, base)
        .map_err(|failure| format!("{}: {failure}", path.display()))?;
    parse_file(path, &kept)?;
    fs::write(path, kept)?;
    Ok(())
}

/// `text` without the table of `type_path` and the comment lines right
/// above it.
fn without_table(text: &str, type_path: &str, base: &Path) -> Result<String> {
    let list = parse(text, base)?;
    let Some(index) = list
        .plugins
        .iter()
        .position(|plugin| plugin.type_path == type_path)
    else {
        return Err(format!("`{type_path}` is not listed").into());
    };
    let lines: Vec<&str> = text.lines().collect();
    let headers: Vec<usize> = lines
        .iter()
        .enumerate()
        .filter(|(_, line)| without_comment(line).trim() == "[[plugin]]")
        .map(|(number, _)| number)
        .collect();
    let start = headers
        .get(index)
        .copied()
        .ok_or("the table is not found")?;
    let mut end = headers.get(index + 1).copied().unwrap_or(lines.len());
    // Comments right above the next table are that table's.
    while end > start + 1
        && lines
            .get(end - 1)
            .is_some_and(|line| without_comment(line).trim().is_empty())
    {
        end -= 1;
    }
    let mut from = start;
    while from > 0
        && lines
            .get(from - 1)
            .is_some_and(|line| line.trim_start().starts_with('#'))
    {
        from -= 1;
    }
    let mut kept: Vec<&str> = lines.get(..from).unwrap_or_default().to_vec();
    kept.extend(lines.get(end..).unwrap_or_default());
    // No run of blank lines where the table was.
    if kept.get(from).is_some_and(|line| line.trim().is_empty())
        && from
            .checked_sub(1)
            .and_then(|before| kept.get(before))
            .is_some_and(|line| line.trim().is_empty())
    {
        kept.remove(from);
    }
    let mut kept = kept.join("\n");
    kept.push('\n');
    Ok(kept)
}

/// One entry of the plugin list, enabled or disabled, as `rig plugin list`
/// shows it.
pub struct Listed {
    /// The entry.
    pub entry: PluginEntry,
    /// Whether it is an active `[[plugin]]` table; a disabled one is
    /// commented out, its `[[plugin]]` line and keys each behind `# `.
    pub enabled: bool,
    /// The comment lines right above it, joined.
    pub description: String,
    /// Its `[[plugin]]` line and the key lines right after it.
    lines: std::ops::Range<usize>,
}

/// The keys a `[[plugin]]` table may hold.
const KEYS: [&str; 7] = ["plugin", "crate", "path", "git", "branch", "rev", "version"];

/// Every entry of the plugin list at `path` (made from the template when
/// missing), enabled and disabled, in file order.
pub fn listed(path: &Path) -> Result<Vec<Listed>> {
    PluginList::load(path)?;
    let text = fs::read_to_string(path)?;
    let base = path.parent().unwrap_or(Path::new("."));
    entries(&text, base).map_err(|failure| format!("{}: {failure}", path.display()).into())
}

/// Enables or disables the entry of `type_path` in the plugin list at
/// `path` by uncommenting or commenting out its `[[plugin]]` line and the
/// key lines after it, keeping every other byte, so disabling and enabling
/// again gives back the same file. Nothing is written unless the result
/// lists exactly the same other plugins. Returns whether anything changed.
pub fn set_enabled(path: &Path, type_path: &str, enabled: bool) -> Result<bool> {
    let text =
        fs::read_to_string(path).map_err(|failure| format!("{}: {failure}", path.display()))?;
    let base = path.parent().unwrap_or(Path::new("."));
    let toggled = toggled(&text, type_path, enabled, base)
        .map_err(|failure| format!("{}: {failure}", path.display()))?;
    let Some(toggled) = toggled else {
        return Ok(false);
    };
    fs::write(path, toggled)?;
    Ok(true)
}

/// `text` with the entry of `type_path` enabled or disabled, or `None`
/// when it already is.
fn toggled(text: &str, type_path: &str, enabled: bool, base: &Path) -> Result<Option<String>> {
    let listed = entries(text, base)?;
    let of_type = |state: bool| {
        listed
            .iter()
            .find(|listed| listed.entry.type_path == type_path && listed.enabled == state)
    };
    if of_type(enabled).is_some() {
        return Ok(None);
    }
    let Some(entry) = of_type(!enabled) else {
        return Err(format!(
            "`{type_path}` is not listed; `rig plugin add` adds it, and `rig plugin list` \
             shows what is"
        )
        .into());
    };
    let mut toggled = String::with_capacity(text.len() + 32);
    for (number, line) in text.split_inclusive('\n').enumerate() {
        match (entry.lines.contains(&number), enabled) {
            (false, _) => toggled.push_str(line),
            (true, true) => toggled.push_str(&uncommented(line)),
            (true, false) => {
                toggled.push_str("# ");
                toggled.push_str(line);
            }
        }
    }
    // Every other plugin stays as it was, whatever the layout of the file.
    let others = |text: &str| -> Result<Vec<String>> {
        Ok(parse(text, base)?
            .plugins
            .into_iter()
            .filter(|plugin| plugin.type_path != type_path)
            .map(|plugin| {
                format!(
                    "{} {} {}",
                    plugin.type_path, plugin.package.name, plugin.package.source
                )
            })
            .collect())
    };
    let now = parse(&toggled, base)?;
    if others(&toggled)? != others(text)?
        || now
            .plugins
            .iter()
            .any(|plugin| plugin.type_path == type_path)
            != enabled
    {
        return Err(format!(
            "`{type_path}`'s entry is laid out so that toggling it would change other entries; \
             edit it by hand"
        )
        .into());
    }
    Ok(Some(toggled))
}

/// The entries of `text`, enabled and disabled, in order. A commented-out
/// block is a disabled entry only when uncommented it is a whole valid
/// table; any other comment is a comment.
fn entries(text: &str, base: &Path) -> Result<Vec<Listed>> {
    let active = parse(text, base)?.plugins;
    let mut active = active.into_iter();
    let lines: Vec<&str> = text.lines().collect();
    let mut listed = Vec::new();
    for (number, line) in lines.iter().enumerate() {
        let after = lines.get(number + 1..).unwrap_or_default();
        let (entry, keys, enabled) = if without_comment(line).trim() == "[[plugin]]" {
            let keys = after
                .iter()
                .take_while(|line| {
                    let line = without_comment(line).trim();
                    !line.is_empty() && line != "[[plugin]]"
                })
                .count();
            let Some(entry) = active.next() else {
                break;
            };
            (entry, keys, true)
        } else if commented(line).is_some_and(|rest| without_comment(rest).trim() == "[[plugin]]") {
            let keys = after.iter().take_while(|line| commented_key(line)).count();
            let mut table = String::from("[[plugin]]\n");
            for key in after.iter().take(keys) {
                table.push_str(&uncommented(key));
                table.push('\n');
            }
            let Some(entry) = parse(&table, base)
                .ok()
                .and_then(|table| table.plugins.into_iter().next())
            else {
                continue;
            };
            (entry, keys, false)
        } else {
            continue;
        };
        let above = lines.get(..number).unwrap_or_default();
        let comments: Vec<&str> = above
            .iter()
            .rev()
            .take_while(|line| {
                line.trim_start().starts_with('#')
                    && !commented_key(line)
                    && commented(line).is_none_or(|rest| rest.trim() != "[[plugin]]")
            })
            .filter_map(|line| commented(line))
            .map(str::trim)
            .collect();
        let description = comments.into_iter().rev().collect::<Vec<_>>().join(" ");
        listed.push(Listed {
            entry,
            enabled,
            description,
            lines: number..number + 1 + keys,
        });
    }
    Ok(listed)
}

/// The text after the `#` of a comment line.
fn commented(line: &str) -> Option<&str> {
    line.trim_start().strip_prefix('#')
}

/// Whether `line` is a commented-out `key = "value"` of a table.
fn commented_key(line: &str) -> bool {
    commented(line)
        .and_then(|rest| without_comment(rest).split_once('='))
        .is_some_and(|(key, value)| {
            KEYS.contains(&key.trim()) && parse_value(value.trim()).is_some()
        })
}

/// `line` without its first `#` and the space after it.
fn uncommented(line: &str) -> String {
    match line.split_once('#') {
        Some((before, after)) => format!("{before}{}", after.strip_prefix(' ').unwrap_or(after)),
        None => line.to_owned(),
    }
}

/// Parses `text`; relative plugin paths are relative to `base`.
pub(super) fn parse(text: &str, base: &Path) -> Result<PluginList> {
    let mut tables: Vec<(usize, BTreeMap<String, String>)> = Vec::new();
    for (number, line) in (1..).zip(text.lines()) {
        let line = without_comment(line).trim();
        if line.is_empty() {
            continue;
        }
        if line == "[[plugin]]" {
            tables.push((number, BTreeMap::new()));
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            return Err(format!("line {number}: expected `key = value` or `[[plugin]]`").into());
        };
        let key = key.trim();
        let value = parse_value(value.trim())
            .ok_or_else(|| format!("line {number}: `{}` is not a string", value.trim()))?;
        let Some((_, table)) = tables.last_mut() else {
            return Err(format!("line {number}: `{key}` comes before the first [[plugin]]").into());
        };
        if table.insert(key.to_owned(), value).is_some() {
            return Err(format!("line {number}: `{key}` is set twice").into());
        }
    }
    let mut plugins: Vec<PluginEntry> = Vec::new();
    let mut types = BTreeSet::new();
    for (number, table) in tables {
        let plugin = plugin(table, base)
            .and_then(|plugin| {
                if !types.insert(plugin.type_path.clone()) {
                    return Err(format!("`{}` is listed twice", plugin.type_path).into());
                }
                let package = &plugin.package;
                if plugins.iter().any(|listed| {
                    listed.package.name == package.name && listed.package.source != package.source
                }) {
                    return Err(
                        format!("`{}` is listed before with another source", package.name).into(),
                    );
                }
                Ok(plugin)
            })
            .map_err(|failure| format!("[[plugin]] at line {number}: {failure}"))?;
        plugins.push(plugin);
    }
    Ok(PluginList { plugins })
}

fn plugin(mut table: BTreeMap<String, String>, base: &Path) -> Result<PluginEntry> {
    let type_path = table
        .remove("plugin")
        .ok_or("`plugin` (the type path) is missing")?;
    if !type_path.split("::").all(|segment| {
        segment.chars().next().is_some_and(|c| !c.is_ascii_digit())
            && segment
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_')
    }) {
        return Err(format!("`{type_path}` is not a Rust type path").into());
    }
    let path = table.remove("path");
    let git = table.remove("git");
    let version = table.remove("version");
    let branch = table.remove("branch");
    let rev = table.remove("rev");
    let name = table
        .remove("crate")
        .ok_or("`crate` (the package name) is missing")?;
    if name.is_empty()
        || !name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        return Err(format!("`{name}` is not a crate name").into());
    }
    let source = match (path, git, version) {
        (None, Some(url), None) => Source::Git { url, branch, rev },
        _ if branch.is_some() || rev.is_some() => {
            return Err("`branch` and `rev` only go with `git`".into());
        }
        (Some(path), None, None) => {
            let path = base.join(path);
            Source::Path(std::path::absolute(&path).unwrap_or(path))
        }
        (None, None, Some(version)) => Source::Version(version),
        (None, None, None) => Source::Rig,
        _ => return Err("set at most one of `path`, `git` and `version`".into()),
    };
    let package = Package { name, source };
    if ["rig-harness", PACKAGE, "bevy"].contains(&package.name.as_str()) {
        return Err(format!("`{}` is part of the agent itself", package.name).into());
    }
    if let Some(key) = table.keys().next() {
        return Err(format!("unknown key `{key}`").into());
    }
    Ok(PluginEntry { type_path, package })
}

/// The line up to a `#` that is not inside a string.
fn without_comment(line: &str) -> &str {
    let mut in_string = false;
    let mut escaped = false;
    for (index, c) in line.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' if in_string => escaped = true,
            '"' => in_string = !in_string,
            '#' if !in_string => return line.get(..index).unwrap_or(line),
            _ => {}
        }
    }
    line
}

/// A value that is one basic TOML string.
fn parse_value(text: &str) -> Option<String> {
    let (value, rest) = parse_string(text)?;
    rest.trim().is_empty().then_some(value)
}

/// A basic TOML string at the start of `text`, and the text after it.
/// Its escapes are `\n`, `\t`, `\"`, `\\` and a code point as `\uXXXX` or
/// `\UXXXXXXXX`, which [`quoted`](super::project::quoted) writes.
pub fn parse_string(text: &str) -> Option<(String, &str)> {
    let mut chars = text.strip_prefix('"')?.char_indices();
    let mut value = String::new();
    while let Some((index, c)) = chars.next() {
        match c {
            '"' => return Some((value, text.get(index + 2..)?)),
            '\\' => value.push(match chars.next()?.1 {
                'n' => '\n',
                't' => '\t',
                '"' => '"',
                '\\' => '\\',
                escape @ ('u' | 'U') => {
                    let digits = if escape == 'u' { 4 } else { 8 };
                    let hex: String = chars.by_ref().take(digits).map(|(_, c)| c).collect();
                    if hex.len() != digits || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
                        return None;
                    }
                    char::from_u32(u32::from_str_radix(&hex, 16).ok()?)?
                }
                _ => return None,
            }),
            c => value.push(c),
        }
    }
    None
}

#[cfg(test)]
mod tests;