Skip to content

Latest commit

 

History

History
192 lines (145 loc) · 7.48 KB

plugins.md

File metadata and controls

192 lines (145 loc) · 7.48 KB

Plugins

Plugin support is optional. Respect.CommandLine does not discover directories, scan assemblies, or load code automatically. A conventional CLI can use CommandRegistry.Register and ignore every API on this page.

A plugin host adds two responsibilities:

  1. decide which assemblies are trusted and load them;
  2. register the command provider and handler resolver they expose.

A plugin references Respect.CommandLine.Abstractions, not the engine package.

Define a plugin

[assembly: PluginContract(ContractVersion.Current)]

public sealed class SamplePlugin : ICommandProvider, ICommandHandlerResolver
{
    public string SourceId => "sample-plugin";

    public ValueTask<IReadOnlyList<CommandContribution>> GetCommandsAsync(
        CancellationToken cancellationToken)
        => ValueTask.FromResult<IReadOnlyList<CommandContribution>>
        ([
            new CommandContribution
            {
                SourceId = SourceId,
                Descriptor = CommandBuilder.Create("sample.greet", "greet")
                    .Summary("Greet someone.")
                    .Option("loud", option => option.Summary("Use upper-case output."))
                    .Argument("name", argument => argument.Optional())
                    .Build(),
            },
        ]);

    public bool TryResolve(CommandId commandId, out ICommandHandler? handler)
    {
        handler = commandId.Value == "sample.greet" ? new GreetHandler() : null;
        return handler is not null;
    }
}

ICommandProvider declares commands as data. ICommandHandlerResolver supplies the executable handlers for their CommandId values. Keeping them separate lets the same descriptors be executed in process today or by another ICommandInvoker later.

The registry calls GetCommandsAsync lazily when it needs a catalog. If the provider throws, its commands are omitted and RCL2007 is reported; other application and plugin commands remain available.

Extend an existing command

ParentPath mounts a contribution under a command the plugin does not own:

new CommandContribution
{
    SourceId = SourceId,
    ParentPath = ["build"],
    Descriptor = CommandBuilder.Create("sample.build.wasm", "wasm")
        .Summary("Build for WebAssembly.")
        .Option("optimize", option => option
            .Short('O')
            .Takes(ValueTypeRef.Int32)
            .ValueName("LEVEL"))
        .Build(),
}

If the host has a build command, this adds acme build wasm -O 2. The plugin never receives or modifies the host's descriptor. An unresolved path drops only that contribution and reports RCL2005.

Register it

Once the host has created a provider and resolver, registration is explicit:

var commandRegistration = registry.RegisterSource(provider);
var handlerRegistration = handlers.AddResolver(resolver);

Both calls return IDisposable tokens. Dispose them to remove the plugin's commands and handler resolver.

A transport discovered after the application was constructed — a worker process, for example — is added to the existing invoker chain with app.AddInvoker(invoker). The default in-process invoker stays first, so the late invoker receives only the InvocationTarget values its CanInvoke accepts. This is the runtime seam for an out-of-process command: the descriptor and handler registry stay in the host, while InvokeAsync owns the child process and returns its exit code.

The sample PluginLoader demonstrates assembly discovery, contract checks, collectible load contexts, diagnostics, and unloading. It is host code rather than framework policy: another application may use a manifest, a signed package store, a fixed allowlist, or no dynamic loading at all.

Validate before using plugin types

Plugins declare their contract version in assembly metadata:

var contract = assembly.GetCustomAttribute<PluginContractAttribute>();

if (contract is null || !ContractVersion.IsSupported(contract.Version))
{
    // Report the assembly and skip it.
}

Perform this check before enumerating or instantiating exported plugin types. It is a compatibility check, not a trust check: it says that the host understands the plugin contract, not that the code is safe.

When using AssemblyLoadContext, give each plugin a collectible context and share the host's Respect.CommandLine.Abstractions assembly:

protected override Assembly? Load(AssemblyName assemblyName)
{
    if (assemblyName.Name == "Respect.CommandLine.Abstractions")
    {
        return null;
    }

    var path = _resolver.ResolveAssemblyToPath(assemblyName);
    return path is null ? null : LoadFromAssemblyPath(path);
}

If a plugin loads a second copy of the abstractions assembly, its ICommandProvider is a different runtime type from the host's interface and cannot be registered.

Send loader failures through ApplicationOptions.InitialDiagnostics. They then follow the same terminal and --json rules as parser and execution diagnostics.

Control conflicts

Command names and IDs use different rules:

  • A duplicate CommandId is an error unless the contribution explicitly sets Replace = true.
  • Under the default PriorityThenQualify policy, the higher-priority command keeps a contested name and the loser remains available as source:name.
  • FirstWins drops later name collisions.
  • Fail records the collision as an error. Combine it with ApplicationOptions.FailOnCatalogErrors = true to stop before routing any command.

Give built-in commands CommandContribution.BuiltInPriority. A host accepting untrusted contributions should also normalize plugin priorities and reject Replace unless its own policy allows overrides; values supplied by plugin code are declarations, not permissions.

Every contribution returned by a registered provider is attributed to the provider's SourceId, so it cannot impersonate another source by changing CommandContribution.SourceId.

Trust boundary

A loaded in-process plugin runs with the host process's permissions. It can read files, access the network, call framework APIs, and ignore the abstractions offered through CommandContext. AssemblyLoadContext isolates dependency versions and enables unloading; it is not a sandbox.

Before loading third-party code, the host should enforce its trust policy using controls such as a fixed allowlist, signatures, manifests, or a directory writable only by an administrator. Code that must be isolated belongs in another process with operating-system restrictions. Respect.CommandLine exposes ICommandInvoker as the execution seam, but does not yet ship an out-of-process transport.

See SECURITY.md for the security policy.

Unload safely

Dispose registrations before unloading the context:

commandRegistration.Dispose();
handlerRegistration.Dispose();
context.Unload();

Do not retain plugin instances, Type objects, handlers, or other references outside the collectible context. The integration tests verify that the sample plugin's assembly is collected after unloading.

Every invocation uses one immutable CommandCatalog snapshot. Unloading a plugin removes it from future snapshots but cannot change the route of a command already running.

Native AOT

Runtime assembly loading requires a JIT runtime. A host that loads plugins cannot be published as a Native AOT executable. Static command registration remains Native AOT compatible; the Sample.Aot project is published in CI with trimming warnings as errors.