Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/wasm.rs

Raw
//! Wasm plugin host (`SMH-SPEC-WASM0001`): deterministic engine, artifact validation,
//! transactional load, and fuel with memory ceilings.
//!
//! The engine serves every plugin identically; embedded and user plugins
//! load through this one path with no privilege difference.

use crate::plugin_control::ReloadControl;
use crate::plugins::registry::PackageRegistry;
use crate::plugins::{Capability, NetScope, PluginManifest, PluginPackage};
use ::smith::error::{ProviderFault, Result, SmithError};
use serde::Deserialize;
use smith::http::HttpExecutor;
use smith::structured::{ToolArguments, ToolSchema};
use smith::tool::ToolMetadata;
use smith_ai::auth::{AuthStore, CredentialKey, CredentialReference};
use smith_core::tools::{
    ToolComponentProvenance, ToolDispatcher, ToolDispatcherSnapshot, ToolEffectContext,
    ToolLoadoutProvenance, ToolLoadoutTool, WorkspaceRoot,
};
use std::cell::Cell;
use std::io::Read;
use std::path::{Path, PathBuf};

/// Largest accepted component artifact, in bytes.
/// Largest accepted component artifact, in bytes.
pub const ARTIFACT_BYTES_MAX: usize = 64 * 1024 * 1024;
/// Only plugin world supported by this prototype host.
pub const SUPPORTED_WORLD_VERSION: &str = "0.1.0";
/// Largest table initial allocation admitted for one plugin.
const TABLE_ELEMENTS_MAX: usize = 10_000;
/// Largest UTF-8 request, settings, or catalog snapshot crossing into a codec.
const CODEC_TEXT_BYTES_MAX: usize = 1024 * 1024;
/// Largest model identifier crossing into a codec.
const CODEC_MODEL_BYTES_MAX: usize = 256;
/// Largest codec state or response chunk crossing into a codec.
const CODEC_BINARY_BYTES_MAX: usize = 1024 * 1024;
/// Largest provider declaration or decoded event list returned by a codec.
const CODEC_ITEMS_MAX: usize = 1_024;
const CODING_TOOLS_COMPONENT: &[u8] =
    include_bytes!(concat!(env!("OUT_DIR"), "/smith_plugin_coding_tools.wasm"));
const CODING_TOOLS_METADATA: &str =
    include_str!(concat!(env!("OUT_DIR"), "/coding_tools_metadata.json"));

#[derive(Deserialize)]
struct CodingToolMetadata {
    name: String,
    description: String,
    input_schema_json: String,
}
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, Store};

mod attachment;
mod composition;
mod kernel;
mod lifecycle;
pub use composition::{CompositionGrants, CompositionResourceLimits};
mod sealed_wasi;
use attachment::WorkspaceEffects;

#[allow(missing_docs, reason = "generated bindings carry no doc comments")]
pub mod bindings {
    // The host world: the guest-facing plugin world plus exactly the WASI
    // imports Rust std on wasm32-wasip2 pulls in, all served by Smith's
    // sealed implementations in `sealed_wasi`.
    wasmtime::component::bindgen!({
        path: "../wit",
        inline: "
            package smith:host;
            world plugin-host {
                include smith:plugin/plugin-world@0.1.0;
                import wasi:io/error@0.2.12;
                import wasi:io/poll@0.2.12;
                import wasi:io/streams@0.2.12;
                import wasi:clocks/monotonic-clock@0.2.12;
                import wasi:cli/environment@0.2.12;
                import wasi:cli/exit@0.2.12;
                import wasi:cli/stdin@0.2.12;
                import wasi:cli/stdout@0.2.12;
                import wasi:cli/stderr@0.2.12;
                import wasi:cli/terminal-stdin@0.2.12;
                import wasi:cli/terminal-stdout@0.2.12;
                import wasi:cli/terminal-stderr@0.2.12;
            }
        ",
        imports: {
            "wasi:cli/exit.exit": trappable,
            "wasi:cli/exit.exit-with-code": trappable,
        },
    });
}

use self::bindings::PluginHost;
use self::bindings::exports::smith::plugin::plugin::ToolDeclaration;
use self::bindings::exports::smith::plugin::provider::{
    CatalogSnapshot, DecodeStep, ProviderRequest, ProviderSettings, RequestTemplate,
};
use self::bindings::exports::smith::plugin::registration::{ProtocolBinding, Registrations};
use self::bindings::smith::plugin::log::Host as LogHost;
use self::bindings::smith::plugin::net_scope::Host as NetScopeHost;
use self::bindings::smith::plugin::secret_proxy::Host as SecretProxyHost;
use self::bindings::smith::plugin::tooling::Host as ToolingHost;

/// Deterministic engine configuration per `SMH-SPEC-WASM0001`.
pub struct PluginEngine {
    engine: Engine,
}

/// Component compiled by this engine and ready for isolated instantiation.
pub(crate) struct ValidatedComponent {
    component: Component,
    compatibility: ArtifactCompatibility,
}

#[derive(Clone, Copy, Debug, Default)]
struct ArtifactCompatibility {
    component_private_resources: bool,
}

impl PluginEngine {
    /// Build the deterministic engine: NaN canonicalization on, relaxed SIMD
    /// off, fuel on, and one-frame backtraces.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the engine cannot be configured.
    pub fn new() -> Result<Self> {
        let mut config = Config::new();
        config.cranelift_nan_canonicalization(true);
        config.wasm_relaxed_simd(false);
        config.consume_fuel(true);
        config.epoch_interruption(true);
        config.wasm_backtrace_max_frames(std::num::NonZeroUsize::new(1));
        let engine =
            Engine::new(&config).map_err(|e| plugin_fault(format!("engine config failed: {e}")))?;
        Ok(Self { engine })
    }

    /// Validate one artifact against the world; a rejected artifact never
    /// instantiates.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault naming the validation stage and cause.
    pub fn validate(&self, artifact: &Path) -> Result<Component> {
        let metadata = std::fs::metadata(artifact)
            .map_err(|error| plugin_fault(format!("validation failed: {error}")))?;
        if metadata.len() > ARTIFACT_BYTES_MAX as u64 {
            return Err(plugin_fault(format!(
                "validation failed: artifact exceeds {ARTIFACT_BYTES_MAX} bytes"
            )));
        }
        let bytes = read_artifact(artifact, metadata.len())?;
        self.validate_bytes(&bytes)
    }

    /// Validate an already embedded component through the same component
    /// validation path as a package artifact.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the component exceeds a limit or fails
    /// validation.
    pub fn validate_bytes(&self, bytes: &[u8]) -> Result<Component> {
        if bytes.len() > ARTIFACT_BYTES_MAX {
            return Err(plugin_fault(format!(
                "validation failed: artifact exceeds {ARTIFACT_BYTES_MAX} bytes"
            )));
        }
        Ok(self.validate_component_bytes(bytes)?.component)
    }

    fn validate_component_bytes(&self, bytes: &[u8]) -> Result<ValidatedComponent> {
        if bytes.len() > ARTIFACT_BYTES_MAX {
            return Err(plugin_fault(format!(
                "validation failed: artifact exceeds {ARTIFACT_BYTES_MAX} bytes"
            )));
        }
        let compatibility = validate_declared_limits(bytes)?;
        let component = Component::from_binary(&self.engine, bytes)
            .map_err(|error| plugin_fault(format!("validation failed: {error}")))?;
        Ok(ValidatedComponent {
            component,
            compatibility,
        })
    }

    /// The shared engine behind every plugin.
    #[must_use]
    pub const fn engine(&self) -> &Engine {
        &self.engine
    }
}

/// One instantiated plugin: pinned store, fuel budget, and bindings.
pub struct PluginInstance {
    component: Component,
    store: Store<PluginHostState>,
    bindings: PluginHost,
    raw: wasmtime::component::Instance,
}

type CredentialConstructor = wasmtime::component::TypedFunc<
    (
        self::bindings::smith::plugin::secret_proxy::ProfileRef,
        Option<String>,
        String,
    ),
    (wasmtime::component::ResourceAny,),
>;
type CredentialRenew = wasmtime::component::TypedFunc<
    (wasmtime::component::ResourceAny,),
    (
        std::result::Result<
            self::bindings::smith::plugin::secret_proxy::SecretRef,
            self::bindings::smith::plugin::secret_proxy::AuthorizationFault,
        >,
    ),
>;

/// A fully validated, instantiated, and declared plugin candidate.
///
/// Constructing a candidate performs no publication, so a failed load cannot
/// change the active registry.
pub struct PluginGeneration {
    manifest: PluginManifest,
    instance: PluginInstance,
    tools: Vec<ToolDeclaration>,
    registrations: Registrations,
    responses_credential_source: Option<String>,
    lifecycle_handlers: Vec<lifecycle::Handler>,
    manifest_sha256: String,
    component_sha256: String,
    component_private_resources: bool,
}

/// Active plugin generation slot.
///
/// Replacing this slot is one assignment after every replacement plugin has
/// completely loaded, preserving the prior generation on every load failure.
#[derive(Default)]
pub struct PluginRegistry {
    generations: Vec<PluginGeneration>,
}

/// Per-plugin runtime ceilings.
#[derive(Clone, Copy, Debug)]
pub struct PluginCeilings {
    /// Memory ceiling in bytes.
    pub memory_bytes: usize,
    /// Fuel budget per call.
    pub fuel: u64,
}

impl Default for PluginCeilings {
    fn default() -> Self {
        Self {
            memory_bytes: 64 * 1024 * 1024,
            fuel: 10_000_000_000,
        }
    }
}

struct PluginHostState {
    /// Host-injected monotonic clock reading; the guest never sees OS time.
    monotonic_now: u64,
    ceilings: PluginCeilings,
    grants: u8,
    effects_enabled: bool,
    lifecycle_deadline: Option<std::time::Instant>,
    lifecycle_allocation_bytes: u64,
    plugin_id: String,
    net_scopes: Vec<NetScope>,
    secret_grants: Vec<SecretGrant>,
    oauth_authority: Option<Box<crate::oauth::LoginAuthority>>,
    /// Attached only for one synchronous component invocation.
    workspace_effects: WorkspaceEffects,
    /// Once terminal HTTP evidence cannot be persisted, guest success is invalid.
    fatal_recording_failure: Cell<bool>,
    log_bytes: usize,
    log_entries: Vec<String>,
    secret_values: Vec<String>,
    resolved_secret_refs: Vec<ResolvedSecretRef>,
    mock_effects: Option<MockEffects>,
    composition: Option<Box<composition::InvocationPool>>,
    memory_bytes: usize,
    table_elements: usize,
    sealed_handles: u32,
}

/// One expected mocked host effect in a plugin fixture.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MockEffectPlan {
    /// WIT operation name.
    pub operation: String,
    /// Canonical JSON request supplied by the guest.
    pub request_json: String,
    /// Fixed mocked result returned to the guest.
    pub response: String,
}

/// Output and ordered host effects observed for one mocked plugin invocation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MockInvocation {
    /// Guest return value.
    pub output: String,
    /// Ordered effects observed at the host boundary.
    pub effects: Vec<MockEffectPlan>,
}

/// One host-owned credential authority delegated to a plugin at one origin.
///
/// The source identifier never names an arbitrary auth-store entry: it is
/// matched only against this explicit grant before resolution at HTTP dispatch.
#[derive(Clone)]
pub struct SecretGrant {
    source_id: String,
    origin: NetScope,
    scopes: Vec<String>,
    credential: CredentialReference,
    auth_store: AuthStore,
}

/// Persistable, host-owned secret authority for one plugin source.
///
/// Plaintext remains in [`AuthStore`] until a matching HTTP header reaches the
/// host network boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SecretGrantConfig {
    source_id: String,
    origin: NetScope,
    scopes: Vec<String>,
    credential_key: CredentialKey,
}

impl SecretGrantConfig {
    /// Create one authority from explicit user-selected source, origin, scopes, and credential.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault for an empty source or an empty scope set.
    pub fn new(
        source_id: String,
        origin: NetScope,
        scopes: Vec<String>,
        credential_key: CredentialKey,
    ) -> Result<Self> {
        if source_id.is_empty() || scopes.is_empty() {
            return Err(plugin_fault(
                "secret grant requires a source and at least one scope",
            ));
        }
        let scopes = canonical_secret_scopes(scopes);
        if scopes.iter().any(|scope| scope != "http-request") {
            return Err(plugin_fault("secret grant has an unsupported scope"));
        }
        Ok(Self {
            source_id,
            origin,
            scopes,
            credential_key,
        })
    }

    /// Guest-visible credential source identity.
    #[must_use]
    pub fn source_id(&self) -> &str {
        &self.source_id
    }

    /// Explicit HTTP origin receiving this credential.
    #[must_use]
    pub const fn origin(&self) -> &NetScope {
        &self.origin
    }

    /// Explicit secret scopes.
    #[must_use]
    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }

    /// Auth-store key selected by user configuration.
    #[must_use]
    pub const fn credential_key(&self) -> CredentialKey {
        self.credential_key
    }

    /// Attach this declarative authority to one runtime's isolated auth store.
    #[must_use]
    pub fn with_auth_store(&self, auth_store: AuthStore) -> SecretGrant {
        SecretGrant {
            source_id: self.source_id.clone(),
            origin: self.origin.clone(),
            scopes: self.scopes.clone(),
            credential: CredentialReference::store_or_env(self.credential_key),
            auth_store,
        }
    }
}

impl SecretGrant {
    /// Grant one store-or-environment authority to an explicit origin and scopes.
    #[must_use]
    pub fn store_or_env(
        source_id: impl Into<String>,
        origin: NetScope,
        scopes: Vec<String>,
        key: CredentialKey,
        auth_store: AuthStore,
    ) -> Self {
        Self {
            source_id: source_id.into(),
            origin,
            scopes: canonical_secret_scopes(scopes),
            credential: CredentialReference::store_or_env(key),
            auth_store,
        }
    }
}

/// One opaque handle bound to one authorized grant and one resolved credential.
struct ResolvedSecretRef {
    grant_index: usize,
    secret_value_index: u8,
}

struct MockEffects {
    plans: Vec<MockEffectPlan>,
    trace: Vec<MockEffectPlan>,
}

const WORKSPACE_GRANT: u8 = 1;
const PROCESS_GRANT: u8 = 2;
const NET_SCOPE_GRANT: u8 = 4;
const SECRET_PROXY_GRANT: u8 = 8;
const LOG_GRANT: u8 = 16;
const LOG_ENTRIES_MAX: usize = 64;
const LOG_BYTES_MAX: usize = 8 * 1024;
const RESOLVED_SECRET_REFS_MAX: usize = 32;

impl PluginHostState {
    const fn granted(&self, grant: u8) -> bool {
        self.grants & grant != 0
    }

    fn limits(&mut self) -> &mut dyn wasmtime::ResourceLimiter {
        self
    }
}

impl wasmtime::ResourceLimiter for PluginHostState {
    fn memory_growing(
        &mut self,
        current: usize,
        desired: usize,
        maximum: Option<usize>,
    ) -> wasmtime::Result<bool> {
        let allowed = self.ceilings.memory_growing(current, desired, maximum)?;
        if allowed {
            self.memory_bytes += desired;
        }
        Ok(allowed)
    }
    fn table_growing(
        &mut self,
        current: usize,
        desired: usize,
        maximum: Option<usize>,
    ) -> wasmtime::Result<bool> {
        let allowed = self.ceilings.table_growing(current, desired, maximum)?;
        if allowed {
            self.table_elements += desired;
        }
        Ok(allowed)
    }
}

impl wasmtime::ResourceLimiter for PluginCeilings {
    fn memory_growing(
        &mut self,
        current: usize,
        desired: usize,
        _maximum: Option<usize>,
    ) -> wasmtime::Result<bool> {
        Ok(current == 0 && desired <= self.memory_bytes)
    }

    fn table_growing(
        &mut self,
        current: usize,
        desired: usize,
        _maximum: Option<usize>,
    ) -> wasmtime::Result<bool> {
        Ok(current == 0 && desired <= TABLE_ELEMENTS_MAX)
    }
}

impl PluginGeneration {
    /// Load one trusted package through its manifest-confined artifact.
    ///
    /// # Errors
    ///
    /// Returns a lifecycle or registration failure without publication.
    pub fn load_package(
        engine: &PluginEngine,
        package: PluginPackage,
        grants: &[Capability],
    ) -> Result<Self> {
        let manifest_sha256 = smith::sha256::digest_hex(package.manifest_bytes());
        let component_sha256 = smith::sha256::digest_hex(package.artifact_bytes());
        let (manifest, artifact) = package.into_parts();
        if manifest.id().starts_with("smith:") {
            return Err(plugin_fault(
                "external packages cannot claim the reserved smith: identity; choose a non-smith: package id",
            ));
        }
        Self::load_embedded_with_hashes(
            engine,
            manifest,
            &artifact,
            grants,
            manifest_sha256,
            component_sha256,
        )
    }

    /// Load one manifest-declared plugin after trust resolved its grants.
    ///
    /// # Errors
    ///
    /// Returns before instantiation when the declared world is unsupported or
    /// a requested capability lacks a grant; otherwise returns lifecycle or
    /// declaration failures without publishing anything.
    pub fn load(
        engine: &PluginEngine,
        manifest: PluginManifest,
        artifact: &Path,
        grants: &[Capability],
    ) -> Result<Self> {
        validate_manifest_grants(&manifest, grants)?;
        let metadata = std::fs::metadata(artifact)
            .map_err(|error| plugin_fault(format!("validation failed: {error}")))?;
        if metadata.len() > ARTIFACT_BYTES_MAX as u64 {
            return Err(plugin_fault(format!(
                "validation failed: artifact exceeds {ARTIFACT_BYTES_MAX} bytes"
            )));
        }
        let bytes = read_artifact(artifact, metadata.len())?;
        Self::load_embedded(engine, manifest, &bytes, grants)
    }

    /// Load an embedded component after validating the same manifest and grants
    /// required for an installed package.
    ///
    /// # Errors
    ///
    /// Returns before instantiation when the manifest or component is invalid.
    pub fn load_embedded(
        engine: &PluginEngine,
        manifest: PluginManifest,
        artifact: &[u8],
        grants: &[Capability],
    ) -> Result<Self> {
        let manifest_sha256 = manifest_digest(&manifest);
        let component_sha256 = smith::sha256::digest_hex(artifact);
        Self::load_embedded_with_hashes(
            engine,
            manifest,
            artifact,
            grants,
            manifest_sha256,
            component_sha256,
        )
    }

    fn load_embedded_with_hashes(
        engine: &PluginEngine,
        manifest: PluginManifest,
        artifact: &[u8],
        grants: &[Capability],
        manifest_sha256: String,
        component_sha256: String,
    ) -> Result<Self> {
        validate_manifest_grants(&manifest, grants)?;
        let component = engine.validate_component_bytes(artifact)?;
        Self::load_validated_embedded_with_hashes(
            engine,
            manifest,
            &component,
            grants,
            manifest_sha256,
            component_sha256,
        )
    }

    fn load_validated_embedded_with_hashes(
        engine: &PluginEngine,
        manifest: PluginManifest,
        component: &ValidatedComponent,
        grants: &[Capability],
        manifest_sha256: String,
        component_sha256: String,
    ) -> Result<Self> {
        validate_manifest_grants(&manifest, grants)?;
        let mut instance =
            PluginInstance::instantiate(engine, &component.component, PluginCeilings::default())?;
        instance.configure_capabilities(manifest.capabilities());
        let tools = instance.declare_tools()?;
        validate_tool_declarations(&tools)?;
        let registrations = instance.declare_registrations()?;
        validate_registrations(&registrations)?;
        let responses_credential_source = instance.declare_responses_binding()?;
        let lifecycle_handlers = instance.declare_lifecycle()?;
        instance.configure_plugin_id(manifest.id());
        instance.enable_effects();
        Ok(Self {
            manifest,
            instance,
            tools,
            registrations,
            responses_credential_source,
            lifecycle_handlers,
            manifest_sha256,
            component_sha256,
            component_private_resources: component.compatibility.component_private_resources,
        })
    }

    // Versioned kernel-only modules keep their login tools outside inference.
    // A codec/source component is not kernel-only and retains its contributions.
    fn credential_module_only(&self) -> bool {
        self.registrations.providers.is_empty()
            && self.registrations.models.is_empty()
            && self.responses_credential_source.is_none()
            && self
                .registrations
                .credential_sources
                .iter()
                .any(|source| source.id.ends_with("@1"))
    }

    /// Manifest validated for this generation.
    #[must_use]
    pub const fn manifest(&self) -> &PluginManifest {
        &self.manifest
    }

    /// SHA-256 of exact manifest bytes loaded for this generation.
    #[must_use]
    pub fn manifest_sha256(&self) -> &str {
        &self.manifest_sha256
    }

    /// SHA-256 of exact component bytes loaded for this generation.
    #[must_use]
    pub fn component_sha256(&self) -> &str {
        &self.component_sha256
    }

    /// Configure explicit network origins resolved at trust or install time.
    pub fn configure_net_scopes(&mut self, scopes: Vec<NetScope>) {
        self.instance.configure_net_scopes(scopes);
    }

    /// Configure host-owned credential authority for explicit guest exchanges.
    pub fn configure_secret_grants(&mut self, grants: Vec<SecretGrant>) {
        self.instance.configure_secret_grants(grants);
    }

    /// Bind explicit host-owned login authority for this generation only.
    pub fn configure_login_authority(&mut self, authority: crate::oauth::LoginAuthority) {
        self.instance.store.data_mut().oauth_authority = Some(Box::new(authority));
    }

    fn credential_module_functions(&mut self) -> Result<(CredentialConstructor, CredentialRenew)> {
        let instance = self.instance.raw;
        let store = &mut self.instance.store;
        let interface = instance
            .get_export_index(&mut *store, None, "smith:plugin/credential-source-v1@0.1.0")
            .ok_or_else(|| {
                plugin_fault(
                    "credential consumer openai-chatgpt-plan: missing credential-source-v1 module",
                )
            })?;
        let constructor = instance
            .get_export_index(
                &mut *store,
                Some(&interface),
                "[constructor]credential-source",
            )
            .ok_or_else(|| plugin_fault("credential module missing constructor"))?;
        let renew = instance
            .get_export_index(
                &mut *store,
                Some(&interface),
                "[method]credential-source.renew",
            )
            .ok_or_else(|| plugin_fault("credential module missing renew"))?;
        let constructor = instance
            .get_typed_func::<(
                self::bindings::smith::plugin::secret_proxy::ProfileRef,
                Option<String>,
                String,
            ), (wasmtime::component::ResourceAny,)>(&mut *store, constructor)
            .map_err(|_| plugin_fault("credential module constructor has invalid type"))?;
        let renew = instance
            .get_typed_func::<(wasmtime::component::ResourceAny,), (
                std::result::Result<
                    self::bindings::smith::plugin::secret_proxy::SecretRef,
                    self::bindings::smith::plugin::secret_proxy::AuthorizationFault,
                >,
            )>(&mut *store, renew)
            .map_err(|_| plugin_fault("credential module renew has invalid type"))?;
        Ok((constructor, renew))
    }

    /// Invoke the optional major-versioned credential module after admitted provider dispatch.
    /// # Errors
    /// Rejects missing exports, invalid resource shape, traps, or failed renewal.
    pub(crate) fn renew_credential_module(
        &mut self,
        profile: &str,
        fixture_issuer: Option<&str>,
        cancel: smith::tool::CancelHandle,
    ) -> Result<[String; 3]> {
        use self::bindings::smith::plugin::secret_proxy::ProfileRef;
        let (constructor, renew) = self.credential_module_functions()?;
        let store = &mut self.instance.store;
        refill_fuel(store)?;
        let connection_id = store
            .data()
            .oauth_authority
            .as_deref()
            .ok_or_else(|| plugin_fault("credential module missing selected host authority"))?
            .connection_id()
            .to_string();
        let (resource,) = constructor
            .call(
                &mut *store,
                (
                    ProfileRef {
                        id: profile.to_string(),
                    },
                    fixture_issuer.map(str::to_string),
                    connection_id,
                ),
            )
            .map_err(|_| plugin_fault("credential module constructor failed"))?;
        store
            .data_mut()
            .oauth_authority
            .as_deref_mut()
            .ok_or_else(|| plugin_fault("credential module missing selected host authority"))?
            .begin_dispatch(cancel);
        refill_fuel(store)?;
        let result = renew.call(&mut *store, (resource,));
        resource
            .resource_drop(&mut *store)
            .map_err(|_| plugin_fault("credential module resource drop failed"))?;
        let (reference,) = result.map_err(|_| plugin_fault("credential module renewal failed"))?;
        let reference = reference.map_err(|_| plugin_fault("selected OAuth session unavailable; explicitly reauthorize if renewal is uncertain"))?;
        if reference.id != profile {
            return Err(plugin_fault(
                "credential module returned an unauthorized profile reference",
            ));
        }
        store
            .data_mut()
            .oauth_authority
            .as_deref_mut()
            .and_then(crate::oauth::LoginAuthority::take_credential)
            .ok_or_else(|| plugin_fault("credential module returned no host credential"))
    }

    // Capture immutable compiled code and validated authority, never a package path.
    pub(crate) fn protocol_loader(&self) -> impl Fn() -> Result<Self> + Send + Sync + use<> {
        let engine = PluginEngine {
            engine: self.instance.store.engine().clone(),
        };
        let component = ValidatedComponent {
            component: self.instance.component.clone(),
            compatibility: ArtifactCompatibility {
                component_private_resources: self.component_private_resources,
            },
        };
        let manifest = self.manifest.clone();
        let manifest_sha256 = self.manifest_sha256.clone();
        let component_sha256 = self.component_sha256.clone();
        move || {
            Self::load_validated_embedded_with_hashes(
                &engine,
                manifest.clone(),
                &component,
                manifest.capabilities(),
                manifest_sha256.clone(),
                component_sha256.clone(),
            )
        }
    }

    /// Validated tools registered by this generation.
    #[must_use]
    pub fn tools(&self) -> &[ToolDeclaration] {
        &self.tools
    }

    pub(crate) fn manifest_id(&self) -> &str {
        self.manifest.id()
    }

    /// Static registrations validated before this generation was published.
    #[must_use]
    pub const fn registrations(&self) -> &Registrations {
        &self.registrations
    }

    /// Require the optional major-versioned Responses protocol binding.
    /// # Errors
    /// Rejects absent binding or an unexpected credential-source dependency.
    pub(crate) fn require_responses_binding(&self) -> Result<()> {
        if self.responses_credential_source.as_deref() != Some("openai-chatgpt-plan@1") {
            return Err(plugin_fault(
                "Responses protocol requires openai-chatgpt-plan@1 credential module binding",
            ));
        }
        if !self.manifest.capabilities().contains(&Capability::NetScope)
            || !self
                .manifest
                .capabilities()
                .contains(&Capability::SecretProxy)
        {
            return Err(plugin_fault(
                "Responses protocol requires net-scope and secret-proxy capabilities",
            ));
        }
        Ok(())
    }

    /// Require one registered provider protocol binding before use.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when registration did not declare `binding`.
    pub fn require_protocol_binding(&self, binding: ProtocolBinding) -> Result<()> {
        if self
            .registrations
            .providers
            .iter()
            .any(|provider| same_protocol_binding(provider.protocol, binding))
        {
            Ok(())
        } else {
            Err(plugin_fault(
                "registration has no matching protocol binding",
            ))
        }
    }

    fn invoke_with_effects(
        &mut self,
        name: &str,
        input_json: &str,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        if !self.tools.iter().any(|tool| tool.name == name) {
            return Err(plugin_fault(format!(
                "invocation failed: tool {name} is not registered"
            )));
        }
        if self
            .manifest
            .capabilities()
            .contains(&Capability::Workspace)
        {
            effects.confine_workspace()?;
        }
        effects.set_component_provenance(ToolComponentProvenance {
            source_id: self.manifest.id().to_string(),
            manifest_sha256: self.manifest_sha256().to_string(),
            component_sha256: self.component_sha256().to_string(),
        });
        self.instance.invoke_with_effects(name, input_json, effects)
    }

    /// Invoke one declared tool with fixture-owned mocked capability responses.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the tool is undeclared, an effect differs
    /// from its plan, or the guest output differs from the fixture expectation.
    pub fn invoke_with_mock_effects(
        &mut self,
        name: &str,
        input_json: &str,
        plans: Vec<MockEffectPlan>,
    ) -> Result<MockInvocation> {
        if !self.tools.iter().any(|tool| tool.name == name) {
            return Err(plugin_fault(format!(
                "invocation failed: tool {name} is not registered"
            )));
        }
        self.instance
            .invoke_with_mock_effects(name, input_json, plans)
    }

    /// Codec-owned settings declared during registration.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when declaration traps or exhausts fuel.
    pub fn provider_settings(&mut self) -> Result<ProviderSettings> {
        self.instance.declare_provider_settings()
    }

    /// Validate and canonicalize one immutable effective configuration snapshot.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when validation traps, exhausts fuel, or rejects settings.
    pub fn validate_provider_settings(
        &mut self,
        settings: ProviderSettings,
    ) -> Result<ProviderSettings> {
        self.instance.validate_provider_settings(settings)
    }

    /// Build one untrusted provider request template through the guest codec.
    ///
    /// The returned authorization value is a secret reference, never secret
    /// plaintext; the host resolves it only at the HTTP effect boundary.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the guest traps, exhausts fuel, or rejects
    /// the request.
    pub fn build_provider_request(
        &mut self,
        model: &str,
        request: &ProviderRequest,
        settings: ProviderSettings,
        catalog: &CatalogSnapshot,
    ) -> Result<RequestTemplate> {
        bound_codec_text("provider model", model, CODEC_MODEL_BYTES_MAX)?;
        let template = self
            .instance
            .build_provider_request(model, request, settings, catalog)?;
        bound_codec_text("provider template URL", &template.url, CODEC_TEXT_BYTES_MAX)?;
        bound_codec_text(
            "provider template authorization",
            &template.authorization,
            CODEC_TEXT_BYTES_MAX,
        )?;
        bound_codec_text(
            "provider template body",
            &template.body,
            CODEC_TEXT_BYTES_MAX,
        )?;
        Ok(template)
    }

    /// Decode one bounded response chunk with host-owned codec state.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the guest traps, exhausts fuel, or rejects
    /// the response.
    pub fn decode_provider_chunk(
        &mut self,
        state: &[u8],
        chunk: &[u8],
        finished: bool,
    ) -> Result<DecodeStep> {
        bound_codec_bytes("provider codec state", state, CODEC_BINARY_BYTES_MAX)?;
        bound_codec_bytes("provider response chunk", chunk, CODEC_BINARY_BYTES_MAX)?;
        let step = self
            .instance
            .decode_provider_chunk(state, chunk, finished)?;
        bound_codec_bytes(
            "provider returned codec state",
            &step.state,
            CODEC_BINARY_BYTES_MAX,
        )?;
        if step.events.len() > CODEC_ITEMS_MAX {
            return Err(codec_limit(
                "provider decoded events",
                step.events.len(),
                CODEC_ITEMS_MAX,
            ));
        }
        Ok(step)
    }
}

/// Dispatches built-in coding tools through the hash-pinned component.
pub struct CodingToolsDispatcher {
    workspace_root: PathBuf,
    runtime: Option<CodingToolsRuntime>,
}

struct CodingToolsRuntime {
    generation: PluginGeneration,
    workspace_root: PathBuf,
    workspace: Option<WorkspaceRoot>,
}

/// Create a lazy dispatcher for the hash-pinned built-in coding tools.
///
/// Component validation, instantiation, and workspace authority acquisition run
/// only for an invoked tool, never for a tool-free agent turn.
#[must_use]
pub fn coding_tools_dispatcher(workspace_root: &Path) -> CodingToolsDispatcher {
    CodingToolsDispatcher {
        workspace_root: workspace_root.to_path_buf(),
        runtime: None,
    }
}

fn manifest_digest(manifest: &PluginManifest) -> String {
    smith::sha256::digest_hex(manifest.id().as_bytes())
}

fn load_coding_tools(workspace_root: &Path) -> Result<CodingToolsRuntime> {
    let metadata = coding_tool_metadata()?;
    let engine = PluginEngine::new()?;
    let manifest = PluginManifest::parse(
        "id \"smith:coding-tools\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"smith_plugin_coding_tools.wasm\"\ncapability \"workspace\"\ncapability \"process\"",
    )?;
    // Product-default authority for Smith's hash-pinned built-in component.
    // `process` is independent from its confined workspace filesystem grant.
    let mut generation = PluginGeneration::load_embedded(
        &engine,
        manifest,
        CODING_TOOLS_COMPONENT,
        &[Capability::Workspace, Capability::Process],
    )?;
    generation.instance.configure_coding_capabilities();
    validate_coding_tool_declarations(generation.tools(), &metadata)?;
    Ok(CodingToolsRuntime {
        generation,
        workspace_root: workspace_root.to_path_buf(),
        workspace: None,
    })
}

impl CodingToolsDispatcher {
    fn tools() -> Result<Vec<ToolMetadata>> {
        coding_tool_metadata()
    }

    fn owns(&mut self, name: &str) -> Result<bool> {
        Ok(self
            .runtime()?
            .generation
            .tools()
            .iter()
            .any(|tool| tool.name == name))
    }

    fn runtime(&mut self) -> Result<&mut CodingToolsRuntime> {
        if self.runtime.is_none() {
            self.runtime = Some(load_coding_tools(&self.workspace_root)?);
        }
        // The branch above initializes the runtime whenever it was absent.
        self.runtime
            .as_mut()
            .ok_or_else(|| plugin_fault("coding tools runtime initialization failed"))
    }
}

impl ToolDispatcher for CodingToolsDispatcher {
    fn begin_provider_round(&mut self) -> Result<ToolDispatcherSnapshot> {
        Ok(tool_snapshot(
            Self::tools()?,
            ToolComponentProvenance {
                source_id: "smith:coding-tools".to_string(),
                manifest_sha256: smith::sha256::digest_hex(
                    b"id \"smith:coding-tools\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"smith_plugin_coding_tools.wasm\"\ncapability \"workspace\"\ncapability \"process\"",
                ),
                component_sha256: smith::sha256::digest_hex(CODING_TOOLS_COMPONENT),
            },
        ))
    }

    fn invoke(
        &mut self,
        name: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        let runtime = self.runtime()?;
        let workspace = if let Some(workspace) = &runtime.workspace {
            workspace.clone()
        } else {
            let workspace = WorkspaceRoot::open(&runtime.workspace_root)?;
            runtime.workspace = Some(workspace.clone());
            workspace
        };
        if !workspace.matches_directory(effects.working_dir())? {
            return Err(plugin_fault(
                "workspace authority does not match this tool session",
            ));
        }
        effects.set_workspace_root(workspace);
        let input_json = serde_json::to_string(input)
            .map_err(|error| plugin_fault(format!("tool input serialization failed: {error}")))?;
        runtime
            .generation
            .invoke_with_effects(name, &input_json, effects)
    }
}

pub(crate) type GenerationLoader =
    std::sync::Arc<dyn Fn() -> Result<PluginGeneration> + Send + Sync>;

/// Dispatcher that combines immutable built-in tools with the current user
/// package generation.
pub use smith_core::tools::ToolPolicyState;

/// Explicit per-qualified-tool model-call policy.
#[derive(Clone, Debug, Default)]
pub struct ToolPolicy {
    states: Vec<(String, ToolPolicyState)>,
}

impl ToolPolicy {
    /// Add one exact qualified tool state.
    ///
    /// # Errors
    /// Returns a plugin fault for an unqualified or duplicate identity.
    pub fn set(&mut self, name: String, state: ToolPolicyState) -> Result<()> {
        if !name.contains('/') || self.states.iter().any(|(known, _)| known == &name) {
            return Err(plugin_fault(
                "tool policy requires one unique qualified tool identity",
            ));
        }
        self.states.push((name, state));
        self.states
            .sort_unstable_by(|left, right| left.0.cmp(&right.0));
        Ok(())
    }

    /// Parse `qualified-name=advertised|hidden|disabled` command-line entries.
    ///
    /// # Errors
    /// Returns a plugin fault naming malformed policy input.
    pub fn from_specs(specs: &[String]) -> Result<Self> {
        let mut policy = Self::default();
        for spec in specs {
            let (name, state) = spec.split_once('=').ok_or_else(|| {
                plugin_fault(format!(
                    "tool policy {spec:?} requires qualified-name=advertised|hidden|disabled"
                ))
            })?;
            let state = match state {
                "advertised" => ToolPolicyState::Advertised,
                "hidden" => ToolPolicyState::Hidden,
                "disabled" => ToolPolicyState::Disabled,
                _ => {
                    return Err(plugin_fault(format!(
                        "tool policy {spec:?} has unknown state; use advertised, hidden, or disabled"
                    )));
                }
            };
            policy.set(name.to_string(), state)?;
        }
        Ok(policy)
    }

    fn state(&self, name: &str) -> ToolPolicyState {
        self.states
            .iter()
            .find(|(known, _)| known == name)
            .map_or(ToolPolicyState::Advertised, |(_, state)| *state)
    }
}

/// Live dispatcher retaining one immutable policy and generation pin per provider round.
pub struct RuntimeToolsDispatcher {
    coding_tools: Option<CodingToolsDispatcher>,
    packages: PackageRegistry,
    auth_store: AuthStore,
    engine: Option<PluginEngine>,
    plugins: PluginRegistry,
    control: Option<ReloadControl>,
    published: bool,
    provider: Option<crate::protocol::ProviderRoundOwner>,
    tool_policy: ToolPolicy,
    tool_authority: ToolPolicy,
    composition_grants: CompositionGrants,
    runtime_republish: bool,
}

/// Create the live package dispatcher for one runtime.
///
/// First use and each typed reload notification attempt a complete candidate
/// load before publication; a failed candidate leaves the prior generation
/// pinned for the active provider request and tool-result batch.
///
pub fn runtime_tools_dispatcher(
    workspace_root: &Path,
    auth_store: AuthStore,
    coding_tools_enabled: bool,
    control: Option<ReloadControl>,
) -> RuntimeToolsDispatcher {
    RuntimeToolsDispatcher {
        coding_tools: coding_tools_enabled.then(|| coding_tools_dispatcher(workspace_root)),
        packages: PackageRegistry::at_default(),
        auth_store,
        engine: None,
        plugins: PluginRegistry::new(),
        control,
        published: false,
        provider: None,
        tool_policy: ToolPolicy::default(),
        tool_authority: ToolPolicy::default(),
        composition_grants: CompositionGrants::default(),
        runtime_republish: false,
    }
}

impl ToolDispatcher for RuntimeToolsDispatcher {
    fn has_lifecycle_handlers(&self, boundary: smith::lifecycle::Boundary) -> bool {
        self.plugins.has_lifecycle_handlers(boundary)
    }

    fn begin_provider_round(&mut self) -> Result<ToolDispatcherSnapshot> {
        let coding_tools = self.coding_tools.as_mut().map_or_else(
            || Ok(ToolDispatcherSnapshot::default()),
            ToolDispatcher::begin_provider_round,
        )?;
        let reload_requested = self
            .control
            .as_ref()
            .is_some_and(ReloadControl::take_reload_request);
        if !self.published || reload_requested {
            self.publish_candidate()?;
        }
        if self.runtime_republish {
            if let (Some(provider), Some(engine)) = (&self.provider, &self.engine) {
                provider.publish(&mut self.plugins, engine)?;
            }
            self.runtime_republish = false;
        }
        let mut snapshot = coding_tools;
        extend_tool_snapshot(&mut snapshot, self.plugins.snapshot_for_role(true)?)?;
        snapshot.registered_tools = snapshot.tools.clone();
        snapshot.policy = snapshot
            .registered_tools
            .iter()
            .map(|tool| (tool.name.clone(), self.tool_policy.state(&tool.name)))
            .collect();
        snapshot
            .tools
            .retain(|tool| self.tool_policy.state(&tool.name) == ToolPolicyState::Advertised);
        snapshot.provenance.tools.retain(|tool| {
            self.tool_policy.state(&tool.definition.name) == ToolPolicyState::Advertised
        });
        Ok(snapshot)
    }

    fn lifecycle(
        &mut self,
        event: &smith::lifecycle::LifecycleEvent,
        cancel: &smith::tool::CancelHandle,
    ) -> Result<smith::lifecycle::LifecycleBatch> {
        self.plugins
            .lifecycle(event, cancel, &self.composition_grants)
    }
    fn lifecycle_effects(
        &mut self,
        event: &smith::lifecycle::LifecycleEvent,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<smith::lifecycle::LifecycleBatch> {
        if !self.plugins.has_lifecycle_handlers(event.boundary) {
            return Ok(smith::lifecycle::LifecycleBatch::default());
        }
        let deadline = std::time::Instant::now()
            + std::time::Duration::from_nanos(self.composition_grants.limits().timeout_nanoseconds);
        let allocation = smith_alloc::AllocationGroup::new()
            .map_err(|_| plugin_fault("lifecycle allocation observer unavailable"))?;
        let _allocation = allocation.enter();
        let redaction_values = self
            .provider
            .as_ref()
            .map(|owner| owner.redaction_values(&self.auth_store))
            .transpose()?
            .unwrap_or_default();
        self.plugins.lifecycle_effects(
            event,
            &effects.cancel_handle(),
            &self.composition_grants,
            Some(effects),
            &redaction_values,
            Some(deadline),
        )
    }

    fn validate_lifecycle(
        &self,
        actions: &[smith::lifecycle::LifecycleAction],
        model: &str,
    ) -> Result<()> {
        use smith::lifecycle::LifecycleAction as A;
        let changes = || {
            actions
                .iter()
                .flat_map(|action| match action {
                    A::SetToolPolicy(changes) => changes.as_slice(),
                    _ => &[],
                })
                .map(|(name, _)| name.as_str())
        };
        let additions = changes()
            .enumerate()
            .filter(|(index, name)| {
                !self
                    .tool_policy
                    .states
                    .iter()
                    .any(|(known, _)| known == *name)
                    && !changes().take(*index).any(|prior| prior == *name)
            })
            .count();
        if additions
            > smith::lifecycle::TOOL_POLICY_ITEMS_MAX.saturating_sub(self.tool_policy.states.len())
        {
            return Err(plugin_fault(
                "lifecycle tool policy exceeds resident item bound",
            ));
        }
        for action in actions {
            match action {
                A::SetModel(selected) if selected != model => {
                    self.provider
                        .as_ref()
                        .ok_or_else(|| plugin_fault("model unavailable"))?
                        .validate_model(selected)?;
                }
                A::SetProvider(selected) => self
                    .provider
                    .as_ref()
                    .ok_or_else(|| plugin_fault("provider unavailable"))?
                    .validate_provider(selected)?,
                A::IncludeUsage(_) => {
                    self.provider
                        .as_ref()
                        .ok_or_else(|| plugin_fault("provider settings unavailable"))?;
                }
                A::SetToolPolicy(changes) => {
                    for (name, state) in changes {
                        let authority = self.tool_authority.state(name);
                        if authority == ToolPolicyState::Disabled && *state != authority
                            || authority == ToolPolicyState::Hidden
                                && *state == ToolPolicyState::Advertised
                        {
                            return Err(plugin_fault("lifecycle cannot widen host tool authority"));
                        }
                        if !self.plugins.generations.iter().any(|generation| {
                            generation.tools.iter().any(|tool| {
                                qualified_tool_name(generation.manifest.id(), &tool.name) == *name
                            })
                        }) {
                            return Err(plugin_fault("tool policy target unavailable"));
                        }
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn commit_lifecycle(&mut self, actions: &[smith::lifecycle::LifecycleAction]) {
        use smith::lifecycle::LifecycleAction as A;
        for action in actions {
            match action {
                A::IncludeUsage(value) => {
                    if let Some(provider) = &mut self.provider {
                        provider.set_include_usage(*value);
                        self.runtime_republish = true;
                    }
                }
                A::SetToolPolicy(changes) => {
                    for (name, state) in changes {
                        if let Some((_, prior)) = self
                            .tool_policy
                            .states
                            .iter_mut()
                            .find(|(known, _)| known == name)
                        {
                            *prior = *state;
                        } else {
                            self.tool_policy.states.push((name.clone(), *state));
                        }
                    }
                }
                _ => {}
            }
        }
    }

    fn invoke(
        &mut self,
        name: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        if self.tool_policy.state(name) == ToolPolicyState::Disabled {
            return Err(SmithError::Tool {
                code: smith::error::ToolCode::ToolDisabled,
                message: format!(
                    "tool '{name}' is disabled by host policy; enable its qualified identity before retrying"
                ),
            });
        }
        if let Some(coding_tools) = &mut self.coding_tools
            && coding_tools.owns(name)?
        {
            return coding_tools.invoke(name, input, effects);
        }
        let input_json = serde_json::to_string(input)
            .map_err(|error| plugin_fault(format!("tool input serialization failed: {error}")))?;
        if !self.composition_grants.has_delegations() {
            return self
                .plugins
                .invoke_for_role(name, &input_json, effects, true);
        }
        self.plugins.invoke_composed(
            name,
            &input_json,
            effects,
            &self.composition_grants,
            &self.tool_policy,
        )
    }
}

impl RuntimeToolsDispatcher {
    fn publish_candidate(&mut self) -> Result<()> {
        match self.try_publish_candidate() {
            Ok(()) => {
                self.published = true;
                Ok(())
            }
            Err(_retained_error) if self.published => Ok(()),
            Err(error) => Err(error),
        }
    }

    fn try_publish_candidate(&mut self) -> Result<()> {
        if self.provider.is_none() && self.packages.list()?.is_empty() {
            return self.plugins.publish_all(Vec::new());
        }
        if self.engine.is_none() {
            self.engine = Some(PluginEngine::new()?);
        }
        let engine = self
            .engine
            .as_ref()
            .ok_or_else(|| plugin_fault("plugin engine initialization failed"))?;
        let mut generations = self.packages.load(engine, &self.auth_store)?;
        if self
            .provider
            .as_ref()
            .is_some_and(crate::protocol::ProviderRoundOwner::subscription)
        {
            generations.push(crate::oauth::source::embedded_generation(engine)?);
        }
        let mut candidate = PluginRegistry::new();
        candidate.publish_all(generations)?;
        // Parse schemas before publication, not on the first subsequent request.
        candidate.snapshot_for_role(true)?;
        if let Some(provider) = &self.provider {
            provider.publish(&mut candidate, engine)?;
        }
        self.plugins = candidate;
        Ok(())
    }

    /// Apply explicit host-owned model-call policy to qualified plugin tools.
    #[must_use]
    pub fn with_tool_policy(mut self, tool_policy: ToolPolicy) -> Self {
        self.tool_authority = tool_policy.clone();
        self.tool_policy = tool_policy;
        self
    }

    /// Set explicit host-owned caller/target filesystem delegations.
    #[must_use]
    pub fn with_composition_grants(mut self, grants: CompositionGrants) -> Self {
        self.composition_grants = grants;
        self
    }

    /// Use an explicitly rooted package registry instead of the XDG default.
    #[must_use]
    pub fn with_package_registry(mut self, packages: PackageRegistry) -> Self {
        self.packages = packages;
        self
    }

    /// Bind ordinary provider dispatch to this dispatcher's round publication.
    ///
    /// No request can execute until the first complete candidate publishes.
    pub fn with_protocol(
        mut self,
        connection: crate::protocol::ProtocolConnectionConfig,
    ) -> (Self, smith::provider::StreamFn) {
        let (stream, provider) = crate::protocol::provider_round_channel(connection, None);
        self.provider = Some(provider);
        (self, stream)
    }

    /// Bind qualified registered provider/model/source selection to the same
    /// candidate as runtime tools.
    pub fn with_registered_protocol(
        mut self,
        connection: crate::protocol::ProtocolConnectionConfig,
        provider: String,
        model: String,
        credential_source: String,
    ) -> (Self, smith::provider::StreamFn) {
        let (stream, owner) = crate::protocol::provider_round_channel(
            connection,
            Some([provider, model, credential_source]),
        );
        self.provider = Some(owner);
        (self, stream)
    }
}

fn extend_tool_snapshot(
    snapshot: &mut ToolDispatcherSnapshot,
    mut other: ToolDispatcherSnapshot,
) -> Result<()> {
    let component_offset = u16::try_from(snapshot.provenance.components.len())
        .map_err(|_| plugin_fault("tool provenance has too many components"))?;
    for tool in &mut other.provenance.tools {
        tool.component_index = tool
            .component_index
            .checked_add(component_offset)
            .ok_or_else(|| plugin_fault("tool provenance component index overflow"))?;
    }
    snapshot.tools.append(&mut other.tools);
    snapshot.policy.append(&mut other.policy);
    snapshot
        .registered_tools
        .append(&mut other.registered_tools);
    snapshot
        .provenance
        .components
        .append(&mut other.provenance.components);
    snapshot
        .provenance
        .tools
        .append(&mut other.provenance.tools);
    Ok(())
}

fn tool_snapshot(
    tools: Vec<ToolMetadata>,
    component: ToolComponentProvenance,
) -> ToolDispatcherSnapshot {
    let provenance_tools = tools
        .iter()
        .cloned()
        .map(|definition| ToolLoadoutTool {
            definition,
            component_index: 0,
        })
        .collect();
    ToolDispatcherSnapshot {
        policy: tools
            .iter()
            .map(|tool| (tool.name.clone(), ToolPolicyState::Advertised))
            .collect(),
        registered_tools: tools.clone(),
        tools,
        provenance: ToolLoadoutProvenance {
            components: vec![component],
            tools: provenance_tools,
        },
    }
}

impl PluginRegistry {
    /// Create an empty registry.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            generations: Vec::new(),
        }
    }

    /// Atomically replace active plugins with one loaded candidate.
    pub fn publish(&mut self, generation: PluginGeneration) -> Option<PluginGeneration> {
        let mut prior = std::mem::replace(&mut self.generations, vec![generation]);
        if prior.len() == 1 { prior.pop() } else { None }
    }

    /// Atomically replace the active complete generation.
    ///
    /// # Errors
    ///
    /// Returns before publication when candidate contributions duplicate an
    /// identity or request capabilities inconsistent with their bindings.
    pub fn publish_all(&mut self, mut generations: Vec<PluginGeneration>) -> Result<()> {
        if generations.len() > 64
            || generations
                .iter()
                .map(|generation| generation.lifecycle_handlers.len())
                .sum::<usize>()
                > 128
        {
            return Err(plugin_fault(
                "component or lifecycle subscription count exceeds registry bounds",
            ));
        }
        validate_generation_tools(&generations)?;
        validate_generation_registrations(&generations)?;
        for generation in &mut generations {
            if generation
                .registrations
                .credential_sources
                .iter()
                .any(|source| source.id.ends_with("@1"))
            {
                generation.credential_module_functions()?;
            }
        }
        generations.sort_by(|left, right| left.manifest.id().cmp(right.manifest.id()));
        self.generations = generations;
        Ok(())
    }

    pub(crate) fn protocol_generation(
        &self,
        binding: Option<ProtocolBinding>,
    ) -> Result<Option<&PluginGeneration>> {
        let mut selected = None;
        for generation in &self.generations {
            let matches = binding.map_or_else(
                || generation.require_responses_binding().is_ok(),
                |binding| generation.require_protocol_binding(binding).is_ok(),
            );
            if matches {
                if selected.is_some() {
                    return Err(plugin_fault("ambiguous trusted protocol bindings"));
                }
                selected = Some(generation);
            }
        }
        Ok(selected)
    }

    pub(crate) fn resolve_registered_provider(
        &self,
        provider: &str,
        model: &str,
        credential_source: &str,
    ) -> Result<(
        &PluginGeneration,
        smith::provider::ProviderRegistrationBinding,
    )> {
        let mut candidates = Vec::new();
        for generation in &self.generations {
            for contribution in &generation.registrations.providers {
                let qualified = qualified_tool_name(generation.manifest.id(), &contribution.id);
                if provider == qualified || provider == contribution.id {
                    candidates.push((qualified, generation, contribution));
                }
            }
        }
        candidates.sort_unstable_by(|left, right| left.0.cmp(&right.0));
        if candidates.len() != 1 {
            let names: Vec<_> = candidates
                .iter()
                .map(|candidate| candidate.0.as_str())
                .collect();
            return Err(plugin_fault(format!(
                "registered provider {provider} missing or ambiguous; candidates={names:?}"
            )));
        }
        let (qualified_provider, generation, contribution) = &candidates[0];
        generation.require_protocol_binding(contribution.protocol)?;
        if !generation
            .manifest
            .capabilities()
            .contains(&Capability::NetScope)
            || !generation
                .manifest
                .capabilities()
                .contains(&Capability::SecretProxy)
        {
            return Err(plugin_fault(
                "registered provider requires net-scope and secret-proxy grants",
            ));
        }
        let qualified_source =
            qualified_tool_name(generation.manifest.id(), &contribution.credential_source_id);
        if credential_source != qualified_source {
            return Err(plugin_fault(
                "registered provider credential source does not match host binding",
            ));
        }
        let selected_model = generation
            .registrations
            .models
            .iter()
            .find(|candidate| {
                candidate.provider_id == contribution.id
                    && (model == candidate.id
                        || model == qualified_tool_name(generation.manifest.id(), &candidate.id))
            })
            .ok_or_else(|| {
                plugin_fault("registered model does not belong to selected provider contribution")
            })?;
        Ok((
            generation,
            smith::provider::ProviderRegistrationBinding {
                provider_id: qualified_provider.clone(),
                model_id: qualified_tool_name(generation.manifest.id(), &selected_model.id),
                credential_source_id: qualified_source,
            },
        ))
    }

    /// Bind one major-versioned credential module to its consumer, never a tool alias.
    /// # Errors
    /// Missing or ambiguous candidates name the consumer and sorted candidate manifests.
    pub fn bind_credential_source(
        &mut self,
        consumer: &str,
        source: &str,
    ) -> Result<&mut PluginGeneration> {
        self.bind_credential_source_with_override(consumer, source, None)
    }

    /// Bind one credential module selected explicitly by its trusted package identity.
    ///
    /// # Errors
    ///
    /// Rejects an override that does not implement `source`, and missing or
    /// ambiguous automatic bindings with sorted candidates and their consumer.
    pub fn bind_credential_source_with_override(
        &mut self,
        consumer: &str,
        source: &str,
        implementation: Option<&str>,
    ) -> Result<&mut PluginGeneration> {
        let index = credential_binding_index(&self.generations, consumer, source, implementation)?;
        Ok(&mut self.generations[index])
    }

    /// Remove one selected credential generation while a caller pins it.
    ///
    /// The caller must return it through [`Self::return_credential_generation`]
    /// before another call can select that implementation.
    pub(crate) fn take_credential_source_with_override(
        &mut self,
        consumer: &str,
        source: &str,
        implementation: Option<&str>,
    ) -> Result<PluginGeneration> {
        let index = credential_binding_index(&self.generations, consumer, source, implementation)?;
        Ok(self.generations.remove(index))
    }

    /// Return a previously selected credential generation to this published set.
    pub(crate) fn return_credential_generation(&mut self, generation: PluginGeneration) {
        self.generations.push(generation);
    }

    /// Whether this registry has a published generation.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.generations.is_empty()
    }

    /// Snapshot namespaced tool definitions from the complete generation.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when a declared schema is invalid JSON.
    pub fn tools(&self) -> Result<Vec<ToolMetadata>> {
        self.snapshot().map(|snapshot| snapshot.tools)
    }

    /// Exact definitions and component identities pinned by this generation.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when a declared schema is invalid JSON.
    pub fn snapshot(&self) -> Result<ToolDispatcherSnapshot> {
        self.snapshot_for_role(false)
    }

    fn snapshot_for_role(&self, inference: bool) -> Result<ToolDispatcherSnapshot> {
        let mut snapshot = ToolDispatcherSnapshot::default();
        for generation in &self.generations {
            if inference && generation.credential_module_only() {
                continue;
            }
            let tools = generation
                .tools()
                .iter()
                .map(|tool| {
                    ToolSchema::from_json(&tool.input_schema_json)
                        .map(|schema| {
                            ToolMetadata::new(
                                qualified_tool_name(generation.manifest().id(), &tool.name),
                                tool.description.clone(),
                            )
                            .with_schema(schema)
                        })
                        .map_err(|error| {
                            plugin_fault(format!(
                                "registration failed: tool {} has invalid input schema: {error}",
                                tool.name
                            ))
                        })
                })
                .collect::<Result<Vec<_>>>()?;
            extend_tool_snapshot(
                &mut snapshot,
                tool_snapshot(
                    tools,
                    ToolComponentProvenance {
                        source_id: generation.manifest().id().to_string(),
                        manifest_sha256: generation.manifest_sha256().to_string(),
                        component_sha256: generation.component_sha256().to_string(),
                    },
                ),
            )?;
        }
        Ok(snapshot)
    }

    /// Invoke a namespaced tool through the active generation and caller effects.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when no active generation owns `name` or the
    /// guest call fails.
    pub fn invoke_with_effects(
        &mut self,
        name: &str,
        input_json: &str,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        self.invoke_for_role(name, input_json, effects, false)
    }

    fn invoke_for_role(
        &mut self,
        name: &str,
        input_json: &str,
        effects: &mut ToolEffectContext<'_>,
        inference: bool,
    ) -> Result<String> {
        for generation in &mut self.generations {
            if inference && generation.credential_module_only() {
                continue;
            }
            let prefix = format!("{}/", generation.manifest().id());
            if let Some(tool_name) = name.strip_prefix(&prefix) {
                return generation.invoke_with_effects(tool_name, input_json, effects);
            }
        }
        let mut matching_generation = None;
        for (index, generation) in self.generations.iter().enumerate() {
            if (!inference || !generation.credential_module_only())
                && generation.tools().iter().any(|tool| tool.name == name)
                && matching_generation.replace(index).is_some()
            {
                return Err(plugin_fault(format!(
                    "invocation failed: tool alias {name} is ambiguous"
                )));
            }
        }
        let Some(index) = matching_generation else {
            return Err(plugin_fault(format!(
                "invocation failed: tool {name} is not registered"
            )));
        };
        self.generations[index].invoke_with_effects(name, input_json, effects)
    }
}

fn coding_tool_metadata() -> Result<Vec<ToolMetadata>> {
    let metadata: Vec<CodingToolMetadata> = serde_json::from_str(CODING_TOOLS_METADATA)
        .map_err(|error| plugin_fault(format!("coding tool metadata is invalid: {error}")))?;
    let declarations: Vec<ToolDeclaration> = metadata
        .iter()
        .map(|tool| ToolDeclaration {
            name: tool.name.clone(),
            description: tool.description.clone(),
            input_schema_json: tool.input_schema_json.clone(),
        })
        .collect();
    validate_tool_declarations(&declarations)?;
    declarations
        .into_iter()
        .map(|tool| {
            ToolSchema::from_json(&tool.input_schema_json)
                .map(|schema| ToolMetadata::new(tool.name, tool.description).with_schema(schema))
                .map_err(|error| plugin_fault(format!("coding tool metadata is invalid: {error}")))
        })
        .collect()
}

fn validate_coding_tool_declarations(
    declared: &[ToolDeclaration],
    metadata: &[ToolMetadata],
) -> Result<()> {
    if declared.len() != metadata.len()
        || declared.iter().zip(metadata).any(|(declared, metadata)| {
            declared.name != metadata.name || declared.description != metadata.description
        })
    {
        return Err(plugin_fault(
            "coding tool component declarations do not match its hash-pinned metadata",
        ));
    }
    Ok(())
}

fn qualified_tool_name(plugin_id: &str, tool_name: &str) -> String {
    format!("{plugin_id}/{tool_name}")
}

fn validate_generation_tools(generations: &[PluginGeneration]) -> Result<()> {
    let mut names = std::collections::BTreeSet::new();
    for generation in ordered_generations(generations) {
        for tool in generation.tools() {
            let name = qualified_tool_name(generation.manifest().id(), &tool.name);
            if !names.insert(name.clone()) {
                return Err(plugin_fault(format!(
                    "registration failed: duplicate tool declaration {name}"
                )));
            }
        }
    }
    Ok(())
}

fn validate_generation_registrations(generations: &[PluginGeneration]) -> Result<()> {
    let mut sources = std::collections::BTreeMap::new();
    let mut providers = std::collections::BTreeMap::new();
    let mut models = std::collections::BTreeMap::new();
    for generation in ordered_generations(generations) {
        let manifest = generation.manifest();
        let registrations = generation.registrations();
        if generation.responses_credential_source.is_some() {
            generation.require_responses_binding()?;
        }
        if !registrations.credential_sources.is_empty()
            && !manifest.capabilities().contains(&Capability::SecretProxy)
        {
            return Err(plugin_fault(format!(
                "registration failed: {} contributes credential sources without secret-proxy capability",
                manifest.id()
            )));
        }
        if !registrations.providers.is_empty()
            && (!manifest.capabilities().contains(&Capability::NetScope)
                || !manifest.capabilities().contains(&Capability::SecretProxy))
        {
            return Err(plugin_fault(format!(
                "registration failed: {} contributes providers without net-scope and secret-proxy capabilities",
                manifest.id()
            )));
        }
        for source in &registrations.credential_sources {
            if !source.id.ends_with("@1") {
                duplicate_contribution(
                    &mut sources,
                    &source.id,
                    manifest.id(),
                    "credential source",
                )?;
            }
        }
        for provider in &registrations.providers {
            duplicate_contribution(&mut providers, &provider.id, manifest.id(), "provider")?;
        }
        for model in &registrations.models {
            duplicate_contribution(&mut models, &model.id, manifest.id(), "model")?;
        }
    }
    Ok(())
}

fn credential_binding_index(
    generations: &[PluginGeneration],
    consumer: &str,
    source: &str,
    implementation: Option<&str>,
) -> Result<usize> {
    let mut candidates: Vec<_> = generations
        .iter()
        .enumerate()
        .filter(|(_, generation)| {
            generation
                .registrations()
                .credential_sources
                .iter()
                .any(|candidate| {
                    candidate.id == source
                        || qualified_tool_name(generation.manifest().id(), &candidate.id) == source
                })
        })
        .map(|(index, generation)| (generation.manifest().id(), index))
        .collect();
    candidates.sort_unstable();
    if let Some(implementation) = implementation {
        if let Some((_, index)) = candidates
            .iter()
            .find(|(candidate, _)| *candidate == implementation)
        {
            return Ok(*index);
        }
        let names: Vec<_> = candidates.iter().map(|(name, _)| *name).collect();
        return Err(plugin_fault(format!(
            "credential consumer {consumer} override {implementation} requires {source}; candidates={names:?}"
        )));
    }
    if candidates.len() != 1 {
        let names: Vec<_> = candidates.iter().map(|(name, _)| *name).collect();
        return Err(plugin_fault(format!(
            "credential consumer {consumer} requires {source}; candidates={names:?}"
        )));
    }
    Ok(candidates[0].1)
}

fn ordered_generations(generations: &[PluginGeneration]) -> Vec<&PluginGeneration> {
    let mut ordered: Vec<_> = generations.iter().collect();
    ordered.sort_by(|left, right| left.manifest().id().cmp(right.manifest().id()));
    ordered
}

fn duplicate_contribution(
    owners: &mut std::collections::BTreeMap<String, String>,
    id: &str,
    owner: &str,
    kind: &str,
) -> Result<()> {
    let qualified = qualified_tool_name(owner, id);
    if let Some(prior) = owners.insert(qualified.clone(), owner.to_string()) {
        return Err(plugin_fault(format!(
            "registration failed: duplicate {kind} {qualified} from {prior} and {owner}"
        )));
    }
    Ok(())
}

impl PluginInstance {
    /// Validate, instantiate, and pin one plugin with default ceilings.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault naming the failed lifecycle stage.
    pub fn load(engine: &PluginEngine, artifact: &Path) -> Result<Self> {
        Self::load_with_ceilings(engine, artifact, PluginCeilings::default())
    }

    /// Validate, instantiate, and pin one plugin with explicit ceilings.
    ///
    /// Every guest entry point receives `ceilings.fuel`; no call inherits a
    /// prior call's remaining budget.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault naming the failed lifecycle stage.
    pub fn load_with_ceilings(
        engine: &PluginEngine,
        artifact: &Path,
        ceilings: PluginCeilings,
    ) -> Result<Self> {
        let component = engine.validate(artifact)?;
        Self::instantiate(engine, &component, ceilings)
    }

    /// Validate and instantiate one component embedded in the release.
    ///
    /// # Errors
    ///
    /// Returns a lifecycle failure without bypassing component validation.
    pub fn load_bytes(engine: &PluginEngine, artifact: &[u8]) -> Result<Self> {
        let component = engine.validate_bytes(artifact)?;
        Self::instantiate(engine, &component, PluginCeilings::default())
    }

    fn configure_capabilities(&mut self, capabilities: &[Capability]) {
        self.store.data_mut().grants = capabilities.iter().fold(0, |grants, capability| {
            grants
                | match capability {
                    Capability::Workspace => WORKSPACE_GRANT,
                    Capability::Process => PROCESS_GRANT,
                    Capability::NetScope => NET_SCOPE_GRANT,
                    Capability::SecretProxy => SECRET_PROXY_GRANT,
                    Capability::Log => LOG_GRANT,
                }
        });
    }

    fn configure_coding_capabilities(&mut self) {
        self.configure_capabilities(&[Capability::Workspace, Capability::Process]);
    }

    fn configure_plugin_id(&mut self, plugin_id: &str) {
        self.store.data_mut().plugin_id = plugin_id.to_string();
    }

    fn enable_effects(&mut self) {
        self.store.data_mut().effects_enabled = true;
    }

    fn configure_net_scopes(&mut self, scopes: Vec<NetScope>) {
        self.store.data_mut().net_scopes = scopes;
    }

    fn configure_secret_grants(&mut self, grants: Vec<SecretGrant>) {
        let state = self.store.data_mut();
        state.secret_grants = grants;
        state.secret_values.clear();
        state.resolved_secret_refs.clear();
    }

    fn instantiate(
        engine: &PluginEngine,
        component: &Component,
        ceilings: PluginCeilings,
    ) -> Result<Self> {
        let mut store = Store::new(
            engine.engine(),
            PluginHostState {
                composition: None,
                memory_bytes: 0,
                table_elements: 0,
                sealed_handles: 0,
                monotonic_now: 0,
                ceilings,
                grants: 0,
                effects_enabled: false,
                lifecycle_deadline: None,
                lifecycle_allocation_bytes: 0,
                plugin_id: String::new(),
                net_scopes: Vec::new(),
                secret_grants: Vec::new(),
                oauth_authority: None,
                workspace_effects: WorkspaceEffects::default(),
                fatal_recording_failure: Cell::new(false),
                log_bytes: 0,
                log_entries: Vec::new(),
                secret_values: Vec::new(),
                resolved_secret_refs: Vec::new(),
                mock_effects: None,
            },
        );
        store.limiter(PluginHostState::limits);
        store.set_epoch_deadline(u64::MAX / 2);
        refill_fuel(&mut store)?;
        let mut linker: Linker<PluginHostState> = Linker::new(engine.engine());
        PluginHost::add_to_linker::<PluginHostState, PluginHasSelf>(&mut linker, |state| state)
            .map_err(|e| plugin_fault(format!("linker setup failed: {e}")))?;
        sealed_wasi::link(&mut linker).map_err(|error| plugin_fault(error.to_string()))?;
        composition::link(&mut linker)
            .map_err(|error| plugin_fault(format!("composition linker: {error}")))?;
        let raw = linker
            .instantiate(&mut store, component)
            .map_err(|e| plugin_fault(format!("instantiation failed: {e}")))?;
        let bindings = PluginHost::new(&mut store, &raw)
            .map_err(|e| plugin_fault(format!("binding failed: {e}")))?;
        Ok(Self {
            component: component.clone(),
            store,
            bindings,
            raw,
        })
    }

    fn declare_responses_binding(&mut self) -> Result<Option<String>> {
        let Some(interface) = self.raw.get_export_index(
            &mut self.store,
            None,
            "smith:plugin/protocol-openai-responses-v1@0.1.0",
        ) else {
            return Ok(None);
        };
        let export = self
            .raw
            .get_export_index(&mut self.store, Some(&interface), "credential-source")
            .ok_or_else(|| {
                plugin_fault("Responses protocol binding missing credential-source declaration")
            })?;
        let declaration = self
            .raw
            .get_typed_func::<(), (String,)>(&mut self.store, export)
            .map_err(|_| plugin_fault("Responses protocol binding has invalid declaration type"))?;
        refill_fuel(&mut self.store)?;
        let (source,) = declaration
            .call(&mut self.store, ())
            .map_err(|_| plugin_fault("Responses protocol binding declaration failed"))?;
        if source.is_empty() || source.len() > 256 {
            return Err(plugin_fault(
                "Responses credential-source binding exceeds identity bounds",
            ));
        }
        Ok(Some(source))
    }

    /// The declared tool set; runs the declaration pass.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault on trap, fuel exhaustion, or conversion
    /// failure.
    pub fn declare_tools(&mut self) -> Result<Vec<ToolDeclaration>> {
        refill_fuel(&mut self.store)?;
        let interface = self
            .bindings
            .smith_plugin_plugin()
            .call_declare_tools(&mut self.store)
            .map_err(|e| plugin_fault(format!("declaration failed: {e}")))?;
        Ok(interface)
    }

    fn declare_registrations(&mut self) -> Result<Registrations> {
        refill_fuel(&mut self.store)?;
        self.bindings
            .smith_plugin_registration()
            .call_declare(&mut self.store)
            .map_err(|error| plugin_fault(format!("registration declaration failed: {error}")))
    }

    /// Invoke one declared tool by name.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault on trap, fuel exhaustion, or a guest error;
    /// guest errors carry the plugin's own message.
    pub fn invoke_with_effects(
        &mut self,
        name: &str,
        input_json: &str,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        if effects.cancel_handle().is_cancelled() {
            return Err(SmithError::Cancelled);
        }
        refill_fuel(&mut self.store)?;
        if self.store.data().fatal_recording_failure.get() {
            return Err(plugin_fault(
                "plugin session has a fatal HTTP recording failure",
            ));
        }
        self.reset_log_budget();
        let _scope = attach_workspace_effects(&self.store, effects)?;
        let outcome = self
            .bindings
            .smith_plugin_plugin()
            .call_invoke(&mut self.store, name, input_json)
            .map_err(|error| {
                let reason = if matches!(
                    error.downcast_ref::<wasmtime::Trap>(),
                    Some(wasmtime::Trap::OutOfFuel)
                ) {
                    smith_core::tools::InvocationStop::Fuel
                } else {
                    smith_core::tools::InvocationStop::Sandbox
                };
                effects.stop(reason);
                plugin_fault(format!("invoke failed: {error}"))
            });
        if self.store.data().fatal_recording_failure.get() {
            return Err(plugin_fault(
                "plugin invocation has a fatal HTTP recording failure",
            ));
        }
        outcome?
            .map(|text| redact_secret_message(&text, &self.store.data().secret_values))
            .map_err(|message| {
                plugin_fault(format!(
                    "plugin error: {}",
                    redact_secret_message(&message, &self.store.data().secret_values)
                ))
            })
    }

    /// Invoke one declared tool with fixture-owned mocked capability responses.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the invocation fails, an effect differs from
    /// the fixture plan, or the guest leaves planned effects unused.
    pub fn invoke_with_mock_effects(
        &mut self,
        name: &str,
        input_json: &str,
        plans: Vec<MockEffectPlan>,
    ) -> Result<MockInvocation> {
        refill_fuel(&mut self.store)?;
        if self.store.data().mock_effects.is_some() {
            return Err(plugin_fault("mock effect context is already attached"));
        }
        self.reset_log_budget();
        self.store.data_mut().mock_effects = Some(MockEffects {
            plans,
            trace: Vec::new(),
        });
        let outcome = self
            .bindings
            .smith_plugin_plugin()
            .call_invoke(&mut self.store, name, input_json)
            .map_err(|error| plugin_fault(format!("invoke failed: {error}")));
        let mock = self
            .store
            .data_mut()
            .mock_effects
            .take()
            .ok_or_else(|| plugin_fault("mock effect context was lost"))?;
        let output =
            outcome?.map_err(|message| plugin_fault(format!("plugin error: {message}")))?;
        if mock.trace.len() != mock.plans.len() {
            return Err(plugin_fault(format!(
                "fixture effect plan has {} unconsumed effect(s)",
                mock.plans.len() - mock.trace.len()
            )));
        }
        Ok(MockInvocation {
            output,
            effects: mock.trace,
        })
    }

    fn reset_log_budget(&mut self) {
        let state = self.store.data_mut();
        state.log_bytes = 0;
        state.log_entries.clear();
        state.secret_values.clear();
        state.resolved_secret_refs.clear();
    }

    fn declare_provider_settings(&mut self) -> Result<ProviderSettings> {
        refill_fuel(&mut self.store)?;
        self.bindings
            .smith_plugin_provider()
            .call_declare_settings(&mut self.store)
            .map_err(|error| plugin_fault(format!("provider settings declaration failed: {error}")))
    }

    fn validate_provider_settings(
        &mut self,
        settings: ProviderSettings,
    ) -> Result<ProviderSettings> {
        refill_fuel(&mut self.store)?;
        let outcome = self
            .bindings
            .smith_plugin_provider()
            .call_validate_settings(&mut self.store, settings)
            .map_err(|error| {
                plugin_fault(format!("provider settings validation failed: {error}"))
            })?;
        outcome.map_err(|message| plugin_fault(format!("plugin error: {message}")))
    }

    fn build_provider_request(
        &mut self,
        model: &str,
        request: &ProviderRequest,
        settings: ProviderSettings,
        catalog: &CatalogSnapshot,
    ) -> Result<RequestTemplate> {
        refill_fuel(&mut self.store)?;
        let outcome = self
            .bindings
            .smith_plugin_provider()
            .call_build_request(&mut self.store, model, request, settings, catalog)
            .map_err(|error| plugin_fault(format!("provider request failed: {error}")))?;
        outcome.map_err(|message| plugin_fault(format!("plugin error: {message}")))
    }

    fn decode_provider_chunk(
        &mut self,
        state: &[u8],
        chunk: &[u8],
        finished: bool,
    ) -> Result<DecodeStep> {
        refill_fuel(&mut self.store)?;
        let outcome = self
            .bindings
            .smith_plugin_provider()
            .call_decode_response(&mut self.store, state, chunk, finished)
            .map_err(|error| plugin_fault(format!("provider decode failed: {error}")))?;
        outcome.map_err(|message| plugin_fault(format!("plugin error: {message}")))
    }
}

fn validate_manifest_grants(manifest: &PluginManifest, grants: &[Capability]) -> Result<()> {
    if manifest.world_version() != SUPPORTED_WORLD_VERSION {
        return Err(plugin_fault(format!(
            "unsupported world version {}; supported version is {SUPPORTED_WORLD_VERSION}; rebuild the plugin against the supported world",
            manifest.world_version()
        )));
    }
    for capability in manifest.capabilities() {
        if !grants.contains(capability) {
            return Err(plugin_fault(format!(
                "instantiation failed: missing grant {}",
                capability.name()
            )));
        }
    }
    Ok(())
}

const fn same_protocol_binding(left: ProtocolBinding, right: ProtocolBinding) -> bool {
    matches!(
        (left, right),
        (
            ProtocolBinding::OpenaiCompatible,
            ProtocolBinding::OpenaiCompatible
        ) | (
            ProtocolBinding::AnthropicMessages,
            ProtocolBinding::AnthropicMessages
        ) | (ProtocolBinding::GoogleGemini, ProtocolBinding::GoogleGemini)
    )
}

fn validate_registrations(registrations: &Registrations) -> Result<()> {
    for (index, source) in registrations.credential_sources.iter().enumerate() {
        if source.id.is_empty()
            || registrations.credential_sources[..index]
                .iter()
                .any(|prior| prior.id == source.id)
        {
            return Err(plugin_fault(
                "registration has an empty or duplicate credential source",
            ));
        }
    }
    for (index, provider) in registrations.providers.iter().enumerate() {
        if provider.id.is_empty()
            || provider.credential_source_id.is_empty()
            || !registrations
                .credential_sources
                .iter()
                .any(|source| source.id == provider.credential_source_id)
            || registrations.providers[..index]
                .iter()
                .any(|prior| prior.id == provider.id)
        {
            return Err(plugin_fault(
                "registration has an invalid provider contribution",
            ));
        }
    }
    for (index, model) in registrations.models.iter().enumerate() {
        if model.id.is_empty()
            || !registrations
                .providers
                .iter()
                .any(|provider| provider.id == model.provider_id)
            || registrations.models[..index]
                .iter()
                .any(|prior| prior.id == model.id)
        {
            return Err(plugin_fault(
                "registration has an invalid model contribution",
            ));
        }
    }
    Ok(())
}

fn validate_tool_declarations(tools: &[ToolDeclaration]) -> Result<()> {
    for (index, tool) in tools.iter().enumerate() {
        if tool.name.is_empty() || tool.description.is_empty() {
            return Err(plugin_fault(
                "registration failed: tool name and description must not be empty",
            ));
        }
        ToolSchema::from_json(&tool.input_schema_json).map_err(|error| {
            plugin_fault(format!(
                "registration failed: tool {} has invalid input schema: {error}",
                tool.name
            ))
        })?;
        if tools[..index].iter().any(|prior| prior.name == tool.name) {
            return Err(plugin_fault(format!(
                "registration failed: duplicate tool declaration {}",
                tool.name
            )));
        }
    }
    Ok(())
}

fn read_artifact(artifact: &Path, expected_bytes: u64) -> Result<Vec<u8>> {
    let capacity = usize::try_from(expected_bytes)
        .map_err(|_| plugin_fault("validation failed: artifact exceeds addressable memory"))?;
    let mut bytes = Vec::new();
    bytes
        .try_reserve_exact(capacity)
        .map_err(|_| plugin_fault("validation failed: artifact allocation failed"))?;
    let file = std::fs::File::open(artifact)
        .map_err(|error| plugin_fault(format!("validation failed: {error}")))?;
    #[expect(
        clippy::disallowed_methods,
        reason = "Take caps this read at ARTIFACT_BYTES_MAX + 1 before overflow is reported"
    )]
    file.take((ARTIFACT_BYTES_MAX + 1) as u64)
        .read_to_end(&mut bytes)
        .map_err(|error| plugin_fault(format!("validation failed: {error}")))?;
    if bytes.len() > ARTIFACT_BYTES_MAX {
        return Err(plugin_fault(format!(
            "validation failed: artifact exceeds {ARTIFACT_BYTES_MAX} bytes"
        )));
    }
    Ok(bytes)
}

fn validate_declared_limits(bytes: &[u8]) -> Result<ArtifactCompatibility> {
    let mut compatibility = ArtifactCompatibility::default();
    for payload in wasmparser::Parser::new(0).parse_all(bytes) {
        match payload.map_err(|error| plugin_fault(format!("validation failed: {error}")))? {
            wasmparser::Payload::ImportSection(imports) => {
                for import in imports.into_imports() {
                    match import
                        .map_err(|error| plugin_fault(format!("validation failed: {error}")))?
                        .ty
                    {
                        wasmparser::TypeRef::Memory(memory) => validate_memory(&memory)?,
                        wasmparser::TypeRef::Table(table) => validate_table(&table)?,
                        _ => {}
                    }
                }
            }
            wasmparser::Payload::MemorySection(memories) => {
                for memory in memories {
                    let memory = memory
                        .map_err(|error| plugin_fault(format!("validation failed: {error}")))?;
                    validate_memory(&memory)?;
                }
            }
            wasmparser::Payload::TableSection(tables) => {
                for table in tables {
                    let table = table
                        .map_err(|error| plugin_fault(format!("validation failed: {error}")))?;
                    validate_table(&table.ty)?;
                }
            }
            wasmparser::Payload::ComponentCanonicalSection(functions) => {
                for function in functions {
                    if matches!(
                        function
                            .map_err(|error| plugin_fault(format!("validation failed: {error}")))?,
                        wasmparser::CanonicalFunction::ResourceNew { .. }
                    ) {
                        compatibility.component_private_resources = true;
                    }
                }
            }
            wasmparser::Payload::ComponentExportSection(exports) => {
                for export in exports {
                    let export = export
                        .map_err(|error| plugin_fault(format!("validation failed: {error}")))?;
                    validate_component_export(export.name.name)?;
                }
            }
            _ => {}
        }
    }
    Ok(compatibility)
}

fn validate_component_export(name: &str) -> Result<()> {
    if name.starts_with("smith:") && !name.starts_with("smith:plugin/") {
        return Err(plugin_fault(format!(
            "validation failed: external artifact exports reserved Smith contract {name}; use a non-smith: contract"
        )));
    }
    Ok(())
}

fn validate_memory(memory: &wasmparser::MemoryType) -> Result<()> {
    let Some(maximum) = memory.maximum else {
        return Err(plugin_fault("validation failed: memory maximum is missing"));
    };
    if maximum != memory.initial {
        return Err(plugin_fault(
            "validation failed: memory maximum differs from minimum",
        ));
    }
    Ok(())
}

fn validate_table(table: &wasmparser::TableType) -> Result<()> {
    let Some(maximum) = table.maximum else {
        return Err(plugin_fault("validation failed: table maximum is missing"));
    };
    if maximum != table.initial {
        return Err(plugin_fault(
            "validation failed: table maximum differs from minimum",
        ));
    }
    Ok(())
}

fn refill_fuel(store: &mut Store<PluginHostState>) -> Result<()> {
    let fuel = store.data().ceilings.fuel;
    store
        .set_fuel(fuel)
        .map_err(|error| plugin_fault(format!("fuel setup failed: {error}")))
}

fn bound_codec_text(name: &str, text: &str, limit: usize) -> Result<()> {
    bound_codec_bytes(name, text.as_bytes(), limit)
}

fn bound_codec_bytes(name: &str, bytes: &[u8], limit: usize) -> Result<()> {
    if bytes.len() > limit {
        return Err(codec_limit(name, bytes.len(), limit));
    }
    Ok(())
}

fn codec_limit(name: &str, actual: usize, limit: usize) -> SmithError {
    plugin_fault(format!("{name} exceeds {limit} bytes or items: {actual}"))
}

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

/// Self-referential data marker for linker setup.
struct PluginHasSelf;

impl wasmtime::component::HasData for PluginHasSelf {
    type Data<'a> = &'a mut PluginHostState;
}

fn effects_enabled(state: &PluginHostState) -> std::result::Result<(), String> {
    if state.effects_enabled {
        Ok(())
    } else {
        Err("host effects are unavailable during plugin registration".to_string())
    }
}

impl bindings::smith::plugin::composition::Host for PluginHostState {
    fn invoke(&mut self, _: String, _: String) -> std::result::Result<String, String> {
        Err("composition is not attached".into())
    }
}

impl LogHost for PluginHostState {
    fn write(&mut self, level: String, message: String) -> std::result::Result<(), String> {
        effects_enabled(self)?;
        if self.lifecycle_deadline.is_some() {
            return Err("lifecycle log effects unavailable".into());
        }
        if !self.granted(LOG_GRANT) {
            return Err("log capability is not granted".to_string());
        }
        if level.is_empty() || message.is_empty() {
            return Err("log level and message must not be empty".to_string());
        }
        let bytes = level
            .len()
            .checked_add(message.len())
            .ok_or_else(|| "log message byte count overflowed".to_string())?;
        if self.log_entries.len() >= LOG_ENTRIES_MAX
            || self
                .log_bytes
                .checked_add(bytes)
                .is_none_or(|total| total > LOG_BYTES_MAX)
        {
            return Err("log invocation exceeds its explicit host bounds".to_string());
        }
        let level = redact_secret_message(&level, &self.secret_values);
        let message = redact_secret_message(&redact_log_message(&message), &self.secret_values);
        if self.mock_effects.is_some() {
            mock_effect(
                self,
                "log-write",
                &serde_json::json!({"level": level, "message": message}),
            )?;
        } else {
            let plugin_id = self.plugin_id.clone();
            workspace_effect_context(self)?
                .record_plugin_log(&smith::http::PluginLogRecord {
                    plugin_id,
                    level: level.clone(),
                    message: message.clone(),
                })
                .map_err(|error| error.to_string())?;
        }
        self.log_bytes += bytes;
        self.log_entries.push(format!("{level}:{message}"));
        Ok(())
    }
}

fn redact_log_message(message: &str) -> String {
    let mut redact_next = false;
    message
        .split_whitespace()
        .map(|part| {
            if std::mem::take(&mut redact_next) {
                return "<redacted>";
            }
            let lower = part.to_ascii_lowercase();
            let header = lower.starts_with("authorization:")
                || lower.starts_with("x-api-key:")
                || lower.starts_with("x-goog-api-key:");
            if header {
                redact_next = part.ends_with(':');
                "<redacted>"
            } else {
                part
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn redact_secret_message(message: &str, secrets: &[String]) -> String {
    secrets
        .iter()
        .fold(message.to_string(), |redacted, secret| {
            if secret.is_empty() {
                return redacted;
            }
            // Nested evidence contains JSON strings, including object keys.
            // Replace escaped spelling too, not only raw credential bytes.
            let Ok(quoted) = serde_json::to_string(secret) else {
                return "<redacted>".into();
            };
            redacted
                .replace(&quoted[1..quoted.len() - 1], "<redacted>")
                .replace(secret, "<redacted>")
        })
}

impl NetScopeHost for PluginHostState {
    fn request(
        &mut self,
        request: self::bindings::smith::plugin::net_scope::HttpRequest,
    ) -> std::result::Result<self::bindings::smith::plugin::net_scope::HttpResponse, String> {
        effects_enabled(self)?;
        if !self.granted(NET_SCOPE_GRANT) {
            return Err("net-scope capability is not granted".to_string());
        }
        if self.mock_effects.is_some() {
            let response = mock_effect(
                self,
                "http-request",
                &serde_json::json!({
                    "destination": request.destination,
                    "method": request.method,
                    "headers": request.headers.into_iter().map(|header| serde_json::json!({"name": header.name, "value": header.value})).collect::<Vec<_>>(),
                    "body": request.body,
                    "options": {"timeout_ms": request.options.timeout_ms, "response_bytes_max": request.options.response_bytes_max},
                }),
            )?;
            return mock_http_response(&response);
        }
        net_scope_request(self, request)
    }
}

const fn authorization_fault(
    fault: &crate::oauth::AuthorizationFault,
) -> self::bindings::smith::plugin::secret_proxy::AuthorizationFault {
    use self::bindings::smith::plugin::secret_proxy::AuthorizationFault;
    use crate::oauth::AuthorizationFault as HostFault;
    match fault {
        HostFault::Cancelled => AuthorizationFault::Cancelled,
        HostFault::Deadline => AuthorizationFault::DeadlineExceeded,
        HostFault::ExchangeUncertain => AuthorizationFault::ExchangeUncertain,
        HostFault::Network => AuthorizationFault::Network,
        HostFault::Storage(_) => AuthorizationFault::Storage,
        HostFault::Authority => AuthorizationFault::Authority,
        HostFault::Rejected(_) | HostFault::ReauthenticationRequired => {
            AuthorizationFault::Rejected
        }
    }
}

fn oauth_policy(
    policy: self::bindings::smith::plugin::secret_proxy::LoginPolicy,
) -> crate::oauth::LoginPolicy {
    crate::oauth::LoginPolicy {
        flow: match policy.flow {
            self::bindings::smith::plugin::secret_proxy::LoginFlow::DynamicOidc => {
                crate::oauth::LoginFlow::DynamicOidc
            }
            self::bindings::smith::plugin::secret_proxy::LoginFlow::GoogleInstalledPkce => {
                crate::oauth::LoginFlow::GoogleInstalledPkce
            }
            self::bindings::smith::plugin::secret_proxy::LoginFlow::FixedClientPkceOpaque => {
                crate::oauth::LoginFlow::FixedClientPkceOpaque
            }
        },
        connection_id: policy.connection_id,
        token_origin: policy.token_origin,
        issuer: policy.issuer,
        resource: policy.audience,
        initial_client: policy.initial_client,
        issued_prefix: policy.issued_prefix,
        authorization_path: policy.authorization_path,
        token_path: policy.token_path,
        agent_name: policy.agent_name,
        scopes: policy.scopes,
        required_scopes: policy.required_scopes,
    }
}

impl SecretProxyHost for PluginHostState {
    fn end_session(
        &mut self,
        profile: self::bindings::smith::plugin::secret_proxy::ProfileRef,
    ) -> std::result::Result<bool, self::bindings::smith::plugin::secret_proxy::AuthorizationFault>
    {
        use self::bindings::smith::plugin::secret_proxy::AuthorizationFault;
        if !self.effects_enabled
            || self.lifecycle_deadline.is_some()
            || !self.granted(SECRET_PROXY_GRANT)
        {
            return Err(AuthorizationFault::Capability);
        }
        let authority = self
            .oauth_authority
            .as_deref()
            .ok_or(AuthorizationFault::Authority)?;
        let mut effects = attached_effect_context(&mut self.workspace_effects)
            .map_err(|_| AuthorizationFault::Authority)?;
        if !effects.requires_atomic_completion() {
            return Err(AuthorizationFault::Authority);
        }
        effects
            .begin_nested_redacted("oauth-end-session", "{\"credentials\":\"host-only\"}")
            .map_err(|_| AuthorizationFault::Storage)?;
        let result = authority.end_session(&profile.id, &effects.cancel_handle());
        let (ok, mutation, evidence) = match result {
            Ok(true) => (
                true,
                smith::error::MutationState::Applied,
                "remote revocation confirmed; local tokens cleared",
            ),
            Ok(false) => (
                true,
                smith::error::MutationState::Applied,
                "remote revocation unconfirmed; local tokens cleared",
            ),
            Err(fault) => (false, smith::error::MutationState::Unknown, fault.message()),
        };
        if effects
            .finish_nested_redacted(ok, mutation, evidence)
            .is_err()
        {
            self.fatal_recording_failure.set(true);
            return Err(AuthorizationFault::Storage);
        }
        result.map_err(|fault| authorization_fault(&fault))
    }

    fn renew(
        &mut self,
        profile: self::bindings::smith::plugin::secret_proxy::ProfileRef,
        policy: self::bindings::smith::plugin::secret_proxy::LoginPolicy,
    ) -> std::result::Result<
        self::bindings::smith::plugin::secret_proxy::SecretRef,
        self::bindings::smith::plugin::secret_proxy::AuthorizationFault,
    > {
        use self::bindings::smith::plugin::secret_proxy::AuthorizationFault;
        if !self.effects_enabled
            || self.lifecycle_deadline.is_some()
            || !self.granted(SECRET_PROXY_GRANT)
        {
            return Err(AuthorizationFault::Capability);
        }
        let authority = self
            .oauth_authority
            .as_deref_mut()
            .ok_or(AuthorizationFault::Authority)?;
        authority
            .renew_for_dispatch(&profile.id, &oauth_policy(policy))
            .map_err(|fault| authorization_fault(&fault))?;
        Ok(self::bindings::smith::plugin::secret_proxy::SecretRef { id: profile.id })
    }

    fn authorize(
        &mut self,
        policy: self::bindings::smith::plugin::secret_proxy::LoginPolicy,
    ) -> std::result::Result<
        self::bindings::smith::plugin::secret_proxy::ProfileRef,
        self::bindings::smith::plugin::secret_proxy::AuthorizationFault,
    > {
        effects_enabled(self).map_err(|_| {
            self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Capability
        })?;
        if self.lifecycle_deadline.is_some() || !self.granted(SECRET_PROXY_GRANT) {
            return Err(
                self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Capability,
            );
        }
        let authority = self
            .oauth_authority
            .as_deref()
            .ok_or(self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Authority)?;
        let policy = oauth_policy(policy);
        let mut effects = attached_effect_context(&mut self.workspace_effects).map_err(|_| {
            self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Authority
        })?;
        if !effects.requires_atomic_completion() {
            return Err(self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Authority);
        }
        effects
            .begin_nested_redacted("oauth-authorize", "{\"credentials\":\"host-only\"}")
            .map_err(|_| {
                self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Storage
            })?;
        let result = authority.authorize(&policy, &effects.cancel_handle());
        let (ok, evidence) = match &result {
            Ok(profile) => (true, profile.id.as_str()),
            Err(fault) => (false, fault.message()),
        };
        if effects
            .finish_nested_redacted(ok, smith::error::MutationState::Unknown, evidence)
            .is_err()
        {
            self.fatal_recording_failure.set(true);
            return Err(self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Storage);
        }
        result
            .map(
                |profile| self::bindings::smith::plugin::secret_proxy::ProfileRef {
                    id: profile.id,
                },
            )
            .map_err(|fault| authorization_fault(&fault))
    }

    fn exchange(
        &mut self,
        request: self::bindings::smith::plugin::secret_proxy::CredentialExchange,
    ) -> std::result::Result<self::bindings::smith::plugin::secret_proxy::SecretRef, String> {
        effects_enabled(self)?;
        if self.lifecycle_deadline.is_some() || !self.granted(SECRET_PROXY_GRANT) {
            return Err("secret-proxy capability is not granted".to_string());
        }
        let source = request.source.id;
        let scopes = canonical_secret_scopes(request.scopes);
        if self.mock_effects.is_some() {
            let response = mock_effect(
                self,
                "credential-exchange",
                &serde_json::json!({
                    "source": {"id": source},
                    "audience": request.audience,
                    "scopes": scopes,
                }),
            )?;
            if response.is_empty() {
                return Err("fixture secret reference is empty".to_string());
            }
            return Ok(self::bindings::smith::plugin::secret_proxy::SecretRef { id: response });
        }
        let evidence = serde_json::to_string(&serde_json::json!({
            "source": format!("secret-ref:{source}"),
            "audience": request.audience,
            "scopes": scopes,
        }))
        .map_err(|error| error.to_string())?;
        let evidence = redact_secret_message(&evidence, &self.secret_values);
        let mut effects = workspace_effect_context(self)?;
        if !effects.requires_atomic_completion() {
            return Err("secret exchange requires admitted durable work".to_string());
        }
        effects
            .begin_nested("secret-exchange", &evidence)
            .map_err(|error| error.to_string())?;
        drop(effects);
        let result = authorized_secret_grant_index(self, &source, &request.audience, &scopes)
            .and_then(|grant_index| {
                resolve_exchanged_secret(self, grant_index).map(|()| grant_index)
            });
        match result {
            Ok(grant_index) => {
                let id = opaque_secret_ref(&source, grant_index);
                let binding = redact_secret_message(&id, &self.secret_values);
                workspace_effect_context(self)?
                    .finish_nested(true, smith::error::MutationState::NotApplied, &binding)
                    .map_err(|error| error.to_string())?;
                Ok(self::bindings::smith::plugin::secret_proxy::SecretRef { id })
            }
            Err(error) => {
                workspace_effect_context(self)?
                    .finish_nested(false, smith::error::MutationState::NotApplied, &error)
                    .map_err(|finish| finish.to_string())?;
                Err(error)
            }
        }
    }
}

fn canonical_secret_scopes(mut scopes: Vec<String>) -> Vec<String> {
    scopes.sort();
    scopes.dedup();
    scopes
}

fn opaque_secret_ref(source_id: &str, grant_index: usize) -> String {
    format!("secret-ref:{source_id}:{grant_index}")
}

fn authorized_secret_grant_index(
    state: &PluginHostState,
    source_id: &str,
    audience: &str,
    scopes: &[String],
) -> std::result::Result<usize, String> {
    state
        .secret_grants
        .iter()
        .position(|grant| {
            grant.source_id == source_id
                && grant.origin.as_str() == audience
                && grant.scopes == scopes
        })
        .ok_or_else(|| {
            "secret exchange exceeds the explicitly granted source, origin, or scopes".to_string()
        })
}

const NET_SCOPE_BYTES_MAX: usize = 1024 * 1024;
const NET_SCOPE_TIMEOUT_MS_MAX: u64 = 30_000;
const LIFECYCLE_HTTP_BODY_BYTES_MAX: usize = 256;
const LIFECYCLE_HTTP_HEADER_BYTES_MAX: usize = 512;
const LIFECYCLE_HTTP_HEADER_ITEMS_MAX: usize = 8;
const LIFECYCLE_HTTP_ORIGIN_BYTES_MAX: usize = 256;
const LIFECYCLE_HTTP_REDACTED_BODY_BYTES_MAX: usize = 7 * 1024;
const _: () = assert!(
    LIFECYCLE_HTTP_REDACTED_BODY_BYTES_MAX * 2 + 1024 <= smith_core::metadata::lifecycle::BYTES_MAX,
    "hex response plus fixed outcome fields must fit full inline lifecycle evidence"
);
// Worst case: one-byte secrets become ten redacted bytes, then hex doubles them.
// The 32 MiB logical payload ceiling covers the advertised 1 MiB plus metadata;
// physical frames remain bounded, with large evidence in same-ledger chunks.
const _: () = assert!(
    NET_SCOPE_BYTES_MAX * 20 + 4096 <= smith_core::metadata::NESTED_PAYLOAD_BYTES_MAX,
    "logical payload bound must cover full redacted 1 MiB HTTP bodies plus metadata"
);

fn redact_secret_body_hex(bytes: &[u8], secrets: &[String]) -> std::result::Result<String, String> {
    let mut sanitizer = crate::response_sanitizer::ResponseSanitizer::new(secrets, b"<redacted>")
        .map_err(str::to_string)?;
    let mut filtered = sanitizer.push(bytes).map_err(str::to_string)?;
    filtered.extend_from_slice(&sanitizer.finish());
    Ok(body_hex(&filtered))
}

fn body_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(char::from(HEX[usize::from(byte >> 4)]));
        output.push(char::from(HEX[usize::from(byte & 15)]));
    }
    output
}

fn redact_secret_headers(
    headers: &[smith::http::HttpHeader],
    secrets: &[String],
) -> Vec<smith::http::HttpHeader> {
    smith::http::redact_headers(headers)
        .into_iter()
        .map(|header| smith::http::HttpHeader {
            name: redact_secret_message(&header.name, secrets),
            value: redact_secret_message(&header.value, secrets),
        })
        .collect()
}

fn lifecycle_http_checkpoint(
    effects: &mut ToolEffectContext<'_>,
    deadline: Option<std::time::Instant>,
    allocation_bytes: u64,
) -> std::result::Result<(), String> {
    if !effects.is_lifecycle() {
        return Ok(());
    }
    let reason = if effects.cancel_handle().is_cancelled() {
        Some(smith_core::tools::InvocationStop::Cancelled)
    } else if deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) {
        Some(smith_core::tools::InvocationStop::Deadline)
    } else {
        let observed = smith_alloc::AllocationGroup::current()
            .ok_or_else(|| "lifecycle allocation group unavailable".to_string())?
            .allocated()
            .map_err(|_| "lifecycle allocation observation failed".to_string())?;
        (observed.bytes > allocation_bytes)
            .then_some(smith_core::tools::InvocationStop::HostAllocation)
    };
    if let Some(reason) = reason {
        effects.stop(reason);
        return Err("shared lifecycle HTTP boundary budget stopped".into());
    }
    Ok(())
}

#[expect(
    clippy::too_many_lines,
    reason = "each HTTP terminal branch synchronously records durable outcome evidence before guest return"
)]
fn net_scope_request(
    state: &mut PluginHostState,
    request: self::bindings::smith::plugin::net_scope::HttpRequest,
) -> std::result::Result<self::bindings::smith::plugin::net_scope::HttpResponse, String> {
    if !state
        .net_scopes
        .iter()
        .any(|scope| scope.as_str() == request.destination)
    {
        return Err("net-scope destination is outside the explicitly granted origins".to_string());
    }
    if request.method != "POST"
        || request.options.timeout_ms == 0
        || request.options.timeout_ms > NET_SCOPE_TIMEOUT_MS_MAX
        || request.options.response_bytes_max == 0
        || request.options.response_bytes_max > NET_SCOPE_BYTES_MAX as u64
        || request.body.len() > NET_SCOPE_BYTES_MAX
    {
        return Err("net-scope request exceeds its explicit host bounds".to_string());
    }
    let response_bytes_max = usize::try_from(request.options.response_bytes_max)
        .map_err(|_| "net-scope response byte bound exceeds addressable memory".to_string())?;
    let plugin_id = state.plugin_id.clone();
    let mut headers: Vec<smith::http::HttpHeader> = request
        .headers
        .into_iter()
        .map(|header| smith::http::HttpHeader {
            name: header.name,
            value: header.value,
        })
        .collect();
    resolve_secret_headers(state, &request.destination, &mut headers)?;
    let fatal_recording_failure = &state.fatal_recording_failure;
    let mut sanitizer =
        crate::response_sanitizer::ResponseSanitizer::new(&state.secret_values, b"<redacted>")
            .map_err(str::to_string)?;
    let exchange = smith::http::HttpExchange {
        method: smith::http::HttpMethod::Post,
        url: request.destination.clone(),
        headers,
        body: request.body,
    };
    let secrets = &state.secret_values;
    let lifecycle_deadline = state.lifecycle_deadline;
    let lifecycle_allocation_bytes = state.lifecycle_allocation_bytes;
    let mut effects = attached_effect_context(&mut state.workspace_effects)?;
    lifecycle_http_checkpoint(&mut effects, lifecycle_deadline, lifecycle_allocation_bytes)?;
    let lifecycle = effects.is_lifecycle();
    if lifecycle
        && (request.options.response_bytes_max > LIFECYCLE_HTTP_BODY_BYTES_MAX as u64
            || exchange.body.len() > LIFECYCLE_HTTP_BODY_BYTES_MAX
            || exchange.url.len() > LIFECYCLE_HTTP_ORIGIN_BYTES_MAX
            || exchange.headers.len() > LIFECYCLE_HTTP_HEADER_ITEMS_MAX
            || exchange
                .headers
                .iter()
                .map(|header| header.name.len() + header.value.len())
                .sum::<usize>()
                > LIFECYCLE_HTTP_HEADER_BYTES_MAX)
    {
        return Err("lifecycle HTTP exceeds full inline evidence bounds".into());
    }
    let durable = effects.requires_atomic_completion() || lifecycle;
    if durable {
        let mut headers = redact_secret_headers(&exchange.headers, secrets);
        let mut origin = redact_secret_message(&exchange.url, secrets);
        let request_body = if lifecycle {
            for header in &mut headers {
                header.name = String::from_utf8(
                    effects
                        .redact_lifecycle_bytes(header.name.as_bytes())
                        .map_err(|error| error.to_string())?,
                )
                .map_err(|_| "redacted header name is not UTF-8")?;
                header.value = String::from_utf8(
                    effects
                        .redact_lifecycle_bytes(header.value.as_bytes())
                        .map_err(|error| error.to_string())?,
                )
                .map_err(|_| "redacted header value is not UTF-8")?;
            }
            origin = String::from_utf8(
                effects
                    .redact_lifecycle_bytes(origin.as_bytes())
                    .map_err(|error| error.to_string())?,
            )
            .map_err(|_| "redacted origin is not UTF-8")?;
            Some(
                effects
                    .redact_lifecycle_bytes(&exchange.body)
                    .map_err(|error| error.to_string())?,
            )
        } else {
            None
        };
        let evidence = serde_json::json!({
            "origin": origin, "method": "POST",
            "headers": headers,
            "body_hex": redact_secret_body_hex(request_body.as_deref().unwrap_or(&exchange.body), secrets)?,
            "timeout_ms": request.options.timeout_ms,
            "response_bytes_max": request.options.response_bytes_max,
        })
        .to_string();
        effects
            .begin_nested_redacted("http", &evidence)
            .map_err(|error| error.to_string())?;
    } else {
        let call_id = effects
            .call_id()
            .ok_or_else(|| "net-scope requires model tool identity".to_string())?;
        effects
            .record_plugin_http(&smith::http::PluginHttpEffectRecord::Intent {
                plugin_id,
                call_id,
                origin: redact_secret_message(&request.destination, secrets),
                method: exchange.method,
                headers: redact_secret_headers(&exchange.headers, secrets).into(),
                request_bytes: exchange.body.len(),
                timeout_ms: request.options.timeout_ms,
                response_bytes_max: request.options.response_bytes_max,
            })
            .map_err(|error| error.to_string())?;
    }
    if let Err(error) =
        lifecycle_http_checkpoint(&mut effects, lifecycle_deadline, lifecycle_allocation_bytes)
    {
        effects
            .finish_nested_redacted(
                false,
                smith::error::MutationState::NotApplied,
                "{\"failure\":\"boundary-stopped-before-transport\"}",
            )
            .map_err(|error| error.to_string())?;
        return Err(error);
    }
    let response_bytes = Cell::new(0_usize);
    let record_outcome =
        |effects: &mut ToolEffectContext<'_>, status, body: &[u8], outcome, error: &str| {
            let result = if durable {
                let redacted_body = if lifecycle {
                    Some(effects.redact_lifecycle_bytes(body))
                } else {
                    None
                };
                if redacted_body.as_ref().is_some_and(|body| {
                    body.as_ref().map_or(true, |body| {
                        body.len() > LIFECYCLE_HTTP_REDACTED_BODY_BYTES_MAX
                    })
                }) {
                    effects
                        .finish_nested_redacted(
                            false,
                            if outcome == smith::http::PluginHttpEffectOutcome::Completed {
                                smith::error::MutationState::Applied
                            } else {
                                smith::error::MutationState::Unknown
                            },
                            "{\"failure\":\"inline-response-bound-exceeded\"}",
                        )
                        .map_err(|error| {
                            fatal_recording_failure.set(true);
                            error.to_string()
                        })?;
                    return Err("lifecycle response redaction exceeds inline evidence bound".into());
                }
                let redacted_body = redacted_body
                    .transpose()
                    .map_err(|error| error.to_string())?;
                let output = serde_json::json!({
                "status": status, "body_hex": body_hex(redacted_body.as_deref().unwrap_or(body)),
                "outcome": outcome, "error": redact_secret_message(error, secrets),
            })
            .to_string();
                let ok = outcome == smith::http::PluginHttpEffectOutcome::Completed;
                effects.finish_nested_redacted(
                    ok,
                    if ok {
                        smith::error::MutationState::Applied
                    } else {
                        smith::error::MutationState::Unknown
                    },
                    &output,
                )
            } else {
                effects.record_plugin_http(&smith::http::PluginHttpEffectRecord::Outcome {
                    status,
                    response_bytes: u64::try_from(response_bytes.get()).unwrap_or(u64::MAX),
                    outcome,
                })
            };
            result.map_err(|error| {
                fatal_recording_failure.set(true);
                error.to_string()
            })?;
            lifecycle_http_checkpoint(effects, lifecycle_deadline, lifecycle_allocation_bytes)
        };
    if effects.cancel_handle().is_cancelled() {
        if durable {
            effects
                .finish_nested(
                    false,
                    smith::error::MutationState::NotApplied,
                    "HTTP cancelled before dispatch",
                )
                .map_err(|error| error.to_string())?;
        } else {
            record_outcome(
                &mut effects,
                0,
                &[],
                smith::http::PluginHttpEffectOutcome::Cancelled,
                "net-scope request cancelled",
            )?;
        }
        return Err("net-scope request cancelled".to_string());
    }
    let timeout = std::time::Duration::from_millis(request.options.timeout_ms);
    let timeout = state.lifecycle_deadline.map_or(timeout, |deadline| {
        timeout.min(deadline.saturating_duration_since(std::time::Instant::now()))
    });
    let executor = if lifecycle {
        crate::http::UreqHttpExecutor::lifecycle(
            timeout,
            &effects.cancel_handle(),
            request.options.response_bytes_max,
        )
    } else {
        crate::http::UreqHttpExecutor::with_timeouts(timeout, timeout)
    };
    let Ok(response) = executor.execute(exchange, effects.cancel_handle()) else {
        let outcome = if effects.cancel_handle().is_cancelled() {
            smith::http::PluginHttpEffectOutcome::Cancelled
        } else {
            smith::http::PluginHttpEffectOutcome::Failed
        };
        record_outcome(
            &mut effects,
            0,
            &[],
            outcome,
            "net-scope HTTP dispatch failed",
        )?;
        return Err("net-scope HTTP dispatch failed".to_string());
    };
    let status = response.head.status;
    let mut body = Vec::new();
    for item in response.body {
        match item {
            smith::http::HttpBodyItem::Chunk(chunk) => {
                let Some(length) = response_bytes.get().checked_add(chunk.bytes.len()) else {
                    record_outcome(
                        &mut effects,
                        status,
                        &body,
                        smith::http::PluginHttpEffectOutcome::Failed,
                        "net-scope response byte count overflowed",
                    )?;
                    return Err("net-scope response byte count overflowed".to_string());
                };
                if length > response_bytes_max {
                    record_outcome(
                        &mut effects,
                        status,
                        &body,
                        smith::http::PluginHttpEffectOutcome::Failed,
                        "net-scope response exceeds its explicit byte bound",
                    )?;
                    return Err("net-scope response exceeds its explicit byte bound".to_string());
                }
                response_bytes.set(length);
                match sanitizer.push(&chunk.bytes) {
                    Ok(filtered) => body.extend_from_slice(&filtered),
                    Err(message) => {
                        record_outcome(
                            &mut effects,
                            status,
                            &body,
                            smith::http::PluginHttpEffectOutcome::Failed,
                            message,
                        )?;
                        return Err(message.to_string());
                    }
                }
            }
            smith::http::HttpBodyItem::End(smith::http::HttpBodyEnd::Complete) => {
                if effects.cancel_handle().is_cancelled() {
                    record_outcome(
                        &mut effects,
                        status,
                        &body,
                        smith::http::PluginHttpEffectOutcome::Cancelled,
                        "net-scope request cancelled",
                    )?;
                    return Err("net-scope request cancelled".to_string());
                }
                body.extend_from_slice(&sanitizer.finish());
                record_outcome(
                    &mut effects,
                    status,
                    &body,
                    smith::http::PluginHttpEffectOutcome::Completed,
                    "",
                )?;
                return Ok(self::bindings::smith::plugin::net_scope::HttpResponse {
                    status,
                    headers: Vec::new(),
                    body,
                });
            }
            smith::http::HttpBodyItem::End(smith::http::HttpBodyEnd::Cancelled) => {
                record_outcome(
                    &mut effects,
                    status,
                    &body,
                    smith::http::PluginHttpEffectOutcome::Cancelled,
                    "net-scope request cancelled",
                )?;
                return Err("net-scope request cancelled".to_string());
            }
            smith::http::HttpBodyItem::End(smith::http::HttpBodyEnd::Truncated { .. }) => {
                record_outcome(
                    &mut effects,
                    status,
                    &body,
                    smith::http::PluginHttpEffectOutcome::Failed,
                    "net-scope response exceeds the host byte bound",
                )?;
                return Err("net-scope response exceeds the host byte bound".to_string());
            }
            smith::http::HttpBodyItem::End(smith::http::HttpBodyEnd::Failed { message: _ }) => {
                record_outcome(
                    &mut effects,
                    status,
                    &body,
                    smith::http::PluginHttpEffectOutcome::Failed,
                    "net-scope response failed",
                )?;
                return Err("net-scope response failed".to_string());
            }
        }
    }
    record_outcome(
        &mut effects,
        status,
        &body,
        smith::http::PluginHttpEffectOutcome::Failed,
        "net-scope response ended without a terminal outcome",
    )?;
    Err("net-scope response ended without a terminal outcome".to_string())
}

fn resolve_exchanged_secret(
    state: &mut PluginHostState,
    grant_index: usize,
) -> std::result::Result<(), String> {
    if state
        .resolved_secret_refs
        .iter()
        .any(|reference| reference.grant_index == grant_index)
    {
        return Ok(());
    }
    if state.resolved_secret_refs.len() == RESOLVED_SECRET_REFS_MAX {
        return Err("resolved secret reference bound exceeded".to_string());
    }
    let grant = state
        .secret_grants
        .get(grant_index)
        .ok_or_else(|| "secret exchange grant disappeared before resolution".to_string())?;
    let secret = grant
        .credential
        .resolve(&grant.auth_store)
        .map_err(|error| error.to_string())?;
    let secret_value_index = if let Some(index) = state
        .secret_values
        .iter()
        .position(|value| value == &secret)
    {
        index
    } else {
        state.secret_values.push(secret);
        if let Err(message) =
            crate::response_sanitizer::ResponseSanitizer::validate(&state.secret_values)
        {
            state.secret_values.pop();
            return Err(message.to_string());
        }
        state.secret_values.len() - 1
    };
    let secret_value_index = u8::try_from(secret_value_index)
        .map_err(|_| "resolved secret value index overflowed its bound".to_string())?;
    state.resolved_secret_refs.push(ResolvedSecretRef {
        grant_index,
        secret_value_index,
    });
    Ok(())
}

fn resolve_secret_headers(
    state: &PluginHostState,
    destination: &str,
    headers: &mut [smith::http::HttpHeader],
) -> std::result::Result<(), String> {
    for header in headers {
        let Some(reference) = header
            .value
            .strip_prefix("{{secret:")
            .and_then(|value| value.strip_suffix("}}"))
        else {
            continue;
        };
        let resolved = state
            .resolved_secret_refs
            .iter()
            .find(|resolved| {
                state
                    .secret_grants
                    .get(resolved.grant_index)
                    .is_some_and(|grant| {
                        opaque_secret_ref(&grant.source_id, resolved.grant_index) == reference
                    })
            })
            .ok_or_else(|| "secret reference was not exchanged before HTTP dispatch".to_string())?;
        let grant = state
            .secret_grants
            .get(resolved.grant_index)
            .ok_or_else(|| "secret exchange grant disappeared before HTTP dispatch".to_string())?;
        if grant.origin.as_str() != destination
            || !grant.scopes.iter().any(|scope| scope == "http-request")
        {
            return Err(
                "secret reference is not granted for this HTTP origin and scope".to_string(),
            );
        }
        header.value = state
            .secret_values
            .get(usize::from(resolved.secret_value_index))
            .cloned()
            .ok_or_else(|| "resolved secret value disappeared before HTTP dispatch".to_string())?;
    }
    Ok(())
}

fn mock_http_response(
    response: &str,
) -> std::result::Result<self::bindings::smith::plugin::net_scope::HttpResponse, String> {
    let response: serde_json::Value = serde_json::from_str(response)
        .map_err(|error| format!("fixture HTTP response is invalid: {error}"))?;
    let status = response
        .get("status")
        .and_then(serde_json::Value::as_u64)
        .and_then(|status| u16::try_from(status).ok())
        .ok_or_else(|| "fixture HTTP response has invalid status".to_string())?;
    let headers =
        response
            .get("headers")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| "fixture HTTP response has invalid headers".to_string())?
            .iter()
            .map(
                |header| -> std::result::Result<
                    self::bindings::smith::plugin::net_scope::Header,
                    String,
                > {
                    let name = header
                        .get("name")
                        .and_then(serde_json::Value::as_str)
                        .ok_or_else(|| {
                            "fixture HTTP response header has invalid name".to_string()
                        })?;
                    let value = header
                        .get("value")
                        .and_then(serde_json::Value::as_str)
                        .ok_or_else(|| {
                            "fixture HTTP response header has invalid value".to_string()
                        })?;
                    Ok(self::bindings::smith::plugin::net_scope::Header {
                        name: name.to_string(),
                        value: value.to_string(),
                    })
                },
            )
            .collect::<std::result::Result<Vec<_>, _>>()?;
    let body = response
        .get("body")
        .and_then(serde_json::Value::as_array)
        .ok_or_else(|| "fixture HTTP response has invalid body".to_string())?
        .iter()
        .map(|byte| {
            byte.as_u64()
                .and_then(|byte| u8::try_from(byte).ok())
                .ok_or_else(|| "fixture HTTP response body has invalid byte".to_string())
        })
        .collect::<std::result::Result<Vec<_>, _>>()?;
    Ok(self::bindings::smith::plugin::net_scope::HttpResponse {
        status,
        headers,
        body,
    })
}

impl ToolingHost for PluginHostState {
    fn read(
        &mut self,
        request: self::bindings::smith::plugin::tooling::FileRead,
    ) -> std::result::Result<self::bindings::smith::plugin::tooling::FileContent, String> {
        let text = workspace_effect(
            self,
            "read",
            &serde_json::json!({"path": request.path, "offset": request.offset, "limit": request.limit, "max_bytes": request.max_bytes}),
        )?;
        Ok(self::bindings::smith::plugin::tooling::FileContent { text })
    }

    fn write(
        &mut self,
        request: self::bindings::smith::plugin::tooling::FileWrite,
    ) -> std::result::Result<(), String> {
        workspace_effect(
            self,
            "write",
            &serde_json::json!({"path": request.path, "content": request.content}),
        )
        .map(|_| ())
    }

    fn edit(
        &mut self,
        request: self::bindings::smith::plugin::tooling::FileEdit,
    ) -> std::result::Result<(), String> {
        workspace_effect(self, "edit", &serde_json::json!({"path": request.path, "old_string": request.old_text, "new_string": request.new_text})).map(|_| ())
    }

    fn list_directory(
        &mut self,
        request: self::bindings::smith::plugin::tooling::DirectoryQuery,
    ) -> std::result::Result<Vec<String>, String> {
        directory_effect(self, "ls", request)
    }

    fn find(
        &mut self,
        request: self::bindings::smith::plugin::tooling::DirectoryQuery,
    ) -> std::result::Result<Vec<String>, String> {
        directory_effect(self, "find", request)
    }

    fn grep(
        &mut self,
        request: self::bindings::smith::plugin::tooling::DirectoryQuery,
    ) -> std::result::Result<Vec<String>, String> {
        directory_effect(self, "grep", request)
    }

    fn run_command(
        &mut self,
        request: self::bindings::smith::plugin::tooling::CommandRequest,
    ) -> std::result::Result<String, String> {
        process_effect(
            self,
            "bash",
            &serde_json::json!({"command": request.text, "timeout_ms": request.timeout_ms}),
        )
    }
}

fn directory_effect(
    state: &mut PluginHostState,
    tool: &str,
    request: self::bindings::smith::plugin::tooling::DirectoryQuery,
) -> std::result::Result<Vec<String>, String> {
    let path = request.path;
    let output = match tool {
        "ls" => workspace_effect(state, tool, &serde_json::json!({"path": path}))?,
        "find" => workspace_effect(
            state,
            tool,
            &serde_json::json!({"path": path, "pattern": request.pattern.unwrap_or_default()}),
        )?,
        "grep" => workspace_effect(
            state,
            tool,
            &serde_json::json!({"path": path, "query": request.pattern.unwrap_or_default()}),
        )?,
        _ => return Err("invalid workspace directory operation".to_string()),
    };
    Ok(output.lines().map(str::to_string).collect())
}

fn workspace_effect(
    state: &mut PluginHostState,
    tool: &str,
    input: &serde_json::Value,
) -> std::result::Result<String, String> {
    effects_enabled(state)?;
    if !state.granted(WORKSPACE_GRANT) {
        return Err("workspace capability is not granted".to_string());
    }
    if state.mock_effects.is_some() {
        return mock_effect(state, tool, input);
    }
    let arguments = smith::structured::ToolArguments::from_serializable(&input)
        .map_err(|error| format!("invalid workspace arguments: {error}"))?;
    let secrets = &state.secret_values;
    attached_effect_context(&mut state.workspace_effects)?
        .invoke_redacted(tool, &arguments, |text| {
            redact_secret_message(text, secrets)
        })
        .map_err(|error| error.to_string())
}

fn process_effect(
    state: &mut PluginHostState,
    tool: &str,
    input: &serde_json::Value,
) -> std::result::Result<String, String> {
    effects_enabled(state)?;
    if !state.granted(PROCESS_GRANT) {
        return Err("process capability is not granted".to_string());
    }
    if state.mock_effects.is_some() {
        return mock_effect(state, tool, input);
    }
    let arguments = smith::structured::ToolArguments::from_serializable(&input)
        .map_err(|error| format!("invalid process arguments: {error}"))?;
    let secrets = &state.secret_values;
    attached_effect_context(&mut state.workspace_effects)?
        .invoke_redacted(tool, &arguments, |text| {
            redact_secret_message(text, secrets)
        })
        .map_err(|error| error.to_string())
}

fn mock_effect(
    state: &mut PluginHostState,
    operation: &str,
    request: &serde_json::Value,
) -> std::result::Result<String, String> {
    let request_json = serde_json::to_string(request)
        .map_err(|error| format!("fixture request serialization failed: {error}"))?;
    let effects = state
        .mock_effects
        .as_mut()
        .ok_or_else(|| "mock effect context is not configured".to_string())?;
    let index = effects.trace.len();
    let Some(plan) = effects.plans.get(index) else {
        return Err(format!(
            "unexpected fixture effect {operation} {request_json}"
        ));
    };
    if plan.operation != operation || plan.request_json != request_json {
        return Err(format!(
            "fixture effect {index} differs: expected {} {}, got {operation} {request_json}",
            plan.operation, plan.request_json
        ));
    }
    effects.trace.push(plan.clone());
    Ok(plan.response.clone())
}

/// Owns a stable attachment for exactly one synchronous guest call.
fn attach_workspace_effects(
    store: &Store<PluginHostState>,
    effects: &mut ToolEffectContext<'_>,
) -> Result<attachment::Attachment> {
    store
        .data()
        .workspace_effects
        .attach(std::ptr::from_mut(effects).cast())
}

fn workspace_effect_context(
    state: &mut PluginHostState,
) -> std::result::Result<ScopedEffectContext<'_>, String> {
    attached_effect_context(&mut state.workspace_effects)
}

/// Suspension owns the only accessible context pointer while a host import runs.
/// A child may attach an exclusive reborrow to another store only inside this lease.
struct ScopedEffectContext<'attachment> {
    suspension: attachment::Suspension,
    lifetime: std::marker::PhantomData<&'attachment mut WorkspaceEffects>,
}

#[expect(
    unsafe_code,
    reason = "the suspended import lease bounds the shared context reborrow"
)]
impl<'attachment> std::ops::Deref for ScopedEffectContext<'attachment> {
    type Target = ToolEffectContext<'attachment>;
    fn deref(&self) -> &Self::Target {
        // SAFETY: the root call owns the live context; suspension removes parent access.
        // This reference cannot outlive the import lease, which restores the attachment.
        unsafe { &*self.suspension.effects().cast() }
    }
}

#[expect(
    unsafe_code,
    reason = "the suspended import lease bounds the exclusive context reborrow"
)]
impl std::ops::DerefMut for ScopedEffectContext<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: only this suspended lease can access the context; &mut self serializes
        // reborrows. Any child attachment must drop before its reborrow returns here.
        unsafe { &mut *self.suspension.effects().cast() }
    }
}

fn attached_effect_context(
    attachment: &mut WorkspaceEffects,
) -> std::result::Result<ScopedEffectContext<'_>, String> {
    Ok(ScopedEffectContext {
        suspension: attachment.suspend()?,
        lifetime: std::marker::PhantomData,
    })
}

#[cfg(test)]
mod nested_tests;

#[cfg(test)]
mod tests {
    //! Runtime limiter tests (`SMH-SPEC-WASM0001`).

    use super::*;
    #[test]
    fn nested_http_binary_evidence_preserves_bytes_without_credential_encodings() {
        assert_eq!(redact_secret_body_hex(&[0, 255], &[]).unwrap(), "00ff");
        assert_eq!(
            redact_secret_body_hex(b"\xfftoken\0", &["token".into()]).unwrap(),
            "ff3c72656461637465643e00"
        );
        let largest = vec![0; NET_SCOPE_BYTES_MAX];
        let encoded = redact_secret_body_hex(&largest, &["\0".into()]).unwrap();
        assert!(encoded.len() + 4096 <= smith_core::metadata::NESTED_PAYLOAD_BYTES_MAX);
    }

    #[test]
    fn registered_secrets_are_redacted_inside_json_keys_values_results_and_errors() {
        let secret = "credential\"with\ncontrol\\bytes".to_string();
        let serialized =
            serde_json::to_string(&serde_json::json!({secret.clone(): secret})).unwrap();
        let redacted = redact_secret_message(&serialized, std::slice::from_ref(&secret));
        assert_eq!(redacted, r#"{"<redacted>":"<redacted>"}"#);
        assert_eq!(
            redact_secret_message(&format!("result or error: {secret}"), &[secret]),
            "result or error: <redacted>"
        );
    }

    #[test]
    fn pure_attachment_reborrow_uses_live_context_provenance() {
        let mut session = smith_core::tools::ToolSession::new(std::env::temp_dir());
        let mut effects = ToolEffectContext::for_operation(&mut session, "write");
        let mut attachment = WorkspaceEffects::default();
        let _outer = attachment
            .attach(std::ptr::from_mut(&mut effects).cast())
            .unwrap();
        {
            let mut parent = attached_effect_context(&mut attachment).unwrap();
            assert!(parent.call_id().is_none());
            let mut child_attachment = WorkspaceEffects::default();
            let _child = child_attachment
                .attach(std::ptr::from_mut(&mut *parent).cast())
                .unwrap();
            {
                let mut child = attached_effect_context(&mut child_attachment).unwrap();
                child.stop(smith_core::tools::InvocationStop::Fuel);
                assert!(child.cancel_handle().is_cancelled());
            }
            assert!(parent.cancel_handle().is_cancelled());
        }
        assert!(attachment.get().is_some());

        attachment.set(None);
        assert!(attached_effect_context(&mut attachment).is_err());
    }

    #[test]
    fn scoped_workspace_effect_context_clears_after_unwind_and_rejects_reentry() {
        let engine = PluginEngine::new().unwrap();
        let store = Store::new(
            engine.engine(),
            PluginHostState {
                composition: None,
                memory_bytes: 0,
                table_elements: 0,
                sealed_handles: 0,
                monotonic_now: 0,
                ceilings: PluginCeilings::default(),
                grants: WORKSPACE_GRANT,
                effects_enabled: true,
                lifecycle_deadline: None,
                lifecycle_allocation_bytes: 0,
                plugin_id: String::new(),
                net_scopes: Vec::new(),
                secret_grants: Vec::new(),
                oauth_authority: None,
                workspace_effects: WorkspaceEffects::default(),
                fatal_recording_failure: Cell::new(false),
                log_bytes: 0,
                log_entries: Vec::new(),
                secret_values: Vec::new(),
                resolved_secret_refs: Vec::new(),
                mock_effects: None,
            },
        );
        let mut effect_context = ();
        let address = std::ptr::from_mut(&mut effect_context).cast();
        let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _scope = store.data().workspace_effects.attach(address).unwrap();
            assert!(store.data().workspace_effects.attach(address).is_err());
            panic!("test unwind");
        }));
        assert!(unwind.is_err());
        assert!(store.data().workspace_effects.get().is_none());

        let _scope = store.data().workspace_effects.attach(address).unwrap();
    }

    #[test]
    fn registered_generation_replacement_keeps_advertised_provenance_hash_pinned() {
        let dir = std::env::temp_dir().join(format!(
            "smith-generation-provenance-{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let first = load_coding_tools(&dir).unwrap().generation;
        let expected_manifest = smith::sha256::digest_hex(b"smith:coding-tools");
        let expected_component = smith::sha256::digest_hex(CODING_TOOLS_COMPONENT);
        let mut registry = PluginRegistry::default();
        registry.publish(first);
        let pinned = registry.snapshot().unwrap();
        assert_eq!(pinned.provenance.components.len(), 1);
        assert_eq!(
            pinned.provenance.components[0].source_id,
            "smith:coding-tools"
        );
        assert_eq!(
            pinned.provenance.components[0].manifest_sha256,
            expected_manifest
        );
        assert_eq!(
            pinned.provenance.components[0].component_sha256,
            expected_component
        );

        let replacement = load_coding_tools(&dir).unwrap().generation;
        registry.publish(replacement);
        assert_eq!(pinned, registry.snapshot().unwrap());
        assert_eq!(
            pinned.provenance.components[0].manifest_sha256,
            expected_manifest
        );
        assert_eq!(
            pinned.provenance.components[0].component_sha256,
            expected_component
        );
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn artifact_validation_allows_plugin_world_and_rejects_other_smith_contracts() {
        validate_declared_limits(CODING_TOOLS_COMPONENT).unwrap();
        let mut malicious = CODING_TOOLS_COMPONENT.to_vec();
        let required = b"smith:plugin/plugin@0.1.0";
        let malicious_name = b"smith:attaxx/plugin@0.1.0";
        assert_eq!(required.len(), malicious_name.len());
        let offsets: Vec<usize> = malicious
            .windows(required.len())
            .enumerate()
            .filter_map(|(offset, window)| (window == required).then_some(offset))
            .collect();
        assert!(
            !offsets.is_empty(),
            "coding component exports the required plugin contract"
        );
        for offset in offsets {
            malicious[offset..offset + required.len()].copy_from_slice(malicious_name);
            if let Err(error) = validate_declared_limits(&malicious)
                && error.to_string().contains("reserved Smith contract")
            {
                return;
            }
            malicious[offset..offset + required.len()].copy_from_slice(required);
        }
        panic!("wasmparser did not expose the malicious Smith export");
    }

    #[test]
    fn admitted_guest_workspace_effects_require_an_outer_call_scope() {
        let dir = std::env::temp_dir().join(format!(
            "smith-admitted-nested-grants-{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let mut runtime = load_coding_tools(&dir).unwrap();
        for capability in ["net-scope", "log"] {
            runtime.generation.manifest = PluginManifest::parse(&format!(
                "id \"smith:coding-tools\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"fixture.wasm\"\ncapability \"workspace\"\ncapability \"{capability}\""
            )).unwrap();
            let mut tools = smith_core::tools::ToolSession::new(&dir)
                .with_completion_boundary(smith::id::EntryId::new(), |_| Ok(()));
            let mut effects = ToolEffectContext::for_operation(&mut tools, "write");
            let error = runtime
                .generation
                .invoke_with_effects(
                    "write",
                    r#"{"path":"never.txt","content":"not authorized"}"#,
                    &mut effects,
                )
                .unwrap_err();
            assert!(error.to_string().contains("requires an outer call"));
            assert!(!dir.join("never.txt").exists());
            assert!(tools.session.active_branch().entries().is_empty());
        }
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn filesystem_only_grant_cannot_invoke_process_import() {
        let mut state = PluginHostState {
            composition: None,
            memory_bytes: 0,
            table_elements: 0,
            sealed_handles: 0,
            monotonic_now: 0,
            ceilings: PluginCeilings::default(),
            grants: WORKSPACE_GRANT,
            effects_enabled: true,
            lifecycle_deadline: None,
            lifecycle_allocation_bytes: 0,
            plugin_id: String::new(),
            net_scopes: Vec::new(),
            secret_grants: Vec::new(),
            oauth_authority: None,
            workspace_effects: WorkspaceEffects::default(),
            fatal_recording_failure: Cell::new(false),
            log_bytes: 0,
            log_entries: Vec::new(),
            secret_values: Vec::new(),
            resolved_secret_refs: Vec::new(),
            mock_effects: None,
        };
        let error = process_effect(
            &mut state,
            "bash",
            &serde_json::json!({"command": "true", "timeout_ms": 1}),
        )
        .unwrap_err();
        assert_eq!(error, "process capability is not granted");
    }

    fn secret_grant(source_id: &str, origin: &str, scopes: &[&str], secret: &str) -> SecretGrant {
        SecretGrant {
            source_id: source_id.to_string(),
            origin: NetScope::parse(origin).unwrap(),
            scopes: scopes.iter().map(|scope| (*scope).to_string()).collect(),
            credential: CredentialReference::explicit(secret),
            auth_store: AuthStore::at(std::env::temp_dir()),
        }
    }

    fn secret_proxy_state(secret_grants: Vec<SecretGrant>) -> PluginHostState {
        PluginHostState {
            composition: None,
            memory_bytes: 0,
            table_elements: 0,
            sealed_handles: 0,
            monotonic_now: 0,
            ceilings: PluginCeilings::default(),
            grants: SECRET_PROXY_GRANT,
            effects_enabled: true,
            lifecycle_deadline: None,
            lifecycle_allocation_bytes: 0,
            plugin_id: String::new(),
            net_scopes: Vec::new(),
            secret_grants,
            oauth_authority: None,
            workspace_effects: WorkspaceEffects::default(),
            fatal_recording_failure: Cell::new(false),
            log_bytes: 0,
            log_entries: Vec::new(),
            secret_values: Vec::new(),
            resolved_secret_refs: Vec::new(),
            mock_effects: None,
        }
    }

    #[test]
    fn oauth_authority_requires_capability_registration_phase_and_durable_admission() {
        use crate::oauth::{LoginAuthority, LoginPolicy, ProfileStore};
        let root =
            std::env::temp_dir().join(format!("oauth-unadmitted-{}", smith::id::SessionId::new()));
        let policy = LoginPolicy {
            flow: crate::oauth::LoginFlow::DynamicOidc,
            connection_id: "openai-chatgpt-plan".into(),
            token_origin: "https://issuer.example".into(),
            issuer: "https://issuer.example".into(),
            resource: "https://resource.example/v1".into(),
            initial_client: "dynamic_agent_client".into(),
            issued_prefix: "oaiapp_".into(),
            authorization_path: "/authorize".into(),
            token_path: "/token".into(),
            agent_name: "Fixture".into(),
            scopes: vec!["openid".into()],
            required_scopes: vec!["openid".into()],
        };
        let request = self::bindings::smith::plugin::secret_proxy::LoginPolicy {
            flow: self::bindings::smith::plugin::secret_proxy::LoginFlow::DynamicOidc,
            connection_id: policy.connection_id.clone(),
            token_origin: policy.token_origin.clone(),
            issuer: policy.issuer.clone(),
            audience: policy.resource.clone(),
            initial_client: policy.initial_client.clone(),
            issued_prefix: policy.issued_prefix.clone(),
            authorization_path: policy.authorization_path.clone(),
            token_path: policy.token_path.clone(),
            agent_name: policy.agent_name.clone(),
            scopes: policy.scopes.clone(),
            required_scopes: policy.required_scopes.clone(),
        };
        let mut state = secret_proxy_state(Vec::new());
        state.oauth_authority = Some(Box::new(
            LoginAuthority::new(policy, ProfileStore::at(root.clone())).unwrap(),
        ));
        state.grants = 0;
        assert!(matches!(
            SecretProxyHost::authorize(&mut state, request.clone()).unwrap_err(),
            self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Capability
        ));
        state.grants = SECRET_PROXY_GRANT;
        state.effects_enabled = false;
        assert!(matches!(
            SecretProxyHost::authorize(&mut state, request.clone()).unwrap_err(),
            self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Capability
        ));
        state.effects_enabled = true;
        let mut tools = smith_core::tools::ToolSession::new(std::env::temp_dir());
        let mut effects = ToolEffectContext::for_operation(&mut tools, "login");
        state
            .workspace_effects
            .set(Some(std::ptr::from_mut(&mut effects).cast()));
        assert!(matches!(
            SecretProxyHost::authorize(&mut state, request).unwrap_err(),
            self::bindings::smith::plugin::secret_proxy::AuthorizationFault::Authority
        ));
        state.workspace_effects.set(None);
        assert!(!root.exists());
    }

    #[test]
    fn secret_proxy_exchanges_only_opaque_fixture_references() {
        let mut state = PluginHostState {
            composition: None,
            memory_bytes: 0,
            table_elements: 0,
            sealed_handles: 0,
            monotonic_now: 0,
            ceilings: PluginCeilings::default(),
            grants: SECRET_PROXY_GRANT,
            effects_enabled: true,
            lifecycle_deadline: None,
            lifecycle_allocation_bytes: 0,
            plugin_id: String::new(),
            net_scopes: Vec::new(),
            secret_grants: Vec::new(),
            oauth_authority: None,
            workspace_effects: WorkspaceEffects::default(),
            fatal_recording_failure: Cell::new(false),
            log_bytes: 0,
            log_entries: Vec::new(),
            secret_values: Vec::new(),
            resolved_secret_refs: Vec::new(),
            mock_effects: Some(MockEffects {
                plans: vec![MockEffectPlan {
                    operation: "credential-exchange".to_string(),
                    request_json:
                        r#"{"source":{"id":"stored"},"audience":"loopback","scopes":["read"]}"#
                            .to_string(),
                    response: "derived".to_string(),
                }],
                trace: Vec::new(),
            }),
        };
        let reference = SecretProxyHost::exchange(
            &mut state,
            self::bindings::smith::plugin::secret_proxy::CredentialExchange {
                source: self::bindings::smith::plugin::secret_proxy::SecretRef {
                    id: "stored".to_string(),
                },
                audience: "loopback".to_string(),
                scopes: vec!["read".to_string()],
            },
        )
        .unwrap();
        assert_eq!(reference.id, "derived");
    }

    #[test]
    fn secret_proxy_rejects_exchange_without_durable_intent_before_secret_resolution() {
        let origin = NetScope::parse("https://api.example.test").unwrap();
        let mut state = PluginHostState {
            composition: None,
            memory_bytes: 0,
            table_elements: 0,
            sealed_handles: 0,
            monotonic_now: 0,
            ceilings: PluginCeilings::default(),
            grants: SECRET_PROXY_GRANT,
            effects_enabled: true,
            lifecycle_deadline: None,
            lifecycle_allocation_bytes: 0,
            plugin_id: String::new(),
            net_scopes: Vec::new(),
            secret_grants: vec![
                SecretGrant {
                    source_id: "anthropic".to_string(),
                    origin,
                    scopes: vec!["http-request".to_string()],
                    credential: CredentialReference::explicit("selected-secret"),
                    auth_store: AuthStore::at(std::env::temp_dir()),
                },
                SecretGrant {
                    source_id: "unused-missing".to_string(),
                    origin: NetScope::parse("https://unused.example.test").unwrap(),
                    scopes: vec!["http-request".to_string()],
                    credential: CredentialReference::explicit(String::new()),
                    auth_store: AuthStore::at(std::env::temp_dir()),
                },
            ],
            oauth_authority: None,
            workspace_effects: WorkspaceEffects::default(),
            fatal_recording_failure: Cell::new(false),
            log_bytes: 0,
            log_entries: Vec::new(),
            secret_values: Vec::new(),
            resolved_secret_refs: Vec::new(),
            mock_effects: None,
        };
        let exchange = |state: &mut PluginHostState, source: &str, audience: &str| {
            SecretProxyHost::exchange(
                state,
                self::bindings::smith::plugin::secret_proxy::CredentialExchange {
                    source: self::bindings::smith::plugin::secret_proxy::SecretRef {
                        id: source.to_string(),
                    },
                    audience: audience.to_string(),
                    scopes: vec!["http-request".to_string()],
                },
            )
        };
        assert!(exchange(&mut state, "anthropic", "https://api.example.test").is_err());
        assert!(state.secret_values.is_empty());
        assert!(state.resolved_secret_refs.is_empty());
        assert!(exchange(&mut state, "other", "https://api.example.test").is_err());
        assert!(exchange(&mut state, "anthropic", "https://other.example.test").is_err());
    }

    #[test]
    fn secret_proxy_rejects_nonadmitted_and_failed_durable_intents_before_resolution() {
        let grants = vec![secret_grant(
            "provider",
            "https://api.example.test",
            &["http-request"],
            "selected-secret",
        )];
        let request = self::bindings::smith::plugin::secret_proxy::CredentialExchange {
            source: self::bindings::smith::plugin::secret_proxy::SecretRef {
                id: "provider".to_string(),
            },
            audience: "https://api.example.test".to_string(),
            scopes: vec!["http-request".to_string()],
        };
        let directory = std::env::temp_dir();
        let mut tools = smith_core::tools::ToolSession::new(&directory);
        let mut effects = ToolEffectContext::for_operation(&mut tools, "fixture");
        let mut state = secret_proxy_state(grants.clone());
        state
            .workspace_effects
            .set(Some(std::ptr::from_mut(&mut effects).cast()));
        assert!(SecretProxyHost::exchange(&mut state, request.clone()).is_err());
        state.workspace_effects.set(None);
        assert!(state.secret_values.is_empty());
        assert!(state.resolved_secret_refs.is_empty());

        let mut tools = smith_core::tools::ToolSession::new(&directory)
            .with_completion_boundary(smith::id::EntryId::new(), |_| Ok(()));
        let mut effects = ToolEffectContext::for_operation(&mut tools, "fixture");
        let mut state = secret_proxy_state(grants);
        state
            .workspace_effects
            .set(Some(std::ptr::from_mut(&mut effects).cast()));
        assert!(SecretProxyHost::exchange(&mut state, request).is_err());
        state.workspace_effects.set(None);
        assert!(state.secret_values.is_empty());
        assert!(state.resolved_secret_refs.is_empty());
    }

    #[test]
    fn secret_headers_bind_each_opaque_reference_to_its_authorized_grant() {
        let mut state = secret_proxy_state(vec![
            secret_grant(
                "provider",
                "https://first.example.test",
                &["http-request"],
                "first-secret",
            ),
            secret_grant(
                "provider",
                "https://second.example.test",
                &["http-request"],
                "second-secret",
            ),
            secret_grant(
                "provider",
                "https://first.example.test",
                &["other"],
                "third-secret",
            ),
        ]);
        assert_eq!(
            authorized_secret_grant_index(
                &state,
                "provider",
                "https://first.example.test",
                &["http-request".to_string()],
            )
            .unwrap(),
            0
        );
        assert_eq!(
            authorized_secret_grant_index(
                &state,
                "provider",
                "https://second.example.test",
                &["http-request".to_string()],
            )
            .unwrap(),
            1
        );
        assert_eq!(
            authorized_secret_grant_index(
                &state,
                "provider",
                "https://first.example.test",
                &["other".to_string()],
            )
            .unwrap(),
            2
        );
        resolve_exchanged_secret(&mut state, 0).unwrap();
        let mut headers = [smith::http::HttpHeader {
            name: "authorization".to_string(),
            value: "{{secret:secret-ref:provider:0}}".to_string(),
        }];
        resolve_secret_headers(&state, "https://first.example.test", &mut headers).unwrap();
        assert_eq!(headers[0].value, "first-secret");
        let mut wrong_origin = [smith::http::HttpHeader {
            name: "authorization".to_string(),
            value: "{{secret:secret-ref:provider:0}}".to_string(),
        }];
        assert!(
            resolve_secret_headers(&state, "https://second.example.test", &mut wrong_origin)
                .is_err()
        );
        let mut unexchanged = [smith::http::HttpHeader {
            name: "authorization".to_string(),
            value: "{{secret:secret-ref:provider:1}}".to_string(),
        }];
        assert!(
            resolve_secret_headers(&state, "https://second.example.test", &mut unexchanged)
                .is_err()
        );
    }

    #[test]
    fn resolved_secret_references_cap_aliases_without_copying_credentials() {
        let grants = (0..=RESOLVED_SECRET_REFS_MAX)
            .map(|index| {
                secret_grant(
                    &format!("alias-{index}"),
                    "https://api.example.test",
                    &["http-request"],
                    "shared-secret",
                )
            })
            .collect();
        let mut state = secret_proxy_state(grants);
        for index in 0..RESOLVED_SECRET_REFS_MAX {
            resolve_exchanged_secret(&mut state, index).unwrap();
        }
        assert_eq!(state.resolved_secret_refs.len(), RESOLVED_SECRET_REFS_MAX);
        assert_eq!(state.secret_values, ["shared-secret"]);
        assert!(resolve_exchanged_secret(&mut state, RESOLVED_SECRET_REFS_MAX).is_err());
        assert_eq!(state.resolved_secret_refs.len(), RESOLVED_SECRET_REFS_MAX);
        assert_eq!(state.secret_values, ["shared-secret"]);
    }

    #[test]
    fn log_capability_redacts_header_tokens_and_enforces_invocation_bound() {
        let mut state = PluginHostState {
            composition: None,
            memory_bytes: 0,
            table_elements: 0,
            sealed_handles: 0,
            monotonic_now: 0,
            ceilings: PluginCeilings::default(),
            grants: LOG_GRANT,
            effects_enabled: true,
            lifecycle_deadline: None,
            lifecycle_allocation_bytes: 0,
            plugin_id: String::new(),
            net_scopes: Vec::new(),
            secret_grants: Vec::new(),
            oauth_authority: None,
            workspace_effects: WorkspaceEffects::default(),
            fatal_recording_failure: Cell::new(false),
            log_bytes: 0,
            log_entries: Vec::new(),
            secret_values: Vec::new(),
            resolved_secret_refs: Vec::new(),
            mock_effects: Some(MockEffects {
                plans: vec![MockEffectPlan {
                    operation: "log-write".to_string(),
                    request_json: r#"{"level":"error","message":"<redacted> <redacted>"}"#
                        .to_string(),
                    response: String::new(),
                }],
                trace: Vec::new(),
            }),
        };
        LogHost::write(
            &mut state,
            "error".to_string(),
            "authorization: secret".to_string(),
        )
        .unwrap();
        assert_eq!(state.log_entries, ["error:<redacted> <redacted>"]);
        state.log_bytes = LOG_BYTES_MAX;
        assert!(LogHost::write(&mut state, "error".to_string(), "x".to_string()).is_err());
    }

    #[test]
    fn net_scope_rejects_unscoped_destination_before_io() {
        let mut state = PluginHostState {
            composition: None,
            memory_bytes: 0,
            table_elements: 0,
            sealed_handles: 0,
            monotonic_now: 0,
            ceilings: PluginCeilings::default(),
            grants: NET_SCOPE_GRANT,
            effects_enabled: true,
            lifecycle_deadline: None,
            lifecycle_allocation_bytes: 0,
            plugin_id: String::new(),
            net_scopes: Vec::new(),
            secret_grants: Vec::new(),
            oauth_authority: None,
            workspace_effects: WorkspaceEffects::default(),
            fatal_recording_failure: Cell::new(false),
            log_bytes: 0,
            log_entries: Vec::new(),
            secret_values: Vec::new(),
            resolved_secret_refs: Vec::new(),
            mock_effects: None,
        };
        let error = NetScopeHost::request(
            &mut state,
            self::bindings::smith::plugin::net_scope::HttpRequest {
                destination: "https://example.test".to_string(),
                method: "POST".to_string(),
                headers: Vec::new(),
                body: Vec::new(),
                options: self::bindings::smith::plugin::net_scope::RequestOptions {
                    timeout_ms: 1,
                    response_bytes_max: 1,
                },
            },
        )
        .unwrap_err();
        assert!(error.contains("explicitly granted origins"));
    }

    #[test]
    fn codec_boundary_rejects_text_and_binary_at_named_limits() {
        let text = "x".repeat(CODEC_TEXT_BYTES_MAX + 1);
        assert!(
            bound_codec_text("provider request", &text, CODEC_TEXT_BYTES_MAX)
                .unwrap_err()
                .to_string()
                .contains("provider request exceeds")
        );
        let bytes = vec![0; CODEC_BINARY_BYTES_MAX + 1];
        assert!(
            bound_codec_bytes("provider response chunk", &bytes, CODEC_BINARY_BYTES_MAX)
                .unwrap_err()
                .to_string()
                .contains("provider response chunk exceeds")
        );
    }

    #[test]
    fn limiter_admits_initial_allocation_and_rejects_growth() {
        let mut ceilings = PluginCeilings::default();
        assert!(
            wasmtime::ResourceLimiter::memory_growing(&mut ceilings, 0, 1, None)
                .expect("limiter result")
        );
        assert!(
            !wasmtime::ResourceLimiter::memory_growing(&mut ceilings, 1, 2, None)
                .expect("limiter result")
        );
        assert!(
            wasmtime::ResourceLimiter::table_growing(&mut ceilings, 0, 1, None)
                .expect("limiter result")
        );
        assert!(
            !wasmtime::ResourceLimiter::table_growing(&mut ceilings, 1, 2, None)
                .expect("limiter result")
        );
    }
}

#[cfg(test)]
mod runtime_tests;