outrig-cli 0.1.0

Command-line tool for running LLM agents with podman-isolated MCP servers.
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
use clap::{ArgAction, Args, Parser, Subcommand};
use std::path::PathBuf;
use std::process::ExitCode;
use tracing_subscriber::EnvFilter;

use crate::cli::build::{self, BuildArgs};
use crate::cli::clean::{self, CleanArgs};
use crate::cli::design_prompt::{self, DesignArgs};
use crate::cli::discard::{self, DiscardArgs};
use crate::cli::logs::{self, LogsArgs};
use crate::cli::ls::{self, LsArgs};
use crate::cli::mcp::{self, McpArgs};
use crate::cli::mcp_self as mcp_self_cli;
use crate::cli::run::{self, RunArgs};
use crate::error::Result;
use crate::paths::{global_config_path, resolve_repo_config, resolve_repo_config_optional};
use crate::{config_init, image_setup, init};

#[derive(Debug, Parser)]
#[command(
    name = "outrig",
    version,
    about = "Run LLM agents with podman-isolated MCP servers."
)]
struct Cli {
    /// Path to the repo `config.toml`. Defaults to walking up from cwd.
    #[arg(long, global = true, value_name = "PATH")]
    config: Option<PathBuf>,

    /// Path to the global config. Defaults to `~/.outrig/config.toml`.
    #[arg(long = "global-config", global = true, value_name = "PATH")]
    global_config: Option<PathBuf>,

    /// Override the session root for this invocation. Default cascade:
    /// flag > config's `session-root` > `<XDG_DATA_HOME>/outrig/sessions/`.
    #[arg(long = "session-root", global = true, value_name = "PATH")]
    session_root: Option<PathBuf>,

    /// Show buildah/podman transcripts. Repeat for trace-level outrig logs.
    #[arg(short = 'v', long = "verbose", global = true, action = ArgAction::Count)]
    verbose: u8,

    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Debug, Subcommand)]
enum Cmd {
    /// Start an interactive agent session.
    Run(RunArgs),
    /// Serve the configured backing MCPs as a single MCP server over stdio.
    Mcp(McpArgs),
    /// Generate prompts and setup snippets for AI-assisted design.
    Design(DesignArgs),
    /// Build (or cache-hit) one or more image-config images.
    Build(BuildArgs),
    /// Read or write outrig's configuration files.
    Config(ConfigArgs),
    /// Interactively set up global + repo config.
    Init {
        /// Overwrite existing files. Propagates to `config init` and `image add`.
        #[arg(long)]
        force: bool,
    },
    /// Manage image-configs.
    Image(ImageArgs),
    /// List sessions newest-first under the session root.
    Ls(LsArgs),
    /// Print or follow a session's MCP-server stderr.
    Logs(LogsArgs),
    /// Delete a session's on-disk record.
    Discard(DiscardArgs),
    /// Delete old stopped session records.
    Clean(CleanArgs),
}

#[derive(Debug, Args)]
struct ConfigArgs {
    #[command(subcommand)]
    cmd: ConfigCmd,
}

#[derive(Debug, Subcommand)]
enum ConfigCmd {
    /// Interactively write the global config (`~/.outrig/config.toml`).
    Init {
        /// Overwrite an existing global config.
        #[arg(long)]
        force: bool,
    },
}

#[derive(Debug, Args)]
struct ImageArgs {
    #[command(subcommand)]
    cmd: ImageCmd,
}

#[derive(Debug, Subcommand)]
enum ImageCmd {
    /// Scaffold a new image-config (Dockerfile + `[images.<name>]`).
    Add {
        /// Image-config name. Prompted if omitted.
        name: Option<String>,
        /// Overwrite an existing Dockerfile / config block of this name.
        #[arg(long)]
        force: bool,
    },
    /// Scaffold a standalone image project (Dockerfile + image.toml + README).
    Init {
        /// Project directory. Defaults to the current directory; its name
        /// becomes the image ref.
        dir: Option<PathBuf>,
        /// Overwrite the generated files if they already exist.
        #[arg(long)]
        force: bool,
    },
    /// Build a standalone image project and validate the built image.
    Build {
        /// Project directory holding `image.toml`. Defaults to the current
        /// directory.
        dir: Option<PathBuf>,
        /// Tag the build output as this ref instead of `[image].ref`. Does not
        /// rewrite `image.toml`.
        #[arg(long, value_name = "REF")]
        tag: Option<String>,
        /// Skip the live MCP server test. Still validates the embedded
        /// `image.toml`.
        #[arg(long = "no-test")]
        no_test: bool,
        /// Force a clean build (passes `--no-cache` to buildah).
        #[arg(long = "no-cache")]
        no_cache: bool,
    },
    /// Inspect an image's OutRig labels without starting it.
    Inspect {
        /// Inspect the registry ref with skopeo instead of the local image store.
        #[arg(long)]
        remote: bool,
        /// Image ref to inspect. Local mode never pulls; remote mode reads registry metadata.
        #[arg(value_name = "REF")]
        image_ref: String,
    },
}

pub fn run() -> ExitCode {
    let cli = Cli::parse();
    init_tracing(cli.verbose);

    outrig::container::install_panic_hook();

    tracing::debug!("outrig starting");
    match dispatch(&cli) {
        Ok(0) => ExitCode::SUCCESS,
        Ok(code) => ExitCode::from(code.clamp(0, 255) as u8),
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::from(1)
        }
    }
}

fn dispatch(cli: &Cli) -> Result<i32> {
    match &cli.cmd {
        Cmd::Run(args) => {
            let (repo_config, global_config, runtime) = repo_cmd_ctx(cli, false)?;
            runtime.block_on(run::execute(
                &repo_config,
                &global_config,
                cli.session_root.as_deref(),
                args,
                cli.verbose,
            ))
        }
        Cmd::Mcp(args) => {
            if args.is_self_description() {
                let runtime = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()?;
                return runtime.block_on(mcp_self_cli::execute(args));
            }
            let (repo_config, global_config, runtime) = repo_cmd_ctx(cli, false)?;
            runtime.block_on(mcp::execute(
                &repo_config,
                &global_config,
                cli.session_root.as_deref(),
                args,
                cli.verbose,
            ))
        }
        Cmd::Design(args) => design_prompt::execute(args),
        Cmd::Build(args) => {
            let (repo_config, global_config, runtime) = repo_cmd_ctx(cli, true)?;
            runtime.block_on(build::execute(&repo_config, &global_config, args))
        }
        Cmd::Config(args) => match &args.cmd {
            ConfigCmd::Init { force } => {
                let runtime = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()?;
                runtime.block_on(config_init::run(*force, cli.global_config.as_deref()))?;
                Ok(0)
            }
        },
        Cmd::Init { force } => {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()?;
            runtime.block_on(init::run(*force, cli.global_config.as_deref()))?;
            Ok(0)
        }
        Cmd::Image(args) => match &args.cmd {
            ImageCmd::Add { name, force } => {
                let cwd = std::env::current_dir()?;
                let runtime = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()?;
                runtime.block_on(image_setup::add::run(
                    &cwd,
                    cli.global_config.as_deref(),
                    name.clone(),
                    *force,
                ))?;
                Ok(0)
            }
            ImageCmd::Init { dir, force } => {
                let cwd = std::env::current_dir()?;
                image_setup::init::run(&cwd, dir.as_deref(), *force)?;
                Ok(0)
            }
            ImageCmd::Build {
                dir,
                tag,
                no_test,
                no_cache,
            } => {
                let cwd = std::env::current_dir()?;
                let runtime = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()?;
                runtime.block_on(image_setup::build::run(
                    &cwd,
                    dir.as_deref(),
                    tag.as_deref(),
                    *no_test,
                    *no_cache,
                ))?;
                Ok(0)
            }
            ImageCmd::Inspect { remote, image_ref } => {
                let runtime = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()?;
                runtime.block_on(image_setup::inspect::run(image_ref, *remote))?;
                Ok(0)
            }
        },
        Cmd::Ls(args) => {
            let (cwd, global, runtime) = session_cmd_ctx(cli)?;
            let session_root = cli.session_root.as_deref();
            let repo_cfg = cli.config.as_deref();
            runtime.block_on(ls::execute(args, session_root, repo_cfg, &global, &cwd))
        }
        Cmd::Logs(args) => {
            let (cwd, global, runtime) = session_cmd_ctx(cli)?;
            let session_root = cli.session_root.as_deref();
            let repo_cfg = cli.config.as_deref();
            runtime.block_on(logs::execute(args, session_root, repo_cfg, &global, &cwd))
        }
        Cmd::Discard(args) => {
            let (cwd, global, runtime) = session_cmd_ctx(cli)?;
            let session_root = cli.session_root.as_deref();
            let repo_cfg = cli.config.as_deref();
            runtime.block_on(discard::execute(
                args,
                session_root,
                repo_cfg,
                &global,
                &cwd,
            ))
        }
        Cmd::Clean(args) => {
            let (cwd, global, runtime) = session_cmd_ctx(cli)?;
            let session_root = cli.session_root.as_deref();
            let repo_cfg = cli.config.as_deref();
            runtime.block_on(clean::execute(args, session_root, repo_cfg, &global, &cwd))
        }
    }
}

fn init_tracing(verbose: u8) {
    let outrig_log = std::env::var("OUTRIG_LOG").ok();
    let rust_log = std::env::var("RUST_LOG").ok();
    let mut filter =
        EnvFilter::try_new(log_filter_spec(outrig_log.as_deref(), rust_log.as_deref()))
            .unwrap_or_else(|_| EnvFilter::new("info"));
    if verbose >= 2 {
        filter = filter.add_directive(
            "outrig=trace"
                .parse()
                .expect("hard-coded outrig trace directive must parse"),
        );
    }
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .init();
    if verbose >= 2 {
        tracing::trace!(target: "outrig", "verbose tracing enabled");
    }
}

fn log_filter_spec<'a>(outrig_log: Option<&'a str>, rust_log: Option<&'a str>) -> &'a str {
    outrig_log.or(rust_log).unwrap_or("info")
}

/// Shared preamble for `ls`/`logs`/`discard`: cwd, the resolved global
/// config path, and a current-thread tokio runtime ready to drive the
/// async `execute` form of each subcommand. The repo config is resolved
/// inside each handler because session lookups can substring-match across
/// repos and shouldn't fail on a missing repo config.
fn session_cmd_ctx(cli: &Cli) -> Result<(PathBuf, PathBuf, tokio::runtime::Runtime)> {
    let cwd = std::env::current_dir()?;
    let global = global_config_path(cli.global_config.as_deref());
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    Ok((cwd, global, runtime))
}

/// Shared preamble for `run`/`mcp`/`build`: the resolved repo config, the
/// resolved global config, and a current-thread tokio runtime. With
/// `require_config` (build), errors if no repo config can be located;
/// otherwise (run/mcp) a missing config falls back to the current directory
/// as repo root, merged over the global config.
fn repo_cmd_ctx(
    cli: &Cli,
    require_config: bool,
) -> Result<(PathBuf, PathBuf, tokio::runtime::Runtime)> {
    let cwd = std::env::current_dir()?;
    let repo_config = if require_config {
        resolve_repo_config(cli.config.as_deref(), &cwd)?
    } else {
        resolve_repo_config_optional(cli.config.as_deref(), &cwd)
    };
    let global_config = global_config_path(cli.global_config.as_deref());
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    Ok((repo_config, global_config, runtime))
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::{Cli, Cmd, ImageCmd, log_filter_spec};

    #[test]
    fn outrig_log_wins_over_rust_log() {
        assert_eq!(
            log_filter_spec(Some("outrig=trace"), Some("debug")),
            "outrig=trace"
        );
    }

    #[test]
    fn rust_log_is_used_when_outrig_log_is_unset() {
        assert_eq!(log_filter_spec(None, Some("debug")), "debug");
    }

    #[test]
    fn log_filter_defaults_to_info() {
        assert_eq!(log_filter_spec(None, None), "info");
    }

    #[test]
    fn image_inspect_defaults_to_local() {
        let cli =
            Cli::try_parse_from(["outrig", "image", "inspect", "rust-dev"]).expect("arg parses");

        let Cmd::Image(args) = cli.cmd else {
            panic!("expected image command");
        };
        let ImageCmd::Inspect { remote, image_ref } = args.cmd else {
            panic!("expected image inspect command");
        };

        assert!(!remote);
        assert_eq!(image_ref, "rust-dev");
    }

    #[test]
    fn image_inspect_remote_arg_parses() {
        let cli = Cli::try_parse_from([
            "outrig",
            "image",
            "inspect",
            "--remote",
            "quay.io/acme/rust-dev:latest",
        ])
        .expect("arg parses");

        let Cmd::Image(args) = cli.cmd else {
            panic!("expected image command");
        };
        let ImageCmd::Inspect { remote, image_ref } = args.cmd else {
            panic!("expected image inspect command");
        };

        assert!(remote);
        assert_eq!(image_ref, "quay.io/acme/rust-dev:latest");
    }
}