1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::future::Future;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5
6use anyhow::{Context, Result, anyhow, bail};
7use arc_swap::ArcSwap;
8use parking_lot::Mutex;
9use reqwest::Client;
10use serde_json::Value;
11use tokio::runtime::{Handle, Runtime};
12use tokio::task::JoinHandle;
13use tokio_util::sync::CancellationToken;
14
15use crate::config::HostConfig;
16use crate::engine::host::{SessionHost, StateHost};
17use crate::engine::runtime::StateMachineRuntime;
18use crate::oauth::{OAuthBrokerConfig, request_resource_token_with_auth};
19use crate::operator_metrics::OperatorMetrics;
20use crate::operator_registry::OperatorRegistry;
21use crate::pack::{ComponentResolution, PackRuntime};
22use crate::runner::adapt_events_email::{
23 EmailExecutionPlan, EmailSendRequest, build_email_execution_plan, execute_email_request,
24};
25use crate::runner::contract_cache::{ContractCache, ContractCacheStats};
26use crate::runner::engine::FlowEngine;
27use crate::runner::mocks::MockLayer;
28use crate::secrets::{DynSecretsManager, canonicalize_secret_key, read_secret_blocking};
29use crate::storage::session::DynSessionStore;
30use crate::storage::state::DynStateStore;
31use crate::telemetry::RolloutIds;
32use crate::trace::PackTraceInfo;
33use crate::wasi::RunnerWasiPolicy;
34use greentic_deploy_spec::ids::{BundleId, DeploymentId, RevisionId};
35use greentic_types::SecretRequirement;
36use runner_core::packs::PackDigest;
37
38const RUNTIME_SECRETS_PACK_ID: &str = "_runner";
39
40#[derive(Clone, Debug, PartialEq, Eq, Hash)]
46pub struct RuntimeKey {
47 pub tenant: String,
48 pub deployment_id: Option<DeploymentId>,
49 pub bundle_id: Option<BundleId>,
50 pub revision_id: Option<RevisionId>,
51}
52
53impl RuntimeKey {
54 pub fn legacy(tenant: impl Into<String>) -> Self {
56 Self {
57 tenant: tenant.into(),
58 deployment_id: None,
59 bundle_id: None,
60 revision_id: None,
61 }
62 }
63
64 pub fn revision(
66 tenant: impl Into<String>,
67 deployment_id: DeploymentId,
68 bundle_id: BundleId,
69 revision_id: RevisionId,
70 ) -> Self {
71 Self {
72 tenant: tenant.into(),
73 deployment_id: Some(deployment_id),
74 bundle_id: Some(bundle_id),
75 revision_id: Some(revision_id),
76 }
77 }
78
79 pub fn is_legacy(&self) -> bool {
81 self.deployment_id.is_none() && self.bundle_id.is_none() && self.revision_id.is_none()
82 }
83}
84
85fn merge_legacy_reload<V: Clone>(
90 prev: &HashMap<RuntimeKey, V>,
91 mut legacy: HashMap<RuntimeKey, V>,
92) -> HashMap<RuntimeKey, V> {
93 for (key, value) in prev {
94 if !key.is_legacy() {
95 legacy.insert(key.clone(), value.clone());
96 }
97 }
98 legacy
99}
100
101fn remove_keyed_entry<V: Clone>(
106 prev: &HashMap<RuntimeKey, V>,
107 key: &RuntimeKey,
108) -> Option<(HashMap<RuntimeKey, V>, V)> {
109 let removed = prev.get(key)?.clone();
110 let mut next = prev.clone();
111 next.remove(key);
112 Some((next, removed))
113}
114
115fn insert_keyed_entry<V: Clone>(
119 prev: &HashMap<RuntimeKey, V>,
120 key: RuntimeKey,
121 value: V,
122) -> HashMap<RuntimeKey, V> {
123 let mut next = prev.clone();
124 next.insert(key, value);
125 next
126}
127
128pub struct ActivePacks {
134 inner: ArcSwap<HashMap<RuntimeKey, Arc<TenantRuntime>>>,
135 write_lock: Mutex<()>,
136}
137
138impl ActivePacks {
139 pub fn new() -> Self {
140 Self {
141 inner: ArcSwap::from_pointee(HashMap::new()),
142 write_lock: Mutex::new(()),
143 }
144 }
145
146 pub fn load_pack(&self, tenant: &str) -> Option<Arc<TenantRuntime>> {
149 self.inner.load().get(&RuntimeKey::legacy(tenant)).cloned()
150 }
151
152 pub fn load_revision(
154 &self,
155 tenant: &str,
156 deployment_id: DeploymentId,
157 bundle_id: BundleId,
158 revision_id: RevisionId,
159 ) -> Option<Arc<TenantRuntime>> {
160 self.inner
161 .load()
162 .get(&RuntimeKey::revision(
163 tenant,
164 deployment_id,
165 bundle_id,
166 revision_id,
167 ))
168 .cloned()
169 }
170
171 pub fn snapshot(&self) -> Arc<HashMap<RuntimeKey, Arc<TenantRuntime>>> {
172 self.inner.load_full()
173 }
174
175 pub fn insert_pack(&self, tenant: &str, runtime: Arc<TenantRuntime>) {
184 let _guard = self.write_lock.lock();
185 let mut next = (*self.inner.load_full()).clone();
186 let replaced = next.insert(RuntimeKey::legacy(tenant), Arc::clone(&runtime));
187 self.inner.store(Arc::new(next));
188 retire_replaced(replaced, &runtime);
189 }
190
191 pub fn insert_revision(
205 &self,
206 tenant: &str,
207 deployment_id: DeploymentId,
208 bundle_id: BundleId,
209 revision_id: RevisionId,
210 runtime: Arc<TenantRuntime>,
211 ) -> Result<()> {
212 if runtime.tenant() != tenant {
213 bail!(
214 "revision runtime tenant `{}` does not match key tenant `{tenant}`",
215 runtime.tenant()
216 );
217 }
218 let ids = runtime.engine().rollout_ids();
219 let key_deployment = deployment_id.to_string();
220 let key_bundle = bundle_id.as_str();
221 let key_revision = revision_id.to_string();
222 if ids.deployment_id.as_deref() != Some(key_deployment.as_str())
223 || ids.bundle_id.as_deref() != Some(key_bundle)
224 || ids.revision_id.as_deref() != Some(key_revision.as_str())
225 {
226 bail!(
227 "revision runtime rollout identity (deployment={:?}, bundle={:?}, revision={:?}) \
228 does not match key (deployment=`{key_deployment}`, bundle=`{key_bundle}`, \
229 revision=`{key_revision}`)",
230 ids.deployment_id,
231 ids.bundle_id,
232 ids.revision_id
233 );
234 }
235 let _guard = self.write_lock.lock();
236 let key = RuntimeKey::revision(tenant, deployment_id, bundle_id, revision_id);
237 let prev = self.inner.load_full();
238 let replaced = prev.get(&key).cloned();
239 let next = insert_keyed_entry(&prev, key, Arc::clone(&runtime));
240 self.inner.store(Arc::new(next));
241 retire_replaced(replaced, &runtime);
242 Ok(())
243 }
244
245 pub fn replace_legacy(&self, legacy: HashMap<RuntimeKey, Arc<TenantRuntime>>) {
249 let _guard = self.write_lock.lock();
250 let prev = self.inner.load_full();
251 let next = merge_legacy_reload(&prev, legacy);
252 self.inner.store(Arc::new(next));
253 }
254
255 pub fn remove_revision(
261 &self,
262 tenant: &str,
263 deployment_id: DeploymentId,
264 bundle_id: BundleId,
265 revision_id: RevisionId,
266 ) -> Option<Arc<TenantRuntime>> {
267 let _guard = self.write_lock.lock();
268 let prev = self.inner.load_full();
269 let key = RuntimeKey::revision(tenant, deployment_id, bundle_id, revision_id);
270 let (next, removed) = remove_keyed_entry(&prev, &key)?;
271 self.inner.store(Arc::new(next));
272 removed.abort_timers();
275 Some(removed)
276 }
277
278 pub fn replace(&self, next: HashMap<RuntimeKey, Arc<TenantRuntime>>) {
281 let _guard = self.write_lock.lock();
282 self.inner.store(Arc::new(next));
283 }
284
285 pub fn len(&self) -> usize {
286 self.inner.load().len()
287 }
288
289 pub fn is_empty(&self) -> bool {
290 self.len() == 0
291 }
292}
293
294fn retire_replaced(replaced: Option<Arc<TenantRuntime>>, current: &Arc<TenantRuntime>) {
297 if let Some(old) = replaced
298 && !Arc::ptr_eq(&old, current)
299 {
300 old.abort_timers();
301 }
302}
303
304impl Default for ActivePacks {
305 fn default() -> Self {
306 Self::new()
307 }
308}
309
310pub struct TenantRuntime {
312 tenant: String,
313 config: Arc<HostConfig>,
314 packs: Vec<Arc<PackRuntime>>,
315 digests: Vec<Option<String>>,
316 engine: Arc<FlowEngine>,
317 state_machine: Arc<StateMachineRuntime>,
318 session_store: DynSessionStore,
325 http_client: Client,
326 mocks: Option<Arc<MockLayer>>,
327 timer_handles: Mutex<Vec<JoinHandle<()>>>,
328 timer_cancel: CancellationToken,
332 background_handles: Mutex<Vec<JoinHandle<()>>>,
336 secrets: DynSecretsManager,
337 operator_registry: OperatorRegistry,
338 operator_metrics: Arc<OperatorMetrics>,
339 contract_cache: ContractCache,
340 approval_inbox: Option<crate::runner::approval_http::HttpApprovalDispatcher>,
344}
345
346#[derive(Clone)]
347pub struct ResolvedComponent {
348 pub digest: String,
349 pub component_ref: String,
350 pub pack: Arc<PackRuntime>,
351}
352
353#[derive(Clone, Debug)]
359pub struct RevisionPackRef {
360 pub path: PathBuf,
361 pub digest: String,
362}
363
364pub struct RevisionLoad<'a> {
368 pub pack_refs: &'a [RevisionPackRef],
369 pub config: Arc<HostConfig>,
370 pub mocks: Option<Arc<MockLayer>>,
371 pub wasi_policy: Arc<RunnerWasiPolicy>,
372 pub session_host: Arc<dyn SessionHost>,
373 pub session_store: DynSessionStore,
374 pub state_store: DynStateStore,
375 pub state_host: Arc<dyn StateHost>,
376 pub secrets_manager: DynSecretsManager,
377 pub deployment_id: DeploymentId,
378 pub bundle_id: BundleId,
379 pub revision_id: RevisionId,
380 pub customer_id: Option<String>,
381 pub runtime_configs_by_pack_id: &'a BTreeMap<String, Arc<BTreeMap<String, Value>>>,
382 pub runtime_refs_by_pack_id: &'a BTreeMap<String, Arc<BTreeMap<String, String>>>,
383 pub runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
384}
385
386#[derive(Clone, Default)]
392#[non_exhaustive]
393pub struct RevisionHostOptions {
394 #[cfg(feature = "agentic-worker")]
395 billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
396 run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
397 approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
398 #[cfg(feature = "agentic-worker")]
399 user_ledger: Option<greentic_aw_runtime::user_ledger::UserLedgerTarget>,
400 #[cfg(feature = "agentic-worker")]
401 artifact_reader: Option<crate::host::ArtifactReaderPort>,
402 #[cfg(feature = "agentic-worker")]
403 ext_artifact_port: Option<crate::host::ExtArtifactPort>,
404}
405
406impl std::fmt::Debug for RevisionHostOptions {
407 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408 let mut out = f.debug_struct("RevisionHostOptions");
409 #[cfg(feature = "agentic-worker")]
410 out.field("billing_meter", &self.billing_meter.is_some());
411 out.field("run_outcome_sink", &self.run_outcome_sink.is_some());
412 out.field("approval_inbox", &self.approval_inbox.is_some());
413 #[cfg(feature = "agentic-worker")]
414 out.field("user_ledger", &self.user_ledger.is_some());
415 #[cfg(feature = "agentic-worker")]
416 out.field("artifact_reader", &self.artifact_reader.is_some());
417 #[cfg(feature = "agentic-worker")]
418 out.field("ext_artifact_port", &self.ext_artifact_port.is_some());
419 out.finish()
420 }
421}
422
423impl RevisionHostOptions {
424 #[cfg(feature = "agentic-worker")]
428 #[must_use]
429 pub fn with_billing_meter(
430 mut self,
431 meter: Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
432 ) -> Self {
433 self.billing_meter = Some(meter);
434 self
435 }
436
437 #[must_use]
443 pub fn with_run_outcome_sink(
444 mut self,
445 sink: Arc<dyn crate::run_outcome::RunOutcomeSink>,
446 ) -> Self {
447 self.run_outcome_sink = Some(sink);
448 self
449 }
450
451 #[must_use]
467 pub fn with_approval_inbox(
468 mut self,
469 target: crate::runner::approval_http::ApprovalInboxTarget,
470 ) -> Self {
471 self.approval_inbox = Some(target);
472 self
473 }
474
475 #[cfg(feature = "agentic-worker")]
497 #[must_use]
498 pub fn with_user_ledger(
499 mut self,
500 target: greentic_aw_runtime::user_ledger::UserLedgerTarget,
501 ) -> Self {
502 self.user_ledger = Some(target);
503 self
504 }
505
506 #[cfg(feature = "agentic-worker")]
521 #[must_use]
522 pub fn with_artifact_reader(mut self, reader: crate::host::ArtifactReaderPort) -> Self {
523 self.artifact_reader = Some(reader);
524 self
525 }
526
527 #[cfg(feature = "agentic-worker")]
537 #[must_use]
538 pub fn with_ext_artifact_port(mut self, port: crate::host::ExtArtifactPort) -> Self {
539 self.ext_artifact_port = Some(port);
540 self
541 }
542}
543
544pub fn block_on<F, R>(future: F) -> R
555where
556 F: Future<Output = R> + Send,
557 R: Send,
558{
559 match Handle::try_current() {
560 Ok(handle) => block_in_context(&handle, future).unwrap_or_else(|(future, err)| {
561 tracing::warn!(error = %err, "falling back to a runtime-less executor");
562 futures::executor::block_on(future)
563 }),
564 Err(_) => match build_scoped_runtime() {
565 Ok(rt) => rt.block_on(future),
566 Err(err) => {
567 tracing::warn!(error = %err, "falling back to a runtime-less executor");
568 futures::executor::block_on(future)
569 }
570 },
571 }
572}
573
574pub fn try_block_on<F, R>(future: F) -> Result<R>
577where
578 F: Future<Output = R> + Send,
579 R: Send,
580{
581 match Handle::try_current() {
582 Ok(handle) => block_in_context(&handle, future).map_err(|(_, err)| err),
583 Err(_) => Ok(build_scoped_runtime()?.block_on(future)),
584 }
585}
586
587fn build_scoped_runtime() -> Result<Runtime> {
588 tokio::runtime::Builder::new_current_thread()
589 .enable_all()
590 .build()
591 .context("failed to create tokio runtime")
592}
593
594fn block_in_context<F, R>(handle: &Handle, future: F) -> std::result::Result<R, (F, anyhow::Error)>
597where
598 F: Future<Output = R> + Send,
599 R: Send,
600{
601 use tokio::runtime::RuntimeFlavor;
602 if matches!(handle.runtime_flavor(), RuntimeFlavor::MultiThread) {
603 return Ok(tokio::task::block_in_place(|| handle.block_on(future)));
604 }
605 let rt = match build_scoped_runtime() {
606 Ok(rt) => rt,
607 Err(err) => return Err((future, err)),
608 };
609 std::thread::scope(|scope| {
611 match scope.spawn(move || rt.block_on(future)).join() {
612 Ok(value) => Ok(value),
613 Err(payload) => std::panic::resume_unwind(payload),
616 }
617 })
618}
619
620impl TenantRuntime {
621 #[allow(clippy::too_many_arguments)]
622 pub async fn load(
623 pack_path: &Path,
624 config: Arc<HostConfig>,
625 mocks: Option<Arc<MockLayer>>,
626 archive_source: Option<&Path>,
627 digest: Option<String>,
628 wasi_policy: Arc<RunnerWasiPolicy>,
629 session_host: Arc<dyn SessionHost>,
630 session_store: DynSessionStore,
631 state_store: DynStateStore,
632 state_host: Arc<dyn StateHost>,
633 secrets_manager: DynSecretsManager,
634 #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
635 #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
636 #[cfg(feature = "agentic-worker")] stream_observers: Option<
637 crate::http::agent_stream::StreamObserverRegistry,
638 >,
639 ) -> Result<Arc<Self>> {
640 Self::load_with_artifact_reader(
641 pack_path,
642 config,
643 mocks,
644 archive_source,
645 digest,
646 wasi_policy,
647 session_host,
648 session_store,
649 state_store,
650 state_host,
651 secrets_manager,
652 #[cfg(feature = "agentic-worker")]
653 ext_llm_port,
654 #[cfg(feature = "agentic-worker")]
655 mcp_source,
656 #[cfg(feature = "agentic-worker")]
658 None,
659 #[cfg(feature = "agentic-worker")]
660 None,
661 #[cfg(feature = "agentic-worker")]
662 stream_observers,
663 )
664 .await
665 }
666
667 #[allow(clippy::too_many_arguments)]
671 pub(crate) async fn load_with_artifact_reader(
672 pack_path: &Path,
673 config: Arc<HostConfig>,
674 mocks: Option<Arc<MockLayer>>,
675 archive_source: Option<&Path>,
676 digest: Option<String>,
677 wasi_policy: Arc<RunnerWasiPolicy>,
678 session_host: Arc<dyn SessionHost>,
679 session_store: DynSessionStore,
680 state_store: DynStateStore,
681 state_host: Arc<dyn StateHost>,
682 secrets_manager: DynSecretsManager,
683 #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
684 #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
685 #[cfg(feature = "agentic-worker")] artifact_reader: Option<crate::host::ArtifactReaderPort>,
686 #[cfg(feature = "agentic-worker")] ext_artifact_port: Option<crate::host::ExtArtifactPort>,
687 #[cfg(feature = "agentic-worker")] stream_observers: Option<
688 crate::http::agent_stream::StreamObserverRegistry,
689 >,
690 ) -> Result<Arc<Self>> {
691 let pack = Self::load_pack_runtime(
692 pack_path,
693 &config,
694 mocks.clone(),
695 archive_source,
696 &wasi_policy,
697 &session_store,
698 &state_store,
699 &secrets_manager,
700 &BTreeMap::new(),
701 &BTreeMap::new(),
702 None,
703 None,
706 )
707 .await?;
708 Self::from_packs_with_artifact_reader(
709 config,
710 vec![(pack, digest)],
711 mocks,
712 session_host,
713 session_store,
714 state_store,
715 state_host,
716 secrets_manager,
717 #[cfg(feature = "agentic-worker")]
718 ext_llm_port,
719 #[cfg(feature = "agentic-worker")]
720 mcp_source,
721 #[cfg(feature = "agentic-worker")]
722 artifact_reader,
723 #[cfg(feature = "agentic-worker")]
724 ext_artifact_port,
725 #[cfg(feature = "agentic-worker")]
726 stream_observers,
727 )
728 .await
729 }
730
731 #[allow(clippy::too_many_arguments)]
751 pub async fn load_revision(
752 pack_refs: &[RevisionPackRef],
753 config: Arc<HostConfig>,
754 mocks: Option<Arc<MockLayer>>,
755 wasi_policy: Arc<RunnerWasiPolicy>,
756 session_host: Arc<dyn SessionHost>,
757 session_store: DynSessionStore,
758 state_store: DynStateStore,
759 state_host: Arc<dyn StateHost>,
760 secrets_manager: DynSecretsManager,
761 deployment_id: DeploymentId,
762 bundle_id: BundleId,
763 revision_id: RevisionId,
764 customer_id: Option<String>,
765 runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
766 runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
767 runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
768 ) -> Result<Arc<Self>> {
769 Self::load_revision_impl(
770 pack_refs,
771 config,
772 mocks,
773 wasi_policy,
774 session_host,
775 session_store,
776 state_store,
777 state_host,
778 secrets_manager,
779 deployment_id,
780 bundle_id,
781 revision_id,
782 customer_id,
783 runtime_configs_by_pack_id,
784 runtime_refs_by_pack_id,
785 runtime_ref_resolver,
786 #[cfg(feature = "agentic-worker")]
787 None,
788 None,
789 None,
790 #[cfg(feature = "agentic-worker")]
791 None,
792 #[cfg(feature = "agentic-worker")]
793 None,
794 #[cfg(feature = "agentic-worker")]
795 None,
796 )
797 .await
798 }
799
800 pub async fn load_revision_with(
844 args: RevisionLoad<'_>,
845 options: RevisionHostOptions,
846 ) -> Result<Arc<Self>> {
847 Self::load_revision_impl(
848 args.pack_refs,
849 args.config,
850 args.mocks,
851 args.wasi_policy,
852 args.session_host,
853 args.session_store,
854 args.state_store,
855 args.state_host,
856 args.secrets_manager,
857 args.deployment_id,
858 args.bundle_id,
859 args.revision_id,
860 args.customer_id,
861 args.runtime_configs_by_pack_id,
862 args.runtime_refs_by_pack_id,
863 args.runtime_ref_resolver,
864 #[cfg(feature = "agentic-worker")]
865 options.billing_meter,
866 options.run_outcome_sink,
867 options.approval_inbox,
868 #[cfg(feature = "agentic-worker")]
869 options.user_ledger,
870 #[cfg(feature = "agentic-worker")]
871 options.artifact_reader,
872 #[cfg(feature = "agentic-worker")]
873 options.ext_artifact_port,
874 )
875 .await
876 }
877
878 #[allow(clippy::too_many_arguments)]
879 async fn load_revision_impl(
880 pack_refs: &[RevisionPackRef],
881 config: Arc<HostConfig>,
882 mocks: Option<Arc<MockLayer>>,
883 wasi_policy: Arc<RunnerWasiPolicy>,
884 session_host: Arc<dyn SessionHost>,
885 session_store: DynSessionStore,
886 state_store: DynStateStore,
887 state_host: Arc<dyn StateHost>,
888 secrets_manager: DynSecretsManager,
889 deployment_id: DeploymentId,
890 bundle_id: BundleId,
891 revision_id: RevisionId,
892 customer_id: Option<String>,
893 runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
894 runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
895 runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
896 #[cfg(feature = "agentic-worker")] billing_meter: Option<
897 Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
898 >,
899 run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
900 approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
901 #[cfg(feature = "agentic-worker")] user_ledger: Option<
902 greentic_aw_runtime::user_ledger::UserLedgerTarget,
903 >,
904 #[cfg(feature = "agentic-worker")] artifact_reader: Option<crate::host::ArtifactReaderPort>,
905 #[cfg(feature = "agentic-worker")] ext_artifact_port: Option<crate::host::ExtArtifactPort>,
906 ) -> Result<Arc<Self>> {
907 if pack_refs.is_empty() {
908 bail!(
909 "revision runtime for tenant {} requires at least one pack",
910 config.tenant
911 );
912 }
913 let mut packs = Vec::with_capacity(pack_refs.len());
914 let mut seen_pack_ids = HashSet::with_capacity(pack_refs.len());
915 for pack_ref in pack_refs {
916 let expected = PackDigest::parse(&pack_ref.digest).with_context(|| {
917 format!(
918 "revision pack `{}` has an invalid digest `{}`",
919 pack_ref.path.display(),
920 pack_ref.digest
921 )
922 })?;
923 if expected.algorithm() != "sha256" {
927 bail!(
928 "revision pack `{}` pins unsupported digest algorithm `{}`; only sha256 is supported",
929 pack_ref.path.display(),
930 expected.algorithm()
931 );
932 }
933 if !expected.matches_file(&pack_ref.path).with_context(|| {
934 format!(
935 "hashing revision pack `{}` for digest verification",
936 pack_ref.path.display()
937 )
938 })? {
939 bail!(
940 "revision pack `{}` does not match pinned digest `{}`",
941 pack_ref.path.display(),
942 pack_ref.digest
943 );
944 }
945 let pack = Self::load_pack_runtime(
946 &pack_ref.path,
947 &config,
948 mocks.clone(),
949 None,
950 &wasi_policy,
951 &session_store,
952 &state_store,
953 &secrets_manager,
954 runtime_configs_by_pack_id,
955 runtime_refs_by_pack_id,
956 runtime_ref_resolver.as_ref(),
957 Some(bundle_id.as_str()),
962 )
963 .await?;
964 let pack_id = pack.metadata().pack_id.clone();
968 if !seen_pack_ids.insert(pack_id.clone()) {
969 bail!(
970 "revision for tenant {} contains duplicate pack_id `{}` (path `{}`)",
971 config.tenant,
972 pack_id,
973 pack_ref.path.display(),
974 );
975 }
976 packs.push((pack, Some(expected.raw_string())));
977 }
978 let rollout = RolloutIds {
979 customer_id,
980 deployment_id: Some(deployment_id.to_string()),
981 bundle_id: Some(bundle_id.as_str().to_string()),
982 revision_id: Some(revision_id.to_string()),
983 };
984 Self::from_packs_with_rollout(
985 config,
986 packs,
987 mocks,
988 session_host,
989 session_store,
990 state_store,
991 state_host,
992 secrets_manager,
993 #[cfg(feature = "agentic-worker")]
999 None,
1000 #[cfg(feature = "agentic-worker")]
1001 None,
1002 #[cfg(feature = "agentic-worker")]
1004 artifact_reader,
1005 #[cfg(feature = "agentic-worker")]
1006 ext_artifact_port,
1007 #[cfg(feature = "agentic-worker")]
1008 None,
1009 rollout,
1010 #[cfg(feature = "agentic-worker")]
1011 billing_meter,
1012 run_outcome_sink,
1013 approval_inbox,
1014 #[cfg(feature = "agentic-worker")]
1015 user_ledger,
1016 )
1017 .await
1018 }
1019
1020 #[allow(clippy::too_many_arguments)]
1044 async fn load_pack_runtime(
1045 pack_path: &Path,
1046 config: &Arc<HostConfig>,
1047 mocks: Option<Arc<MockLayer>>,
1048 archive_source: Option<&Path>,
1049 wasi_policy: &Arc<RunnerWasiPolicy>,
1050 session_store: &DynSessionStore,
1051 state_store: &DynStateStore,
1052 secrets_manager: &DynSecretsManager,
1053 runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
1054 runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
1055 runtime_ref_resolver: Option<&Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
1056 unit_id: Option<&str>,
1057 ) -> Result<Arc<PackRuntime>> {
1058 let oauth_config = config.oauth_broker_config();
1059 let mut pack = PackRuntime::load(
1060 pack_path,
1061 Arc::clone(config),
1062 mocks,
1063 archive_source,
1064 Some(Arc::clone(session_store)),
1065 Some(Arc::clone(state_store)),
1066 Arc::clone(wasi_policy),
1067 Arc::clone(secrets_manager),
1068 oauth_config,
1069 true,
1070 ComponentResolution::default(),
1071 )
1072 .await
1073 .with_context(|| {
1074 format!(
1075 "failed to load pack {} for tenant {}",
1076 pack_path.display(),
1077 config.tenant
1078 )
1079 })?;
1080 let pack_id = pack.metadata().pack_id.clone();
1081 if let Some(non_secret) = runtime_configs_by_pack_id.get(pack_id.as_str()) {
1082 pack.set_runtime_config_non_secret(Some(Arc::clone(non_secret)));
1083 }
1084 pack.set_unit_id(unit_id.map(str::to_string));
1085 if let Some(refs) = runtime_refs_by_pack_id.get(pack_id.as_str()) {
1086 let resolver = runtime_ref_resolver.ok_or_else(|| {
1087 anyhow!(
1088 "pack `{}` has runtime_refs bound but no RuntimeRefResolver was provided",
1089 pack_id,
1090 )
1091 })?;
1092 pack.set_runtime_refs(Some(crate::runtime_refs::RuntimeRefsInjection {
1093 refs: Arc::clone(refs),
1094 resolver: Arc::clone(resolver),
1095 }));
1096 }
1097 Ok(Arc::new(pack))
1098 }
1099
1100 #[allow(clippy::too_many_arguments)]
1101 pub async fn from_packs(
1102 config: Arc<HostConfig>,
1103 packs: Vec<(Arc<PackRuntime>, Option<String>)>,
1104 mocks: Option<Arc<MockLayer>>,
1105 session_host: Arc<dyn SessionHost>,
1106 session_store: DynSessionStore,
1107 state_store: DynStateStore,
1108 state_host: Arc<dyn StateHost>,
1109 secrets_manager: DynSecretsManager,
1110 #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
1111 #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
1112 #[cfg(feature = "agentic-worker")] stream_observers: Option<
1113 crate::http::agent_stream::StreamObserverRegistry,
1114 >,
1115 ) -> Result<Arc<Self>> {
1116 Self::from_packs_with_artifact_reader(
1117 config,
1118 packs,
1119 mocks,
1120 session_host,
1121 session_store,
1122 state_store,
1123 state_host,
1124 secrets_manager,
1125 #[cfg(feature = "agentic-worker")]
1126 ext_llm_port,
1127 #[cfg(feature = "agentic-worker")]
1128 mcp_source,
1129 #[cfg(feature = "agentic-worker")]
1131 None,
1132 #[cfg(feature = "agentic-worker")]
1133 None,
1134 #[cfg(feature = "agentic-worker")]
1135 stream_observers,
1136 )
1137 .await
1138 }
1139
1140 #[allow(clippy::too_many_arguments)]
1142 pub(crate) async fn from_packs_with_artifact_reader(
1143 config: Arc<HostConfig>,
1144 packs: Vec<(Arc<PackRuntime>, Option<String>)>,
1145 mocks: Option<Arc<MockLayer>>,
1146 session_host: Arc<dyn SessionHost>,
1147 session_store: DynSessionStore,
1148 state_store: DynStateStore,
1149 state_host: Arc<dyn StateHost>,
1150 secrets_manager: DynSecretsManager,
1151 #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
1152 #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
1153 #[cfg(feature = "agentic-worker")] artifact_reader: Option<crate::host::ArtifactReaderPort>,
1154 #[cfg(feature = "agentic-worker")] ext_artifact_port: Option<crate::host::ExtArtifactPort>,
1155 #[cfg(feature = "agentic-worker")] stream_observers: Option<
1156 crate::http::agent_stream::StreamObserverRegistry,
1157 >,
1158 ) -> Result<Arc<Self>> {
1159 Self::from_packs_with_rollout(
1160 config,
1161 packs,
1162 mocks,
1163 session_host,
1164 session_store,
1165 state_store,
1166 state_host,
1167 secrets_manager,
1168 #[cfg(feature = "agentic-worker")]
1169 ext_llm_port,
1170 #[cfg(feature = "agentic-worker")]
1171 mcp_source,
1172 #[cfg(feature = "agentic-worker")]
1173 artifact_reader,
1174 #[cfg(feature = "agentic-worker")]
1175 ext_artifact_port,
1176 #[cfg(feature = "agentic-worker")]
1177 stream_observers,
1178 RolloutIds::default(),
1179 #[cfg(feature = "agentic-worker")]
1182 None,
1183 None,
1184 None,
1185 #[cfg(feature = "agentic-worker")]
1187 None,
1188 )
1189 .await
1190 }
1191
1192 #[allow(clippy::too_many_arguments)]
1197 pub(crate) async fn from_packs_with_rollout(
1198 config: Arc<HostConfig>,
1199 packs: Vec<(Arc<PackRuntime>, Option<String>)>,
1200 mocks: Option<Arc<MockLayer>>,
1201 session_host: Arc<dyn SessionHost>,
1202 session_store: DynSessionStore,
1203 _state_store: DynStateStore,
1204 state_host: Arc<dyn StateHost>,
1205 secrets_manager: DynSecretsManager,
1206 #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
1207 #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
1208 #[cfg(feature = "agentic-worker")] artifact_reader: Option<crate::host::ArtifactReaderPort>,
1209 #[cfg(feature = "agentic-worker")] ext_artifact_port: Option<crate::host::ExtArtifactPort>,
1210 #[cfg(feature = "agentic-worker")] stream_observers: Option<
1211 crate::http::agent_stream::StreamObserverRegistry,
1212 >,
1213 rollout: RolloutIds,
1214 #[cfg(feature = "agentic-worker")] installed_billing_meter: Option<
1215 Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
1216 >,
1217 run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
1218 approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
1219 #[cfg(feature = "agentic-worker")] user_ledger: Option<
1220 greentic_aw_runtime::user_ledger::UserLedgerTarget,
1221 >,
1222 ) -> Result<Arc<Self>> {
1223 let operator_registry = OperatorRegistry::build(&packs)?;
1224 let operator_metrics = Arc::new(OperatorMetrics::default());
1225 let pack_runtimes = packs
1226 .iter()
1227 .map(|(pack, _)| Arc::clone(pack))
1228 .collect::<Vec<_>>();
1229 let digests = packs
1230 .iter()
1231 .map(|(_, digest)| digest.clone())
1232 .collect::<Vec<_>>();
1233 let mut pack_trace = HashMap::new();
1234 for (pack, digest) in &packs {
1235 let pack_id = pack.metadata().pack_id.clone();
1236 let pack_ref = config
1237 .pack_bindings
1238 .iter()
1239 .find(|binding| binding.pack_id == pack_id)
1240 .map(|binding| binding.pack_ref.clone())
1241 .unwrap_or_else(|| pack_id.clone());
1242 pack_trace.insert(
1243 pack_id,
1244 PackTraceInfo {
1245 pack_ref,
1246 resolved_digest: digest.clone(),
1247 },
1248 );
1249 }
1250 #[cfg(feature = "agentic-worker")]
1258 let agent_project_id = rollout.bundle_id.clone();
1259 let engine = FlowEngine::new(pack_runtimes.clone(), Arc::clone(&config))
1260 .await
1261 .context("failed to prime flow engine")?
1262 .with_rollout_ids(rollout);
1263 #[cfg(feature = "agentic-worker")]
1267 let engine = engine.with_mcp_source(mcp_source);
1268 #[cfg(feature = "agentic-worker")]
1276 let engine = engine.with_mcp_secrets(Some(Arc::clone(&secrets_manager)));
1277 #[cfg_attr(not(feature = "agentic-worker"), allow(unused_mut))]
1278 let mut engine = engine;
1279
1280 let dispatch_nats_client = match std::env::var("GREENTIC_EVENTS_NATS_URL") {
1297 Ok(nats_url) => match async_nats::connect(&nats_url).await {
1298 Ok(client) => {
1299 engine.set_remote_dispatch_handler(Arc::new(
1300 crate::runner::remote_dispatch::NatsDispatcher::new(client.clone()),
1301 ));
1302 Some(client)
1303 }
1304 Err(error) => {
1305 tracing::warn!(
1306 %error,
1307 "GREENTIC_EVENTS_NATS_URL set but NATS connect failed; sorla.call disabled"
1308 );
1309 None
1310 }
1311 },
1312 Err(_) => None,
1313 };
1314
1315 if approval_inbox.is_some() && dispatch_nats_client.is_some() {
1320 tracing::info!(
1321 "GREENTIC_EVENTS_NATS_URL connected; approvals go over NATS and the HTTP approval inbox is not installed"
1322 );
1323 }
1324 let approval_inbox = crate::runner::approval_http::inbox_to_install(
1325 dispatch_nats_client.is_some(),
1326 approval_inbox,
1327 )
1328 .and_then(
1329 |target| match crate::runner::approval_http::HttpApprovalDispatcher::new(target) {
1330 Ok(inbox) => {
1331 engine.set_approval_dispatch_handler(Arc::new(inbox.clone()));
1332 tracing::info!("HTTP approval inbox wired into runtime: approval.call");
1333 Some(inbox)
1334 }
1335 Err(error) => {
1336 tracing::warn!(
1337 %error,
1338 "HTTP approval inbox not installed; approval.call needing a human will fail"
1339 );
1340 None
1341 }
1342 },
1343 );
1344
1345 let audit_nats_client = dispatch_nats_client.clone();
1354
1355 #[cfg(feature = "agentic-worker")]
1358 let mut nested_agent_handler: Option<
1359 Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
1360 > = None;
1361
1362 #[cfg(feature = "agentic-worker")]
1363 {
1364 use crate::runner::agent_node::{
1365 agent_configs_from_manifest, merge_agent_sources, merge_sidecar_into,
1366 };
1367 use std::collections::HashMap;
1368
1369 let mut pack_agents: HashMap<String, greentic_aw_runtime::AgentConfig> = HashMap::new();
1374 for pack in &pack_runtimes {
1375 let mut blobs = pack.manifest_agent_blobs();
1376 merge_sidecar_into(&mut blobs, pack.dw_agents_sidecar_blobs());
1380 if blobs.is_empty() {
1381 continue;
1382 }
1383 let pack_id = pack.metadata().pack_id.clone();
1384 let configs = agent_configs_from_manifest(&pack_id, &blobs);
1385 for (agent_id, agent_config) in configs {
1386 if let Some(existing) = pack_agents.get(&agent_id) {
1387 tracing::warn!(
1388 agent_id,
1389 prior_pack = existing.agent_id.as_str(),
1390 new_pack = pack_id.as_str(),
1391 "agent_id collision across packs; last pack wins"
1392 );
1393 }
1394 pack_agents.insert(agent_id, agent_config);
1395 }
1396 }
1397
1398 let merged_agents = merge_agent_sources(pack_agents, config.agents.clone());
1400
1401 engine.set_ext_artifact_port(ext_artifact_port.clone());
1404
1405 crate::runner::runtime_ext::ingest_all_corpora(&pack_runtimes, &config.tenant_ctx())
1414 .await;
1415
1416 let redis_set = std::env::var("GREENTIC_AW_REDIS_URL")
1427 .map(|v| !v.is_empty())
1428 .unwrap_or(false);
1429 let agent_audit_sink = audit_nats_client
1435 .clone()
1436 .map(crate::trace::audit_sink::AuditSink::new);
1437 let graph_agents = merged_agents.clone();
1442 #[cfg(feature = "operala-in-process")]
1447 let operala_agents = merged_agents.clone();
1448 let billing_meter =
1453 crate::runner::agent_node::resolve_billing_meter(installed_billing_meter);
1454 let agent_handler = if redis_set {
1455 crate::runner::agent_node::build_agent_node_wiring_metered(
1456 merged_agents,
1457 config.tenant.clone(),
1458 Arc::clone(&secrets_manager),
1459 ext_llm_port.clone(),
1460 pack_runtimes.clone(),
1461 agent_audit_sink.clone(),
1462 stream_observers.clone(),
1463 agent_project_id.clone(),
1464 billing_meter.clone(),
1465 user_ledger.clone(),
1466 artifact_reader.clone(),
1467 ext_artifact_port.clone(),
1468 )
1469 .await
1470 } else {
1471 #[cfg(feature = "desktop-agent-ephemeral")]
1472 {
1473 crate::runner::agent_node::build_agent_node_wiring_ephemeral_metered(
1474 merged_agents,
1475 config.tenant.clone(),
1476 Arc::clone(&secrets_manager),
1477 ext_llm_port.clone(),
1478 pack_runtimes.clone(),
1479 agent_audit_sink.clone(),
1480 stream_observers.clone(),
1481 agent_project_id.clone(),
1482 billing_meter.clone(),
1483 user_ledger.clone(),
1484 artifact_reader.clone(),
1485 ext_artifact_port.clone(),
1486 )
1487 .await
1488 }
1489 #[cfg(not(feature = "desktop-agent-ephemeral"))]
1490 {
1491 crate::runner::agent_node::build_agent_node_wiring_metered(
1492 merged_agents,
1493 config.tenant.clone(),
1494 Arc::clone(&secrets_manager),
1495 ext_llm_port.clone(),
1496 pack_runtimes.clone(),
1497 agent_audit_sink.clone(),
1498 stream_observers.clone(),
1499 agent_project_id.clone(),
1500 billing_meter.clone(),
1501 user_ledger.clone(),
1502 artifact_reader.clone(),
1503 ext_artifact_port.clone(),
1504 )
1505 .await
1506 }
1507 };
1508 #[cfg(feature = "operala-in-process")]
1511 let operala_agent_runtime = agent_handler
1512 .as_ref()
1513 .map(|wiring| Arc::clone(&wiring.runtime));
1514 if let Some(wiring) = agent_handler {
1515 nested_agent_handler = Some(Arc::clone(&wiring.handler));
1516 engine.set_agent_node_handler(wiring.handler);
1517 tracing::info!("DwAgent runtime wired into FlowEngine");
1518 }
1519
1520 #[cfg(feature = "operala-in-process")]
1534 {
1535 use crate::runner::operala_node::{
1536 OPERALA_DISPATCH_ENV, OperalaSelection, select_operala_handler_metered,
1537 };
1538 use crate::runner::operala_tools::OperalaToolContext;
1539
1540 let operala_tools = match operala_agent_runtime {
1548 Some(runtime) => Some(Arc::new(OperalaToolContext::new(
1549 runtime,
1550 &operala_agents,
1551 agent_project_id.clone(),
1552 ))),
1553 None => {
1554 if operala_agents.values().any(|agent| !agent.tools.is_empty()) {
1555 tracing::warn!(
1556 tenant = %config.tenant,
1557 "no agent runtime was built for this tenant (dw.agent is \
1558 unwired too: GREENTIC_AW_STATE_BACKEND=redis without \
1559 GREENTIC_AW_REDIS_URL, Redis unreachable, or the extension \
1560 runtime failed; see the earlier log lines); operala.call deep \
1561 workers will run WITHOUT the tools their agents declare"
1562 );
1563 }
1564 None
1565 }
1566 };
1567
1568 let agent_llm = operala_agents
1580 .values()
1581 .map(|agent| &agent.llm)
1582 .find(|llm| !llm.provider.trim().is_empty() && !llm.model.trim().is_empty());
1583 let fallback_provider = std::env::var("GREENTIC_LLM_PROVIDER")
1584 .ok()
1585 .filter(|value| !value.trim().is_empty())
1586 .or_else(|| agent_llm.map(|llm| llm.provider.clone()));
1587 let fallback_model = std::env::var("GREENTIC_LLM_MODEL")
1588 .ok()
1589 .filter(|value| !value.trim().is_empty())
1590 .or_else(|| agent_llm.map(|llm| llm.model.clone()));
1591 let base_url = std::env::var("GREENTIC_LLM_BASE_URL")
1592 .ok()
1593 .filter(|value| !value.trim().is_empty());
1594
1595 let key_secrets = &secrets_manager;
1599 let key_tenant = config.tenant.as_str();
1600 let key_agents = &operala_agents;
1601 let resolve_key = move || async move {
1602 let env_key = std::env::var("GREENTIC_LLM_API_KEY")
1603 .ok()
1604 .filter(|value| !value.trim().is_empty())
1605 .or_else(|| {
1606 std::env::var("OPENAI_API_KEY")
1607 .ok()
1608 .filter(|value| !value.trim().is_empty())
1609 });
1610 match env_key {
1611 Some(key) => Some(key),
1612 None => {
1613 crate::runner::agent_node::resolve_in_process_llm_key(
1614 key_secrets,
1615 key_tenant,
1616 key_agents,
1617 )
1618 .await
1619 }
1620 }
1621 };
1622
1623 let dispatch_env = std::env::var(OPERALA_DISPATCH_ENV).ok();
1624 match select_operala_handler_metered(
1625 dispatch_env.as_deref(),
1626 resolve_key,
1627 base_url,
1628 fallback_provider,
1629 fallback_model,
1630 operala_tools,
1631 billing_meter.clone(),
1634 agent_project_id.clone(),
1635 )
1636 .await
1637 {
1638 OperalaSelection::InProcess(handler) => {
1639 engine.set_operala_node_handler(handler);
1640 tracing::info!(
1641 dispatch = "in-process",
1642 "operala.call in-process deep-worker runtime wired into FlowEngine \
1643 (provider/model resolved per-worker from node input.llm)"
1644 );
1645 }
1646 OperalaSelection::Nats => {
1647 tracing::info!(
1648 dispatch = "nats",
1649 "GREENTIC_OPERALA_DISPATCH=nats: operala.call dispatches over NATS; \
1650 in-process deep-worker handler not wired"
1651 );
1652 if std::env::var("GREENTIC_EVENTS_NATS_URL")
1653 .ok()
1654 .filter(|value| !value.trim().is_empty())
1655 .is_none()
1656 {
1657 tracing::warn!(
1658 "GREENTIC_OPERALA_DISPATCH=nats but GREENTIC_EVENTS_NATS_URL is \
1659 unset; operala.call nodes will fail (no remote dispatch \
1660 handler). Set the NATS URL or unset the flag."
1661 );
1662 }
1663 }
1664 OperalaSelection::NoKey => {
1665 tracing::warn!(
1666 dispatch = "nats",
1667 "no LLM API key resolved (env or store) for operala.call \
1668 in-process wiring; operala.call nodes will fall back to NATS \
1669 (and fail without it)"
1670 );
1671 }
1672 }
1673 }
1674
1675 let mut graphs: HashMap<String, greentic_aw_runtime::graph::GraphConfig> =
1683 HashMap::new();
1684 for pack in &pack_runtimes {
1685 let Some(bytes) = pack.read_agent_graph_sidecar() else {
1686 continue;
1687 };
1688 let pack_id = pack.metadata().pack_id.clone();
1689 if let Some(config) =
1690 crate::runner::graph_node::graph_config_from_sidecar(&pack_id, &bytes)
1691 && graphs.insert(pack_id.clone(), config).is_some()
1692 {
1693 tracing::warn!(
1694 pack_id = pack_id.as_str(),
1695 "agent-graph sidecar for pack_id seen twice; last pack wins"
1696 );
1697 }
1698 }
1699
1700 for (graph_id, graph_config) in config.graphs.clone() {
1704 graphs.insert(graph_id, graph_config);
1705 }
1706
1707 if let Some(handler) = crate::runner::graph_node::build_graph_node_handler_metered(
1712 graphs,
1713 agent_audit_sink.clone(),
1714 Arc::new(pack_runtimes.clone()),
1715 graph_agents,
1716 config.tenant.clone(),
1717 Arc::clone(&secrets_manager),
1718 agent_project_id.clone(),
1719 billing_meter.clone(),
1720 )
1721 .await
1722 {
1723 engine.set_graph_node_handler(handler);
1724 tracing::info!("DwAgentGraph runtime wired into FlowEngine");
1725 }
1726 }
1727
1728 #[cfg(feature = "agentic-worker")]
1732 {
1733 let dw_dispatch =
1734 crate::runner::agent_node::dw_agent_dispatch_mode(|k| std::env::var(k).ok());
1735 engine.set_dw_agent_dispatch(dw_dispatch);
1736 if let Some(handlers) =
1744 crate::runner::nested_flow::for_dispatch(dw_dispatch, nested_agent_handler.as_ref())
1745 {
1746 if crate::runner::nested_flow::nested_flow_agents_enabled() {
1747 for pack in &pack_runtimes {
1748 pack.set_nested_flow_handlers(handlers.clone());
1749 }
1750 tracing::info!("dw.agent handler lent to flow-tool engines");
1751 } else {
1752 tracing::info!(
1753 env = crate::runner::nested_flow::NESTED_FLOW_AGENTS_ENV,
1754 "dw.agent handler not lent to flow-tool engines (opted out)"
1755 );
1756 }
1757 }
1758 if matches!(
1759 dw_dispatch,
1760 crate::runner::agent_node::DwAgentDispatch::Nats
1761 ) && std::env::var("GREENTIC_EVENTS_NATS_URL")
1762 .ok()
1763 .filter(|s| !s.is_empty())
1764 .is_none()
1765 {
1766 tracing::warn!(
1767 "GREENTIC_AW_DISPATCH=nats but GREENTIC_EVENTS_NATS_URL is unset; \
1768 dw.agent nodes will fail (no remote dispatch handler). \
1769 Set the NATS URL or unset the flag."
1770 );
1771 }
1772 }
1773
1774 let engine = Arc::new(engine);
1775 let state_machine = Arc::new(
1776 StateMachineRuntime::from_flow_engine_with_run_outcome_sink(
1777 Arc::clone(&config),
1778 Arc::clone(&engine),
1779 pack_trace,
1780 session_host,
1781 Arc::clone(&session_store),
1782 state_host,
1783 Arc::clone(&secrets_manager),
1784 mocks.clone(),
1785 audit_nats_client,
1786 run_outcome_sink,
1787 )
1788 .context("failed to initialise state machine runtime")?,
1789 );
1790
1791 if let Some(inbox) = &approval_inbox {
1795 inbox.attach_resumer(Arc::new(
1796 crate::runner::runtime_session_resumer::RuntimeSessionResumer::strict(Arc::clone(
1797 &state_machine,
1798 )),
1799 ));
1800 }
1801
1802 let http_guard = crate::http_guard::HttpGuard::from_env();
1812 let http_client = Client::builder()
1813 .dns_resolver(Arc::new(crate::http_guard::GuardedResolver {
1814 guard: http_guard,
1815 }))
1816 .redirect(crate::http_guard::redirect_policy(http_guard))
1817 .build()?;
1818
1819 let mut background_handles: Vec<JoinHandle<()>> = Vec::new();
1828 if let Some(client) = dispatch_nats_client {
1829 let resumer = Arc::new(
1830 crate::runner::runtime_session_resumer::RuntimeSessionResumer::new(Arc::clone(
1831 &state_machine,
1832 ))
1833 .with_watchdog_notifier(
1834 crate::runner::dispatch_listener::nats_watchdog_notifier(
1835 client.clone(),
1836 config.tenant.clone(),
1837 ),
1838 ),
1839 );
1840 background_handles.push(spawn_listener_logged(
1841 "watchdog-cancel",
1842 crate::runner::dispatch_listener::run_watchdog_cancel_listener(
1843 client.clone(),
1844 config.tenant.clone(),
1845 crate::runner::dispatch_listener::process_cancel_origin().to_string(),
1846 ),
1847 ));
1848 for runtime_name in ["sorla", "operala", "agentic", "telco-x", "approval"] {
1849 let scope = crate::runner::dispatch_listener::ListenerScope {
1853 queue_group: Some(format!("runner-{}-{runtime_name}", config.tenant)),
1854 tenant: Some(config.tenant.clone()),
1855 };
1856 background_handles.push(spawn_listener_logged(
1857 runtime_name,
1858 crate::runner::dispatch_listener::run_response_listener_scoped(
1859 client.clone(),
1860 runtime_name.to_string(),
1861 Arc::clone(&resumer)
1862 as Arc<dyn crate::runner::dispatch_listener::SessionResumer>,
1863 scope,
1864 ),
1865 ));
1866 }
1867 #[cfg(feature = "agentic-worker")]
1872 background_handles.push(spawn_listener_logged(
1873 "mcp-warm",
1874 crate::runner::mcp_warm_listener::run_mcp_warm_listener(client.clone()),
1875 ));
1876 tracing::info!(
1877 "Remote-dispatch (NATS) wired into runtime: sorla.call / operala.call / agentic.call / telco-x.call"
1878 );
1879 }
1880 Ok(Arc::new(Self {
1881 tenant: config.tenant.clone(),
1882 config,
1883 packs: pack_runtimes,
1884 digests,
1885 engine,
1886 state_machine,
1887 session_store,
1888 http_client,
1889 mocks,
1890 timer_handles: Mutex::new(Vec::new()),
1891 timer_cancel: CancellationToken::new(),
1892 background_handles: Mutex::new(background_handles),
1893 secrets: secrets_manager,
1894 operator_registry,
1895 operator_metrics,
1896 contract_cache: ContractCache::from_env(),
1897 approval_inbox,
1898 }))
1899 }
1900
1901 pub fn tenant(&self) -> &str {
1902 &self.tenant
1903 }
1904
1905 pub fn config(&self) -> &Arc<HostConfig> {
1906 &self.config
1907 }
1908
1909 pub fn operator_registry(&self) -> &OperatorRegistry {
1910 &self.operator_registry
1911 }
1912
1913 pub fn operator_metrics(&self) -> &OperatorMetrics {
1914 &self.operator_metrics
1915 }
1916
1917 pub fn contract_cache(&self) -> &ContractCache {
1918 &self.contract_cache
1919 }
1920
1921 pub fn contract_cache_stats(&self) -> ContractCacheStats {
1922 self.contract_cache.stats()
1923 }
1924
1925 pub fn main_pack(&self) -> &Arc<PackRuntime> {
1926 self.packs
1927 .first()
1928 .expect("tenant runtime must contain at least one pack")
1929 }
1930
1931 pub fn pack(&self) -> Arc<PackRuntime> {
1932 Arc::clone(self.main_pack())
1933 }
1934
1935 pub fn overlays(&self) -> Vec<Arc<PackRuntime>> {
1936 self.packs.iter().skip(1).cloned().collect()
1937 }
1938
1939 pub fn all_packs(&self) -> &[Arc<PackRuntime>] {
1947 &self.packs
1948 }
1949
1950 pub fn pack_digests(&self) -> &[Option<String>] {
1954 &self.digests
1955 }
1956
1957 pub fn engine(&self) -> &Arc<FlowEngine> {
1958 &self.engine
1959 }
1960
1961 pub fn state_machine(&self) -> &Arc<StateMachineRuntime> {
1962 &self.state_machine
1963 }
1964
1965 pub fn session_store(&self) -> &DynSessionStore {
1970 &self.session_store
1971 }
1972
1973 pub fn http_client(&self) -> &Client {
1974 &self.http_client
1975 }
1976
1977 pub fn oauth_config(&self) -> Option<OAuthBrokerConfig> {
1978 self.config.oauth_broker_config()
1979 }
1980
1981 pub fn digest(&self) -> Option<&str> {
1982 self.digests.first().and_then(|d| d.as_deref())
1983 }
1984
1985 pub fn overlay_digests(&self) -> Vec<Option<String>> {
1986 self.digests.iter().skip(1).cloned().collect()
1987 }
1988
1989 pub fn required_secrets(&self) -> Vec<SecretRequirement> {
1990 self.packs
1991 .iter()
1992 .flat_map(|pack| pack.required_secrets().iter().cloned())
1993 .collect()
1994 }
1995
1996 pub fn missing_secrets(&self) -> Vec<SecretRequirement> {
1997 self.packs
1998 .iter()
1999 .flat_map(|pack| pack.missing_secrets(&self.config.tenant_ctx()))
2000 .collect()
2001 }
2002
2003 pub fn mocks(&self) -> Option<&Arc<MockLayer>> {
2004 self.mocks.as_ref()
2005 }
2006
2007 pub fn register_timers(&self, handles: Vec<JoinHandle<()>>) {
2008 self.timer_handles.lock().extend(handles);
2009 }
2010
2011 pub(crate) fn timer_cancel_token(&self) -> CancellationToken {
2013 self.timer_cancel.clone()
2014 }
2015
2016 pub fn abort_timers(&self) {
2026 self.timer_cancel.cancel();
2027 self.timer_handles.lock().clear();
2028 }
2029
2030 #[cfg(test)]
2031 pub(crate) fn timer_count(&self) -> usize {
2032 self.timer_handles.lock().len()
2033 }
2034
2035 pub fn get_secret(&self, key: &str) -> Result<String> {
2047 if crate::provider_core_only::is_enabled() {
2048 bail!(crate::provider_core_only::blocked_message("secrets"))
2049 }
2050 if !self.config.secrets_policy.is_allowed(key) {
2051 bail!("secret {key} is not permitted by bindings policy");
2052 }
2053 let ctx = self.config.tenant_ctx();
2054 let canonical_key = canonicalize_secret_key(key);
2055 let bytes =
2056 read_secret_blocking(&self.secrets, &ctx, RUNTIME_SECRETS_PACK_ID, &canonical_key)
2057 .context("failed to read secret from manager")?;
2058 let value = String::from_utf8(bytes).context("secret value is not valid UTF-8")?;
2059 Ok(value)
2060 }
2061
2062 pub fn build_events_email_execution_plan(
2063 &self,
2064 tenant: &greentic_types::TenantCtx,
2065 request: &EmailSendRequest,
2066 ) -> Result<EmailExecutionPlan> {
2067 let oauth = self
2068 .oauth_config()
2069 .ok_or_else(|| anyhow!("oauth broker config is not configured for tenant runtime"))?;
2070 build_email_execution_plan(&oauth, tenant, request)
2071 }
2072
2073 pub async fn execute_events_email_request(
2074 &self,
2075 access_token: &str,
2076 request: &EmailSendRequest,
2077 ) -> Result<()> {
2078 execute_email_request(self.http_client(), access_token, request).await
2079 }
2080
2081 pub async fn execute_events_email_with_oauth(
2082 &self,
2083 tenant: &greentic_types::TenantCtx,
2084 request: &EmailSendRequest,
2085 ) -> Result<()> {
2086 let plan = self.build_events_email_execution_plan(tenant, request)?;
2087 let shared_secret = self.oauth_config().and_then(|c| c.shared_secret);
2090 let token = request_resource_token_with_auth(
2091 self.http_client(),
2092 &plan.token_request,
2093 shared_secret.as_deref(),
2094 )
2095 .await?;
2096 self.execute_events_email_request(&token.access_token, request)
2097 .await
2098 }
2099
2100 pub fn pack_for_component(&self, component_ref: &str) -> Option<Arc<PackRuntime>> {
2101 self.packs
2102 .iter()
2103 .find(|pack| pack.contains_component(component_ref))
2104 .cloned()
2105 }
2106
2107 pub fn pack_for_component_with_digest(
2108 &self,
2109 component_ref: &str,
2110 ) -> Option<(Arc<PackRuntime>, Option<String>)> {
2111 self.packs
2112 .iter()
2113 .zip(self.digests.iter())
2114 .find(|(pack, _)| pack.contains_component(component_ref))
2115 .map(|(pack, digest)| (Arc::clone(pack), digest.clone()))
2116 }
2117
2118 pub fn resolve_component(&self, component_ref: &str) -> Option<ResolvedComponent> {
2119 self.pack_for_component_with_digest(component_ref)
2120 .map(|(pack, digest)| ResolvedComponent {
2121 digest: digest
2122 .or_else(|| self.digest().map(ToString::to_string))
2123 .unwrap_or_else(|| "unknown".to_string()),
2124 component_ref: component_ref.to_string(),
2125 pack,
2126 })
2127 }
2128}
2129
2130fn spawn_listener_logged<F>(name: &'static str, listener: F) -> JoinHandle<()>
2134where
2135 F: Future<Output = Result<()>> + Send + 'static,
2136{
2137 tokio::spawn(async move {
2138 if let Err(error) = listener.await {
2139 tracing::warn!(listener = name, %error, "background listener stopped");
2140 }
2141 })
2142}
2143
2144impl Drop for TenantRuntime {
2145 fn drop(&mut self) {
2146 self.timer_cancel.cancel();
2149 self.timer_handles.lock().clear();
2150 for handle in self.background_handles.lock().drain(..) {
2151 handle.abort();
2152 }
2153 if let Some(inbox) = &self.approval_inbox {
2154 inbox.shutdown();
2155 }
2156 }
2157}
2158
2159#[cfg(test)]
2160mod timer_retirement_tests {
2161 use super::*;
2162
2163 const CRON: &str = r#"[{ flow_id: "flow.main", cron: "0 0 1 1 *" }]"#;
2164
2165 async fn runtime_with_timers() -> (impl Sized, Arc<TenantRuntime>) {
2166 let (workspace, runtime) = crate::test_support::build_test_runtime_with_timers(CRON)
2167 .await
2168 .expect("runtime");
2169 let timers = crate::runner::adapt_timer::spawn_timers(Arc::clone(&runtime)).expect("spawn");
2170 runtime.register_timers(timers);
2171 (workspace, runtime)
2172 }
2173
2174 #[tokio::test]
2175 async fn insert_pack_stops_the_timers_of_the_runtime_it_replaces() {
2176 let (_w1, old) = runtime_with_timers().await;
2177 let (_w2, new) = runtime_with_timers().await;
2178 let active = ActivePacks::new();
2179 active.insert_pack("demo", Arc::clone(&old));
2180 assert!(!old.timer_cancel_token().is_cancelled());
2181
2182 active.insert_pack("demo", Arc::clone(&new));
2183 assert!(
2184 old.timer_cancel_token().is_cancelled(),
2185 "the replaced runtime must stop firing"
2186 );
2187 assert!(
2188 !new.timer_cancel_token().is_cancelled(),
2189 "the replacement keeps its timers"
2190 );
2191 }
2192
2193 #[tokio::test]
2194 async fn re_inserting_the_same_runtime_keeps_its_timers() {
2195 let (_w, runtime) = runtime_with_timers().await;
2196 let active = ActivePacks::new();
2197 active.insert_pack("demo", Arc::clone(&runtime));
2198 active.insert_pack("demo", Arc::clone(&runtime));
2199 assert!(!runtime.timer_cancel_token().is_cancelled());
2200 }
2201
2202 #[tokio::test]
2203 async fn remove_revision_stops_the_timers_of_the_removed_runtime() {
2204 let (_w, runtime) = runtime_with_timers().await;
2205 let (deployment, bundle, revision) = (
2206 DeploymentId::new(),
2207 BundleId::from("bundle-a"),
2208 RevisionId::new(),
2209 );
2210 let active = ActivePacks::new();
2211 let mut map = HashMap::new();
2214 map.insert(
2215 RuntimeKey::revision("demo", deployment, bundle.clone(), revision),
2216 Arc::clone(&runtime),
2217 );
2218 active.replace(map);
2219 let removed = active.remove_revision("demo", deployment, bundle, revision);
2220 assert!(removed.is_some());
2221 assert!(runtime.timer_cancel_token().is_cancelled());
2222 }
2223}
2224
2225#[cfg(test)]
2226mod block_on_tests {
2227 use super::*;
2228
2229 #[test]
2230 fn works_without_a_runtime() {
2231 assert_eq!(block_on(async { 7 }), 7);
2232 }
2233
2234 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2235 async fn does_not_panic_inside_a_multi_thread_runtime() {
2236 assert_eq!(block_on(async { 8 }), 8);
2237 assert_eq!(try_block_on(async { 9 }).ok(), Some(9));
2238 }
2239
2240 #[tokio::test(flavor = "current_thread")]
2241 async fn does_not_panic_inside_a_current_thread_runtime() {
2242 assert_eq!(block_on(async { 10 }), 10);
2243 assert_eq!(try_block_on(async { 11 }).ok(), Some(11));
2244 }
2245}
2246
2247#[cfg(test)]
2248mod runtime_key_tests {
2249 use super::*;
2250
2251 #[test]
2252 fn legacy_keys_match_only_on_tenant() {
2253 assert_eq!(RuntimeKey::legacy("acme"), RuntimeKey::legacy("acme"));
2254 assert_ne!(RuntimeKey::legacy("acme"), RuntimeKey::legacy("other"));
2255 }
2256
2257 #[test]
2258 fn legacy_and_revision_keys_never_collide() {
2259 let key = RuntimeKey::revision(
2260 "acme",
2261 DeploymentId::new(),
2262 BundleId::from("bundle-a"),
2263 RevisionId::new(),
2264 );
2265 assert_ne!(RuntimeKey::legacy("acme"), key);
2266 }
2267
2268 #[test]
2269 fn revision_keys_distinguish_revision_id() {
2270 let deployment = DeploymentId::new();
2271 let bundle = BundleId::from("bundle-a");
2272 let rev_a = RevisionId::new();
2273 let rev_b = RevisionId::new();
2274 let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
2275 let key_b = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_b);
2276 let same = RuntimeKey::revision("acme", deployment, bundle, rev_a);
2277 assert_ne!(key_a, key_b);
2278 assert_eq!(key_a, same);
2279 }
2280
2281 #[test]
2282 fn legacy_reload_preserves_revision_entries() {
2283 let revision_key = RuntimeKey::revision(
2284 "acme",
2285 DeploymentId::new(),
2286 BundleId::from("bundle-a"),
2287 RevisionId::new(),
2288 );
2289 let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2290 prev.insert(RuntimeKey::legacy("acme"), 1); prev.insert(RuntimeKey::legacy("retired"), 2); prev.insert(revision_key.clone(), 99); let mut legacy: HashMap<RuntimeKey, u32> = HashMap::new();
2295 legacy.insert(RuntimeKey::legacy("acme"), 10);
2296 legacy.insert(RuntimeKey::legacy("newcomer"), 20);
2297
2298 let next = merge_legacy_reload(&prev, legacy);
2299
2300 assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&10));
2301 assert_eq!(next.get(&RuntimeKey::legacy("newcomer")), Some(&20));
2302 assert_eq!(next.get(&RuntimeKey::legacy("retired")), None);
2303 assert_eq!(next.get(&revision_key), Some(&99));
2304 }
2305
2306 #[test]
2307 fn remove_keyed_entry_pops_only_the_targeted_key() {
2308 let deployment = DeploymentId::new();
2309 let bundle = BundleId::from("bundle-a");
2310 let rev_a = RevisionId::new();
2311 let rev_b = RevisionId::new();
2312 let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
2313 let key_b = RuntimeKey::revision("acme", deployment, bundle, rev_b);
2314
2315 let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2316 prev.insert(RuntimeKey::legacy("acme"), 1);
2317 prev.insert(key_a.clone(), 10);
2318 prev.insert(key_b.clone(), 20);
2319
2320 let (next, removed) = remove_keyed_entry(&prev, &key_a).expect("present");
2321 assert_eq!(removed, 10);
2322 assert_eq!(next.get(&key_a), None);
2323 assert_eq!(next.get(&key_b), Some(&20));
2324 assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&1));
2325 }
2326
2327 #[test]
2328 fn remove_keyed_entry_returns_none_for_missing_key() {
2329 let prev: HashMap<RuntimeKey, u32> = HashMap::new();
2330 let ghost = RuntimeKey::revision(
2331 "acme",
2332 DeploymentId::new(),
2333 BundleId::from("bundle-a"),
2334 RevisionId::new(),
2335 );
2336 assert!(remove_keyed_entry(&prev, &ghost).is_none());
2337 }
2338
2339 #[test]
2340 fn remove_keyed_entry_leaves_other_deployments_alone() {
2341 let bundle = BundleId::from("bundle-a");
2342 let dep_a = DeploymentId::new();
2343 let dep_b = DeploymentId::new();
2344 let rev = RevisionId::new();
2345 let key_a = RuntimeKey::revision("acme", dep_a, bundle.clone(), rev);
2346 let key_b = RuntimeKey::revision("acme", dep_b, bundle, rev);
2347
2348 let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2349 prev.insert(key_a.clone(), 100);
2350 prev.insert(key_b.clone(), 200);
2351
2352 let (next, removed) = remove_keyed_entry(&prev, &key_a).expect("present");
2353 assert_eq!(removed, 100);
2354 assert_eq!(next.get(&key_b), Some(&200));
2355 assert_eq!(next.len(), 1);
2356 }
2357
2358 #[test]
2359 fn map_lookup_separates_legacy_from_revision() {
2360 let deployment = DeploymentId::new();
2361 let bundle = BundleId::from("bundle-a");
2362 let revision = RevisionId::new();
2363
2364 let mut map: HashMap<RuntimeKey, u32> = HashMap::new();
2365 map.insert(RuntimeKey::legacy("acme"), 1);
2366 map.insert(
2367 RuntimeKey::revision("acme", deployment, bundle.clone(), revision),
2368 2,
2369 );
2370
2371 assert_eq!(map.get(&RuntimeKey::legacy("acme")), Some(&1));
2372 assert_eq!(
2373 map.get(&RuntimeKey::revision("acme", deployment, bundle, revision)),
2374 Some(&2)
2375 );
2376 assert_eq!(map.get(&RuntimeKey::legacy("ghost")), None);
2377 }
2378
2379 #[test]
2380 fn insert_keyed_entry_adds_revision_preserving_legacy_and_siblings() {
2381 let deployment = DeploymentId::new();
2382 let bundle = BundleId::from("bundle-a");
2383 let rev_a = RevisionId::new();
2384 let rev_b = RevisionId::new();
2385 let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
2386 let key_b = RuntimeKey::revision("acme", deployment, bundle, rev_b);
2387
2388 let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2389 prev.insert(RuntimeKey::legacy("acme"), 1);
2390 prev.insert(key_a.clone(), 10);
2391
2392 let next = insert_keyed_entry(&prev, key_b.clone(), 20);
2393
2394 assert_eq!(next.get(&key_b), Some(&20));
2396 assert_eq!(next.get(&key_a), Some(&10));
2397 assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&1));
2398 assert_eq!(next.len(), 3);
2399 }
2400
2401 #[test]
2402 fn insert_keyed_entry_replaces_existing_revision() {
2403 let key = RuntimeKey::revision(
2404 "acme",
2405 DeploymentId::new(),
2406 BundleId::from("bundle-a"),
2407 RevisionId::new(),
2408 );
2409 let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2410 prev.insert(key.clone(), 10);
2411
2412 let next = insert_keyed_entry(&prev, key.clone(), 99);
2413
2414 assert_eq!(next.get(&key), Some(&99));
2415 assert_eq!(next.len(), 1);
2416 }
2417}
2418
2419#[cfg(all(test, feature = "agentic-worker"))]
2420#[path = "runtime_billing_ratchet_tests.rs"]
2421mod runtime_billing_ratchet_tests;