Table of Contents

AI Agent Instructions for Albatross.CommandLine

This document provides condensed guidance for AI agents working with the Albatross.CommandLine library (v9).

Overview

Albatross.CommandLine is a .NET library that simplifies CLI application development by wrapping System.CommandLine with automatic code generation and dependency injection. It uses Roslyn incremental source generators to create command infrastructure from annotated classes.

Requirements: System.CommandLine 3.0 (prerelease), Microsoft.Extensions.Hosting 10.x. The core library targets netstandard2.1 and net10.0; create new CLI apps on net10.0. v9 is published on the prerelease channel until System.CommandLine v3 reaches GA.

Stance: the library provides capabilities, not policies. It adds no global options, no console logging and no output format by default — stdout/stderr belong to the command.

Core Architecture

Key Components

Component Purpose
CommandHost Main orchestrator - manages DI, parsing, and execution
BaseHandler<T> Abstract base class for command handlers
VerbAttribute Tags parameter classes and links them to handlers
OptionAttribute / ArgumentAttribute Marks properties as CLI parameters
CommandContext Execution context for sharing state between option handlers and the command handler
ICommandErrorHandler Receives every error the pipeline detects and reports it

Namespaces and Packages

  • Albatross.CommandLine - Core runtime classes (package Albatross.CommandLine, which also bundles the source generator — never reference Albatross.CommandLine.CodeGen separately)
  • Albatross.CommandLine.Annotations - All attributes
  • <RootNamespace>.AutoGenerated - Generated AddCommands() / RegisterCommands()
  • Albatross.CommandLine.Inputs - Built-in reusable parameter types
  • Albatross.CommandLine.Defaults - WithDefaults(): appsettings.json config + file-based Serilog logging
  • Albatross.CommandLine.Outputs - CommandOutput envelope, JSON Print, CompactOption, GlobalErrorHandler

Standard Patterns

Entry Point

using MyApp.AutoGenerated;   // generated RegisterCommands()/AddCommands() live in <RootNamespace>.AutoGenerated

await using var host = new CommandHost("AppName")
    .RegisterServices(RegisterServices)
    .AddCommands()
    .Parse(args)
    .WithDefaults()          // optional (Defaults package): config + file logging
    .Build();
return await host.InvokeAsync();

static void RegisterServices(ParseResult result, IServiceCollection services) {
    services.AddSingleton<ICommandErrorHandler, GlobalErrorHandler>(); // optional (Outputs package)
    services.RegisterCommands(); // Generated method
    // Add custom services
}

Command Definition

[Verb<MyHandler>("command-name", Description = "Help text")]
public record class MyParams {
    [Option(Description = "Output file path")]
    public string? OutputFile { get; init; }

    [Argument(Description = "Input file")]
    public required string InputFile { get; init; }
}

public class MyHandler : BaseHandler<MyParams> {
    public MyHandler(ParseResult result, MyParams parameters) : base(result, parameters) { }

    public override async Task<int> InvokeAsync(CancellationToken token) {
        Writer.WriteLine($"Processing {parameters.InputFile}");
        return 0;
    }
}

All params and handler classes must be declared inside a namespace.

Parent Commands (Grouping)

[Verb("parent", Description = "Parent command group")]
public record class ParentParams { }

[Verb<ChildHandler>("parent child", Description = "Child command")]
public record class ChildParams { }

Printing Results

Print data through the Outputs package so stdout is a stable JSON contract. Diagnostics go to ILogger, never to stdout.

[Verb<GetWidgetsHandler>("get widgets")]
public record class GetWidgetsParams {
    [UseOption<CompactOption>]
    public bool Compact { get; init; }
}

// in the handler
var widgets = await service.GetAll(cancellationToken);
widgets.Print(parameters.Compact);              // indented, colored on a TTY; plain when piped
await widgets.PrintAsync(parameters.Compact, cancellationToken); // no color; Ctrl+C stops it; always valid JSON

result.PrintSuccess("deleted widget 42");       // CommandOutput envelope to stdout
return result.PrintError("widget not found");   // CommandOutput envelope to stderr, returns 1

Prefer PrintAsync for large or unbounded results and for output a program parses; let its OperationCanceledException propagate. Print's indented output is rendered by Spectre, which wraps long lines even when redirected and can break a JSON string.

Results are serialized with System.Text.Json: use System.Text.Json.Serialization attributes on result types. There is no built-in query option; callers shape output with jq.

Logging

WithDefaults() / WithSerilog() log to a daily file under IApplicationPath.LogRoot with no console sink. The level is set in the Serilog section of appsettings.json. There is no --verbosity option; without WithDefaults() there is no logging provider at all.

Naming Conventions

Element Convention Example
Parameters class *Params suffix BackupParams
Generated command Remove Params, add Command BackupCommand
Handler class *Handler or *CommandHandler BackupHandler
Properties to CLI kebab-case OutputFolder → --output-folder
Option aliases Single char: -x, multi: --name -o, --output

Attribute Quick Reference

VerbAttribute

[Verb<THandler>("name")]                                           // Standard command
[Verb<THandler>("name", BaseParamsClass = typeof(TBase))]          // Params class derived from a shared base
[Verb("name")]                                                     // Parent command (no handler)
[assembly: Verb<TParams, THandler>("name")]                        // Assembly level only (e.g. reusing a handler type)

OptionAttribute

[Option("-o", Description = "...", Required = true)]               // aliases; the name still comes from the property
[Option(DefaultToInitializer = true)]                              // Use property initializer as default
[Option(AllowMultipleArgumentsPerToken = true)]                    // --items a b c

ArgumentAttribute

[Argument(Description = "...")]
[Argument(ArityMin = 1, ArityMax = 10)]     // For collections

Default Requirement Rules

  • Non-nullable types → Required
  • Nullable types → Optional
  • Boolean flags → Optional
  • Collections → Optional
  • With DefaultToInitializer = true → Optional

Advanced Patterns

Reusable Parameters

A reusable option needs a (string name, params string[] aliases) constructor; a reusable argument needs (string name).

// Define once
[DefaultNameAliases("--input", "-i")]
public class InputFileOption : Option<FileInfo> {
    public InputFileOption(string name, params string[] aliases) : base(name, aliases) {
        Description = "Input file path";
        Validators.Add(result => {
            if (result.GetValue(this) is FileInfo file && !file.Exists)
                result.AddError($"File not found: {file.FullName}");
        });
    }
}

[Verb<MyHandler>("process")]
public record class ProcessParams {
    // Use via attribute
    [UseOption<InputFileOption>]
    public FileInfo? Input { get; init; }
}

Option Preprocessing (Validation)

To stop the command, record an error on the context or throw. Either way the command handler is skipped and the error is reported through ICommandErrorHandler with ErrorSource.OptionHandler.

[DefaultNameAliases("--my-option", "-m")]
[OptionHandler<MyOption, MyOptionHandler>]
public class MyOption : Option<string> {
    public MyOption(string name, params string[] aliases): base(name, aliases){ 
        Description = "Custom option description";
    }
}

public class MyOptionHandler : IAsyncOptionHandler<MyOption> {
    private readonly ICommandContext _context;

    public MyOptionHandler(ICommandContext context) => _context = context;

    public async Task InvokeAsync(MyOption symbol, ParseResult result, CancellationToken token) {
        var text = result.GetValue(symbol);
        if(!string.IsNullOrEmpty(text)) {
            var err = await ValidateAsync(text);
            if(!string.IsNullOrEmpty(err)) {
                _context.SetInputActionError(new Error(ErrorSource.OptionHandler, symbol.Name, err, null));
            }
        }
    }
    async Task<string?> ValidateAsync(string value) {
        // custom validation logic
    }
}

Input Transformation

Transform a simple input (e.g., string identifier) into a complex object (e.g., DTO) before it reaches the command handler.

// Define the output type
public record class InstrumentSummary {
    public required int Id { get; init; }
    public required string Name { get; init; }
}

// Define the option with transformation handler
[DefaultNameAliases("--instrument", "-i")]
[OptionHandler<InstrumentOption, InstrumentOptionHandler, InstrumentSummary>]
public class InstrumentOption : Option<string> {
    public InstrumentOption(string name, params string[] alias) : base(name, alias) {
        this.Description = "The security instrument identifier";
    }
}

// Implement the transformation handler
public class InstrumentOptionHandler : IAsyncOptionHandler<InstrumentOption, InstrumentSummary> {
    private readonly InstrumentService instrumentService;

    public InstrumentOptionHandler(InstrumentService instrumentService) {
        this.instrumentService = instrumentService;
    }

    public async Task<OptionHandlerResult<InstrumentSummary>> InvokeAsync(
        InstrumentOption option, ParseResult result, CancellationToken cancellationToken) {
        var text = result.GetValue(option);
        if (string.IsNullOrEmpty(text)) {
            return new OptionHandlerResult<InstrumentSummary>();
        } else {
            var data = await instrumentService.GetSummary(text, cancellationToken);
            return new OptionHandlerResult<InstrumentSummary>(data);
        }
    }
}

// Use in params class - property type is the transformed type
[Verb<GetInstrumentDetails>("instrument detail", Description = "Get instrument details")]
public record class GetInstrumentDetailsParams {
    [UseOption<InstrumentOption>]
    public required InstrumentSummary Summary { get; init; }
}

// Handler receives the transformed object
public class GetInstrumentDetails : BaseHandler<GetInstrumentDetailsParams> {
    public GetInstrumentDetails(ParseResult result, GetInstrumentDetailsParams parameters)
        : base(result, parameters) { }

    public override Task<int> InvokeAsync(CancellationToken cancellationToken) {
        Writer.WriteLine($"Instrument: {parameters.Summary.Name} (ID: {parameters.Summary.Id})");
        return Task.FromResult(0);
    }
}

Mutually Exclusive Parameters

public abstract record class BaseParams {
    [Option]
    public bool DryRun { get; init; }
}

[Verb<SharedHandler>("cmd option-a", BaseParamsClass = typeof(BaseParams))]
public record class OptionAParams : BaseParams {
    [Option]
    public string? OptionA { get; init; }
}

[Verb<SharedHandler>("cmd option-b", BaseParamsClass = typeof(BaseParams))]
public record class OptionBParams : BaseParams {
    [Option]
    public int OptionB { get; init; }
}

public class SharedHandler : BaseHandler<BaseParams> {
    public SharedHandler(ParseResult result, BaseParams parameters) : base(result, parameters) { }

    public override async Task<int> InvokeAsync(CancellationToken token) {
        return parameters switch {
            OptionAParams a => HandleA(a),
            OptionBParams b => HandleB(b),
            _ => throw new NotSupportedException($"Unsupported parameters type: {parameters.GetType()}")
        };
    }
}

Command Customization

Generated command classes are partial. Add custom initialization:

// In your code
public partial class MyCommand {
    partial void Initialize() {
        // Access Option_* and Argument_* properties
        Option_OutputFile.Validators.Add(result => {
            if (result.GetValue(Option_OutputFile) is FileInfo file && file.Exists)
                result.AddError($"{file.FullName} already exists");
        });
    }
}

Built-in Input Types

From Albatross.CommandLine.Inputs:

  • InputFileOption / InputFileArgument - Validates file exists
  • InputDirectoryOption / InputDirectoryArgument - Validates directory exists
  • OutputFileOption - For output file paths
  • OutputDirectoryOption / OutputDirectoryArgument - For output directories
  • OutputDirectoryWithAutoCreateOption - Auto-creates if missing
  • TimeZoneOption - For timezone name inputs
  • ConfirmOption - Prompts for confirmation before proceeding
  • TrackerOption - Records processed items so a rerun skips them

Execution Pipeline

Parse Arguments
    ↓
Create DI Scope
    ↓
Option PreActions (IAsyncOptionHandler implementations)
    ↓ (stop if any recorded an error or threw)
Command Action (IAsyncCommandHandler.InvokeAsync)
    ↓
Errors (option handler, service resolution, command handler, cancellation) → ICommandErrorHandler
    ↓
Dispose Scope

Errors are logged where they are caught; the error handler only reports them and picks the exit code (default 1).

Code Generation Output

The source generator creates:

  1. Command classes - One per [Verb] with Option_* and Argument_* properties
  2. RegisterCommands() - Registers params classes and handlers in DI
  3. AddCommands() - Adds commands to CommandBuilder

View generated code: Set <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> in project file, check obj/generated/.

Common Tasks

Add a New Command

  1. Create params class with [Verb<Handler>("name")]
  2. Add properties with [Option] or [Argument]
  3. Create handler extending BaseHandler<T>
  4. Implement InvokeAsync; print data with Print

DI Services Available

  • ParseResult - System.CommandLine parse result
  • ICommandContext - Execution context
  • T parameters - The params class instance
  • ILogger<T> - Logging (a log file with WithDefaults(); nowhere without)
  • IConfiguration - Requires WithConfig() or WithDefaults()
  • Any custom registered services

Key Differences from Raw System.CommandLine

  1. Attribute-driven - No manual command building
  2. DI-first - All handlers receive dependencies via constructor
  3. Async-only - Handlers use InvokeAsync with cancellation support
  4. Generated code - Commands, registration, and wiring are auto-generated
  5. Parameters injection - Handler receives typed params object, not individual values
  6. Unified error contract - Every failure is an Error routed to one ICommandErrorHandler