Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-cli/src/cli.rs

Raw
//! Command-line engine boundary (`SMH-SPEC-SPEC0001`).
//!
//! Commands include credential management, eval, read-only observation, session inspection, and JSON-RPC.
//! Eval and RPC use the shared runtime assembly from `smith-harness`.

use clap::{CommandFactory, FromArgMatches, Parser, ValueEnum};
use smith::error::Result;
use smith_harness::catalog::{refresh_models_dev, startup_catalog};
use smith_harness::durable::{ReadOnlyControl, writer_backend};
use smith_harness::http::default_executor;
use smith_harness::oauth::login::SubscriptionProvider;
use smith_harness::plugin_control::request_reload;
use smith_harness::plugins::registry::{PackageRegistry, PackageSource};
use smith_harness::plugins::{Capability, NetScope, PluginPackage};
use smith_harness::protocol::ProtocolConnection;
use smith_harness::runtime::{RuntimeConfig, RuntimeProvider, validate_catalog_model};
use smith_harness::trust::TrustStore;
use smith_harness::wasm::{PluginEngine, PluginGeneration, PluginRegistry, SecretGrantConfig};
use smith_harness::{
    AuthStore, CredentialKey, ProviderKind, RefreshOutcome, credential_key_env_var_present,
    credential_key_env_vars,
};
use smith_rpc::{RpcState, handle_line};
use std::io::{BufRead, Read, Write};
use std::path::Path;
use std::process::Command as ProcessCommand;
use std::sync::Arc;
use std::{fmt, io};

#[path = "login_cancellation.rs"]
mod login_cancellation;

/// Smith, a fast coding-agent runtime.
#[derive(Debug, Parser)]
#[command(name = "smith", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

/// Interface mode.
#[derive(Debug, Parser)]
enum Command {
    /// Store API credentials or sign in to a subscription; never guess billing mode.
    #[command(
        about = "Store API credentials or sign in to a subscription; never guess billing mode"
    )]
    Login {
        /// Vendor billing connection: API credentials or subscription sign-in.
        #[arg(long, default_value = "openai-chatgpt-plan")]
        provider: ProviderArg,
        /// Subscription-only Google Cloud project used for Code Assist setup.
        #[arg(long)]
        project: Option<String>,
        /// Subscription-only: reauthorize this exact saved registration; never register another client implicitly.
        #[arg(long)]
        profile: Option<String>,
        /// Subscription-only trusted loopback issuer; uses a separate fixture-only profile namespace.
        #[arg(long)]
        fixture_issuer: Option<String>,
    },
    /// End one subscription session; retain profile identity for later sign-in.
    Logout {
        /// Explicit subscription billing connection.
        #[arg(long, default_value = "openai-chatgpt-plan")]
        provider: SubscriptionArg,
        /// Exact saved profile identity.
        #[arg(long)]
        profile: String,
        /// Explicit isolated loopback fixture namespace.
        #[arg(long)]
        fixture_issuer: Option<String>,
    },
    /// Manage stored provider credentials.
    Auth {
        #[command(subcommand)]
        action: AuthAction,
    },
    /// Run one prompt without the TUI.
    Eval {
        /// Exact subscription profile; required for subscription connections.
        #[arg(long)]
        profile: Option<String>,
        /// Explicit isolated loopback subscription fixture namespace.
        #[arg(long)]
        fixture_issuer: Option<String>,
        /// Trusted credential-module package selected for this subscription only.
        #[arg(long, requires = "profile")]
        credential_module: Option<String>,
        /// The prompt to run.
        prompt: String,
        /// Print the structured outcome as JSON.
        #[arg(long)]
        json: bool,
        /// Explicitly resume this existing session ID.
        #[arg(long)]
        session: Option<smith::id::SessionId>,
        #[command(flatten)]
        selection: ExecutionProviderArgs,
    },
    /// Inspect or explicitly refresh the offline model catalog.
    Catalog {
        #[command(subcommand)]
        action: CatalogAction,
    },
    /// Inspect a plugin package without invoking its operational tools.
    Plugin {
        #[command(subcommand)]
        action: PluginAction,
    },
    /// Attach read-only to a session, including one owned by another writer.
    Observe {
        /// Session identity to observe without provider or tool initialization.
        id: smith::id::SessionId,
        /// Optional explicit export target; created only on 'e', never overwritten.
        #[arg(long)]
        export: Option<std::path::PathBuf>,
    },
    /// Inspect stored sessions without acquiring a writer or provider.
    Sessions {
        #[command(subcommand)]
        action: SessionAction,
    },
    /// Serve LF-delimited JSON-RPC on standard input and output.
    Rpc {
        /// Explicitly resume this existing session ID.
        #[arg(long)]
        session: Option<smith::id::SessionId>,
        /// Inspect an existing session without provider, auth, or network setup.
        #[arg(long, requires = "session")]
        read_only: bool,
        #[command(flatten)]
        selection: ProviderArgs,
    },
}

/// Shared provider declarations for every execution surface.
#[derive(Debug, clap::Args)]
struct ProviderArgs {
    /// Provider kind; required for real endpoints.
    #[arg(long, env = "SMITH_PROVIDER", hide_env_values = true)]
    provider: Option<ProviderArg>,
    /// Model id; required for real endpoints.
    #[arg(long, env = "SMITH_MODEL", hide_env_values = true)]
    model: Option<String>,
    /// Endpoint base URL override.
    #[arg(long, env = "SMITH_BASE_URL", hide_env_values = true)]
    base_url: Option<String>,
    /// Request streamed usage; explicit value replaces user and trusted project settings.
    #[arg(long, action = clap::ArgAction::Set)]
    include_usage: Option<bool>,
    /// Host-owned state for one qualified component tool: `name=advertised|hidden|disabled`.
    #[arg(long = "tool-policy", action = clap::ArgAction::Append)]
    tool_policy: Vec<String>,
    /// Delegate a descendant directory: qualified-caller=qualified-target#directory.
    #[arg(long = "tool-delegation", action = clap::ArgAction::Append)]
    tool_delegation: Vec<String>,
}

#[derive(Debug, clap::Args)]
struct ExecutionProviderArgs {
    /// Use the scripted mock provider instead of a real endpoint.
    #[arg(long)]
    r#mock: bool,
    #[command(flatten)]
    connection: ProviderArgs,
}

/// Catalog operations.
#[derive(Debug, Parser)]
enum CatalogAction {
    /// Fetch, validate, cache, and publish a current models.dev snapshot.
    Refresh {
        /// Persistent cache path. CLI overrides `SMITH_CATALOG_CACHE`.
        #[arg(long, env = "SMITH_CATALOG_CACHE")]
        cache: Option<std::path::PathBuf>,
    },
    /// List offline catalog models grouped by executable connection without network access.
    Show {
        /// Persistent cache path. CLI overrides `SMITH_CATALOG_CACHE`.
        #[arg(long, env = "SMITH_CATALOG_CACHE")]
        cache: Option<std::path::PathBuf>,
        /// Restrict output to one connection name.
        #[arg(long, value_enum)]
        provider: Option<ProviderArg>,
        /// Emit a structured listing.
        #[arg(long)]
        json: bool,
    },
    /// Report effective offline catalog source and model count without network access.
    Status {
        /// Persistent cache path. CLI overrides `SMITH_CATALOG_CACHE`.
        #[arg(long, env = "SMITH_CATALOG_CACHE")]
        cache: Option<std::path::PathBuf>,
    },
}

/// Plugin package operations.
#[derive(Debug, Parser)]
enum PluginAction {
    /// Create a plugin package with a pinned world copy.
    Init {
        /// New package directory.
        package: std::path::PathBuf,
        /// Plugin name used in manifest and language project names.
        #[arg(long)]
        name: String,
        /// Guest language adapter.
        #[arg(long, value_enum, default_value_t = PluginLanguageArg::Rust)]
        language: PluginLanguageArg,
    },
    /// Explicitly build a package through its selected language adapter.
    Build {
        /// Package directory containing its language project.
        package: std::path::PathBuf,
    },
    /// Build then validate a package in the sealed plugin host.
    Test {
        /// Package directory containing plugin.kdl and plugin-test.json.
        package: std::path::PathBuf,
        /// Capability grant available to mocked guest calls.
        #[arg(long, value_enum)]
        grant: Vec<CapabilityArg>,
    },
    /// Validate, hash, and register a user package for live runtimes.
    Install {
        /// Package directory containing plugin.kdl and its artifact.
        package: std::path::PathBuf,
        /// Capability grant accepted at install time.
        #[arg(long, value_enum)]
        grant: Vec<CapabilityArg>,
        /// Explicit HTTPS or literal-loopback HTTP origin for net-scope.
        #[arg(long = "net-origin")]
        net_origin: Vec<String>,
        /// Guest credential-source id granted to this package.
        #[arg(long = "secret-source")]
        secret_source: Option<String>,
        /// Auth-store provider selected for the secret source.
        #[arg(long = "secret-provider", value_enum)]
        secret_provider: Option<ProviderArg>,
        /// Explicit origin allowed to receive the exchanged secret.
        #[arg(long = "secret-origin")]
        secret_origin: Option<String>,
        /// Explicit scope allowed for the exchanged secret.
        #[arg(long = "secret-scope", value_enum)]
        secret_scope: Vec<SecretScopeArg>,
    },
    /// Register a canonical development source with precedence over installs.
    Link {
        /// Package directory containing plugin.kdl and its artifact.
        package: std::path::PathBuf,
        /// Capability grant accepted for this development link.
        #[arg(long, value_enum)]
        grant: Vec<CapabilityArg>,
        /// Explicit HTTPS or literal-loopback HTTP origin for net-scope.
        #[arg(long = "net-origin")]
        net_origin: Vec<String>,
        /// Guest credential-source id granted to this package.
        #[arg(long = "secret-source")]
        secret_source: Option<String>,
        /// Auth-store provider selected for the secret source.
        #[arg(long = "secret-provider", value_enum)]
        secret_provider: Option<ProviderArg>,
        /// Explicit origin allowed to receive the exchanged secret.
        #[arg(long = "secret-origin")]
        secret_origin: Option<String>,
        /// Explicit scope allowed for the exchanged secret.
        #[arg(long = "secret-scope", value_enum)]
        secret_scope: Vec<SecretScopeArg>,
    },
    /// List installed packages and development links without loading artifacts.
    List,
    /// Remove every installed and development-link source for one plugin id.
    Remove {
        /// Plugin manifest id.
        id: String,
    },
    /// Validate then publish the persisted package set to one runtime or every live runtime.
    Reload {
        /// Select one session runtime instead of every live runtime.
        #[arg(long)]
        session: Option<smith::id::SessionId>,
    },
    /// Watch, rebuild, validate, and publish one development link.
    Dev {
        /// Package directory containing plugin.kdl and its language project.
        package: std::path::PathBuf,
        /// Select one session runtime instead of every live runtime.
        #[arg(long)]
        session: Option<smith::id::SessionId>,
        /// Capability grant accepted for this development link.
        #[arg(long, value_enum)]
        grant: Vec<CapabilityArg>,
        /// Source scan interval in milliseconds.
        #[arg(long, default_value_t = 250, value_parser = clap::value_parser!(u64).range(10..=5_000))]
        watch_interval_ms: u64,
    },
    /// Persist a canonical project package trust decision and its exact grants.
    Trust {
        /// Package directory to trust.
        package: std::path::PathBuf,
        /// Capability grant accepted at trust time.
        #[arg(long, value_enum)]
        grant: Vec<CapabilityArg>,
        /// Explicit HTTPS or literal-loopback HTTP origin for net-scope.
        #[arg(long = "net-origin")]
        net_origin: Vec<String>,
        /// Guest credential-source id granted to this package.
        #[arg(long = "secret-source")]
        secret_source: Option<String>,
        /// Auth-store provider selected for the secret source.
        #[arg(long = "secret-provider", value_enum)]
        secret_provider: Option<ProviderArg>,
        /// Explicit origin allowed to receive the exchanged secret.
        #[arg(long = "secret-origin")]
        secret_origin: Option<String>,
        /// Explicit scope allowed for the exchanged secret.
        #[arg(long = "secret-scope", value_enum)]
        secret_scope: Vec<SecretScopeArg>,
    },
    /// Validate a trusted package's grants, world, artifact, and declarations.
    Check {
        /// Package directory containing plugin.kdl and its artifact.
        package: std::path::PathBuf,
        /// Trust this exact package path for this check only.
        #[arg(long)]
        trust: bool,
        /// Capability grant available while checking the package.
        #[arg(long, value_enum)]
        grant: Vec<CapabilityArg>,
    },
}

/// Capability grant accepted by plugin tooling.
#[derive(Clone, Copy, Debug, ValueEnum)]
enum CapabilityArg {
    /// Scoped network HTTP effect.
    NetScope,
    /// Credential exchange effect.
    SecretProxy,
    /// Bounded diagnostic logging effect.
    Log,
    /// Scoped workspace filesystem effects.
    Workspace,
    /// Supervised commands inherit host-user filesystem and network access.
    Process,
}

impl CapabilityArg {
    const fn capability(self) -> Capability {
        match self {
            Self::NetScope => Capability::NetScope,
            Self::SecretProxy => Capability::SecretProxy,
            Self::Log => Capability::Log,
            Self::Workspace => Capability::Workspace,
            Self::Process => Capability::Process,
        }
    }
}

fn grants_from_args(grants: Vec<CapabilityArg>) -> Vec<Capability> {
    grants.into_iter().map(CapabilityArg::capability).collect()
}

fn net_scopes_from_args(origins: &[String]) -> Result<Vec<NetScope>> {
    origins
        .iter()
        .map(|origin| NetScope::parse(origin))
        .collect()
}

/// Guest secret scope accepted by the current HTTP-only proxy boundary.
#[derive(Clone, Copy, Debug, ValueEnum)]
enum SecretScopeArg {
    /// Substitute an exchanged reference only in an authorized HTTP request header.
    HttpRequest,
}

impl SecretScopeArg {
    const fn name(self) -> &'static str {
        match self {
            Self::HttpRequest => "http-request",
        }
    }
}

fn secret_grants_from_args(
    source: Option<String>,
    provider: Option<ProviderArg>,
    origin: Option<String>,
    scopes: Vec<SecretScopeArg>,
) -> Result<Vec<SecretGrantConfig>> {
    match (source, provider, origin, scopes.is_empty()) {
        (None, None, None, true) => Ok(Vec::new()),
        (Some(source), Some(provider), Some(origin), false) => Ok(vec![SecretGrantConfig::new(
            source,
            NetScope::parse(&origin)?,
            scopes
                .into_iter()
                .map(SecretScopeArg::name)
                .map(str::to_string)
                .collect(),
            provider.credential_key()?,
        )?]),
        _ => Err(plugin_command_fault(
            "secret authority requires --secret-source, --secret-provider, --secret-origin, and --secret-scope",
        )),
    }
}

const fn package_source_name(source: PackageSource) -> &'static str {
    match source {
        PackageSource::Installed => "installed",
        PackageSource::DevLink => "linked",
    }
}

/// Read-only inspection operations.
#[derive(Debug, Parser)]
enum SessionAction {
    /// List session IDs and file sizes in stable ID order.
    List {
        #[arg(long)]
        json: bool,
    },
    /// Read all recorded entries in physical order.
    Get {
        id: smith::id::SessionId,
        #[arg(long)]
        json: bool,
    },
    /// Search literal case-sensitive UTF-8 substring across all recorded branches.
    /// Exit 1 when no match; exit 2 on error.
    Grep {
        pattern: String,
        #[arg(long)]
        json: bool,
    },
    /// Durably queue user input without scheduling provider or tool execution.
    Submit {
        /// Existing session identity.
        id: smith::id::SessionId,
        /// Text input to queue.
        input: String,
        /// Session-scoped deduplication key.
        #[arg(long)]
        key: Option<String>,
    },
    /// Execute exactly one already admitted text-only turn; no tools advertised.
    Execute {
        /// Existing session identity.
        id: smith::id::SessionId,
        /// Durable submission identity.
        #[arg(value_parser = parse_entry_id)]
        submission_id: smith::id::EntryId,
        #[command(flatten)]
        selection: ExecutionProviderArgs,
    },
    /// Inspect durable queued, running (recovery-required), or terminal state.
    Receipt {
        /// Existing session identity.
        id: smith::id::SessionId,
        /// Durable submission identity.
        #[arg(value_parser = parse_entry_id)]
        submission_id: smith::id::EntryId,
    },
}

fn parse_entry_id(text: &str) -> std::result::Result<smith::id::EntryId, String> {
    smith::id::proquint::decode(text)
        .map(smith::id::EntryId::from_u128)
        .map_err(|error| error.to_string())
}

/// Credential operations.
#[derive(Debug, Parser)]
enum AuthAction {
    /// List OAuth profile metadata, never tokens or unverified account claims.
    Profiles {
        /// Explicit subscription billing connection.
        #[arg(long, default_value = "openai-chatgpt-plan")]
        provider: SubscriptionArg,
        /// Explicit loopback fixture namespace, never production profiles.
        #[arg(long)]
        fixture_issuer: Option<String>,
    },
    /// Store a credential read from standard input.
    Add {
        /// Provider the credential belongs to.
        #[arg(long)]
        provider: ProviderArg,
    },
    /// List local credential sources; account access is not verified.
    List,
    /// Delete one stored credential.
    Remove {
        /// Provider whose credential is deleted.
        #[arg(long)]
        provider: ProviderArg,
    },
    /// Check one local credential source without remote verification.
    Check {
        /// Provider whose credential is checked.
        #[arg(long)]
        provider: ProviderArg,
    },
}

/// Provider names accepted on the command line.
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum ProviderArg {
    /// OpenAI-compatible endpoints.
    Openai,
    /// `ChatGPT` plan through Responses; requires explicit profile and model.
    OpenaiChatgptPlan,
    /// Claude subscription; explicit local profile, no API-key fallback.
    AnthropicClaudePlan,
    /// Google Gemini CLI subscription; no API-key fallback.
    GoogleGeminiCliPlan,
    /// Anthropic Messages API.
    Anthropic,
    /// Google Gemini API.
    Google,
    /// Metered Z.ai API connection.
    Zai,
    /// Z.ai Coding Plan connection; never falls back to metered API billing.
    ZaiCodingPlan,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum SubscriptionArg {
    #[value(name = "openai-chatgpt-plan")]
    OpenaiChatgpt,
    #[value(name = "anthropic-claude-plan")]
    AnthropicClaude,
    #[value(name = "google-gemini-cli-plan")]
    GoogleGeminiCli,
}

impl SubscriptionArg {
    const fn provider(self) -> SubscriptionProvider {
        match self {
            Self::OpenaiChatgpt => SubscriptionProvider::OpenAi,
            Self::AnthropicClaude => SubscriptionProvider::Anthropic,
            Self::GoogleGeminiCli => SubscriptionProvider::Google,
        }
    }
}

impl ProviderArg {
    const ALL: [Self; 5] = [
        Self::Openai,
        Self::Anthropic,
        Self::Google,
        Self::Zai,
        Self::ZaiCodingPlan,
    ];

    const fn subscription(self) -> Option<SubscriptionProvider> {
        match self {
            Self::OpenaiChatgptPlan => Some(SubscriptionProvider::OpenAi),
            Self::AnthropicClaudePlan => Some(SubscriptionProvider::Anthropic),
            Self::GoogleGeminiCliPlan => Some(SubscriptionProvider::Google),
            _ => None,
        }
    }

    const fn connection_id(self) -> &'static str {
        match self {
            Self::Openai => "openai-compatible-api",
            Self::OpenaiChatgptPlan => "openai-chatgpt-plan",
            Self::AnthropicClaudePlan => "anthropic-claude-plan",
            Self::GoogleGeminiCliPlan => "google-gemini-cli-plan",
            Self::Anthropic => "anthropic-api",
            Self::Google => "google-api",
            Self::Zai => "zai-api",
            Self::ZaiCodingPlan => "zai-coding-plan",
        }
    }

    const fn kind(self) -> ProviderKind {
        match self {
            Self::Openai | Self::OpenaiChatgptPlan => ProviderKind::OpenAiCompatible,
            Self::Anthropic | Self::AnthropicClaudePlan => ProviderKind::Anthropic,
            Self::Google | Self::GoogleGeminiCliPlan => ProviderKind::Google,
            Self::Zai | Self::ZaiCodingPlan => ProviderKind::Zai,
        }
    }

    const fn zai_connection(self) -> Option<ProtocolConnection> {
        match self {
            Self::Zai => Some(ProtocolConnection::Api),
            Self::ZaiCodingPlan => Some(ProtocolConnection::CodingPlan),
            Self::Openai
            | Self::OpenaiChatgptPlan
            | Self::Anthropic
            | Self::AnthropicClaudePlan
            | Self::GoogleGeminiCliPlan
            | Self::Google => None,
        }
    }

    fn credential_key(self) -> Result<CredentialKey> {
        match self {
            Self::OpenaiChatgptPlan | Self::AnthropicClaudePlan | Self::GoogleGeminiCliPlan => {
                Err(plugin_command_fault(
                    "subscription auth uses login/auth profiles, not API-key add/check/remove",
                ))
            }
            Self::ZaiCodingPlan => Ok(CredentialKey::ZaiCodingPlan),
            Self::Openai | Self::Anthropic | Self::Google | Self::Zai => {
                Ok(CredentialKey::Provider(self.kind()))
            }
        }
    }
}

/// Help-path work surface measured by the startup instruction ceiling.
///
/// Counts come from the parsed command tree used by short help.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HelpSurface {
    /// Constructed command nodes.
    pub command_nodes: u64,
    /// Argument placements after Clap propagated global arguments.
    pub argument_placements: u64,
    /// UTF-8 bytes rendered by root short help.
    pub rendered_bytes: u64,
}

/// Collect the actual root short-help surface without executing a command.
///
/// This creates the same derived Clap tree as [`run`], parses `smith --help`,
/// then examines its propagated tree. It is used only outside Callgrind.
/// # Errors
/// Returns an error if help parsing fails or a surface count exceeds `u64`.
pub fn short_help_surface() -> std::result::Result<HelpSurface, String> {
    let (command, help) = root_short_help()?;
    let mut surface = HelpSurface {
        command_nodes: 0,
        argument_placements: 0,
        rendered_bytes: u64::try_from(help.len())
            .map_err(|_| "root short-help length exceeds u64".to_string())?,
    };
    inspect_help_surface(&command, &mut surface)?;
    Ok(surface)
}

/// Render actual root short help with selection environment values redacted.
/// # Errors
/// Returns an error if parsing does not produce the expected help response.
pub fn short_help() -> std::result::Result<String, String> {
    root_short_help().map(|(_, help)| help)
}

fn cli_command() -> clap::Command {
    Cli::command()
        .color(clap::ColorChoice::Never)
        .term_width(100)
}

fn root_short_help() -> std::result::Result<(clap::Command, String), String> {
    let mut command = cli_command();
    let Err(error) = command.try_get_matches_from_mut(["smith", "--help"]) else {
        return Err("root short help unexpectedly parsed as a command".to_string());
    };
    if error.kind() != clap::error::ErrorKind::DisplayHelp {
        return Err(format!(
            "root short help returned {:?}, not DisplayHelp",
            error.kind()
        ));
    }
    Ok((command, error.to_string()))
}

fn inspect_help_surface(
    command: &clap::Command,
    surface: &mut HelpSurface,
) -> std::result::Result<(), String> {
    surface.command_nodes = surface
        .command_nodes
        .checked_add(1)
        .ok_or_else(|| "help command-node count overflows u64".to_string())?;
    let arguments = u64::try_from(command.get_arguments().count())
        .map_err(|_| "help argument-placement count exceeds u64".to_string())?;
    surface.argument_placements = surface
        .argument_placements
        .checked_add(arguments)
        .ok_or_else(|| "help argument-placement count overflows u64".to_string())?;
    for child in command.get_subcommands() {
        inspect_help_surface(child, surface)?;
    }
    Ok(())
}

/// Parse process arguments and run the selected Smith command.
#[expect(
    clippy::too_many_lines,
    reason = "command dispatch keeps CLI argument ownership explicit"
)]
pub fn run() -> std::process::ExitCode {
    let matches = cli_command().get_matches();
    let cli = match Cli::from_arg_matches(&matches) {
        Ok(cli) => cli,
        Err(error) => {
            error.exit();
        }
    };
    let inspection = matches!(&cli.command, Command::Sessions { action } if !matches!(action, SessionAction::Execute { .. }));
    let executing_admitted = matches!(
        &cli.command,
        Command::Sessions {
            action: SessionAction::Execute { .. }
        }
    );
    let result = match cli.command {
        Command::Login {
            project,
            provider,
            fixture_issuer,
            profile,
        } => login(
            project.as_deref(),
            provider,
            fixture_issuer.as_deref(),
            profile.as_deref(),
        )
        .map(|()| true),
        Command::Logout {
            provider,
            profile,
            fixture_issuer,
        } => oauth_logout(provider.provider(), &profile, fixture_issuer.as_deref()).map(|()| true),
        Command::Auth { action } => auth(&action).map(|()| true),
        Command::Catalog { action } => catalog(action).map(|()| true),
        Command::Plugin { action } => plugin(action).map(|()| true),
        Command::Sessions { action } => sessions(action),
        Command::Observe { id, export } => observe(id, export.as_ref()).map(|()| true),
        Command::Eval {
            profile,
            fixture_issuer,
            credential_module,
            prompt,
            json,
            session,
            selection:
                ExecutionProviderArgs {
                    r#mock,
                    connection:
                        ProviderArgs {
                            provider,
                            model,
                            base_url,
                            include_usage,
                            tool_policy,
                            tool_delegation,
                        },
                },
        } => selected_eval_provider(
            r#mock,
            provider,
            model.clone(),
            base_url,
            profile,
            fixture_issuer,
            credential_module,
        )
        .and_then(|runtime_provider| {
            report_selection(
                provider,
                model.as_deref(),
                &subcommand_sources(&matches, "eval"),
            )?;
            eval(
                &prompt,
                json,
                &runtime_config(
                    runtime_provider,
                    session,
                    include_usage,
                    &tool_policy,
                    &tool_delegation,
                )?,
            )
        })
        .map(|()| true),
        Command::Rpc {
            session,
            read_only,
            selection,
        } => rpc(session, read_only, selection).map(|()| true),
    };
    match result {
        Ok(true) => std::process::ExitCode::SUCCESS,
        Err(smith::error::SmithError::Cancelled) if !executing_admitted => {
            std::process::ExitCode::SUCCESS
        }
        Ok(false) => std::process::ExitCode::FAILURE,
        Err(error) => {
            drop(stderr_line(format_args!("smith: {error}")));
            std::process::ExitCode::from(if inspection { 2 } else { 1 })
        }
    }
}

fn login(
    project: Option<&str>,
    provider: ProviderArg,
    fixture_issuer: Option<&str>,
    profile: Option<&str>,
) -> Result<()> {
    if let Some(provider) = provider.subscription() {
        return login_subscription(project, provider, fixture_issuer, profile);
    }
    if project.is_some() || fixture_issuer.is_some() || profile.is_some() {
        return Err(plugin_command_fault(
            "--profile/--fixture-issuer/--project are subscription-only and require a subscription provider",
        ));
    }
    auth(&AuthAction::Add { provider })
}

fn login_subscription(
    project: Option<&str>,
    provider: SubscriptionProvider,
    fixture_issuer: Option<&str>,
    profile: Option<&str>,
) -> Result<()> {
    let mut cancellation = login_cancellation::LoginCancellation::install()?;
    let journal = oauth_journal()?;
    let profile = smith_harness::oauth::login::run(
        provider,
        &journal,
        fixture_issuer,
        profile,
        project,
        cancellation.take_receiver()?,
        || cancellation.finish(),
    )?;
    let display = match provider {
        SubscriptionProvider::OpenAi => "ChatGPT",
        SubscriptionProvider::Anthropic => "Claude",
        SubscriptionProvider::Google => "Google",
    };
    stdout_line(format_args!("{display} profile: {profile}"))
}

fn oauth_logout(
    provider: SubscriptionProvider,
    profile: &str,
    fixture_issuer: Option<&str>,
) -> Result<()> {
    let status = smith_harness::oauth::login::end_session(
        provider,
        &oauth_journal()?,
        fixture_issuer,
        profile,
    )?;
    stdout_line(format_args!("{status}"))
}

fn oauth_journal() -> Result<std::path::PathBuf> {
    session_dir().map(|directory| directory.join(format!("{}.smh", smith::id::SessionId::new())))
}

fn stdout_line(arguments: fmt::Arguments<'_>) -> Result<()> {
    let mut stdout = io::stdout().lock();
    stdout
        .write_fmt(format_args!("{arguments}\n"))
        .map_err(|error| session_stdout_error(&error))
}

fn stderr_line(arguments: fmt::Arguments<'_>) -> io::Result<()> {
    let mut stderr = io::stderr().lock();
    stderr.write_fmt(format_args!("{arguments}\n"))
}

fn cli_stderr_error(error: &io::Error) -> smith::error::SmithError {
    smith::error::SmithError::Provider {
        fault: smith::error::ProviderFault::Transient {
            message: format!("stderr write failed: {error}"),
        },
    }
}

fn catalog(action: CatalogAction) -> Result<()> {
    let (cache, refresh, listing) = match action {
        CatalogAction::Refresh { cache } => (cache.unwrap_or_else(catalog_cache_path), true, None),
        CatalogAction::Show {
            cache,
            provider,
            json,
        } => (
            cache.unwrap_or_else(catalog_cache_path),
            false,
            Some((provider, json)),
        ),
        CatalogAction::Status { cache } => (cache.unwrap_or_else(catalog_cache_path), false, None),
    };
    let mut state = startup_catalog(&cache)?;
    if refresh {
        let outcome = refresh_models_dev(
            &mut state,
            &cache,
            &default_executor(),
            &smith::tool::CancelHandle::new(),
        )?;
        if !matches!(outcome, RefreshOutcome::Published { .. }) {
            return Err(smith::error::SmithError::Provider {
                fault: smith::error::ProviderFault::Transient {
                    message: format!(
                        "catalog refresh failed: {outcome:?}; retained offline snapshot"
                    ),
                },
            });
        }
    }
    match listing {
        Some((provider, json)) => catalog_show(state.snapshot(), provider, json),
        None => catalog_status(state.snapshot()),
    }
}

fn catalog_status(snapshot: &smith_harness::CatalogSnapshot) -> Result<()> {
    stdout_line(format_args!(
        "catalog: {}; generation={}; models={}",
        snapshot.provenance.label(),
        snapshot.generation,
        snapshot.catalog.models.len()
    ))
}

fn catalog_show(
    snapshot: &smith_harness::CatalogSnapshot,
    provider: Option<ProviderArg>,
    json: bool,
) -> Result<()> {
    if provider.is_some_and(|provider| provider.subscription().is_some()) {
        return Err(plugin_command_fault(
            "subscription model entitlement requires an explicitly selected profile; no API billing fallback",
        ));
    }
    let connections = ProviderArg::ALL
        .into_iter()
        .filter(|connection| provider.is_none_or(|selected| selected == *connection));
    if json {
        let providers: Vec<_> = connections
            .map(|connection| catalog_json_connection(snapshot, connection))
            .collect();
        return stdout_line(format_args!(
            "{}",
            serde_json::json!({
                "provenance": snapshot.provenance.label(),
                "generation": snapshot.generation,
                "providers": providers,
            })
        ));
    }
    stdout_line(format_args!(
        "catalog: {}; generation={}",
        snapshot.provenance.label(),
        snapshot.generation
    ))?;
    for connection in connections {
        let mut models: Vec<_> = snapshot
            .catalog
            .models
            .values()
            .filter(|model| model.provider == connection.kind())
            .collect();
        models.sort_unstable_by(|left, right| left.id.cmp(&right.id));
        stdout_line(format_args!(
            "{} (connection={}, access=unknown):",
            connection.slug(),
            connection.connection_id()
        ))?;
        for model in models {
            stdout_line(format_args!(
                "  {} [{}]",
                catalog_human_value(&model.id),
                catalog_human_capabilities(&model.capabilities)
            ))?;
        }
    }
    Ok(())
}

fn catalog_json_connection(
    snapshot: &smith_harness::CatalogSnapshot,
    connection: ProviderArg,
) -> serde_json::Value {
    let mut models: Vec<_> = snapshot
        .catalog
        .models
        .values()
        .filter(|model| model.provider == connection.kind())
        .collect();
    models.sort_unstable_by(|left, right| left.id.cmp(&right.id));
    let models: Vec<_> = models
        .into_iter()
        .map(|model| {
            serde_json::json!({
                "id": model.id,
                "capabilities": catalog_json_capabilities(&model.capabilities),
            })
        })
        .collect();
    serde_json::json!({
        "provider": connection.slug(),
        "catalog_provider": connection.kind().slug(),
        "connection": connection.connection_id(),
        "execution_support": "supported",
        "account_access": "unknown",
        "models": models,
    })
}

fn catalog_json_capabilities(capabilities: &smith_harness::ModelCapabilities) -> serde_json::Value {
    let supported: Vec<_> = catalog_supported_capabilities(capabilities).collect();
    serde_json::json!({
        "context_window": capabilities.context_window,
        "max_output_tokens": capabilities.output_tokens_max,
        "supported": supported,
    })
}

fn catalog_human_value(value: &str) -> std::str::EscapeDefault<'_> {
    value.escape_default()
}

fn catalog_human_capabilities(capabilities: &smith_harness::ModelCapabilities) -> String {
    let mut values = vec![
        format!("context={}", capabilities.context_window),
        format!("output={}", capabilities.output_tokens_max),
    ];
    values.extend(catalog_supported_capabilities(capabilities).map(str::to_string));
    values.join(", ")
}

fn catalog_supported_capabilities(
    capabilities: &smith_harness::ModelCapabilities,
) -> impl Iterator<Item = &'static str> {
    [
        ("images", capabilities.input_images),
        ("tools", capabilities.tool_use),
        ("thinking", capabilities.thinking),
        ("strict-tools", capabilities.strict_tool_input),
        ("cache", capabilities.cache_control),
    ]
    .into_iter()
    .filter_map(|(name, supported)| supported.then_some(name))
}

#[expect(
    clippy::too_many_lines,
    reason = "one CLI command dispatcher keeps subcommand output and errors adjacent"
)]
fn plugin(action: PluginAction) -> Result<()> {
    match action {
        PluginAction::Init {
            package,
            name,
            language,
        } => {
            plugin_init(&package, &name, language)?;
            stdout_line(format_args!("{}: initialized", package.display()))?;
        }
        PluginAction::Build { package } => {
            plugin_build(&package)?;
            stdout_line(format_args!("{}: built", package.display()))?;
        }
        PluginAction::Test { package, grant } => {
            plugin_build(&package)?;
            smith_harness::plugins::test::run(&package, &grants_from_args(grant))?;
            stdout_line(format_args!("{}: test passed", package.display()))?;
        }
        PluginAction::Install {
            package,
            grant,
            net_origin,
            secret_source,
            secret_provider,
            secret_origin,
            secret_scope,
        } => {
            let engine = PluginEngine::new()?;
            let grants = grants_from_args(grant);
            let scopes = net_scopes_from_args(&net_origin)?;
            let secret_grants = secret_grants_from_args(
                secret_source,
                secret_provider,
                secret_origin,
                secret_scope,
            )?;
            if !scopes.is_empty() && !grants.contains(&Capability::NetScope) {
                return Err(plugin_command_fault(
                    "--net-origin requires --grant net-scope",
                ));
            }
            let record = PackageRegistry::at_default().install_with_authority(
                &engine,
                &package,
                &grants,
                &scopes,
                &secret_grants,
            )?;
            stdout_line(format_args!("{}: installed", record.id()))?;
        }
        PluginAction::Link {
            package,
            grant,
            net_origin,
            secret_source,
            secret_provider,
            secret_origin,
            secret_scope,
        } => {
            let engine = PluginEngine::new()?;
            let grants = grants_from_args(grant);
            let scopes = net_scopes_from_args(&net_origin)?;
            let secret_grants = secret_grants_from_args(
                secret_source,
                secret_provider,
                secret_origin,
                secret_scope,
            )?;
            if !scopes.is_empty() && !grants.contains(&Capability::NetScope) {
                return Err(plugin_command_fault(
                    "--net-origin requires --grant net-scope",
                ));
            }
            let record = PackageRegistry::at_default().link_with_authority(
                &engine,
                &package,
                &grants,
                &scopes,
                &secret_grants,
            )?;
            stdout_line(format_args!("{}: linked", record.id()))?;
        }
        PluginAction::List => {
            for record in PackageRegistry::at_default().list()? {
                stdout_line(format_args!(
                    "{} {} {} {} {}",
                    package_source_name(record.source()),
                    record.id(),
                    record.root().display(),
                    record.manifest_sha256(),
                    record.artifact_sha256()
                ))?;
            }
        }
        PluginAction::Remove { id } => {
            if !PackageRegistry::at_default().remove(&id)? {
                return Err(plugin_command_fault(format!(
                    "plugin {id} is not registered"
                )));
            }
            stdout_line(format_args!("{id}: removed"))?;
        }
        PluginAction::Reload { session } => {
            let engine = PluginEngine::new()?;
            let candidate =
                PackageRegistry::at_default().load(&engine, &AuthStore::at_default())?;
            let count = candidate.len();
            let mut registry = PluginRegistry::new();
            registry.publish_all(candidate)?;
            request_reload(session)?;
            stdout_line(format_args!("plugins: reloaded {count}"))?;
        }
        PluginAction::Dev {
            package,
            session,
            grant,
            watch_interval_ms,
        } => plugin_dev(
            &package,
            session.as_ref(),
            &grants_from_args(grant),
            std::time::Duration::from_millis(watch_interval_ms),
        )?,
        PluginAction::Trust {
            package,
            grant,
            net_origin,
            secret_source,
            secret_provider,
            secret_origin,
            secret_scope,
        } => {
            let grants = grants_from_args(grant);
            let scopes = net_scopes_from_args(&net_origin)?;
            let secret_grants = secret_grants_from_args(
                secret_source,
                secret_provider,
                secret_origin,
                secret_scope,
            )?;
            if !scopes.is_empty() && !grants.contains(&Capability::NetScope) {
                return Err(plugin_command_fault(
                    "--net-origin requires --grant net-scope",
                ));
            }
            if !secret_grants.is_empty()
                && (!grants.contains(&Capability::NetScope)
                    || !grants.contains(&Capability::SecretProxy))
            {
                return Err(plugin_command_fault(
                    "secret authority requires --grant net-scope and --grant secret-proxy",
                ));
            }
            TrustStore::at(smith::config::plugin_trust_dir()).grant_with_authority(
                &package,
                &grants,
                &scopes,
                &secret_grants,
            )?;
            stdout_line(format_args!("{}: trusted", package.display()))?;
            if grants.contains(&Capability::Process) {
                stdout_line(format_args!(
                    "process grant accepted: commands inherit host-user filesystem and network access"
                ))?;
            }
        }
        PluginAction::Check {
            package,
            trust,
            grant,
        } => {
            let grants = grants_from_args(grant);
            let (grants, scopes) = if trust {
                (grants, Vec::new())
            } else {
                let trust_store = TrustStore::at(smith::config::plugin_trust_dir());
                let grants = trust_store.decision(&package)?.ok_or_else(|| {
                    smith::error::SmithError::Provider {
                        fault: smith::error::ProviderFault::Plugin {
                            message: "project plugin is untrusted; trust the project with smith plugin trust <package> before loading its package".to_string(),
                        },
                    }
                })?;
                let scopes = trust_store
                    .net_scopes(&package)?
                    .ok_or_else(|| plugin_command_fault("project trust decision disappeared"))?;
                (grants, scopes)
            };
            plugin_check(&package, &grants, scopes)?;
        }
    }
    Ok(())
}

fn plugin_check(
    package_root: &Path,
    grants: &[Capability],
    net_scopes: Vec<smith_harness::plugins::NetScope>,
) -> Result<()> {
    let package = PluginPackage::discover(package_root, true)?;
    let engine = PluginEngine::new()?;
    let mut generation = PluginGeneration::load_package(&engine, package, grants)?;
    generation.configure_net_scopes(net_scopes);
    stdout_line(format_args!("{}: check passed", generation.manifest().id()))?;
    if grants.contains(&Capability::Process) {
        stdout_line(format_args!(
            "process grant active: commands inherit host-user filesystem and network access"
        ))?;
    }
    Ok(())
}

fn plugin_build(package: &Path) -> Result<()> {
    PluginLanguage::detect(package)?.build(package)
}

/// Guest language selected when scaffolding a package.
#[derive(Clone, Copy, Debug, ValueEnum)]
enum PluginLanguageArg {
    /// Raw Rust `wit-bindgen` guest.
    Rust,
    /// TypeScript guest componentized through the pinned Jco toolchain.
    #[value(name = "typescript")]
    TypeScript,
}

/// Language-specific plugin build contract.
enum PluginLanguage {
    Rust,
    TypeScript,
}

impl PluginLanguage {
    fn detect(package: &Path) -> Result<Self> {
        match (
            package.join("Cargo.toml").is_file(),
            package.join("package.json").is_file(),
        ) {
            (true, false) => Ok(Self::Rust),
            (false, true) => Ok(Self::TypeScript),
            (true, true) => Err(plugin_command_fault(
                "multiple language adapters recognize this package; keep only Cargo.toml or package.json",
            )),
            (false, false) => Err(plugin_command_fault(
                "no language adapter recognizes this package; add Cargo.toml or package.json",
            )),
        }
    }

    fn build(self, package: &Path) -> Result<()> {
        match self {
            Self::Rust => build_rust_plugin(package),
            Self::TypeScript => build_typescript_plugin(package),
        }
    }
}

fn build_rust_plugin(package: &Path) -> Result<()> {
    let cargo_manifest = package.join("Cargo.toml");
    run_plugin_adapter(
        ProcessCommand::new("cargo")
            .args(["build", "--manifest-path"])
            .arg(cargo_manifest)
            .args(["--target", "wasm32-wasip2", "--locked"]),
        "Rust adapter build",
    )
}

fn build_typescript_plugin(package: &Path) -> Result<()> {
    let target = package.join("target");
    std::fs::create_dir_all(&target).map_err(|error| {
        plugin_command_fault(format!(
            "TypeScript adapter target creation failed: {error}"
        ))
    })?;
    run_plugin_adapter(
        ProcessCommand::new(plugin_tool("tsc")?)
            .args(["--project"])
            .arg(package.join("tsconfig.json")),
        "TypeScript adapter type check",
    )?;
    let raw = target.join("plugin.raw.wasm");
    run_plugin_adapter(
        ProcessCommand::new(plugin_tool("jco")?)
            .args(["componentize"])
            .arg(target.join("plugin.js"))
            .args(["--wit"])
            .arg(package.join("wit"))
            .args(["--world-name", "plugin-world", "--out"])
            .arg(&raw)
            .args(["--disable", "all"]),
        "TypeScript adapter componentize",
    )?;
    normalize_typescript_component(&target, &raw)
}

fn plugin_tool(name: &str) -> Result<std::path::PathBuf> {
    let root = std::env::var_os("SMITH_PLUGIN_TOOL_DIR").map_or_else(
        || {
            std::env::var_os("CARGO_TARGET_DIR")
                .map_or_else(
                    || std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target"),
                    std::path::PathBuf::from,
                )
                .join("tools")
        },
        std::path::PathBuf::from,
    );
    let path = match name {
        "jco" => root.join("jco/node_modules/.bin/jco"),
        "tsc" => root.join("jco/node_modules/.bin/tsc"),
        "wasm-tools" => root.join("bin/wasm-tools"),
        _ => return Err(plugin_command_fault("unknown plugin build tool")),
    };
    if path.is_file() {
        Ok(path)
    } else {
        Err(plugin_command_fault(format!(
            "TypeScript adapter requires {}; run cargo x bootstrap from the Smith checkout",
            path.display()
        )))
    }
}

/// Maximum WAT source emitted by the Jco normalization step.
const TYPESCRIPT_WAT_BYTES_MAX: usize = 256 * 1024 * 1024;

fn normalize_typescript_component(target: &Path, raw: &Path) -> Result<()> {
    let wat = target.join("plugin.normalized.wat");
    let output = target.join("plugin.wasm");
    run_plugin_adapter(
        ProcessCommand::new(plugin_tool("wasm-tools")?)
            .args(["print"])
            .arg(raw)
            .args(["-o"])
            .arg(&wat),
        "TypeScript adapter component inspection",
    )?;
    let source = read_typescript_wat(&wat)?;
    let (normalized, memories) = normalize_component_memories(&source)?;
    if memories == 0 {
        return Err(plugin_command_fault(
            "TypeScript adapter component has no core memory to normalize",
        ));
    }
    std::fs::write(&wat, normalized).map_err(|error| {
        plugin_command_fault(format!(
            "TypeScript adapter component normalization write failed: {error}"
        ))
    })?;
    run_plugin_adapter(
        ProcessCommand::new(plugin_tool("wasm-tools")?)
            .args(["parse"])
            .arg(&wat)
            .args(["-o"])
            .arg(&output),
        "TypeScript adapter component normalization",
    )
}

fn read_typescript_wat(path: &Path) -> Result<String> {
    let metadata = std::fs::metadata(path).map_err(|error| {
        plugin_command_fault(format!(
            "TypeScript adapter component inspection failed: {error}"
        ))
    })?;
    if metadata.len() > TYPESCRIPT_WAT_BYTES_MAX as u64 {
        return Err(plugin_command_fault(format!(
            "TypeScript adapter component inspection exceeds {TYPESCRIPT_WAT_BYTES_MAX} bytes"
        )));
    }
    let capacity = usize::try_from(metadata.len()).map_err(|_| {
        plugin_command_fault("TypeScript adapter component inspection exceeds addressable memory")
    })?;
    let mut bytes = Vec::new();
    bytes.try_reserve_exact(capacity).map_err(|_| {
        plugin_command_fault("TypeScript adapter component inspection allocation failed")
    })?;
    let file = std::fs::File::open(path).map_err(|error| {
        plugin_command_fault(format!(
            "TypeScript adapter component inspection failed: {error}"
        ))
    })?;
    #[expect(
        clippy::disallowed_methods,
        reason = "Take bounds TypeScript component inspection before UTF-8 decoding"
    )]
    file.take((TYPESCRIPT_WAT_BYTES_MAX + 1) as u64)
        .read_to_end(&mut bytes)
        .map_err(|error| {
            plugin_command_fault(format!(
                "TypeScript adapter component inspection failed: {error}"
            ))
        })?;
    if bytes.len() > TYPESCRIPT_WAT_BYTES_MAX {
        return Err(plugin_command_fault(format!(
            "TypeScript adapter component inspection exceeds {TYPESCRIPT_WAT_BYTES_MAX} bytes"
        )));
    }
    String::from_utf8(bytes).map_err(|error| {
        plugin_command_fault(format!(
            "TypeScript adapter component inspection is not UTF-8: {error}"
        ))
    })
}

fn normalize_component_memories(source: &str) -> Result<(String, usize)> {
    let mut normalized = String::with_capacity(source.len());
    let mut memories = 0;
    for line in source.lines() {
        let trimmed = line.trim();
        let mut fields = trimmed.split_ascii_whitespace();
        let memory = fields.next();
        let identifier = fields.next();
        let limit = fields.next();
        let pages = match (memory, identifier, limit, fields.next()) {
            (Some("(memory"), Some(_), Some(limit), None) if limit.ends_with(')') => {
                Some(limit.trim_end_matches(')'))
            }
            _ => None,
        };
        if let Some(pages) = pages {
            pages.parse::<u64>().map_err(|error| {
                plugin_command_fault(format!(
                    "TypeScript adapter component memory declaration is invalid: {error}"
                ))
            })?;
            let prefix = &line[..line.len() - 1];
            normalized.push_str(prefix);
            normalized.push(' ');
            normalized.push_str(pages);
            normalized.push(')');
            memories += 1;
        } else {
            normalized.push_str(line);
        }
        normalized.push('\n');
    }
    Ok((normalized, memories))
}

fn run_plugin_adapter(command: &mut ProcessCommand, stage: &str) -> Result<()> {
    let output = command
        .output()
        .map_err(|error| plugin_command_fault(format!("{stage} failed to start: {error}")))?;
    if output.status.success() {
        Ok(())
    } else {
        Err(plugin_command_fault(format!(
            "{stage} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )))
    }
}

fn plugin_dev(
    package: &Path,
    session: Option<&smith::id::SessionId>,
    grants: &[Capability],
    watch_interval: std::time::Duration,
) -> Result<()> {
    let engine = PluginEngine::new()?;
    let registry = PackageRegistry::at_default();
    plugin_build(package)?;
    let record = registry.link(&engine, package, grants)?;
    if let Err(error) = request_reload(session.copied()) {
        stderr_line(format_args!(
            "{}: candidate saved but runtime notification failed: {error}",
            record.id()
        ))
        .map_err(|error| cli_stderr_error(&error))?;
    }
    stdout_line(format_args!("{}: watching", record.id()))?;
    let mut snapshot = PackageSourceSnapshot::read(package)?;
    loop {
        std::thread::sleep(watch_interval);
        let next = PackageSourceSnapshot::read(package)?;
        if next == snapshot {
            continue;
        }
        snapshot = next;
        if let Err(error) = plugin_build(package) {
            stderr_line(format_args!(
                "{}: rebuild failed; active generation retained: {error}",
                package.display()
            ))
            .map_err(|error| cli_stderr_error(&error))?;
            continue;
        }
        let record = match registry.link(&engine, package, grants) {
            Ok(record) => record,
            Err(error) => {
                stderr_line(format_args!(
                    "{}: candidate validation failed; active generation retained: {error}",
                    package.display()
                ))
                .map_err(|error| cli_stderr_error(&error))?;
                continue;
            }
        };
        if let Err(error) = request_reload(session.copied()) {
            stderr_line(format_args!(
                "{}: candidate saved but runtime notification failed: {error}",
                record.id()
            ))
            .map_err(|error| cli_stderr_error(&error))?;
            continue;
        }
        stdout_line(format_args!("{}: reloaded", record.id()))?;
        snapshot = PackageSourceSnapshot::read(package)?;
    }
}

#[derive(Eq, PartialEq)]
struct PackageSourceSnapshot(Vec<PackageSourceStamp>);

#[derive(Eq, Ord, PartialEq, PartialOrd)]
struct PackageSourceStamp {
    path: std::path::PathBuf,
    modified_ns: u128,
    bytes: u64,
}

impl PackageSourceSnapshot {
    fn read(package: &Path) -> Result<Self> {
        const WATCHED_ENTRIES_MAX: usize = 10_000;
        const WATCHED_DEPTH_MAX: usize = 64;
        let mut stamps = Vec::new();
        let mut entries_seen = 0;
        collect_source_stamps(
            package,
            package,
            &mut stamps,
            &mut entries_seen,
            WATCHED_ENTRIES_MAX,
            WATCHED_DEPTH_MAX,
        )?;
        stamps.sort();
        Ok(Self(stamps))
    }
}

fn collect_source_stamps(
    root: &Path,
    directory: &Path,
    stamps: &mut Vec<PackageSourceStamp>,
    entries_seen: &mut usize,
    entries_max: usize,
    depth_max: usize,
) -> Result<()> {
    for entry in std::fs::read_dir(directory).map_err(|error| {
        plugin_command_fault(format!("plugin source watch read failed: {error}"))
    })? {
        let entry = entry.map_err(|error| {
            plugin_command_fault(format!("plugin source watch entry failed: {error}"))
        })?;
        *entries_seen = entries_seen
            .checked_add(1)
            .ok_or_else(|| plugin_command_fault("plugin source watch entry count overflow"))?;
        if *entries_seen > entries_max {
            return Err(plugin_command_fault(format!(
                "plugin source watch exceeds {entries_max} entries"
            )));
        }
        let name = entry.file_name();
        if name == "target" || name == ".git" {
            continue;
        }
        let path = entry.path();
        let file_type = entry.file_type().map_err(|error| {
            plugin_command_fault(format!("plugin source watch type failed: {error}"))
        })?;
        if file_type.is_dir() {
            if depth_max == 0 {
                return Err(plugin_command_fault(
                    "plugin source watch exceeds directory depth limit",
                ));
            }
            collect_source_stamps(
                root,
                &path,
                stamps,
                entries_seen,
                entries_max,
                depth_max - 1,
            )?;
            continue;
        }
        if !file_type.is_file() {
            continue;
        }
        stamps
            .try_reserve(1)
            .map_err(|_| plugin_command_fault("plugin source watch allocation failed"))?;
        let metadata = entry.metadata().map_err(|error| {
            plugin_command_fault(format!("plugin source watch metadata failed: {error}"))
        })?;
        let modified_ns = metadata
            .modified()
            .map_err(|error| {
                plugin_command_fault(format!("plugin source watch timestamp failed: {error}"))
            })?
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let path = path
            .strip_prefix(root)
            .map_err(|error| {
                plugin_command_fault(format!("plugin source watch path failed: {error}"))
            })?
            .to_path_buf();
        stamps.push(PackageSourceStamp {
            path,
            modified_ns,
            bytes: metadata.len(),
        });
    }
    Ok(())
}

fn plugin_init(package: &Path, name: &str, language: PluginLanguageArg) -> Result<()> {
    let slug = plugin_slug(name)?;
    if package.exists() {
        return Err(plugin_command_fault(
            "refusing to initialize an existing path",
        ));
    }
    std::fs::create_dir_all(package.join("src"))
        .map_err(|error| plugin_command_fault(format!("package creation failed: {error}")))?;
    copy_directory(
        &std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../wit"),
        &package.join("wit"),
    )?;
    if matches!(language, PluginLanguageArg::TypeScript) {
        return plugin_init_typescript(package, name);
    }
    let crate_name = format!("smith-plugin-{slug}");
    let artifact = format!(
        "target/wasm32-wasip2/debug/smith_plugin_{}.wasm",
        slug.replace('-', "_")
    );
    std::fs::write(package.join("Cargo.toml"), format!("[package]\nname = \"{crate_name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\nbuild = \"build.rs\"\n\n[lib]\ncrate-type = [\"cdylib\"]\n\n[dependencies]\nwit-bindgen = \"=0.62.0\"\n"))
        .map_err(|error| plugin_command_fault(format!("Cargo manifest write failed: {error}")))?;
    std::fs::write(
        package.join("plugin.kdl"),
        format!("id \"{name}\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"{artifact}\"\n"),
    )
    .map_err(|error| plugin_command_fault(format!("plugin manifest write failed: {error}")))?;
    std::fs::write(package.join("build.rs"), "fn main() {\n    if std::env::var_os(\"CARGO_CFG_TARGET_ARCH\").as_deref() != Some(\"wasm32\".as_ref()) { return; }\n    println!(\"cargo::rustc-link-arg=--initial-memory=2097152\");\n    println!(\"cargo::rustc-link-arg=--max-memory=2097152\");\n}\n")
        .map_err(|error| plugin_command_fault(format!("build script write failed: {error}")))?;
    std::fs::write(
        package.join("plugin-test.json"),
        "{\n  \"invocations\": [{\n    \"name\": \"fixture\",\n    \"input_json\": \"{}\",\n    \"expected_output\": \"{}\",\n    \"effects\": []\n  }]\n}\n",
    )
    .map_err(|error| plugin_command_fault(format!("plugin fixture write failed: {error}")))?;
    std::fs::write(package.join("src/lib.rs"), "#![expect(missing_docs, reason = \"wit-bindgen generates the world surface\")]\n#![expect(clippy::pedantic, reason = \"wit-bindgen generates the world surface\")]\n\nwit_bindgen::generate!({ path: \"wit/smith-plugin.wit\", world: \"plugin-world\" });\n\nuse exports::smith::plugin::plugin::{Guest, ToolDeclaration};\nuse exports::smith::plugin::provider::{CatalogSnapshot, DecodeStep, Guest as ProviderGuest, ProviderRequest, ProviderSettings, RequestTemplate, SettingsProvenance};\nuse exports::smith::plugin::registration::{Guest as RegistrationGuest, Registrations};\n\nstruct Plugin;\n\nimpl RegistrationGuest for Plugin {\n    fn declare() -> Registrations { Registrations { credential_sources: Vec::new(), providers: Vec::new(), models: Vec::new() } }\n}\n\nimpl ProviderGuest for Plugin {\n    fn declare_settings() -> ProviderSettings { ProviderSettings { include_usage: false, subscription: false, provenance: SettingsProvenance::BuiltIn } }\n    fn validate_settings(_settings: ProviderSettings) -> Result<ProviderSettings, String> { Err(\"no provider codec\".to_string()) }\n    fn build_request(_model: String, _request: ProviderRequest, _settings: ProviderSettings, _catalog: CatalogSnapshot) -> Result<RequestTemplate, String> { Err(\"no provider codec\".to_string()) }\n    fn decode_response(_state: Vec<u8>, _chunk: Vec<u8>, _finished: bool) -> Result<DecodeStep, String> { Err(\"no provider codec\".to_string()) }\n}\n\nimpl Guest for Plugin {\n    fn declare_tools() -> Vec<ToolDeclaration> { vec![ToolDeclaration { name: \"fixture\".to_string(), description: \"Fixture echo tool.\".to_string(), input_schema_json: r#\"{\"type\":\"object\"}\"#.to_string() }] }\n    fn invoke(name: String, input_json: String) -> Result<String, String> { if name == \"fixture\" { Ok(input_json) } else { Err(format!(\"unknown tool: {name}\")) } }\n}\n\nexport!(Plugin);\n")
        .map_err(|error| plugin_command_fault(format!("guest source write failed: {error}")))?;
    let output = ProcessCommand::new("cargo")
        .args(["generate-lockfile", "--manifest-path"])
        .arg(package.join("Cargo.toml"))
        .output()
        .map_err(|error| plugin_command_fault(format!("cargo adapter failed to start: {error}")))?;
    if !output.status.success() {
        return Err(plugin_command_fault(format!(
            "cargo adapter lockfile failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    Ok(())
}

fn plugin_init_typescript(package: &Path, name: &str) -> Result<()> {
    std::fs::write(
        package.join("package.json"),
        "{\n  \"name\": \"smith-plugin\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n",
    )
    .map_err(|error| {
        plugin_command_fault(format!("TypeScript package manifest write failed: {error}"))
    })?;
    std::fs::write(
        package.join("tsconfig.json"),
        "{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"target\",\n    \"strict\": true\n  },\n  \"include\": [\"src/**/*.ts\"]\n}\n",
    )
    .map_err(|error| plugin_command_fault(format!("TypeScript config write failed: {error}")))?;
    std::fs::write(
        package.join("plugin.kdl"),
        format!(
            "id \"{name}\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"target/plugin.wasm\"\n"
        ),
    )
    .map_err(|error| plugin_command_fault(format!("plugin manifest write failed: {error}")))?;
    std::fs::write(
        package.join("plugin-test.json"),
        "{\n  \"invocations\": [{\n    \"name\": \"fixture\",\n    \"input_json\": \"{}\",\n    \"expected_output\": \"{}\",\n    \"effects\": []\n  }]\n}\n",
    )
    .map_err(|error| plugin_command_fault(format!("plugin fixture write failed: {error}")))?;
    std::fs::write(
        package.join("src/plugin.ts"),
        "export const plugin = {\n  declareTools() { return [{ name: \"fixture\", description: \"Fixture echo tool.\", inputSchemaJson: '{\\\"type\\\":\\\"object\\\"}' }]; },\n  invoke(name: string, inputJson: string) { if (name !== \"fixture\") throw new Error(`unknown tool: ${name}`); return inputJson; },\n};\nexport const provider = {\n  declareSettings() { return { includeUsage: false, subscription: false, provenance: { tag: \"built-in\" } }; },\n  validateSettings() { throw new Error(\"no provider codec\"); },\n  buildRequest() { throw new Error(\"no provider codec\"); },\n  decodeResponse() { throw new Error(\"no provider codec\"); },\n};\nexport const registration = { declare() { return { credentialSources: [], providers: [], models: [] }; } };\n",
    )
    .map_err(|error| plugin_command_fault(format!("TypeScript guest source write failed: {error}")))?;
    Ok(())
}

fn plugin_slug(name: &str) -> Result<String> {
    let slug: String = name
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() {
                character.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect();
    let slug = slug.trim_matches('-');
    if slug.is_empty() {
        return Err(plugin_command_fault(
            "plugin name needs an ASCII letter or digit",
        ));
    }
    Ok(slug.to_string())
}

fn copy_directory(source: &Path, destination: &Path) -> Result<()> {
    std::fs::create_dir_all(destination)
        .map_err(|error| plugin_command_fault(format!("WIT directory creation failed: {error}")))?;
    for entry in std::fs::read_dir(source)
        .map_err(|error| plugin_command_fault(format!("WIT directory read failed: {error}")))?
    {
        let entry = entry.map_err(|error| {
            plugin_command_fault(format!("WIT directory entry failed: {error}"))
        })?;
        let target = destination.join(entry.file_name());
        if entry
            .file_type()
            .map_err(|error| plugin_command_fault(format!("WIT entry metadata failed: {error}")))?
            .is_dir()
        {
            copy_directory(&entry.path(), &target)?;
        } else {
            std::fs::copy(entry.path(), target)
                .map_err(|error| plugin_command_fault(format!("WIT copy failed: {error}")))?;
        }
    }
    Ok(())
}

fn plugin_command_fault(message: impl Into<String>) -> smith::error::SmithError {
    smith::error::SmithError::Provider {
        fault: smith::error::ProviderFault::Plugin {
            message: message.into(),
        },
    }
}

fn auth(action: &AuthAction) -> Result<()> {
    if let AuthAction::Add { provider }
    | AuthAction::Remove { provider }
    | AuthAction::Check { provider } = action
    {
        provider.credential_key()?;
    }
    let store = AuthStore::at_default();
    match action {
        AuthAction::Profiles {
            provider,
            fixture_issuer,
        } => {
            let profiles = smith_harness::oauth::login::profile_store_for(
                provider.provider(),
                fixture_issuer.as_deref(),
            )?
            .list()
            .map_err(plugin_command_fault)?;
            let listing = serde_json::to_string(&profiles)
                .map_err(|_| plugin_command_fault("OAuth metadata encoding failed"))?;
            stdout_line(format_args!("{listing}"))?;
        }
        AuthAction::Add { provider } => {
            let mut stdin = std::io::stdin().lock();
            let line = read_stdin_line(&mut stdin, AUTH_SECRET_BYTES_MAX)
                .map_err(|error| auth_stdin_error(&error))?;
            drop(stdin);
            let secret = match line {
                StdinLine::Line(line) => line,
                StdinLine::Eof => String::new(),
            };
            if secret.is_empty() {
                return Err(smith::error::SmithError::Provider {
                    fault: smith::error::ProviderFault::Authentication {
                        message: "refusing to store an empty credential".to_string(),
                    },
                });
            }
            let key = provider.credential_key()?;
            store.save(key, &secret)?;
            stdout_line(format_args!("{}: stored", key.slug()))?;
        }
        AuthAction::List => {
            let stored = store.list()?;
            for key in CredentialKey::ALL {
                if stored.contains(&key) {
                    stdout_line(format_args!(
                        "{}: store (not verified; offline)",
                        key.slug()
                    ))?;
                }
                if let Some(var) = credential_key_env_var_present(key) {
                    stdout_line(format_args!(
                        "{}: env:{var} (not verified; offline)",
                        key.slug()
                    ))?;
                }
            }
        }
        AuthAction::Remove { provider } => {
            let key = provider.credential_key()?;
            if store.remove(key)? {
                stdout_line(format_args!("{}: removed", key.slug()))?;
            } else {
                return Err(smith::error::SmithError::Provider {
                    fault: smith::error::ProviderFault::Authentication {
                        message: format!("no stored credential for {}", key.slug()),
                    },
                });
            }
        }
        AuthAction::Check { provider } => {
            let key = provider.credential_key()?;
            if store.load(key)?.is_some() {
                stdout_line(format_args!("{}: store", key.slug()))?;
            } else if let Some(var) = credential_key_env_var_present(key) {
                stdout_line(format_args!("{}: env:{var}", key.slug()))?;
            } else {
                return Err(smith::error::SmithError::Provider {
                    fault: smith::error::ProviderFault::Authentication {
                        message: format!(
                            "no credential for {} (tried store, env {})",
                            key.slug(),
                            credential_key_env_vars(key).join(", ")
                        ),
                    },
                });
            }
        }
    }
    Ok(())
}

/// Which surface supplied each selection option, for provenance reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OptionSource {
    /// An explicit command-line flag.
    Cli,
    /// A `SMITH_` environment variable.
    Env,
    /// Nothing supplied a value.
    Unset,
}

fn source_of(matches: &clap::ArgMatches, field: &str) -> OptionSource {
    match matches.value_source(field) {
        Some(clap::parser::ValueSource::CommandLine) => OptionSource::Cli,
        Some(clap::parser::ValueSource::EnvVariable) => OptionSource::Env,
        _ => OptionSource::Unset,
    }
}

fn subcommand_sources(matches: &clap::ArgMatches, name: &str) -> SelectionSources {
    let sub = matches.subcommand_matches(name);
    SelectionSources {
        provider: sub.map_or(OptionSource::Unset, |m| source_of(m, "provider")),
        model: sub.map_or(OptionSource::Unset, |m| source_of(m, "model")),
        base_url: sub.map_or(OptionSource::Unset, |m| source_of(m, "base_url")),
    }
}

/// Provenance of each selection option.
struct SelectionSources {
    provider: OptionSource,
    model: OptionSource,
    base_url: OptionSource,
}

impl SelectionSources {
    fn describe(&self, provider: ProviderArg, model: &str) -> String {
        let provider = provider.slug();
        format!(
            "provider={provider}({}) model={model}({}) base-url({})",
            self.provider.tag(),
            self.model.tag(),
            self.base_url.tag()
        )
    }
}

impl OptionSource {
    const fn tag(self) -> &'static str {
        match self {
            Self::Cli => "cli",
            Self::Env => "env",
            Self::Unset => "unset",
        }
    }
}

impl ProviderArg {
    const fn slug(self) -> &'static str {
        match self {
            Self::Openai => "openai",
            Self::OpenaiChatgptPlan => "openai-chatgpt-plan",
            Self::AnthropicClaudePlan => "anthropic-claude-plan",
            Self::GoogleGeminiCliPlan => "google-gemini-cli-plan",
            Self::Anthropic => "anthropic",
            Self::Google => "google",
            Self::Zai => "zai",
            Self::ZaiCodingPlan => "zai-coding-plan",
        }
    }
}

fn real_provider(
    provider: Option<ProviderArg>,
    model: Option<String>,
    base_url: Option<String>,
) -> Result<RuntimeProvider> {
    let Some(provider) = provider else {
        return Err(smith::error::SmithError::Provider {
            fault: smith::error::ProviderFault::Authentication {
                message: "no provider selected (tried --provider/SMITH_PROVIDER)".to_string(),
            },
        });
    };
    let Some(model) = model else {
        return Err(smith::error::SmithError::Provider {
            fault: smith::error::ProviderFault::Authentication {
                message: format!(
                    "no model selected for {} (tried --model/SMITH_MODEL)",
                    provider.slug()
                ),
            },
        });
    };
    if provider.subscription().is_some() {
        return Err(plugin_command_fault(
            "subscription requires eval --profile ID; no API-key fallback",
        ));
    }
    if let Some(connection) = provider.zai_connection() {
        return Ok(RuntimeProvider::Zai {
            artifact: std::env::var_os("SMITH_ZAI_PLUGIN").map(std::path::PathBuf::from),
            base_url: base_url.unwrap_or_else(|| "https://api.z.ai".to_string()),
            connection,
            model,
        });
    }
    Ok(RuntimeProvider::real(provider.kind(), base_url, model))
}

fn selected_eval_provider(
    mock: bool,
    provider: Option<ProviderArg>,
    model: Option<String>,
    base_url: Option<String>,
    profile: Option<String>,
    fixture_issuer: Option<String>,
    credential_module: Option<String>,
) -> Result<RuntimeProvider> {
    if let Some(subscription) = provider.and_then(ProviderArg::subscription) {
        if mock || base_url.is_some() {
            return Err(plugin_command_fault(
                "subscription cannot use --mock or --base-url; fixtures require --fixture-issuer",
            ));
        }
        let profile = profile.ok_or_else(|| {
            plugin_command_fault(
                "subscription requires --profile ID; no implicit account or API-key fallback",
            )
        })?;
        let model = model.ok_or_else(|| {
            plugin_command_fault("subscription requires --model; no unverified default model")
        })?;
        let credential = smith_harness::oauth::source::SubscriptionCredential::for_provider(
            subscription,
            profile,
            fixture_issuer,
        )?;
        let credential = match credential_module {
            Some(module) => credential.with_module_override(module)?,
            None => credential,
        };
        return Ok(match subscription {
            SubscriptionProvider::Anthropic => {
                RuntimeProvider::AnthropicClaudePlan { credential, model }
            }
            SubscriptionProvider::Google => {
                RuntimeProvider::GoogleGeminiCliPlan { credential, model }
            }
            SubscriptionProvider::OpenAi => {
                RuntimeProvider::OpenAiChatGptPlan { credential, model }
            }
        });
    }
    if profile.is_some() || fixture_issuer.is_some() || credential_module.is_some() {
        return Err(plugin_command_fault(
            "--profile/--fixture-issuer/--credential-module require a subscription provider",
        ));
    }
    selected_provider(mock, provider, model, base_url)
}

fn selected_provider(
    mock: bool,
    provider: Option<ProviderArg>,
    model: Option<String>,
    base_url: Option<String>,
) -> Result<RuntimeProvider> {
    if mock {
        return Ok(RuntimeProvider::Mock(vec![smith_harness::mock_text_reply(
            "mock provider: no model configured",
        )]));
    }
    real_provider(provider, model, base_url)
}

fn report_selection(
    provider: Option<ProviderArg>,
    model: Option<&str>,
    sources: &SelectionSources,
) -> Result<()> {
    if let Some(provider) = provider
        && let Some(model) = model
    {
        stderr_line(format_args!("smith: {}", sources.describe(provider, model)))
            .map_err(|error| cli_stderr_error(&error))?;
    }
    Ok(())
}

fn eval(prompt: &str, json: bool, config: &RuntimeConfig) -> Result<()> {
    let outcome = {
        let _turn = smith_alloc::enter(smith_alloc::Scope::Turn);
        smith_harness::runtime::execute_prompt(config, prompt)
    }?;
    if json {
        stdout_line(format_args!(
            "{}",
            serde_json::json!({
                "text": outcome.text,
                "reason": format!("{:?}", outcome.reason),
                "cost": outcome.cost.map(|cost| serde_json::json!({
                    "input_tokens": cost.input_tokens,
                    "output_tokens": cost.output_tokens,
                })),
                "cost_complete": outcome.cost_complete,
            })
        ))?;
    } else {
        stdout_line(format_args!("{}", outcome.text))?;
    }
    Ok(())
}

/// Largest credential accepted from standard input, matching the auth store.
const AUTH_SECRET_BYTES_MAX: usize = 64 * 1024;

/// Largest JSON-RPC request line, matching Smith's default frame policy.
const RPC_INPUT_LINE_BYTES_MAX: usize = 1024 * 1024;

/// Lines queued from stdin while the RPC loop drains responses.
const RPC_INPUT_QUEUE_LINES: usize = 64;

#[derive(Debug)]
enum StdinLine {
    Line(String),
    Eof,
}

/// Read one UTF-8 line without allocating beyond `bytes_max`.
fn read_stdin_line(reader: &mut impl BufRead, bytes_max: usize) -> std::io::Result<StdinLine> {
    let mut bytes = Vec::new();
    loop {
        let buffer = reader.fill_buf()?;
        if buffer.is_empty() {
            return if bytes.is_empty() {
                Ok(StdinLine::Eof)
            } else {
                String::from_utf8(bytes)
                    .map(StdinLine::Line)
                    .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
            };
        }
        let line_end = buffer.iter().position(|byte| *byte == b'\n');
        let text = &buffer[..line_end.unwrap_or(buffer.len())];
        if bytes.len().saturating_add(text.len()) > bytes_max {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("standard input line exceeds {bytes_max} bytes"),
            ));
        }
        let consumed_bytes = text.len() + usize::from(line_end.is_some());
        bytes.extend_from_slice(text);
        reader.consume(consumed_bytes);
        if line_end.is_some() {
            if bytes.last() == Some(&b'\r') {
                bytes.pop();
            }
            return String::from_utf8(bytes)
                .map(StdinLine::Line)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error));
        }
    }
}

fn auth_stdin_error(error: &std::io::Error) -> smith::error::SmithError {
    let message = if error.kind() == std::io::ErrorKind::InvalidData
        && error.to_string() == format!("standard input line exceeds {AUTH_SECRET_BYTES_MAX} bytes")
    {
        format!(
            "credential input exceeds {AUTH_SECRET_BYTES_MAX} bytes; provide one credential no larger than the auth-store limit"
        )
    } else {
        error.to_string()
    };
    smith::error::SmithError::Session {
        code: smith::error::SessionCode::AuthRead,
        message,
    }
}

fn rpc_stdin_error(error: &std::io::Error) -> smith::error::SmithError {
    let message = if error.kind() == std::io::ErrorKind::InvalidData
        && error.to_string()
            == format!("standard input line exceeds {RPC_INPUT_LINE_BYTES_MAX} bytes")
    {
        format!(
            "JSON-RPC request exceeds {RPC_INPUT_LINE_BYTES_MAX} bytes; split the request into smaller requests"
        )
    } else {
        error.to_string()
    };
    smith::error::SmithError::Session {
        code: smith::error::SessionCode::RpcStdin,
        message,
    }
}

#[expect(
    clippy::large_types_passed_by_value,
    reason = "Copy session ID enters runtime configuration without cloning"
)]
fn rpc(
    session: Option<smith::id::SessionId>,
    read_only: bool,
    selection: ProviderArgs,
) -> Result<()> {
    let ProviderArgs {
        provider,
        model,
        base_url,
        include_usage,
        tool_policy,
        tool_delegation,
    } = selection;
    let mut state = if read_only {
        let id = session.ok_or_else(|| smith::error::SmithError::Config {
            field: "session".into(),
            message: "--read-only requires --session".into(),
        })?;
        let path = session_path(
            &std::path::PathBuf::from(smith::config::Config::default_valid().session_dir)
                .join("run"),
            id,
            true,
        )?;
        RpcState::inspection(Arc::new(ReadOnlyControl::open(&path)?))
    } else {
        let runtime_provider = match provider {
            Some(provider) => real_provider(Some(provider), model, base_url)?,
            None => RuntimeProvider::Mock(vec![smith_harness::mock_text_reply(
                "rpc mock provider ready",
            )]),
        };
        let config = runtime_config(
            runtime_provider,
            session,
            include_usage,
            &tool_policy,
            &tool_delegation,
        )?;
        let (control, executor) = writer_backend(config)?;
        RpcState::new(Arc::new(control), executor)
    };
    let (input_tx, input_rx) = std::sync::mpsc::sync_channel(RPC_INPUT_QUEUE_LINES);
    std::thread::spawn(move || {
        {
            let mut stdin = std::io::stdin().lock();
            loop {
                let line = match read_stdin_line(&mut stdin, RPC_INPUT_LINE_BYTES_MAX) {
                    Ok(StdinLine::Line(line)) => Ok(line),
                    Ok(StdinLine::Eof) => break,
                    Err(error) => Err(error),
                };
                let errored = line.is_err();
                if input_tx.send(Some(line)).is_err() || errored {
                    return;
                }
            }
            drop(stdin);
        }
        // The consumer may close after stdin reaches EOF.
        let _end_send_result = input_tx.send(None);
    });

    let mut stdout = std::io::stdout();
    let mut input_closed = false;
    loop {
        match input_rx.recv_timeout(std::time::Duration::from_millis(10)) {
            Ok(Some(Ok(line))) => {
                for response in handle_line(&mut state, &line) {
                    stdout
                        .write_all(response.as_bytes())
                        .map_err(rpc_stdout_error)?;
                }
            }
            Ok(Some(Err(error))) => return Err(rpc_stdin_error(&error)),
            Ok(None) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                input_closed = true;
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
        }
        for response in state.drain_lines() {
            stdout
                .write_all(response.as_bytes())
                .map_err(rpc_stdout_error)?;
        }
        stdout.flush().map_err(rpc_stdout_error)?;
        if input_closed && state.is_settled() {
            for response in state.drain_lines() {
                stdout
                    .write_all(response.as_bytes())
                    .map_err(rpc_stdout_error)?;
            }
            return Ok(());
        }
    }
}

fn rpc_stdout_error(error: std::io::Error) -> smith::error::SmithError {
    let message = error.to_string();
    drop(error);
    smith::error::SmithError::Session {
        code: smith::error::SessionCode::RpcStdout,
        message,
    }
}

fn observe(id: smith::id::SessionId, export: Option<&std::path::PathBuf>) -> Result<()> {
    let dir = session_dir()?;
    let path = session_path(&dir, id, true)?;
    smith_harness::observer::run(id, path, export)
}

fn sessions(action: SessionAction) -> Result<bool> {
    use smith_harness::inspection;
    let dir =
        std::path::PathBuf::from(smith::config::Config::default_valid().session_dir).join("run");
    let mut stdout = std::io::stdout().lock();
    match action {
        SessionAction::List { json } => {
            // Proquint text needs no JSON escaping, so both forms stream
            // through Display without an intermediate string.
            inspection::list(&dir, |summary| {
                let (id, bytes) = (summary.id, summary.bytes);
                if json {
                    writeln!(stdout, "{{\"session\":\"{id}\",\"bytes\":{bytes}}}")
                } else {
                    writeln!(stdout, "{id} {bytes} bytes")
                }
                .map_err(|e| session_stdout_error(&e))
            })?;
            Ok(true)
        }
        SessionAction::Get { id, json } => {
            let path = dir.join(format!("{id}.smh"));
            inspection::entries(&path, |entry, content| {
                inspection::output(&mut stdout, id, entry, content, json, true)
                    .map_err(|e| session_stdout_error(&e))
            })?;
            Ok(true)
        }
        SessionAction::Grep { pattern, json } => {
            let mut found = false;
            inspection::list(&dir, |summary| {
                let id = summary.id;
                let path = dir.join(format!("{id}.smh"));
                inspection::entries(&path, |entry, content| {
                    if inspection::contains(content, &pattern) {
                        found = true;
                        inspection::output(&mut stdout, id, entry, content, json, false)
                            .map_err(|e| session_stdout_error(&e))?;
                    }
                    Ok(())
                })
            })?;
            Ok(found)
        }
        SessionAction::Submit { id, input, key } => {
            let path = session_path(&dir, id, true)?;
            let receipt = smith_harness::storage::admit(
                &path,
                &smith::message::Message::with_text(smith::message::Role::User, input),
                key.as_deref(),
            )?;
            output_admission_receipt(&mut stdout, &receipt, true)?;
            Ok(true)
        }
        SessionAction::Execute {
            id,
            submission_id,
            selection,
        } => {
            let provider = selected_provider(
                selection.r#mock,
                selection.connection.provider,
                selection.connection.model,
                selection.connection.base_url,
            )?;
            let config = runtime_config(
                provider,
                Some(id),
                selection.connection.include_usage,
                &selection.connection.tool_policy,
                &selection.connection.tool_delegation,
            )?;
            smith_harness::runtime::execute_admitted(&config, submission_id)?;
            let receipt = inspection::receipt(&config.session_path, submission_id)?
                .ok_or_else(|| plugin_command_fault("settled submission receipt missing"))?;
            output_admission_receipt(&mut stdout, &receipt, false)?;
            Ok(true)
        }
        SessionAction::Receipt { id, submission_id } => {
            let path = session_path(&dir, id, true)?;
            let receipt = inspection::receipt(&path, submission_id)?.ok_or_else(|| {
                smith::error::SmithError::Session {
                    code: smith::error::SessionCode::SessionNotFound,
                    message: format!("submission {submission_id} does not exist in session {id}"),
                }
            })?;
            output_admission_receipt(&mut stdout, &receipt, false)?;
            Ok(true)
        }
    }
}

fn output_admission_receipt(
    stdout: &mut impl Write,
    receipt: &smith_harness::storage::AdmissionReceipt,
    acknowledged: bool,
) -> Result<()> {
    let destination = receipt
        .destination
        .map_or_else(|| "null".to_owned(), |id| format!("\"{id}\""));
    let boundary = if acknowledged {
        "\"durability\":\"acknowledged\""
    } else {
        "\"visibility\":\"visible\""
    };
    let dir = session_dir()?;
    let status = smith_harness::inspection::work_status(
        &dir.join(format!("{}.smh", receipt.session_id)),
        receipt.submission_id,
    )?;
    let (state, detail) = match status {
        Some(smith_harness::storage::WorkStatus::Queued) => ("queued", ""),
        Some(smith_harness::storage::WorkStatus::Running) => {
            ("running", ",\"recovery_required\":true")
        }
        Some(smith_harness::storage::WorkStatus::Terminal(reason)) => (
            "terminal",
            match reason {
                None => ",\"outcome\":\"failed\"",
                Some(smith::stream::StopReason::Abort) => ",\"outcome\":\"cancelled\"",
                Some(_) => ",\"outcome\":\"completed\"",
            },
        ),
        None => return Err(plugin_command_fault("submission receipt missing")),
    };
    let terminal = if let Some(smith_harness::storage::WorkStatus::Terminal(reason)) = status {
        let output = smith_harness::inspection::work_output(
            &dir.join(format!("{}.smh", receipt.session_id)),
            receipt.submission_id,
        )?;
        let output = output.map_or_else(|| "null".to_owned(), |id| format!("\"{id}\""));
        let reason = reason.map_or_else(|| "null".to_owned(), |reason| format!("\"{reason:?}\""));
        format!(",\"output\":{output},\"stop_reason\":{reason}")
    } else {
        String::new()
    };
    writeln!(
        stdout,
        "{{\"session\":\"{}\",\"submission\":\"{}\",\"destination\":{destination},\"state\":\"{state}\"{detail}{terminal},{boundary}}}",
        receipt.session_id,
        receipt.submission_id,
    )
    .map_err(|error| session_stdout_error(&error))
}

fn session_stdout_error(error: &std::io::Error) -> smith::error::SmithError {
    if error.kind() == std::io::ErrorKind::BrokenPipe {
        smith::error::SmithError::Cancelled
    } else {
        smith::error::SmithError::Session {
            code: smith::error::SessionCode::SessionStdout,
            message: error.to_string(),
        }
    }
}

fn catalog_cache_path() -> std::path::PathBuf {
    std::env::var_os("SMITH_CATALOG_CACHE")
        .map_or_else(smith::config::catalog_cache_path, std::path::PathBuf::from)
}

#[expect(
    clippy::large_types_passed_by_value,
    reason = "Copy session ID is consumed once to form the runtime path"
)]
fn runtime_config(
    provider: RuntimeProvider,
    session: Option<smith::id::SessionId>,
    include_usage: Option<bool>,
    tool_policy: &[String],
    tool_delegation: &[String],
) -> Result<RuntimeConfig> {
    let selected_session = session.unwrap_or_default();
    let catalog_snapshot = if provider.requires_catalog_validation() {
        let catalog = startup_catalog(&catalog_cache_path())?;
        validate_catalog_model(&catalog.snapshot().catalog, &provider)?;
        Some(catalog.snapshot().clone())
    } else {
        None
    };
    let dir = session_dir()?;
    let workdir = std::env::current_dir().map_err(|error| smith::error::SmithError::Config {
        field: "workdir".into(),
        message: format!(
            "cannot resolve invocation directory: {error}; start Smith from an accessible directory"
        ),
    })?;
    let (provider_settings, ignored_project) = smith_harness::connection_settings::resolve(
        &smith::config::plugin_registry_dir().with_file_name("provider-settings.kdl"),
        &workdir,
        &TrustStore::at(smith::config::plugin_trust_dir()),
        include_usage,
    )?;
    if ignored_project && !matches!(provider, RuntimeProvider::Mock(_)) {
        stderr_line(format_args!("untrusted project provider settings ignored; use smith plugin trust <project> to admit project configuration")).map_err(|error| cli_stderr_error(&error))?;
    }
    Ok(RuntimeConfig {
        session_path: session_path(&dir, selected_session, session.is_some())?,
        provider,
        workdir,
        provider_settings,
        api_key: None,
        auth_dir: smith::config::auth_dir(),
        catalog_snapshot,
        coding_tools_enabled: true,
        plugin_control_path: Some(smith::config::plugin_control_socket_path(selected_session)),
        plugin_registry_dir: None,
        tool_policy: smith_harness::wasm::ToolPolicy::from_specs(tool_policy)?,
        composition_grants: smith_harness::wasm::CompositionGrants::from_specs(tool_delegation)?,
    })
}

fn session_path(
    dir: &std::path::Path,
    session: smith::id::SessionId,
    selected: bool,
) -> Result<std::path::PathBuf> {
    let path = dir.join(format!("{session}.smh"));
    if selected && !path.is_file() {
        return Err(smith::error::SmithError::Session {
            code: smith::error::SessionCode::SessionNotFound,
            message: format!("session does not exist: {}", path.display()),
        });
    }
    Ok(path)
}

fn session_dir() -> Result<std::path::PathBuf> {
    let config = smith::config::Config::default_valid();
    create_session_dir(std::path::PathBuf::from(config.session_dir).join("run"))
}

fn create_session_dir(dir: std::path::PathBuf) -> Result<std::path::PathBuf> {
    std::fs::create_dir_all(&dir).map_err(|error| smith::error::SmithError::Storage {
        code: smith::error::StorageCode::RuntimeDir,
        operation: smith::error::StorageOperation::CreateDirAll,
        path: dir.clone(),
        message: error.to_string(),
        publication: None,
    })?;
    Ok(dir)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn short_help_surface_uses_the_production_command_factory() {
        let surface = short_help_surface().expect("root short help is a Clap display-help error");
        let mut command = cli_command();
        let error = command
            .try_get_matches_from_mut(["smith", "--help"])
            .expect_err("root help exits through Clap DisplayHelp");
        assert_eq!(error.kind(), clap::error::ErrorKind::DisplayHelp);
        assert_eq!(surface.rendered_bytes, error.to_string().len() as u64);
        assert!(surface.command_nodes > 1);
        assert!(surface.argument_placements >= surface.command_nodes);
    }

    #[test]
    fn typescript_component_normalization_makes_memory_limits_fixed() {
        let source = "(component\n  (core module $main\n    (memory (;0;) 145)\n  )\n)\n";
        let (normalized, memories) = normalize_component_memories(source).expect("memory syntax");
        assert_eq!(memories, 1);
        assert!(normalized.contains("(memory (;0;) 145 145)"));
    }

    #[test]
    fn bounded_stdin_line_distinguishes_eof_limit_newline_and_utf8() {
        let at_limit = b"four\n";
        assert!(matches!(
            read_stdin_line(&mut &at_limit[..], 4),
            Ok(StdinLine::Line(line)) if line == "four"
        ));
        let over_limit = b"fives";
        assert!(read_stdin_line(&mut &over_limit[..], 4).is_err());
        let no_newline = b"four";
        assert!(matches!(
            read_stdin_line(&mut &no_newline[..], 4),
            Ok(StdinLine::Line(line)) if line == "four"
        ));
        assert!(matches!(
            read_stdin_line(&mut &b""[..], 4),
            Ok(StdinLine::Eof)
        ));
        assert_eq!(
            read_stdin_line(&mut &b"\xff\n"[..], 4)
                .expect_err("invalid UTF-8 is rejected")
                .kind(),
            std::io::ErrorKind::InvalidData
        );
    }

    #[test]
    fn session_directory_creation_reports_storage_path_and_operation() {
        let root =
            std::env::temp_dir().join(format!("smith_cli_session_dir_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        assert!(std::fs::write(&root, "block directory creation").is_ok());
        let attempted = root.join("run");
        let error = create_session_dir(attempted.clone()).expect_err("file blocks directory");
        assert_eq!(error.code(), "RUNTIME_DIR");
        assert!(
            error
                .to_string()
                .contains("storage [RUNTIME_DIR] create_dir_all")
        );
        match &error {
            smith::error::SmithError::Storage {
                code,
                operation,
                path,
                ..
            } => {
                assert_eq!(*code, smith::error::StorageCode::RuntimeDir);
                assert_eq!(operation.as_str(), "create_dir_all");
                assert_eq!(path, &attempted);
            }
            other => panic!("expected storage error, got {other:?}"),
        }
        let serialized = serde_json::to_value(&error).expect("serialize error");
        assert_eq!(serialized["Storage"]["code"], "RUNTIME_DIR");
        assert_eq!(
            serialized["Storage"]["path"],
            attempted.to_string_lossy().as_ref()
        );
        assert!(std::fs::remove_file(root).is_ok());
    }
}