rig 0.45.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
//! The generated agent project: `Cargo.toml`, `src/main.rs` and
//! `.cargo/config.toml` under `$RIG_HOME/project`. Each file is written only
//! when its contents change, so cargo's fingerprints stay valid, and each
//! names the launcher version, so a new launcher rebuilds the agent.

use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};

use rig_harness_protocol::{Home, env};

use super::plugin_list::{PluginList, Source, parse_string};
use super::{Result, VERSION};

/// The generated package's name, and so its binary's.
pub const PACKAGE: &str = "rig-harness-agent";

/// The lock this launcher was built with: the workspace's in a checkout,
/// the `rig` crate's own when installed from crates.io.
const LOCK: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.lock"));

/// Where the agent project gets the `rig-harness` crate from.
pub enum RigSource {
    /// A rig checkout, by path.
    Local(PathBuf),
    /// crates.io, at this launcher's exact version.
    Registry,
}

impl RigSource {
    /// `RIG_SOURCE` when set; else the checkout this launcher was installed
    /// from (`cargo install --path`), when it is still there; else
    /// crates.io. A checkout in cargo's own cache (`cargo install --git`)
    /// does not count: cargo may delete it at any time.
    pub fn detect() -> Result<Self> {
        if let Some(checkout) = std::env::var_os(env::SOURCE).filter(|path| !path.is_empty()) {
            let checkout = std::path::absolute(PathBuf::from(checkout))?;
            if !is_checkout(&checkout) {
                return Err(format!(
                    "RIG_SOURCE={} is not a rig checkout: it has no crates/rig-harness/Cargo.toml",
                    checkout.display()
                )
                .into());
            }
            return Ok(Self::Local(checkout));
        }
        let installed_from = Path::new(env!("CARGO_MANIFEST_DIR"));
        let cargo_home = std::env::var_os("CARGO_HOME")
            .filter(|path| !path.is_empty())
            .map(PathBuf::from)
            .or_else(|| std::env::home_dir().map(|home| home.join(".cargo")));
        let in_cargo_cache = cargo_home.is_some_and(|cargo| installed_from.starts_with(cargo));
        Ok(if is_checkout(installed_from) && !in_cargo_cache {
            Self::Local(installed_from.to_path_buf())
        } else {
            Self::Registry
        })
    }
}

fn is_checkout(path: &Path) -> bool {
    path.join("crates/rig-harness/Cargo.toml").is_file()
}

/// The rig crates every agent has: rig-harness and the rig crates it
/// depends on. A plugin may depend on each, and the agent and its plugins
/// must share them: one copy of each in the agent's dependency graph.
pub const CORE_CRATES: [&str; 7] = [
    "rig-core",
    "rig-ecs",
    "rig-harness",
    "rig-harness-protocol",
    "rig-http",
    "rig-memory",
    "rig-tools",
];

/// The directory of the rig crate `name` in `checkout`: the checkout itself
/// for the `rig` facade, else `crates/<name>` or `plugins/<name>`.
pub fn crate_dir(checkout: &Path, name: &str) -> Option<PathBuf> {
    if name == "rig" {
        return Some(checkout.to_path_buf());
    }
    ["crates", "plugins"]
        .into_iter()
        .map(|folder| checkout.join(folder).join(name))
        .find(|directory| directory.join("Cargo.toml").is_file())
}

/// The rig crates the agent built for `list` uses: [`CORE_CRATES`], the
/// rig crates `list` lists, the rig crates a plugin crate listed by path
/// depends on, and what each of those that is a plugin crate depends on in
/// turn. Without a checkout, [`CORE_CRATES`] and the rig crates listed.
pub fn rig_crates(list: &PluginList, source: &RigSource) -> BTreeSet<String> {
    let mut used: BTreeSet<String> = CORE_CRATES.map(str::to_owned).into();
    let packages = list.plugins.iter().map(|plugin| &plugin.package);
    let RigSource::Local(checkout) = source else {
        let listed = packages.filter(|package| package.source == Source::Rig);
        used.extend(listed.map(|package| package.name.clone()));
        return used;
    };
    let mut pending: Vec<String> = Vec::new();
    for package in packages {
        match &package.source {
            Source::Rig => pending.push(package.name.clone()),
            Source::Path(directory) => pending.extend(dependencies(directory)),
            Source::Git { .. } | Source::Version(_) => {}
        }
    }
    while let Some(name) = pending.pop() {
        let Some(directory) = crate_dir(checkout, &name) else {
            continue;
        };
        if used.insert(name) && directory.starts_with(checkout.join("plugins")) {
            pending.extend(dependencies(&directory));
        }
    }
    used
}

/// The names of the dependencies the crate in `directory` always has: the
/// keys of its `[dependencies]` tables, its target-specific ones included,
/// without the optional ones, each written on one line.
fn dependencies(directory: &Path) -> Vec<String> {
    let Ok(manifest) = fs::read_to_string(directory.join("Cargo.toml")) else {
        return Vec::new();
    };
    let mut names = Vec::new();
    let mut in_dependencies = false;
    for line in manifest.lines().map(str::trim) {
        if let Some(header) = line
            .strip_prefix('[')
            .and_then(|line| line.strip_suffix(']'))
        {
            let header = header.trim();
            in_dependencies = header == "dependencies"
                || (header.starts_with("target.") && header.ends_with(".dependencies"));
            continue;
        }
        let Some((name, value)) = line.split_once('=') else {
            continue;
        };
        if in_dependencies && !line.starts_with('#') && !value.contains("optional = true") {
            names.push(name.trim().trim_matches('"').to_owned());
        }
    }
    names
}

/// The `[patch.crates-io]` table that builds the rig crates `used` from
/// `checkout`, so a plugin that names their crates.io release (as `rig
/// plugin new` writes it) uses the agent's own. It names only crates the
/// agent uses, since cargo warns about a patch nothing uses.
pub fn rig_patch(checkout: &Path, used: &BTreeSet<String>) -> String {
    let mut text = String::from("[patch.crates-io]\n");
    for name in used {
        if let Some(directory) = crate_dir(checkout, name) {
            text.push_str(&format!(
                "{name} = {{ path = {} }}\n",
                quoted_path(&directory)
            ));
        }
    }
    text
}

/// The version of the rig crates the agent is built from: the checkout's
/// workspace version, else this launcher's.
pub fn rig_version(source: &RigSource) -> String {
    let RigSource::Local(checkout) = source else {
        return VERSION.to_owned();
    };
    fs::read_to_string(checkout.join("Cargo.toml"))
        .ok()
        .and_then(|manifest| manifest_string(&manifest, "workspace.package", "version"))
        .unwrap_or_else(|| VERSION.to_owned())
}

/// The string `key` of the table `[table]` of a Cargo manifest, such as the
/// `name` of `[package]`, when it is written as `key = "value"`.
pub fn manifest_string(manifest: &str, table: &str, key: &str) -> Option<String> {
    let mut current = String::new();
    for line in manifest.lines() {
        let line = line.trim();
        if let Some(header) = line
            .strip_prefix('[')
            .and_then(|line| line.strip_suffix(']'))
        {
            current = header.trim().to_owned();
            continue;
        }
        if current != table {
            continue;
        }
        let Some((name, value)) = line.split_once('=') else {
            continue;
        };
        if name.trim() == key {
            return parse_string(value.trim()).map(|(value, _)| value);
        }
    }
    None
}

/// Writes the agent project for `list`.
pub fn generate(home: &Home, list: &PluginList, source: &RigSource) -> Result<()> {
    let project = home.project();
    write_if_changed(&project.join("Cargo.toml"), &manifest(home, list, source)?)?;
    write_if_changed(&project.join("src/main.rs"), &main_rs(home, list, source))?;
    write_if_changed(&project.join(".cargo/config.toml"), &cargo_config(home))?;
    // A lock seeds the versions CI tested: the checkout's, or the one
    // packaged with this launcher. The packaged one covers the `rig` crate's
    // own dependencies only; cargo resolves rig-harness's and Bevy's fresh.
    let lock = project.join("Cargo.lock");
    if !lock.exists() {
        match source {
            RigSource::Local(checkout) => {
                fs::copy(checkout.join("Cargo.lock"), lock)?;
            }
            RigSource::Registry => fs::write(lock, LOCK)?,
        }
    }
    Ok(())
}

fn manifest(home: &Home, list: &PluginList, source: &RigSource) -> Result<String> {
    let mut text = format!(
        "# Generated by rig {VERSION} from {}. `rig build` and /reload rewrite this file.\n\
         [package]\n\
         name = \"{PACKAGE}\"\n\
         version = \"0.0.0\"\n\
         edition = \"2024\"\n\
         publish = false\n\
         \n\
         # Its own workspace, so a RIG_HOME inside another workspace still builds.\n\
         [workspace]\n\
         \n\
         [dependencies]\n",
        home.plugins_toml().display()
    );
    text.push_str(&format!(
        "rig-harness = {{ {} }}\n",
        rig_source(source, "rig-harness")?
    ));
    let mut listed = BTreeSet::new();
    for package in list.plugins.iter().map(|plugin| &plugin.package) {
        // A crate with several plugins is one dependency.
        if !listed.insert(package.name.as_str()) {
            continue;
        }
        let source = match &package.source {
            Source::Path(path) => format!("path = {}", quoted_path(path)),
            Source::Git { url, branch, rev } => {
                let mut source = format!("git = {}", quoted(url));
                if let Some(branch) = branch {
                    source.push_str(&format!(", branch = {}", quoted(branch)));
                }
                if let Some(rev) = rev {
                    source.push_str(&format!(", rev = {}", quoted(rev)));
                }
                source
            }
            Source::Version(version) => format!("version = {}", quoted(version)),
            Source::Rig => rig_source(source, &package.name)?,
        };
        text.push_str(&format!("{} = {{ {source} }}\n", package.name));
    }
    if let RigSource::Local(checkout) = source {
        // A plugin naming the crates.io releases builds against the checkout.
        text.push('\n');
        text.push_str(&rig_patch(checkout, &rig_crates(list, source)));
    }
    text.push_str(&profile(list, source));
    Ok(text)
}

/// The agent's build profile: dependencies at full speed, built once, and
/// the crates `/reload` rebuilds (rig's own from a checkout, and plugins by
/// path or git) at opt-level 1, so a rebuild stays quick.
fn profile(list: &PluginList, source: &RigSource) -> String {
    let mut text = String::from(
        "\n[profile.dev]\ndebug = \"line-tables-only\"\n\
         \n[profile.dev.package.\"*\"]\nopt-level = 3\ndebug-assertions = false\n\
         overflow-checks = false\n",
    );
    let mut edited: BTreeSet<String> = match source {
        RigSource::Local(_) => rig_crates(list, source),
        RigSource::Registry => BTreeSet::new(),
    };
    let packages = list.plugins.iter().map(|plugin| &plugin.package);
    edited.extend(
        packages
            .filter(|package| matches!(package.source, Source::Path(_) | Source::Git { .. }))
            .map(|package| package.name.clone()),
    );
    for name in edited {
        text.push_str(&format!("\n[profile.dev.package.{name}]\nopt-level = 1\n"));
    }
    text
}

/// The dependency source of the rig crate `name`: its directory in the
/// checkout, else this launcher's exact version on crates.io.
fn rig_source(source: &RigSource, name: &str) -> Result<String> {
    Ok(match source {
        RigSource::Local(checkout) => {
            let directory = crate_dir(checkout, name).ok_or_else(|| {
                format!(
                    "plugins.toml lists the crate `{name}` without a source, so as one of rig's \
                     own crates, but the rig checkout {} has no crates/{name} or plugins/{name}; \
                     give it `path`, `git` or `version` if it comes from elsewhere",
                    checkout.display()
                )
            })?;
            format!("path = {}", quoted_path(&directory))
        }
        RigSource::Registry => format!("version = \"={VERSION}\""),
    })
}

/// Where the rig crate `name` comes from, as the agent's `PluginSource`
/// of a plugin names it: `path <directory>` or `version <version>`.
fn rig_origin(source: &RigSource, name: &str) -> String {
    match source {
        RigSource::Local(checkout) => crate_dir(checkout, name)
            .map(|directory| format!("path {}", directory.display()))
            .unwrap_or_default(),
        RigSource::Registry => format!("version {VERSION}"),
    }
}

/// The agent: the harness, then each plugin in the list's order, through
/// `rig_harness::load`, which skips a plugin an earlier one added and
/// records where each comes from; `rig_harness::run` runs it, or describes
/// what its plugins add when the launcher asks.
fn main_rs(home: &Home, list: &PluginList, source: &RigSource) -> String {
    let mut text = format!(
        "// Generated by rig {VERSION} from {}. /reload rewrites this file.\n\
         fn main() -> rig_harness::AppExit {{\n    \
             let mut app = rig_harness::App::new();\n    \
             // A failing system, observer or command from a plugin is logged.\n    \
             app.set_error_handler(rig_harness::error::warn);\n    \
             // Bevy's base and the headless loop come first, so the agent runs on\n    \
             // their clock and a windowing plugin listed below can replace the loop.\n    \
             app.add_plugins((rig_harness::HeadlessPlugins, rig_harness::RigHarnessPlugins));\n",
        home.plugins_toml().display(),
    );
    for plugin in &list.plugins {
        let package = &plugin.package;
        let krate = package.name.as_str();
        let from = match &package.source {
            Source::Rig => rig_origin(source, krate),
            other => other.to_string(),
        };
        text.push_str(&format!(
            "    rig_harness::load::<{}>(&mut app, {krate:?}, {from:?});\n",
            plugin.type_path
        ));
    }
    text.push_str(
        "    // A debug build warns at start of agent-loop systems left unordered.\n    \
         #[cfg(debug_assertions)]\n    \
         rig_harness::check_stages_at_start(&mut app);\n",
    );
    // Runs the app, or describes it when the launcher asks.
    text.push_str("    rig_harness::run(app)\n}\n");
    text
}

/// cargo's settings: the target directory. `CARGO_BUILD_JOBS` sets the
/// jobs, as for any cargo build.
fn cargo_config(home: &Home) -> String {
    format!(
        "# Generated by rig {VERSION}.\n[build]\ntarget-dir = {}\n",
        quoted_path(&home.target())
    )
}

/// Writes `contents` to `path` unless it already holds them.
pub fn write_if_changed(path: &Path, contents: &str) -> Result<()> {
    if fs::read_to_string(path).is_ok_and(|current| current == contents) {
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, contents)?;
    Ok(())
}

/// `path` as a TOML basic string.
pub fn quoted_path(path: &Path) -> String {
    quoted(&path.to_string_lossy())
}

/// A TOML basic string.
pub fn quoted(text: &str) -> String {
    let mut quoted = String::from("\"");
    for c in text.chars() {
        match c {
            '"' => quoted.push_str("\\\""),
            '\\' => quoted.push_str("\\\\"),
            c if c.is_control() => quoted.push_str(&format!("\\u{:04X}", u32::from(c))),
            c => quoted.push(c),
        }
    }
    quoted.push('"');
    quoted
}

#[cfg(test)]
mod tests;