Skip to main content

greentic_runner_host/
pack.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::fs::File;
3use std::io::Read;
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6use std::sync::Arc;
7use std::time::Duration;
8
9use crate::cache::{ArtifactKey, CacheConfig, CacheManager, CpuPolicy, EngineProfile};
10use crate::component_api::{
11    self, node::ExecCtx as ComponentExecCtx, node::InvokeResult, node::NodeError,
12};
13use crate::identify_hint::IdentifyInstanceHint;
14use crate::oauth::{OAuthBrokerConfig, ResourceTokenRequest};
15use crate::provider::{ProviderBinding, ProviderRegistry};
16use crate::provider_core::{
17    schema_core::SchemaCorePre as LegacySchemaCorePre,
18    schema_core_path::SchemaCorePre as PathSchemaCorePre,
19    schema_core_schema::SchemaCorePre as SchemaSchemaCorePre,
20};
21use crate::provider_core_only;
22use crate::runtime_refs::RuntimeRefsInjection;
23use crate::runtime_wasmtime::{Component, Engine, Linker, ResourceTable};
24use anyhow::{Context, Result, anyhow, bail};
25use futures::executor::block_on;
26use greentic_distributor_client::dist::{
27    CachePolicy, DistClient, DistError, DistOptions, ResolvePolicy,
28};
29use greentic_interfaces_wasmtime::host_helpers::v1::{
30    self as host_v1, HostFns, add_all_v1_to_linker,
31    oauth_broker::OAuthBrokerHost as OAuthBrokerHostTrait,
32    runner_host_http::RunnerHostHttp,
33    runner_host_kv::RunnerHostKv,
34    runtime_config::{ConfigError, RuntimeConfigHost},
35    secrets_store::{SecretsError, SecretsErrorV1_1, SecretsStoreHost, SecretsStoreHostV1_1},
36    state_store::{
37        OpAck as StateOpAck, OpAckV1_1 as StateOpAckV1_1, StateKey as HostStateKey,
38        StateStoreError as StateError, StateStoreErrorV1_1 as StateErrorV1_1, StateStoreHost,
39        StateStoreHostV1_1, TenantCtx as StateTenantCtx, TenantCtxV1_1 as StateTenantCtxV1_1,
40    },
41    telemetry_logger::{
42        OpAck as TelemetryAck, SpanContext as TelemetrySpanContext,
43        TelemetryLoggerError as TelemetryError, TelemetryLoggerHost,
44        TenantCtx as TelemetryTenantCtx,
45    },
46};
47use greentic_interfaces_wasmtime::http_client_client_v1_1::greentic::http::http_client as http_client_client_alias;
48use greentic_interfaces_wasmtime::instance_identity_instance_identity_describe_v0_1::InstanceIdentityDescribePre;
49use greentic_interfaces_wasmtime::instance_identity_v0_1::InstanceIdentityPre;
50use greentic_interfaces_wasmtime::{
51    http_client_client_v1_0::greentic::interfaces_types::types as http_types_v1_0,
52    http_client_client_v1_1::greentic::interfaces_types::types as http_types_v1_1,
53};
54use greentic_pack::builder as legacy_pack;
55use greentic_types::flow::FlowHasher;
56use greentic_types::{
57    ArtifactLocationV1, ComponentId, ComponentManifest, ComponentSourceRef, ComponentSourcesV1,
58    EXT_COMPONENT_SOURCES_V1, EnvId, ExtensionRef, Flow, FlowComponentRef, FlowId, FlowKind,
59    FlowMetadata, InputMapping, Node, NodeId, OutputMapping, Routing, StateKey as StoreStateKey,
60    TeamId, TelemetryHints, TenantCtx as TypesTenantCtx, TenantId, UserId, decode_pack_manifest,
61    pack_manifest::ExtensionInline,
62};
63use host_v1::http_client as host_http_client;
64use host_v1::http_client::{
65    HttpClientError, HttpClientErrorV1_1, HttpClientHost, HttpClientHostV1_1,
66    Request as HttpRequest, RequestOptionsV1_1 as HttpRequestOptionsV1_1,
67    RequestV1_1 as HttpRequestV1_1, Response as HttpResponse, ResponseV1_1 as HttpResponseV1_1,
68    TenantCtx as HttpTenantCtx, TenantCtxV1_1 as HttpTenantCtxV1_1,
69};
70use indexmap::IndexMap;
71use once_cell::sync::Lazy;
72use parking_lot::{Mutex, RwLock};
73use reqwest::blocking::Client as BlockingClient;
74use runner_core::normalize_under_root;
75use serde::{Deserialize, Serialize};
76use serde_cbor;
77use serde_json::{self, Value};
78use sha2::Digest;
79use tempfile::TempDir;
80use tokio::fs;
81use wasmparser::{Parser, Payload};
82use wasmtime::{Store, StoreContextMut};
83use wasmtime_wasi_http::WasiHttpCtx;
84use wasmtime_wasi_http::p2::{
85    WasiHttpCtxView, WasiHttpView, add_only_http_to_linker_sync as add_wasi_http_to_linker,
86};
87use wasmtime_wasi_tls::p2::{LinkOptions, add_to_linker as add_wasi_tls_to_linker};
88use wasmtime_wasi_tls::{WasiTlsCtx, WasiTlsCtxBuilder, WasiTlsCtxView, WasiTlsView};
89use zip::ZipArchive;
90
91use crate::runner::engine::{FlowContext, FlowEngine, FlowExecution, FlowSnapshot, FlowStatus};
92use crate::runner::flow_adapter::{FlowIR, flow_doc_to_ir, flow_ir_to_flow, is_native_op_key};
93use crate::runner::mocks::{HttpDecision, HttpMockRequest, HttpMockResponse, MockLayer};
94#[cfg(feature = "fault-injection")]
95use crate::testing::fault_injection::{FaultContext, FaultPoint, maybe_fail};
96
97use crate::config::HostConfig;
98use crate::fault;
99use crate::secrets::{
100    DynSecretsManager, PackSecretError, canonicalize_secret_key, read_pack_secret_blocking,
101    write_pack_secret_blocking,
102};
103use crate::storage::state::STATE_PREFIX;
104use crate::storage::{DynSessionStore, DynStateStore};
105use crate::verify;
106use crate::wasi::{PreopenSpec, RunnerWasiPolicy};
107use tracing::warn;
108use wasmtime_wasi::p2::add_to_linker_sync as add_wasi_to_linker;
109use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
110
111use greentic_flow::model::FlowDoc;
112
113#[allow(dead_code)]
114pub struct PackRuntime {
115    /// Component artifact path (wasm file).
116    path: PathBuf,
117    /// Optional archive (.gtpack) used to load flows/manifests.
118    archive_path: Option<PathBuf>,
119    config: Arc<HostConfig>,
120    engine: Engine,
121    metadata: PackMetadata,
122    manifest: Option<greentic_types::PackManifest>,
123    legacy_manifest: Option<Box<legacy_pack::PackManifest>>,
124    component_manifests: HashMap<String, ComponentManifest>,
125    mocks: Option<Arc<MockLayer>>,
126    flows: Option<PackFlows>,
127    components: HashMap<String, PackComponent>,
128    http_client: Arc<BlockingClient>,
129    session_store: Option<DynSessionStore>,
130    state_store: Option<DynStateStore>,
131    wasi_policy: Arc<RunnerWasiPolicy>,
132    /// The policy `load` was HANDED, before `for_tenant` scoped it. A nested
133    /// load (`load_flow_engine`) must start from this: `for_tenant` is not
134    /// idempotent, so re-scoping `wasi_policy` would give `<host>/tenants/<t>/tenants/<t>`.
135    base_wasi_policy: Arc<RunnerWasiPolicy>,
136    assets_tempdir: Option<TempDir>,
137    provider_registry: RwLock<Option<ProviderRegistry>>,
138    /// Per-revision lazy cache of `describe-identify-instance` results,
139    /// keyed by `component_ref`. `None` value means the component does not
140    /// export the describe world (or the hint was malformed) — the
141    /// caller falls back to passing input headers through unchanged. The
142    /// outer `Option` distinguishes "not probed yet" from "probed and
143    /// has no hint". `ArcSwap`-driven revision swaps allocate a fresh
144    /// `PackRuntime` so this cache is naturally invalidated.
145    identify_hint_cache: RwLock<HashMap<String, Option<IdentifyInstanceHint>>>,
146    /// Components whose describe-identify probe failed recently. Failures are
147    /// remembered only for [`IDENTIFY_FAILURE_BACKOFF`] so a transient error
148    /// does not disable hinting for the lifetime of the runtime.
149    identify_hint_failures: RwLock<HashMap<String, std::time::Instant>>,
150    secrets: DynSecretsManager,
151    oauth_config: Option<OAuthBrokerConfig>,
152    cache: CacheManager,
153    /// `pack-config.v1.non_secret` map plumbed into each `HostState` for the
154    /// `greentic:runtime-config@1.0.0` host import. Defaults to `None` when no
155    /// producer (greentic-start) has materialized a `PackConfig` yet; in that
156    /// case all runtime-config lookups fall through to the secrets-store
157    /// compat shim.
158    runtime_config_non_secret: Option<Arc<BTreeMap<String, Value>>>,
159    /// `pack-config.v1.runtime_refs` (C5): per-pack `key → URI` bindings plus
160    /// the env-shared [`RuntimeRefResolver`]. Consulted by the
161    /// `greentic:runtime-config@1.0.0` host import AFTER `non_secret` and
162    /// BEFORE the compat shim. `None` when no producer set it yet.
163    ///
164    /// [`RuntimeRefResolver`]: crate::runtime_refs::RuntimeRefResolver
165    runtime_refs: Option<RuntimeRefsInjection>,
166    /// Lazily-parsed `assets/mcp-routes.json` sidecar — see
167    /// [`PackRuntime::mcp_routes`]. Read on first use rather than at load so a
168    /// pack with no MCP nodes never touches the archive for it.
169    mcp_routes: std::sync::OnceLock<Option<crate::runner::mcp_pack_routes::PackMcpRoutes>>,
170    /// Lazily-parsed `assets/a2a-routes.json` sidecar — see
171    /// [`PackRuntime::a2a_routes`]. Twin of `mcp_routes`, read on first use.
172    a2a_routes: std::sync::OnceLock<Option<crate::runner::a2a_pack_routes::PackA2aRoutes>>,
173    /// Lazily-parsed `assets/run-context.json` sidecar — see
174    /// [`PackRuntime::run_context`]. Twin of `a2a_routes`, read on first use.
175    run_context: std::sync::OnceLock<Option<crate::runner::run_context_routes::PackRunContext>>,
176    /// Lazily-parsed `assets/user-ledger.json` sidecar — see
177    /// [`PackRuntime::user_ledger`].
178    user_ledger: std::sync::OnceLock<Option<crate::runner::user_ledger_routes::PackUserLedger>>,
179    /// Handlers a `flow:` tool's per-call engine borrows from the host that
180    /// wired the top-level engine — see [`crate::runner::nested_flow`].
181    /// Write-once; empty means "nested engines get no handler" (the
182    /// pre-existing behaviour).
183    nested_flow_handlers: std::sync::OnceLock<crate::runner::nested_flow::NestedFlowHandlers>,
184    /// Lazily-parsed `assets/sorla-routes.json` sidecar — see
185    /// [`PackRuntime::sorla_routes`]. Twin of `mcp_routes`, read on first use.
186    sorla_routes: std::sync::OnceLock<Option<crate::runner::sorla_pack_routes::PackSorlaRoutes>>,
187    /// The deployed unit this pack instance belongs to — the revision's
188    /// `bundle_id`, set by [`TenantRuntime::load_revision`] through
189    /// [`set_unit_id`](Self::set_unit_id).
190    ///
191    /// It scopes every extension credential this pack's components read, so two
192    /// units of the SAME pack in one environment can hold different values.
193    /// `None` on the legacy tenant-only path and in `for_component_test`, which
194    /// then resolve the bare pack scope exactly as before.
195    ///
196    /// [`TenantRuntime::load_revision`]: crate::runtime::TenantRuntime::load_revision
197    unit_id: Option<String>,
198}
199
200struct PackComponent {
201    #[allow(dead_code)]
202    name: String,
203    #[allow(dead_code)]
204    version: String,
205    component: Arc<Component>,
206}
207
208/// Outcome of calling a provider component's `identify-instance` export
209/// (`greentic:provider-instance-identity@0.1.0`). Callers MUST treat the
210/// three variants differently per the WIT contract.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub enum IdentifyOutcome {
213    /// Component does not export the world — caller falls back to the
214    /// operator's statically-declared `provider_id`.
215    Unsupported,
216    /// Component exported the world and returned `None` — caller MUST
217    /// fail closed (401/404), no fallback.
218    NoMatch,
219    /// Component identified the payload as belonging to this
220    /// `provider_id` — caller routes to the matching `MessagingEndpoint`.
221    Identified(String),
222}
223
224impl IdentifyOutcome {
225    /// Merge `other` into `self` per the lattice
226    /// `Identified > NoMatch > Unsupported`. Used by callers fanning the probe
227    /// out over multiple packs (overlays) where the strongest signal across
228    /// packs wins.
229    pub fn merge_in(&mut self, other: IdentifyOutcome) {
230        match (&*self, &other) {
231            // Identified is the top — never gets overwritten.
232            (IdentifyOutcome::Identified(_), _) => {}
233            // Promote to Identified from anything else.
234            (_, IdentifyOutcome::Identified(_)) => *self = other,
235            // NoMatch promotes Unsupported but cannot downgrade itself.
236            (IdentifyOutcome::Unsupported, IdentifyOutcome::NoMatch) => *self = other,
237            _ => {}
238        }
239    }
240}
241
242/// Describe a panic payload from a joined/caught Wasmtime thread.
243fn wasi_panic_reason(err: &(dyn std::any::Any + Send)) -> String {
244    if let Some(msg) = err.downcast_ref::<&str>() {
245        msg.to_string()
246    } else if let Some(msg) = err.downcast_ref::<String>() {
247        msg.clone()
248    } else {
249        "unknown panic".to_string()
250    }
251}
252
253/// Run `task` on a dedicated OS thread and await its result without parking a
254/// tokio worker (the result is delivered through a oneshot channel).
255async fn run_on_wasi_thread<F, T>(task_name: &'static str, task: F) -> Result<T>
256where
257    F: FnOnce() -> Result<T> + Send + 'static,
258    T: Send + 'static,
259{
260    let (tx, rx) = tokio::sync::oneshot::channel::<std::thread::Result<Result<T>>>();
261    let builder = std::thread::Builder::new().name(format!("greentic-wasmtime-{task_name}"));
262    builder
263        .spawn(move || {
264            let pid = std::process::id();
265            let thread_id = std::thread::current().id();
266            tracing::info!(
267                event = "wasmtime.thread.start",
268                task = task_name,
269                pid,
270                thread_id = ?thread_id,
271                "starting Wasmtime thread"
272            );
273            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(task));
274            let _ = tx.send(outcome);
275        })
276        .context("failed to spawn Wasmtime thread")?;
277    match rx.await {
278        Ok(Ok(result)) => result,
279        Ok(Err(panic)) => Err(anyhow!(
280            "Wasmtime thread panicked: {}",
281            wasi_panic_reason(panic.as_ref())
282        )),
283        Err(_) => Err(anyhow!("Wasmtime thread ended without producing a result")),
284    }
285}
286
287/// Synchronous variant for callers that are not async (blocks the caller).
288fn run_on_wasi_thread_blocking<F, T>(task_name: &'static str, task: F) -> Result<T>
289where
290    F: FnOnce() -> Result<T> + Send + 'static,
291    T: Send + 'static,
292{
293    let builder = std::thread::Builder::new().name(format!("greentic-wasmtime-{task_name}"));
294    let handle = builder
295        .spawn(move || {
296            let pid = std::process::id();
297            let thread_id = std::thread::current().id();
298            let tokio_handle_present = tokio::runtime::Handle::try_current().is_ok();
299            tracing::info!(
300                event = "wasmtime.thread.start",
301                task = task_name,
302                pid,
303                thread_id = ?thread_id,
304                tokio_handle_present,
305                "starting Wasmtime thread"
306            );
307            task()
308        })
309        .context("failed to spawn Wasmtime thread")?;
310    handle
311        .join()
312        .map_err(|err| {
313            let reason = if let Some(msg) = err.downcast_ref::<&str>() {
314                msg.to_string()
315            } else if let Some(msg) = err.downcast_ref::<String>() {
316                msg.clone()
317            } else {
318                "unknown panic".to_string()
319            };
320            anyhow!("Wasmtime thread panicked: {reason}")
321        })
322        .and_then(|res| res)
323}
324
325/// How long a failed describe-identify probe suppresses re-probing.
326const IDENTIFY_FAILURE_BACKOFF: Duration = Duration::from_secs(30);
327
328fn identify_failure_backoff_active(
329    failed_at: Option<std::time::Instant>,
330    now: std::time::Instant,
331) -> bool {
332    failed_at.is_some_and(|at| now.saturating_duration_since(at) < IDENTIFY_FAILURE_BACKOFF)
333}
334
335#[derive(Debug, Default, Clone)]
336pub struct ComponentResolution {
337    /// Root of a materialized pack directory containing `manifest.cbor` and `components/`.
338    pub materialized_root: Option<PathBuf>,
339    /// Explicit overrides mapping component id -> wasm path.
340    pub overrides: HashMap<String, PathBuf>,
341    /// If true, do not fetch remote components; require cached artifacts.
342    pub dist_offline: bool,
343    /// Optional cache directory for resolved remote components.
344    pub dist_cache_dir: Option<PathBuf>,
345    /// Allow bundled components without wasm_sha256 (dev-only escape hatch).
346    pub allow_missing_hash: bool,
347}
348
349fn build_blocking_client() -> Result<BlockingClient, String> {
350    // Built on a scratch thread: the blocking client must not be constructed
351    // inside an async context.
352    std::thread::spawn(|| {
353        let guard = crate::http_guard::HttpGuard::from_env();
354        BlockingClient::builder()
355            .no_proxy()
356            .dns_resolver(Arc::new(crate::http_guard::GuardedResolver { guard }))
357            .redirect(crate::http_guard::redirect_policy(guard))
358            .build()
359            .map_err(|err| format!("failed to build blocking http client: {err}"))
360    })
361    .join()
362    .map_err(|_| "blocking http client builder thread panicked".to_string())?
363}
364
365fn normalize_pack_path(path: &Path) -> Result<(PathBuf, PathBuf)> {
366    let (root, candidate) = if path.is_absolute() {
367        let parent = path
368            .parent()
369            .ok_or_else(|| anyhow!("pack path {} has no parent", path.display()))?;
370        let root = parent
371            .canonicalize()
372            .with_context(|| format!("failed to canonicalize {}", parent.display()))?;
373        let file = path
374            .file_name()
375            .ok_or_else(|| anyhow!("pack path {} has no file name", path.display()))?;
376        (root, PathBuf::from(file))
377    } else {
378        let cwd = std::env::current_dir().context("failed to resolve current directory")?;
379        let base = if let Some(parent) = path.parent() {
380            cwd.join(parent)
381        } else {
382            cwd
383        };
384        let root = base
385            .canonicalize()
386            .with_context(|| format!("failed to canonicalize {}", base.display()))?;
387        let file = path
388            .file_name()
389            .ok_or_else(|| anyhow!("pack path {} has no file name", path.display()))?;
390        (root, PathBuf::from(file))
391    };
392    let safe = normalize_under_root(&root, &candidate)?;
393    Ok((root, safe))
394}
395
396static HTTP_CLIENT: Lazy<Result<Arc<BlockingClient>, String>> =
397    Lazy::new(|| build_blocking_client().map(Arc::new));
398
399/// Shared blocking HTTP client; construction failure is an error, not a panic.
400fn shared_http_client() -> Result<Arc<BlockingClient>> {
401    match &*HTTP_CLIENT {
402        Ok(client) => Ok(Arc::clone(client)),
403        Err(message) => Err(anyhow!("{message}")),
404    }
405}
406
407/// Default for [`FlowDescriptor::entry`]. A flow is treated as an entrypoint
408/// unless it is explicitly tagged `internal`, so packs (and serialized
409/// descriptors) that predate the `entry` field keep their prior behaviour of
410/// every flow being externally routable.
411fn default_flow_entry() -> bool {
412    true
413}
414
415/// A flow is an *entry* flow — a valid target for an inbound provider event
416/// resolved by flow type — unless it is tagged `internal`. Internal flows are
417/// only reachable via `flow.call` (e.g. a dispatcher's sub-flows) and must
418/// never be selected for type-only routing. Untagged flows default to entry,
419/// preserving behaviour for packs that don't declare the distinction.
420fn tags_indicate_entry<'a, I>(tags: I) -> bool
421where
422    I: IntoIterator<Item = &'a str>,
423{
424    !tags.into_iter().any(|tag| tag == "internal")
425}
426
427#[derive(Debug, Clone, Serialize, Deserialize)]
428pub struct FlowDescriptor {
429    pub id: String,
430    #[serde(rename = "type")]
431    pub flow_type: String,
432    pub pack_id: String,
433    pub profile: String,
434    pub version: String,
435    #[serde(default)]
436    pub description: Option<String>,
437    /// Whether this flow is an entrypoint (see [`tags_indicate_entry`]).
438    #[serde(default = "default_flow_entry")]
439    pub entry: bool,
440}
441
442/// What an interactive agent-tool flow run produced
443/// ([`PackRuntime::run_flow_for_tool_interactive`] /
444/// [`PackRuntime::resume_flow_for_tool`]).
445#[derive(Clone, Debug)]
446pub enum ToolFlowOutcome {
447    /// The flow ran to its end; the value is its output.
448    Completed(Value),
449    /// The flow parked awaiting the user. `snapshot` is the serialized
450    /// [`FlowSnapshot`] to resume from; `presentation` is the flow's output at
451    /// the park point (the finalized card, or every message emitted so far).
452    Waiting {
453        snapshot: Value,
454        presentation: Value,
455    },
456}
457
458fn tool_flow_outcome(flow_id: &str, execution: FlowExecution) -> Result<ToolFlowOutcome, String> {
459    match execution.status {
460        FlowStatus::Completed => Ok(ToolFlowOutcome::Completed(execution.output)),
461        FlowStatus::Waiting(wait) => {
462            let snapshot = serde_json::to_value(&wait.snapshot)
463                .map_err(|e| format!("flow '{flow_id}': cannot serialize its park point: {e}"))?;
464            Ok(ToolFlowOutcome::Waiting {
465                snapshot,
466                presentation: execution.output,
467            })
468        }
469    }
470}
471
472pub struct HostState {
473    #[allow(dead_code)]
474    pack_id: String,
475    config: Arc<HostConfig>,
476    http_client: Arc<BlockingClient>,
477    default_env: String,
478    #[allow(dead_code)]
479    session_store: Option<DynSessionStore>,
480    state_store: Option<DynStateStore>,
481    mocks: Option<Arc<MockLayer>>,
482    secrets: DynSecretsManager,
483    oauth_config: Option<OAuthBrokerConfig>,
484    exec_ctx: Option<ComponentExecCtx>,
485    component_ref: Option<String>,
486    provider_core_component: bool,
487    /// `pack-config.v1.non_secret` map for the `greentic:runtime-config@1.0.0`
488    /// host import. Populated by the producer (greentic-start) from the
489    /// deployed `PackConfig`; `None` when no PackConfig was published, in
490    /// which case lookups fall back to the secrets-store compat shim with
491    /// a once-per-process deprecation warning.
492    runtime_config_non_secret: Option<Arc<BTreeMap<String, Value>>>,
493    /// `pack-config.v1.runtime_refs` (C5) injection: per-pack `key → URI`
494    /// bindings plus the env-shared resolver. The host import resolves the
495    /// URI on every call so the value tracks `runtime.json` hot-reloads.
496    runtime_refs: Option<RuntimeRefsInjection>,
497    /// The deployed unit whose copy of this pack's secrets the component reads
498    /// and writes — see [`PackRuntime::unit_id`] and
499    /// [`with_unit`](Self::with_unit). `None` means "no unit known", which
500    /// resolves the bare pack scope exactly as before.
501    unit_id: Option<String>,
502}
503
504impl HostState {
505    #[allow(clippy::too_many_arguments)]
506    pub fn new(
507        pack_id: String,
508        config: Arc<HostConfig>,
509        http_client: Arc<BlockingClient>,
510        mocks: Option<Arc<MockLayer>>,
511        session_store: Option<DynSessionStore>,
512        state_store: Option<DynStateStore>,
513        secrets: DynSecretsManager,
514        oauth_config: Option<OAuthBrokerConfig>,
515        exec_ctx: Option<ComponentExecCtx>,
516        component_ref: Option<String>,
517        provider_core_component: bool,
518        runtime_config_non_secret: Option<Arc<BTreeMap<String, Value>>>,
519        runtime_refs: Option<RuntimeRefsInjection>,
520    ) -> Result<Self> {
521        let default_env = crate::config::greentic_env_or_local();
522        Ok(Self {
523            pack_id,
524            config,
525            http_client,
526            default_env,
527            session_store,
528            state_store,
529            mocks,
530            secrets,
531            oauth_config,
532            exec_ctx,
533            component_ref,
534            provider_core_component,
535            runtime_config_non_secret,
536            runtime_refs,
537            unit_id: None,
538        })
539    }
540
541    /// Bind this host state to a deployed unit, so its pack-secret reads try
542    /// that unit's own address before the shared one and its writes land there
543    /// only.
544    ///
545    /// A separate builder rather than a 14th argument to [`new`](Self::new):
546    /// `new` is public and already carries thirteen, and `None` — "no unit
547    /// known" — is a legitimate state (the legacy tenant-only runtime, the
548    /// process-level serve path), not an oversight. Every caller in
549    /// [`PackRuntime`] threads its own `unit_id` through here.
550    #[must_use]
551    pub fn with_unit(mut self, unit_id: Option<String>) -> Self {
552        self.unit_id = unit_id;
553        self
554    }
555
556    /// Read one of this pack's secrets at the unit scope, falling back to the
557    /// shared pack scope. THE single read path for every `SecretsStoreHost` /
558    /// `RuntimeConfigHost` entry point on this type — four call sites used to
559    /// spell the same address inline, which is how one of them would be missed.
560    fn read_pack_secret(
561        &self,
562        ctx: &TypesTenantCtx,
563        canonical_key: &str,
564    ) -> std::result::Result<Vec<u8>, PackSecretError> {
565        read_pack_secret_blocking(
566            &self.secrets,
567            ctx,
568            &self.pack_id,
569            self.unit_id.as_deref(),
570            canonical_key,
571        )
572    }
573
574    /// Write one of this pack's secrets. Lands at the unit address ONLY when a
575    /// unit is known — never a write-through to the shared address, which every
576    /// other unit of this pack reads.
577    fn write_pack_secret(
578        &self,
579        ctx: &TypesTenantCtx,
580        canonical_key: &str,
581        value: &[u8],
582    ) -> Result<()> {
583        write_pack_secret_blocking(
584            &self.secrets,
585            ctx,
586            &self.pack_id,
587            self.unit_id.as_deref(),
588            canonical_key,
589            value,
590        )
591    }
592
593    #[allow(clippy::too_many_arguments)]
594    fn instantiate_component_result(
595        linker: &mut Linker<ComponentState>,
596        store: &mut Store<ComponentState>,
597        component: &Component,
598        ctx: &ComponentExecCtx,
599        caller: Option<&crate::caller_identity::ComponentCaller>,
600        provider_id: Option<&str>,
601        component_ref: &str,
602        operation: &str,
603        input_json: &str,
604    ) -> Result<InvokeResult> {
605        let pre_instance = linker.instantiate_pre(component)?;
606        match component_api::v0_6::ComponentPre::new(pre_instance) {
607            Ok(pre) => {
608                let envelope = component_api::envelope_v0_6_for(
609                    ctx,
610                    caller,
611                    provider_id,
612                    component_ref,
613                    input_json,
614                )?;
615                let operation_owned = operation.to_string();
616                let result = block_on(async {
617                    let bindings = pre.instantiate_async(&mut *store).await?;
618                    let node = bindings.greentic_component_node();
619                    node.call_invoke(&mut *store, &operation_owned, &envelope)
620                })?;
621                component_api::invoke_result_from_v0_6(result)
622            }
623            Err(err_v06) => {
624                if !is_missing_node_export(&err_v06, "0.6.0") {
625                    return Err(err_v06.into());
626                }
627                let pre_instance = linker.instantiate_pre(component)?;
628                match component_api::v0_5::ComponentPre::new(pre_instance) {
629                    Ok(pre) => {
630                        let result = block_on(async {
631                            let bindings = pre.instantiate_async(&mut *store).await?;
632                            let node = bindings.greentic_component_node();
633                            let ctx_v05 =
634                                component_api::exec_ctx_v0_5_for(ctx, caller, provider_id);
635                            let operation_owned = operation.to_string();
636                            let input_owned = input_json.to_string();
637                            node.call_invoke(&mut *store, &ctx_v05, &operation_owned, &input_owned)
638                        })?;
639                        Ok(component_api::invoke_result_from_v0_5(result))
640                    }
641                    Err(err) => {
642                        if !is_missing_node_export(&err, "0.5.0") {
643                            return Err(err.into());
644                        }
645                        let pre_instance = linker.instantiate_pre(component)?;
646                        match component_api::v0_4::ComponentPre::new(pre_instance) {
647                            Ok(pre) => {
648                                let result = block_on(async {
649                                    let bindings = pre.instantiate_async(&mut *store).await?;
650                                    let node = bindings.greentic_component_node();
651                                    let ctx_v04 =
652                                        component_api::exec_ctx_v0_4_for(ctx, caller, provider_id);
653                                    let operation_owned = operation.to_string();
654                                    let input_owned = input_json.to_string();
655                                    node.call_invoke(
656                                        &mut *store,
657                                        &ctx_v04,
658                                        &operation_owned,
659                                        &input_owned,
660                                    )
661                                })?;
662                                Ok(component_api::invoke_result_from_v0_4(result))
663                            }
664                            Err(err_v04) => {
665                                if is_missing_node_export(&err_v04, "0.4.0") {
666                                    Self::try_v06_runtime(linker, store, component, input_json)
667                                } else {
668                                    Err(err_v04.into())
669                                }
670                            }
671                        }
672                    }
673                }
674            }
675        }
676    }
677
678    /// Fallback for v0.6 components that export `component-runtime::run(input, state)`
679    /// instead of the legacy `node::invoke(ctx, op, input)`.
680    fn try_v06_runtime(
681        linker: &mut Linker<ComponentState>,
682        store: &mut Store<ComponentState>,
683        component: &Component,
684        input_json: &str,
685    ) -> Result<InvokeResult> {
686        let pre_instance = linker.instantiate_pre(component)?;
687        let pre = component_api::v0_6_runtime::ComponentV0V6RuntimePre::new(pre_instance).map_err(
688            |err| err.context("component exports neither node@0.5/0.4 nor component-runtime@0.6"),
689        )?;
690
691        let result = block_on(async {
692            let bindings = pre.instantiate_async(&mut *store).await?;
693            let runtime = bindings.greentic_component_component_runtime();
694
695            // Encode input as CBOR — the component's run() expects CBOR bytes.
696            let input_value = parse_v06_input(input_json);
697            let input_cbor =
698                serde_cbor::to_vec(&input_value).context("encode input as CBOR for v0.6")?;
699            let empty_state = serde_cbor::to_vec(&Value::Object(Default::default()))
700                .context("encode empty state")?;
701
702            let run_result = runtime
703                .call_run(&mut *store, &input_cbor, &empty_state)
704                .map_err(|err| err.context("v0.6 component-runtime::run call failed"))?;
705
706            // Decode output CBOR to JSON.
707            let output_value: Value = serde_cbor::from_slice(&run_result.output)
708                .context("decode v0.6 run output CBOR")?;
709            let output_json = serde_json::to_string(&output_value)
710                .context("serialize v0.6 run output to JSON")?;
711
712            Ok::<_, anyhow::Error>(output_json)
713        })?;
714
715        Ok(InvokeResult::Ok(result))
716    }
717
718    fn convert_invoke_result(result: InvokeResult) -> Result<Value> {
719        match result {
720            InvokeResult::Ok(body) => {
721                if body.is_empty() {
722                    return Ok(Value::Null);
723                }
724                serde_json::from_str(&body).or_else(|_| Ok(Value::String(body)))
725            }
726            InvokeResult::Err(NodeError {
727                code,
728                message,
729                retryable,
730                backoff_ms,
731                details,
732            }) => {
733                let mut obj = serde_json::Map::new();
734                obj.insert("ok".into(), Value::Bool(false));
735                let mut error = serde_json::Map::new();
736                error.insert("code".into(), Value::String(code));
737                error.insert("message".into(), Value::String(message));
738                error.insert("retryable".into(), Value::Bool(retryable));
739                if let Some(backoff) = backoff_ms {
740                    error.insert("backoff_ms".into(), Value::Number(backoff.into()));
741                }
742                if let Some(details) = details {
743                    error.insert(
744                        "details".into(),
745                        serde_json::from_str(&details).unwrap_or(Value::String(details)),
746                    );
747                }
748                obj.insert("error".into(), Value::Object(error));
749                Ok(Value::Object(obj))
750            }
751        }
752    }
753
754    /// Build a `TenantCtx` for secrets lookups that includes the team from the
755    /// execution context. `config.tenant_ctx()` only populates env + tenant;
756    /// without this, secrets scoped to a specific team are unreachable.
757    fn secrets_tenant_ctx(&self) -> TypesTenantCtx {
758        let mut ctx = self.config.tenant_ctx();
759        if let Some(exec_ctx) = self.exec_ctx.as_ref()
760            && let Some(team) = exec_ctx.tenant.team.as_ref()
761            && let Ok(team_id) = TeamId::from_str(team)
762        {
763            ctx = ctx.with_team(Some(team_id));
764        }
765        ctx
766    }
767
768    pub fn get_secret(&self, key: &str) -> Result<String> {
769        if provider_core_only::is_enabled() {
770            bail!(provider_core_only::blocked_message("secrets"))
771        }
772        if !self.config.secrets_policy.is_allowed(key) {
773            bail!("secret {key} is not permitted by bindings policy");
774        }
775        if let Some(mock) = &self.mocks
776            && let Some(value) = mock.secrets_lookup(key)
777        {
778            return Ok(value);
779        }
780        let ctx = self.secrets_tenant_ctx();
781        let canonical_key = canonicalize_secret_key(key);
782        let bytes = self
783            .read_pack_secret(&ctx, &canonical_key)
784            .context("failed to read secret from manager")?;
785        let value = String::from_utf8(bytes).context("secret value is not valid UTF-8")?;
786        Ok(value)
787    }
788
789    fn allows_secret_write_in_provider_core_only(&self) -> bool {
790        self.provider_core_component || self.component_ref.is_none()
791    }
792
793    fn tenant_ctx_from_v1(&self, ctx: Option<StateTenantCtx>) -> Result<TypesTenantCtx> {
794        // The tenant and env are bound by the host. Guest-supplied values are
795        // never trusted: honouring them would let a component read or write
796        // another tenant's state.
797        let tenant_raw = self
798            .exec_ctx
799            .as_ref()
800            .map(|ctx| ctx.tenant.tenant.clone())
801            .unwrap_or_else(|| self.config.tenant.clone());
802        let env_raw = self.default_env.clone();
803        if let Some(guest) = ctx.as_ref() {
804            if !guest.tenant.is_empty() && guest.tenant != tenant_raw {
805                warn!(
806                    pack_id = %self.pack_id,
807                    guest_tenant = %crate::log_safe::log_safe(&guest.tenant),
808                    "ignoring guest-supplied tenant in state ctx; using host-bound tenant"
809                );
810            }
811            if !guest.env.is_empty() && guest.env != env_raw {
812                warn!(
813                    pack_id = %self.pack_id,
814                    guest_env = %crate::log_safe::log_safe(&guest.env),
815                    "ignoring guest-supplied env in state ctx; using host-bound env"
816                );
817            }
818        }
819        let tenant_id = TenantId::from_str(&tenant_raw)
820            .with_context(|| format!("invalid tenant id `{tenant_raw}`"))?;
821        let env_id =
822            EnvId::from_str(&env_raw).with_context(|| format!("invalid env id `{env_raw}`"))?;
823        let mut tenant_ctx = TypesTenantCtx::new(env_id, tenant_id);
824        if let Some(exec_ctx) = self.exec_ctx.as_ref() {
825            if let Some(team) = exec_ctx.tenant.team.as_ref() {
826                let team_id =
827                    TeamId::from_str(team).with_context(|| format!("invalid team id `{team}`"))?;
828                tenant_ctx = tenant_ctx.with_team(Some(team_id));
829            }
830            if let Some(user) = exec_ctx.tenant.user.as_ref() {
831                let user_id =
832                    UserId::from_str(user).with_context(|| format!("invalid user id `{user}`"))?;
833                tenant_ctx = tenant_ctx.with_user(Some(user_id));
834            }
835            tenant_ctx = tenant_ctx.with_flow(exec_ctx.flow_id.clone());
836            if let Some(node) = exec_ctx.node_id.as_ref() {
837                tenant_ctx = tenant_ctx.with_node(node.clone());
838            }
839            if let Some(session) = exec_ctx.tenant.correlation_id.as_ref() {
840                tenant_ctx = tenant_ctx.with_session(session.clone());
841            }
842            tenant_ctx.trace_id = exec_ctx.tenant.trace_id.clone();
843        }
844
845        if let Some(ctx) = ctx {
846            if let Some(team) = ctx.team.or(ctx.team_id) {
847                let team_id =
848                    TeamId::from_str(&team).with_context(|| format!("invalid team id `{team}`"))?;
849                tenant_ctx = tenant_ctx.with_team(Some(team_id));
850            }
851            if let Some(user) = ctx.user.or(ctx.user_id) {
852                let user_id =
853                    UserId::from_str(&user).with_context(|| format!("invalid user id `{user}`"))?;
854                tenant_ctx = tenant_ctx.with_user(Some(user_id));
855            }
856            if let Some(flow) = ctx.flow_id {
857                tenant_ctx = tenant_ctx.with_flow(flow);
858            }
859            if let Some(node) = ctx.node_id {
860                tenant_ctx = tenant_ctx.with_node(node);
861            }
862            if let Some(provider) = ctx.provider_id {
863                tenant_ctx = tenant_ctx.with_provider(provider);
864            }
865            if let Some(session) = ctx.session_id {
866                tenant_ctx = tenant_ctx.with_session(session);
867            }
868            tenant_ctx.trace_id = ctx.trace_id;
869        }
870        Ok(tenant_ctx)
871    }
872
873    fn send_http_request(
874        &mut self,
875        req: HttpRequest,
876        opts: Option<HttpRequestOptionsV1_1>,
877        _ctx: Option<HttpTenantCtx>,
878    ) -> Result<HttpResponse, HttpClientError> {
879        if !self.config.http_enabled {
880            return Err(HttpClientError {
881                code: "denied".into(),
882                message: "http client disabled by policy".into(),
883            });
884        }
885
886        if let Some(body) = req.body.as_deref()
887            && let Err(message) = crate::wasm_limits::check_size(
888                "request body",
889                body.len(),
890                crate::wasm_limits::http_max_request_bytes(),
891            )
892        {
893            return Err(HttpClientError {
894                code: "too-large".into(),
895                message,
896            });
897        }
898
899        let mut mock_state = None;
900        let raw_body = req.body.clone();
901        if let Some(mock) = &self.mocks
902            && let Ok(meta) = HttpMockRequest::new(&req.method, &req.url, raw_body.as_deref())
903        {
904            match mock.http_begin(&meta) {
905                HttpDecision::Mock(response) => {
906                    let headers = response
907                        .headers
908                        .iter()
909                        .map(|(k, v)| (k.clone(), v.clone()))
910                        .collect();
911                    return Ok(HttpResponse {
912                        status: response.status,
913                        headers,
914                        body: response.body.clone().map(|b| b.into_bytes()),
915                    });
916                }
917                HttpDecision::Deny(reason) => {
918                    return Err(HttpClientError {
919                        code: "denied".into(),
920                        message: reason,
921                    });
922                }
923                HttpDecision::Passthrough { record } => {
924                    mock_state = Some((meta, record));
925                }
926            }
927        }
928
929        let guard = crate::http_guard::HttpGuard::from_env();
930        if let Ok(parsed) = url::Url::parse(&req.url)
931            && let Err(reason) = guard.check_url_literal(&parsed)
932        {
933            return Err(HttpClientError {
934                code: "denied".into(),
935                message: reason,
936            });
937        }
938
939        let method = req.method.parse().unwrap_or(reqwest::Method::GET);
940        let mut builder = self.http_client.request(method, &req.url);
941        for (key, value) in req.headers {
942            if let Ok(header) = reqwest::header::HeaderName::from_bytes(key.as_bytes())
943                && let Ok(header_value) = reqwest::header::HeaderValue::from_str(&value)
944            {
945                builder = builder.header(header, header_value);
946            }
947        }
948
949        if let Some(body) = raw_body.clone() {
950            builder = builder.body(body);
951        }
952
953        if let Some(opts) = opts {
954            if let Some(timeout) =
955                guest_timeout(opts.timeout_ms, crate::http_timeout_hooks::ceiling())
956            {
957                builder = builder.timeout(timeout);
958            }
959            if opts.allow_insecure == Some(true) {
960                warn!(origin = %crate::log_safe::log_safe_origin(&req.url), "allow-insecure not supported; using default TLS validation");
961            }
962            if let Some(follow_redirects) = opts.follow_redirects
963                && !follow_redirects
964            {
965                warn!(origin = %crate::log_safe::log_safe_origin(&req.url), "follow-redirects=false not supported; using default client behaviour");
966            }
967        }
968
969        let response = match builder.send() {
970            Ok(resp) => resp,
971            Err(err) => {
972                // reqwest's Display appends ` for url (<full url>)`; the URL can
973                // carry a token (bot<TOKEN> path, webhook path, query).
974                let blocked = crate::http_guard::is_blocked_error(&err);
975                let err = err.without_url();
976                warn!(origin = %crate::log_safe::log_safe_origin(&req.url), error = %err, "http client request failed");
977                if blocked {
978                    return Err(HttpClientError {
979                        code: "denied".into(),
980                        message: crate::http_guard::BLOCKED_MARKER.to_string(),
981                    });
982                }
983                return Err(HttpClientError {
984                    code: "unavailable".into(),
985                    message: err.to_string(),
986                });
987            }
988        };
989
990        let status = response.status().as_u16();
991        let headers_vec = response
992            .headers()
993            .iter()
994            .map(|(k, v)| {
995                (
996                    k.as_str().to_string(),
997                    v.to_str().unwrap_or_default().to_string(),
998                )
999            })
1000            .collect::<Vec<_>>();
1001        let body_bytes = match crate::http_guard::read_capped_body(
1002            response,
1003            guard.max_response_bytes,
1004        ) {
1005            Ok(bytes) => Some(bytes),
1006            Err(err) => {
1007                warn!(origin = %crate::log_safe::log_safe_origin(&req.url), error = %crate::http_guard::body_read_reason(&err), "http response body read failed");
1008                return Err(HttpClientError {
1009                    code: "unavailable".into(),
1010                    message: format!(
1011                        "failed to read response body: {}",
1012                        crate::http_guard::body_read_reason(&err)
1013                    ),
1014                });
1015            }
1016        };
1017
1018        if let Some((meta, true)) = mock_state.take()
1019            && let Some(mock) = &self.mocks
1020        {
1021            let recorded = HttpMockResponse::new(
1022                status,
1023                headers_vec.clone().into_iter().collect(),
1024                body_bytes
1025                    .as_ref()
1026                    .map(|b| String::from_utf8_lossy(b).into_owned()),
1027            );
1028            mock.http_record(&meta, &recorded);
1029        }
1030
1031        Ok(HttpResponse {
1032            status,
1033            headers: headers_vec,
1034            body: body_bytes,
1035        })
1036    }
1037}
1038
1039#[cfg(test)]
1040mod canonicalize_tests {
1041    use crate::secrets::canonicalize_secret_key;
1042
1043    #[test]
1044    fn upper_snake_to_lower_snake() {
1045        assert_eq!(
1046            canonicalize_secret_key("TELEGRAM_BOT_TOKEN"),
1047            "telegram_bot_token"
1048        );
1049    }
1050
1051    #[test]
1052    fn trim_and_replace_non_alphanumeric() {
1053        assert_eq!(
1054            canonicalize_secret_key("  webex-bot-token  "),
1055            "webex_bot_token"
1056        );
1057    }
1058
1059    #[test]
1060    fn preserve_existing_lower_snake_with_extra_underscores() {
1061        assert_eq!(canonicalize_secret_key("MiXeD__Case"), "mixed__case");
1062    }
1063}
1064
1065/// Parse the invocation input for a v0.6 component. Non-JSON input is passed
1066/// through as a string rather than failing (or being silently nulled).
1067fn parse_v06_input(input_json: &str) -> Value {
1068    serde_json::from_str(input_json).unwrap_or_else(|_| Value::String(input_json.to_string()))
1069}
1070
1071impl SecretsStoreHost for HostState {
1072    fn get(&mut self, key: String) -> Result<Option<Vec<u8>>, SecretsError> {
1073        if provider_core_only::is_enabled() {
1074            warn!(secret = %crate::log_safe::log_safe(&key), "provider-core only mode enabled; blocking secrets store");
1075            return Err(SecretsError::Denied);
1076        }
1077        if !self.config.secrets_policy.is_allowed(&key) {
1078            return Err(SecretsError::Denied);
1079        }
1080        if let Some(mock) = &self.mocks
1081            && let Some(value) = mock.secrets_lookup(&key)
1082        {
1083            return Ok(Some(value.into_bytes()));
1084        }
1085        let ctx = self.secrets_tenant_ctx();
1086        let canonical_key = canonicalize_secret_key(&key);
1087        match self.read_pack_secret(&ctx, &canonical_key) {
1088            Ok(bytes) => Ok(Some(bytes)),
1089            Err(err) => {
1090                warn!(secret = %crate::log_safe::log_safe(&key), canonical = %crate::log_safe::log_safe(&canonical_key), error = %err, "secret lookup failed");
1091                Err(match err {
1092                    PackSecretError::NotFound(_) => SecretsError::NotFound,
1093                    PackSecretError::Denied(_) => SecretsError::Denied,
1094                    PackSecretError::Backend(_) => SecretsError::Internal,
1095                })
1096            }
1097        }
1098    }
1099}
1100
1101impl SecretsStoreHostV1_1 for HostState {
1102    fn get(&mut self, key: String) -> Result<Option<Vec<u8>>, SecretsErrorV1_1> {
1103        if provider_core_only::is_enabled() {
1104            warn!(secret = %crate::log_safe::log_safe(&key), "provider-core only mode enabled; blocking secrets store");
1105            return Err(SecretsErrorV1_1::Denied);
1106        }
1107        if !self.config.secrets_policy.is_allowed(&key) {
1108            return Err(SecretsErrorV1_1::Denied);
1109        }
1110        if let Some(mock) = &self.mocks
1111            && let Some(value) = mock.secrets_lookup(&key)
1112        {
1113            return Ok(Some(value.into_bytes()));
1114        }
1115        let ctx = self.secrets_tenant_ctx();
1116        let canonical_key = canonicalize_secret_key(&key);
1117        match self.read_pack_secret(&ctx, &canonical_key) {
1118            Ok(bytes) => Ok(Some(bytes)),
1119            Err(err) => {
1120                warn!(secret = %crate::log_safe::log_safe(&key), canonical = %crate::log_safe::log_safe(&canonical_key), error = %err, "secret lookup failed");
1121                Err(match err {
1122                    PackSecretError::NotFound(_) => SecretsErrorV1_1::NotFound,
1123                    PackSecretError::Denied(_) => SecretsErrorV1_1::Denied,
1124                    PackSecretError::Backend(_) => SecretsErrorV1_1::Internal,
1125                })
1126            }
1127        }
1128    }
1129
1130    /// The WIT `put` returns nothing, so a refusal cannot be reported through
1131    /// this trait method; it is logged and dropped. The linker does not route
1132    /// guest calls here: [`add_secrets_store_to_linker`] calls
1133    /// [`HostState::try_put_secret`] and turns a refusal into a guest trap.
1134    fn put(&mut self, key: String, value: Vec<u8>) {
1135        if let Err(err) = self.try_put_secret(&key, &value) {
1136            warn!(error = %err, "secret write refused");
1137        }
1138    }
1139}
1140
1141/// Why a guest `secrets-store.put` was refused.
1142#[derive(Debug, thiserror::Error)]
1143pub enum SecretPutError {
1144    #[error("secret write denied for key {0}: invalid key")]
1145    InvalidKey(String),
1146    #[error("secret write denied for key {0}: provider-core-only mode")]
1147    ProviderCoreOnly(String),
1148    #[error("secret write denied for key {0}: policy")]
1149    Policy(String),
1150    #[error("secret write failed for key {0}")]
1151    WriteFailed(String),
1152}
1153
1154impl HostState {
1155    /// Fallible secret write. Never panics; guest-reachable refusals come back
1156    /// as [`SecretPutError`] (the key in the message is log-safe and bounded).
1157    pub fn try_put_secret(&mut self, key: &str, value: &[u8]) -> Result<(), SecretPutError> {
1158        let safe_key = crate::log_safe::log_safe(key).into_owned();
1159        if key.trim().is_empty() {
1160            warn!(secret = %safe_key, "secret write blocked: empty key");
1161            return Err(SecretPutError::InvalidKey(safe_key));
1162        }
1163        if provider_core_only::is_enabled() && !self.allows_secret_write_in_provider_core_only() {
1164            warn!(
1165                secret = %safe_key,
1166                component = self.component_ref.as_deref().unwrap_or("<pack>"),
1167                "provider-core only mode enabled; blocking secrets store write"
1168            );
1169            return Err(SecretPutError::ProviderCoreOnly(safe_key));
1170        }
1171        if !self.config.secrets_policy.is_allowed(key) {
1172            warn!(secret = %safe_key, "secret write denied by bindings policy");
1173            return Err(SecretPutError::Policy(safe_key));
1174        }
1175        let ctx = self.secrets_tenant_ctx();
1176        let canonical_key = canonicalize_secret_key(key);
1177        if let Err(err) = self.write_pack_secret(&ctx, &canonical_key, value) {
1178            warn!(
1179                secret = %safe_key,
1180                canonical = %crate::log_safe::log_safe(&canonical_key),
1181                error = %err,
1182                "secret write failed"
1183            );
1184            return Err(SecretPutError::WriteFailed(safe_key));
1185        }
1186        Ok(())
1187    }
1188}
1189
1190fn v1_1_error_to_v1_0(err: SecretsErrorV1_1) -> SecretsError {
1191    match err {
1192        SecretsErrorV1_1::NotFound => SecretsError::NotFound,
1193        SecretsErrorV1_1::Denied => SecretsError::Denied,
1194        SecretsErrorV1_1::InvalidKey => SecretsError::InvalidKey,
1195        SecretsErrorV1_1::Internal => SecretsError::Internal,
1196    }
1197}
1198
1199/// Register `secrets-store` `@1.1.0` and `@1.0.0` on the linker. Replaces the
1200/// library's `add_secrets_store_compat_to_linker` so a refused `put` surfaces
1201/// as an ordinary guest trap (an invocation error) instead of a host panic;
1202/// the WIT `put` has no result type to carry the error.
1203fn add_secrets_store_to_linker(linker: &mut Linker<ComponentState>) -> Result<()> {
1204    let mut v1_1 = linker.instance("greentic:secrets-store/secrets-store@1.1.0")?;
1205    v1_1.func_wrap(
1206        "get",
1207        |mut caller: StoreContextMut<'_, ComponentState>, (key,): (String,)| {
1208            let host = caller.data_mut().host_mut();
1209            Ok((SecretsStoreHostV1_1::get(host, key),))
1210        },
1211    )?;
1212    v1_1.func_wrap(
1213        "put",
1214        |mut caller: StoreContextMut<'_, ComponentState>, (key, value): (String, Vec<u8>)| {
1215            let host = caller.data_mut().host_mut();
1216            host.try_put_secret(&key, &value)
1217                .map_err(wasmtime::Error::new)
1218        },
1219    )?;
1220    let mut v1_0 = linker.instance("greentic:secrets-store/secrets-store@1.0.0")?;
1221    v1_0.func_wrap(
1222        "get",
1223        |mut caller: StoreContextMut<'_, ComponentState>, (key,): (String,)| {
1224            let host = caller.data_mut().host_mut();
1225            let result = SecretsStoreHostV1_1::get(host, key).map_err(v1_1_error_to_v1_0);
1226            Ok((result,))
1227        },
1228    )?;
1229    Ok(())
1230}
1231
1232/// Process-global set of `pack-config.v1` keys for which the compat shim has
1233/// already logged a deprecation warning. Used to debounce once-per-process
1234/// per-key so resolving the same legacy key from many invocations does not
1235/// spam the log.
1236static WARNED_COMPAT_KEYS: Lazy<Mutex<HashSet<String>>> = Lazy::new(|| Mutex::new(HashSet::new()));
1237
1238fn warn_compat_fallback_once(key: &str) {
1239    let mut warned = WARNED_COMPAT_KEYS.lock();
1240    if warned.insert(key.to_string()) {
1241        warn!(
1242            key = %crate::log_safe::log_safe(key),
1243            "runtime-config key resolved via secrets-store compat fallback; \
1244             move this value into pack-config.v1.non_secret"
1245        );
1246    }
1247}
1248
1249impl RuntimeConfigHost for HostState {
1250    fn get(&mut self, key: String) -> Result<Option<String>, ConfigError> {
1251        if key.trim().is_empty() {
1252            return Err(ConfigError::InvalidKey);
1253        }
1254
1255        // 1) Primary channel: pack-config.v1.non_secret. Values are stored as
1256        //    `serde_json::Value`; the WIT contract returns UTF-8 strings
1257        //    conventionally JSON-encoded, so stringify here.
1258        if let Some(map) = self.runtime_config_non_secret.as_ref()
1259            && let Some(value) = map.get(&key)
1260        {
1261            return serde_json::to_string(value).map(Some).map_err(|err| {
1262                warn!(key = %crate::log_safe::log_safe(&key), error = %err, "runtime-config value JSON-encode failed");
1263                ConfigError::Internal
1264            });
1265        }
1266
1267        // 1b) C5 channel: pack-config.v1.runtime_refs. Resolved on every call
1268        //     so values track `runtime.json` hot-reloads. The per-pack `refs`
1269        //     map gates which keys this channel claims; non-bound keys fall
1270        //     through to the compat shim.
1271        if let Some(injection) = self.runtime_refs.as_ref()
1272            && let Some(uri) = injection.refs.get(&key)
1273        {
1274            use crate::runtime_refs::RuntimeRefResolverError;
1275            return match injection.resolver.resolve(uri) {
1276                Ok(Some(value)) => serde_json::to_string(&value).map(Some).map_err(|err| {
1277                    warn!(key = %crate::log_safe::log_safe(&key), error = %err, "runtime-ref value JSON-encode failed");
1278                    ConfigError::Internal
1279                }),
1280                Ok(None) => Ok(None),
1281                Err(err @ RuntimeRefResolverError::Invalid(_)) => {
1282                    warn!(key = %crate::log_safe::log_safe(&key), error = %err, "runtime-ref rejected");
1283                    Err(ConfigError::InvalidKey)
1284                }
1285                Err(err @ RuntimeRefResolverError::Internal(_)) => {
1286                    warn!(key = %crate::log_safe::log_safe(&key), error = %err, "runtime-ref resolution failed");
1287                    Err(ConfigError::Internal)
1288                }
1289            };
1290        }
1291
1292        // 2) Compat fallback: try the secrets-store. Warn once per key per
1293        //    process so this stays visible without spamming the log.
1294        match SecretsStoreHost::get(self, key.clone()) {
1295            Ok(Some(bytes)) => match String::from_utf8(bytes) {
1296                Ok(value) => {
1297                    warn_compat_fallback_once(&key);
1298                    Ok(Some(value))
1299                }
1300                Err(_) => {
1301                    warn!(
1302                        key = %crate::log_safe::log_safe(&key),
1303                        "runtime-config compat fallback found non-UTF-8 secret bytes; \
1304                         returning not-found"
1305                    );
1306                    Err(ConfigError::Internal)
1307                }
1308            },
1309            Ok(None) => Ok(None),
1310            Err(SecretsError::NotFound) => Ok(None),
1311            Err(SecretsError::Denied) => Err(ConfigError::Denied),
1312            Err(SecretsError::InvalidKey) => Err(ConfigError::InvalidKey),
1313            Err(SecretsError::Internal) => Err(ConfigError::Internal),
1314        }
1315    }
1316}
1317
1318impl HttpClientHost for HostState {
1319    fn send(
1320        &mut self,
1321        req: HttpRequest,
1322        ctx: Option<HttpTenantCtx>,
1323    ) -> Result<HttpResponse, HttpClientError> {
1324        self.send_http_request(req, None, ctx)
1325    }
1326}
1327
1328impl HttpClientHostV1_1 for HostState {
1329    fn send(
1330        &mut self,
1331        req: HttpRequestV1_1,
1332        opts: Option<HttpRequestOptionsV1_1>,
1333        ctx: Option<HttpTenantCtxV1_1>,
1334    ) -> Result<HttpResponseV1_1, HttpClientErrorV1_1> {
1335        let legacy_req = HttpRequest {
1336            method: req.method,
1337            url: req.url,
1338            headers: req.headers,
1339            body: req.body,
1340        };
1341        let legacy_ctx = ctx.map(|ctx| HttpTenantCtx {
1342            env: ctx.env,
1343            tenant: ctx.tenant,
1344            tenant_id: ctx.tenant_id,
1345            team: ctx.team,
1346            team_id: ctx.team_id,
1347            user: ctx.user,
1348            user_id: ctx.user_id,
1349            trace_id: ctx.trace_id,
1350            correlation_id: ctx.correlation_id,
1351            i18n_id: ctx.i18n_id,
1352            attributes: ctx.attributes,
1353            session_id: ctx.session_id,
1354            flow_id: ctx.flow_id,
1355            node_id: ctx.node_id,
1356            provider_id: ctx.provider_id,
1357            deadline_ms: ctx.deadline_ms,
1358            attempt: ctx.attempt,
1359            idempotency_key: ctx.idempotency_key,
1360            impersonation: ctx.impersonation.map(|imp| http_types_v1_0::Impersonation {
1361                actor_id: imp.actor_id,
1362                reason: imp.reason,
1363            }),
1364        });
1365
1366        self.send_http_request(legacy_req, opts, legacy_ctx)
1367            .map(|resp| HttpResponseV1_1 {
1368                status: resp.status,
1369                headers: resp.headers,
1370                body: resp.body,
1371            })
1372            .map_err(|err| HttpClientErrorV1_1 {
1373                code: err.code,
1374                message: err.message,
1375            })
1376    }
1377}
1378
1379impl StateStoreHost for HostState {
1380    fn read(
1381        &mut self,
1382        key: HostStateKey,
1383        ctx: Option<StateTenantCtx>,
1384    ) -> Result<Vec<u8>, StateError> {
1385        let store = match self.state_store.as_ref() {
1386            Some(store) => store.clone(),
1387            None => {
1388                return Err(StateError {
1389                    code: "unavailable".into(),
1390                    message: "state store not configured".into(),
1391                });
1392            }
1393        };
1394        let tenant_ctx = match self.tenant_ctx_from_v1(ctx) {
1395            Ok(ctx) => ctx,
1396            Err(err) => {
1397                return Err(StateError {
1398                    code: "invalid-ctx".into(),
1399                    message: err.to_string(),
1400                });
1401            }
1402        };
1403        #[cfg(feature = "fault-injection")]
1404        {
1405            let exec_ctx = self.exec_ctx.as_ref();
1406            let flow_id = exec_ctx
1407                .map(|ctx| ctx.flow_id.as_str())
1408                .unwrap_or("unknown");
1409            let node_id = exec_ctx.and_then(|ctx| ctx.node_id.as_deref());
1410            let attempt = exec_ctx.map(|ctx| ctx.tenant.attempt).unwrap_or(1);
1411            let fault_ctx = FaultContext {
1412                pack_id: self.pack_id.as_str(),
1413                flow_id,
1414                node_id,
1415                attempt,
1416            };
1417            if let Err(err) = maybe_fail(FaultPoint::StateRead, fault_ctx) {
1418                return Err(StateError {
1419                    code: "internal".into(),
1420                    message: err.to_string(),
1421                });
1422            }
1423        }
1424        let key = StoreStateKey::from(key);
1425        match store.get_json(&tenant_ctx, STATE_PREFIX, &key, None) {
1426            Ok(Some(value)) => state_bytes_from_value(&value).map_err(|err| StateError {
1427                code: "internal".into(),
1428                message: format!("failed to encode stored state value: {err}"),
1429            }),
1430            Ok(None) => Err(StateError {
1431                code: "not_found".into(),
1432                message: "state key not found".into(),
1433            }),
1434            Err(err) => Err(StateError {
1435                code: "internal".into(),
1436                message: err.to_string(),
1437            }),
1438        }
1439    }
1440
1441    fn write(
1442        &mut self,
1443        key: HostStateKey,
1444        bytes: Vec<u8>,
1445        ctx: Option<StateTenantCtx>,
1446    ) -> Result<StateOpAck, StateError> {
1447        if let Err(message) = crate::wasm_limits::check_size(
1448            "state value",
1449            bytes.len(),
1450            crate::wasm_limits::state_max_value_bytes(),
1451        ) {
1452            return Err(StateError {
1453                code: "too-large".into(),
1454                message,
1455            });
1456        }
1457        let store = match self.state_store.as_ref() {
1458            Some(store) => store.clone(),
1459            None => {
1460                return Err(StateError {
1461                    code: "unavailable".into(),
1462                    message: "state store not configured".into(),
1463                });
1464            }
1465        };
1466        let tenant_ctx = match self.tenant_ctx_from_v1(ctx) {
1467            Ok(ctx) => ctx,
1468            Err(err) => {
1469                return Err(StateError {
1470                    code: "invalid-ctx".into(),
1471                    message: err.to_string(),
1472                });
1473            }
1474        };
1475        #[cfg(feature = "fault-injection")]
1476        {
1477            let exec_ctx = self.exec_ctx.as_ref();
1478            let flow_id = exec_ctx
1479                .map(|ctx| ctx.flow_id.as_str())
1480                .unwrap_or("unknown");
1481            let node_id = exec_ctx.and_then(|ctx| ctx.node_id.as_deref());
1482            let attempt = exec_ctx.map(|ctx| ctx.tenant.attempt).unwrap_or(1);
1483            let fault_ctx = FaultContext {
1484                pack_id: self.pack_id.as_str(),
1485                flow_id,
1486                node_id,
1487                attempt,
1488            };
1489            if let Err(err) = maybe_fail(FaultPoint::StateWrite, fault_ctx) {
1490                return Err(StateError {
1491                    code: "internal".into(),
1492                    message: err.to_string(),
1493                });
1494            }
1495        }
1496        let key = StoreStateKey::from(key);
1497        let value = state_value_from_bytes(&bytes);
1498        match store.set_json(&tenant_ctx, STATE_PREFIX, &key, None, &value, None) {
1499            Ok(()) => Ok(StateOpAck::Ok),
1500            Err(err) => Err(StateError {
1501                code: "internal".into(),
1502                message: err.to_string(),
1503            }),
1504        }
1505    }
1506
1507    fn delete(
1508        &mut self,
1509        key: HostStateKey,
1510        ctx: Option<StateTenantCtx>,
1511    ) -> Result<StateOpAck, StateError> {
1512        let store = match self.state_store.as_ref() {
1513            Some(store) => store.clone(),
1514            None => {
1515                return Err(StateError {
1516                    code: "unavailable".into(),
1517                    message: "state store not configured".into(),
1518                });
1519            }
1520        };
1521        let tenant_ctx = match self.tenant_ctx_from_v1(ctx) {
1522            Ok(ctx) => ctx,
1523            Err(err) => {
1524                return Err(StateError {
1525                    code: "invalid-ctx".into(),
1526                    message: err.to_string(),
1527                });
1528            }
1529        };
1530        let key = StoreStateKey::from(key);
1531        match store.del(&tenant_ctx, STATE_PREFIX, &key) {
1532            Ok(_) => Ok(StateOpAck::Ok),
1533            Err(err) => Err(StateError {
1534                code: "internal".into(),
1535                message: err.to_string(),
1536            }),
1537        }
1538    }
1539}
1540
1541/// Marker key of the envelope used to store state values that are neither JSON
1542/// nor valid UTF-8, so the original bytes survive a write/read round trip.
1543const STATE_BYTES_ENVELOPE_KEY: &str = "$greentic_bytes_b64";
1544
1545/// Convert guest state bytes to the JSON value persisted by the state store.
1546///
1547/// JSON documents are stored as-is, other UTF-8 text as a JSON string (legacy
1548/// behaviour), and arbitrary binary as a base64 envelope (never lossy).
1549fn state_value_from_bytes(bytes: &[u8]) -> Value {
1550    if let Ok(value) = serde_json::from_slice::<Value>(bytes) {
1551        return value;
1552    }
1553    match std::str::from_utf8(bytes) {
1554        Ok(text) => Value::String(text.to_string()),
1555        Err(_) => {
1556            use base64::Engine as _;
1557            let mut envelope = serde_json::Map::new();
1558            envelope.insert(
1559                STATE_BYTES_ENVELOPE_KEY.to_string(),
1560                Value::String(base64::engine::general_purpose::STANDARD.encode(bytes)),
1561            );
1562            Value::Object(envelope)
1563        }
1564    }
1565}
1566
1567/// Inverse of [`state_value_from_bytes`] for reads.
1568fn state_bytes_from_value(value: &Value) -> Result<Vec<u8>, String> {
1569    if let Value::Object(map) = value
1570        && map.len() == 1
1571        && let Some(Value::String(encoded)) = map.get(STATE_BYTES_ENVELOPE_KEY)
1572    {
1573        use base64::Engine as _;
1574        return base64::engine::general_purpose::STANDARD
1575            .decode(encoded)
1576            .map_err(|err| format!("invalid binary state envelope: {err}"));
1577    }
1578    serde_json::to_vec(value).map_err(|err| err.to_string())
1579}
1580
1581/// `StateStore::set_json_if_absent` reports a backend that has no atomic
1582/// implementation as `InvalidInput` with this message; surface it as a stable
1583/// `unsupported` code instead of a generic failure.
1584const UNSUPPORTED_IF_ABSENT_MARKER: &str = "set_json_if_absent is not supported";
1585
1586fn state_error_from_if_absent(err: greentic_types::GreenticError) -> StateError {
1587    let code = if err.code == greentic_types::ErrorCode::InvalidInput
1588        && err.message.contains(UNSUPPORTED_IF_ABSENT_MARKER)
1589    {
1590        "unsupported"
1591    } else if err.code == greentic_types::ErrorCode::Unavailable {
1592        "unavailable"
1593    } else {
1594        "internal"
1595    };
1596    StateError {
1597        code: code.into(),
1598        message: err.to_string(),
1599    }
1600}
1601
1602impl HostState {
1603    /// Shared body of `write-if-absent`: same tenant derivation, fault hook,
1604    /// prefix and bytes-to-JSON conversion as `StateStoreHost::write`.
1605    fn state_write_if_absent(
1606        &mut self,
1607        key: HostStateKey,
1608        bytes: Vec<u8>,
1609        ctx: Option<StateTenantCtx>,
1610    ) -> Result<bool, StateError> {
1611        if let Err(message) = crate::wasm_limits::check_size(
1612            "state value",
1613            bytes.len(),
1614            crate::wasm_limits::state_max_value_bytes(),
1615        ) {
1616            return Err(StateError {
1617                code: "too-large".into(),
1618                message,
1619            });
1620        }
1621        let store = match self.state_store.as_ref() {
1622            Some(store) => store.clone(),
1623            None => {
1624                return Err(StateError {
1625                    code: "unavailable".into(),
1626                    message: "state store not configured".into(),
1627                });
1628            }
1629        };
1630        let tenant_ctx = match self.tenant_ctx_from_v1(ctx) {
1631            Ok(ctx) => ctx,
1632            Err(err) => {
1633                return Err(StateError {
1634                    code: "invalid-ctx".into(),
1635                    message: err.to_string(),
1636                });
1637            }
1638        };
1639        #[cfg(feature = "fault-injection")]
1640        {
1641            let exec_ctx = self.exec_ctx.as_ref();
1642            let flow_id = exec_ctx
1643                .map(|ctx| ctx.flow_id.as_str())
1644                .unwrap_or("unknown");
1645            let node_id = exec_ctx.and_then(|ctx| ctx.node_id.as_deref());
1646            let attempt = exec_ctx.map(|ctx| ctx.tenant.attempt).unwrap_or(1);
1647            let fault_ctx = FaultContext {
1648                pack_id: self.pack_id.as_str(),
1649                flow_id,
1650                node_id,
1651                attempt,
1652            };
1653            if let Err(err) = maybe_fail(FaultPoint::StateWrite, fault_ctx) {
1654                return Err(StateError {
1655                    code: "internal".into(),
1656                    message: err.to_string(),
1657                });
1658            }
1659        }
1660        let key = StoreStateKey::from(key);
1661        let value = state_value_from_bytes(&bytes);
1662        store
1663            .set_json_if_absent(&tenant_ctx, STATE_PREFIX, &key, &value, None)
1664            .map_err(state_error_from_if_absent)
1665    }
1666}
1667
1668fn state_ctx_v1_from_v1_1(ctx: StateTenantCtxV1_1) -> StateTenantCtx {
1669    StateTenantCtx {
1670        env: ctx.env,
1671        tenant: ctx.tenant,
1672        tenant_id: ctx.tenant_id,
1673        team: ctx.team,
1674        team_id: ctx.team_id,
1675        user: ctx.user,
1676        user_id: ctx.user_id,
1677        trace_id: ctx.trace_id,
1678        i18n_id: ctx.i18n_id,
1679        correlation_id: ctx.correlation_id,
1680        attributes: ctx.attributes,
1681        session_id: ctx.session_id,
1682        flow_id: ctx.flow_id,
1683        node_id: ctx.node_id,
1684        provider_id: ctx.provider_id,
1685        deadline_ms: ctx.deadline_ms,
1686        attempt: ctx.attempt,
1687        idempotency_key: ctx.idempotency_key,
1688        impersonation: ctx.impersonation.map(|imp| {
1689            greentic_interfaces_wasmtime::state_store_store_v1_0::greentic::interfaces_types::types::Impersonation {
1690                actor_id: imp.actor_id,
1691                reason: imp.reason,
1692            }
1693        }),
1694    }
1695}
1696
1697fn state_error_v1_1(err: StateError) -> StateErrorV1_1 {
1698    StateErrorV1_1 {
1699        code: err.code,
1700        message: err.message,
1701    }
1702}
1703
1704/// `greentic:state/state-store@1.1.0`: the same read/write/delete as 1.0.0
1705/// (delegated, so tenant derivation, fault hooks and byte conversion cannot
1706/// drift) plus the atomic `write-if-absent`.
1707impl StateStoreHostV1_1 for HostState {
1708    fn read(
1709        &mut self,
1710        key: HostStateKey,
1711        ctx: Option<StateTenantCtxV1_1>,
1712    ) -> Result<Vec<u8>, StateErrorV1_1> {
1713        StateStoreHost::read(self, key, ctx.map(state_ctx_v1_from_v1_1)).map_err(state_error_v1_1)
1714    }
1715
1716    fn write(
1717        &mut self,
1718        key: HostStateKey,
1719        bytes: Vec<u8>,
1720        ctx: Option<StateTenantCtxV1_1>,
1721    ) -> Result<StateOpAckV1_1, StateErrorV1_1> {
1722        StateStoreHost::write(self, key, bytes, ctx.map(state_ctx_v1_from_v1_1))
1723            .map(|_| StateOpAckV1_1::Ok)
1724            .map_err(state_error_v1_1)
1725    }
1726
1727    fn delete(
1728        &mut self,
1729        key: HostStateKey,
1730        ctx: Option<StateTenantCtxV1_1>,
1731    ) -> Result<StateOpAckV1_1, StateErrorV1_1> {
1732        StateStoreHost::delete(self, key, ctx.map(state_ctx_v1_from_v1_1))
1733            .map(|_| StateOpAckV1_1::Ok)
1734            .map_err(state_error_v1_1)
1735    }
1736
1737    fn write_if_absent(
1738        &mut self,
1739        key: HostStateKey,
1740        bytes: Vec<u8>,
1741        ctx: Option<StateTenantCtxV1_1>,
1742    ) -> Result<bool, StateErrorV1_1> {
1743        self.state_write_if_absent(key, bytes, ctx.map(state_ctx_v1_from_v1_1))
1744            .map_err(state_error_v1_1)
1745    }
1746}
1747
1748/// Cap on guest telemetry fields re-emitted per log call.
1749const MAX_TELEMETRY_FIELDS: usize = 64;
1750
1751impl TelemetryLoggerHost for HostState {
1752    fn log(
1753        &mut self,
1754        span: TelemetrySpanContext,
1755        fields: Vec<(String, String)>,
1756        _ctx: Option<TelemetryTenantCtx>,
1757    ) -> Result<TelemetryAck, TelemetryError> {
1758        if let Some(mock) = &self.mocks
1759            && mock.telemetry_drain(&[("span_json", span.flow_id.as_str())])
1760        {
1761            return Ok(TelemetryAck::Ok);
1762        }
1763        // Everything in `span` and `fields` is guest-claimed. The tenant the
1764        // host actually bound is logged beside it; guest text is sanitised
1765        // and bounded so it cannot forge log lines or flood the log.
1766        let mut map = serde_json::Map::new();
1767        for (k, v) in fields.into_iter().take(MAX_TELEMETRY_FIELDS) {
1768            let k = crate::log_safe::log_safe_max(&k, 128).into_owned();
1769            let v = crate::log_safe::log_safe_max(&v, 1024).into_owned();
1770            map.insert(k, Value::String(v));
1771        }
1772        tracing::info!(
1773            host_tenant = %self.config.tenant,
1774            guest_tenant = %crate::log_safe::log_safe(&span.tenant),
1775            flow_id = %crate::log_safe::log_safe(&span.flow_id),
1776            node = ?span.node_id.as_deref().map(crate::log_safe::log_safe),
1777            provider = %crate::log_safe::log_safe(&span.provider),
1778            fields = %serde_json::Value::Object(map),
1779            "telemetry log from pack"
1780        );
1781        Ok(TelemetryAck::Ok)
1782    }
1783}
1784
1785impl RunnerHostHttp for HostState {
1786    fn request(
1787        &mut self,
1788        method: String,
1789        url: String,
1790        headers: Vec<String>,
1791        body: Option<Vec<u8>>,
1792    ) -> Result<Vec<u8>, String> {
1793        let req = HttpRequest {
1794            method,
1795            url,
1796            headers: headers
1797                .chunks(2)
1798                .filter_map(|chunk| {
1799                    if chunk.len() == 2 {
1800                        Some((chunk[0].clone(), chunk[1].clone()))
1801                    } else {
1802                        None
1803                    }
1804                })
1805                .collect(),
1806            body,
1807        };
1808        match HttpClientHost::send(self, req, None) {
1809            Ok(resp) => Ok(resp.body.unwrap_or_default()),
1810            Err(err) => Err(err.message),
1811        }
1812    }
1813}
1814
1815impl RunnerHostKv for HostState {
1816    fn get(&mut self, _ns: String, _key: String) -> Option<String> {
1817        None
1818    }
1819
1820    fn put(&mut self, _ns: String, _key: String, _val: String) {}
1821}
1822
1823impl OAuthBrokerHostTrait for HostState {
1824    /// Returns an access-token JSON string (`{"access_token":…,"expires_at":…}`) for the given
1825    /// provider and scopes, or an empty string on error.
1826    ///
1827    /// `subject` is informational for MVP — tenant, env, and team are taken from the host context
1828    /// (config + default_env + oauth_config.team), NOT derived from `subject`.
1829    fn get_token(
1830        &mut self,
1831        provider_id: wasmtime::component::__internal::String,
1832        _subject: wasmtime::component::__internal::String,
1833        scopes: wasmtime::component::__internal::Vec<wasmtime::component::__internal::String>,
1834    ) -> wasmtime::component::__internal::String {
1835        let Some(cfg) = self.oauth_config.clone() else {
1836            return String::new();
1837        };
1838        let req = ResourceTokenRequest {
1839            http_base_url: cfg.http_base_url,
1840            env: self.default_env.clone(),
1841            tenant: self.config.tenant.clone(),
1842            team: cfg.team.clone(),
1843            resource_id: provider_id.to_string(),
1844            scopes: scopes.into_iter().collect(),
1845        };
1846        match crate::oauth::request_resource_token_blocking(
1847            &self.http_client,
1848            &req,
1849            cfg.shared_secret.as_deref(),
1850        ) {
1851            Ok(resp) => serde_json::to_string(&resp).unwrap_or_default(),
1852            Err(e) => {
1853                tracing::warn!(
1854                    provider = %provider_id,
1855                    error = %e,
1856                    "oauth get-token proxy failed"
1857                );
1858                String::new()
1859            }
1860        }
1861    }
1862
1863    /// Operator-time only — OAuth consent URL generation happens in the admin UI, not at runtime.
1864    fn get_consent_url(
1865        &mut self,
1866        _provider_id: wasmtime::component::__internal::String,
1867        _subject: wasmtime::component::__internal::String,
1868        _scopes: wasmtime::component::__internal::Vec<wasmtime::component::__internal::String>,
1869        _redirect_path: wasmtime::component::__internal::String,
1870        _extra_json: wasmtime::component::__internal::String,
1871    ) -> wasmtime::component::__internal::String {
1872        String::new()
1873    }
1874
1875    /// Operator-time only — OAuth code exchange happens in the admin UI, not at runtime.
1876    fn exchange_code(
1877        &mut self,
1878        _provider_id: wasmtime::component::__internal::String,
1879        _subject: wasmtime::component::__internal::String,
1880        _code: wasmtime::component::__internal::String,
1881        _redirect_path: wasmtime::component::__internal::String,
1882    ) -> wasmtime::component::__internal::String {
1883        String::new()
1884    }
1885}
1886
1887enum ManifestLoad {
1888    New {
1889        manifest: Box<greentic_types::PackManifest>,
1890        flows: PackFlows,
1891    },
1892    Legacy {
1893        manifest: Box<legacy_pack::PackManifest>,
1894        flows: PackFlows,
1895    },
1896}
1897
1898fn load_manifest_and_flows(path: &Path) -> Result<ManifestLoad> {
1899    let mut archive = ZipArchive::new(File::open(path)?)
1900        .with_context(|| format!("{} is not a valid gtpack", path.display()))?;
1901    let bytes = read_entry(&mut archive, "manifest.cbor")
1902        .with_context(|| format!("missing manifest.cbor in {}", path.display()))?;
1903    match decode_pack_manifest(&bytes) {
1904        Ok(manifest) => {
1905            let cache = PackFlows::from_manifest(manifest.clone());
1906            Ok(ManifestLoad::New {
1907                manifest: Box::new(manifest),
1908                flows: cache,
1909            })
1910        }
1911        Err(err) => {
1912            tracing::debug!(
1913                error = %err,
1914                pack = %path.display(),
1915                "decode_pack_manifest failed for archive; falling back to legacy manifest"
1916            );
1917            let legacy: legacy_pack::PackManifest = serde_cbor::from_slice(&bytes)
1918                .context("failed to decode legacy pack manifest from manifest.cbor")?;
1919            let flows = load_legacy_flows_from_archive(&mut archive, &legacy)?;
1920            Ok(ManifestLoad::Legacy {
1921                manifest: Box::new(legacy),
1922                flows,
1923            })
1924        }
1925    }
1926}
1927
1928fn load_manifest_and_flows_from_dir(root: &Path) -> Result<ManifestLoad> {
1929    let manifest_path = root.join("manifest.cbor");
1930    let bytes = std::fs::read(&manifest_path)
1931        .with_context(|| format!("missing manifest.cbor in {}", root.display()))?;
1932    match decode_pack_manifest(&bytes) {
1933        Ok(manifest) => {
1934            let cache = PackFlows::from_manifest(manifest.clone());
1935            Ok(ManifestLoad::New {
1936                manifest: Box::new(manifest),
1937                flows: cache,
1938            })
1939        }
1940        Err(err) => {
1941            tracing::debug!(
1942                error = %err,
1943                pack = %root.display(),
1944                "decode_pack_manifest failed for materialized pack; trying legacy manifest"
1945            );
1946            let legacy: legacy_pack::PackManifest = serde_cbor::from_slice(&bytes)
1947                .context("failed to decode legacy pack manifest from manifest.cbor")?;
1948            let flows = load_legacy_flows_from_dir(root, &legacy)?;
1949            Ok(ManifestLoad::Legacy {
1950                manifest: Box::new(legacy),
1951                flows,
1952            })
1953        }
1954    }
1955}
1956
1957fn load_legacy_flows_from_dir(
1958    root: &Path,
1959    manifest: &legacy_pack::PackManifest,
1960) -> Result<PackFlows> {
1961    build_legacy_flows(manifest, |rel_path| {
1962        let path = root.join(rel_path);
1963        std::fs::read(&path).with_context(|| format!("missing flow json {}", path.display()))
1964    })
1965}
1966
1967fn load_legacy_flows_from_archive(
1968    archive: &mut ZipArchive<File>,
1969    manifest: &legacy_pack::PackManifest,
1970) -> Result<PackFlows> {
1971    build_legacy_flows(manifest, |rel_path| {
1972        read_entry(archive, rel_path).with_context(|| format!("missing flow json {}", rel_path))
1973    })
1974}
1975
1976fn build_legacy_flows(
1977    manifest: &legacy_pack::PackManifest,
1978    mut read_json: impl FnMut(&str) -> Result<Vec<u8>>,
1979) -> Result<PackFlows> {
1980    let mut flows = HashMap::new();
1981    let mut descriptors = Vec::new();
1982
1983    for entry in &manifest.flows {
1984        let bytes = read_json(&entry.file_json)
1985            .with_context(|| format!("missing flow json {}", entry.file_json))?;
1986        let doc = parse_flow_doc_with_legacy_aliases(&bytes)?;
1987        let normalized = normalize_flow_doc(doc);
1988        let flow_ir = flow_doc_to_ir(normalized)?;
1989        let flow = flow_ir_to_flow(flow_ir)?;
1990
1991        descriptors.push(FlowDescriptor {
1992            id: entry.id.clone(),
1993            flow_type: entry.kind.clone(),
1994            pack_id: manifest.meta.pack_id.clone(),
1995            profile: manifest.meta.pack_id.clone(),
1996            version: manifest.meta.version.to_string(),
1997            description: None,
1998            // Legacy manifests carry no flow tags; treat every flow as an
1999            // entrypoint, matching prior behaviour.
2000            entry: true,
2001        });
2002        flows.insert(entry.id.clone(), flow);
2003    }
2004
2005    let mut entry_flows = manifest.meta.entry_flows.clone();
2006    if entry_flows.is_empty() {
2007        entry_flows = manifest.flows.iter().map(|f| f.id.clone()).collect();
2008    }
2009    let metadata = PackMetadata {
2010        pack_id: manifest.meta.pack_id.clone(),
2011        version: manifest.meta.version.to_string(),
2012        entry_flows,
2013        secret_requirements: Vec::new(),
2014    };
2015
2016    Ok(PackFlows {
2017        descriptors,
2018        flows,
2019        metadata,
2020    })
2021}
2022
2023fn parse_flow_doc_with_legacy_aliases(bytes: &[u8]) -> Result<FlowDoc> {
2024    let mut value: Value =
2025        serde_json::from_slice(bytes).context("failed to decode flow doc JSON")?;
2026    if let Some(map) = value.as_object_mut()
2027        && !map.contains_key("type")
2028        && let Some(flow_type) = map.remove("flow_type")
2029    {
2030        map.insert("type".to_string(), flow_type);
2031    }
2032    serde_json::from_value(value).context("failed to decode flow doc structure")
2033}
2034
2035pub struct ComponentState {
2036    pub host: HostState,
2037    wasi_ctx: WasiCtx,
2038    wasi_tls_ctx: WasiTlsCtx,
2039    wasi_http_ctx: WasiHttpCtx,
2040    http_timeout_hooks: crate::http_guard::GuardedHooks,
2041    resource_table: ResourceTable,
2042    wasm_limits: crate::wasm_limits::WasmLimits,
2043    store_limits: crate::wasm_limits::GuestLimiter,
2044}
2045
2046/// Resolve the guest's requested `timeout-ms` against the host ceiling.
2047/// Absent or zero keeps the client default (`None`); anything else is
2048/// clamped so a guest cannot extend the default into an unbounded host call.
2049pub(crate) fn guest_timeout(requested_ms: Option<u32>, ceiling: Duration) -> Option<Duration> {
2050    match requested_ms {
2051        None | Some(0) => None,
2052        Some(ms) => Some(Duration::from_millis(u64::from(ms)).min(ceiling)),
2053    }
2054}
2055
2056/// Create the per-invocation store: memory/table/instance limiter plus a fresh
2057/// epoch deadline (see [`crate::wasm_limits`]).
2058fn new_limited_store(engine: &Engine, state: ComponentState) -> wasmtime::Store<ComponentState> {
2059    let limits = state.wasm_limits;
2060    let mut store = wasmtime::Store::new(engine, state);
2061    store.limiter(|state| &mut state.store_limits);
2062    crate::wasm_limits::arm_deadline(&mut store, &limits);
2063    store
2064}
2065
2066/// Install the process-default rustls [`rustls::crypto::CryptoProvider`] exactly once.
2067///
2068/// `wasmtime-wasi-tls` 45's `RustlsProvider::default()` builds its
2069/// `rustls::ClientConfig` via `ClientConfig::builder()`, which resolves the
2070/// process-default provider. Our dependency graph enables BOTH the `ring` and
2071/// `aws_lc_rs` rustls backends, so there is no unambiguous implicit default and
2072/// the builder panics ("no process-level CryptoProvider available") the first
2073/// time [`WasiTlsCtxBuilder::build`] constructs the default provider. Install
2074/// the workspace-selected aws-lc-rs provider before that ever happens.
2075/// Idempotent: a returned `Err` means a default was already installed.
2076fn install_default_crypto_provider() {
2077    static ONCE: std::sync::Once = std::sync::Once::new();
2078    ONCE.call_once(|| {
2079        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
2080    });
2081}
2082
2083impl ComponentState {
2084    pub fn new(host: HostState, policy: Arc<RunnerWasiPolicy>) -> Result<Self> {
2085        // Must run before `WasiTlsCtxBuilder::build()` below, which eagerly
2086        // constructs wasi-tls's default rustls provider.
2087        install_default_crypto_provider();
2088        let wasi_ctx = policy
2089            .instantiate()
2090            .context("failed to build WASI context")?;
2091        let wasm_limits = crate::wasm_limits::WasmLimits::from_env();
2092        let http_enabled = host.config.http_enabled;
2093        Ok(Self {
2094            host,
2095            wasi_ctx,
2096            wasi_tls_ctx: WasiTlsCtxBuilder::new().build(),
2097            wasi_http_ctx: WasiHttpCtx::new(),
2098            http_timeout_hooks: crate::http_guard::GuardedHooks::from_env(http_enabled),
2099            resource_table: ResourceTable::new(),
2100            wasm_limits,
2101            store_limits: wasm_limits.store_limits(),
2102        })
2103    }
2104
2105    fn host_mut(&mut self) -> &mut HostState {
2106        &mut self.host
2107    }
2108
2109    fn should_cancel_host(&mut self) -> bool {
2110        false
2111    }
2112
2113    fn yield_now_host(&mut self) {
2114        // no-op cooperative yield
2115    }
2116}
2117
2118impl component_api::v0_4::greentic::component::control::Host for ComponentState {
2119    fn should_cancel(&mut self) -> bool {
2120        self.should_cancel_host()
2121    }
2122
2123    fn yield_now(&mut self) {
2124        self.yield_now_host();
2125    }
2126}
2127
2128impl component_api::v0_5::greentic::component::control::Host for ComponentState {
2129    fn should_cancel(&mut self) -> bool {
2130        self.should_cancel_host()
2131    }
2132
2133    fn yield_now(&mut self) {
2134        self.yield_now_host();
2135    }
2136}
2137
2138fn add_component_control_instance(
2139    linker: &mut Linker<ComponentState>,
2140    name: &str,
2141) -> wasmtime::Result<()> {
2142    let mut inst = linker.instance(name)?;
2143    inst.func_wrap(
2144        "should-cancel",
2145        |mut caller: StoreContextMut<'_, ComponentState>, (): ()| {
2146            let host = caller.data_mut();
2147            Ok((host.should_cancel_host(),))
2148        },
2149    )?;
2150    inst.func_wrap(
2151        "yield-now",
2152        |mut caller: StoreContextMut<'_, ComponentState>, (): ()| {
2153            let host = caller.data_mut();
2154            host.yield_now_host();
2155            Ok(())
2156        },
2157    )?;
2158    Ok(())
2159}
2160
2161fn add_component_control_to_linker(linker: &mut Linker<ComponentState>) -> wasmtime::Result<()> {
2162    add_component_control_instance(linker, "greentic:component/control@0.5.0")?;
2163    add_component_control_instance(linker, "greentic:component/control@0.4.0")?;
2164    Ok(())
2165}
2166
2167/// Reduced-authority linker for `identify-instance` and
2168/// `describe-identify-instance` probes (M1 IID Phase D).
2169///
2170/// Identity probes match an inbound webhook payload against known
2171/// per-endpoint discriminators (Telegram secret-token header, Slack
2172/// signing-secret, Teams JWT issuer, …) and return an endpoint id
2173/// or `none`. The WIT contract is a pure projection over `(headers,
2174/// body)` — no outbound HTTP, no persistent state, no secrets.
2175///
2176/// # Why this delegates to `register_all` (Wasmtime eager-import constraint)
2177///
2178/// Wasmtime's [`Linker::instantiate_pre`] type-checks the component's
2179/// **entire** import graph eagerly — not just the imports reachable from
2180/// the export the caller intends to invoke. A provider component that
2181/// exports `instance-identity-api` alongside `schema-core-api` typically
2182/// also imports `http-client`, `secrets-store`, etc. for the latter.
2183/// If the linker omits those imports, `instantiate_pre` fails with
2184/// `"a matching implementation was not found in the linker"` before the
2185/// identity export is even checked.
2186///
2187/// The ideal probe linker would register deny-shim handlers that satisfy
2188/// the import graph but trap on actual invocation. That requires
2189/// deny-shim support in `greentic-interfaces-wasmtime` (tracked as a
2190/// follow-up). Until then, probes use the same linker surface as normal
2191/// execution, with state-store disabled.
2192///
2193/// The reduced-authority boundary is enforced at the WASI policy layer
2194/// instead: probe call sites construct a locked-down
2195/// [`RunnerWasiPolicy`](crate::wasi::RunnerWasiPolicy) with no
2196/// preopens, no env passthrough, and no stdio inheritance. See
2197/// [`RunnerWasiPolicy::probe()`](crate::wasi::RunnerWasiPolicy::probe)
2198/// and the `probe_wasi_policy_is_locked_down` test.
2199pub fn register_identity_probe(linker: &mut Linker<ComponentState>) -> Result<()> {
2200    // Delegates to `register_all` with state-store disabled. See doc
2201    // comment above for the rationale (Wasmtime eager-import validation).
2202    register_all(linker, false)
2203}
2204
2205#[cfg(test)]
2206mod register_identity_probe_tests {
2207    use super::*;
2208
2209    /// Verify that [`register_identity_probe`] successfully links all
2210    /// imports needed by real provider components (wasi-core, wasi-tls,
2211    /// wasi-http, http-client, secrets-store, telemetry, etc.).
2212    ///
2213    /// Before this fix, the probe linker omitted most host imports.
2214    /// Wasmtime's `instantiate_pre` validates the **entire** import
2215    /// graph eagerly, so any provider with runtime imports (all real
2216    /// providers) would fail before the identity export was checked.
2217    #[test]
2218    fn register_identity_probe_links_successfully() {
2219        let engine = wasmtime::Engine::default();
2220        let mut linker = Linker::<ComponentState>::new(&engine);
2221        register_identity_probe(&mut linker).expect("probe linker registers all imports");
2222    }
2223
2224    /// Verify that the probe WASI policy has no preopens, no env, and
2225    /// no stdio — the only reduced-authority boundary available today.
2226    #[test]
2227    fn probe_wasi_policy_is_locked_down() {
2228        let policy = RunnerWasiPolicy::probe();
2229        assert!(!policy.inherit_stdio, "probe WASI must not inherit stdio");
2230        assert!(
2231            policy.preopens.is_empty(),
2232            "probe WASI must have no preopens"
2233        );
2234        assert!(
2235            policy.env_allow.is_empty(),
2236            "probe WASI must not allow env vars"
2237        );
2238        assert!(
2239            policy.env_set.is_empty(),
2240            "probe WASI must not set env vars"
2241        );
2242    }
2243}
2244
2245pub fn register_all(linker: &mut Linker<ComponentState>, allow_state_store: bool) -> Result<()> {
2246    install_default_crypto_provider();
2247
2248    add_wasi_to_linker(linker)?;
2249
2250    // Add wasi-tls types and turn on the feature in linker
2251    let mut opts = LinkOptions::default();
2252    opts.tls(true);
2253    add_wasi_tls_to_linker(linker, &opts)?;
2254
2255    // Add wasi-http types and turn on the feature in linker
2256    add_wasi_http_to_linker(linker)?;
2257
2258    add_all_v1_to_linker(
2259        linker,
2260        HostFns {
2261            http_client_v1_1: Some(|state: &mut ComponentState| state.host_mut()),
2262            http_client: Some(|state: &mut ComponentState| state.host_mut()),
2263            oauth_broker: Some(|state: &mut ComponentState| state.host_mut()),
2264            runner_host_http: Some(|state: &mut ComponentState| state.host_mut()),
2265            runner_host_kv: Some(|state: &mut ComponentState| state.host_mut()),
2266            telemetry_logger: Some(|state: &mut ComponentState| state.host_mut()),
2267            // The v1.1 helper registers BOTH `state-store@1.1.0` and `@1.0.0` from
2268            // one host impl, so the legacy field stays `None` (it is ignored when
2269            // v1.1 is set and would otherwise read as a double registration).
2270            state_store_v1_1: allow_state_store
2271                .then_some(|state: &mut ComponentState| state.host_mut()),
2272            state_store: None,
2273            // Registered below by `add_secrets_store_to_linker` so a refused
2274            // `put` traps the guest instead of panicking the host.
2275            secrets_store_v1_1: None,
2276            secrets_store: None,
2277            runtime_config: Some(|state: &mut ComponentState| state.host_mut()),
2278        },
2279    )?;
2280    add_secrets_store_to_linker(linker)?;
2281    add_http_client_client_world_aliases(linker)?;
2282    add_telemetry_logging_stub(linker)?;
2283    Ok(())
2284}
2285
2286/// Some generated MCP components import `greentic:telemetry/logging` for guest
2287/// instrumentation (it's baked in by the generator's telemetry wiring). The
2288/// runner emits its own telemetry via the native pipeline and does not consume
2289/// these guest events, so we satisfy the import with no-ops — otherwise such a
2290/// component fails to instantiate ("matching implementation was not found in the
2291/// linker"). Registered dynamically (`func_new`) so we don't need generated
2292/// bindings for the interface; the signature is resolved at instantiation.
2293fn add_telemetry_logging_stub(linker: &mut Linker<ComponentState>) -> Result<()> {
2294    let mut inst = match linker.instance("greentic:telemetry/logging") {
2295        Ok(inst) => inst,
2296        // Already defined by another registration path — nothing to do.
2297        Err(_) => return Ok(()),
2298    };
2299    // log: func(lvl: level, message: string, fields: fields)
2300    inst.func_new("log", |_store, _ty, _params, _results| Ok(()))?;
2301    // span-start: func(name: string, fields: fields) -> u64
2302    inst.func_new("span-start", |_store, _ty, _params, results| {
2303        if let Some(slot) = results.get_mut(0) {
2304            *slot = wasmtime::component::Val::U64(0);
2305        }
2306        Ok(())
2307    })?;
2308    // span-end: func(id: u64)
2309    inst.func_new("span-end", |_store, _ty, _params, _results| Ok(()))?;
2310    Ok(())
2311}
2312
2313fn add_http_client_client_world_aliases(linker: &mut Linker<ComponentState>) -> Result<()> {
2314    let mut inst_v1_1 = linker.instance("greentic:http/client@1.1.0")?;
2315    inst_v1_1.func_wrap(
2316        "send",
2317        move |mut caller: StoreContextMut<'_, ComponentState>,
2318              (req, opts, ctx): (
2319            http_client_client_alias::Request,
2320            Option<http_client_client_alias::RequestOptions>,
2321            Option<http_client_client_alias::TenantCtx>,
2322        )| {
2323            let host = caller.data_mut().host_mut();
2324            let result = HttpClientHostV1_1::send(
2325                host,
2326                alias_request_to_host(req),
2327                opts.map(alias_request_options_to_host),
2328                ctx.map(alias_tenant_ctx_to_host),
2329            );
2330            Ok((match result {
2331                Ok(resp) => Ok(alias_response_from_host(resp)),
2332                Err(err) => Err(alias_error_from_host(err)),
2333            },))
2334        },
2335    )?;
2336    let mut inst_v1_0 = linker.instance("greentic:http/client@1.0.0")?;
2337    inst_v1_0.func_wrap(
2338        "send",
2339        move |mut caller: StoreContextMut<'_, ComponentState>,
2340              (req, ctx): (
2341            host_http_client::Request,
2342            Option<host_http_client::TenantCtx>,
2343        )| {
2344            let host = caller.data_mut().host_mut();
2345            let result = HttpClientHost::send(host, req, ctx);
2346            Ok((result,))
2347        },
2348    )?;
2349    Ok(())
2350}
2351
2352fn alias_request_to_host(req: http_client_client_alias::Request) -> host_http_client::RequestV1_1 {
2353    host_http_client::RequestV1_1 {
2354        method: req.method,
2355        url: req.url,
2356        headers: req.headers,
2357        body: req.body,
2358    }
2359}
2360
2361fn alias_request_options_to_host(
2362    opts: http_client_client_alias::RequestOptions,
2363) -> host_http_client::RequestOptionsV1_1 {
2364    host_http_client::RequestOptionsV1_1 {
2365        timeout_ms: opts.timeout_ms,
2366        allow_insecure: opts.allow_insecure,
2367        follow_redirects: opts.follow_redirects,
2368    }
2369}
2370
2371fn alias_tenant_ctx_to_host(
2372    ctx: http_client_client_alias::TenantCtx,
2373) -> host_http_client::TenantCtxV1_1 {
2374    host_http_client::TenantCtxV1_1 {
2375        env: ctx.env,
2376        tenant: ctx.tenant,
2377        tenant_id: ctx.tenant_id,
2378        team: ctx.team,
2379        team_id: ctx.team_id,
2380        user: ctx.user,
2381        user_id: ctx.user_id,
2382        trace_id: ctx.trace_id,
2383        correlation_id: ctx.correlation_id,
2384        i18n_id: ctx.i18n_id,
2385        attributes: ctx.attributes,
2386        session_id: ctx.session_id,
2387        flow_id: ctx.flow_id,
2388        node_id: ctx.node_id,
2389        provider_id: ctx.provider_id,
2390        deadline_ms: ctx.deadline_ms,
2391        attempt: ctx.attempt,
2392        idempotency_key: ctx.idempotency_key,
2393        impersonation: ctx.impersonation.map(|imp| http_types_v1_1::Impersonation {
2394            actor_id: imp.actor_id,
2395            reason: imp.reason,
2396        }),
2397    }
2398}
2399
2400fn alias_response_from_host(
2401    resp: host_http_client::ResponseV1_1,
2402) -> http_client_client_alias::Response {
2403    http_client_client_alias::Response {
2404        status: resp.status,
2405        headers: resp.headers,
2406        body: resp.body,
2407    }
2408}
2409
2410fn alias_error_from_host(
2411    err: host_http_client::HttpClientErrorV1_1,
2412) -> http_client_client_alias::HostError {
2413    http_client_client_alias::HostError {
2414        code: err.code,
2415        message: err.message,
2416    }
2417}
2418
2419impl WasiView for ComponentState {
2420    fn ctx(&mut self) -> WasiCtxView<'_> {
2421        WasiCtxView {
2422            ctx: &mut self.wasi_ctx,
2423            table: &mut self.resource_table,
2424        }
2425    }
2426}
2427
2428impl WasiHttpView for ComponentState {
2429    fn http(&mut self) -> WasiHttpCtxView<'_> {
2430        WasiHttpCtxView {
2431            ctx: &mut self.wasi_http_ctx,
2432            table: &mut self.resource_table,
2433            hooks: &mut self.http_timeout_hooks,
2434        }
2435    }
2436}
2437
2438impl WasiTlsView for ComponentState {
2439    fn tls(&mut self) -> WasiTlsCtxView<'_> {
2440        WasiTlsCtxView {
2441            ctx: &mut self.wasi_tls_ctx,
2442            table: &mut self.resource_table,
2443        }
2444    }
2445}
2446
2447#[allow(unsafe_code)]
2448unsafe impl Send for ComponentState {}
2449#[allow(unsafe_code)]
2450unsafe impl Sync for ComponentState {}
2451
2452impl PackRuntime {
2453    fn allows_state_store(&self, component_ref: &str) -> bool {
2454        if self.state_store.is_none() {
2455            return false;
2456        }
2457        if !self.config.state_store_policy.allow {
2458            return false;
2459        }
2460        let Some(manifest) = self.component_manifests.get(component_ref) else {
2461            // No manifest entry — allow state-store; Wasmtime rejects if not imported.
2462            return true;
2463        };
2464        // If manifest declares host.state capabilities, honour them.
2465        // If host.state is None (not declared in manifest), default to true so
2466        // components whose CBOR manifest omits the field still get state-store
2467        // linked — Wasmtime will reject at instantiation if not actually imported.
2468        manifest
2469            .capabilities
2470            .host
2471            .state
2472            .as_ref()
2473            .map(|caps| caps.read || caps.write)
2474            .unwrap_or(true)
2475    }
2476
2477    pub fn contains_component(&self, component_ref: &str) -> bool {
2478        self.components.contains_key(component_ref)
2479    }
2480
2481    /// Returns a clonable handle to the pack's state store, when one is
2482    /// configured. Used by the flow engine's built-in `state.get`/`state.set`
2483    /// operators which call into the same store that WASM components read
2484    /// through their `state.read`/`state.write` host imports.
2485    pub fn state_store_handle(&self) -> Option<crate::storage::DynStateStore> {
2486        self.state_store.clone()
2487    }
2488
2489    #[allow(clippy::too_many_arguments)]
2490    pub async fn load(
2491        path: impl AsRef<Path>,
2492        config: Arc<HostConfig>,
2493        mocks: Option<Arc<MockLayer>>,
2494        archive_source: Option<&Path>,
2495        session_store: Option<DynSessionStore>,
2496        state_store: Option<DynStateStore>,
2497        wasi_policy: Arc<RunnerWasiPolicy>,
2498        secrets: DynSecretsManager,
2499        oauth_config: Option<OAuthBrokerConfig>,
2500        verify_archive: bool,
2501        component_resolution: ComponentResolution,
2502    ) -> Result<Self> {
2503        let path = path.as_ref();
2504        let (_pack_root, safe_path) = normalize_pack_path(path)?;
2505        let path_meta = std::fs::metadata(&safe_path).ok();
2506        let is_dir = path_meta
2507            .as_ref()
2508            .map(|meta| meta.is_dir())
2509            .unwrap_or(false);
2510        let is_component = !is_dir
2511            && safe_path
2512                .extension()
2513                .and_then(|ext| ext.to_str())
2514                .map(|ext| ext.eq_ignore_ascii_case("wasm"))
2515                .unwrap_or(false);
2516        let archive_hint_path = if let Some(source) = archive_source {
2517            let (_, normalized) = normalize_pack_path(source)?;
2518            Some(normalized)
2519        } else if is_component || is_dir {
2520            None
2521        } else {
2522            Some(safe_path.clone())
2523        };
2524        let archive_hint = archive_hint_path.as_deref();
2525        if verify_archive {
2526            if let Some(verify_target) = archive_hint.and_then(|p| {
2527                std::fs::metadata(p)
2528                    .ok()
2529                    .filter(|meta| meta.is_file())
2530                    .map(|_| p)
2531            }) {
2532                verify::verify_pack(verify_target).await?;
2533                tracing::info!(pack_path = %verify_target.display(), "pack archive structure check passed (signature/digest checks happen at resolve time)");
2534            } else {
2535                tracing::debug!("skipping archive verification (no archive source)");
2536            }
2537        }
2538        let (engine, engine_profile) = crate::runtime_cache_engine_and_profile()?;
2539        let cache = CacheManager::new(CacheConfig::default(), engine_profile);
2540        let mut metadata = PackMetadata::fallback(&safe_path);
2541        let mut manifest = None;
2542        let mut legacy_manifest: Option<Box<legacy_pack::PackManifest>> = None;
2543        let mut flows = None;
2544        let materialized_root = component_resolution.materialized_root.clone().or_else(|| {
2545            if is_dir {
2546                Some(safe_path.clone())
2547            } else {
2548                None
2549            }
2550        });
2551        let (pack_assets_dir, assets_tempdir) =
2552            locate_pack_assets(materialized_root.as_deref(), archive_hint)?;
2553        let setup_yaml_exists = pack_assets_dir
2554            .as_ref()
2555            .map(|dir| dir.join("setup.yaml").is_file())
2556            .unwrap_or(false);
2557        tracing::info!(
2558            pack_root = %safe_path.display(),
2559            assets_setup_yaml_exists = setup_yaml_exists,
2560            "pack unpack metadata"
2561        );
2562
2563        if let Some(root) = materialized_root.as_ref() {
2564            match load_manifest_and_flows_from_dir(root) {
2565                Ok(ManifestLoad::New {
2566                    manifest: m,
2567                    flows: cache,
2568                }) => {
2569                    metadata = cache.metadata.clone();
2570                    manifest = Some(*m);
2571                    flows = Some(cache);
2572                }
2573                Ok(ManifestLoad::Legacy {
2574                    manifest: m,
2575                    flows: cache,
2576                }) => {
2577                    metadata = cache.metadata.clone();
2578                    legacy_manifest = Some(m);
2579                    flows = Some(cache);
2580                }
2581                Err(err) => {
2582                    if archive_hint.is_none() {
2583                        // No archive to fall back to: continuing would hand
2584                        // back an empty pack that looks successfully loaded.
2585                        return Err(err).with_context(|| {
2586                            format!(
2587                                "failed to load materialized pack manifest from {}",
2588                                root.display()
2589                            )
2590                        });
2591                    }
2592                    warn!(error = %err, pack = %root.display(), "failed to parse materialized pack manifest; falling back to the archive");
2593                }
2594            }
2595        }
2596
2597        if manifest.is_none()
2598            && legacy_manifest.is_none()
2599            && let Some(archive_path) = archive_hint
2600        {
2601            let manifest_load = load_manifest_and_flows(archive_path).with_context(|| {
2602                format!(
2603                    "failed to load manifest.cbor from {}",
2604                    archive_path.display()
2605                )
2606            })?;
2607            match manifest_load {
2608                ManifestLoad::New {
2609                    manifest: m,
2610                    flows: cache,
2611                } => {
2612                    metadata = cache.metadata.clone();
2613                    manifest = Some(*m);
2614                    flows = Some(cache);
2615                }
2616                ManifestLoad::Legacy {
2617                    manifest: m,
2618                    flows: cache,
2619                } => {
2620                    metadata = cache.metadata.clone();
2621                    legacy_manifest = Some(m);
2622                    flows = Some(cache);
2623                }
2624            }
2625        }
2626        #[cfg(feature = "fault-injection")]
2627        {
2628            let fault_ctx = FaultContext {
2629                pack_id: metadata.pack_id.as_str(),
2630                flow_id: "unknown",
2631                node_id: None,
2632                attempt: 1,
2633            };
2634            maybe_fail(FaultPoint::PackResolve, fault_ctx)
2635                .map_err(|err| anyhow!(err.to_string()))?;
2636        }
2637        let mut pack_lock = None;
2638        for root in find_pack_lock_roots(&safe_path, is_dir, archive_hint) {
2639            // A lock that cannot be read or parsed is skipped, not fatal: the
2640            // manifest's own component sources remain authoritative.
2641            match load_pack_lock(&root) {
2642                Ok(found) => pack_lock = found,
2643                Err(error) => {
2644                    warn!(error = %error, root = %root.display(), "ignoring unusable pack.lock");
2645                }
2646            }
2647            if pack_lock.is_some() {
2648                break;
2649            }
2650        }
2651        let component_sources_payload = if pack_lock.is_none() {
2652            if let Some(manifest) = manifest.as_ref() {
2653                manifest
2654                    .get_component_sources_v1()
2655                    .context("invalid component sources extension")?
2656            } else {
2657                None
2658            }
2659        } else {
2660            None
2661        };
2662        let component_sources = if let Some(lock) = pack_lock.as_ref() {
2663            Some(component_sources_table_from_pack_lock(
2664                lock,
2665                component_resolution.allow_missing_hash,
2666            )?)
2667        } else {
2668            component_sources_table(component_sources_payload.as_ref())?
2669        };
2670        let components = if is_component {
2671            let wasm_bytes = fs::read(&safe_path).await?;
2672            metadata = PackMetadata::from_wasm(&wasm_bytes)
2673                .unwrap_or_else(|| PackMetadata::fallback(&safe_path));
2674            let name = safe_path
2675                .file_stem()
2676                .map(|s| s.to_string_lossy().to_string())
2677                .unwrap_or_else(|| "component".to_string());
2678            let component = compile_component_with_cache(&cache, &engine, None, wasm_bytes).await?;
2679            let mut map = HashMap::new();
2680            map.insert(
2681                name.clone(),
2682                PackComponent {
2683                    name,
2684                    version: metadata.version.clone(),
2685                    component,
2686                },
2687            );
2688            map
2689        } else {
2690            let specs = component_specs(
2691                manifest.as_ref(),
2692                legacy_manifest.as_deref(),
2693                component_sources_payload.as_ref(),
2694                pack_lock.as_ref(),
2695            );
2696            if specs.is_empty() {
2697                HashMap::new()
2698            } else {
2699                let mut loaded = HashMap::new();
2700                let mut missing: HashSet<String> =
2701                    specs.iter().map(|spec| spec.id.clone()).collect();
2702                let mut searched = Vec::new();
2703
2704                if !component_resolution.overrides.is_empty() {
2705                    load_components_from_overrides(
2706                        &cache,
2707                        &engine,
2708                        &component_resolution.overrides,
2709                        &specs,
2710                        &mut missing,
2711                        &mut loaded,
2712                    )
2713                    .await?;
2714                    searched.push("override map".to_string());
2715                }
2716
2717                if let Some(component_sources) = component_sources.as_ref() {
2718                    load_components_from_sources(
2719                        &cache,
2720                        &engine,
2721                        component_sources,
2722                        &component_resolution,
2723                        &specs,
2724                        &mut missing,
2725                        &mut loaded,
2726                        materialized_root.as_deref(),
2727                        archive_hint,
2728                    )
2729                    .await?;
2730                    searched.push(format!("extension {}", EXT_COMPONENT_SOURCES_V1));
2731                }
2732
2733                if let Some(root) = materialized_root.as_ref() {
2734                    load_components_from_dir(
2735                        &cache,
2736                        &engine,
2737                        root,
2738                        &specs,
2739                        &mut missing,
2740                        &mut loaded,
2741                    )
2742                    .await?;
2743                    searched.push(format!("components dir {}", root.display()));
2744                }
2745
2746                if let Some(archive_path) = archive_hint {
2747                    load_components_from_archive(
2748                        &cache,
2749                        &engine,
2750                        archive_path,
2751                        &specs,
2752                        &mut missing,
2753                        &mut loaded,
2754                    )
2755                    .await?;
2756                    searched.push(format!("archive {}", archive_path.display()));
2757                }
2758
2759                if !missing.is_empty() {
2760                    let missing_list = missing.into_iter().collect::<Vec<_>>().join(", ");
2761                    let sources = if searched.is_empty() {
2762                        "no component sources".to_string()
2763                    } else {
2764                        searched.join(", ")
2765                    };
2766                    bail!(
2767                        "components missing: {}; looked in {}",
2768                        missing_list,
2769                        sources
2770                    );
2771                }
2772
2773                loaded
2774            }
2775        };
2776        let http_client = shared_http_client()?;
2777        let mut component_manifests = HashMap::new();
2778        if let Some(manifest) = manifest.as_ref() {
2779            for component in &manifest.components {
2780                component_manifests.insert(component.id.as_str().to_string(), component.clone());
2781            }
2782        }
2783        let base_wasi_policy = Arc::clone(&wasi_policy);
2784        let mut pack_policy = wasi_policy
2785            .for_tenant(&config.tenant, &config.env_passthrough)
2786            .with_context(|| format!("failed to build WASI policy for tenant {}", config.tenant))?;
2787        if let Some(dir) = pack_assets_dir {
2788            tracing::debug!(path = %dir.display(), "preopening pack assets directory for WASI /assets");
2789            pack_policy =
2790                pack_policy.with_preopen(PreopenSpec::new(dir, "/assets").read_only(true));
2791        }
2792        let wasi_policy = Arc::new(pack_policy);
2793        Ok(Self {
2794            path: safe_path,
2795            archive_path: archive_hint.map(Path::to_path_buf),
2796            config,
2797            engine,
2798            metadata,
2799            manifest,
2800            legacy_manifest,
2801            component_manifests,
2802            mocks,
2803            flows,
2804            components,
2805            http_client,
2806            session_store,
2807            state_store,
2808            wasi_policy,
2809            base_wasi_policy,
2810            assets_tempdir,
2811            provider_registry: RwLock::new(None),
2812            identify_hint_cache: RwLock::new(HashMap::new()),
2813            identify_hint_failures: RwLock::new(HashMap::new()),
2814            secrets,
2815            oauth_config,
2816            cache,
2817            runtime_config_non_secret: None,
2818            runtime_refs: None,
2819            mcp_routes: std::sync::OnceLock::new(),
2820            a2a_routes: std::sync::OnceLock::new(),
2821            run_context: std::sync::OnceLock::new(),
2822            user_ledger: std::sync::OnceLock::new(),
2823            nested_flow_handlers: std::sync::OnceLock::new(),
2824            sorla_routes: std::sync::OnceLock::new(),
2825            unit_id: None,
2826        })
2827    }
2828
2829    /// Lend this pack's flow-tool engines the host's node handlers. Called
2830    /// once per pack by the host after it wired its top-level engine; a
2831    /// second call keeps the first registration and warns.
2832    pub fn set_nested_flow_handlers(
2833        &self,
2834        handlers: crate::runner::nested_flow::NestedFlowHandlers,
2835    ) {
2836        if self.nested_flow_handlers.set(handlers).is_err() {
2837            tracing::warn!(
2838                pack_id = self.metadata.pack_id.as_str(),
2839                "nested flow-tool handlers already registered for this pack; keeping the first"
2840            );
2841        }
2842    }
2843
2844    /// Bind this pack instance to the deployed unit it belongs to (the
2845    /// revision's `bundle_id`), so every extension credential its components
2846    /// read resolves that unit's own value before the value shared by every
2847    /// unit of the same pack.
2848    ///
2849    /// Called by `TenantRuntime::load_revision` through `load_pack_runtime`,
2850    /// before the `Arc<PackRuntime>` is created — the same seam
2851    /// [`set_runtime_config_non_secret`](Self::set_runtime_config_non_secret)
2852    /// uses. `None` is the legacy tenant-only path, which keeps the bare pack
2853    /// scope.
2854    pub fn set_unit_id(&mut self, unit_id: Option<String>) {
2855        self.unit_id = unit_id;
2856    }
2857
2858    /// The deployed unit this pack instance is bound to, if any. See
2859    /// [`set_unit_id`](Self::set_unit_id).
2860    pub fn unit_id(&self) -> Option<&str> {
2861        self.unit_id.as_deref()
2862    }
2863
2864    /// Inject the `pack-config.v1.non_secret` map for this pack. Called by
2865    /// the producer (greentic-start, C4.3) after loading the deployed
2866    /// `PackConfig`. Passing `None` clears any previously-set map.
2867    pub fn set_runtime_config_non_secret(&mut self, map: Option<Arc<BTreeMap<String, Value>>>) {
2868        self.runtime_config_non_secret = map;
2869    }
2870
2871    /// Read-only accessor for the injected `pack-config.v1.non_secret` map.
2872    /// Used by the revision loader's tests to assert producer plumbing.
2873    pub fn runtime_config_non_secret(&self) -> Option<&Arc<BTreeMap<String, Value>>> {
2874        self.runtime_config_non_secret.as_ref()
2875    }
2876
2877    /// Inject the `pack-config.v1.runtime_refs` channel (C5): per-pack
2878    /// `key → URI` bindings plus the env-shared resolver. Called by
2879    /// greentic-start after loading the deployed `PackConfig`. Passing
2880    /// `None` clears any previously-set injection.
2881    pub fn set_runtime_refs(&mut self, injection: Option<RuntimeRefsInjection>) {
2882        self.runtime_refs = injection;
2883    }
2884
2885    /// Read-only accessor for the injected runtime-refs channel. Used by
2886    /// the revision loader's tests to assert producer plumbing.
2887    pub fn runtime_refs(&self) -> Option<&RuntimeRefsInjection> {
2888        self.runtime_refs.as_ref()
2889    }
2890
2891    pub async fn list_flows(&self) -> Result<Vec<FlowDescriptor>> {
2892        if let Some(cache) = &self.flows {
2893            return Ok(cache.descriptors.clone());
2894        }
2895        if let Some(manifest) = &self.manifest {
2896            let descriptors = manifest
2897                .flows
2898                .iter()
2899                .map(|flow| FlowDescriptor {
2900                    id: flow.id.as_str().to_string(),
2901                    flow_type: flow_kind_to_str(flow.kind).to_string(),
2902                    pack_id: manifest.pack_id.as_str().to_string(),
2903                    profile: manifest.pack_id.as_str().to_string(),
2904                    version: manifest.version.to_string(),
2905                    description: None,
2906                    entry: tags_indicate_entry(flow.tags.iter().map(String::as_str)),
2907                })
2908                .collect();
2909            return Ok(descriptors);
2910        }
2911        Ok(Vec::new())
2912    }
2913
2914    /// Synchronous accessor for the cached flow descriptors. Reads the same
2915    /// in-memory fields as `list_flows` but without `.await`, so it is safe to
2916    /// call from a synchronous context (e.g. `FlowInvoker::list_flows`).
2917    /// This avoids a `block_on`-in-async-context panic on the runner thread.
2918    ///
2919    /// Its only caller is `runner::flow_invoker::PackRuntimeFlowInvoker`,
2920    /// which is entirely `#![cfg(feature = "agentic-worker")]`; gate this the
2921    /// same way so it isn't flagged dead when that feature is off.
2922    #[cfg(feature = "agentic-worker")]
2923    pub(crate) fn flow_descriptors(&self) -> Vec<FlowDescriptor> {
2924        if let Some(cache) = &self.flows {
2925            return cache.descriptors.clone();
2926        }
2927        if let Some(manifest) = &self.manifest {
2928            return manifest
2929                .flows
2930                .iter()
2931                .map(|flow| FlowDescriptor {
2932                    id: flow.id.as_str().to_string(),
2933                    flow_type: flow_kind_to_str(flow.kind).to_string(),
2934                    pack_id: manifest.pack_id.as_str().to_string(),
2935                    profile: manifest.pack_id.as_str().to_string(),
2936                    version: manifest.version.to_string(),
2937                    description: None,
2938                    entry: tags_indicate_entry(flow.tags.iter().map(String::as_str)),
2939                })
2940                .collect();
2941        }
2942        Vec::new()
2943    }
2944
2945    /// The tenant-scoped WASI policy this pack's components run under.
2946    #[doc(hidden)]
2947    pub fn effective_wasi_policy(&self) -> Arc<RunnerWasiPolicy> {
2948        Arc::clone(&self.wasi_policy)
2949    }
2950
2951    /// The WASI policy of the pack a direct flow run loads. Must equal
2952    /// [`Self::effective_wasi_policy`]; exposed so a test can pin that.
2953    #[doc(hidden)]
2954    pub async fn nested_load_wasi_policy(&self) -> Result<Arc<RunnerWasiPolicy>> {
2955        let (pack, _engine) = self.load_flow_engine().await?;
2956        Ok(pack.effective_wasi_policy())
2957    }
2958
2959    /// The unit id and non-secret runtime config a direct flow run's pack
2960    /// carries. Must equal this pack's; exposed so a test can pin that.
2961    #[doc(hidden)]
2962    pub async fn nested_load_scope(
2963        &self,
2964    ) -> Result<(Option<String>, Option<Arc<BTreeMap<String, Value>>>)> {
2965        let (pack, _engine) = self.load_flow_engine().await?;
2966        Ok((
2967            pack.unit_id().map(str::to_string),
2968            pack.runtime_config_non_secret().cloned(),
2969        ))
2970    }
2971
2972    /// Load a fresh engine over this pack, the way every direct flow run here
2973    /// does. Shared by [`Self::execute_flow_inner`] and
2974    /// [`Self::resume_flow_for_tool`], so a resumed tool flow runs on exactly
2975    /// the pack and engine configuration its first leg did.
2976    async fn load_flow_engine(&self) -> Result<(Arc<PackRuntime>, FlowEngine)> {
2977        let mut loaded = PackRuntime::load(
2978            &self.path,
2979            Arc::clone(&self.config),
2980            self.mocks.clone(),
2981            self.archive_path.as_deref(),
2982            self.session_store.clone(),
2983            self.state_store.clone(),
2984            Arc::clone(&self.base_wasi_policy),
2985            self.secrets.clone(),
2986            self.oauth_config.clone(),
2987            false,
2988            ComponentResolution::default(),
2989        )
2990        .await?;
2991        // A freshly loaded pack carries none of the producer-injected scope.
2992        // Without these a nested `component.exec` would read the secret scope
2993        // shared by every unit and see an empty runtime config.
2994        loaded.set_unit_id(self.unit_id.clone());
2995        loaded.set_runtime_config_non_secret(self.runtime_config_non_secret.clone());
2996        loaded.set_runtime_refs(self.runtime_refs.clone());
2997        let pack = Arc::new(loaded);
2998        let mut engine = FlowEngine::new(vec![Arc::clone(&pack)], Arc::clone(&self.config)).await?;
2999        // Read from `self` (the pack the host built its agent runtime over),
3000        // not from the freshly loaded `pack`, whose slot is empty.
3001        if let Some(handlers) = self.nested_flow_handlers.get() {
3002            handlers.install_on(&mut engine);
3003        }
3004        Ok((pack, engine))
3005    }
3006
3007    /// The [`FlowContext`] a direct (non-ingress) flow run executes under.
3008    fn direct_flow_ctx<'a>(
3009        &'a self,
3010        pack: &'a PackRuntime,
3011        flow_id: &'a str,
3012        caller: Option<&'a Value>,
3013    ) -> FlowContext<'a> {
3014        FlowContext {
3015            tenant: self.config.tenant.as_str(),
3016            pack_id: pack.metadata().pack_id.as_str(),
3017            flow_id,
3018            node_id: None,
3019            tool: None,
3020            action: None,
3021            session_id: None,
3022            provider_id: None,
3023            reply_scope: None,
3024            retry_config: self.config.retry_config().into(),
3025            attempt: 1,
3026            observer: None,
3027            mocks: pack.mocks.as_deref(),
3028            caller,
3029        }
3030    }
3031
3032    /// Shared load + engine + execute body for `run_flow` and
3033    /// `run_flow_for_tool`. Returns the raw `FlowExecution` so each caller can
3034    /// match on `FlowStatus` according to its own contract.
3035    async fn execute_flow_inner(
3036        &self,
3037        flow_id: &str,
3038        mut input: serde_json::Value,
3039    ) -> Result<FlowExecution> {
3040        let frame = crate::runner::nested_flow::enter(flow_id).map_err(anyhow::Error::msg)?;
3041        let (pack, engine) = self.load_flow_engine().await?;
3042        // The input is the model's tool arguments: the caller it names is
3043        // replaced by the OUTER step's host-stamped one BEFORE `caller_block`
3044        // reads it (see `nested_flow::pin_caller`).
3045        crate::runner::nested_flow::pin_caller(&mut input);
3046        // Same single establishment point as the ingress path, for callers
3047        // that drive a flow directly — see `crate::caller_identity`.
3048        // Cloned rather than borrowed: `input` is moved into the run below,
3049        // and the context must outlive that move.
3050        let caller_block = crate::caller_identity::caller_block(&input).cloned();
3051        let ctx = self.direct_flow_ctx(&pack, flow_id, caller_block.as_ref());
3052        // `ctx.session_id` stays `None` on purpose; a `dw.agent` in this flow
3053        // reads its session from the frame (`nested_flow::agent_session_for`).
3054        crate::runner::nested_flow::scope(frame, engine.execute(ctx, input)).await
3055    }
3056
3057    #[allow(dead_code)]
3058    pub async fn run_flow(
3059        &self,
3060        flow_id: &str,
3061        input: serde_json::Value,
3062    ) -> Result<serde_json::Value> {
3063        let execution = self.execute_flow_inner(flow_id, input).await?;
3064        match execution.status {
3065            FlowStatus::Completed => Ok(execution.output),
3066            FlowStatus::Waiting(wait) => Ok(serde_json::json!({
3067                "status": "pending",
3068                "reason": wait.reason,
3069                "resume": wait.snapshot,
3070                "response": execution.output,
3071            })),
3072        }
3073    }
3074
3075    /// Non-interactive flow execution for use as an agent tool. Identical to
3076    /// `run_flow` in its load + execute path, but `FlowStatus::Waiting` is an
3077    /// error because agent tools must be non-interactive (they cannot pause and
3078    /// resume mid-LLM-turn).
3079    ///
3080    /// Returns `Ok(output)` on `Completed`, `Err(message)` on any failure.
3081    pub async fn run_flow_for_tool(
3082        &self,
3083        flow_id: &str,
3084        input: serde_json::Value,
3085    ) -> Result<serde_json::Value, String> {
3086        let execution = self
3087            .execute_flow_inner(flow_id, input)
3088            .await
3089            .map_err(|e| e.to_string())?;
3090        match execution.status {
3091            FlowStatus::Completed => Ok(execution.output),
3092            FlowStatus::Waiting(wait) => Err(format!(
3093                "flow '{flow_id}' tried to pause ({:?}); agent tools must be non-interactive",
3094                wait.reason
3095            )),
3096        }
3097    }
3098
3099    /// Interactive flow execution for an agentic worker's `flow:` tool.
3100    ///
3101    /// Unlike [`Self::run_flow_for_tool`], a flow that parks (a card awaiting
3102    /// its routed submit) is not an error: it answers
3103    /// [`ToolFlowOutcome::Waiting`] with the serialized [`FlowSnapshot`] to
3104    /// hand back to [`Self::resume_flow_for_tool`] and the flow's output at
3105    /// the park point — the finalized card — to present meanwhile.
3106    ///
3107    /// Only the in-process `dw.agent` loop calls this. Graph tool nodes and
3108    /// deep workers keep `run_flow_for_tool`, because neither can suspend.
3109    pub async fn run_flow_for_tool_interactive(
3110        &self,
3111        flow_id: &str,
3112        input: serde_json::Value,
3113    ) -> Result<ToolFlowOutcome, String> {
3114        let execution = self
3115            .execute_flow_inner(flow_id, input)
3116            .await
3117            .map_err(|e| e.to_string())?;
3118        tool_flow_outcome(flow_id, execution)
3119    }
3120
3121    /// Resume a flow parked by [`Self::run_flow_for_tool_interactive`] with
3122    /// `input` — the user's submit, shaped exactly as the inbound activity a
3123    /// standalone card flow would have been resumed with.
3124    ///
3125    /// `snapshot` must be a [`FlowSnapshot`] of `flow_id`; any other flow's
3126    /// snapshot is refused rather than resumed under the wrong name.
3127    pub async fn resume_flow_for_tool(
3128        &self,
3129        flow_id: &str,
3130        snapshot: serde_json::Value,
3131        mut input: serde_json::Value,
3132    ) -> Result<ToolFlowOutcome, String> {
3133        let snapshot: FlowSnapshot = serde_json::from_value(snapshot)
3134            .map_err(|e| format!("flow '{flow_id}': unreadable resume snapshot: {e}"))?;
3135        if snapshot.flow_id != flow_id {
3136            return Err(format!(
3137                "flow '{flow_id}': resume snapshot belongs to flow '{}'",
3138                snapshot.flow_id
3139            ));
3140        }
3141        let frame = crate::runner::nested_flow::enter(flow_id)?;
3142        let (pack, engine) = self.load_flow_engine().await.map_err(|e| e.to_string())?;
3143        // Same rule as the call: the resume input is model-reachable text, so
3144        // its caller is the outer step's, substituted before it is read.
3145        crate::runner::nested_flow::pin_caller(&mut input);
3146        let caller_block = crate::caller_identity::caller_block(&input).cloned();
3147        let snapshot_flow = snapshot.flow_id.clone();
3148        let ctx = self.direct_flow_ctx(&pack, &snapshot_flow, caller_block.as_ref());
3149        let execution =
3150            crate::runner::nested_flow::scope(frame, engine.resume(ctx, snapshot, input))
3151                .await
3152                .map_err(|e| e.to_string())?;
3153        tool_flow_outcome(flow_id, execution)
3154    }
3155
3156    pub async fn invoke_component(
3157        &self,
3158        component_ref: &str,
3159        ctx: ComponentExecCtx,
3160        operation: &str,
3161        config_json: Option<String>,
3162        input_json: String,
3163    ) -> Result<Value> {
3164        self.invoke_component_as(component_ref, ctx, None, operation, config_json, input_json)
3165            .await
3166    }
3167
3168    /// [`Self::invoke_component`] on behalf of a provider-verified caller.
3169    ///
3170    /// `caller` is presented to the component as its `user`/`team` (and, where
3171    /// the world has one, the `caller.*` attribute map). It is an argument
3172    /// rather than a field of `ExecCtx` because downstream crates build that
3173    /// struct with literal initializers; and it never touches `ctx.tenant`,
3174    /// which stays the host's scope for the component's secrets and state.
3175    pub async fn invoke_component_as(
3176        &self,
3177        component_ref: &str,
3178        ctx: ComponentExecCtx,
3179        caller: Option<crate::caller_identity::ComponentCaller>,
3180        operation: &str,
3181        config_json: Option<String>,
3182        input_json: String,
3183    ) -> Result<Value> {
3184        self.invoke_component_for(
3185            component_ref,
3186            ctx,
3187            caller,
3188            None,
3189            operation,
3190            config_json,
3191            input_json,
3192        )
3193        .await
3194    }
3195
3196    /// [`Self::invoke_component_as`] for an invocation delivered by
3197    /// `provider_id` (the flow engine's `FlowContext::provider_id`).
3198    ///
3199    /// The provider is presented to a 0.5 component in its `provider_id` slot,
3200    /// and — when it is also the host scope's `user`, as the flow engine sets
3201    /// it — is NOT presented as the component's user: a caller with no
3202    /// verified subject reaches the component with no user (see
3203    /// `component_api::presented_user` and `GREENTIC_PRESENT_PROVIDER_AS_USER`).
3204    /// `ctx.tenant` is still passed to the host untouched, so the component's
3205    /// state and secrets scope does not move.
3206    #[allow(clippy::too_many_arguments)]
3207    pub async fn invoke_component_for(
3208        &self,
3209        component_ref: &str,
3210        ctx: ComponentExecCtx,
3211        caller: Option<crate::caller_identity::ComponentCaller>,
3212        provider_id: Option<&str>,
3213        operation: &str,
3214        config_json: Option<String>,
3215        input_json: String,
3216    ) -> Result<Value> {
3217        let provider_id = provider_id.map(str::to_string);
3218        let component_ref = resolve_component_key(component_ref, operation, |key| {
3219            self.components.contains_key(key)
3220        });
3221        let pack_component = self
3222            .components
3223            .get(component_ref)
3224            .with_context(|| format!("component '{component_ref}' not found in pack"))?;
3225        let engine = self.engine.clone();
3226        let config = Arc::clone(&self.config);
3227        let http_client = Arc::clone(&self.http_client);
3228        let mocks = self.mocks.clone();
3229        let session_store = self.session_store.clone();
3230        let state_store = self.state_store.clone();
3231        let secrets = Arc::clone(&self.secrets);
3232        let oauth_config = self.oauth_config.clone();
3233        let wasi_policy = Arc::clone(&self.wasi_policy);
3234        let pack_id = self.metadata().pack_id.clone();
3235        // Hoisted with `pack_id`: the WASI closure below is `move` and must not
3236        // borrow `self`.
3237        let unit_id = self.unit_id.clone();
3238        let allow_state_store = self.allows_state_store(component_ref);
3239        let component = pack_component.component.clone();
3240        let component_ref_owned = component_ref.to_string();
3241        let operation_owned = operation.to_string();
3242        let input_owned =
3243            Self::merge_component_config_into_input_json(config_json.as_deref(), &input_json)
3244                .context("merge component config into invocation payload")?;
3245        let ctx_owned = ctx;
3246        let runtime_config_non_secret = self.runtime_config_non_secret.clone();
3247        let runtime_refs = self.runtime_refs.clone();
3248
3249        run_on_wasi_thread("component.invoke", move || {
3250            let mut linker = Linker::new(&engine);
3251            register_all(&mut linker, allow_state_store)?;
3252            add_component_control_to_linker(&mut linker)?;
3253
3254            let host_state = HostState::new(
3255                pack_id.clone(),
3256                config,
3257                http_client,
3258                mocks,
3259                session_store,
3260                state_store,
3261                secrets,
3262                oauth_config,
3263                Some(ctx_owned.clone()),
3264                Some(component_ref_owned.clone()),
3265                false,
3266                runtime_config_non_secret,
3267                runtime_refs,
3268            )?
3269            .with_unit(unit_id.clone());
3270            let store_state = ComponentState::new(host_state, wasi_policy)?;
3271            let mut store = new_limited_store(&engine, store_state);
3272
3273            let invoke_result = HostState::instantiate_component_result(
3274                &mut linker,
3275                &mut store,
3276                &component,
3277                &ctx_owned,
3278                caller.as_ref(),
3279                provider_id.as_deref(),
3280                &component_ref_owned,
3281                &operation_owned,
3282                &input_owned,
3283            )?;
3284            HostState::convert_invoke_result(invoke_result)
3285        })
3286        .await
3287    }
3288
3289    /// Fold a provider instance's configured answers into its invocation
3290    /// payload, the same way [`Self::merge_component_config_into_input_json`]
3291    /// does for a component.
3292    ///
3293    /// `ProviderBinding` has carried `config_json` since providers gained
3294    /// instances, and `runner::operator` passes it whenever it reaches a
3295    /// provider through `invoke_component`. This path — the one
3296    /// `HostRuntime`'s webhook dispatch uses — took the payload and handed it
3297    /// over untouched, so a provider invoked here saw `request.config` as an
3298    /// empty object no matter what the operator had answered. Nothing failed:
3299    /// every setup answer simply was not there, which a provider reports (if
3300    /// at all) as its own feature being switched off.
3301    ///
3302    /// Two rules, and the second is why this is not just a call to the
3303    /// component version:
3304    ///
3305    /// - **No config, no change.** A provider instance with no configured
3306    ///   answers gets the byte-identical payload it gets today, so nothing
3307    ///   about an unconfigured provider moves.
3308    /// - **The payload must already be JSON.** A provider's input arrives as
3309    ///   bytes from a webhook body, not as a flow node's value, so it may not
3310    ///   be JSON at all. The component merge wraps a non-JSON input as a JSON
3311    ///   string, which for a provider would replace a binary body with an
3312    ///   envelope the component cannot read — trading a missing config for a
3313    ///   corrupted request. Here a payload that does not parse is passed
3314    ///   through untouched and the drop is logged with the provider named,
3315    ///   because silence is what this whole function exists to end.
3316    fn merge_provider_config_into_input(
3317        config_json: Option<&str>,
3318        input_json: Vec<u8>,
3319        provider_type: &str,
3320    ) -> Vec<u8> {
3321        let Some(config_json) = config_json else {
3322            return input_json;
3323        };
3324        let Ok(input_str) = std::str::from_utf8(&input_json) else {
3325            tracing::warn!(
3326                provider_type,
3327                "provider payload is not UTF-8; invoking without its configured answers"
3328            );
3329            return input_json;
3330        };
3331        if serde_json::from_str::<Value>(input_str).is_err() {
3332            tracing::warn!(
3333                provider_type,
3334                "provider payload is not JSON; invoking without its configured answers"
3335            );
3336            return input_json;
3337        }
3338        match Self::merge_component_config_into_input_json(Some(config_json), input_str) {
3339            Ok(merged) => merged.into_bytes(),
3340            Err(error) => {
3341                tracing::warn!(
3342                    provider_type,
3343                    %error,
3344                    "could not merge the provider's configured answers into its payload; \
3345                     invoking without them"
3346                );
3347                input_json
3348            }
3349        }
3350    }
3351
3352    fn merge_component_config_into_input_json(
3353        config_json: Option<&str>,
3354        input_json: &str,
3355    ) -> Result<String> {
3356        let Some(config_json) = config_json else {
3357            return Ok(input_json.to_string());
3358        };
3359
3360        let config_value: Value =
3361            serde_json::from_str(config_json).context("parse component config JSON")?;
3362
3363        if let Ok(mut invocation) =
3364            serde_json::from_str::<greentic_types::InvocationEnvelope>(input_json)
3365        {
3366            let payload_value = serde_json::from_slice(&invocation.payload).unwrap_or_else(|_| {
3367                Value::String(String::from_utf8_lossy(&invocation.payload).into_owned())
3368            });
3369            invocation.payload = serde_json::to_vec(&serde_json::json!({
3370                "config": config_value,
3371                "input": payload_value,
3372            }))
3373            .context("serialize merged invocation payload")?;
3374            return serde_json::to_string(&invocation)
3375                .context("serialize merged invocation envelope");
3376        }
3377
3378        let input_value = serde_json::from_str(input_json)
3379            .unwrap_or_else(|_| Value::String(input_json.to_string()));
3380        serde_json::to_string(&serde_json::json!({
3381            "config": config_value,
3382            "input": input_value,
3383        }))
3384        .context("serialize merged component input")
3385    }
3386
3387    pub fn resolve_provider(
3388        &self,
3389        provider_id: Option<&str>,
3390        provider_type: Option<&str>,
3391    ) -> Result<ProviderBinding> {
3392        let registry = self.provider_registry()?;
3393        registry.resolve(provider_id, provider_type)
3394    }
3395
3396    pub async fn invoke_provider(
3397        &self,
3398        binding: &ProviderBinding,
3399        ctx: ComponentExecCtx,
3400        op: &str,
3401        input_json: Vec<u8>,
3402    ) -> Result<Value> {
3403        let component_ref_owned = binding.component_ref.clone();
3404        let pack_component = self.components.get(&component_ref_owned).with_context(|| {
3405            format!("provider component '{component_ref_owned}' not found in pack")
3406        })?;
3407        let component = pack_component.component.clone();
3408
3409        let engine = self.engine.clone();
3410        let config = Arc::clone(&self.config);
3411        let http_client = Arc::clone(&self.http_client);
3412        let mocks = self.mocks.clone();
3413        let session_store = self.session_store.clone();
3414        let state_store = self.state_store.clone();
3415        let secrets = Arc::clone(&self.secrets);
3416        let oauth_config = self.oauth_config.clone();
3417        let wasi_policy = Arc::clone(&self.wasi_policy);
3418        let pack_id = self.metadata().pack_id.clone();
3419        // Hoisted with `pack_id`: the WASI closure below is `move` and must not
3420        // borrow `self`.
3421        let unit_id = self.unit_id.clone();
3422        let allow_state_store = self.allows_state_store(&component_ref_owned);
3423        let input_owned = Self::merge_provider_config_into_input(
3424            binding.config_json.as_deref(),
3425            input_json,
3426            &binding.provider_type,
3427        );
3428        let op_owned = op.to_string();
3429        let ctx_owned = ctx;
3430        let world = binding.world.clone();
3431        let runtime_config_non_secret = self.runtime_config_non_secret.clone();
3432        let runtime_refs = self.runtime_refs.clone();
3433
3434        run_on_wasi_thread("provider.invoke", move || {
3435            let mut linker = Linker::new(&engine);
3436            register_all(&mut linker, allow_state_store)?;
3437            add_component_control_to_linker(&mut linker)?;
3438            let host_state = HostState::new(
3439                pack_id.clone(),
3440                config,
3441                http_client,
3442                mocks,
3443                session_store,
3444                state_store,
3445                secrets,
3446                oauth_config,
3447                Some(ctx_owned.clone()),
3448                Some(component_ref_owned.clone()),
3449                true,
3450                runtime_config_non_secret,
3451                runtime_refs,
3452            )?
3453            .with_unit(unit_id.clone());
3454            let store_state = ComponentState::new(host_state, wasi_policy)?;
3455            let mut store = new_limited_store(&engine, store_state);
3456
3457            // Extension-provider worlds (greentic:extension-provider@0.2.0 /
3458            // @0.1.0) are introspection surfaces (list-channels,
3459            // describe-channel, *-schema, dry-run-encode) and deliberately do
3460            // NOT export a generic `invoke(op, input)` data-plane call. If a
3461            // pack declares such a world for the runtime data plane, dispatch
3462            // here would otherwise fall through to the legacy schema-core
3463            // bindings and fail with an opaque "no exported instance" wasmtime
3464            // error. Detect it up front (declared-world fast path, confirmed by
3465            // an instance-level probe) and surface a typed, downcastable
3466            // `ProviderInvokeError` instead. The data-plane routing for these
3467            // worlds is an open design question (see PR body NEEDS_DECISION);
3468            // legacy schema-core remains the default path below.
3469            if world.contains("extension-provider") {
3470                let pre_instance = linker.instantiate_pre(component.as_ref())?;
3471                let instance =
3472                    block_on(async { pre_instance.instantiate_async(&mut store).await })?;
3473                let detected =
3474                    crate::extension_provider::probe_provider_world(&mut store, &instance);
3475                let version = detected
3476                    .map(|w| w.version())
3477                    .unwrap_or("unknown")
3478                    .to_string();
3479                let typed = crate::extension_provider::ProviderInvokeError::Internal(format!(
3480                    "extension-provider@{version} world exposes no data-plane invoke; \
3481                     operation '{op_owned}' has no extension-provider equivalent (introspection \
3482                     surface only)"
3483                ));
3484                return Err(crate::extension_provider::into_anyhow(typed));
3485            }
3486
3487            let use_schema_core_schema = world.contains("provider-schema-core");
3488            let use_schema_core_path = world.contains("provider/schema-core");
3489            let result = if use_schema_core_schema {
3490                let pre_instance = linker.instantiate_pre(component.as_ref())?;
3491                let pre: SchemaSchemaCorePre<ComponentState> =
3492                    SchemaSchemaCorePre::new(pre_instance)?;
3493                let bindings = block_on(async { pre.instantiate_async(&mut store).await })?;
3494                let provider = bindings.greentic_provider_schema_core_schema_core_api();
3495                provider.call_invoke(&mut store, &op_owned, &input_owned)?
3496            } else if use_schema_core_path {
3497                let pre_instance = linker.instantiate_pre(component.as_ref())?;
3498                let path_attempt = (|| -> Result<Vec<u8>> {
3499                    let pre: PathSchemaCorePre<ComponentState> =
3500                        PathSchemaCorePre::new(pre_instance)?;
3501                    let bindings = block_on(async { pre.instantiate_async(&mut store).await })?;
3502                    let provider = bindings.greentic_provider_schema_core_api();
3503                    Ok(provider.call_invoke(&mut store, &op_owned, &input_owned)?)
3504                })();
3505                match path_attempt {
3506                    Ok(value) => value,
3507                    Err(path_err)
3508                        if path_err.to_string().contains("no exported instance named") =>
3509                    {
3510                        let pre_instance = linker.instantiate_pre(component.as_ref())?;
3511                        let pre: SchemaSchemaCorePre<ComponentState> =
3512                            SchemaSchemaCorePre::new(pre_instance)?;
3513                        let bindings = block_on(async { pre.instantiate_async(&mut store).await })?;
3514                        let provider = bindings.greentic_provider_schema_core_schema_core_api();
3515                        provider.call_invoke(&mut store, &op_owned, &input_owned)?
3516                    }
3517                    Err(path_err) => return Err(path_err),
3518                }
3519            } else {
3520                let pre_instance = linker.instantiate_pre(component.as_ref())?;
3521                let pre: LegacySchemaCorePre<ComponentState> =
3522                    LegacySchemaCorePre::new(pre_instance)?;
3523                let bindings = block_on(async { pre.instantiate_async(&mut store).await })?;
3524                let provider = bindings.greentic_provider_core_schema_core_api();
3525                provider.call_invoke(&mut store, &op_owned, &input_owned)?
3526            };
3527            deserialize_json_bytes(result)
3528        })
3529        .await
3530    }
3531
3532    /// Call the provider component's `identify-instance` export
3533    /// (`greentic:provider-instance-identity@0.1.0`) with the inbound
3534    /// payload bytes. Returns an [`IdentifyOutcome`] — see the variant
3535    /// docs for the per-case contract.
3536    ///
3537    /// # Payload shape (M1 IID.4d wrapper)
3538    ///
3539    /// `payload` is forwarded opaque to the component. The shape is set by
3540    /// the caller; the M1 IID.4d wrapper convention from `greentic-start`
3541    /// is `{headers: [{name,value}], body: <parsed-or-null>}` so providers
3542    /// whose discriminator lives in HTTP headers (Telegram via
3543    /// `x-telegram-bot-api-secret-token`) can identify the instance the
3544    /// same call shape that body-based providers (Teams, Slack, Webex,
3545    /// etc.) use. See the docstring on
3546    /// `greentic:provider-instance-identity/instance-identity-api.identify-instance`
3547    /// for the full contract; this host method does not parse or
3548    /// validate the bytes.
3549    ///
3550    /// # Host authority on identity probes
3551    ///
3552    /// The linker registers the full host import surface (Wasmtime
3553    /// validates all imports eagerly at `instantiate_pre`, not just
3554    /// those reachable from the invoked export). The WASI sandbox is
3555    /// locked down: no preopens, no env, no stdio. Deny-shim linker
3556    /// handlers (trap on call, satisfy at link time) are a follow-up
3557    /// in `greentic-interfaces-wasmtime`. See [`register_identity_probe`].
3558    pub async fn invoke_identify_instance(
3559        &self,
3560        binding: &ProviderBinding,
3561        payload: Vec<u8>,
3562    ) -> Result<IdentifyOutcome> {
3563        let component_ref_owned = binding.component_ref.clone();
3564        let pack_component = self.components.get(&component_ref_owned).with_context(|| {
3565            format!("provider component '{component_ref_owned}' not found in pack")
3566        })?;
3567        let component = pack_component.component.clone();
3568
3569        let engine = self.engine.clone();
3570        let config = Arc::clone(&self.config);
3571        let http_client = Arc::clone(&self.http_client);
3572        let mocks = self.mocks.clone();
3573        let session_store = self.session_store.clone();
3574        let state_store = self.state_store.clone();
3575        let secrets = Arc::clone(&self.secrets);
3576        let oauth_config = self.oauth_config.clone();
3577        let pack_id = self.metadata().pack_id.clone();
3578        // Hoisted with `pack_id`: the WASI closure below is `move` and must not
3579        // borrow `self`.
3580        let unit_id = self.unit_id.clone();
3581
3582        // Locked-down WASI policy: no preopens, no env, no stdio.
3583        // The linker registers all imports (Wasmtime requires it for
3584        // instantiate_pre), but the WASI sandbox is the tightest we
3585        // can enforce today. See [`register_identity_probe`] docs.
3586        let wasi_policy = Arc::new(RunnerWasiPolicy::probe());
3587        let runtime_config_non_secret = self.runtime_config_non_secret.clone();
3588        let runtime_refs = self.runtime_refs.clone();
3589        run_on_wasi_thread("provider.identify_instance", move || {
3590            let mut linker = Linker::new(&engine);
3591            register_identity_probe(&mut linker)?;
3592            let host_state = HostState::new(
3593                pack_id.clone(),
3594                config,
3595                http_client,
3596                mocks,
3597                session_store,
3598                state_store,
3599                secrets,
3600                oauth_config,
3601                None,
3602                Some(component_ref_owned.clone()),
3603                true,
3604                runtime_config_non_secret,
3605                runtime_refs,
3606            )?
3607            .with_unit(unit_id.clone());
3608            let store_state = ComponentState::new(host_state, wasi_policy)?;
3609            let mut store = new_limited_store(&engine, store_state);
3610
3611            let pre_instance = linker.instantiate_pre(component.as_ref())?;
3612            let pre = match InstanceIdentityPre::<ComponentState>::new(pre_instance) {
3613                Ok(pre) => pre,
3614                Err(err) if is_missing_export_error(&format!("{err:#}")) => {
3615                    return Ok(IdentifyOutcome::Unsupported);
3616                }
3617                Err(err) => return Err(err.into()),
3618            };
3619            let bindings = block_on(async { pre.instantiate_async(&mut store).await })?;
3620            let api = bindings.greentic_provider_instance_identity_instance_identity_api();
3621            let result = api.call_identify_instance(&mut store, &payload)?;
3622            Ok(match result {
3623                Some(id) => IdentifyOutcome::Identified(id),
3624                None => IdentifyOutcome::NoMatch,
3625            })
3626        })
3627        .await
3628    }
3629
3630    /// Call the provider component's `describe-identify-instance` export
3631    /// (`greentic:provider-instance-identity/instance-identity-describe@0.1.0`)
3632    /// and parse the returned JSON into an [`IdentifyInstanceHint`].
3633    ///
3634    /// Returns `Ok(None)` for every "no hint available" case: the
3635    /// component does not export the describe world, the export returned
3636    /// `none`, the returned bytes are not valid JSON, or the `version`
3637    /// gate failed. The two malformed cases are warn-logged so a typo'd
3638    /// hint surfaces in operator logs without blocking ingest. Component
3639    /// traps and other infrastructure errors propagate as `Err`.
3640    ///
3641    /// This is the uncached probe — see [`resolve_identify_hint`] for the
3642    /// cached wrapper that callers SHOULD use on the inbound hot path.
3643    ///
3644    /// [`resolve_identify_hint`]: PackRuntime::resolve_identify_hint
3645    pub async fn invoke_describe_identify_instance(
3646        &self,
3647        binding: &ProviderBinding,
3648    ) -> Result<Option<IdentifyInstanceHint>> {
3649        let component_ref_owned = binding.component_ref.clone();
3650        let pack_component = self.components.get(&component_ref_owned).with_context(|| {
3651            format!("provider component '{component_ref_owned}' not found in pack")
3652        })?;
3653        let component = pack_component.component.clone();
3654
3655        let engine = self.engine.clone();
3656        let config = Arc::clone(&self.config);
3657        let http_client = Arc::clone(&self.http_client);
3658        let mocks = self.mocks.clone();
3659        let session_store = self.session_store.clone();
3660        let state_store = self.state_store.clone();
3661        let secrets = Arc::clone(&self.secrets);
3662        let oauth_config = self.oauth_config.clone();
3663        let pack_id = self.metadata().pack_id.clone();
3664        // Hoisted with `pack_id`: the WASI closure below is `move` and must not
3665        // borrow `self`.
3666        let unit_id = self.unit_id.clone();
3667
3668        // Locked-down WASI policy — same rationale as
3669        // `invoke_identify_instance`. See [`register_identity_probe`] docs.
3670        let wasi_policy = Arc::new(RunnerWasiPolicy::probe());
3671        let runtime_config_non_secret = self.runtime_config_non_secret.clone();
3672        let runtime_refs = self.runtime_refs.clone();
3673        run_on_wasi_thread("provider.describe_identify_instance", move || {
3674            let mut linker = Linker::new(&engine);
3675            register_identity_probe(&mut linker)?;
3676            let host_state = HostState::new(
3677                pack_id.clone(),
3678                config,
3679                http_client,
3680                mocks,
3681                session_store,
3682                state_store,
3683                secrets,
3684                oauth_config,
3685                None,
3686                Some(component_ref_owned.clone()),
3687                true,
3688                runtime_config_non_secret,
3689                runtime_refs,
3690            )?
3691            .with_unit(unit_id.clone());
3692            let store_state = ComponentState::new(host_state, wasi_policy)?;
3693            let mut store = new_limited_store(&engine, store_state);
3694
3695            let pre_instance = linker.instantiate_pre(component.as_ref())?;
3696            let pre = match InstanceIdentityDescribePre::<ComponentState>::new(pre_instance) {
3697                Ok(pre) => pre,
3698                Err(err) if is_missing_export_error(&format!("{err:#}")) => {
3699                    return Ok(None);
3700                }
3701                Err(err) => return Err(err.into()),
3702            };
3703            let bindings = block_on(async { pre.instantiate_async(&mut store).await })?;
3704            let api = bindings.greentic_provider_instance_identity_instance_identity_describe_api();
3705            let raw = api.call_describe_identify_instance(&mut store)?;
3706            let Some(bytes) = raw else {
3707                // Component exported the world but said "no hint right now".
3708                // Per the WIT contract this is equivalent to a missing
3709                // export — unhinted fallback at the caller.
3710                return Ok(None);
3711            };
3712            match IdentifyInstanceHint::from_json(&bytes) {
3713                Ok(hint) => Ok(Some(hint)),
3714                Err(err) => {
3715                    // Malformed hint or wrong version. Don't fail closed:
3716                    // the contract demands the host fall back to unhinted
3717                    // (invoke identify-instance with the global allowlist).
3718                    // Warn so the provider author can fix the hint.
3719                    warn!(
3720                        event = "provider.describe_identify_instance.malformed",
3721                        component_ref = %component_ref_owned,
3722                        error = %err,
3723                        "ignoring malformed describe-identify-instance hint; \
3724                         falling back to unhinted wrapper"
3725                    );
3726                    Ok(None)
3727                }
3728            }
3729        })
3730        .await
3731    }
3732
3733    /// Cached wrapper around [`invoke_describe_identify_instance`]. The
3734    /// hint for a given `binding.component_ref` is invariant across
3735    /// inbound requests within a revision (it is a function of the
3736    /// component itself, not of the payload), so we probe lazily on
3737    /// first ask and reuse thereafter. `ArcSwap`-driven revision swaps
3738    /// allocate a fresh [`PackRuntime`], naturally invalidating the cache.
3739    ///
3740    /// Returns `None` when the component does not export the describe
3741    /// world, when the probe returns no hint, or when the probe fails
3742    /// (trap, timeout, instantiation error). Failures are warn-logged and
3743    /// remembered only for a short backoff window (not cached permanently), so
3744    /// a transient error is retried while a persistent trap is not re-run on
3745    /// every request.
3746    ///
3747    /// [`invoke_describe_identify_instance`]:
3748    ///     PackRuntime::invoke_describe_identify_instance
3749    pub async fn resolve_identify_hint(
3750        &self,
3751        binding: &ProviderBinding,
3752    ) -> Option<IdentifyInstanceHint> {
3753        if let Some(cached) = self.identify_hint_cache.read().get(&binding.component_ref) {
3754            return cached.clone();
3755        }
3756        let failed_at = self
3757            .identify_hint_failures
3758            .read()
3759            .get(&binding.component_ref)
3760            .copied();
3761        if identify_failure_backoff_active(failed_at, std::time::Instant::now()) {
3762            return None;
3763        }
3764        let hint = match self.invoke_describe_identify_instance(binding).await {
3765            Ok(hint) => hint,
3766            Err(err) => {
3767                warn!(
3768                    event = "provider.describe_identify_instance.failed",
3769                    component_ref = %binding.component_ref,
3770                    error = %err,
3771                    "describe-identify-instance probe failed; \
3772                     falling back to unhinted wrapper for this component \
3773                     (the probe is retried after a short backoff)"
3774                );
3775                // Do not cache the failure as a permanent `None`.
3776                self.identify_hint_failures
3777                    .write()
3778                    .insert(binding.component_ref.clone(), std::time::Instant::now());
3779                return None;
3780            }
3781        };
3782        self.identify_hint_failures
3783            .write()
3784            .remove(&binding.component_ref);
3785        // Tolerate a concurrent populate — `insert` is idempotent on the
3786        // same (component_ref, hint) shape and the probe is pure w.r.t.
3787        // the component, so re-probing on a write-race yields identical
3788        // bytes.
3789        self.identify_hint_cache
3790            .write()
3791            .insert(binding.component_ref.clone(), hint.clone());
3792        hint
3793    }
3794
3795    /// Fan out [`resolve_identify_hint`] over each requested `provider_type`.
3796    /// Result map is keyed by `provider_type`; `None` value means the
3797    /// pack has no binding for that type OR the binding's component does
3798    /// not export the describe world (unhinted — caller forwards input
3799    /// headers unfiltered for back-compat).
3800    ///
3801    /// `provider_id`-collision errors from [`ProviderRegistry::resolve`]
3802    /// against a `provider_type` query are propagated (M1.1 invariant
3803    /// violation, malformed pack).
3804    ///
3805    /// Fan out [`resolve_identify_hint`] across requested types. `None` value
3806    /// means the pack has no binding for that type OR the binding's component
3807    /// does not export the describe world.
3808    ///
3809    /// The per-binding loop is inlined (rather than factored into a shared
3810    /// `AsyncFnMut`-based helper) deliberately: routing through an
3811    /// `AsyncFnMut` closure destabilises HRTB `Send` inference for the
3812    /// returned future, which propagates up to host-level fan-out APIs and
3813    /// from there to downstream spawned-service consumers. See the
3814    /// regression test `identify_futures_are_send` on the host.
3815    ///
3816    /// [`resolve_identify_hint`]: PackRuntime::resolve_identify_hint
3817    pub async fn describe_identify_hints_by_provider_type(
3818        &self,
3819        provider_types: &[&str],
3820    ) -> Result<HashMap<String, Option<IdentifyInstanceHint>>> {
3821        let mut out = HashMap::with_capacity(provider_types.len());
3822        let registry = match self.provider_registry_optional()? {
3823            Some(registry) => registry,
3824            None => {
3825                for ty in provider_types {
3826                    out.insert((*ty).to_string(), None);
3827                }
3828                return Ok(out);
3829            }
3830        };
3831        for ty in provider_types {
3832            let Some(binding) = registry.try_resolve(None, Some(ty))? else {
3833                out.insert((*ty).to_string(), None);
3834                continue;
3835            };
3836            let hint = self.resolve_identify_hint(&binding).await;
3837            out.insert((*ty).to_string(), hint);
3838        }
3839        Ok(out)
3840    }
3841
3842    /// Unscoped legacy API: fan out [`invoke_identify_instance`] with the
3843    /// caller-supplied opaque `payload` bytes forwarded verbatim. No
3844    /// describe-identify-instance hint lookup, no per-provider header
3845    /// scoping. New callers should use the `_scoped` sibling for
3846    /// per-provider header allowlist scoping (Phase D).
3847    ///
3848    /// Loop inlined for the same reason as
3849    /// [`describe_identify_hints_by_provider_type`].
3850    ///
3851    /// [`invoke_identify_instance`]: PackRuntime::invoke_identify_instance
3852    /// [`describe_identify_hints_by_provider_type`]:
3853    ///     PackRuntime::describe_identify_hints_by_provider_type
3854    pub async fn identify_endpoints_by_provider_type(
3855        &self,
3856        provider_types: &[&str],
3857        payload: &[u8],
3858    ) -> Result<HashMap<String, IdentifyOutcome>> {
3859        let mut out = HashMap::with_capacity(provider_types.len());
3860        let registry = match self.provider_registry_optional()? {
3861            Some(registry) => registry,
3862            None => {
3863                for ty in provider_types {
3864                    out.insert((*ty).to_string(), IdentifyOutcome::Unsupported);
3865                }
3866                return Ok(out);
3867            }
3868        };
3869        for ty in provider_types {
3870            let Some(binding) = registry.try_resolve(None, Some(ty))? else {
3871                out.insert((*ty).to_string(), IdentifyOutcome::Unsupported);
3872                continue;
3873            };
3874            let outcome = self
3875                .invoke_identify_instance(&binding, payload.to_vec())
3876                .await?;
3877            out.insert((*ty).to_string(), outcome);
3878        }
3879        Ok(out)
3880    }
3881
3882    /// Per-provider scoped variant of [`identify_endpoints_by_provider_type`].
3883    ///
3884    /// The wrapper payload is built per-binding from `(headers, body)` and
3885    /// the component's cached identify-instance hint (see
3886    /// [`resolve_identify_hint`]): hinted providers see only the headers
3887    /// their hint declares; unhinted providers see every header passed in.
3888    /// Result-map semantics match the unscoped variant.
3889    ///
3890    /// Loop inlined for the same reason as
3891    /// [`describe_identify_hints_by_provider_type`].
3892    ///
3893    /// [`identify_endpoints_by_provider_type`]:
3894    ///     PackRuntime::identify_endpoints_by_provider_type
3895    /// [`resolve_identify_hint`]: PackRuntime::resolve_identify_hint
3896    /// [`describe_identify_hints_by_provider_type`]:
3897    ///     PackRuntime::describe_identify_hints_by_provider_type
3898    pub async fn identify_endpoints_by_provider_type_scoped(
3899        &self,
3900        provider_types: &[&str],
3901        headers: &[(String, String)],
3902        body: &Value,
3903    ) -> Result<HashMap<String, IdentifyOutcome>> {
3904        let mut out = HashMap::with_capacity(provider_types.len());
3905        let registry = match self.provider_registry_optional()? {
3906            Some(registry) => registry,
3907            None => {
3908                for ty in provider_types {
3909                    out.insert((*ty).to_string(), IdentifyOutcome::Unsupported);
3910                }
3911                return Ok(out);
3912            }
3913        };
3914        for ty in provider_types {
3915            let Some(binding) = registry.try_resolve(None, Some(ty))? else {
3916                out.insert((*ty).to_string(), IdentifyOutcome::Unsupported);
3917                continue;
3918            };
3919            let hint = self.resolve_identify_hint(&binding).await;
3920            let payload = build_scoped_identify_payload(headers, body, hint.as_ref());
3921            let outcome = self.invoke_identify_instance(&binding, payload).await?;
3922            out.insert((*ty).to_string(), outcome);
3923        }
3924        Ok(out)
3925    }
3926
3927    pub(crate) fn provider_registry(&self) -> Result<ProviderRegistry> {
3928        if let Some(registry) = self.provider_registry.read().clone() {
3929            return Ok(registry);
3930        }
3931        let manifest = self
3932            .manifest
3933            .as_ref()
3934            .context("pack manifest required for provider resolution")?;
3935        let env = crate::config::greentic_env_or_local();
3936        let registry = ProviderRegistry::new(
3937            manifest,
3938            self.state_store.clone(),
3939            &self.config.tenant,
3940            &env,
3941        )?;
3942        *self.provider_registry.write() = Some(registry.clone());
3943        Ok(registry)
3944    }
3945
3946    pub(crate) fn provider_registry_optional(&self) -> Result<Option<ProviderRegistry>> {
3947        if self.manifest.is_none() {
3948            return Ok(None);
3949        }
3950        Ok(Some(self.provider_registry()?))
3951    }
3952
3953    pub fn load_flow(&self, flow_id: &str) -> Result<Flow> {
3954        if let Some(cache) = &self.flows {
3955            return cache
3956                .flows
3957                .get(flow_id)
3958                .cloned()
3959                .ok_or_else(|| anyhow!("flow '{flow_id}' not found in pack"));
3960        }
3961        if let Some(manifest) = &self.manifest {
3962            let entry = manifest
3963                .flows
3964                .iter()
3965                .find(|f| f.id.as_str() == flow_id)
3966                .ok_or_else(|| anyhow!("flow '{flow_id}' not found in manifest"))?;
3967            return Ok(entry.flow.clone());
3968        }
3969        bail!("flow '{flow_id}' not available (pack exports disabled)")
3970    }
3971
3972    pub fn metadata(&self) -> &PackMetadata {
3973        &self.metadata
3974    }
3975
3976    /// The manifest's human `name`, when the pack declares one (blank counts
3977    /// as absent). A legacy manifest carries no name.
3978    pub fn manifest_name(&self) -> Option<&str> {
3979        self.manifest
3980            .as_ref()
3981            .and_then(|manifest| manifest.name.as_deref())
3982            .map(str::trim)
3983            .filter(|name| !name.is_empty())
3984    }
3985
3986    /// Archive this runtime was loaded from, when it came from one. The pack
3987    /// watcher uses it to keep the cached copy of a runtime it retains alive.
3988    pub fn archive_path(&self) -> Option<&Path> {
3989        self.archive_path.as_deref()
3990    }
3991
3992    /// Read an asset file from the pack's assets directory.
3993    ///
3994    /// Accepts paths like `assets/cards/card-a.json` or `cards/card-a.json`
3995    /// (the `assets/` prefix is stripped automatically).
3996    pub fn read_asset(&self, asset_path: &str) -> Result<Vec<u8>> {
3997        let normalized = asset_path
3998            .trim_start_matches("assets/")
3999            .trim_start_matches("/assets/");
4000        // Try assets tempdir first (extracted from archive).
4001        if let Some(tempdir) = &self.assets_tempdir
4002            && let Some(full) = confined_asset_path(&tempdir.path().join("assets"), normalized)?
4003        {
4004            return std::fs::read(&full).with_context(|| format!("read asset {}", full.display()));
4005        }
4006        // Try materialized directory.
4007        if let Some(full) = confined_asset_path(&self.path.join("assets"), normalized)? {
4008            return std::fs::read(&full).with_context(|| format!("read asset {}", full.display()));
4009        }
4010        bail!("asset not found: {}", asset_path)
4011    }
4012
4013    pub fn component_manifest(&self, component_ref: &str) -> Option<&ComponentManifest> {
4014        self.component_manifests.get(component_ref)
4015    }
4016
4017    /// Iterate every `(component_ref, manifest)` this pack holds. Used by the
4018    /// agentic-worker component tool source to enumerate the operations a
4019    /// worker may call as tools without exposing the internal manifest map.
4020    pub fn component_manifest_entries(&self) -> impl Iterator<Item = (&str, &ComponentManifest)> {
4021        self.component_manifests
4022            .iter()
4023            .map(|(component_ref, manifest)| (component_ref.as_str(), manifest))
4024    }
4025
4026    /// Returns the raw agent config blobs embedded in this pack's manifest.
4027    ///
4028    /// Only present on the New (`greentic_types::PackManifest`) path; Legacy
4029    /// packs do not carry agent config and return an empty map. Callers
4030    /// (e.g. `TenantRuntime::from_packs`) deserialize these blobs into
4031    /// concrete `AgentConfig` structs via
4032    /// `agent_node::agent_configs_from_manifest`.
4033    pub fn manifest_agent_blobs(&self) -> std::collections::BTreeMap<String, serde_json::Value> {
4034        self.manifest
4035            .as_ref()
4036            .map(|m| m.agents.clone())
4037            .unwrap_or_default()
4038    }
4039
4040    /// Read the optional `agent-graph.json` sidecar embedded at the pack root.
4041    ///
4042    /// Returns the raw bytes when present, or `None` when the pack carries no
4043    /// sidecar (the common case). Tries the materialized pack directory first,
4044    /// then the `.gtpack` archive — mirroring [`load_schema_json`]'s resolution.
4045    /// IO/zip errors are logged and treated as "absent" so a damaged or
4046    /// unreadable sidecar never aborts pack loading; the caller
4047    /// (`graph_node::graph_config_from_sidecar`) then validates the bytes.
4048    ///
4049    /// [`load_schema_json`]: PackRuntime::load_schema_json
4050    pub fn read_agent_graph_sidecar(&self) -> Option<Vec<u8>> {
4051        self.read_pack_file("agent-graph.json")
4052    }
4053
4054    /// Archive-relative entry names of the design-extension `.gtxpack` archives
4055    /// this pack carries, sorted and deduplicated.
4056    ///
4057    /// Reads the materialized pack directory and the `.gtpack` archive, the
4058    /// same two sources — in the same order — as [`PackRuntime::read_pack_file`],
4059    /// so an entry this returns is one that call can then read.
4060    ///
4061    /// The `.gtxpack` suffix, not membership of `extensions/`, is what makes an
4062    /// entry an extension: that directory already carries the wizard's
4063    /// `extensions/*.json` manifest sidecars, which predate this feature and are
4064    /// not extensions. The rule lives in
4065    /// [`crate::runner::pack_extensions::is_extension_archive_entry`], beside
4066    /// the contract it comes from.
4067    ///
4068    /// An empty result is the normal reading of a pack built before the feature,
4069    /// and of any pack whose worker binds no extension tools.
4070    #[cfg(feature = "agentic-worker")]
4071    pub fn extension_archive_entries(&self) -> Vec<String> {
4072        use crate::runner::pack_extensions::{EXTENSIONS_PREFIX, is_extension_archive_entry};
4073
4074        let mut names = std::collections::BTreeSet::new();
4075
4076        if self.path.is_dir() {
4077            let dir = self.path.join(EXTENSIONS_PREFIX.trim_end_matches('/'));
4078            match std::fs::read_dir(&dir) {
4079                Ok(entries) => {
4080                    for entry in entries.flatten() {
4081                        if !entry
4082                            .file_type()
4083                            .map(|kind| kind.is_file())
4084                            .unwrap_or(false)
4085                        {
4086                            continue;
4087                        }
4088                        let Some(file_name) = entry.file_name().to_str().map(str::to_string) else {
4089                            continue;
4090                        };
4091                        let candidate = format!("{EXTENSIONS_PREFIX}{file_name}");
4092                        if is_extension_archive_entry(&candidate) {
4093                            names.insert(candidate);
4094                        }
4095                    }
4096                }
4097                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
4098                Err(error) => tracing::warn!(
4099                    path = %dir.display(),
4100                    error = %error,
4101                    "failed to list the pack's extensions directory"
4102                ),
4103            }
4104        }
4105
4106        if let Some(archive_path) = self
4107            .archive_path
4108            .as_ref()
4109            .or_else(|| path_is_gtpack(&self.path).then_some(&self.path))
4110        {
4111            match File::open(archive_path)
4112                .map_err(anyhow::Error::from)
4113                .and_then(|file| ZipArchive::new(file).map_err(anyhow::Error::from))
4114            {
4115                Ok(archive) => names.extend(
4116                    archive
4117                        .file_names()
4118                        .filter(|name| is_extension_archive_entry(name))
4119                        .map(str::to_string),
4120                ),
4121                Err(error) => tracing::warn!(
4122                    path = %archive_path.display(),
4123                    error = %error,
4124                    "failed to read the pack archive while listing extensions"
4125                ),
4126            }
4127        }
4128
4129        names.into_iter().collect()
4130    }
4131
4132    /// Every playbook document the pack carries, as bare ids.
4133    ///
4134    /// The contract is one file per playbook at `assets/playbooks/<id>.yaml`
4135    /// with no index beside it, because every field a listing needs is inside
4136    /// each document — so enumerating the directory is the only way to find
4137    /// them, and [`PackRuntime::read_asset`] can then read one by id.
4138    ///
4139    /// Searched in the same places assets are, and for the same reason
4140    /// [`extension_archive_entries`](Self::extension_archive_entries) searches
4141    /// two: the extracted tempdir an archive-backed pack holds, the
4142    /// materialized directory, and the archive itself. A `BTreeSet` makes the
4143    /// result stable and deduplicates a pack that has both.
4144    ///
4145    /// An empty result is the normal reading of a pack that carries no
4146    /// playbooks — which is every pack built before the feature.
4147    #[cfg(feature = "agentic-worker")]
4148    pub fn playbook_ids(&self) -> Vec<String> {
4149        const PREFIX: &str = "assets/playbooks/";
4150        const SUFFIX: &str = ".yaml";
4151
4152        fn id_of(name: &str) -> Option<String> {
4153            let rest = name.strip_prefix(PREFIX)?.strip_suffix(SUFFIX)?;
4154            // One level only: a nested path is not an id this reader can
4155            // address through `read_asset`, so it is not a playbook.
4156            (!rest.is_empty() && !rest.contains('/')).then(|| rest.to_string())
4157        }
4158
4159        let mut ids = std::collections::BTreeSet::new();
4160
4161        let mut scan_dir = |root: &std::path::Path| {
4162            let dir = root.join(PREFIX.trim_end_matches('/'));
4163            match std::fs::read_dir(&dir) {
4164                Ok(entries) => {
4165                    for entry in entries.flatten() {
4166                        if !entry
4167                            .file_type()
4168                            .map(|kind| kind.is_file())
4169                            .unwrap_or(false)
4170                        {
4171                            continue;
4172                        }
4173                        let Some(file_name) = entry.file_name().to_str().map(str::to_string) else {
4174                            continue;
4175                        };
4176                        if let Some(id) = id_of(&format!("{PREFIX}{file_name}")) {
4177                            ids.insert(id);
4178                        }
4179                    }
4180                }
4181                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
4182                Err(error) => tracing::warn!(
4183                    path = %dir.display(),
4184                    error = %error,
4185                    "failed to list the pack's playbooks directory"
4186                ),
4187            }
4188        };
4189
4190        if let Some(tempdir) = &self.assets_tempdir {
4191            scan_dir(tempdir.path());
4192        }
4193        if self.path.is_dir() {
4194            scan_dir(&self.path);
4195        }
4196
4197        if let Some(archive_path) = self
4198            .archive_path
4199            .as_ref()
4200            .or_else(|| path_is_gtpack(&self.path).then_some(&self.path))
4201        {
4202            match File::open(archive_path)
4203                .map_err(anyhow::Error::from)
4204                .and_then(|file| ZipArchive::new(file).map_err(anyhow::Error::from))
4205            {
4206                Ok(archive) => ids.extend(archive.file_names().filter_map(id_of)),
4207                Err(error) => tracing::warn!(
4208                    path = %archive_path.display(),
4209                    error = %error,
4210                    "failed to read the pack archive while listing playbooks"
4211                ),
4212            }
4213        }
4214
4215        ids.into_iter().collect()
4216    }
4217
4218    /// MCP route material from the optional `assets/mcp-routes.json` sidecar.
4219    ///
4220    /// `None` when the pack carries none — which is how a pack built before
4221    /// the feature reads, and means "fall back to the tenant's admin catalog"
4222    /// rather than "this pack has no MCP servers".
4223    ///
4224    /// Parsed at most once per `PackRuntime` and memoized: a hot reload
4225    /// allocates a fresh `PackRuntime`, so there is nothing to invalidate.
4226    pub fn mcp_routes(&self) -> Option<&crate::runner::mcp_pack_routes::PackMcpRoutes> {
4227        self.mcp_routes
4228            .get_or_init(|| {
4229                self.read_pack_file(crate::runner::mcp_pack_routes::MCP_ROUTES_ENTRY)
4230                    .and_then(|bytes| {
4231                        crate::runner::mcp_pack_routes::PackMcpRoutes::from_sidecar_bytes(&bytes)
4232                    })
4233            })
4234            .as_ref()
4235    }
4236
4237    /// A2A agent route material from the optional `assets/a2a-routes.json`
4238    /// sidecar (cross-repo contract 2026-09-21 §4).
4239    ///
4240    /// `None` when the pack carries none. That is how a pack built before
4241    /// the feature reads, and it means "no A2A agents". Parsed at most once
4242    /// per `PackRuntime`; a hot reload allocates a fresh one.
4243    pub fn a2a_routes(&self) -> Option<&crate::runner::a2a_pack_routes::PackA2aRoutes> {
4244        self.a2a_routes
4245            .get_or_init(|| {
4246                self.read_pack_file(crate::runner::a2a_pack_routes::A2A_ROUTES_ENTRY)
4247                    .and_then(|bytes| {
4248                        crate::runner::a2a_pack_routes::PackA2aRoutes::from_sidecar_bytes(&bytes)
4249                    })
4250            })
4251            .as_ref()
4252    }
4253
4254    /// Per-binding sharing modes from the optional `assets/run-context.json`
4255    /// sidecar (shared context, Phase A2). `None` when the pack carries none,
4256    /// which means every binding of every agent is `none`.
4257    ///
4258    /// Parsed at most once per `PackRuntime` (lazily), but
4259    /// `share_policy_from_packs` (agent_node.rs) calls it for EVERY pack at
4260    /// each agent-runtime build, so the sidecar is in practice read when a
4261    /// runtime is built, not only when an agent first shares.
4262    pub fn run_context(&self) -> Option<&crate::runner::run_context_routes::PackRunContext> {
4263        self.run_context
4264            .get_or_init(|| {
4265                self.read_pack_file(crate::runner::run_context_routes::RUN_CONTEXT_ENTRY)
4266                    .and_then(|bytes| {
4267                        crate::runner::run_context_routes::PackRunContext::from_sidecar_bytes(
4268                            &bytes,
4269                        )
4270                    })
4271            })
4272            .as_ref()
4273    }
4274
4275    /// Agents that use the user ledger, from the optional
4276    /// `assets/user-ledger.json` sidecar. `None` when the pack carries none
4277    /// (or it was malformed/oversized): then no agent uses the ledger.
4278    pub fn user_ledger(&self) -> Option<&crate::runner::user_ledger_routes::PackUserLedger> {
4279        self.user_ledger
4280            .get_or_init(|| {
4281                self.read_pack_file(crate::runner::user_ledger_routes::USER_LEDGER_ENTRY)
4282                    .and_then(|bytes| {
4283                        crate::runner::user_ledger_routes::PackUserLedger::from_sidecar_bytes(
4284                            &bytes,
4285                        )
4286                    })
4287            })
4288            .as_ref()
4289    }
4290
4291    /// SoR requirements from the optional `assets/sorla-routes.json` sidecar.
4292    ///
4293    /// `None` when the pack carries none — a pack built before the feature,
4294    /// or one with no `sorla.call` nodes and no worker tools bound to a SoR.
4295    /// Parsed at most once per `PackRuntime`; a hot reload allocates a fresh
4296    /// one.
4297    pub fn sorla_routes(&self) -> Option<&crate::runner::sorla_pack_routes::PackSorlaRoutes> {
4298        self.sorla_routes
4299            .get_or_init(|| {
4300                self.read_pack_file(crate::runner::sorla_pack_routes::SORLA_ROUTES_ENTRY)
4301                    .and_then(|bytes| {
4302                        crate::runner::sorla_pack_routes::PackSorlaRoutes::from_sidecar_bytes(
4303                            &bytes,
4304                        )
4305                    })
4306            })
4307            .as_ref()
4308    }
4309
4310    /// Raw agent-config blobs from the optional `dw-agents.json` sidecar.
4311    ///
4312    /// Designer-built packs (old greentic-pack, which cannot populate
4313    /// `manifest.agents`) embed their `AgentConfig` map here. Returns an empty
4314    /// map when the sidecar is absent or unparseable (lenient, mirroring
4315    /// [`PackRuntime::manifest_agent_blobs`]) so a damaged sidecar never aborts
4316    /// pack loading. `manifest.agents` remains authoritative; callers fill only
4317    /// the agent_ids the manifest did not carry.
4318    pub fn dw_agents_sidecar_blobs(&self) -> std::collections::BTreeMap<String, serde_json::Value> {
4319        let Some(bytes) = self.read_pack_file("dw-agents.json") else {
4320            return std::collections::BTreeMap::new();
4321        };
4322        match serde_json::from_slice::<std::collections::BTreeMap<String, serde_json::Value>>(
4323            &bytes,
4324        ) {
4325            Ok(map) => map,
4326            Err(error) => {
4327                tracing::warn!(error = %error, "ignoring malformed dw-agents.json sidecar");
4328                std::collections::BTreeMap::new()
4329            }
4330        }
4331    }
4332
4333    /// Read a single named file from the pack by its archive-relative path,
4334    /// trying the materialized pack directory first and the `.gtpack` archive as
4335    /// a fallback. Returns `None` when the file is absent (or on a read error,
4336    /// which is logged). Used for sidecar files (`agent-graph.json`) and bundled
4337    /// assets (`knowledge_corpus.json`, `assets/knowledge/*.txt`).
4338    pub fn read_pack_file(&self, name: &str) -> Option<Vec<u8>> {
4339        self.read_pack_file_capped(name, MAX_ARCHIVE_ENTRY_READ_BYTES)
4340    }
4341
4342    /// [`read_pack_file`](Self::read_pack_file) with a caller-chosen ceiling
4343    /// (never above [`MAX_ARCHIVE_ENTRY_READ_BYTES`]). An entry larger than
4344    /// `limit` yields `None` after at most `limit + 1` bytes were read, so a
4345    /// caller with a budget never holds an over-budget entry in memory.
4346    pub fn read_pack_file_capped(&self, name: &str, limit: u64) -> Option<Vec<u8>> {
4347        let limit = limit.min(MAX_ARCHIVE_ENTRY_READ_BYTES);
4348        // Materialized pack directory (root holds manifest.cbor + sidecars/assets).
4349        if self.path.is_dir() {
4350            // `name` can come from pack-authored content (a corpus sidecar's
4351            // asset paths), so it must not leave the pack directory.
4352            let confined = match confined_asset_path(&self.path, name) {
4353                Ok(found) => found,
4354                Err(error) => {
4355                    tracing::warn!(
4356                        error = %error,
4357                        "refusing to read {name} from pack directory"
4358                    );
4359                    return None;
4360                }
4361            };
4362            if let Some(candidate) = confined {
4363                match File::open(&candidate)
4364                    .and_then(|mut file| read_to_end_bounded(&mut file, limit))
4365                {
4366                    Ok(bytes) => return Some(bytes),
4367                    Err(error) => {
4368                        tracing::warn!(
4369                            path = %candidate.display(),
4370                            error = %error,
4371                            "failed to read {name} from pack directory"
4372                        );
4373                        return None;
4374                    }
4375                }
4376            }
4377        }
4378
4379        // `.gtpack` archive.
4380        let archive_path = self
4381            .archive_path
4382            .as_ref()
4383            .or_else(|| path_is_gtpack(&self.path).then_some(&self.path))?;
4384        let file = match File::open(archive_path) {
4385            Ok(file) => file,
4386            Err(error) => {
4387                tracing::warn!(
4388                    path = %archive_path.display(),
4389                    error = %error,
4390                    "failed to open pack archive while reading {name}"
4391                );
4392                return None;
4393            }
4394        };
4395        let mut archive = match ZipArchive::new(file) {
4396            Ok(archive) => archive,
4397            Err(error) => {
4398                tracing::warn!(
4399                    path = %archive_path.display(),
4400                    error = %error,
4401                    "failed to read pack archive while reading {name}"
4402                );
4403                return None;
4404            }
4405        };
4406        match archive.by_name(name) {
4407            Ok(mut entry) => match read_to_end_bounded(&mut entry, limit) {
4408                Ok(bytes) => Some(bytes),
4409                Err(error) => {
4410                    tracing::warn!(
4411                        path = %archive_path.display(),
4412                        error = %error,
4413                        "failed to extract {name} from pack archive"
4414                    );
4415                    None
4416                }
4417            },
4418            Err(zip::result::ZipError::FileNotFound) => None,
4419            Err(error) => {
4420                tracing::warn!(
4421                    path = %archive_path.display(),
4422                    error = %error,
4423                    "error reading {name} from pack archive"
4424                );
4425                None
4426            }
4427        }
4428    }
4429
4430    pub fn describe_component_contract_v0_6(&self, component_ref: &str) -> Result<Option<Value>> {
4431        let pack_component = self
4432            .components
4433            .get(component_ref)
4434            .with_context(|| format!("component '{component_ref}' not found in pack"))?;
4435        let engine = self.engine.clone();
4436        let config = Arc::clone(&self.config);
4437        let http_client = Arc::clone(&self.http_client);
4438        let mocks = self.mocks.clone();
4439        let session_store = self.session_store.clone();
4440        let state_store = self.state_store.clone();
4441        let secrets = Arc::clone(&self.secrets);
4442        let oauth_config = self.oauth_config.clone();
4443        let wasi_policy = Arc::clone(&self.wasi_policy);
4444        let pack_id = self.metadata().pack_id.clone();
4445        // Hoisted with `pack_id`: the WASI closure below is `move` and must not
4446        // borrow `self`.
4447        let unit_id = self.unit_id.clone();
4448        let allow_state_store = self.allows_state_store(component_ref);
4449        let component = pack_component.component.clone();
4450        let component_ref_owned = component_ref.to_string();
4451        let runtime_config_non_secret = self.runtime_config_non_secret.clone();
4452        let runtime_refs = self.runtime_refs.clone();
4453
4454        run_on_wasi_thread_blocking("component.describe", move || {
4455            let mut linker = Linker::new(&engine);
4456            register_all(&mut linker, allow_state_store)?;
4457            add_component_control_to_linker(&mut linker)?;
4458
4459            let host_state = HostState::new(
4460                pack_id.clone(),
4461                config,
4462                http_client,
4463                mocks,
4464                session_store,
4465                state_store,
4466                secrets,
4467                oauth_config,
4468                None,
4469                Some(component_ref_owned),
4470                false,
4471                runtime_config_non_secret,
4472                runtime_refs,
4473            )?
4474            .with_unit(unit_id.clone());
4475            let store_state = ComponentState::new(host_state, wasi_policy)?;
4476            let mut store = new_limited_store(&engine, store_state);
4477            let pre_instance = linker.instantiate_pre(&component)?;
4478            let pre = match component_api::v0_6_descriptor::ComponentV0V6V0Pre::new(pre_instance) {
4479                Ok(pre) => pre,
4480                Err(_) => return Ok(None),
4481            };
4482            let bytes = block_on(async {
4483                let bindings = pre.instantiate_async(&mut store).await?;
4484                let descriptor = bindings.greentic_component_component_descriptor();
4485                descriptor.call_describe(&mut store)
4486            })?;
4487
4488            if bytes.is_empty() {
4489                return Ok(Some(Value::Null));
4490            }
4491            if let Ok(value) = serde_cbor::from_slice::<Value>(&bytes) {
4492                return Ok(Some(value));
4493            }
4494            if let Ok(value) = serde_json::from_slice::<Value>(&bytes) {
4495                return Ok(Some(value));
4496            }
4497            if let Ok(text) = String::from_utf8(bytes) {
4498                if let Ok(value) = serde_json::from_str::<Value>(&text) {
4499                    return Ok(Some(value));
4500                }
4501                return Ok(Some(Value::String(text)));
4502            }
4503            Ok(Some(Value::Null))
4504        })
4505    }
4506
4507    pub fn load_schema_json(&self, schema_ref: &str) -> Result<Option<Value>> {
4508        let rel = normalize_schema_ref(schema_ref)?;
4509        if self.path.is_dir() {
4510            let candidate = self.path.join(&rel);
4511            if candidate.exists() {
4512                let bytes = std::fs::read(&candidate).with_context(|| {
4513                    format!("failed to read schema file {}", candidate.display())
4514                })?;
4515                let value = serde_json::from_slice::<Value>(&bytes)
4516                    .with_context(|| format!("invalid schema JSON in {}", candidate.display()))?;
4517                return Ok(Some(value));
4518            }
4519        }
4520
4521        if let Some(archive_path) = self
4522            .archive_path
4523            .as_ref()
4524            .or_else(|| path_is_gtpack(&self.path).then_some(&self.path))
4525        {
4526            let file = File::open(archive_path)
4527                .with_context(|| format!("failed to open {}", archive_path.display()))?;
4528            let mut archive = ZipArchive::new(file)
4529                .with_context(|| format!("failed to read pack {}", archive_path.display()))?;
4530            match archive.by_name(&rel) {
4531                Ok(mut entry) => {
4532                    let bytes = read_to_end_bounded(&mut entry, MAX_ARCHIVE_ENTRY_READ_BYTES)?;
4533                    let value = serde_json::from_slice::<Value>(&bytes).with_context(|| {
4534                        format!("invalid schema JSON in {}:{}", archive_path.display(), rel)
4535                    })?;
4536                    Ok(Some(value))
4537                }
4538                Err(zip::result::ZipError::FileNotFound) => Ok(None),
4539                Err(err) => Err(anyhow!(err)).with_context(|| {
4540                    format!(
4541                        "failed to read schema `{}` from {}",
4542                        rel,
4543                        archive_path.display()
4544                    )
4545                }),
4546            }
4547        } else {
4548            Ok(None)
4549        }
4550    }
4551
4552    pub fn required_secrets(&self) -> &[greentic_types::SecretRequirement] {
4553        &self.metadata.secret_requirements
4554    }
4555
4556    pub fn missing_secrets(
4557        &self,
4558        tenant_ctx: &TypesTenantCtx,
4559    ) -> Vec<greentic_types::SecretRequirement> {
4560        let env = tenant_ctx.env.as_str().to_string();
4561        let tenant = tenant_ctx.tenant.as_str().to_string();
4562        let team = tenant_ctx.team.as_ref().map(|t| t.as_str().to_string());
4563        self.required_secrets()
4564            .iter()
4565            .filter(|req| {
4566                // scope must match current context if provided
4567                if let Some(scope) = &req.scope {
4568                    if scope.env != env {
4569                        return false;
4570                    }
4571                    if scope.tenant != tenant {
4572                        return false;
4573                    }
4574                    if let Some(ref team_req) = scope.team
4575                        && team.as_ref() != Some(team_req)
4576                    {
4577                        return false;
4578                    }
4579                }
4580                let ctx = self.config.tenant_ctx();
4581                // Unit scope first: a requirement this unit has its own value
4582                // for is SATISFIED, and reading only the shared address would
4583                // report it missing and block the deploy gate.
4584                read_pack_secret_blocking(
4585                    &self.secrets,
4586                    &ctx,
4587                    &self.metadata.pack_id,
4588                    self.unit_id.as_deref(),
4589                    canonicalize_secret_key(req.key.as_str()).as_str(),
4590                )
4591                .is_err()
4592            })
4593            .cloned()
4594            .collect()
4595    }
4596
4597    pub fn for_component_test(
4598        components: Vec<(String, PathBuf)>,
4599        flows: HashMap<String, FlowIR>,
4600        pack_id: &str,
4601        config: Arc<HostConfig>,
4602    ) -> Result<Self> {
4603        let engine = Engine::default();
4604        let engine_profile =
4605            EngineProfile::from_engine(&engine, CpuPolicy::Native, "default".to_string());
4606        let cache = CacheManager::new(CacheConfig::default(), engine_profile);
4607        let mut component_map = HashMap::new();
4608        for (name, path) in components {
4609            if !path.exists() {
4610                bail!("component artifact missing: {}", path.display());
4611            }
4612            let wasm_bytes = std::fs::read(&path)?;
4613            let component =
4614                Arc::new(Component::from_binary(&engine, &wasm_bytes).map_err(|err| {
4615                    anyhow!("failed to compile component {}: {err}", path.display())
4616                })?);
4617            component_map.insert(
4618                name.clone(),
4619                PackComponent {
4620                    name,
4621                    version: "0.0.0".into(),
4622                    component,
4623                },
4624            );
4625        }
4626
4627        let mut flow_map = HashMap::new();
4628        let mut descriptors = Vec::new();
4629        for (id, ir) in flows {
4630            let flow_type = ir.flow_type.clone();
4631            let flow = flow_ir_to_flow(ir)?;
4632            flow_map.insert(id.clone(), flow);
4633            descriptors.push(FlowDescriptor {
4634                id: id.clone(),
4635                flow_type,
4636                pack_id: pack_id.to_string(),
4637                profile: "test".into(),
4638                version: "0.0.0".into(),
4639                description: None,
4640                entry: true,
4641            });
4642        }
4643        let entry_flows = descriptors.iter().map(|flow| flow.id.clone()).collect();
4644        let metadata = PackMetadata {
4645            pack_id: pack_id.to_string(),
4646            version: "0.0.0".into(),
4647            entry_flows,
4648            secret_requirements: Vec::new(),
4649        };
4650        let flows_cache = PackFlows {
4651            descriptors: descriptors.clone(),
4652            flows: flow_map,
4653            metadata: metadata.clone(),
4654        };
4655
4656        Ok(Self {
4657            path: PathBuf::new(),
4658            archive_path: None,
4659            config,
4660            engine,
4661            metadata,
4662            manifest: None,
4663            legacy_manifest: None,
4664            component_manifests: HashMap::new(),
4665            mocks: None,
4666            flows: Some(flows_cache),
4667            components: component_map,
4668            http_client: shared_http_client()?,
4669            session_store: None,
4670            state_store: None,
4671            wasi_policy: Arc::new(RunnerWasiPolicy::new()),
4672            base_wasi_policy: Arc::new(RunnerWasiPolicy::new()),
4673            assets_tempdir: None,
4674            provider_registry: RwLock::new(None),
4675            identify_hint_cache: RwLock::new(HashMap::new()),
4676            identify_hint_failures: RwLock::new(HashMap::new()),
4677            secrets: crate::secrets::default_manager()?,
4678            oauth_config: None,
4679            cache,
4680            runtime_config_non_secret: None,
4681            runtime_refs: None,
4682            mcp_routes: std::sync::OnceLock::new(),
4683            a2a_routes: std::sync::OnceLock::new(),
4684            run_context: std::sync::OnceLock::new(),
4685            user_ledger: std::sync::OnceLock::new(),
4686            nested_flow_handlers: std::sync::OnceLock::new(),
4687            sorla_routes: std::sync::OnceLock::new(),
4688            unit_id: None,
4689        })
4690    }
4691}
4692
4693/// Resolve a flow node's component reference to the key under which the
4694/// component is actually registered, given the requested `operation` and a
4695/// `is_registered` membership predicate over the pack's component keys.
4696///
4697/// greentic-pack resolves a component node to a bare component symbol
4698/// (e.g. `ai.greentic.component-templates`) and carries the operation
4699/// separately, so the full reference is the registration key. Older,
4700/// hand-authored flows instead pack the operation into the node id
4701/// (`qa.process`) while registering the component under the bare name
4702/// (`qa`). For those, fall back to the segment before the last dot — but
4703/// ONLY when that trailing segment IS the requested operation. Without the
4704/// suffix check, a missing dotted component whose prefix happens to be a
4705/// *different* registered component (`ai.greentic.component-templates` absent,
4706/// `ai.greentic` present) would silently resolve to the wrong component and
4707/// run it with the caller's tenant/session/state/secrets. Returns the
4708/// reference unchanged when neither form matches, so the caller's
4709/// "not found" error names the original reference.
4710fn resolve_component_key<'a>(
4711    component_ref: &'a str,
4712    operation: &str,
4713    is_registered: impl Fn(&str) -> bool,
4714) -> &'a str {
4715    if is_registered(component_ref) {
4716        return component_ref;
4717    }
4718    if let Some((prefix, suffix)) = component_ref.rsplit_once('.')
4719        && suffix == operation
4720        && is_registered(prefix)
4721    {
4722        return prefix;
4723    }
4724    component_ref
4725}
4726
4727#[cfg(test)]
4728mod resolve_component_key_tests {
4729    use super::resolve_component_key;
4730    use std::collections::HashSet;
4731
4732    fn registered(keys: &[&'static str]) -> impl Fn(&str) -> bool {
4733        let set: HashSet<&'static str> = keys.iter().copied().collect();
4734        move |key: &str| set.contains(key)
4735    }
4736
4737    #[test]
4738    fn full_reference_is_used_when_registered() {
4739        // greentic-pack's resolved symbol: full ref is the registration key.
4740        let is_reg = registered(&["ai.greentic.component-templates", "ai.greentic"]);
4741        assert_eq!(
4742            resolve_component_key("ai.greentic.component-templates", "handle_message", is_reg),
4743            "ai.greentic.component-templates"
4744        );
4745    }
4746
4747    #[test]
4748    fn legacy_packed_id_falls_back_when_suffix_is_operation() {
4749        // `qa.process` packs op into the id; component registered as `qa`.
4750        let is_reg = registered(&["qa"]);
4751        assert_eq!(resolve_component_key("qa.process", "process", is_reg), "qa");
4752    }
4753
4754    #[test]
4755    fn drifted_dotted_reference_does_not_fall_back_to_prefix() {
4756        // Full symbol absent, a *different* prefix component present, and the
4757        // trailing segment is NOT the requested operation -> must not silently
4758        // resolve to the prefix; return the original so the caller errors out.
4759        let is_reg = registered(&["ai.greentic"]);
4760        assert_eq!(
4761            resolve_component_key("ai.greentic.component-templates", "handle_message", is_reg),
4762            "ai.greentic.component-templates"
4763        );
4764    }
4765
4766    #[test]
4767    fn unregistered_reference_is_returned_unchanged() {
4768        let is_reg = registered(&[]);
4769        assert_eq!(resolve_component_key("foo", "bar", is_reg), "foo");
4770    }
4771}
4772
4773fn normalize_schema_ref(schema_ref: &str) -> Result<String> {
4774    let candidate = schema_ref.trim();
4775    if candidate.is_empty() {
4776        bail!("schema ref cannot be empty");
4777    }
4778    let path = Path::new(candidate);
4779    if path.is_absolute() {
4780        bail!("schema ref must be relative: {}", schema_ref);
4781    }
4782    let mut normalized = PathBuf::new();
4783    for component in path.components() {
4784        match component {
4785            std::path::Component::Normal(part) => normalized.push(part),
4786            std::path::Component::CurDir => {}
4787            _ => bail!("schema ref must not contain traversal: {}", schema_ref),
4788        }
4789    }
4790    let normalized = normalized
4791        .to_str()
4792        .map(ToString::to_string)
4793        .ok_or_else(|| anyhow!("schema ref must be valid UTF-8"))?;
4794    if normalized.is_empty() {
4795        bail!("schema ref cannot normalize to empty path");
4796    }
4797    Ok(normalized)
4798}
4799
4800fn path_is_gtpack(path: &Path) -> bool {
4801    path.extension()
4802        .and_then(|ext| ext.to_str())
4803        .map(|ext| ext.eq_ignore_ascii_case("gtpack"))
4804        .unwrap_or(false)
4805}
4806
4807fn is_missing_node_export(err: &wasmtime::Error, version: &str) -> bool {
4808    let message = err.to_string();
4809    message.contains("no exported instance named")
4810        && message.contains(&format!("greentic:component/node@{version}"))
4811}
4812
4813struct PackFlows {
4814    descriptors: Vec<FlowDescriptor>,
4815    flows: HashMap<String, Flow>,
4816    metadata: PackMetadata,
4817}
4818
4819const RUNTIME_FLOW_EXTENSION_IDS: [&str; 3] = [
4820    "greentic.pack.runtime_flow",
4821    "greentic.pack.flow_runtime",
4822    "greentic.pack.runtime_flows",
4823];
4824
4825#[derive(Debug, Deserialize)]
4826struct RuntimeFlowBundle {
4827    flows: Vec<RuntimeFlow>,
4828}
4829
4830#[derive(Debug, Deserialize)]
4831struct RuntimeFlow {
4832    id: String,
4833    #[serde(alias = "flow_type")]
4834    kind: FlowKind,
4835    #[serde(default)]
4836    schema_version: Option<String>,
4837    #[serde(default)]
4838    start: Option<String>,
4839    #[serde(default)]
4840    entrypoints: BTreeMap<String, Value>,
4841    nodes: BTreeMap<String, RuntimeNode>,
4842    #[serde(default)]
4843    metadata: Option<FlowMetadata>,
4844}
4845
4846#[derive(Debug, Deserialize)]
4847struct RuntimeNode {
4848    #[serde(alias = "component")]
4849    component_id: String,
4850    #[serde(default, alias = "operation")]
4851    operation_name: Option<String>,
4852    #[serde(default, alias = "payload", alias = "input")]
4853    operation_payload: Value,
4854    #[serde(default)]
4855    config: Value,
4856    #[serde(default)]
4857    routing: Option<Routing>,
4858    #[serde(default)]
4859    telemetry: Option<TelemetryHints>,
4860}
4861
4862fn deserialize_json_bytes(bytes: Vec<u8>) -> Result<Value> {
4863    if bytes.is_empty() {
4864        return Ok(Value::Null);
4865    }
4866    serde_json::from_slice(&bytes).or_else(|_| {
4867        String::from_utf8(bytes)
4868            .map(Value::String)
4869            .map_err(|err| anyhow!(err))
4870    })
4871}
4872
4873/// `wasmtime::component::bindgen!` returns this error shape when a
4874/// `*Pre::new(...)` call resolves a world whose required export is
4875/// absent on the component. We treat that as "component does not opt
4876/// in" and let the caller fall back to the operator's statically
4877/// declared instance. Mirrors the same pattern in `invoke_provider`
4878/// for the legacy/path schema-core fallback.
4879///
4880/// The match is intentionally narrow: the error must mention BOTH a
4881/// broad wasmtime marker (`"no exported instance named"` or
4882/// `"no exported function named"`) AND the identity-world-specific
4883/// name segment (`"instance-identity-api"`, `"identify-instance"`,
4884/// `"instance-identity-describe-api"`, or `"describe-identify-instance"`).
4885/// A component that exports the identity world with a malformed
4886/// signature or a typo'd function name will NOT be silently treated
4887/// as unsupported — it will surface as a hard error.
4888fn is_missing_export_error(message: &str) -> bool {
4889    let has_broad_marker = message.contains("no exported instance named")
4890        || message.contains("no exported function named");
4891    let has_identity_segment = message.contains("instance-identity-api")
4892        || message.contains("identify-instance")
4893        || message.contains("instance-identity-describe-api")
4894        || message.contains("describe-identify-instance");
4895    has_broad_marker && has_identity_segment
4896}
4897
4898/// Build the M1 IID.4d wrapper payload (`{ headers, body }`) scoped per
4899/// the provider's [`IdentifyInstanceHint`].
4900///
4901/// - `Some(hint)` ⇒ headers are filtered to ONLY those whose lowercase
4902///   name appears in [`hint.header_names()`](IdentifyInstanceHint::header_names).
4903///   A hint with no `Header` sources yields `"headers": []` — the
4904///   component is declaring that it identifies from the body alone.
4905/// - `None` ⇒ headers pass through unfiltered. The caller is responsible
4906///   for prefiltering (greentic-start applies a global allowlist at the
4907///   ingress boundary), so back-compat with not-yet-hinted providers
4908///   matches the pre-PR-B2 behavior exactly: every probed component
4909///   receives every allowlisted header.
4910///
4911/// `body` is forwarded verbatim regardless of hint shape. Body-path
4912/// short-circuit (using the hint's `BodyPath { json_pointer }` to skip
4913/// invoking `identify-instance` entirely) is a deliberately-deferred
4914/// Phase D follow-up — the current pass scopes the header allowlist only.
4915fn build_scoped_identify_payload(
4916    headers: &[(String, String)],
4917    body: &Value,
4918    hint: Option<&IdentifyInstanceHint>,
4919) -> Vec<u8> {
4920    let scoped_headers: Vec<&(String, String)> = match hint {
4921        // Hints carry 1-3 source headers in practice; a linear scan beats
4922        // a HashSet for that size (no hash + no allocation).
4923        Some(hint) => {
4924            let allowed = hint.header_names();
4925            headers
4926                .iter()
4927                .filter(|(name, _)| allowed.contains(&name.as_str()))
4928                .collect()
4929        }
4930        None => headers.iter().collect(),
4931    };
4932    let wrapper = serde_json::json!({
4933        "headers": scoped_headers
4934            .iter()
4935            .map(|(name, value)| serde_json::json!({ "name": name, "value": value }))
4936            .collect::<Vec<_>>(),
4937        "body": body,
4938    });
4939    serde_json::to_vec(&wrapper).expect("wrapper payload always serializes")
4940}
4941
4942#[cfg(test)]
4943mod build_scoped_identify_payload_tests {
4944    use super::*;
4945    use crate::identify_hint::HintSource;
4946    use serde_json::json;
4947
4948    fn hint(sources: Vec<HintSource>) -> IdentifyInstanceHint {
4949        IdentifyInstanceHint { sources }
4950    }
4951
4952    #[test]
4953    fn unhinted_passes_all_input_headers_through() {
4954        // Back-compat: components without describe-identify-instance must
4955        // continue to see every header the caller (greentic-start)
4956        // allowlisted. Pre-PR-B2 behavior verbatim.
4957        let headers = vec![
4958            (
4959                "x-telegram-bot-api-secret-token".into(),
4960                "telegram-tok".into(),
4961            ),
4962            ("x-future-routing-tag".into(), "abc".into()),
4963        ];
4964        let body = json!({ "update_id": 1 });
4965        let bytes = build_scoped_identify_payload(&headers, &body, None);
4966        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
4967        assert_eq!(
4968            parsed["headers"],
4969            json!([
4970                { "name": "x-telegram-bot-api-secret-token", "value": "telegram-tok" },
4971                { "name": "x-future-routing-tag", "value": "abc" }
4972            ])
4973        );
4974        assert_eq!(parsed["body"], body);
4975    }
4976
4977    #[test]
4978    fn header_hint_filters_to_declared_names_only() {
4979        // Telegram-shape hint: declares one header, sees only that one.
4980        // Other allowlisted headers (e.g. a future Slack signature) MUST
4981        // NOT leak into the Telegram probe.
4982        let h = hint(vec![HintSource::Header {
4983            name: "x-telegram-bot-api-secret-token".into(),
4984        }]);
4985        let headers = vec![
4986            (
4987                "x-telegram-bot-api-secret-token".into(),
4988                "telegram-tok".into(),
4989            ),
4990            ("x-slack-signature".into(), "v0=sig".into()),
4991        ];
4992        let body = json!({});
4993        let bytes = build_scoped_identify_payload(&headers, &body, Some(&h));
4994        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
4995        assert_eq!(
4996            parsed["headers"],
4997            json!([
4998                { "name": "x-telegram-bot-api-secret-token", "value": "telegram-tok" }
4999            ])
5000        );
5001    }
5002
5003    #[test]
5004    fn hints_without_header_sources_drop_all_headers() {
5005        // Body-path-only (Teams-shape) and degenerate-empty hints both yield
5006        // an empty `Header` source set; the wrapper MUST carry no headers
5007        // either way. Passing Telegram's secret token through to either is
5008        // the exact blast-radius bug PR-B2 closes.
5009        let headers = vec![(
5010            "x-telegram-bot-api-secret-token".into(),
5011            "should-not-leak".into(),
5012        )];
5013        let body = json!({ "anything": true });
5014        for h in [
5015            hint(vec![HintSource::BodyPath {
5016                json_pointer: "/recipient/id".into(),
5017            }]),
5018            hint(vec![]),
5019        ] {
5020            let bytes = build_scoped_identify_payload(&headers, &body, Some(&h));
5021            let parsed: Value = serde_json::from_slice(&bytes).unwrap();
5022            assert_eq!(parsed["headers"], json!([]), "hint={:?}", h.sources);
5023            assert_eq!(parsed["body"], body);
5024        }
5025    }
5026
5027    #[test]
5028    fn header_filter_preserves_input_order_and_dups() {
5029        // Multi-value headers and ordering matter to debuggability
5030        // (operators reading the wrapper from a probe should see the
5031        // headers in the same order they arrived). Filter is a
5032        // retain-only operation; no sort, no dedup.
5033        let h = hint(vec![HintSource::Header {
5034            name: "x-route".into(),
5035        }]);
5036        let headers = vec![
5037            ("x-route".into(), "a".into()),
5038            ("x-other".into(), "skip".into()),
5039            ("x-route".into(), "b".into()),
5040        ];
5041        let body = json!({});
5042        let bytes = build_scoped_identify_payload(&headers, &body, Some(&h));
5043        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
5044        assert_eq!(
5045            parsed["headers"],
5046            json!([
5047                { "name": "x-route", "value": "a" },
5048                { "name": "x-route", "value": "b" }
5049            ])
5050        );
5051    }
5052}
5053
5054impl PackFlows {
5055    fn from_manifest(manifest: greentic_types::PackManifest) -> Self {
5056        if let Some(flows) = flows_from_runtime_extension(&manifest) {
5057            return flows;
5058        }
5059        let descriptors = manifest
5060            .flows
5061            .iter()
5062            .map(|entry| FlowDescriptor {
5063                id: entry.id.as_str().to_string(),
5064                flow_type: flow_kind_to_str(entry.kind).to_string(),
5065                pack_id: manifest.pack_id.as_str().to_string(),
5066                profile: manifest.pack_id.as_str().to_string(),
5067                version: manifest.version.to_string(),
5068                description: None,
5069                entry: tags_indicate_entry(entry.tags.iter().map(String::as_str)),
5070            })
5071            .collect();
5072        let mut flows = HashMap::new();
5073        for entry in &manifest.flows {
5074            flows.insert(entry.id.as_str().to_string(), entry.flow.clone());
5075        }
5076        Self {
5077            metadata: PackMetadata::from_manifest(&manifest),
5078            descriptors,
5079            flows,
5080        }
5081    }
5082}
5083
5084fn flows_from_runtime_extension(manifest: &greentic_types::PackManifest) -> Option<PackFlows> {
5085    let extensions = manifest.extensions.as_ref()?;
5086    let extension = extensions.iter().find_map(|(key, ext)| {
5087        if RUNTIME_FLOW_EXTENSION_IDS
5088            .iter()
5089            .any(|candidate| candidate == key)
5090        {
5091            Some(ext)
5092        } else {
5093            None
5094        }
5095    })?;
5096    let runtime_flows = match decode_runtime_flow_extension(extension) {
5097        Some(flows) if !flows.is_empty() => flows,
5098        _ => return None,
5099    };
5100
5101    let descriptors = runtime_flows
5102        .iter()
5103        .map(|flow| FlowDescriptor {
5104            id: flow.id.as_str().to_string(),
5105            flow_type: flow_kind_to_str(flow.kind).to_string(),
5106            pack_id: manifest.pack_id.as_str().to_string(),
5107            profile: manifest.pack_id.as_str().to_string(),
5108            version: manifest.version.to_string(),
5109            description: None,
5110            entry: tags_indicate_entry(flow.metadata.tags.iter().map(String::as_str)),
5111        })
5112        .collect::<Vec<_>>();
5113    let flows = runtime_flows
5114        .into_iter()
5115        .map(|flow| (flow.id.as_str().to_string(), flow))
5116        .collect();
5117
5118    Some(PackFlows {
5119        metadata: PackMetadata::from_manifest(manifest),
5120        descriptors,
5121        flows,
5122    })
5123}
5124
5125fn decode_runtime_flow_extension(extension: &ExtensionRef) -> Option<Vec<Flow>> {
5126    let value = match extension.inline.as_ref()? {
5127        ExtensionInline::Other(value) => value.clone(),
5128        _ => return None,
5129    };
5130
5131    if let Ok(bundle) = serde_json::from_value::<RuntimeFlowBundle>(value.clone()) {
5132        return Some(collect_runtime_flows(bundle.flows));
5133    }
5134
5135    if let Ok(flows) = serde_json::from_value::<Vec<RuntimeFlow>>(value.clone()) {
5136        return Some(collect_runtime_flows(flows));
5137    }
5138
5139    if let Ok(flows) = serde_json::from_value::<Vec<Flow>>(value) {
5140        return Some(flows);
5141    }
5142
5143    warn!(
5144        extension = %extension.kind,
5145        version = %extension.version,
5146        "runtime flow extension present but could not be decoded"
5147    );
5148    None
5149}
5150
5151fn collect_runtime_flows(flows: Vec<RuntimeFlow>) -> Vec<Flow> {
5152    flows
5153        .into_iter()
5154        .filter_map(|flow| match runtime_flow_to_flow(flow) {
5155            Ok(flow) => Some(flow),
5156            Err(err) => {
5157                warn!(error = %err, "failed to decode runtime flow");
5158                None
5159            }
5160        })
5161        .collect()
5162}
5163
5164fn runtime_flow_to_flow(runtime: RuntimeFlow) -> Result<Flow> {
5165    let flow_id = FlowId::from_str(&runtime.id)
5166        .with_context(|| format!("invalid flow id `{}`", runtime.id))?;
5167    let mut entrypoints = runtime.entrypoints;
5168    if entrypoints.is_empty()
5169        && let Some(start) = &runtime.start
5170    {
5171        entrypoints.insert("default".into(), Value::String(start.clone()));
5172    }
5173
5174    let mut nodes: IndexMap<NodeId, Node, FlowHasher> = IndexMap::default();
5175    for (id, node) in runtime.nodes {
5176        let node_id = NodeId::from_str(&id).with_context(|| format!("invalid node id `{id}`"))?;
5177        let component_id = ComponentId::from_str(&node.component_id)
5178            .with_context(|| format!("invalid component id `{}`", node.component_id))?;
5179        let operation_payload = if node.config.is_null() {
5180            node.operation_payload
5181        } else {
5182            serde_json::json!({
5183                "input": node.operation_payload,
5184                "config": node.config,
5185            })
5186        };
5187        let component = FlowComponentRef {
5188            id: component_id,
5189            pack_alias: None,
5190            operation: node.operation_name,
5191        };
5192        let routing = node.routing.unwrap_or(Routing::End);
5193        let telemetry = node.telemetry.unwrap_or_default();
5194        nodes.insert(
5195            node_id.clone(),
5196            Node {
5197                id: node_id,
5198                component,
5199                input: InputMapping {
5200                    mapping: operation_payload,
5201                },
5202                output: OutputMapping {
5203                    mapping: Value::Null,
5204                },
5205                err_map: None,
5206                routing,
5207                telemetry,
5208                // Pack-manifest component nodes are not conversational chat
5209                // segments; the SP3 flag flows via the flow-doc parse path
5210                // (greentic_flow -> types::Node.conversational).
5211                conversational: false,
5212            },
5213        );
5214    }
5215
5216    Ok(Flow {
5217        schema_version: runtime.schema_version.unwrap_or_else(|| "1.0".to_string()),
5218        id: flow_id,
5219        kind: runtime.kind,
5220        entrypoints,
5221        nodes,
5222        metadata: runtime.metadata.unwrap_or_default(),
5223    })
5224}
5225
5226fn flow_kind_to_str(kind: greentic_types::FlowKind) -> &'static str {
5227    match kind {
5228        greentic_types::FlowKind::Messaging => "messaging",
5229        greentic_types::FlowKind::Event => "event",
5230        greentic_types::FlowKind::ComponentConfig => "component-config",
5231        greentic_types::FlowKind::Job => "job",
5232        greentic_types::FlowKind::Http => "http",
5233    }
5234}
5235
5236fn read_entry(archive: &mut ZipArchive<File>, name: &str) -> Result<Vec<u8>> {
5237    let mut file = archive
5238        .by_name(name)
5239        .with_context(|| format!("entry {name} missing from archive"))?;
5240    let buf = read_to_end_bounded(&mut file, MAX_ARCHIVE_ENTRY_READ_BYTES)
5241        .with_context(|| format!("failed to read entry {name} from archive"))?;
5242    Ok(buf)
5243}
5244
5245fn normalize_flow_doc(mut doc: FlowDoc) -> FlowDoc {
5246    for node in doc.nodes.values_mut() {
5247        let Some((component_ref, payload)) = node
5248            .raw
5249            .iter()
5250            .next()
5251            .map(|(key, value)| (key.clone(), value.clone()))
5252        else {
5253            continue;
5254        };
5255        // Runner-native op-keys (`emit.*`, `mcp`, `dw.agent`, `sorla.call`, …)
5256        // are dispatched by the engine directly off the `component` string, so
5257        // they must survive verbatim — wrapping them in a `component.exec` node
5258        // would misclassify them as `NodeKind::Exec`. The runtime-flow load
5259        // path (`flow_doc_to_ir`) already preserves them; mirror that here for
5260        // the legacy flow-JSON path using the shared op-key predicate.
5261        if is_native_op_key(&component_ref) {
5262            node.operation = Some(component_ref);
5263            node.payload = payload;
5264            node.raw.clear();
5265            continue;
5266        }
5267        let (target_component, operation, input, config) =
5268            infer_component_exec(&payload, &component_ref);
5269        let mut payload_obj = serde_json::Map::new();
5270        // component.exec is meta; ensure the payload carries the actual target component.
5271        payload_obj.insert("component".into(), Value::String(target_component));
5272        payload_obj.insert("operation".into(), Value::String(operation));
5273        payload_obj.insert("input".into(), input);
5274        if let Some(cfg) = config {
5275            payload_obj.insert("config".into(), cfg);
5276        }
5277        node.operation = Some("component.exec".to_string());
5278        node.payload = Value::Object(payload_obj);
5279        node.raw.clear();
5280    }
5281    doc
5282}
5283
5284fn infer_component_exec(
5285    payload: &Value,
5286    component_ref: &str,
5287) -> (String, String, Value, Option<Value>) {
5288    let default_op = if component_ref.starts_with("templating.") {
5289        "render"
5290    } else {
5291        "invoke"
5292    }
5293    .to_string();
5294
5295    if let Value::Object(map) = payload {
5296        let has_embedded_component =
5297            map.get("component").is_some() || map.get("component_ref").is_some();
5298        let op = map
5299            .get("op")
5300            .or_else(|| map.get("operation"))
5301            .and_then(Value::as_str)
5302            .map(|s| s.to_string())
5303            .unwrap_or_else(|| {
5304                if has_embedded_component {
5305                    component_ref.to_string()
5306                } else {
5307                    default_op.clone()
5308                }
5309            });
5310
5311        let mut input = map.clone();
5312        let config = input.remove("config");
5313        let canonical_input = if has_embedded_component {
5314            input.get("input").cloned()
5315        } else {
5316            None
5317        };
5318        let component = input
5319            .get("component")
5320            .or_else(|| input.get("component_ref"))
5321            .and_then(Value::as_str)
5322            .map(|s| s.to_string())
5323            .unwrap_or_else(|| component_ref.to_string());
5324        input.remove("component");
5325        input.remove("component_ref");
5326        input.remove("op");
5327        input.remove("operation");
5328        let input = canonical_input.unwrap_or(Value::Object(input));
5329        return (component, op, input, config);
5330    }
5331
5332    (component_ref.to_string(), default_op, payload.clone(), None)
5333}
5334
5335#[derive(Clone, Debug)]
5336struct ComponentSpec {
5337    id: String,
5338    version: String,
5339    legacy_path: Option<String>,
5340}
5341
5342#[derive(Clone, Debug)]
5343struct ComponentSourceInfo {
5344    digest: Option<String>,
5345    source: ComponentSourceRef,
5346    artifact: ComponentArtifactLocation,
5347    expected_wasm_sha256: Option<String>,
5348    skip_digest_verification: bool,
5349}
5350
5351#[derive(Clone, Debug)]
5352enum ComponentArtifactLocation {
5353    Inline { wasm_path: String },
5354    Remote,
5355}
5356
5357#[derive(Clone, Debug, Deserialize)]
5358struct PackLockV1 {
5359    schema_version: u32,
5360    components: Vec<PackLockComponent>,
5361}
5362
5363#[derive(Clone, Debug, Deserialize)]
5364struct PackLockComponent {
5365    name: String,
5366    #[serde(default, rename = "source_ref")]
5367    source_ref: Option<String>,
5368    #[serde(default, rename = "ref")]
5369    legacy_ref: Option<String>,
5370    #[serde(default)]
5371    component_id: Option<ComponentId>,
5372    #[serde(default)]
5373    bundled: Option<bool>,
5374    #[serde(default, rename = "bundled_path")]
5375    bundled_path: Option<String>,
5376    #[serde(default, rename = "path")]
5377    legacy_path: Option<String>,
5378    #[serde(default)]
5379    wasm_sha256: Option<String>,
5380    #[serde(default, rename = "sha256")]
5381    legacy_sha256: Option<String>,
5382    #[serde(default)]
5383    resolved_digest: Option<String>,
5384    #[serde(default)]
5385    digest: Option<String>,
5386}
5387
5388fn component_specs(
5389    manifest: Option<&greentic_types::PackManifest>,
5390    legacy_manifest: Option<&legacy_pack::PackManifest>,
5391    component_sources: Option<&ComponentSourcesV1>,
5392    pack_lock: Option<&PackLockV1>,
5393) -> Vec<ComponentSpec> {
5394    if let Some(manifest) = manifest {
5395        if !manifest.components.is_empty() {
5396            return manifest
5397                .components
5398                .iter()
5399                .map(|entry| ComponentSpec {
5400                    id: entry.id.as_str().to_string(),
5401                    version: entry.version.to_string(),
5402                    legacy_path: None,
5403                })
5404                .collect();
5405        }
5406        if let Some(lock) = pack_lock {
5407            let mut seen = HashSet::new();
5408            let mut specs = Vec::new();
5409            for entry in &lock.components {
5410                let id = entry
5411                    .component_id
5412                    .as_ref()
5413                    .map(|id| id.as_str())
5414                    .unwrap_or(entry.name.as_str());
5415                if seen.insert(id.to_string()) {
5416                    specs.push(ComponentSpec {
5417                        id: id.to_string(),
5418                        version: "0.0.0".to_string(),
5419                        legacy_path: None,
5420                    });
5421                }
5422            }
5423            return specs;
5424        }
5425        if let Some(sources) = component_sources {
5426            let mut seen = HashSet::new();
5427            let mut specs = Vec::new();
5428            for entry in &sources.components {
5429                let id = entry
5430                    .component_id
5431                    .as_ref()
5432                    .map(|id| id.as_str())
5433                    .unwrap_or(entry.name.as_str());
5434                if seen.insert(id.to_string()) {
5435                    specs.push(ComponentSpec {
5436                        id: id.to_string(),
5437                        version: "0.0.0".to_string(),
5438                        legacy_path: None,
5439                    });
5440                }
5441            }
5442            return specs;
5443        }
5444    }
5445    if let Some(legacy_manifest) = legacy_manifest {
5446        return legacy_manifest
5447            .components
5448            .iter()
5449            .map(|entry| ComponentSpec {
5450                id: entry.name.clone(),
5451                version: entry.version.to_string(),
5452                legacy_path: Some(entry.file_wasm.clone()),
5453            })
5454            .collect();
5455    }
5456    Vec::new()
5457}
5458
5459fn component_sources_table(
5460    sources: Option<&ComponentSourcesV1>,
5461) -> Result<Option<HashMap<String, ComponentSourceInfo>>> {
5462    let Some(sources) = sources else {
5463        return Ok(None);
5464    };
5465    let mut table = HashMap::new();
5466    for entry in &sources.components {
5467        let artifact = match &entry.artifact {
5468            ArtifactLocationV1::Inline { wasm_path, .. } => ComponentArtifactLocation::Inline {
5469                wasm_path: wasm_path.clone(),
5470            },
5471            ArtifactLocationV1::Remote => ComponentArtifactLocation::Remote,
5472        };
5473        let info = ComponentSourceInfo {
5474            digest: Some(entry.resolved.digest.clone()),
5475            source: entry.source.clone(),
5476            artifact,
5477            expected_wasm_sha256: None,
5478            skip_digest_verification: false,
5479        };
5480        if let Some(component_id) = entry.component_id.as_ref() {
5481            table.insert(component_id.as_str().to_string(), info.clone());
5482        }
5483        table.insert(entry.name.clone(), info);
5484    }
5485    Ok(Some(table))
5486}
5487
5488fn load_pack_lock(path: &Path) -> Result<Option<PackLockV1>> {
5489    let lock_path = if path.is_dir() {
5490        let candidate = path.join("pack.lock");
5491        if candidate.exists() {
5492            Some(candidate)
5493        } else {
5494            let candidate = path.join("pack.lock.json");
5495            candidate.exists().then_some(candidate)
5496        }
5497    } else {
5498        None
5499    };
5500    let Some(lock_path) = lock_path else {
5501        return Ok(None);
5502    };
5503    let raw = std::fs::read_to_string(&lock_path)
5504        .with_context(|| format!("failed to read {}", lock_path.display()))?;
5505    let lock: PackLockV1 = serde_json::from_str(&raw).context("failed to parse pack.lock")?;
5506    if lock.schema_version != 1 {
5507        bail!("pack.lock schema_version must be 1");
5508    }
5509    Ok(Some(lock))
5510}
5511
5512fn find_pack_lock_roots(
5513    pack_path: &Path,
5514    is_dir: bool,
5515    archive_hint: Option<&Path>,
5516) -> Vec<PathBuf> {
5517    if is_dir {
5518        return vec![pack_path.to_path_buf()];
5519    }
5520    // Only the archive's own directory: a `pack.lock` further up the tree
5521    // belongs to whatever else happens to live there (another pack, a shared
5522    // cache dir) and would silently replace this pack's component table.
5523    let archive = archive_hint.unwrap_or(pack_path);
5524    archive
5525        .parent()
5526        .map(|parent| vec![parent.to_path_buf()])
5527        .unwrap_or_default()
5528}
5529
5530fn normalize_sha256(digest: &str) -> Result<String> {
5531    let trimmed = digest.trim();
5532    if trimmed.is_empty() {
5533        bail!("sha256 digest cannot be empty");
5534    }
5535    if let Some(stripped) = trimmed.strip_prefix("sha256:") {
5536        if stripped.is_empty() {
5537            bail!("sha256 digest must include hex bytes after sha256:");
5538        }
5539        return Ok(trimmed.to_string());
5540    }
5541    if trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
5542        return Ok(format!("sha256:{trimmed}"));
5543    }
5544    bail!("sha256 digest must be hex or sha256:<hex>");
5545}
5546
5547fn component_sources_table_from_pack_lock(
5548    lock: &PackLockV1,
5549    allow_missing_hash: bool,
5550) -> Result<HashMap<String, ComponentSourceInfo>> {
5551    let mut table = HashMap::new();
5552    let mut names = HashSet::new();
5553    for entry in &lock.components {
5554        if !names.insert(entry.name.clone()) {
5555            bail!(
5556                "pack.lock contains duplicate component name `{}`",
5557                entry.name
5558            );
5559        }
5560        let source_ref = match (&entry.source_ref, &entry.legacy_ref) {
5561            (Some(primary), Some(legacy)) => {
5562                if primary != legacy {
5563                    bail!(
5564                        "pack.lock component {} has conflicting refs: {} vs {}",
5565                        entry.name,
5566                        primary,
5567                        legacy
5568                    );
5569                }
5570                primary.as_str()
5571            }
5572            (Some(primary), None) => primary.as_str(),
5573            (None, Some(legacy)) => legacy.as_str(),
5574            (None, None) => {
5575                bail!("pack.lock component {} missing source_ref", entry.name);
5576            }
5577        };
5578        let source: ComponentSourceRef = source_ref
5579            .parse()
5580            .with_context(|| format!("invalid component ref `{}`", source_ref))?;
5581        let bundled_path = match (&entry.bundled_path, &entry.legacy_path) {
5582            (Some(primary), Some(legacy)) => {
5583                if primary != legacy {
5584                    bail!(
5585                        "pack.lock component {} has conflicting bundled paths: {} vs {}",
5586                        entry.name,
5587                        primary,
5588                        legacy
5589                    );
5590                }
5591                Some(primary.clone())
5592            }
5593            (Some(primary), None) => Some(primary.clone()),
5594            (None, Some(legacy)) => Some(legacy.clone()),
5595            (None, None) => None,
5596        };
5597        let bundled = entry.bundled.unwrap_or(false) || bundled_path.is_some();
5598        let (artifact, digest, expected_wasm_sha256, skip_digest_verification) = if bundled {
5599            let wasm_path = bundled_path.ok_or_else(|| {
5600                anyhow!(
5601                    "pack.lock component {} marked bundled but bundled_path is missing",
5602                    entry.name
5603                )
5604            })?;
5605            let expected_raw = match (&entry.wasm_sha256, &entry.legacy_sha256) {
5606                (Some(primary), Some(legacy)) => {
5607                    if primary != legacy {
5608                        bail!(
5609                            "pack.lock component {} has conflicting wasm_sha256 values: {} vs {}",
5610                            entry.name,
5611                            primary,
5612                            legacy
5613                        );
5614                    }
5615                    Some(primary.as_str())
5616                }
5617                (Some(primary), None) => Some(primary.as_str()),
5618                (None, Some(legacy)) => Some(legacy.as_str()),
5619                (None, None) => None,
5620            };
5621            let expected = match expected_raw {
5622                Some(value) => Some(normalize_sha256(value)?),
5623                None => None,
5624            };
5625            if expected.is_none() && !allow_missing_hash {
5626                bail!(
5627                    "pack.lock component {} missing wasm_sha256 for bundled component",
5628                    entry.name
5629                );
5630            }
5631            (
5632                ComponentArtifactLocation::Inline { wasm_path },
5633                expected.clone(),
5634                expected,
5635                allow_missing_hash && expected_raw.is_none(),
5636            )
5637        } else {
5638            if source.is_tag() {
5639                bail!(
5640                    "component {} uses tag ref {} but is not bundled; rebuild the pack",
5641                    entry.name,
5642                    source
5643                );
5644            }
5645            let expected = entry
5646                .resolved_digest
5647                .as_deref()
5648                .or(entry.digest.as_deref())
5649                .ok_or_else(|| {
5650                    anyhow!(
5651                        "pack.lock component {} missing resolved_digest for remote component",
5652                        entry.name
5653                    )
5654                })?;
5655            (
5656                ComponentArtifactLocation::Remote,
5657                Some(normalize_digest(expected)),
5658                None,
5659                false,
5660            )
5661        };
5662        let info = ComponentSourceInfo {
5663            digest,
5664            source,
5665            artifact,
5666            expected_wasm_sha256,
5667            skip_digest_verification,
5668        };
5669        if let Some(component_id) = entry.component_id.as_ref() {
5670            let key = component_id.as_str().to_string();
5671            if table.contains_key(&key) {
5672                bail!(
5673                    "pack.lock contains duplicate component id `{}`",
5674                    component_id.as_str()
5675                );
5676            }
5677            table.insert(key, info.clone());
5678        }
5679        if entry.name
5680            != entry
5681                .component_id
5682                .as_ref()
5683                .map(|id| id.as_str())
5684                .unwrap_or("")
5685        {
5686            table.insert(entry.name.clone(), info);
5687        }
5688    }
5689    Ok(table)
5690}
5691
5692/// Where a materialized component lives under `root`, or `Ok(None)` when it is
5693/// not there. The relative path comes from pack-authored content (a legacy
5694/// manifest's `legacy_path`, or the component id), so it is confined to `root`
5695/// the same way asset paths are: normal components only, symlinks resolved.
5696fn component_path_for_spec(root: &Path, spec: &ComponentSpec) -> Result<Option<PathBuf>> {
5697    let relative = match &spec.legacy_path {
5698        Some(path) => path.clone(),
5699        None => format!("components/{}.wasm", spec.id),
5700    };
5701    confined_asset_path(root, &relative)
5702}
5703
5704fn normalize_digest(digest: &str) -> String {
5705    if digest.starts_with("sha256:") || digest.starts_with("blake3:") {
5706        digest.to_string()
5707    } else {
5708        format!("sha256:{digest}")
5709    }
5710}
5711
5712fn compute_digest_for(bytes: &[u8], digest: &str) -> Result<String> {
5713    if digest.starts_with("blake3:") {
5714        let hash = blake3::hash(bytes);
5715        return Ok(format!("blake3:{}", hash.to_hex()));
5716    }
5717    let mut hasher = sha2::Sha256::new();
5718    hasher.update(bytes);
5719    Ok(format!("sha256:{}", to_hex(&hasher.finalize())))
5720}
5721
5722fn compute_sha256_digest_for(bytes: &[u8]) -> String {
5723    let mut hasher = sha2::Sha256::new();
5724    hasher.update(bytes);
5725    format!("sha256:{}", to_hex(&hasher.finalize()))
5726}
5727
5728/// Cache key derived from the sha256 of the actual wasm bytes. A manifest- or
5729/// lock-declared digest is deliberately not used here: it may not have been
5730/// verified against `bytes`, and keying the compiled-artifact cache by an
5731/// unverified claim would let one component's compiled code be served for
5732/// another.
5733fn build_artifact_key(cache: &CacheManager, bytes: &[u8]) -> ArtifactKey {
5734    ArtifactKey::new(
5735        cache.engine_profile_id().to_string(),
5736        compute_sha256_digest_for(bytes),
5737    )
5738}
5739
5740async fn compile_component_with_cache(
5741    cache: &CacheManager,
5742    engine: &Engine,
5743    _declared_digest: Option<&str>,
5744    bytes: Vec<u8>,
5745) -> Result<Arc<Component>> {
5746    let key = build_artifact_key(cache, &bytes);
5747    cache.get_component(engine, &key, || Ok(bytes)).await
5748}
5749
5750fn verify_component_digest(component_id: &str, expected: &str, bytes: &[u8]) -> Result<()> {
5751    let normalized_expected = normalize_digest(expected);
5752    let actual = compute_digest_for(bytes, &normalized_expected)?;
5753    if normalize_digest(&actual) != normalized_expected {
5754        bail!(
5755            "component {component_id} digest mismatch: expected {normalized_expected}, got {actual}"
5756        );
5757    }
5758    Ok(())
5759}
5760
5761fn verify_wasm_sha256(component_id: &str, expected: &str, bytes: &[u8]) -> Result<()> {
5762    let normalized_expected = normalize_sha256(expected)?;
5763    let actual = compute_sha256_digest_for(bytes);
5764    if actual != normalized_expected {
5765        bail!(
5766            "component {component_id} bundled digest mismatch: expected {normalized_expected}, got {actual}"
5767        );
5768    }
5769    Ok(())
5770}
5771
5772fn to_hex(digest: &[u8]) -> String {
5773    digest.iter().map(|byte| format!("{byte:02x}")).collect()
5774}
5775
5776#[cfg(test)]
5777mod pack_lock_tests {
5778    use super::*;
5779    use tempfile::TempDir;
5780
5781    #[test]
5782    fn pack_lock_tag_ref_requires_bundle() {
5783        let lock = PackLockV1 {
5784            schema_version: 1,
5785            components: vec![PackLockComponent {
5786                name: "templates".to_string(),
5787                source_ref: Some("oci://registry.test/templates:latest".to_string()),
5788                legacy_ref: None,
5789                component_id: None,
5790                bundled: Some(false),
5791                bundled_path: None,
5792                legacy_path: None,
5793                wasm_sha256: None,
5794                legacy_sha256: None,
5795                resolved_digest: None,
5796                digest: None,
5797            }],
5798        };
5799        let err = component_sources_table_from_pack_lock(&lock, false).unwrap_err();
5800        assert!(
5801            err.to_string().contains("tag ref") && err.to_string().contains("rebuild the pack"),
5802            "unexpected error: {err}"
5803        );
5804    }
5805
5806    #[test]
5807    fn bundled_hash_mismatch_errors() {
5808        let rt = tokio::runtime::Runtime::new().expect("runtime");
5809        let temp = TempDir::new().expect("temp dir");
5810        let engine = Engine::default();
5811        let engine_profile =
5812            EngineProfile::from_engine(&engine, CpuPolicy::Native, "default".to_string());
5813        let cache_config = CacheConfig {
5814            root: temp.path().join("cache"),
5815            ..CacheConfig::default()
5816        };
5817        let cache = CacheManager::new(cache_config, engine_profile);
5818        let wasm_path = temp.path().join("component.wasm");
5819        let fixture_wasm = Path::new(env!("CARGO_MANIFEST_DIR"))
5820            .join("../../tests/fixtures/packs/secrets_store_smoke/components/echo_secret.wasm");
5821        let bytes = std::fs::read(&fixture_wasm).expect("read fixture wasm");
5822        std::fs::write(&wasm_path, &bytes).expect("write temp wasm");
5823
5824        let spec = ComponentSpec {
5825            id: "qa.process".to_string(),
5826            version: "0.0.0".to_string(),
5827            legacy_path: None,
5828        };
5829        let mut missing = HashSet::new();
5830        missing.insert(spec.id.clone());
5831
5832        let mut sources = HashMap::new();
5833        sources.insert(
5834            spec.id.clone(),
5835            ComponentSourceInfo {
5836                digest: Some("sha256:deadbeef".to_string()),
5837                source: ComponentSourceRef::Oci("registry.test/qa.process@sha256:deadbeef".into()),
5838                artifact: ComponentArtifactLocation::Inline {
5839                    wasm_path: "component.wasm".to_string(),
5840                },
5841                expected_wasm_sha256: Some("sha256:deadbeef".to_string()),
5842                skip_digest_verification: false,
5843            },
5844        );
5845
5846        let mut loaded = HashMap::new();
5847        let result = rt.block_on(load_components_from_sources(
5848            &cache,
5849            &engine,
5850            &sources,
5851            &ComponentResolution::default(),
5852            &[spec],
5853            &mut missing,
5854            &mut loaded,
5855            Some(temp.path()),
5856            None,
5857        ));
5858        let err = result.unwrap_err();
5859        assert!(
5860            err.to_string().contains("bundled digest mismatch"),
5861            "unexpected error: {err}"
5862        );
5863    }
5864}
5865
5866#[cfg(test)]
5867mod pack_resolution_prop_tests {
5868    use super::*;
5869    use greentic_types::{ArtifactLocationV1, ComponentSourceEntryV1, ResolvedComponentV1};
5870    use proptest::prelude::*;
5871    use proptest::test_runner::{Config as ProptestConfig, RngAlgorithm, TestRng, TestRunner};
5872    use std::collections::BTreeSet;
5873    use std::path::Path;
5874    use std::str::FromStr;
5875
5876    #[derive(Clone, Debug)]
5877    enum ResolveRequest {
5878        ById(String),
5879        ByName(String),
5880    }
5881
5882    #[derive(Clone, Debug, PartialEq, Eq)]
5883    struct ResolvedComponent {
5884        key: String,
5885        source: String,
5886        artifact: String,
5887        digest: Option<String>,
5888        expected_wasm_sha256: Option<String>,
5889        skip_digest_verification: bool,
5890    }
5891
5892    #[derive(Clone, Debug, PartialEq, Eq)]
5893    struct ResolveError {
5894        code: String,
5895        message: String,
5896        context_key: String,
5897    }
5898
5899    #[derive(Clone, Debug)]
5900    struct Scenario {
5901        pack_lock: Option<PackLockV1>,
5902        component_sources: Option<ComponentSourcesV1>,
5903        request: ResolveRequest,
5904        expected_sha256: Option<String>,
5905        bytes: Vec<u8>,
5906    }
5907
5908    fn resolve_component_test(
5909        sources: Option<&ComponentSourcesV1>,
5910        lock: Option<&PackLockV1>,
5911        request: &ResolveRequest,
5912    ) -> Result<ResolvedComponent, ResolveError> {
5913        let table = if let Some(lock) = lock {
5914            component_sources_table_from_pack_lock(lock, false).map_err(|err| ResolveError {
5915                code: classify_pack_lock_error(err.to_string().as_str()).to_string(),
5916                message: err.to_string(),
5917                context_key: request_key(request).to_string(),
5918            })?
5919        } else {
5920            let sources = component_sources_table(sources).map_err(|err| ResolveError {
5921                code: "component_sources_error".to_string(),
5922                message: err.to_string(),
5923                context_key: request_key(request).to_string(),
5924            })?;
5925            sources.ok_or_else(|| ResolveError {
5926                code: "missing_component_sources".to_string(),
5927                message: "component sources not provided".to_string(),
5928                context_key: request_key(request).to_string(),
5929            })?
5930        };
5931
5932        let key = request_key(request);
5933        let source = table.get(key).ok_or_else(|| ResolveError {
5934            code: "component_not_found".to_string(),
5935            message: format!("component {key} not found"),
5936            context_key: key.to_string(),
5937        })?;
5938
5939        Ok(ResolvedComponent {
5940            key: key.to_string(),
5941            source: source.source.to_string(),
5942            artifact: match source.artifact {
5943                ComponentArtifactLocation::Inline { .. } => "inline".to_string(),
5944                ComponentArtifactLocation::Remote => "remote".to_string(),
5945            },
5946            digest: source.digest.clone(),
5947            expected_wasm_sha256: source.expected_wasm_sha256.clone(),
5948            skip_digest_verification: source.skip_digest_verification,
5949        })
5950    }
5951
5952    fn request_key(request: &ResolveRequest) -> &str {
5953        match request {
5954            ResolveRequest::ById(value) => value.as_str(),
5955            ResolveRequest::ByName(value) => value.as_str(),
5956        }
5957    }
5958
5959    fn classify_pack_lock_error(message: &str) -> &'static str {
5960        if message.contains("duplicate component name") {
5961            "duplicate_name"
5962        } else if message.contains("duplicate component id") {
5963            "duplicate_id"
5964        } else if message.contains("conflicting refs") {
5965            "conflicting_ref"
5966        } else if message.contains("conflicting bundled paths") {
5967            "conflicting_bundled_path"
5968        } else if message.contains("conflicting wasm_sha256") {
5969            "conflicting_wasm_sha256"
5970        } else if message.contains("missing source_ref") {
5971            "missing_source_ref"
5972        } else if message.contains("marked bundled but bundled_path is missing") {
5973            "missing_bundled_path"
5974        } else if message.contains("missing wasm_sha256") {
5975            "missing_wasm_sha256"
5976        } else if message.contains("tag ref") && message.contains("not bundled") {
5977            "tag_ref_requires_bundle"
5978        } else if message.contains("missing resolved_digest") {
5979            "missing_resolved_digest"
5980        } else if message.contains("invalid component ref") {
5981            "invalid_component_ref"
5982        } else if message.contains("sha256 digest") {
5983            "invalid_sha256"
5984        } else {
5985            "unknown_error"
5986        }
5987    }
5988
5989    fn known_error_codes() -> BTreeSet<&'static str> {
5990        [
5991            "component_sources_error",
5992            "missing_component_sources",
5993            "component_not_found",
5994            "duplicate_name",
5995            "duplicate_id",
5996            "conflicting_ref",
5997            "conflicting_bundled_path",
5998            "conflicting_wasm_sha256",
5999            "missing_source_ref",
6000            "missing_bundled_path",
6001            "missing_wasm_sha256",
6002            "tag_ref_requires_bundle",
6003            "missing_resolved_digest",
6004            "invalid_component_ref",
6005            "invalid_sha256",
6006            "unknown_error",
6007        ]
6008        .into_iter()
6009        .collect()
6010    }
6011
6012    fn proptest_config() -> ProptestConfig {
6013        let cases = std::env::var("PROPTEST_CASES")
6014            .ok()
6015            .and_then(|value| value.parse::<u32>().ok())
6016            .unwrap_or(128);
6017        ProptestConfig {
6018            cases,
6019            failure_persistence: None,
6020            ..ProptestConfig::default()
6021        }
6022    }
6023
6024    fn proptest_seed() -> Option<[u8; 32]> {
6025        let seed = std::env::var("PROPTEST_SEED")
6026            .ok()
6027            .and_then(|value| value.parse::<u64>().ok())?;
6028        let mut bytes = [0u8; 32];
6029        bytes[..8].copy_from_slice(&seed.to_le_bytes());
6030        Some(bytes)
6031    }
6032
6033    fn run_cases(strategy: impl Strategy<Value = Scenario>, cases: u32, seed: Option<[u8; 32]>) {
6034        let config = ProptestConfig {
6035            cases,
6036            failure_persistence: None,
6037            ..ProptestConfig::default()
6038        };
6039        let mut runner = match seed {
6040            Some(bytes) => {
6041                TestRunner::new_with_rng(config, TestRng::from_seed(RngAlgorithm::ChaCha, &bytes))
6042            }
6043            None => TestRunner::new(config),
6044        };
6045        runner
6046            .run(&strategy, |scenario| {
6047                run_scenario(&scenario);
6048                Ok(())
6049            })
6050            .unwrap();
6051    }
6052
6053    fn run_scenario(scenario: &Scenario) {
6054        let known_codes = known_error_codes();
6055        let first = resolve_component_test(
6056            scenario.component_sources.as_ref(),
6057            scenario.pack_lock.as_ref(),
6058            &scenario.request,
6059        );
6060        let second = resolve_component_test(
6061            scenario.component_sources.as_ref(),
6062            scenario.pack_lock.as_ref(),
6063            &scenario.request,
6064        );
6065        assert_eq!(normalize_result(&first), normalize_result(&second));
6066
6067        if let Some(lock) = scenario.pack_lock.as_ref() {
6068            let lock_only = resolve_component_test(None, Some(lock), &scenario.request);
6069            assert_eq!(normalize_result(&first), normalize_result(&lock_only));
6070        }
6071
6072        if let Err(err) = first.as_ref() {
6073            assert!(
6074                known_codes.contains(err.code.as_str()),
6075                "unexpected error code {}: {}",
6076                err.code,
6077                err.message
6078            );
6079        }
6080
6081        if let Some(expected) = scenario.expected_sha256.as_deref() {
6082            let expected_ok =
6083                verify_wasm_sha256("test.component", expected, &scenario.bytes).is_ok();
6084            let actual = compute_sha256_digest_for(&scenario.bytes);
6085            if actual == normalize_sha256(expected).unwrap_or_default() {
6086                assert!(expected_ok, "expected sha256 match to succeed");
6087            } else {
6088                assert!(!expected_ok, "expected sha256 mismatch to fail");
6089            }
6090        }
6091    }
6092
6093    fn normalize_result(
6094        result: &Result<ResolvedComponent, ResolveError>,
6095    ) -> Result<ResolvedComponent, ResolveError> {
6096        match result {
6097            Ok(value) => Ok(value.clone()),
6098            Err(err) => Err(err.clone()),
6099        }
6100    }
6101
6102    fn scenario_strategy() -> impl Strategy<Value = Scenario> {
6103        let name = any::<u8>().prop_map(|n| format!("component{n}.core"));
6104        let alt_name = any::<u8>().prop_map(|n| format!("component_alt{n}.core"));
6105        let tag_ref = any::<bool>();
6106        let bundled = any::<bool>();
6107        let include_sha = any::<bool>();
6108        let include_component_id = any::<bool>();
6109        let request_by_id = any::<bool>();
6110        let use_lock = any::<bool>();
6111        let use_sources = any::<bool>();
6112        let bytes = prop::collection::vec(any::<u8>(), 1..64);
6113
6114        (
6115            name,
6116            alt_name,
6117            tag_ref,
6118            bundled,
6119            include_sha,
6120            include_component_id,
6121            request_by_id,
6122            use_lock,
6123            use_sources,
6124            bytes,
6125        )
6126            .prop_map(
6127                |(
6128                    name,
6129                    alt_name,
6130                    tag_ref,
6131                    bundled,
6132                    include_sha,
6133                    include_component_id,
6134                    request_by_id,
6135                    use_lock,
6136                    use_sources,
6137                    bytes,
6138                )| {
6139                    let component_id_str = if include_component_id {
6140                        alt_name.clone()
6141                    } else {
6142                        name.clone()
6143                    };
6144                    let component_id = ComponentId::from_str(&component_id_str).ok();
6145                    let source_ref = if tag_ref {
6146                        format!("oci://registry.test/{name}:v1")
6147                    } else {
6148                        format!(
6149                            "oci://registry.test/{name}@sha256:{}",
6150                            hex::encode([0x11u8; 32])
6151                        )
6152                    };
6153                    let expected_sha256 = if bundled && include_sha {
6154                        Some(compute_sha256_digest_for(&bytes))
6155                    } else {
6156                        None
6157                    };
6158
6159                    let lock_component = PackLockComponent {
6160                        name: name.clone(),
6161                        source_ref: Some(source_ref),
6162                        legacy_ref: None,
6163                        component_id,
6164                        bundled: Some(bundled),
6165                        bundled_path: if bundled {
6166                            Some(format!("components/{name}.wasm"))
6167                        } else {
6168                            None
6169                        },
6170                        legacy_path: None,
6171                        wasm_sha256: expected_sha256.clone(),
6172                        legacy_sha256: None,
6173                        resolved_digest: if bundled {
6174                            None
6175                        } else {
6176                            Some("sha256:deadbeef".to_string())
6177                        },
6178                        digest: None,
6179                    };
6180
6181                    let pack_lock = if use_lock {
6182                        Some(PackLockV1 {
6183                            schema_version: 1,
6184                            components: vec![lock_component],
6185                        })
6186                    } else {
6187                        None
6188                    };
6189
6190                    let component_sources = if use_sources {
6191                        Some(ComponentSourcesV1::new(vec![ComponentSourceEntryV1 {
6192                            name: name.clone(),
6193                            component_id: ComponentId::from_str(&name).ok(),
6194                            source: ComponentSourceRef::from_str(
6195                                "oci://registry.test/component@sha256:deadbeef",
6196                            )
6197                            .expect("component ref"),
6198                            resolved: ResolvedComponentV1 {
6199                                digest: "sha256:deadbeef".to_string(),
6200                                signature: None,
6201                                signed_by: None,
6202                            },
6203                            artifact: if bundled {
6204                                ArtifactLocationV1::Inline {
6205                                    wasm_path: format!("components/{name}.wasm"),
6206                                    manifest_path: None,
6207                                }
6208                            } else {
6209                                ArtifactLocationV1::Remote
6210                            },
6211                            licensing_hint: None,
6212                            metering_hint: None,
6213                        }]))
6214                    } else {
6215                        None
6216                    };
6217
6218                    let request = if request_by_id {
6219                        ResolveRequest::ById(component_id_str.clone())
6220                    } else {
6221                        ResolveRequest::ByName(name.clone())
6222                    };
6223
6224                    Scenario {
6225                        pack_lock,
6226                        component_sources,
6227                        request,
6228                        expected_sha256,
6229                        bytes,
6230                    }
6231                },
6232            )
6233    }
6234
6235    #[test]
6236    fn pack_resolution_proptest() {
6237        let seed = proptest_seed();
6238        run_cases(scenario_strategy(), proptest_config().cases, seed);
6239    }
6240
6241    #[test]
6242    fn pack_resolution_regression_seeds() {
6243        let seeds_path =
6244            Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/proptest-seeds.txt");
6245        let raw = std::fs::read_to_string(&seeds_path).expect("read proptest seeds");
6246        for line in raw.lines() {
6247            let line = line.trim();
6248            if line.is_empty() || line.starts_with('#') {
6249                continue;
6250            }
6251            let seed = line.parse::<u64>().expect("seed must be an integer");
6252            let mut bytes = [0u8; 32];
6253            bytes[..8].copy_from_slice(&seed.to_le_bytes());
6254            run_cases(scenario_strategy(), 1, Some(bytes));
6255        }
6256    }
6257}
6258
6259fn locate_pack_assets(
6260    materialized_root: Option<&Path>,
6261    archive_hint: Option<&Path>,
6262) -> Result<(Option<PathBuf>, Option<TempDir>)> {
6263    if let Some(root) = materialized_root {
6264        let assets = root.join("assets");
6265        if assets.is_dir() {
6266            return Ok((Some(assets), None));
6267        }
6268    }
6269    if let Some(path) = archive_hint
6270        && let Some((tempdir, assets)) = extract_assets_from_archive(path)?
6271    {
6272        return Ok((Some(assets), Some(tempdir)));
6273    }
6274    Ok((None, None))
6275}
6276
6277/// Per-entry cap for extracted pack assets (decompressed).
6278const MAX_ASSET_ENTRY_BYTES: u64 = 128 * 1024 * 1024;
6279/// Total cap for all extracted pack assets (decompressed).
6280const MAX_ASSETS_TOTAL_BYTES: u64 = 512 * 1024 * 1024;
6281/// Cap on the number of entries (files and directories) under `assets/` in one pack.
6282const MAX_ASSET_ENTRIES: usize = 20_000;
6283/// Cap for archive entries read fully into memory (manifests, schemas, ...).
6284const MAX_ARCHIVE_ENTRY_READ_BYTES: u64 = 64 * 1024 * 1024;
6285
6286/// Read at most `limit` bytes from `reader`; exceeding it is an error rather
6287/// than silent truncation (guards against zip bombs).
6288fn read_to_end_bounded<R: Read>(reader: R, limit: u64) -> std::io::Result<Vec<u8>> {
6289    let mut buf = Vec::new();
6290    reader.take(limit.saturating_add(1)).read_to_end(&mut buf)?;
6291    if buf.len() as u64 > limit {
6292        return Err(std::io::Error::new(
6293            std::io::ErrorKind::InvalidData,
6294            format!("archive entry exceeds the {limit} byte read limit"),
6295        ));
6296    }
6297    Ok(buf)
6298}
6299
6300/// Resolve `relative` under `root`, refusing anything that could leave it
6301/// (`..`, absolute paths, symlinks pointing outside). `Ok(None)` when the file
6302/// does not exist.
6303fn confined_asset_path(root: &Path, relative: &str) -> Result<Option<PathBuf>> {
6304    use std::path::Component;
6305    let mut clean = PathBuf::new();
6306    for component in Path::new(relative).components() {
6307        match component {
6308            Component::Normal(part) => clean.push(part),
6309            Component::CurDir => {}
6310            _ => bail!("invalid asset path: {relative}"),
6311        }
6312    }
6313    if clean.as_os_str().is_empty() {
6314        bail!("invalid asset path: {relative}");
6315    }
6316    let candidate = root.join(&clean);
6317    if !candidate.exists() {
6318        return Ok(None);
6319    }
6320    let canonical_root = root
6321        .canonicalize()
6322        .with_context(|| format!("failed to canonicalize {}", root.display()))?;
6323    let canonical = candidate
6324        .canonicalize()
6325        .with_context(|| format!("failed to canonicalize {}", candidate.display()))?;
6326    if !canonical.starts_with(&canonical_root) {
6327        bail!("asset path escapes the assets root: {relative}");
6328    }
6329    Ok(Some(canonical))
6330}
6331
6332fn extract_assets_from_archive(path: &Path) -> Result<Option<(TempDir, PathBuf)>> {
6333    extract_assets_with_entry_cap(path, MAX_ASSET_ENTRIES)
6334}
6335
6336/// [`extract_assets_from_archive`] refusing a pack with more than `max_entries`
6337/// entries under `assets/` (files and directories alike). The byte caps alone do
6338/// not bound inode use: a million empty files cost no bytes.
6339fn extract_assets_with_entry_cap(
6340    path: &Path,
6341    max_entries: usize,
6342) -> Result<Option<(TempDir, PathBuf)>> {
6343    let file =
6344        File::open(path).with_context(|| format!("failed to open pack {}", path.display()))?;
6345    let mut archive =
6346        ZipArchive::new(file).with_context(|| format!("failed to read pack {}", path.display()))?;
6347    let temp = TempDir::new().context("failed to create temporary assets directory")?;
6348    let mut found = false;
6349    let mut total_bytes = 0u64;
6350    let mut asset_entries = 0usize;
6351    for idx in 0..archive.len() {
6352        let mut entry = archive.by_index(idx)?;
6353        let raw_name = entry.name().to_string();
6354        if !raw_name.starts_with("assets/") {
6355            continue;
6356        }
6357        asset_entries += 1;
6358        if asset_entries > max_entries {
6359            bail!(
6360                "pack {} has too many asset entries (limit {max_entries})",
6361                path.display()
6362            );
6363        }
6364        // `enclosed_name` rejects absolute paths and `..` escapes (zip-slip).
6365        let Some(safe_name) = entry.enclosed_name() else {
6366            bail!(
6367                "pack {} contains an unsafe asset path `{raw_name}`",
6368                path.display()
6369            );
6370        };
6371        if entry.is_symlink() {
6372            warn!(entry = %raw_name, "skipping symlink entry in pack assets");
6373            continue;
6374        }
6375        let dest = temp.path().join(&safe_name);
6376        if raw_name.ends_with('/') {
6377            std::fs::create_dir_all(&dest)?;
6378            found = true;
6379            continue;
6380        }
6381        if entry.size() > MAX_ASSET_ENTRY_BYTES {
6382            bail!(
6383                "asset `{raw_name}` in {} is too large ({} bytes, limit {MAX_ASSET_ENTRY_BYTES})",
6384                path.display(),
6385                entry.size()
6386            );
6387        }
6388        if let Some(parent) = dest.parent() {
6389            std::fs::create_dir_all(parent)?;
6390        }
6391        let mut outfile = std::fs::File::create(&dest)?;
6392        // Bound the real decompressed size, not just the declared one.
6393        let mut limited = (&mut entry).take(MAX_ASSET_ENTRY_BYTES + 1);
6394        let copied = std::io::copy(&mut limited, &mut outfile)?;
6395        if copied > MAX_ASSET_ENTRY_BYTES {
6396            bail!(
6397                "asset `{raw_name}` in {} exceeds the size limit",
6398                path.display()
6399            );
6400        }
6401        total_bytes = total_bytes.saturating_add(copied);
6402        if total_bytes > MAX_ASSETS_TOTAL_BYTES {
6403            bail!(
6404                "assets in {} exceed the total size limit ({MAX_ASSETS_TOTAL_BYTES} bytes)",
6405                path.display()
6406            );
6407        }
6408        found = true;
6409    }
6410    if found {
6411        let assets_path = temp.path().join("assets");
6412        Ok(Some((temp, assets_path)))
6413    } else {
6414        Ok(None)
6415    }
6416}
6417
6418fn dist_options_from(component_resolution: &ComponentResolution) -> DistOptions {
6419    let mut opts = DistOptions {
6420        allow_tags: true,
6421        ..DistOptions::default()
6422    };
6423    if let Some(cache_dir) = component_resolution.dist_cache_dir.clone() {
6424        opts.cache_dir = cache_dir;
6425    }
6426    if component_resolution.dist_offline {
6427        opts.offline = true;
6428    }
6429    opts
6430}
6431
6432#[allow(clippy::too_many_arguments)]
6433async fn load_components_from_sources(
6434    cache: &CacheManager,
6435    engine: &Engine,
6436    component_sources: &HashMap<String, ComponentSourceInfo>,
6437    component_resolution: &ComponentResolution,
6438    specs: &[ComponentSpec],
6439    missing: &mut HashSet<String>,
6440    into: &mut HashMap<String, PackComponent>,
6441    materialized_root: Option<&Path>,
6442    archive_hint: Option<&Path>,
6443) -> Result<()> {
6444    let mut archive = if let Some(path) = archive_hint {
6445        Some(
6446            ZipArchive::new(File::open(path)?)
6447                .with_context(|| format!("{} is not a valid gtpack", path.display()))?,
6448        )
6449    } else {
6450        None
6451    };
6452    let mut dist_client: Option<DistClient> = None;
6453
6454    for spec in specs {
6455        if !missing.contains(&spec.id) {
6456            continue;
6457        }
6458        let Some(source) = component_sources.get(&spec.id) else {
6459            continue;
6460        };
6461
6462        let bytes = match &source.artifact {
6463            ComponentArtifactLocation::Inline { wasm_path } => {
6464                if let Some(root) = materialized_root {
6465                    // `wasm_path` is pack-authored: confine it to the pack root.
6466                    let confined = confined_asset_path(root, wasm_path).with_context(|| {
6467                        format!("inline component {} has an unusable path", spec.id)
6468                    })?;
6469                    let path = confined.clone().unwrap_or_else(|| root.join(wasm_path));
6470                    if confined.is_some() {
6471                        std::fs::read(&path).with_context(|| {
6472                            format!(
6473                                "failed to read inline component {} from {}",
6474                                spec.id,
6475                                path.display()
6476                            )
6477                        })?
6478                    } else if archive.is_none() {
6479                        bail!("inline component {} missing at {}", spec.id, path.display());
6480                    } else {
6481                        read_entry(
6482                            archive.as_mut().expect("archive present when needed"),
6483                            wasm_path,
6484                        )
6485                        .with_context(|| {
6486                            format!(
6487                                "inline component {} missing at {} in pack archive",
6488                                spec.id, wasm_path
6489                            )
6490                        })?
6491                    }
6492                } else if let Some(archive) = archive.as_mut() {
6493                    read_entry(archive, wasm_path).with_context(|| {
6494                        format!(
6495                            "inline component {} missing at {} in pack archive",
6496                            spec.id, wasm_path
6497                        )
6498                    })?
6499                } else {
6500                    bail!(
6501                        "inline component {} missing and no pack source available",
6502                        spec.id
6503                    );
6504                }
6505            }
6506            ComponentArtifactLocation::Remote => {
6507                if source.source.is_tag() {
6508                    bail!(
6509                        "component {} uses tag ref {} but is not bundled; rebuild the pack",
6510                        spec.id,
6511                        source.source
6512                    );
6513                }
6514                let client = dist_client.get_or_insert_with(|| {
6515                    DistClient::new(dist_options_from(component_resolution))
6516                });
6517                let reference = source.source.to_string();
6518                fault::maybe_fail_asset(&reference)
6519                    .await
6520                    .with_context(|| format!("fault injection blocked asset {reference}"))?;
6521                let digest = source.digest.as_deref().ok_or_else(|| {
6522                    anyhow!(
6523                        "component {} missing expected digest for remote component",
6524                        spec.id
6525                    )
6526                })?;
6527                let cache_path = if let Ok(cache_path) = client.fetch_digest(digest).await {
6528                    cache_path
6529                } else if component_resolution.dist_offline {
6530                    client
6531                        .fetch_digest(digest)
6532                        .await
6533                        .map_err(|err| dist_error_for_component(err, &spec.id, &reference))?
6534                } else {
6535                    let source = client
6536                        .parse_source(&reference)
6537                        .map_err(|err| dist_error_for_component(err, &spec.id, &reference))?;
6538                    let descriptor = client
6539                        .resolve(source, ResolvePolicy)
6540                        .await
6541                        .map_err(|err| dist_error_for_component(err, &spec.id, &reference))?;
6542                    let resolved = client
6543                        .fetch(&descriptor, CachePolicy)
6544                        .await
6545                        .map_err(|err| dist_error_for_component(err, &spec.id, &reference))?;
6546                    let expected = normalize_digest(digest);
6547                    let actual = normalize_digest(&resolved.digest);
6548                    if expected != actual {
6549                        bail!(
6550                            "component {} digest mismatch after fetch: expected {}, got {}",
6551                            spec.id,
6552                            expected,
6553                            actual
6554                        );
6555                    }
6556                    resolved.cache_path.ok_or_else(|| {
6557                        anyhow!(
6558                            "component {} resolved from {} but cache path is missing",
6559                            spec.id,
6560                            reference
6561                        )
6562                    })?
6563                };
6564                std::fs::read(&cache_path).with_context(|| {
6565                    format!(
6566                        "failed to read cached component {} from {}",
6567                        spec.id,
6568                        cache_path.display()
6569                    )
6570                })?
6571            }
6572        };
6573
6574        if let Some(expected) = source.expected_wasm_sha256.as_deref() {
6575            verify_wasm_sha256(&spec.id, expected, &bytes)?;
6576        } else if source.skip_digest_verification {
6577            let actual = compute_sha256_digest_for(&bytes);
6578            warn!(
6579                component_id = %spec.id,
6580                digest = %actual,
6581                "bundled component missing wasm_sha256; allowing due to flag"
6582            );
6583        } else {
6584            let expected = source.digest.as_deref().ok_or_else(|| {
6585                anyhow!(
6586                    "component {} missing expected digest for verification",
6587                    spec.id
6588                )
6589            })?;
6590            verify_component_digest(&spec.id, expected, &bytes)?;
6591        }
6592        let component =
6593            compile_component_with_cache(cache, engine, source.digest.as_deref(), bytes)
6594                .await
6595                .with_context(|| format!("failed to compile component {}", spec.id))?;
6596        into.insert(
6597            spec.id.clone(),
6598            PackComponent {
6599                name: spec.id.clone(),
6600                version: spec.version.clone(),
6601                component,
6602            },
6603        );
6604        missing.remove(&spec.id);
6605    }
6606
6607    Ok(())
6608}
6609
6610fn dist_error_for_component(err: DistError, component_id: &str, reference: &str) -> anyhow::Error {
6611    match err {
6612        DistError::NotFound { reference: missing } => anyhow!(
6613            "remote component {} is not cached for {}. Run `greentic-dist pull --lock <pack.lock>` or `greentic-dist pull {}`",
6614            component_id,
6615            missing,
6616            reference
6617        ),
6618        DistError::Offline { reference: blocked } => anyhow!(
6619            "offline mode blocked fetching component {} from {}; run `greentic-dist pull --lock <pack.lock>` or `greentic-dist pull {}`",
6620            component_id,
6621            blocked,
6622            reference
6623        ),
6624        DistError::Unauthorized { target } => anyhow!(
6625            "component {} requires authenticated source {}; run `greentic-dist pull --lock <pack.lock>` or `greentic-dist pull {}`",
6626            component_id,
6627            target,
6628            reference
6629        ),
6630        other => anyhow!(
6631            "failed to resolve component {} from {}: {}",
6632            component_id,
6633            reference,
6634            other
6635        ),
6636    }
6637}
6638
6639async fn load_components_from_overrides(
6640    cache: &CacheManager,
6641    engine: &Engine,
6642    overrides: &HashMap<String, PathBuf>,
6643    specs: &[ComponentSpec],
6644    missing: &mut HashSet<String>,
6645    into: &mut HashMap<String, PackComponent>,
6646) -> Result<()> {
6647    for spec in specs {
6648        if !missing.contains(&spec.id) {
6649            continue;
6650        }
6651        let Some(path) = overrides.get(&spec.id) else {
6652            continue;
6653        };
6654        let bytes = std::fs::read(path)
6655            .with_context(|| format!("failed to read override component {}", path.display()))?;
6656        let component = compile_component_with_cache(cache, engine, None, bytes)
6657            .await
6658            .with_context(|| {
6659                format!(
6660                    "failed to compile component {} from override {}",
6661                    spec.id,
6662                    path.display()
6663                )
6664            })?;
6665        into.insert(
6666            spec.id.clone(),
6667            PackComponent {
6668                name: spec.id.clone(),
6669                version: spec.version.clone(),
6670                component,
6671            },
6672        );
6673        missing.remove(&spec.id);
6674    }
6675    Ok(())
6676}
6677
6678async fn load_components_from_dir(
6679    cache: &CacheManager,
6680    engine: &Engine,
6681    root: &Path,
6682    specs: &[ComponentSpec],
6683    missing: &mut HashSet<String>,
6684    into: &mut HashMap<String, PackComponent>,
6685) -> Result<()> {
6686    for spec in specs {
6687        if !missing.contains(&spec.id) {
6688            continue;
6689        }
6690        let Some(path) = component_path_for_spec(root, spec)
6691            .with_context(|| format!("component {} has an unusable path", spec.id))?
6692        else {
6693            tracing::debug!(component = %spec.id, root = %root.display(), "materialized component missing; will try other sources");
6694            continue;
6695        };
6696        let bytes = std::fs::read(&path)
6697            .with_context(|| format!("failed to read component {}", path.display()))?;
6698        let component = compile_component_with_cache(cache, engine, None, bytes)
6699            .await
6700            .with_context(|| {
6701                format!(
6702                    "failed to compile component {} from {}",
6703                    spec.id,
6704                    path.display()
6705                )
6706            })?;
6707        into.insert(
6708            spec.id.clone(),
6709            PackComponent {
6710                name: spec.id.clone(),
6711                version: spec.version.clone(),
6712                component,
6713            },
6714        );
6715        missing.remove(&spec.id);
6716    }
6717    Ok(())
6718}
6719
6720async fn load_components_from_archive(
6721    cache: &CacheManager,
6722    engine: &Engine,
6723    path: &Path,
6724    specs: &[ComponentSpec],
6725    missing: &mut HashSet<String>,
6726    into: &mut HashMap<String, PackComponent>,
6727) -> Result<()> {
6728    let mut archive = ZipArchive::new(File::open(path)?)
6729        .with_context(|| format!("{} is not a valid gtpack", path.display()))?;
6730    for spec in specs {
6731        if !missing.contains(&spec.id) {
6732            continue;
6733        }
6734        let file_name = spec
6735            .legacy_path
6736            .clone()
6737            .unwrap_or_else(|| format!("components/{}.wasm", spec.id));
6738        let bytes = match read_entry(&mut archive, &file_name) {
6739            Ok(bytes) => bytes,
6740            Err(err) => {
6741                warn!(component = %spec.id, pack = %path.display(), error = %err, "component entry missing in pack archive");
6742                continue;
6743            }
6744        };
6745        let component = compile_component_with_cache(cache, engine, None, bytes)
6746            .await
6747            .with_context(|| format!("failed to compile component {}", spec.id))?;
6748        into.insert(
6749            spec.id.clone(),
6750            PackComponent {
6751                name: spec.id.clone(),
6752                version: spec.version.clone(),
6753                component,
6754            },
6755        );
6756        missing.remove(&spec.id);
6757    }
6758    Ok(())
6759}
6760
6761#[cfg(test)]
6762pub(crate) mod tests {
6763    use super::*;
6764    use greentic_flow::model::{FlowDoc, NodeDoc};
6765    use indexmap::IndexMap;
6766    use serde_json::json;
6767
6768    /// The whole point: a configured provider used to be invoked with its
6769    /// answers dropped, so `request.config` arrived empty.
6770    #[test]
6771    fn a_configured_provider_receives_its_answers() {
6772        let merged = PackRuntime::merge_provider_config_into_input(
6773            Some(r#"{"auto_start_on_open":false}"#),
6774            br#"{"hello":"world"}"#.to_vec(),
6775            "webchat-gui",
6776        );
6777        let value: Value = serde_json::from_slice(&merged).expect("merged payload is JSON");
6778        assert_eq!(value["config"]["auto_start_on_open"], json!(false));
6779        assert_eq!(value["input"]["hello"], json!("world"));
6780    }
6781
6782    /// An unconfigured provider must get the bytes it gets today, unchanged —
6783    /// so nothing about a provider nobody has answered for moves.
6784    #[test]
6785    fn an_unconfigured_provider_payload_is_untouched() {
6786        let original = br#"{"hello":"world"}"#.to_vec();
6787        let merged =
6788            PackRuntime::merge_provider_config_into_input(None, original.clone(), "webchat-gui");
6789        assert_eq!(merged, original);
6790    }
6791
6792    /// A provider's input is a webhook body, not a flow value, so it may not be
6793    /// JSON. The component merge would wrap it as a JSON string; doing that
6794    /// here would swap a missing config for a corrupted request body.
6795    #[test]
6796    fn a_non_json_provider_payload_is_passed_through_rather_than_wrapped() {
6797        let original = vec![0x89u8, 0x50, 0x4e, 0x47];
6798        let merged = PackRuntime::merge_provider_config_into_input(
6799            Some(r#"{"k":1}"#),
6800            original.clone(),
6801            "some-provider",
6802        );
6803        assert_eq!(merged, original, "binary payloads must survive verbatim");
6804
6805        let text = b"not json at all".to_vec();
6806        let merged =
6807            PackRuntime::merge_provider_config_into_input(Some(r#"{"k":1}"#), text.clone(), "p");
6808        assert_eq!(merged, text);
6809    }
6810
6811    #[test]
6812    fn tags_indicate_entry_treats_internal_as_non_entry() {
6813        // `internal`-tagged flows are helpers reachable only via flow.call.
6814        assert!(!tags_indicate_entry(["internal"]));
6815        assert!(!tags_indicate_entry(["default", "internal"]));
6816        // The public entrypoint and untagged/other-tagged flows are entries.
6817        assert!(tags_indicate_entry(["default"]));
6818        assert!(tags_indicate_entry(["ui", "featured"]));
6819        assert!(tags_indicate_entry(std::iter::empty::<&str>()));
6820    }
6821
6822    #[test]
6823    fn flow_descriptor_deserializes_missing_entry_as_true() {
6824        // Descriptors serialized before the `entry` field default to entry,
6825        // preserving prior routing behaviour.
6826        let desc: FlowDescriptor = serde_json::from_value(json!({
6827            "id": "default",
6828            "type": "messaging",
6829            "pack_id": "weatherapi-pack",
6830            "profile": "weatherapi-pack",
6831            "version": "0.1.0"
6832        }))
6833        .expect("descriptor without `entry` must deserialize");
6834        assert!(desc.entry);
6835    }
6836
6837    /// Build a minimal `PackRuntime` rooted at `dir` so that `read_pack_file`
6838    /// resolves files from that directory via `self.path.is_dir()`.
6839    /// Mirrors the `for_component_test` constructor but sets `path` to the
6840    /// caller-supplied directory instead of `PathBuf::new()`.
6841    ///
6842    /// `pub(crate)` so sibling modules whose subject is what a pack CARRIES —
6843    /// `runner::pack_extensions` — can drive the real reader rather than a
6844    /// stand-in that could disagree with it.
6845    ///
6846    /// Passing a path to a `.gtpack` file rather than a directory exercises the
6847    /// archive branch of the same readers: `self.path.is_dir()` is false, and
6848    /// `path_is_gtpack(&self.path)` then supplies the archive.
6849    pub(crate) fn pack_runtime_for_dir(dir: &std::path::Path) -> PackRuntime {
6850        let engine = Engine::default();
6851        let engine_profile =
6852            EngineProfile::from_engine(&engine, CpuPolicy::Native, "default".to_string());
6853        let cache = CacheManager::new(CacheConfig::default(), engine_profile);
6854        let config = Arc::new(crate::config::HostConfig {
6855            tenant: "test-tenant".to_string(),
6856            bindings_path: std::path::PathBuf::from("/tmp/bindings.yaml"),
6857            flow_type_bindings: HashMap::new(),
6858            rate_limits: crate::config::RateLimits::default(),
6859            retry: crate::config::FlowRetryConfig::default(),
6860            http_enabled: false,
6861            secrets_policy: crate::config::SecretsPolicy::allow_all(),
6862            state_store_policy: crate::config::StateStorePolicy::default(),
6863            webhook_policy: crate::config::WebhookPolicy::default(),
6864            timers: Vec::new(),
6865            oauth: None,
6866            mocks: None,
6867            pack_bindings: Vec::new(),
6868            env_passthrough: Vec::new(),
6869            trace: crate::trace::TraceConfig::from_env(),
6870            validation: crate::validate::ValidationConfig::from_env(),
6871            operator_policy: crate::config::OperatorPolicy::allow_all(),
6872            fast2flow: Default::default(),
6873            #[cfg(feature = "agentic-worker")]
6874            agents: HashMap::new(),
6875            #[cfg(feature = "agentic-worker")]
6876            graphs: HashMap::new(),
6877        });
6878        PackRuntime {
6879            path: dir.to_path_buf(),
6880            archive_path: None,
6881            config,
6882            engine,
6883            metadata: PackMetadata {
6884                pack_id: "test-pack".to_string(),
6885                version: "0.0.0".to_string(),
6886                entry_flows: Vec::new(),
6887                secret_requirements: Vec::new(),
6888            },
6889            manifest: None,
6890            legacy_manifest: None,
6891            component_manifests: HashMap::new(),
6892            mocks: None,
6893            flows: None,
6894            components: HashMap::new(),
6895            http_client: shared_http_client().expect("http client"),
6896            session_store: None,
6897            state_store: None,
6898            wasi_policy: Arc::new(crate::wasi::RunnerWasiPolicy::new()),
6899            base_wasi_policy: Arc::new(crate::wasi::RunnerWasiPolicy::new()),
6900            assets_tempdir: None,
6901            provider_registry: RwLock::new(None),
6902            identify_hint_cache: RwLock::new(HashMap::new()),
6903            identify_hint_failures: RwLock::new(HashMap::new()),
6904            secrets: crate::secrets::default_manager().expect("default secrets manager"),
6905            oauth_config: None,
6906            runtime_config_non_secret: None,
6907            runtime_refs: None,
6908            mcp_routes: std::sync::OnceLock::new(),
6909            a2a_routes: std::sync::OnceLock::new(),
6910            run_context: std::sync::OnceLock::new(),
6911            user_ledger: std::sync::OnceLock::new(),
6912            nested_flow_handlers: std::sync::OnceLock::new(),
6913            sorla_routes: std::sync::OnceLock::new(),
6914            unit_id: None,
6915            cache,
6916        }
6917    }
6918
6919    #[test]
6920    fn dw_agents_sidecar_blobs_reads_map_from_pack_dir() {
6921        let dir = tempfile::tempdir().unwrap();
6922        let agents = serde_json::json!({
6923            "greeter": { "agent_id": "greeter", "system_prompt": "hi", "tools": [],
6924                         "llm": { "provider": "openai", "model": "gpt-4o-mini" } }
6925        });
6926        std::fs::write(
6927            dir.path().join("dw-agents.json"),
6928            serde_json::to_vec(&agents).unwrap(),
6929        )
6930        .unwrap();
6931        let pack = pack_runtime_for_dir(dir.path());
6932        let blobs = pack.dw_agents_sidecar_blobs();
6933        assert!(blobs.contains_key("greeter"));
6934        assert_eq!(blobs["greeter"]["agent_id"], "greeter");
6935    }
6936
6937    /// The contract's rule 2, exercised against a real pack directory: the
6938    /// `.gtxpack` suffix decides, not membership of `extensions/`.
6939    ///
6940    /// The `.json` sidecar here is not hypothetical — the pack wizard writes
6941    /// `extensions/*.json` manifest sidecars and they are walked into the
6942    /// archive verbatim, so treating that directory as homogeneous would hand
6943    /// the extension loader a file that has never been an extension.
6944    #[cfg(feature = "agentic-worker")]
6945    #[test]
6946    fn extension_archive_entries_lists_only_gtxpack_files_from_a_pack_dir() {
6947        let dir = tempfile::tempdir().unwrap();
6948        let extensions = dir.path().join("extensions");
6949        std::fs::create_dir_all(extensions.join("nested")).unwrap();
6950        std::fs::write(extensions.join("acme.tool.gtxpack"), b"archive").unwrap();
6951        std::fs::write(extensions.join("wizard-answers.json"), b"{}").unwrap();
6952        std::fs::write(extensions.join("nested/deep.gtxpack"), b"archive").unwrap();
6953        std::fs::write(dir.path().join("manifest.cbor"), b"").unwrap();
6954
6955        let pack = pack_runtime_for_dir(dir.path());
6956        assert_eq!(
6957            pack.extension_archive_entries(),
6958            vec!["extensions/acme.tool.gtxpack".to_string()]
6959        );
6960        assert_eq!(
6961            pack.read_pack_file("extensions/acme.tool.gtxpack")
6962                .as_deref(),
6963            Some(b"archive".as_slice()),
6964            "every listed entry must be readable by the same reader"
6965        );
6966    }
6967
6968    /// The same rule over a real `.gtpack` ZIP, which is the shape a deployed
6969    /// runner actually sees — a container never has the pack materialised.
6970    #[cfg(feature = "agentic-worker")]
6971    #[test]
6972    fn extension_archive_entries_lists_only_gtxpack_files_from_a_gtpack_archive() {
6973        use std::io::Write;
6974
6975        let dir = tempfile::tempdir().unwrap();
6976        let archive_path = dir.path().join("worker.gtpack");
6977        let mut writer = zip::ZipWriter::new(std::fs::File::create(&archive_path).unwrap());
6978        let options: zip::write::FileOptions<'_, ()> =
6979            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
6980        for (name, bytes) in [
6981            ("extensions/acme.tool.gtxpack", b"archive".as_slice()),
6982            ("extensions/wizard-answers.json", b"{}".as_slice()),
6983            ("extensions/design/kinded.gtxpack", b"archive".as_slice()),
6984            ("assets/mcp-routes.json", b"{}".as_slice()),
6985        ] {
6986            writer.start_file(name, options).unwrap();
6987            writer.write_all(bytes).unwrap();
6988        }
6989        writer.finish().unwrap();
6990
6991        let pack = pack_runtime_for_dir(&archive_path);
6992        assert_eq!(
6993            pack.extension_archive_entries(),
6994            vec!["extensions/acme.tool.gtxpack".to_string()]
6995        );
6996    }
6997
6998    #[cfg(feature = "agentic-worker")]
6999    #[test]
7000    fn extension_archive_entries_is_empty_for_a_pack_built_before_the_feature() {
7001        let dir = tempfile::tempdir().unwrap();
7002        let pack = pack_runtime_for_dir(dir.path());
7003        assert!(pack.extension_archive_entries().is_empty());
7004    }
7005
7006    #[test]
7007    fn dw_agents_sidecar_blobs_absent_is_empty() {
7008        let dir = tempfile::tempdir().unwrap();
7009        let pack = pack_runtime_for_dir(dir.path());
7010        assert!(pack.dw_agents_sidecar_blobs().is_empty());
7011    }
7012
7013    #[test]
7014    fn dw_agents_sidecar_blobs_malformed_is_empty() {
7015        let dir = tempfile::tempdir().unwrap();
7016        std::fs::write(dir.path().join("dw-agents.json"), b"not json").unwrap();
7017        let pack = pack_runtime_for_dir(dir.path());
7018        assert!(pack.dw_agents_sidecar_blobs().is_empty());
7019    }
7020
7021    #[test]
7022    fn normalizes_raw_component_to_component_exec() {
7023        let mut nodes = IndexMap::new();
7024        let mut raw = IndexMap::new();
7025        raw.insert(
7026            "templating.handlebars".into(),
7027            json!({ "template": "Hi {{name}}" }),
7028        );
7029        nodes.insert(
7030            "start".into(),
7031            NodeDoc {
7032                raw,
7033                routing: json!([{"out": true}]),
7034                ..Default::default()
7035            },
7036        );
7037        let doc = FlowDoc {
7038            id: "welcome".into(),
7039            title: None,
7040            description: None,
7041            flow_type: "messaging".into(),
7042            start: Some("start".into()),
7043            parameters: json!({}),
7044            tags: Vec::new(),
7045            schema_version: None,
7046            entrypoints: IndexMap::new(),
7047            meta: None,
7048            slot_schema: None,
7049            nodes,
7050        };
7051
7052        let normalized = normalize_flow_doc(doc);
7053        let node = normalized.nodes.get("start").expect("node exists");
7054        assert_eq!(node.operation.as_deref(), Some("component.exec"));
7055        assert!(node.raw.is_empty());
7056        let payload = node.payload.as_object().expect("payload object");
7057        assert_eq!(
7058            payload.get("component"),
7059            Some(&Value::String("templating.handlebars".into()))
7060        );
7061        assert_eq!(
7062            payload.get("operation"),
7063            Some(&Value::String("render".into()))
7064        );
7065        let input = payload.get("input").unwrap();
7066        assert_eq!(input, &json!({ "template": "Hi {{name}}" }));
7067    }
7068
7069    #[test]
7070    fn normalizes_canonical_operation_node_to_component_exec_with_config() {
7071        let mut nodes = IndexMap::new();
7072        let mut raw = IndexMap::new();
7073        raw.insert(
7074            "handle_message".into(),
7075            json!({
7076                "component": "oci://ghcr.io/greenticai/component/component-llm-openai:stable",
7077                "config": {
7078                    "provider": "ollama",
7079                    "base_url": "http://127.0.0.1:11434/v1",
7080                    "default_model": "llama3.2"
7081                },
7082                "input": {
7083                    "messages": [{
7084                        "role": "user",
7085                        "content": "Say hello from Ollama."
7086                    }]
7087                }
7088            }),
7089        );
7090        nodes.insert(
7091            "llm".into(),
7092            NodeDoc {
7093                raw,
7094                routing: json!([{"out": true}]),
7095                ..Default::default()
7096            },
7097        );
7098        let doc = FlowDoc {
7099            id: "ollama-repro".into(),
7100            title: None,
7101            description: None,
7102            flow_type: "messaging".into(),
7103            start: Some("llm".into()),
7104            parameters: json!({}),
7105            tags: Vec::new(),
7106            schema_version: None,
7107            entrypoints: IndexMap::new(),
7108            meta: None,
7109            slot_schema: None,
7110            nodes,
7111        };
7112
7113        let normalized = normalize_flow_doc(doc);
7114        let node = normalized.nodes.get("llm").expect("node exists");
7115        assert_eq!(node.operation.as_deref(), Some("component.exec"));
7116        assert!(node.raw.is_empty());
7117        let payload = node.payload.as_object().expect("payload object");
7118        assert_eq!(
7119            payload.get("component"),
7120            Some(&Value::String(
7121                "oci://ghcr.io/greenticai/component/component-llm-openai:stable".into()
7122            ))
7123        );
7124        assert_eq!(
7125            payload.get("operation"),
7126            Some(&Value::String("handle_message".into()))
7127        );
7128        assert_eq!(
7129            payload.get("config"),
7130            Some(&json!({
7131                "provider": "ollama",
7132                "base_url": "http://127.0.0.1:11434/v1",
7133                "default_model": "llama3.2"
7134            }))
7135        );
7136        assert_eq!(
7137            payload.get("input"),
7138            Some(&json!({
7139                "messages": [{
7140                    "role": "user",
7141                    "content": "Say hello from Ollama."
7142                }]
7143            }))
7144        );
7145    }
7146
7147    #[test]
7148    fn missing_export_error_detection_recognises_bindgen_shapes() {
7149        // Positive: identity-world missing-instance error
7150        assert!(is_missing_export_error(
7151            "instantiation: no exported instance named \
7152             `greentic:provider-instance-identity/instance-identity-api@0.1.0`"
7153        ));
7154        // Positive: identity-world missing-function error
7155        assert!(is_missing_export_error(
7156            "instantiation: no exported function named `identify-instance`"
7157        ));
7158        // Negative: unrelated trap
7159        assert!(!is_missing_export_error(
7160            "Wasm trap: out of bounds memory access"
7161        ));
7162        // Negative: a DIFFERENT world's missing export must NOT match —
7163        // e.g. schema-core missing is a hard error, not "unsupported"
7164        assert!(!is_missing_export_error(
7165            "instantiation: no exported instance named \
7166             `greentic:provider-schema-core/schema-core-api@1.0.0`"
7167        ));
7168        // Negative: broad marker present but for a non-identity function
7169        assert!(!is_missing_export_error(
7170            "instantiation: no exported function named `invoke`"
7171        ));
7172    }
7173
7174    #[test]
7175    fn identify_outcome_merge_in_follows_lattice() {
7176        let unsupported = || IdentifyOutcome::Unsupported;
7177        let no_match = || IdentifyOutcome::NoMatch;
7178        let id_a = || IdentifyOutcome::Identified("a".to_string());
7179        let id_b = || IdentifyOutcome::Identified("b".to_string());
7180
7181        // Unsupported is the floor — every other variant promotes it.
7182        let mut x = unsupported();
7183        x.merge_in(unsupported());
7184        assert_eq!(x, unsupported());
7185        let mut x = unsupported();
7186        x.merge_in(no_match());
7187        assert_eq!(x, no_match());
7188        let mut x = unsupported();
7189        x.merge_in(id_a());
7190        assert_eq!(x, id_a());
7191
7192        // NoMatch beats Unsupported but is overridable by Identified.
7193        let mut x = no_match();
7194        x.merge_in(unsupported());
7195        assert_eq!(x, no_match(), "NoMatch must not downgrade to Unsupported");
7196        let mut x = no_match();
7197        x.merge_in(no_match());
7198        assert_eq!(x, no_match());
7199        let mut x = no_match();
7200        x.merge_in(id_a());
7201        assert_eq!(x, id_a(), "Identified must override NoMatch");
7202
7203        // Identified is the top — nothing overwrites it (first id wins).
7204        let mut x = id_a();
7205        x.merge_in(unsupported());
7206        assert_eq!(x, id_a());
7207        let mut x = id_a();
7208        x.merge_in(no_match());
7209        assert_eq!(x, id_a());
7210        let mut x = id_a();
7211        x.merge_in(id_b());
7212        assert_eq!(
7213            x,
7214            id_a(),
7215            "first Identified wins; later id does not replace"
7216        );
7217    }
7218
7219    #[test]
7220    fn a2a_routes_are_read_from_a_pack_directory() {
7221        let dir = tempfile::tempdir().unwrap();
7222        std::fs::create_dir_all(dir.path().join("assets")).unwrap();
7223        std::fs::write(
7224            dir.path().join("assets/a2a-routes.json"),
7225            br#"[{"agent_id":"recipe","base_url":"https://agent.example.com","requires_auth":true}]"#,
7226        )
7227        .unwrap();
7228        let pack = pack_runtime_for_dir(dir.path());
7229        let routes = pack.a2a_routes().expect("sidecar present");
7230        assert!(routes.get("recipe").unwrap().requires_auth);
7231        assert!(
7232            std::ptr::eq(routes, pack.a2a_routes().unwrap()),
7233            "memoised: the second read returns the same parse"
7234        );
7235    }
7236
7237    #[test]
7238    fn a2a_routes_are_read_from_a_gtpack_archive() {
7239        use std::io::Write;
7240
7241        let dir = tempfile::tempdir().unwrap();
7242        let archive_path = dir.path().join("worker.gtpack");
7243        let mut writer = zip::ZipWriter::new(std::fs::File::create(&archive_path).unwrap());
7244        let options: zip::write::FileOptions<'_, ()> =
7245            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
7246        writer
7247            .start_file("assets/a2a-routes.json", options)
7248            .unwrap();
7249        writer
7250            .write_all(br#"[{"agent_id":"recipe","base_url":"https://agent.example.com"}]"#)
7251            .unwrap();
7252        writer.finish().unwrap();
7253
7254        let pack = pack_runtime_for_dir(&archive_path);
7255        assert!(pack.a2a_routes().and_then(|r| r.get("recipe")).is_some());
7256    }
7257
7258    #[test]
7259    fn a_pack_without_the_a2a_sidecar_has_no_a2a_routes() {
7260        let dir = tempfile::tempdir().unwrap();
7261        let pack = pack_runtime_for_dir(dir.path());
7262        assert!(pack.a2a_routes().is_none());
7263    }
7264
7265    #[test]
7266    fn the_user_ledger_sidecar_is_read_from_the_pack_dir() {
7267        let dir = tempfile::tempdir().unwrap();
7268        std::fs::create_dir_all(dir.path().join("assets")).unwrap();
7269        std::fs::write(
7270            dir.path().join("assets/user-ledger.json"),
7271            br#"{"helper":"read_write"}"#,
7272        )
7273        .unwrap();
7274        let pack = pack_runtime_for_dir(dir.path());
7275        let declared = pack.user_ledger().expect("sidecar");
7276        assert_eq!(declared.agents().count(), 1);
7277        let empty = tempfile::tempdir().unwrap();
7278        assert!(pack_runtime_for_dir(empty.path()).user_ledger().is_none());
7279    }
7280
7281    #[test]
7282    fn the_user_ledger_sidecar_is_read_from_a_gtpack_archive() {
7283        use std::io::Write;
7284
7285        let dir = tempfile::tempdir().unwrap();
7286        let archive_path = dir.path().join("worker.gtpack");
7287        let mut writer = zip::ZipWriter::new(std::fs::File::create(&archive_path).unwrap());
7288        let options: zip::write::FileOptions<'_, ()> =
7289            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
7290        writer
7291            .start_file("assets/user-ledger.json", options)
7292            .unwrap();
7293        writer.write_all(br#"{"helper":"read"}"#).unwrap();
7294        writer.finish().unwrap();
7295        let pack = pack_runtime_for_dir(&archive_path);
7296        assert_eq!(pack.user_ledger().map(|l| l.agents().count()), Some(1));
7297    }
7298
7299    #[test]
7300    fn a_malformed_user_ledger_sidecar_fails_closed_without_taking_the_pack_down() {
7301        let dir = tempfile::tempdir().unwrap();
7302        std::fs::create_dir_all(dir.path().join("assets")).unwrap();
7303        std::fs::write(dir.path().join("assets/user-ledger.json"), b"{not json").unwrap();
7304        let pack = pack_runtime_for_dir(dir.path());
7305        assert!(pack.user_ledger().is_none());
7306        assert!(pack.a2a_routes().is_none(), "other sidecars unaffected");
7307    }
7308}
7309
7310#[cfg(test)]
7311mod identify_endpoints_pack_tests {
7312    use super::*;
7313    use crate::config::{
7314        FlowRetryConfig, HostConfig, OperatorPolicy, RateLimits, SecretsPolicy, StateStorePolicy,
7315        WebhookPolicy,
7316    };
7317    use crate::trace::TraceConfig;
7318    use crate::validate::ValidationConfig;
7319
7320    fn test_host_config() -> HostConfig {
7321        HostConfig {
7322            tenant: "test".to_string(),
7323            bindings_path: PathBuf::from("/tmp/bindings.yaml"),
7324            flow_type_bindings: HashMap::new(),
7325            rate_limits: RateLimits::default(),
7326            retry: FlowRetryConfig::default(),
7327            http_enabled: false,
7328            secrets_policy: SecretsPolicy::allow_all(),
7329            state_store_policy: StateStorePolicy::default(),
7330            webhook_policy: WebhookPolicy::default(),
7331            timers: Vec::new(),
7332            oauth: None,
7333            mocks: None,
7334            pack_bindings: Vec::new(),
7335            env_passthrough: Vec::new(),
7336            trace: TraceConfig::from_env(),
7337            validation: ValidationConfig::from_env(),
7338            operator_policy: OperatorPolicy::allow_all(),
7339            fast2flow: Default::default(),
7340            #[cfg(feature = "agentic-worker")]
7341            agents: HashMap::new(),
7342            #[cfg(feature = "agentic-worker")]
7343            graphs: HashMap::new(),
7344        }
7345    }
7346
7347    #[tokio::test]
7348    async fn no_manifest_returns_unsupported_for_all_types() {
7349        // A PackRuntime with manifest: None (e.g. legacy single-component
7350        // packs or the for_component_test constructor) has no provider
7351        // registry. Every requested type must map to Unsupported — NOT
7352        // NoMatch — so the caller knows it can fall back to the static
7353        // provider_id rather than failing closed.
7354        let pack = PackRuntime::for_component_test(
7355            Vec::new(),
7356            HashMap::new(),
7357            "test-pack",
7358            Arc::new(test_host_config()),
7359        )
7360        .expect("empty pack construction");
7361        let result = pack
7362            .identify_endpoints_by_provider_type(&["teams", "slack", "telegram"], b"{}")
7363            .await
7364            .expect("no-manifest path must succeed");
7365        assert_eq!(result.len(), 3);
7366        for ty in &["teams", "slack", "telegram"] {
7367            assert_eq!(
7368                result.get(*ty),
7369                Some(&IdentifyOutcome::Unsupported),
7370                "type '{ty}' must be Unsupported when pack has no manifest"
7371            );
7372        }
7373    }
7374
7375    #[tokio::test]
7376    async fn empty_provider_types_returns_empty_map() {
7377        let pack = PackRuntime::for_component_test(
7378            Vec::new(),
7379            HashMap::new(),
7380            "test-pack",
7381            Arc::new(test_host_config()),
7382        )
7383        .expect("empty pack construction");
7384        let result = pack
7385            .identify_endpoints_by_provider_type(&[], b"{}")
7386            .await
7387            .expect("empty types fast path");
7388        assert!(result.is_empty());
7389    }
7390}
7391
7392#[cfg(test)]
7393mod legacy_flow_normalize_tests {
7394    use super::*;
7395    use greentic_flow::model::{FlowDoc, NodeDoc};
7396    use indexmap::IndexMap;
7397    use serde_json::{Value, json};
7398
7399    /// Build a single-node `FlowDoc` whose only node carries the raw-YGTC
7400    /// op-key `op_key` with `payload`, mirroring the legacy flow-JSON shape the
7401    /// loader feeds into `normalize_flow_doc` -> `flow_doc_to_ir`.
7402    fn single_node_doc(op_key: &str, payload: Value) -> FlowDoc {
7403        let mut raw = IndexMap::new();
7404        raw.insert(op_key.to_string(), payload);
7405        let mut nodes = IndexMap::new();
7406        nodes.insert(
7407            "node".into(),
7408            NodeDoc {
7409                raw,
7410                routing: json!([{ "out": true }]),
7411                ..Default::default()
7412            },
7413        );
7414        FlowDoc {
7415            id: "legacy".into(),
7416            title: None,
7417            description: None,
7418            flow_type: "messaging".into(),
7419            start: Some("node".into()),
7420            parameters: json!({}),
7421            tags: Vec::new(),
7422            schema_version: None,
7423            entrypoints: IndexMap::new(),
7424            meta: None,
7425            slot_schema: None,
7426            nodes,
7427        }
7428    }
7429
7430    /// REGRESSION: the legacy flow-JSON load path (`normalize_flow_doc` ->
7431    /// `flow_doc_to_ir`) must preserve a raw-YGTC `{ mcp: { ... }, routing }`
7432    /// node VERBATIM as `component == "mcp"` with its payload intact, exactly
7433    /// like the runtime-flow (packc) path. Before the fix `normalize_flow_doc`
7434    /// rewrote every non-`emit.*` op-key into a `component.exec` node, so the
7435    /// engine saw `NodeKind::Exec` instead of the MCP dispatch arm.
7436    #[test]
7437    fn normalize_preserves_mcp_op_key_through_legacy_path() {
7438        let doc = single_node_doc(
7439            "mcp",
7440            json!({
7441                "server": "github",
7442                "tool": "get_issue",
7443                "arguments": { "id": "{{ entry.issue_id }}" },
7444                "output": "issue"
7445            }),
7446        );
7447
7448        let normalized = normalize_flow_doc(doc);
7449        let node = normalized.nodes.get("node").expect("node exists");
7450        // NOT rewritten into a `component.exec` wrapper.
7451        assert_eq!(
7452            node.operation.as_deref(),
7453            Some("mcp"),
7454            "the `mcp` op-key must survive normalization verbatim, not become component.exec"
7455        );
7456        assert!(node.raw.is_empty(), "raw op-key should be lowered");
7457
7458        // Lowering through the real adapter yields `component == "mcp"` with
7459        // the LOCKED ENCODING v2 payload (server/tool/arguments/output) intact.
7460        let ir = flow_doc_to_ir(normalized).expect("flow_doc_to_ir");
7461        let lowered = ir.nodes.get("node").expect("lowered node exists");
7462        assert_eq!(lowered.component, "mcp");
7463        assert_eq!(lowered.payload_expr["server"], json!("github"));
7464        assert_eq!(lowered.payload_expr["tool"], json!("get_issue"));
7465        assert_eq!(
7466            lowered.payload_expr["arguments"]["id"],
7467            json!("{{ entry.issue_id }}")
7468        );
7469        assert_eq!(lowered.payload_expr["output"], json!("issue"));
7470    }
7471
7472    /// No regression to the passthrough set: the other native op-keys-with-
7473    /// payload (`dw.agent`, `sorla.call`) must also survive `normalize_flow_doc`
7474    /// verbatim rather than being wrapped in `component.exec`.
7475    #[test]
7476    fn normalize_preserves_dw_agent_and_sorla_call_op_keys() {
7477        for op_key in ["dw.agent", "sorla.call", "media.create"] {
7478            let doc = single_node_doc(op_key, json!({ "input": { "x": 1 } }));
7479            let normalized = normalize_flow_doc(doc);
7480            let node = normalized.nodes.get("node").expect("node exists");
7481            assert_eq!(
7482                node.operation.as_deref(),
7483                Some(op_key),
7484                "`{op_key}` must survive normalization verbatim, not become component.exec"
7485            );
7486            assert!(node.raw.is_empty());
7487
7488            let ir = flow_doc_to_ir(normalized).expect("flow_doc_to_ir");
7489            let lowered = ir.nodes.get("node").expect("lowered node exists");
7490            assert_eq!(lowered.component, op_key);
7491        }
7492    }
7493}
7494
7495#[derive(Clone, Debug, Default, Serialize, Deserialize)]
7496pub struct PackMetadata {
7497    pub pack_id: String,
7498    pub version: String,
7499    #[serde(default)]
7500    pub entry_flows: Vec<String>,
7501    #[serde(default)]
7502    pub secret_requirements: Vec<greentic_types::SecretRequirement>,
7503}
7504
7505impl PackMetadata {
7506    fn from_wasm(bytes: &[u8]) -> Option<Self> {
7507        let parser = Parser::new(0);
7508        for payload in parser.parse_all(bytes) {
7509            let payload = payload.ok()?;
7510            match payload {
7511                Payload::CustomSection(section) => {
7512                    if section.name() == "greentic.manifest"
7513                        && let Ok(meta) = Self::from_bytes(section.data())
7514                    {
7515                        return Some(meta);
7516                    }
7517                }
7518                Payload::DataSection(reader) => {
7519                    for segment in reader.into_iter().flatten() {
7520                        if let Ok(meta) = Self::from_bytes(segment.data) {
7521                            return Some(meta);
7522                        }
7523                    }
7524                }
7525                _ => {}
7526            }
7527        }
7528        None
7529    }
7530
7531    fn from_bytes(bytes: &[u8]) -> Result<Self, serde_cbor::Error> {
7532        #[derive(Deserialize)]
7533        struct RawManifest {
7534            pack_id: String,
7535            version: String,
7536            #[serde(default)]
7537            entry_flows: Vec<String>,
7538            #[serde(default)]
7539            flows: Vec<RawFlow>,
7540            #[serde(default)]
7541            secret_requirements: Vec<greentic_types::SecretRequirement>,
7542        }
7543
7544        #[derive(Deserialize)]
7545        struct RawFlow {
7546            id: String,
7547        }
7548
7549        let manifest: RawManifest = serde_cbor::from_slice(bytes)?;
7550        let mut entry_flows = if manifest.entry_flows.is_empty() {
7551            manifest.flows.iter().map(|f| f.id.clone()).collect()
7552        } else {
7553            manifest.entry_flows.clone()
7554        };
7555        entry_flows.retain(|id| !id.is_empty());
7556        Ok(Self {
7557            pack_id: manifest.pack_id,
7558            version: manifest.version,
7559            entry_flows,
7560            secret_requirements: manifest.secret_requirements,
7561        })
7562    }
7563
7564    pub fn fallback(path: &Path) -> Self {
7565        let pack_id = path
7566            .file_stem()
7567            .map(|s| s.to_string_lossy().into_owned())
7568            .unwrap_or_else(|| "unknown-pack".to_string());
7569        Self {
7570            pack_id,
7571            version: "0.0.0".to_string(),
7572            entry_flows: Vec::new(),
7573            secret_requirements: Vec::new(),
7574        }
7575    }
7576
7577    pub fn from_manifest(manifest: &greentic_types::PackManifest) -> Self {
7578        let entry_flows = manifest
7579            .flows
7580            .iter()
7581            .map(|flow| flow.id.as_str().to_string())
7582            .collect::<Vec<_>>();
7583        Self {
7584            pack_id: manifest.pack_id.as_str().to_string(),
7585            version: manifest.version.to_string(),
7586            entry_flows,
7587            secret_requirements: manifest.secret_requirements.clone(),
7588        }
7589    }
7590}
7591
7592#[cfg(test)]
7593mod audit_hardening_tests {
7594    use super::tests::pack_runtime_for_dir;
7595    use super::*;
7596    use std::io::Write;
7597
7598    fn write_zip(path: &Path, entries: &[(&str, &[u8])]) {
7599        let file = File::create(path).expect("create zip");
7600        let mut writer = zip::ZipWriter::new(file);
7601        for (name, body) in entries {
7602            writer
7603                .start_file(*name, zip::write::SimpleFileOptions::default())
7604                .expect("start file");
7605            writer.write_all(body).expect("write entry");
7606        }
7607        writer.finish().expect("finish zip");
7608    }
7609
7610    #[test]
7611    fn extract_assets_rejects_zip_slip_entry() {
7612        let dir = tempfile::tempdir().expect("tmp");
7613        let archive = dir.path().join("evil.gtpack");
7614        write_zip(&archive, &[("assets/../../evil.txt", b"pwned")]);
7615        let err =
7616            extract_assets_from_archive(&archive).expect_err("zip-slip entry must be rejected");
7617        assert!(err.to_string().contains("unsafe asset path"));
7618        assert!(!dir.path().join("evil.txt").exists());
7619    }
7620
7621    #[test]
7622    fn extract_assets_caps_the_entry_count() {
7623        let dir = tempfile::tempdir().expect("tmp");
7624        let archive = dir.path().join("many.gtpack");
7625        let names: Vec<String> = (0..6).map(|i| format!("assets/f{i}.txt")).collect();
7626        let entries: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), &b""[..])).collect();
7627        write_zip(&archive, &entries);
7628        let err = extract_assets_with_entry_cap(&archive, 5)
7629            .expect_err("more entries than the cap must be refused");
7630        assert!(err.to_string().contains("too many asset entries"), "{err}");
7631        assert!(extract_assets_with_entry_cap(&archive, 6).is_ok());
7632        // Entries outside `assets/` do not count.
7633        let other = dir.path().join("other.gtpack");
7634        let mut entries: Vec<(&str, &[u8])> = vec![("assets/a.txt", &b"x"[..])];
7635        let outside: Vec<String> = (0..10).map(|i| format!("flows/f{i}.ygtc")).collect();
7636        entries.extend(outside.iter().map(|n| (n.as_str(), &b""[..])));
7637        write_zip(&other, &entries);
7638        assert!(extract_assets_with_entry_cap(&other, 1).is_ok());
7639    }
7640
7641    #[test]
7642    fn extract_assets_extracts_regular_entries() {
7643        let dir = tempfile::tempdir().expect("tmp");
7644        let archive = dir.path().join("ok.gtpack");
7645        write_zip(
7646            &archive,
7647            &[("assets/cards/a.json", b"{}"), ("other.txt", b"x")],
7648        );
7649        let (temp, assets) = extract_assets_from_archive(&archive)
7650            .expect("extract")
7651            .expect("assets present");
7652        assert_eq!(
7653            std::fs::read(assets.join("cards/a.json")).expect("read"),
7654            b"{}"
7655        );
7656        drop(temp);
7657    }
7658
7659    #[test]
7660    fn bounded_read_rejects_oversized_entries() {
7661        let data = [7u8; 100];
7662        assert_eq!(
7663            read_to_end_bounded(&data[..], 100).expect("fits").len(),
7664            100
7665        );
7666        assert!(read_to_end_bounded(&data[..], 99).is_err());
7667    }
7668
7669    #[test]
7670    fn confined_asset_path_blocks_traversal_and_symlink_escape() {
7671        let dir = tempfile::tempdir().expect("tmp");
7672        let root = dir.path().join("assets");
7673        std::fs::create_dir_all(root.join("cards")).expect("mkdir");
7674        std::fs::write(root.join("cards/a.json"), b"{}").expect("write");
7675        std::fs::write(dir.path().join("secret.txt"), b"top-secret").expect("write secret");
7676
7677        assert!(
7678            confined_asset_path(&root, "cards/a.json")
7679                .expect("ok")
7680                .is_some()
7681        );
7682        assert!(
7683            confined_asset_path(&root, "cards/missing.json")
7684                .expect("ok")
7685                .is_none()
7686        );
7687        assert!(confined_asset_path(&root, "../secret.txt").is_err());
7688        assert!(confined_asset_path(&root, "/etc/passwd").is_err());
7689        assert!(confined_asset_path(&root, "cards/../../secret.txt").is_err());
7690
7691        #[cfg(unix)]
7692        {
7693            std::os::unix::fs::symlink(dir.path().join("secret.txt"), root.join("link.txt"))
7694                .expect("symlink");
7695            assert!(confined_asset_path(&root, "link.txt").is_err());
7696        }
7697    }
7698
7699    #[test]
7700    fn pack_lock_is_searched_only_beside_the_archive() {
7701        let archive = Path::new("/a/b/c.gtpack");
7702        assert_eq!(
7703            find_pack_lock_roots(archive, false, None),
7704            vec![PathBuf::from("/a/b")]
7705        );
7706        assert_eq!(
7707            find_pack_lock_roots(Path::new("/x/y.gtpack"), false, Some(archive)),
7708            vec![PathBuf::from("/a/b")]
7709        );
7710    }
7711
7712    #[test]
7713    fn a_corrupt_pack_lock_is_an_error_for_the_loader_to_skip() {
7714        let dir = tempfile::tempdir().expect("tmp");
7715        std::fs::write(dir.path().join("pack.lock"), b"not json").expect("write");
7716        assert!(load_pack_lock(dir.path()).is_err());
7717    }
7718
7719    #[test]
7720    fn component_paths_are_confined_to_the_pack_root() {
7721        let dir = tempfile::tempdir().expect("tmp");
7722        let root = dir.path().join("pack");
7723        std::fs::create_dir_all(root.join("components")).expect("mkdir");
7724        std::fs::write(root.join("components/ok.wasm"), b"\0asm").expect("write");
7725        std::fs::write(dir.path().join("outside.wasm"), b"\0asm").expect("write");
7726        let spec = |id: &str, legacy: Option<&str>| ComponentSpec {
7727            id: id.to_string(),
7728            version: "0.0.0".to_string(),
7729            legacy_path: legacy.map(str::to_string),
7730        };
7731        assert!(
7732            component_path_for_spec(&root, &spec("ok", None))
7733                .expect("ok")
7734                .is_some()
7735        );
7736        assert!(
7737            component_path_for_spec(&root, &spec("gone", None))
7738                .expect("ok")
7739                .is_none()
7740        );
7741        assert!(component_path_for_spec(&root, &spec("x", Some("../outside.wasm"))).is_err());
7742        let absolute = dir.path().join("outside.wasm").display().to_string();
7743        assert!(component_path_for_spec(&root, &spec("x", Some(&absolute))).is_err());
7744        assert!(component_path_for_spec(&root, &spec("../outside", None)).is_err());
7745    }
7746
7747    #[test]
7748    fn read_pack_file_is_confined_to_the_pack_directory() {
7749        let dir = tempfile::tempdir().expect("tmp");
7750        let root = dir.path().join("pack");
7751        std::fs::create_dir_all(root.join("assets")).expect("mkdir");
7752        std::fs::write(root.join("assets/ok.txt"), b"fine").expect("write");
7753        let secret = dir.path().join("secret.txt");
7754        std::fs::write(&secret, b"top-secret").expect("write secret");
7755        let pack = pack_runtime_for_dir(&root);
7756
7757        assert_eq!(pack.read_pack_file("assets/ok.txt"), Some(b"fine".to_vec()));
7758        assert_eq!(pack.read_pack_file("../secret.txt"), None);
7759        assert_eq!(pack.read_pack_file("assets/../../secret.txt"), None);
7760        assert_eq!(pack.read_pack_file(&secret.display().to_string()), None);
7761
7762        #[cfg(unix)]
7763        {
7764            std::os::unix::fs::symlink(&secret, root.join("assets/link.txt")).expect("symlink");
7765            assert_eq!(pack.read_pack_file("assets/link.txt"), None);
7766        }
7767    }
7768
7769    #[test]
7770    fn state_values_preserve_json_text_and_binary() {
7771        assert_eq!(
7772            state_value_from_bytes(b"{\"a\":1}"),
7773            serde_json::json!({"a": 1})
7774        );
7775        assert_eq!(
7776            state_value_from_bytes(b"plain text"),
7777            Value::String("plain text".into())
7778        );
7779        let binary = vec![0xff, 0x00, 0xfe];
7780        let stored = state_value_from_bytes(&binary);
7781        assert_eq!(state_bytes_from_value(&stored).expect("decode"), binary);
7782        assert_eq!(
7783            state_bytes_from_value(&serde_json::json!({"a": 1})).expect("json"),
7784            b"{\"a\":1}".to_vec()
7785        );
7786    }
7787
7788    #[test]
7789    fn v06_input_falls_back_to_a_string_for_non_json() {
7790        assert_eq!(parse_v06_input("{\"a\":1}"), serde_json::json!({"a": 1}));
7791        assert_eq!(
7792            parse_v06_input("hello there"),
7793            Value::String("hello there".into())
7794        );
7795    }
7796
7797    #[test]
7798    fn identify_failure_backoff_expires() {
7799        let now = std::time::Instant::now();
7800        assert!(!identify_failure_backoff_active(None, now));
7801        assert!(identify_failure_backoff_active(Some(now), now));
7802        let later = now + IDENTIFY_FAILURE_BACKOFF + Duration::from_secs(1);
7803        assert!(!identify_failure_backoff_active(Some(now), later));
7804    }
7805
7806    #[test]
7807    fn artifact_key_is_derived_from_actual_bytes() {
7808        let engine = Engine::default();
7809        let profile = EngineProfile::from_engine(&engine, CpuPolicy::Native, "default".into());
7810        let cache = CacheManager::new(CacheConfig::default(), profile);
7811        let key_a = build_artifact_key(&cache, b"one");
7812        let key_b = build_artifact_key(&cache, b"two");
7813        assert_ne!(key_a.wasm_digest, key_b.wasm_digest);
7814        assert_eq!(key_a.wasm_digest, compute_sha256_digest_for(b"one"));
7815    }
7816
7817    #[tokio::test]
7818    async fn wasi_thread_reports_panics_as_errors_without_blocking() {
7819        let err = run_on_wasi_thread::<_, ()>("test.panic", || panic!("boom"))
7820            .await
7821            .expect_err("panic is surfaced");
7822        assert!(err.to_string().contains("boom"));
7823        let ok = run_on_wasi_thread("test.ok", || Ok(41 + 1))
7824            .await
7825            .expect("ok");
7826        assert_eq!(ok, 42);
7827    }
7828}
7829
7830#[cfg(test)]
7831mod guest_http_timeout_tests {
7832    use super::guest_timeout;
7833    use std::time::Duration;
7834
7835    const CEILING: Duration = Duration::from_secs(30);
7836
7837    #[test]
7838    fn absent_or_zero_keeps_the_default() {
7839        assert_eq!(guest_timeout(None, CEILING), None);
7840        assert_eq!(guest_timeout(Some(0), CEILING), None);
7841    }
7842
7843    #[test]
7844    fn value_under_the_ceiling_is_honoured() {
7845        assert_eq!(
7846            guest_timeout(Some(5_000), CEILING),
7847            Some(Duration::from_secs(5))
7848        );
7849    }
7850
7851    #[test]
7852    fn value_over_the_ceiling_is_clamped() {
7853        assert_eq!(guest_timeout(Some(u32::MAX), CEILING), Some(CEILING));
7854        assert_eq!(guest_timeout(Some(30_001), CEILING), Some(CEILING));
7855    }
7856}