agpm-cli 0.4.14

AGent Package Manager - A Git-based package manager for coding agents
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use anyhow::Result;
use colored::Colorize;
use std::collections::{BTreeMap, HashMap};

use crate::cache::Cache;
use crate::lockfile::LockFile;
use crate::lockfile::patch_display::extract_patch_displays;

/// Configuration for output formatting options
#[derive(Debug, Clone)]
pub struct OutputConfig {
    pub title: String,
    pub format: String,
    pub files: bool,
    pub detailed: bool,
    pub verbose: bool,
    pub should_show_agents: bool,
    pub should_show_snippets: bool,
}

impl Default for OutputConfig {
    fn default() -> Self {
        Self {
            title: "Installed Resources".to_string(),
            format: "table".to_string(),
            files: false,
            detailed: false,
            verbose: false,
            should_show_agents: true,
            should_show_snippets: true,
        }
    }
}

/// Internal representation for list items used in various output formats.
///
/// This struct normalizes resource information from both agents and snippets
/// in the lockfile to provide a consistent view for display purposes.
#[derive(Debug, Clone)]
pub struct ListItem {
    /// The name/key of the resource as defined in the manifest
    pub name: String,
    /// The source repository name (if from a Git source)
    pub source: Option<String>,
    /// The version/tag/branch of the resource
    pub version: Option<String>,
    /// The path within the source repository
    pub path: Option<String>,
    /// The type of resource ("agent" or "snippet")
    pub resource_type: String,
    /// The local installation path where the resource file is located
    pub installed_at: Option<String>,
    /// The SHA-256 checksum of the installed resource file
    pub checksum: Option<String>,
    /// The resolved Git commit hash
    pub resolved_commit: Option<String>,
    /// The tool ("claude-code", "opencode", "agpm", or custom)
    pub tool: Option<String>,
    /// Patches that were applied to this resource
    pub applied_patches: std::collections::BTreeMap<String, toml::Value>,
    /// Approximate token count of the installed resource content
    pub approximate_token_count: Option<u64>,
}

/// Output items in the specified format
pub fn output_items(items: &[ListItem], config: &OutputConfig) -> Result<()> {
    if items.is_empty() {
        if config.format == "json" {
            println!("{{}}");
        } else {
            println!("No installed resources found.");
        }
        return Ok(());
    }

    match config.format.as_str() {
        "json" => output_json(items)?,
        "yaml" => output_yaml(items)?,
        "compact" => output_compact(items),
        "simple" => output_simple(items),
        _ => output_table(items, config),
    }

    Ok(())
}

/// Output items in detailed mode with patch comparisons
pub async fn output_items_detailed(
    items: &[ListItem],
    title: &str,
    lockfile: &LockFile,
    cache: Option<&Cache>,
    should_show_agents: bool,
    should_show_snippets: bool,
) -> Result<()> {
    if items.is_empty() {
        println!("{{}}");
        return Ok(());
    }

    println!("{}", title.bold());
    println!();

    // Group by resource type
    if should_show_agents {
        let agents: Vec<_> = items.iter().filter(|i| i.resource_type == "agent").collect();
        if !agents.is_empty() {
            println!("{}:", "Agents".cyan().bold());
            for item in agents {
                print_item_detailed(item, lockfile, cache).await;
            }
            println!();
        }
    }

    if should_show_snippets {
        let snippets: Vec<_> = items.iter().filter(|i| i.resource_type == "snippet").collect();
        if !snippets.is_empty() {
            println!("{}:", "Snippets".cyan().bold());
            for item in snippets {
                print_item_detailed(item, lockfile, cache).await;
            }
        }
    }

    // Calculate total token count
    let total_tokens: u64 = items.iter().filter_map(|i| i.approximate_token_count).sum();
    if total_tokens > 0 {
        let formatted = crate::tokens::format_token_count(total_tokens as usize);
        println!("{}: {} resources (~{} tokens)", "Total".green().bold(), items.len(), formatted);
    } else {
        println!("{}: {} resources", "Total".green().bold(), items.len());
    }

    Ok(())
}

/// Output in JSON format
fn output_json(items: &[ListItem]) -> Result<()> {
    let json_items: Vec<serde_json::Value> = items
        .iter()
        .map(|item| {
            let mut obj = serde_json::json!({
                "name": item.name,
                "type": item.resource_type,
                "tool": item.tool
            });

            if let Some(ref source) = item.source {
                obj["source"] = serde_json::Value::String(source.clone());
            }
            if let Some(ref version) = item.version {
                obj["version"] = serde_json::Value::String(version.clone());
            }
            if let Some(ref path) = item.path {
                obj["path"] = serde_json::Value::String(path.clone());
            }
            if let Some(ref installed_at) = item.installed_at {
                obj["installed_at"] = serde_json::Value::String(installed_at.clone());
            }
            if let Some(ref checksum) = item.checksum {
                obj["checksum"] = serde_json::Value::String(checksum.clone());
            }
            if let Some(token_count) = item.approximate_token_count {
                obj["approximate_token_count"] = serde_json::Value::Number(token_count.into());
            }

            obj
        })
        .collect();

    println!("{}", serde_json::to_string_pretty(&json_items)?);
    Ok(())
}

/// Output in YAML format
fn output_yaml(items: &[ListItem]) -> Result<()> {
    let yaml_items: Vec<HashMap<String, serde_yaml::Value>> = items
        .iter()
        .map(|item| {
            let mut obj = HashMap::new();
            obj.insert("name".to_string(), serde_yaml::Value::String(item.name.clone()));
            obj.insert("type".to_string(), serde_yaml::Value::String(item.resource_type.clone()));
            // Safety: ListItem.tool is always Some when created from lockfile.
            // The converter uses unwrap_or_else("claude-code") ensuring this invariant.
            obj.insert(
                "tool".to_string(),
                serde_yaml::Value::String(item.tool.clone().expect("Tool should always be set")),
            );

            if let Some(ref source) = item.source {
                obj.insert("source".to_string(), serde_yaml::Value::String(source.clone()));
            }
            if let Some(ref version) = item.version {
                obj.insert("version".to_string(), serde_yaml::Value::String(version.clone()));
            }
            if let Some(ref path) = item.path {
                obj.insert("path".to_string(), serde_yaml::Value::String(path.clone()));
            }
            if let Some(ref installed_at) = item.installed_at {
                obj.insert(
                    "installed_at".to_string(),
                    serde_yaml::Value::String(installed_at.clone()),
                );
            }
            if let Some(token_count) = item.approximate_token_count {
                obj.insert(
                    "approximate_token_count".to_string(),
                    serde_yaml::Value::Number(token_count.into()),
                );
            }

            obj
        })
        .collect();

    println!("{}", serde_yaml::to_string(&yaml_items)?);
    Ok(())
}

/// Output in compact format
fn output_compact(items: &[ListItem]) {
    for item in items {
        let source = item.source.as_deref().unwrap_or("local");
        let version = item.version.as_deref().unwrap_or("latest");
        println!("{} {} {}", item.name, version, source);
    }
}

/// Output in simple format
fn output_simple(items: &[ListItem]) {
    for item in items {
        println!("{} ({}))", item.name, item.resource_type);
    }
}

/// Column widths for table formatting
struct ColumnWidths {
    name: usize,
    version: usize,
    source: usize,
    resource_type: usize,
    tool: usize,
}

impl ColumnWidths {
    fn calculate(items: &[ListItem]) -> Self {
        Self {
            name: items
                .iter()
                .map(|i| {
                    if i.applied_patches.is_empty() {
                        i.name.len()
                    } else {
                        i.name.len() + 10 // " (patched)" suffix
                    }
                })
                .max()
                .unwrap_or(4)
                .max(4), // "Name" header
            version: items
                .iter()
                .map(|i| i.version.as_deref().unwrap_or("latest").len())
                .max()
                .unwrap_or(7)
                .max(7), // "Version" header
            source: items
                .iter()
                .map(|i| i.source.as_deref().unwrap_or("local").len())
                .max()
                .unwrap_or(6)
                .max(6), // "Source" header
            resource_type: items.iter().map(|i| i.resource_type.len()).max().unwrap_or(4).max(4), // "Type" header
            tool: items
                .iter()
                .map(|i| i.tool.as_deref().unwrap_or("claude-code").len())
                .max()
                .unwrap_or(8)
                .max(8), // "Artifact" header
        }
    }

    fn total_width(&self) -> usize {
        self.name + 1 + self.version + 1 + self.source + 1 + self.resource_type + 1 + self.tool
    }
}

/// Output in table format
fn output_table(items: &[ListItem], config: &OutputConfig) {
    println!("{}", config.title.bold());
    println!();

    // Calculate dynamic column widths based on content
    let widths = ColumnWidths::calculate(items);

    // Sort items by type, tool, then name
    let mut sorted_items: Vec<_> = items.to_vec();
    sorted_items.sort_by(|a, b| {
        a.resource_type
            .cmp(&b.resource_type)
            .then_with(|| a.tool.as_deref().unwrap_or("").cmp(b.tool.as_deref().unwrap_or("")))
            .then_with(|| a.name.cmp(&b.name))
    });

    // Show headers for table format (but not verbose mode)
    if !sorted_items.is_empty() && config.format == "table" && !config.verbose {
        println!(
            "{:<name_w$} {:<ver_w$} {:<src_w$} {:<type_w$} {:<tool_w$}",
            "Name".cyan().bold(),
            "Version".cyan().bold(),
            "Source".cyan().bold(),
            "Type".cyan().bold(),
            "Tool".cyan().bold(),
            name_w = widths.name,
            ver_w = widths.version,
            src_w = widths.source,
            type_w = widths.resource_type,
            tool_w = widths.tool
        );
        println!("{}", "-".repeat(widths.total_width()).bright_black());
    }

    if config.format == "table" && !config.files && !config.detailed && !config.verbose {
        // Print items directly in table format
        for item in &sorted_items {
            print_item_with_widths(item, &widths);
        }
    } else {
        // Simple listing
        if config.should_show_agents {
            let agents: Vec<_> = items.iter().filter(|i| i.resource_type == "agent").collect();
            if !agents.is_empty() {
                println!("{}:", "Agents".cyan().bold());
                for item in agents {
                    print_item(item, &config.format, config.files, config.detailed);
                }
                println!();
            }
        }

        if config.should_show_snippets {
            let snippets: Vec<_> = items.iter().filter(|i| i.resource_type == "snippet").collect();
            if !snippets.is_empty() {
                println!("{}:", "Snippets".cyan().bold());
                for item in snippets {
                    print_item(item, &config.format, config.files, config.detailed);
                }
            }
        }
    }

    println!("{}: {} resources", "Total".green().bold(), items.len());
}

/// Print a single item in detailed mode with patch comparison
async fn print_item_detailed(item: &ListItem, lockfile: &LockFile, cache: Option<&Cache>) {
    let source = item.source.as_deref().unwrap_or("local");
    let version = item.version.as_deref().unwrap_or("latest");

    println!("    {}", item.name.bright_white());
    println!("      Source: {}", source.bright_black());
    println!("      Version: {}", version.yellow());
    if let Some(ref path) = item.path {
        println!("      Path: {}", path.bright_black());
    }
    if let Some(ref installed_at) = item.installed_at {
        println!("      Installed at: {}", installed_at.bright_black());
    }
    if let Some(ref checksum) = item.checksum {
        println!("      Checksum: {}", checksum.bright_black());
    }
    if let Some(token_count) = item.approximate_token_count {
        let formatted = crate::tokens::format_token_count(token_count as usize);
        println!("      Tokens: ~{}", formatted.bright_black());
    }

    // Show patches with original → overridden comparison
    if !item.applied_patches.is_empty() {
        println!("      Applied patches:");

        // If we have cache, try to get original values
        if let Some(cache) = cache {
            // Find the locked resource for this item
            if let Some(locked_resource) = find_locked_resource(item, lockfile) {
                let patch_displays = extract_patch_displays(locked_resource, cache).await;
                for display in patch_displays {
                    let formatted = display.format();
                    // Indent each line of the multi-line diff output
                    for (i, line) in formatted.lines().enumerate() {
                        if i == 0 {
                            // First line: bullet point
                            println!("{}", line);
                        } else {
                            // Subsequent lines: indent to align with content
                            println!("          {}", line);
                        }
                    }
                }
            } else {
                // Fallback: just show overridden values
                print_patches_fallback(&item.applied_patches);
            }
        } else {
            // No cache: just show overridden values
            print_patches_fallback(&item.applied_patches);
        }
    }
    println!();
}

/// Fallback patch display without original values
fn print_patches_fallback(patches: &BTreeMap<String, toml::Value>) {
    let mut patch_keys: Vec<_> = patches.keys().collect();
    patch_keys.sort();
    for key in patch_keys {
        let value = &patches[key];
        let formatted_value = format_patch_value(value);
        println!("{}: {}", key.blue(), formatted_value);
    }
}

/// Find the locked resource corresponding to a list item
fn find_locked_resource<'a>(
    item: &ListItem,
    lockfile: &'a LockFile,
) -> Option<&'a crate::lockfile::LockedResource> {
    // Determine resource type
    let resource_type = match item.resource_type.as_str() {
        "agent" => crate::core::ResourceType::Agent,
        "snippet" => crate::core::ResourceType::Snippet,
        "command" => crate::core::ResourceType::Command,
        "script" => crate::core::ResourceType::Script,
        "hook" => crate::core::ResourceType::Hook,
        "mcp-server" => crate::core::ResourceType::McpServer,
        _ => return None,
    };

    // Find matching resource in lockfile
    lockfile.get_resources(&resource_type).iter().find(|r| r.name == item.name)
}

/// Print a single item in table format with dynamic column widths
fn print_item_with_widths(item: &ListItem, widths: &ColumnWidths) {
    let source = item.source.as_deref().unwrap_or("local");
    let version = item.version.as_deref().unwrap_or("latest");
    let tool = item.tool.as_deref().unwrap_or("claude-code");

    // Build the name field with proper padding before adding colors
    let name_with_indicator = if !item.applied_patches.is_empty() {
        format!("{} (patched)", item.name)
    } else {
        item.name.clone()
    };

    // Apply padding to plain text, then colorize
    let name_field = format!("{:<width$}", name_with_indicator, width = widths.name);
    let version_field = format!("{:<width$}", version, width = widths.version);
    let source_field = format!("{:<width$}", source, width = widths.source);
    let type_field = format!("{:<width$}", item.resource_type, width = widths.resource_type);
    let tool_field = format!("{:<width$}", tool, width = widths.tool);

    println!(
        "{} {} {} {} {}",
        name_field.bright_white(),
        version_field.yellow(),
        source_field.bright_black(),
        type_field.bright_white(),
        tool_field.bright_black()
    );
}

/// Print a single item
fn print_item(item: &ListItem, format: &str, files: bool, detailed: bool) {
    let source = item.source.as_deref().unwrap_or("local");
    let version = item.version.as_deref().unwrap_or("latest");

    if format == "table" && !files && !detailed {
        // Table format with fixed width (fallback, prefer print_item_with_width)
        let name_with_indicator = if !item.applied_patches.is_empty() {
            format!("{} (patched)", item.name)
        } else {
            item.name.clone()
        };

        let name_field = format!("{:<32}", name_with_indicator);
        let colored_name = name_field.bright_white();

        println!(
            "{} {:<15} {:<15} {:<12} {:<15}",
            colored_name,
            version.yellow(),
            source.bright_black(),
            item.resource_type.bright_white(),
            item.tool.clone().expect("Tool should always be set").bright_black()
        );
    } else if files {
        if let Some(ref installed_at) = item.installed_at {
            println!("    {}", installed_at.bright_black());
        } else if let Some(ref path) = item.path {
            println!("    {}", path.bright_black());
        }
    } else if detailed {
        println!("    {}", item.name.bright_white());
        println!("      Source: {}", source.bright_black());
        println!("      Version: {}", version.yellow());
        if let Some(ref path) = item.path {
            println!("      Path: {}", path.bright_black());
        }
        if let Some(ref installed_at) = item.installed_at {
            println!("      Installed at: {}", installed_at.bright_black());
        }
        if let Some(ref checksum) = item.checksum {
            println!("      Checksum: {}", checksum.bright_black());
        }
        if let Some(token_count) = item.approximate_token_count {
            let formatted = crate::tokens::format_token_count(token_count as usize);
            println!("      Tokens: ~{}", formatted.bright_black());
        }
        if !item.applied_patches.is_empty() {
            println!("      {}", "Patches:".cyan());
            let mut patch_keys: Vec<_> = item.applied_patches.keys().collect();
            patch_keys.sort(); // Sort for consistent display
            for key in patch_keys {
                let value = &item.applied_patches[key];
                let formatted_value = format_patch_value(value);
                println!("        {}: {}", key.yellow(), formatted_value.green());
            }
        }
        println!();
    } else {
        let commit_info = if let Some(ref commit) = item.resolved_commit {
            format!("@{}", &commit[..7.min(commit.len())])
        } else {
            String::new()
        };

        println!(
            "    {} {} {} {}",
            item.name.bright_white(),
            format!("({source}))").bright_black(),
            version.yellow(),
            commit_info.bright_black()
        );

        if let Some(ref installed_at) = item.installed_at {
            println!("{}", installed_at.bright_black());
        }
    }
}

/// Format a toml::Value for display in patch output.
///
/// Produces clean, readable output:
/// - Strings: wrapped in quotes `"value"`
/// - Numbers/Booleans: plain text
/// - Arrays/Tables: formatted as TOML syntax
pub fn format_patch_value(value: &toml::Value) -> String {
    match value {
        toml::Value::String(s) => format!("\"{}\"", s),
        toml::Value::Integer(i) => i.to_string(),
        toml::Value::Float(f) => f.to_string(),
        toml::Value::Boolean(b) => b.to_string(),
        toml::Value::Array(arr) => {
            let elements: Vec<String> = arr.iter().map(format_patch_value).collect();
            format!("[{}]", elements.join(", "))
        }
        toml::Value::Table(_) | toml::Value::Datetime(_) => {
            // For complex types, use to_string() as fallback
            value.to_string()
        }
    }
}