argonauts-app 0.1.0

Argonauts Code's app controller and run host: the conversation, routing, choosing Captain or crew, and the run host each run has.
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
//! The CLI adapters beyond the built-in four: the `[[cli]]` entries the registry
//! accepts, with your `agents.<id>.binary` in place of theirs, and the built-in home templates
//! they start from.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::Context as _;
use argonauts_adapter_acp::acp_adapter;
use argonauts_adapter_manifest::manifest_adapter_with;
use argonauts_conductor::plan_usage::find_unsandboxed;
use argonauts_core::adapter::Transport;
use argonauts_core::layout::user_files;
use argonauts_core::paths::{create_private_dir_all, write_private_file};
use argonauts_core::registry::{CliManifest, ModelRegistry};
use argonauts_core::settings::Settings;
use argonauts_core::{Adapter, Paths, project_config_path};
use argonauts_registry::clis::{builtin_home_template, check_manifest};
use argonauts_registry::models::discovery::ClaudeSource;
use argonauts_registry::models::{
    AskOpenCode, CatalogSource, FileRegistry, ProjectModels, project_models_path,
    registry_with_trust,
};

use crate::trust::TrustStore;

/// A repo's `.argonauts/models.toml`, and the state folder whose `trusted.json` says whether
/// its entries count.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RepoModels {
    root: PathBuf,
    state_dir: PathBuf,
}

impl RepoModels {
    pub(crate) fn new(root: &Path, state_dir: &Path) -> Self {
        Self {
            root: root.to_owned(),
            state_dir: state_dir.to_owned(),
        }
    }

    pub(crate) fn root(&self) -> &Path {
        &self.root
    }

    /// Whether you trusted the repo: it was set up with `argonauts setup`, or saved into, and
    /// its `.argonauts/config.toml` holds what you trusted. Only then do OpenCode's own
    /// commands outside a session start in it with the network.
    pub(crate) fn trusted(&self) -> bool {
        TrustStore::load(&self.state_dir).was_trusted(&project_config_path(&self.root))
    }

    /// The hash `trusted.json` holds for the file, read fresh, since you can trust it any time.
    pub(crate) fn trusted_hashes(&self) -> Vec<String> {
        TrustStore::load(&self.state_dir)
            .recorded(&project_models_path(&self.root))
            .into_iter()
            .collect()
    }

    /// The file read once, with whether you trusted that text. `None` when it can't be read.
    fn read(&self) -> Option<ProjectModels> {
        match ProjectModels::read(&project_models_path(&self.root), &self.trusted_hashes()) {
            Ok(project) => Some(project),
            Err(err) => {
                tracing::warn!("{err}");
                None
            }
        }
    }
}

/// The model registry, with the repo's `models.toml` once you trust it, starting from the
/// model list `cache` keeps when given, and asking OpenCode inside the sandbox. With a cache,
/// as the app keeps one, Claude Code's models also come from Anthropic once a day, and the
/// model catalog from Argonauts Code's repository; without one nothing is fetched.
pub(crate) fn registry(
    settings: &Settings,
    repo: Option<&RepoModels>,
    cache: Option<&Path>,
) -> Arc<dyn ModelRegistry> {
    file_registry(settings, repo, cache)
}

/// [`registry`] whole, so what discovery skipped can be shown.
pub(crate) fn file_registry(
    settings: &Settings,
    repo: Option<&RepoModels>,
    cache: Option<&Path>,
) -> Arc<FileRegistry> {
    let trusted = repo.map(RepoModels::trusted_hashes).unwrap_or_default();
    let claude = cache.map(|_| ClaudeSource::for_settings(settings));
    let catalog = cache.map(|_| CatalogSource::argonauts());
    let opencode = AskOpenCode {
        confine: crate::confine::read_only(settings, repo),
        in_repo: repo.is_some_and(RepoModels::trusted),
    };
    registry_with_trust(
        settings,
        repo.map(RepoModels::root),
        &trusted,
        cache,
        claude,
        catalog,
        Some(opencode),
    )
}

/// Every `[[cli]]` entry that counts now: the built-in profiles (one that's off by default
/// only when it's in `turned_on`), yours, then the repo's once you trust it. Entries left out
/// are logged with why.
pub(crate) fn manifests(
    settings: &Settings,
    home: &Paths,
    repo: Option<&RepoModels>,
    turned_on: &[String],
) -> Vec<CliManifest> {
    let project = repo.and_then(RepoModels::read);
    let repo_root = repo.map(RepoModels::root);
    let entries = argonauts_registry::cli_manifests(
        &home.global_models(),
        project.as_ref().map(ProjectModels::path),
        project.as_ref().is_some_and(ProjectModels::trusted),
        repo_root,
        turned_on,
    );
    for warning in &entries.warnings {
        tracing::warn!("{warning}");
    }
    entries
        .manifests
        .into_iter()
        .filter_map(|manifest| with_binary(settings, manifest, repo_root))
        .collect()
}

/// Your `agents.<id>.binary` replaces the entry's, then faces the checks an entry in your own
/// `models.toml` does, so it must be an absolute path outside the repo. Without one, an entry
/// that names its binary, as the built-in profiles do, runs the one found on `PATH` the way
/// doctor finds it, since sessions start only absolute paths.
fn with_binary(
    settings: &Settings,
    mut manifest: CliManifest,
    repo_root: Option<&Path>,
) -> Option<CliManifest> {
    let Some(binary) = settings
        .agents
        .get(&manifest.id)
        .and_then(|agent| agent.binary.as_ref())
    else {
        if !manifest.binary.contains('/')
            && let Ok(found) = find_unsandboxed(&manifest.binary, repo_root)
        {
            manifest.binary = found.display().to_string();
        }
        return Some(manifest);
    };
    manifest.binary = binary.display().to_string();
    let check = check_manifest(&manifest, repo_root);
    if !check.is_ok() {
        tracing::warn!(
            "agents.{}.binary: CLI {} is left out: {}",
            manifest.id,
            manifest.id,
            check.errors.join("; ")
        );
        return None;
    }
    Some(manifest)
}

/// One adapter per entry, kept while the entry stays the same: an ACP adapter leaks its names
/// once, so building one per settings change would grow without end.
#[derive(Default)]
pub(crate) struct CliAdapters {
    made: Vec<(CliManifest, Arc<dyn Adapter>)>,
}

impl CliAdapters {
    /// `builtins` lend their parsers to entries with `output = "parser"`.
    pub(crate) fn adapters(
        &mut self,
        manifests: Vec<CliManifest>,
        builtins: &[Arc<dyn Adapter>],
        home: &Paths,
    ) -> Vec<Arc<dyn Adapter>> {
        manifests
            .into_iter()
            .map(|manifest| {
                if let Err(err) = install_home_template(home, &manifest) {
                    tracing::warn!("CLI {}: {err:#}", manifest.id);
                }
                if let Some((_, adapter)) = self.made.iter().find(|(made, _)| *made == manifest) {
                    return Arc::clone(adapter);
                }
                let adapter = match manifest.transport {
                    Transport::Acp => acp_adapter(manifest.clone()),
                    Transport::Lines => manifest_adapter_with(manifest.clone(), builtins),
                };
                self.made.push((manifest, Arc::clone(&adapter)));
                adapter
            })
            .collect()
    }
}

/// Writes a built-in home template, such as Hermes', into `~/.argonauts/clis/<name>/`,
/// where the adapters copy a fresh home from for each session. A file already there is yours
/// and stays as it is.
pub(crate) fn install_home_template(home: &Paths, manifest: &CliManifest) -> anyhow::Result<()> {
    let Some(template) = &manifest.home else {
        return Ok(());
    };
    let Some(files) = builtin_home_template(&template.template) else {
        return Ok(());
    };
    let folder = home.home().join(user_files::CLIS).join(&template.template);
    for (path, contents) in files {
        let file = folder.join(path);
        if file.exists() {
            continue;
        }
        if let Some(dir) = file.parent() {
            create_private_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
        }
        write_private_file(&file, contents.as_bytes())
            .with_context(|| format!("writing {}", file.display()))?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use argonauts_core::RepoId;
    use argonauts_core::layout::project_files;
    use argonauts_core::settings::agents::AgentSettings;

    use super::*;

    const HERMES: &str = "hermes";

    fn hermes_on() -> Vec<String> {
        vec![HERMES.to_owned()]
    }

    fn ids(manifests: &[CliManifest]) -> Vec<&str> {
        manifests
            .iter()
            .map(|manifest| manifest.id.as_str())
            .collect()
    }

    fn with_agent_binary(id: &str, binary: &str) -> Settings {
        let mut settings = Settings::default();
        settings.agents.insert(
            id.to_owned(),
            AgentSettings {
                binary: Some(PathBuf::from(binary)),
                ..AgentSettings::default()
            },
        );
        settings
    }

    #[test]
    fn hermes_counts_only_once_a_layer_turns_it_on() {
        let dir = tempfile::tempdir().unwrap();
        let home = Paths::new(dir.path().join("home"));
        let off = manifests(&Settings::default(), &home, None, &[]);
        assert!(!ids(&off).contains(&HERMES), "{:?}", ids(&off));
        assert!(ids(&off).contains(&"opencode-acp"), "{:?}", ids(&off));

        let on = manifests(&Settings::default(), &home, None, &hermes_on());
        assert!(ids(&on).contains(&HERMES), "{:?}", ids(&on));
    }

    #[test]
    fn your_binary_replaces_the_entrys_and_must_be_absolute_and_outside_the_repo() {
        let dir = tempfile::tempdir().unwrap();
        let home = Paths::new(dir.path().join("home"));
        let repo_root = dir.path().join("repo");
        std::fs::create_dir_all(&repo_root).unwrap();
        let repo = RepoModels::new(&repo_root, &dir.path().join("state"));

        let settings = with_agent_binary(HERMES, "/opt/hermes/bin/hermes");
        let found = manifests(&settings, &home, Some(&repo), &hermes_on());
        let hermes = found.iter().find(|manifest| manifest.id == HERMES).unwrap();
        assert_eq!(hermes.binary, "/opt/hermes/bin/hermes");

        let relative = with_agent_binary(HERMES, "bin/hermes");
        let found = manifests(&relative, &home, Some(&repo), &hermes_on());
        assert!(!ids(&found).contains(&HERMES), "{:?}", ids(&found));

        let inside = repo_root.join("hermes");
        let inside = with_agent_binary(HERMES, &inside.display().to_string());
        let found = manifests(&inside, &home, Some(&repo), &hermes_on());
        assert!(!ids(&found).contains(&HERMES), "{:?}", ids(&found));
    }

    #[test]
    fn a_profile_naming_its_binary_runs_the_one_on_path() {
        let dir = tempfile::tempdir().unwrap();
        let home = Paths::new(dir.path().join("home"));
        let found = manifests(&Settings::default(), &home, None, &hermes_on());
        let mut hermes = found
            .into_iter()
            .find(|manifest| manifest.id == HERMES)
            .unwrap();
        // A name every machine has on `PATH`, in place of Hermes'.
        hermes.binary = "sh".to_owned();
        let named = with_binary(&Settings::default(), hermes, None).unwrap();
        assert!(Path::new(&named.binary).is_absolute(), "{}", named.binary);
        assert!(named.binary.ends_with("/sh"), "{}", named.binary);
    }

    #[test]
    fn the_repos_entries_wait_for_trust_in_that_exact_text() {
        let dir = tempfile::tempdir().unwrap();
        let home = Paths::new(dir.path().join("home"));
        let root = dir.path().join("repo");
        std::fs::create_dir_all(root.join(".argonauts")).unwrap();
        let path = root.join(".argonauts").join(project_files::MODELS);
        let entry = "[[cli]]\nid = \"outside\"\ndisplay_name = \"Outside\"\nbinary = \"/opt/outside\"\nprovider = \"o\"\nread_only_args = []\nbuild_args = []\n";
        std::fs::write(&path, entry).unwrap();
        let state_dir = home.state_dir(&RepoId::for_repo(&root).unwrap());
        let repo = RepoModels::new(&root, &state_dir);

        assert!(
            !ids(&manifests(&Settings::default(), &home, Some(&repo), &[])).contains(&"outside")
        );
        std::fs::create_dir_all(&state_dir).unwrap();
        TrustStore::load(&state_dir).trust(&path).unwrap();
        assert!(
            ids(&manifests(&Settings::default(), &home, Some(&repo), &[])).contains(&"outside")
        );

        std::fs::write(&path, format!("{entry}# changed\n")).unwrap();
        assert!(
            !ids(&manifests(&Settings::default(), &home, Some(&repo), &[])).contains(&"outside"),
            "a change needs trust again"
        );
    }

    #[test]
    fn hermes_home_template_is_written_once_and_yours_is_kept() {
        let dir = tempfile::tempdir().unwrap();
        let home = Paths::new(dir.path().join("home"));
        let found = manifests(&Settings::default(), &home, None, &hermes_on());
        let hermes = found.iter().find(|manifest| manifest.id == HERMES).unwrap();
        install_home_template(&home, hermes).unwrap();
        let config = home
            .home()
            .join(user_files::CLIS)
            .join(HERMES)
            .join("config.yaml");
        let written = std::fs::read_to_string(&config).unwrap();
        assert_eq!(
            builtin_home_template(HERMES)
                .unwrap()
                .iter()
                .find(|(path, _)| *path == "config.yaml")
                .map(|(_, contents)| *contents),
            Some(written.as_str())
        );

        std::fs::write(&config, "# mine\n").unwrap();
        install_home_template(&home, hermes).unwrap();
        assert_eq!(std::fs::read_to_string(&config).unwrap(), "# mine\n");
    }

    #[test]
    fn an_unchanged_entry_keeps_its_adapter() {
        let dir = tempfile::tempdir().unwrap();
        let home = Paths::new(dir.path().join("home"));
        let mut made = CliAdapters::default();
        let builtins = crate::adapters::builtin_adapters();
        let first = made.adapters(
            manifests(&Settings::default(), &home, None, &hermes_on()),
            &builtins,
            &home,
        );
        let again = made.adapters(
            manifests(&Settings::default(), &home, None, &hermes_on()),
            &builtins,
            &home,
        );
        assert_eq!(first.len(), again.len());
        assert!(first.iter().zip(&again).all(|(a, b)| Arc::ptr_eq(a, b)));

        let moved = with_agent_binary(HERMES, "/opt/other/hermes");
        let changed = made.adapters(
            manifests(&moved, &home, None, &hermes_on()),
            &builtins,
            &home,
        );
        let hermes = changed
            .iter()
            .find(|adapter| adapter.id() == HERMES)
            .unwrap();
        assert_eq!(hermes.binary(), "/opt/other/hermes");
    }
}