bob-cli 0.2.2

CLI app for Bob - a general-purpose AI agent framework
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! # Bob CLI
//!
//! Command-line interface for the Bob Agent Framework.
//!
//! # Subcommands
//!
//! - `repl` — Interactive REPL for chatting with the agent
//! - `skills list` — List skills in a directory
//! - `skills validate` — Validate a skill directory
//! - `skills read-properties` — Read skill properties as JSON/YAML/TOML
//! - `skills to-prompt` — Generate XML block for agent prompts

mod bootstrap;
mod config;
mod request_context;

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

use bob_runtime::{Agent, Session};
use clap::{Parser, Subcommand};
use eyre::WrapErr;

use crate::{
    bootstrap::{CliRuntimeHandles, build_runtime},
    config::AgentConfig,
};

/// Bob CLI — a general-purpose AI agent framework CLI.
#[derive(Parser, Debug)]
#[command(name = "bob", version, about)]
struct Cli {
    /// Path to the agent configuration file.
    #[arg(short, long, default_value = "agent.toml")]
    config: String,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Start an interactive REPL session with the agent.
    Repl,

    /// Skill management commands.
    #[command(subcommand)]
    Skills(SkillsCommands),
}

#[derive(Subcommand, Debug)]
enum SkillsCommands {
    /// List skills in a directory.
    #[command(visible_alias = "ls")]
    List {
        /// Directory to search for skills.
        #[arg(default_value = ".")]
        directory: PathBuf,

        /// Search recursively.
        #[arg(short, long)]
        recursive: bool,

        /// Validate each skill and show status.
        #[arg(short, long)]
        check: bool,

        /// Show only skills that fail validation (implies --check).
        #[arg(short, long)]
        failed: bool,

        /// Show full details (path and complete description).
        #[arg(short, long, conflicts_with_all = ["paths", "names"])]
        long: bool,

        /// Show only paths (for scripting).
        #[arg(short, long, conflicts_with_all = ["long", "names"])]
        paths: bool,

        /// Show only names (for scripting).
        #[arg(short, long, conflicts_with_all = ["long", "paths"])]
        names: bool,

        /// Output as JSON.
        #[arg(long)]
        json: bool,
    },

    /// Validate a skill directory.
    #[command(visible_alias = "check")]
    Validate {
        /// Path to skill directory or SKILL.md file.
        #[arg(default_value = ".")]
        skill_path: String,
    },

    /// Read skill properties as JSON/YAML/TOML.
    #[command(name = "read-properties", visible_alias = "props")]
    ReadProperties {
        /// Path to skill directory or SKILL.md file.
        #[arg(default_value = ".")]
        skill_path: String,

        /// Output format.
        #[arg(short, long, default_value = "json")]
        format: String,

        /// Compact output (no pretty printing, JSON only).
        #[arg(long)]
        compact: bool,
    },

    /// Generate `available_skills` XML block for agent prompts.
    #[command(name = "to-prompt", visible_alias = "prompt")]
    ToPrompt {
        /// Paths to skill directories or SKILL.md files.
        #[arg(required = true)]
        skill_paths: Vec<String>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum ReplCommand {
    Help,
    NewSession,
}

fn parse_repl_command(input: &str) -> Option<ReplCommand> {
    let trimmed = input.trim();
    match trimmed {
        "/help" | "/h" => Some(ReplCommand::Help),
        "/new" | "/reset" => Some(ReplCommand::NewSession),
        _ => None,
    }
}

#[expect(clippy::print_stdout, reason = "help text is intentionally printed for REPL UX")]
fn print_help() {
    println!(
        "\
CLI session commands:
  /help, /h             Show this help message
  /new, /reset          Start a new session context
  /quit, /q             Exit the REPL

Available slash commands:
  /tools                List available tools
  /tool <name>          Describe a specific tool
  /tape search <query>  Search tape history
  /tape info            Show tape statistics
  /anchors              List tape anchors
  /handoff [name]       Create handoff checkpoint
  /usage                Show session token usage
"
    );
}

/// Build an Agent from configuration.
async fn build_agent(cfg: &AgentConfig) -> eyre::Result<Agent> {
    let CliRuntimeHandles { runtime, tools, store, tape, skills_context: _ } =
        build_runtime(cfg).await?;

    let mut builder = Agent::from_runtime(runtime, tools).with_store(store).with_tape(tape);

    // Load system prompt from workspace file if it exists
    if let Ok(prompt) = std::fs::read_to_string(".agent/system-prompt.md") {
        builder = builder.with_system_prompt(prompt);
    }

    Ok(builder.build())
}

/// Run the interactive REPL loop.
#[expect(
    clippy::print_stdout,
    clippy::print_stderr,
    reason = "CLI REPL must use stdout/stderr for user interaction"
)]
async fn repl(mut session: Session, model: &str, cfg: &AgentConfig) {
    use tokio::io::{AsyncBufReadExt, BufReader};

    let stdin = BufReader::new(tokio::io::stdin());
    let mut lines = stdin.lines();

    let skills_context = bootstrap::build_skills_composer(cfg).ok().flatten();

    eprintln!("Bob agent ready  (model: {model})");
    eprintln!("Session: {}", session.session_id());
    eprintln!("Type a message and press Enter. /help for commands.\n");

    loop {
        eprint!("> ");
        let _ = tokio::io::AsyncWriteExt::flush(&mut tokio::io::stderr()).await;

        let line = match lines.next_line().await {
            Ok(Some(l)) => l,
            Ok(None) => break,
            Err(e) => {
                eprintln!("stdin error: {e}");
                break;
            }
        };

        let input = line.trim().to_string();
        if input.is_empty() {
            continue;
        }

        if let Some(command) = parse_repl_command(&input) {
            match command {
                ReplCommand::Help => {
                    print_help();
                    continue;
                }
                ReplCommand::NewSession => {
                    session = session.new_session();
                    eprintln!("Started new session: {}", session.session_id());
                    continue;
                }
            }
        }

        // Build request context with skills if available
        let context = request_context::build_request_context(
            &input,
            skills_context.as_ref(),
            cfg.policy.as_ref(),
        );

        match session.chat_with_context(&input, context).await {
            Ok(response) => {
                if response.is_quit {
                    break;
                }
                if !response.content.is_empty() {
                    println!("{}", response.content);
                }
                if response.usage.total() > 0 {
                    println!(
                        "\n[usage] prompt={} completion={} total={}",
                        response.usage.prompt_tokens,
                        response.usage.completion_tokens,
                        response.usage.total()
                    );
                }
            }
            Err(err) => {
                eprintln!("Error: {err}");
            }
        }
    }

    eprintln!("\nGoodbye!");
}

// ── Skills Commands ──────────────────────────────────────────────────

/// Output mode for list command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ListOutputMode {
    Short,
    Long,
    PathsOnly,
    NamesOnly,
}

/// Information about a discovered skill.
#[derive(serde::Serialize)]
struct SkillInfo {
    name: String,
    description: String,
    path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    valid: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

/// Skill properties for read-properties command.
#[derive(serde::Serialize)]
struct SkillProperties {
    name: String,
    description: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    license: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    compatibility: Option<String>,
}

/// Resolves a skill path, handling SKILL.md files.
fn resolve_skill_path(path: &Path) -> Result<PathBuf, eyre::Report> {
    if !path.exists() {
        return Err(eyre::eyre!("path not found: '{}'", path.display()));
    }

    if path.is_file() &&
        path.file_name().is_some_and(|name| name == "SKILL.md") &&
        let Some(parent) = path.parent()
    {
        return Ok(parent.to_path_buf());
    }

    Ok(path.to_path_buf())
}

/// Truncates a description to the specified maximum length.
fn truncate_description(description: &str, max_len: usize) -> String {
    if description.len() <= max_len {
        return description.to_string();
    }

    let target_len = max_len.saturating_sub(3);
    let truncate_at = description[..target_len].rfind(' ').unwrap_or(target_len);
    format!("{}...", &description[..truncate_at])
}

/// Escape XML special characters.
fn escape_xml(s: &str) -> String {
    let mut escaped = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => {
                escaped.push('\u{26}');
                escaped.push_str("amp;");
            }
            '<' => {
                escaped.push('\u{3c}');
                escaped.push_str("lt;");
            }
            '>' => {
                escaped.push('\u{3e}');
                escaped.push_str("gt;");
            }
            '"' => {
                escaped.push('\u{22}');
                escaped.push_str("quot;");
            }
            '\'' => {
                escaped.push('\u{27}');
                escaped.push_str("apos;");
            }
            _ => escaped.push(c),
        }
    }
    escaped
}

/// Discover skills in a directory.
fn discover_skills(
    directory: &Path,
    recursive: bool,
    validate: bool,
) -> Result<Vec<SkillInfo>, eyre::Report> {
    let mut skills = Vec::new();
    discover_skills_in_dir(directory, recursive, validate, &mut skills)?;
    skills.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(skills)
}

fn discover_skills_in_dir(
    directory: &Path,
    recursive: bool,
    validate: bool,
    skills: &mut Vec<SkillInfo>,
) -> Result<(), eyre::Report> {
    let entries = std::fs::read_dir(directory)
        .map_err(|e| eyre::eyre!("failed to read directory '{}': {e}", directory.display()))?;

    for entry in entries {
        let entry = entry.map_err(|e| eyre::eyre!("failed to read directory entry: {e}"))?;
        let path = entry.path();

        if path.is_dir() {
            let skill_md = path.join("SKILL.md");
            if skill_md.exists() {
                match bob_skills::SkillDirectory::load(&path) {
                    Ok(dir) => {
                        let skill = dir.skill();
                        skills.push(SkillInfo {
                            name: skill.name().as_str().to_string(),
                            description: skill.description().as_str().to_string(),
                            path: path.display().to_string(),
                            valid: validate.then_some(true),
                            error: None,
                        });
                    }
                    Err(e) if validate => {
                        let name = path
                            .file_name()
                            .and_then(|n| n.to_str())
                            .unwrap_or("unknown")
                            .to_string();
                        skills.push(SkillInfo {
                            name,
                            description: String::new(),
                            path: path.display().to_string(),
                            valid: Some(false),
                            error: Some(e.to_string()),
                        });
                    }
                    Err(_) => {}
                }
            }

            if recursive {
                discover_skills_in_dir(&path, recursive, validate, skills)?;
            }
        }
    }

    Ok(())
}

/// Run the `skills list` command.
#[expect(clippy::print_stdout, clippy::print_stderr, reason = "CLI must print to stdout/stderr")]
fn run_skills_list(
    directory: &Path,
    recursive: bool,
    validate: bool,
    failed_only: bool,
    list_mode: ListOutputMode,
    json_output: bool,
) -> Result<(), eyre::Report> {
    if !directory.exists() {
        return Err(eyre::eyre!("path not found: '{}'", directory.display()));
    }

    let skills = discover_skills(directory, recursive, validate)?;

    let skills: Vec<_> = if failed_only {
        skills.into_iter().filter(|s| s.valid == Some(false)).collect()
    } else {
        skills
    };

    if skills.is_empty() {
        let msg = if failed_only { "No invalid skills found" } else { "No skills found" };
        eprintln!("{msg} in '{}'", directory.display());
        return Ok(());
    }

    if json_output {
        let json = serde_json::to_string_pretty(&skills)?;
        println!("{json}");
    } else {
        match list_mode {
            ListOutputMode::Short => {
                for skill in &skills {
                    let symbol = match skill.valid {
                        Some(true) => "",
                        Some(false) => "",
                        None => "",
                    };
                    let desc = truncate_description(&skill.description, 50);
                    println!("{symbol}{}  {}", skill.name, desc);
                }
            }
            ListOutputMode::Long => {
                for (i, skill) in skills.iter().enumerate() {
                    if i > 0 {
                        println!();
                    }
                    let symbol = match skill.valid {
                        Some(true) => "",
                        Some(false) => "",
                        None => "",
                    };
                    println!("{symbol}{}", skill.name);
                    println!("  Path: {}", skill.path);
                    if skill.valid == Some(false) {
                        if let Some(ref e) = skill.error {
                            println!("  Error: {e}");
                        }
                    } else {
                        println!("  {}", skill.description);
                    }
                }
            }
            ListOutputMode::PathsOnly => {
                for skill in &skills {
                    println!("{}", skill.path);
                }
            }
            ListOutputMode::NamesOnly => {
                for skill in &skills {
                    println!("{}", skill.name);
                }
            }
        }
    }

    eprintln!("Found {} skill(s)", skills.len());
    Ok(())
}

/// Run the `skills validate` command.
#[expect(clippy::print_stderr, reason = "CLI must print validation result to stderr")]
fn run_skills_validate(skill_path: &str) -> Result<(), eyre::Report> {
    let path = Path::new(skill_path);
    let skill_path = resolve_skill_path(path)?;

    bob_skills::SkillDirectory::load(&skill_path)
        .map_err(|e| eyre::eyre!("failed to load skill at '{}': {e}", skill_path.display()))?;

    let name = skill_path.file_name().and_then(|n| n.to_str()).unwrap_or("skill");
    eprintln!("{name} ({})", skill_path.display());
    Ok(())
}

/// Run the `skills read-properties` command.
#[expect(clippy::print_stdout, reason = "CLI must print to stdout")]
fn run_skills_read_properties(
    skill_path: &str,
    format: &str,
    compact: bool,
) -> Result<(), eyre::Report> {
    let path = Path::new(skill_path);
    let skill_path = resolve_skill_path(path)?;

    let dir = bob_skills::SkillDirectory::load(&skill_path)
        .map_err(|e| eyre::eyre!("failed to load skill at '{}': {e}", skill_path.display()))?;

    let skill = dir.skill();
    let frontmatter = skill.frontmatter();

    let properties = SkillProperties {
        name: skill.name().as_str().to_string(),
        description: skill.description().as_str().to_string(),
        license: frontmatter.license().map(String::from),
        compatibility: frontmatter.compatibility().map(|c| c.as_str().to_string()),
    };

    let output = match format.to_lowercase().as_str() {
        "json" => {
            if compact {
                serde_json::to_string(&properties)?
            } else {
                serde_json::to_string_pretty(&properties)?
            }
        }
        "yaml" | "yml" => serde_yml::to_string(&properties)
            .map(|s| s.trim_end().to_string())
            .map_err(|e| eyre::eyre!("YAML serialization error: {e}"))?,
        "toml" => toml::to_string_pretty(&properties)
            .map_err(|e| eyre::eyre!("TOML serialization error: {e}"))?,
        _ => return Err(eyre::eyre!("invalid format '{format}'; valid formats: json, yaml, toml")),
    };

    println!("{output}");
    Ok(())
}

/// Run the `skills to-prompt` command.
#[expect(clippy::print_stdout, reason = "CLI must print to stdout")]
fn run_skills_to_prompt(skill_paths: &[String]) -> Result<(), eyre::Report> {
    if skill_paths.is_empty() {
        return Err(eyre::eyre!("no skill paths provided"));
    }

    let mut skills_xml = Vec::new();

    for path_str in skill_paths {
        let path = Path::new(path_str);
        let skill_path = resolve_skill_path(path)?;

        let absolute_path = std::fs::canonicalize(&skill_path)
            .map_err(|e| eyre::eyre!("failed to canonicalize '{}': {e}", skill_path.display()))?;

        let dir = bob_skills::SkillDirectory::load(&skill_path)
            .map_err(|e| eyre::eyre!("failed to load skill at '{}': {e}", skill_path.display()))?;

        let skill = dir.skill();
        let skill_md_path = absolute_path.join("SKILL.md");

        skills_xml.push(format!(
            "<skill>\n<name>{}</name>\n<description>{}</description>\n<location>{}</location>\n</skill>\n",
            escape_xml(skill.name().as_str()),
            escape_xml(skill.description().as_str()),
            escape_xml(&skill_md_path.display().to_string()),
        ));
    }

    println!("<available_skills>");
    for xml in skills_xml {
        print!("{xml}");
    }
    println!("</available_skills>");

    Ok(())
}

// ── Main ─────────────────────────────────────────────────────────────

#[tokio::main]
async fn main() -> eyre::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .with_target(false)
        .init();

    let cli = Cli::parse();

    match cli.command {
        Commands::Repl => {
            let cfg = config::load_config(&cli.config)
                .wrap_err_with(|| format!("failed to load config from '{}'", cli.config))?;

            // Build agent using the new simplified API
            let agent = build_agent(&cfg).await?;
            let session = agent.start_session();

            repl(session, &cfg.runtime.default_model, &cfg).await;
        }
        Commands::Skills(skills_cmd) => match skills_cmd {
            SkillsCommands::List {
                directory,
                recursive,
                check,
                failed,
                long,
                paths,
                names,
                json,
            } => {
                let list_mode = if paths {
                    ListOutputMode::PathsOnly
                } else if names {
                    ListOutputMode::NamesOnly
                } else if long {
                    ListOutputMode::Long
                } else {
                    ListOutputMode::Short
                };
                let validate = check || failed;
                run_skills_list(&directory, recursive, validate, failed, list_mode, json)?;
            }
            SkillsCommands::Validate { skill_path } => {
                run_skills_validate(&skill_path)?;
            }
            SkillsCommands::ReadProperties { skill_path, format, compact } => {
                run_skills_read_properties(&skill_path, &format, compact)?;
            }
            SkillsCommands::ToPrompt { skill_paths } => {
                run_skills_to_prompt(&skill_paths)?;
            }
        },
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{ReplCommand, parse_repl_command};

    #[test]
    fn parse_help_command() {
        assert_eq!(parse_repl_command("/help"), Some(ReplCommand::Help));
        assert_eq!(parse_repl_command("/h"), Some(ReplCommand::Help));
    }

    #[test]
    fn parse_new_session_commands() {
        assert_eq!(parse_repl_command("/new"), Some(ReplCommand::NewSession));
        assert_eq!(parse_repl_command("/reset"), Some(ReplCommand::NewSession));
    }

    #[test]
    fn non_command_input_returns_none() {
        assert_eq!(parse_repl_command("hello"), None);
        assert_eq!(parse_repl_command("/tools"), None);
    }
}