1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
use std::collections::{BTreeMap, HashMap, HashSet};
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{Context, Result, anyhow, bail};
use arc_swap::ArcSwap;
use parking_lot::Mutex;
use reqwest::Client;
use serde_json::Value;
use tokio::runtime::{Handle, Runtime};
use tokio::task::JoinHandle;
use crate::config::HostConfig;
use crate::engine::host::{SessionHost, StateHost};
use crate::engine::runtime::StateMachineRuntime;
use crate::oauth::{OAuthBrokerConfig, request_resource_token};
use crate::operator_metrics::OperatorMetrics;
use crate::operator_registry::OperatorRegistry;
use crate::pack::{ComponentResolution, PackRuntime};
use crate::runner::adapt_events_email::{
EmailExecutionPlan, EmailSendRequest, build_email_execution_plan, execute_email_request,
};
use crate::runner::contract_cache::{ContractCache, ContractCacheStats};
use crate::runner::engine::FlowEngine;
use crate::runner::mocks::MockLayer;
use crate::secrets::{DynSecretsManager, canonicalize_secret_key, read_secret_blocking};
use crate::storage::session::DynSessionStore;
use crate::storage::state::DynStateStore;
use crate::telemetry::RolloutIds;
use crate::trace::PackTraceInfo;
use crate::wasi::RunnerWasiPolicy;
use greentic_deploy_spec::ids::{BundleId, DeploymentId, RevisionId};
use greentic_types::SecretRequirement;
use runner_core::packs::PackDigest;
const RUNTIME_SECRETS_PACK_ID: &str = "_runner";
/// Key identifying a live runtime in [`ActivePacks`].
///
/// Tenant-only entries use [`RuntimeKey::legacy`] (all id fields `None`);
/// fully-qualified entries use [`RuntimeKey::revision`] (all `Some`). The two
/// forms never collide, so both can coexist in the same map.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RuntimeKey {
pub tenant: String,
pub deployment_id: Option<DeploymentId>,
pub bundle_id: Option<BundleId>,
pub revision_id: Option<RevisionId>,
}
impl RuntimeKey {
/// Tenant-only key for the pre-revision-routing path.
pub fn legacy(tenant: impl Into<String>) -> Self {
Self {
tenant: tenant.into(),
deployment_id: None,
bundle_id: None,
revision_id: None,
}
}
/// Fully-qualified key for a specific deployment/bundle/revision.
pub fn revision(
tenant: impl Into<String>,
deployment_id: DeploymentId,
bundle_id: BundleId,
revision_id: RevisionId,
) -> Self {
Self {
tenant: tenant.into(),
deployment_id: Some(deployment_id),
bundle_id: Some(bundle_id),
revision_id: Some(revision_id),
}
}
/// `true` for the tenant-only key produced by [`legacy`](Self::legacy).
pub fn is_legacy(&self) -> bool {
self.deployment_id.is_none() && self.bundle_id.is_none() && self.revision_id.is_none()
}
}
/// Build the next runtime map for a legacy (tenant-only) reload: install the
/// freshly-resolved `legacy` entries and carry over every revision-keyed entry
/// untouched. Revision runtimes are owned by the deployment lifecycle, not the
/// pack watcher, so a tenant-pack reload must not evict them.
fn merge_legacy_reload<V: Clone>(
prev: &HashMap<RuntimeKey, V>,
mut legacy: HashMap<RuntimeKey, V>,
) -> HashMap<RuntimeKey, V> {
for (key, value) in prev {
if !key.is_legacy() {
legacy.insert(key.clone(), value.clone());
}
}
legacy
}
/// Pure swap helper for [`ActivePacks::remove_revision`]: clone the prev map
/// minus `key`, return it alongside the removed value. `None` when the key was
/// absent so the caller can skip the `ArcSwap` store. Generic over `V` so the
/// swap logic is testable without standing up a real `TenantRuntime`.
fn remove_keyed_entry<V: Clone>(
prev: &HashMap<RuntimeKey, V>,
key: &RuntimeKey,
) -> Option<(HashMap<RuntimeKey, V>, V)> {
let removed = prev.get(key)?.clone();
let mut next = prev.clone();
next.remove(key);
Some((next, removed))
}
/// Pure swap helper for [`ActivePacks::insert_revision`]: clone the prev map
/// and insert `value` under `key`, returning the next map. Generic over `V` so
/// the swap logic is testable without standing up a real `TenantRuntime`.
fn insert_keyed_entry<V: Clone>(
prev: &HashMap<RuntimeKey, V>,
key: RuntimeKey,
value: V,
) -> HashMap<RuntimeKey, V> {
let mut next = prev.clone();
next.insert(key, value);
next
}
/// Atomically swapped view of live tenant runtimes.
///
/// Reads are lock-free via `ArcSwap`. Mutations serialize on `write_lock` so a
/// read-modify-write swap (e.g. a watcher reload preserving revision entries)
/// cannot interleave with a concurrent insert and clobber the other's update.
pub struct ActivePacks {
inner: ArcSwap<HashMap<RuntimeKey, Arc<TenantRuntime>>>,
write_lock: Mutex<()>,
}
impl ActivePacks {
pub fn new() -> Self {
Self {
inner: ArcSwap::from_pointee(HashMap::new()),
write_lock: Mutex::new(()),
}
}
/// Look up the tenant-only (legacy) runtime. Compatibility helper for the
/// pre-revision-routing path; see [`load_revision`](Self::load_revision).
pub fn load_pack(&self, tenant: &str) -> Option<Arc<TenantRuntime>> {
self.inner.load().get(&RuntimeKey::legacy(tenant)).cloned()
}
/// Look up the runtime for a specific deployment/bundle/revision.
pub fn load_revision(
&self,
tenant: &str,
deployment_id: DeploymentId,
bundle_id: BundleId,
revision_id: RevisionId,
) -> Option<Arc<TenantRuntime>> {
self.inner
.load()
.get(&RuntimeKey::revision(
tenant,
deployment_id,
bundle_id,
revision_id,
))
.cloned()
}
pub fn snapshot(&self) -> Arc<HashMap<RuntimeKey, Arc<TenantRuntime>>> {
self.inner.load_full()
}
/// Insert (or replace) a single tenant-only runtime, preserving all other
/// entries — including revision-keyed ones.
pub fn insert_pack(&self, tenant: &str, runtime: Arc<TenantRuntime>) {
let _guard = self.write_lock.lock();
let mut next = (*self.inner.load_full()).clone();
next.insert(RuntimeKey::legacy(tenant), runtime);
self.inner.store(Arc::new(next));
}
/// Insert (or replace) a single revision-keyed runtime, preserving every
/// other entry — the tenant-only legacy entry and sibling revisions alike.
/// This is the producer the deployment warm path calls once a revision's
/// packs are loaded; the pack watcher's [`replace_legacy`](Self::replace_legacy)
/// then carries the entry across tenant-pack reloads untouched.
///
/// Fails closed when the runtime's identity does not match the key it would
/// be stored under: a wiring bug that files one tenant's runtime under
/// another tenant's revision (breaking isolation) or stores a runtime whose
/// telemetry reports a different revision than it routes (breaking rollout
/// attribution) is rejected here rather than silently serving traffic under
/// the wrong identity. Pairs with [`TenantRuntime::load_revision`], which
/// derives the runtime's rollout identity from these same ids.
pub fn insert_revision(
&self,
tenant: &str,
deployment_id: DeploymentId,
bundle_id: BundleId,
revision_id: RevisionId,
runtime: Arc<TenantRuntime>,
) -> Result<()> {
if runtime.tenant() != tenant {
bail!(
"revision runtime tenant `{}` does not match key tenant `{tenant}`",
runtime.tenant()
);
}
let ids = runtime.engine().rollout_ids();
let key_deployment = deployment_id.to_string();
let key_bundle = bundle_id.as_str();
let key_revision = revision_id.to_string();
if ids.deployment_id.as_deref() != Some(key_deployment.as_str())
|| ids.bundle_id.as_deref() != Some(key_bundle)
|| ids.revision_id.as_deref() != Some(key_revision.as_str())
{
bail!(
"revision runtime rollout identity (deployment={:?}, bundle={:?}, revision={:?}) \
does not match key (deployment=`{key_deployment}`, bundle=`{key_bundle}`, \
revision=`{key_revision}`)",
ids.deployment_id,
ids.bundle_id,
ids.revision_id
);
}
let _guard = self.write_lock.lock();
let key = RuntimeKey::revision(tenant, deployment_id, bundle_id, revision_id);
let next = insert_keyed_entry(&self.inner.load_full(), key, runtime);
self.inner.store(Arc::new(next));
Ok(())
}
/// Swap in a freshly-resolved set of tenant-only (legacy) runtimes while
/// carrying over every revision-keyed entry. Used by the pack watcher, whose
/// index is authoritative for tenant packs but not for deployment revisions.
pub fn replace_legacy(&self, legacy: HashMap<RuntimeKey, Arc<TenantRuntime>>) {
let _guard = self.write_lock.lock();
let prev = self.inner.load_full();
let next = merge_legacy_reload(&prev, legacy);
self.inner.store(Arc::new(next));
}
/// Remove and return the runtime for a single revision-keyed entry,
/// preserving every other entry (legacy and revision alike). Used by the
/// drain coordinator (`gtc op revisions drain`) after the drain window
/// closes to tear down exactly the one revision being retired. `None` if
/// no such entry was present — idempotent for safe re-runs.
pub fn remove_revision(
&self,
tenant: &str,
deployment_id: DeploymentId,
bundle_id: BundleId,
revision_id: RevisionId,
) -> Option<Arc<TenantRuntime>> {
let _guard = self.write_lock.lock();
let prev = self.inner.load_full();
let key = RuntimeKey::revision(tenant, deployment_id, bundle_id, revision_id);
let (next, removed) = remove_keyed_entry(&prev, &key)?;
self.inner.store(Arc::new(next));
Some(removed)
}
/// Replace the entire map, dropping every entry (legacy and revision alike).
/// Used for full host stop.
pub fn replace(&self, next: HashMap<RuntimeKey, Arc<TenantRuntime>>) {
let _guard = self.write_lock.lock();
self.inner.store(Arc::new(next));
}
pub fn len(&self) -> usize {
self.inner.load().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Default for ActivePacks {
fn default() -> Self {
Self::new()
}
}
/// Runtime bundle for a tenant pack.
pub struct TenantRuntime {
tenant: String,
config: Arc<HostConfig>,
packs: Vec<Arc<PackRuntime>>,
digests: Vec<Option<String>>,
engine: Arc<FlowEngine>,
state_machine: Arc<StateMachineRuntime>,
/// The session store this runtime was loaded with. Shared with the inner
/// state machine — re-exposed here so callers outside the flow run loop
/// (M1.5 welcome-flow first-contact probe) can query the SAME bucket the
/// state machine will read/write. For revision mode each revision passes
/// its own store into `load_revision`; querying the RunnerHost-level
/// store would key the wrong bucket.
session_store: DynSessionStore,
http_client: Client,
mocks: Option<Arc<MockLayer>>,
timer_handles: Mutex<Vec<JoinHandle<()>>>,
secrets: DynSecretsManager,
operator_registry: OperatorRegistry,
operator_metrics: Arc<OperatorMetrics>,
contract_cache: ContractCache,
/// The HTTP approval inbox, when this runtime serves one. Shut down on
/// drop: the poller stops, held decision tokens are forgotten, and a
/// superseded revision can never resume into a store it no longer owns.
approval_inbox: Option<crate::runner::approval_http::HttpApprovalDispatcher>,
}
#[derive(Clone)]
pub struct ResolvedComponent {
pub digest: String,
pub component_ref: String,
pub pack: Arc<PackRuntime>,
}
/// One pinned pack of a deployment revision: the on-disk path plus the
/// `algo:value` content digest the deployment staged it under.
/// [`TenantRuntime::load_revision`] fails closed when the file no longer
/// matches the digest, defending the stage→warm window against a swapped or
/// stale cache path.
#[derive(Clone, Debug)]
pub struct RevisionPackRef {
pub path: PathBuf,
pub digest: String,
}
/// The arguments of [`TenantRuntime::load_revision`], as one struct, for
/// [`TenantRuntime::load_revision_with`]. Field meanings are exactly
/// `load_revision`'s parameters of the same names.
pub struct RevisionLoad<'a> {
pub pack_refs: &'a [RevisionPackRef],
pub config: Arc<HostConfig>,
pub mocks: Option<Arc<MockLayer>>,
pub wasi_policy: Arc<RunnerWasiPolicy>,
pub session_host: Arc<dyn SessionHost>,
pub session_store: DynSessionStore,
pub state_store: DynStateStore,
pub state_host: Arc<dyn StateHost>,
pub secrets_manager: DynSecretsManager,
pub deployment_id: DeploymentId,
pub bundle_id: BundleId,
pub revision_id: RevisionId,
pub customer_id: Option<String>,
pub runtime_configs_by_pack_id: &'a BTreeMap<String, Arc<BTreeMap<String, Value>>>,
pub runtime_refs_by_pack_id: &'a BTreeMap<String, Arc<BTreeMap<String, String>>>,
pub runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
}
/// What the embedding HOST decides for one revision, beyond its pinned packs.
/// `Default` is exactly [`TenantRuntime::load_revision`]'s behaviour.
/// Non-exhaustive so a later host seam is an additive field, not a breaking
/// change: construct with `RevisionHostOptions::default()` plus the `with_*`
/// setters.
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct RevisionHostOptions {
#[cfg(feature = "agentic-worker")]
billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
#[cfg(feature = "agentic-worker")]
user_ledger: Option<greentic_aw_runtime::user_ledger::UserLedgerTarget>,
}
impl std::fmt::Debug for RevisionHostOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut out = f.debug_struct("RevisionHostOptions");
#[cfg(feature = "agentic-worker")]
out.field("billing_meter", &self.billing_meter.is_some());
out.field("run_outcome_sink", &self.run_outcome_sink.is_some());
out.field("approval_inbox", &self.approval_inbox.is_some());
#[cfg(feature = "agentic-worker")]
out.field("user_ledger", &self.user_ledger.is_some());
out.finish()
}
}
impl RevisionHostOptions {
/// Record this unit's agentic-worker LLM usage through `meter` as well —
/// see [`TenantRuntime::load_revision_with`] for how it combines with the
/// env-configured cloud-commerce sink.
#[cfg(feature = "agentic-worker")]
#[must_use]
pub fn with_billing_meter(
mut self,
meter: Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
) -> Self {
self.billing_meter = Some(meter);
self
}
/// Report one [`crate::run_outcome::RunOutcome`] per flow turn of this
/// unit through `sink` — the deployed run audit. greentic-start installs a
/// [`crate::run_outcome::HttpRunOutcomeSink`] built from the same staged
/// `metering` block as the billing meter. Without one, flow execution and
/// the persisted resume state are unchanged.
#[must_use]
pub fn with_run_outcome_sink(
mut self,
sink: Arc<dyn crate::run_outcome::RunOutcomeSink>,
) -> Self {
self.run_outcome_sink = Some(sink);
self
}
/// File this unit's human approvals with the admin's HTTP approval inbox
/// and poll for the decisions, instead of needing a NATS broker — the
/// HTTP approval rail (greentic-designer
/// `docs/superpowers/specs/2026-09-29-approval-rail-http-design.md`).
/// greentic-start builds the target from the same staged `metering`
/// block as the run-outcome sink.
///
/// Serves ONLY `approval.call`: it goes into the engine's own approval
/// slot, so `sorla.call` still fails with `sorla_route_missing` on a lane
/// with no broker. When `GREENTIC_EVENTS_NATS_URL` also connects, NATS
/// wins and the inbox is not installed. A target that fails validation
/// (blank field, cleartext URL off loopback) is logged and skipped; the
/// runtime loads either way, and an approval that needs a human then fails
/// at the node as it did before. Validate early with
/// [`crate::runner::approval_http::HttpApprovalDispatcher::new`].
#[must_use]
pub fn with_approval_inbox(
mut self,
target: crate::runner::approval_http::ApprovalInboxTarget,
) -> Self {
self.approval_inbox = Some(target);
self
}
/// Read and append this unit's user ledger (shared context, Phase C) at
/// the admin's ledger door. greentic-start builds the target from the same
/// staged `metering` block as the approval inbox: `base_url` is the
/// worker-usage endpoint with its last segment swapped for `ledger`,
/// `token` the unit's metering token, `tenant_slug` the block's slug. The
/// runner never reads that block itself.
///
/// Nothing happens unless a pack also names an agent in
/// `assets/user-ledger.json`, and only a turn whose caller the provider
/// verified, outside any tool call, touches the ledger. That sidecar alone
/// decides `read` versus `read_write` for the pack's own agents: there is
/// no host-side ceiling on the mode. The gates are the door token's
/// `ledger` purpose (the admin refuses a token without it), the
/// `GREENTIC_AW_USER_LEDGER` kill switch, the tenant match between the
/// runtime and the turn, and a provider-verified subject. A target that
/// fails validation (blank field, cleartext URL off loopback, userinfo in
/// the URL) is one warning and the runtime loads without the ledger;
/// validate early with
/// [`greentic_aw_runtime::user_ledger::HttpUserLedger::new`]. The admin
/// refuses a token without the `ledger` purpose, and the client then
/// stops asking for a while. `GREENTIC_AW_USER_LEDGER=0` turns it off.
#[cfg(feature = "agentic-worker")]
#[must_use]
pub fn with_user_ledger(
mut self,
target: greentic_aw_runtime::user_ledger::UserLedgerTarget,
) -> Self {
self.user_ledger = Some(target);
self
}
}
/// Block on a future whether or not we're already inside a tokio runtime.
pub fn block_on<F: Future<Output = R>, R>(future: F) -> R {
if let Ok(handle) = Handle::try_current() {
handle.block_on(future)
} else {
Runtime::new()
.expect("failed to create tokio runtime")
.block_on(future)
}
}
impl TenantRuntime {
#[allow(clippy::too_many_arguments)]
pub async fn load(
pack_path: &Path,
config: Arc<HostConfig>,
mocks: Option<Arc<MockLayer>>,
archive_source: Option<&Path>,
digest: Option<String>,
wasi_policy: Arc<RunnerWasiPolicy>,
session_host: Arc<dyn SessionHost>,
session_store: DynSessionStore,
state_store: DynStateStore,
state_host: Arc<dyn StateHost>,
secrets_manager: DynSecretsManager,
#[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
#[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
#[cfg(feature = "agentic-worker")] stream_observers: Option<
crate::http::agent_stream::StreamObserverRegistry,
>,
) -> Result<Arc<Self>> {
let pack = Self::load_pack_runtime(
pack_path,
&config,
mocks.clone(),
archive_source,
&wasi_policy,
&session_store,
&state_store,
&secrets_manager,
&BTreeMap::new(),
&BTreeMap::new(),
None,
// Tenant-only path: no deployed unit, so pack secrets resolve the
// bare pack scope exactly as before.
None,
)
.await?;
Self::from_packs(
config,
vec![(pack, digest)],
mocks,
session_host,
session_store,
state_store,
state_host,
secrets_manager,
#[cfg(feature = "agentic-worker")]
ext_llm_port,
#[cfg(feature = "agentic-worker")]
mcp_source,
#[cfg(feature = "agentic-worker")]
stream_observers,
)
.await
}
/// Build a revision-keyed runtime from its pinned pack list (the resolved
/// `pack_list` of a deployment revision). The first entry is the main pack;
/// the rest are overlays.
///
/// Fails closed if any pack file no longer matches the digest the
/// deployment pinned it under — defending the stage→warm window against a
/// swapped or stale cache path. The verified digests are threaded into the
/// runtime so admin status, traces, and contract hashes report the real
/// content (parity with the legacy index path). The rollout telemetry
/// identity is **derived from** `deployment_id` / `bundle_id` /
/// `revision_id` / `customer_id`, so the engine's attribution cannot drift
/// from the key the runtime is later inserted under.
///
/// Installs no host billing meter: agentic-worker usage goes to the
/// env-configured cloud-commerce sink when `GREENTIC_BILLING_*` is set,
/// else nowhere. Graph turns and in-process deep workers are now metered
/// and graph turns run under the real tenant; see
/// [`load_revision_with`](Self::load_revision_with) for the four
/// behaviour changes that brings, and for installing a per-unit meter.
#[allow(clippy::too_many_arguments)]
pub async fn load_revision(
pack_refs: &[RevisionPackRef],
config: Arc<HostConfig>,
mocks: Option<Arc<MockLayer>>,
wasi_policy: Arc<RunnerWasiPolicy>,
session_host: Arc<dyn SessionHost>,
session_store: DynSessionStore,
state_store: DynStateStore,
state_host: Arc<dyn StateHost>,
secrets_manager: DynSecretsManager,
deployment_id: DeploymentId,
bundle_id: BundleId,
revision_id: RevisionId,
customer_id: Option<String>,
runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
) -> Result<Arc<Self>> {
Self::load_revision_impl(
pack_refs,
config,
mocks,
wasi_policy,
session_host,
session_store,
state_store,
state_host,
secrets_manager,
deployment_id,
bundle_id,
revision_id,
customer_id,
runtime_configs_by_pack_id,
runtime_refs_by_pack_id,
runtime_ref_resolver,
#[cfg(feature = "agentic-worker")]
None,
None,
None,
#[cfg(feature = "agentic-worker")]
None,
)
.await
}
/// [`load_revision`](Self::load_revision), taking its arguments as one
/// struct plus the host-chosen [`RevisionHostOptions`] for this unit.
///
/// Two options exist: the run-outcome sink
/// ([`RevisionHostOptions::with_run_outcome_sink`], the deployed run audit
/// — see `crate::run_outcome`) and the billing sink
/// ([`RevisionHostOptions::with_billing_meter`]). For the latter, greentic-start installs a
/// [`greentic_aw_runtime::billing::WorkerUsageMeter`] built from the unit's
/// staged `metering` block, so the unit's LLM spend is recorded at the
/// admin's per-unit ingest door. It is per-REVISION rather than a
/// `HostBuilder` setting on purpose: one greentic-start process serves every
/// unit of an environment, and each unit has its own worker-usage token.
///
/// # Which sink runs (see `agent_node::resolve_billing_meter`)
///
/// - An installed meter AND `GREENTIC_BILLING_BASE_URL` +
/// `GREENTIC_BILLING_SERVICE_SECRET` set: every usage event goes to BOTH
/// (a [`greentic_aw_runtime::billing::FanOutBillingMeter`]), and the
/// credit gate (`over_budget`) is the env cloud-commerce sink's. An
/// installed meter never removes the credit gate.
/// - An installed meter only: that meter alone (it has no credit gate).
/// - No installed meter: exactly [`load_revision`] — the env sink when
/// configured, else none.
///
/// # Behaviour that changed with this seam, for BOTH entry points
///
/// Recorded because a publish on the dev lane reaches every consumer:
///
/// - (a) agent-graph agent and supervisor turns now emit usage and pass
/// the credit gate when `GREENTIC_BILLING_*` is set. Before, they ran on
/// a `NoopBillingMeter` and were never metered or gated;
/// - (b) in-process deep workers (`operala.call`) now emit their own
/// reasoning-loop tokens to the chosen sink, cloud-commerce included;
/// - (c) graph turns now run under the real tenant/env, so their tokens
/// count against that tenant's `daily_token_cap_per_tenant` bucket,
/// shared with `dw.agent` (before: one global `graph/run` bucket);
/// - (d) long-term memory previously written under the synthetic
/// `graph/run` tenant by `agent_ref` graph turns is no longer reachable.
/// That key was shared by every tenant, so losing it is intended.
/// Per-visit conversation state is re-seeded from the graph checkpoint on
/// every visit, so in-flight runs lose nothing.
///
/// [`load_revision`]: Self::load_revision
pub async fn load_revision_with(
args: RevisionLoad<'_>,
options: RevisionHostOptions,
) -> Result<Arc<Self>> {
Self::load_revision_impl(
args.pack_refs,
args.config,
args.mocks,
args.wasi_policy,
args.session_host,
args.session_store,
args.state_store,
args.state_host,
args.secrets_manager,
args.deployment_id,
args.bundle_id,
args.revision_id,
args.customer_id,
args.runtime_configs_by_pack_id,
args.runtime_refs_by_pack_id,
args.runtime_ref_resolver,
#[cfg(feature = "agentic-worker")]
options.billing_meter,
options.run_outcome_sink,
options.approval_inbox,
#[cfg(feature = "agentic-worker")]
options.user_ledger,
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn load_revision_impl(
pack_refs: &[RevisionPackRef],
config: Arc<HostConfig>,
mocks: Option<Arc<MockLayer>>,
wasi_policy: Arc<RunnerWasiPolicy>,
session_host: Arc<dyn SessionHost>,
session_store: DynSessionStore,
state_store: DynStateStore,
state_host: Arc<dyn StateHost>,
secrets_manager: DynSecretsManager,
deployment_id: DeploymentId,
bundle_id: BundleId,
revision_id: RevisionId,
customer_id: Option<String>,
runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
#[cfg(feature = "agentic-worker")] billing_meter: Option<
Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
>,
run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
#[cfg(feature = "agentic-worker")] user_ledger: Option<
greentic_aw_runtime::user_ledger::UserLedgerTarget,
>,
) -> Result<Arc<Self>> {
if pack_refs.is_empty() {
bail!(
"revision runtime for tenant {} requires at least one pack",
config.tenant
);
}
let mut packs = Vec::with_capacity(pack_refs.len());
let mut seen_pack_ids = HashSet::with_capacity(pack_refs.len());
for pack_ref in pack_refs {
let expected = PackDigest::parse(&pack_ref.digest).with_context(|| {
format!(
"revision pack `{}` has an invalid digest `{}`",
pack_ref.path.display(),
pack_ref.digest
)
})?;
// `matches_file` always hashes with SHA-256, so a digest pinned under
// any other algorithm could never match — reject it with a clear
// message rather than the misleading "does not match" below.
if expected.algorithm() != "sha256" {
bail!(
"revision pack `{}` pins unsupported digest algorithm `{}`; only sha256 is supported",
pack_ref.path.display(),
expected.algorithm()
);
}
if !expected.matches_file(&pack_ref.path).with_context(|| {
format!(
"hashing revision pack `{}` for digest verification",
pack_ref.path.display()
)
})? {
bail!(
"revision pack `{}` does not match pinned digest `{}`",
pack_ref.path.display(),
pack_ref.digest
);
}
let pack = Self::load_pack_runtime(
&pack_ref.path,
&config,
mocks.clone(),
None,
&wasi_policy,
&session_store,
&state_store,
&secrets_manager,
runtime_configs_by_pack_id,
runtime_refs_by_pack_id,
runtime_ref_resolver.as_ref(),
// The unit every extension credential in this pack is scoped
// to. Same value `FlowEngine::mcp_credential_unit` reads off
// `rollout_ids.bundle_id` below, so the flow-node MCP lane and
// the component lane cannot disagree about which unit is running.
Some(bundle_id.as_str()),
)
.await?;
// Reject duplicate pack_id within a single revision — two refs
// resolving to the same pack_id would silently share config/routing
// entries and produce an ambiguous runtime.
let pack_id = pack.metadata().pack_id.clone();
if !seen_pack_ids.insert(pack_id.clone()) {
bail!(
"revision for tenant {} contains duplicate pack_id `{}` (path `{}`)",
config.tenant,
pack_id,
pack_ref.path.display(),
);
}
packs.push((pack, Some(expected.raw_string())));
}
let rollout = RolloutIds {
customer_id,
deployment_id: Some(deployment_id.to_string()),
bundle_id: Some(bundle_id.as_str().to_string()),
revision_id: Some(revision_id.to_string()),
};
Self::from_packs_with_rollout(
config,
packs,
mocks,
session_host,
session_store,
state_store,
state_host,
secrets_manager,
// No host-injected ports on the revision-keyed path: it is
// constructed from a pinned pack list rather than from a
// `RunnerHost`, so there is none to read them from. Matches what
// `ext_llm_port` already does here — an engine built this way
// falls back to env for both.
#[cfg(feature = "agentic-worker")]
None,
#[cfg(feature = "agentic-worker")]
None,
#[cfg(feature = "agentic-worker")]
None,
rollout,
#[cfg(feature = "agentic-worker")]
billing_meter,
run_outcome_sink,
approval_inbox,
#[cfg(feature = "agentic-worker")]
user_ledger,
)
.await
}
/// Load a single [`PackRuntime`] from a path, sharing the tenant's session /
/// state / secrets backends. Shared by [`load`](Self::load) (one pack) and
/// [`load_revision`](Self::load_revision) (the revision's pack list).
///
/// `runtime_configs_by_pack_id` is consulted AFTER the pack loads (the
/// `pack_id` is only known after the manifest read) and BEFORE the
/// `Arc<PackRuntime>` is created. A matching entry is injected via
/// [`PackRuntime::set_runtime_config_non_secret`] so the C4.3 producer
/// plumbing requires no post-hoc `Arc::get_mut` dance — the single-pack
/// [`load`](Self::load) path just passes an empty map.
///
/// `runtime_refs_by_pack_id` mirrors the same shape for the C5
/// `pack-config.v1.runtime_refs` channel; a matching entry is injected
/// via [`PackRuntime::set_runtime_refs`] alongside `runtime_ref_resolver`.
///
/// `unit_id` is the deployed unit this pack belongs to — the revision's
/// `bundle_id` on the [`load_revision`](Self::load_revision) path, `None`
/// on the legacy tenant-only [`load`](Self::load) path. It scopes every
/// extension credential the pack's components read, so two units of the
/// SAME pack in one environment can hold different values. It is taken as
/// a parameter rather than read from a process environment variable
/// because one greentic-start process serves every revision of an
/// environment, so an env var could not differ per unit.
#[allow(clippy::too_many_arguments)]
async fn load_pack_runtime(
pack_path: &Path,
config: &Arc<HostConfig>,
mocks: Option<Arc<MockLayer>>,
archive_source: Option<&Path>,
wasi_policy: &Arc<RunnerWasiPolicy>,
session_store: &DynSessionStore,
state_store: &DynStateStore,
secrets_manager: &DynSecretsManager,
runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
runtime_ref_resolver: Option<&Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
unit_id: Option<&str>,
) -> Result<Arc<PackRuntime>> {
let oauth_config = config.oauth_broker_config();
let mut pack = PackRuntime::load(
pack_path,
Arc::clone(config),
mocks,
archive_source,
Some(Arc::clone(session_store)),
Some(Arc::clone(state_store)),
Arc::clone(wasi_policy),
Arc::clone(secrets_manager),
oauth_config,
true,
ComponentResolution::default(),
)
.await
.with_context(|| {
format!(
"failed to load pack {} for tenant {}",
pack_path.display(),
config.tenant
)
})?;
let pack_id = pack.metadata().pack_id.clone();
if let Some(non_secret) = runtime_configs_by_pack_id.get(pack_id.as_str()) {
pack.set_runtime_config_non_secret(Some(Arc::clone(non_secret)));
}
pack.set_unit_id(unit_id.map(str::to_string));
if let Some(refs) = runtime_refs_by_pack_id.get(pack_id.as_str()) {
let resolver = runtime_ref_resolver.ok_or_else(|| {
anyhow!(
"pack `{}` has runtime_refs bound but no RuntimeRefResolver was provided",
pack_id,
)
})?;
pack.set_runtime_refs(Some(crate::runtime_refs::RuntimeRefsInjection {
refs: Arc::clone(refs),
resolver: Arc::clone(resolver),
}));
}
Ok(Arc::new(pack))
}
#[allow(clippy::too_many_arguments)]
pub async fn from_packs(
config: Arc<HostConfig>,
packs: Vec<(Arc<PackRuntime>, Option<String>)>,
mocks: Option<Arc<MockLayer>>,
session_host: Arc<dyn SessionHost>,
session_store: DynSessionStore,
state_store: DynStateStore,
state_host: Arc<dyn StateHost>,
secrets_manager: DynSecretsManager,
#[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
#[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
#[cfg(feature = "agentic-worker")] stream_observers: Option<
crate::http::agent_stream::StreamObserverRegistry,
>,
) -> Result<Arc<Self>> {
Self::from_packs_with_rollout(
config,
packs,
mocks,
session_host,
session_store,
state_store,
state_host,
secrets_manager,
#[cfg(feature = "agentic-worker")]
ext_llm_port,
#[cfg(feature = "agentic-worker")]
mcp_source,
#[cfg(feature = "agentic-worker")]
stream_observers,
RolloutIds::default(),
// The tenant-only path has no unit, so no host-chosen meter and
// no run-outcome sink.
#[cfg(feature = "agentic-worker")]
None,
None,
None,
// ... and no host-provided user ledger target.
#[cfg(feature = "agentic-worker")]
None,
)
.await
}
/// Like [`from_packs`](Self::from_packs) but stamps `rollout` onto the flow
/// engine so every span this runtime emits carries the deployment / bundle /
/// revision / customer identity. [`from_packs`](Self::from_packs) is the
/// legacy (tenant-only) path and passes [`RolloutIds::default`].
#[allow(clippy::too_many_arguments)]
pub(crate) async fn from_packs_with_rollout(
config: Arc<HostConfig>,
packs: Vec<(Arc<PackRuntime>, Option<String>)>,
mocks: Option<Arc<MockLayer>>,
session_host: Arc<dyn SessionHost>,
session_store: DynSessionStore,
_state_store: DynStateStore,
state_host: Arc<dyn StateHost>,
secrets_manager: DynSecretsManager,
#[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
#[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
#[cfg(feature = "agentic-worker")] stream_observers: Option<
crate::http::agent_stream::StreamObserverRegistry,
>,
rollout: RolloutIds,
#[cfg(feature = "agentic-worker")] installed_billing_meter: Option<
Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
>,
run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
#[cfg(feature = "agentic-worker")] user_ledger: Option<
greentic_aw_runtime::user_ledger::UserLedgerTarget,
>,
) -> Result<Arc<Self>> {
let operator_registry = OperatorRegistry::build(&packs)?;
let operator_metrics = Arc::new(OperatorMetrics::default());
let pack_runtimes = packs
.iter()
.map(|(pack, _)| Arc::clone(pack))
.collect::<Vec<_>>();
let digests = packs
.iter()
.map(|(_, digest)| digest.clone())
.collect::<Vec<_>>();
let mut pack_trace = HashMap::new();
for (pack, digest) in &packs {
let pack_id = pack.metadata().pack_id.clone();
let pack_ref = config
.pack_bindings
.iter()
.find(|binding| binding.pack_id == pack_id)
.map(|binding| binding.pack_ref.clone())
.unwrap_or_else(|| pack_id.clone());
pack_trace.insert(
pack_id,
PackTraceInfo {
pack_ref,
resolved_digest: digest.clone(),
},
);
}
// The deployed unit's identity, used as the `project_id` billing
// dimension for this runtime's agentic-worker spend. It is exactly what
// greentic-designer records as `pack_name`, so authoring-time and
// runtime spend join on it. Captured BEFORE `rollout` moves into the
// engine; `None` on the legacy tenant-only path (no bundle is pinned
// there), which makes billing omit the dimension rather than fall back
// to a non-unique in-pack agent id.
#[cfg(feature = "agentic-worker")]
let agent_project_id = rollout.bundle_id.clone();
let engine = FlowEngine::new(pack_runtimes.clone(), Arc::clone(&config))
.await
.context("failed to prime flow engine")?
.with_rollout_ids(rollout);
// A host-injected MCP source replaces the one `FlowEngine::new` derives
// from env; `None` leaves that env-derived source alone, so a
// standalone runner is unaffected.
#[cfg(feature = "agentic-worker")]
let engine = engine.with_mcp_source(mcp_source);
// An `mcp` flow node resolves its credential through the manager this
// runtime already holds — dev-store in a Cloud Run or Kubernetes
// deployment, which is the only backend there that can read a
// `secrets://` URI. Without this the node built its own manager from
// `SECRETS_BACKEND`, which no remote deployment sets, and every lookup
// missed. An explicit `SECRETS_BACKEND` still wins; see
// `mcp_node::aw::choose_mcp_secrets`.
#[cfg(feature = "agentic-worker")]
let engine = engine.with_mcp_secrets(Some(Arc::clone(&secrets_manager)));
#[cfg_attr(not(feature = "agentic-worker"), allow(unused_mut))]
let mut engine = engine;
// Wire Sorla remote-dispatch (NATS) into the flow engine BEFORE it is
// moved behind an `Arc`. `set_remote_dispatch_handler` takes `&mut self`,
// so the dispatcher must be attached while `engine` is still owned and
// mutable. The response listener (which needs the post-build ingress
// handle) is spawned further below, after the runtime is constructed.
//
// Gated on `GREENTIC_EVENTS_NATS_URL`: when unset, `sorla.call` stays
// disabled and existing behaviour is unchanged. When set but NATS cannot
// be reached we log a warning and continue (the engine simply has no
// dispatch handler, so `sorla.call` nodes fail fast at execution time).
//
// Connected here (BEFORE the agentic-worker block below) rather than
// its original post-block position so the agent-node handler
// construction below can also thread the (possibly connected) client
// into an `AuditSink` for `dw.agent` step audit events (EPIC-B B-3);
// pure reordering, no behaviour change to the dispatch wiring itself.
let dispatch_nats_client = match std::env::var("GREENTIC_EVENTS_NATS_URL") {
Ok(nats_url) => match async_nats::connect(&nats_url).await {
Ok(client) => {
engine.set_remote_dispatch_handler(Arc::new(
crate::runner::remote_dispatch::NatsDispatcher::new(client.clone()),
));
Some(client)
}
Err(error) => {
tracing::warn!(
%error,
"GREENTIC_EVENTS_NATS_URL set but NATS connect failed; sorla.call disabled"
);
None
}
},
Err(_) => None,
};
// The HTTP approval rail (greentic-designer approval-rail-http design
// §4.6): into the engine's OWN approval slot, never the shared one, so
// `sorla.call` keeps failing with `sorla_route_missing` here. NATS
// stays authoritative where it connected.
if approval_inbox.is_some() && dispatch_nats_client.is_some() {
tracing::info!(
"GREENTIC_EVENTS_NATS_URL connected; approvals go over NATS and the HTTP approval inbox is not installed"
);
}
let approval_inbox = crate::runner::approval_http::inbox_to_install(
dispatch_nats_client.is_some(),
approval_inbox,
)
.and_then(
|target| match crate::runner::approval_http::HttpApprovalDispatcher::new(target) {
Ok(inbox) => {
engine.set_approval_dispatch_handler(Arc::new(inbox.clone()));
tracing::info!("HTTP approval inbox wired into runtime: approval.call");
Some(inbox)
}
Err(error) => {
tracing::warn!(
%error,
"HTTP approval inbox not installed; approval.call needing a human will fail"
);
None
}
},
);
// Clone the (possibly connected) client for the audit sink (EPIC-B
// B-2/B-3): threaded into `StateMachineRuntime::from_flow_engine` so
// `TraceRecorder` can publish best-effort audit events over NATS, and
// (as an `AuditSink`) into the `dw.agent` node handler below so agent
// tool-call/tool-result steps are audited too. Cloned BEFORE the
// response-listener loop further below moves `dispatch_nats_client`.
// `None` when NATS is unset/unreachable, which keeps both audit paths
// off by default (zero behaviour change).
let audit_nats_client = dispatch_nats_client.clone();
// The dw.agent handler, kept so flow-tool engines can borrow it
// (`runner::nested_flow`) once the dispatch mode is known below.
#[cfg(feature = "agentic-worker")]
let mut nested_agent_handler: Option<
Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
> = None;
#[cfg(feature = "agentic-worker")]
{
use crate::runner::agent_node::{
agent_configs_from_manifest, merge_agent_sources, merge_sidecar_into,
};
use std::collections::HashMap;
// Collect agent configs from all New-manifest packs. When the same
// agent_id appears in multiple packs the last pack wins (packs are
// ordered: first = primary, rest = overlays). Collisions are logged
// so operators can audit cross-pack conflicts.
let mut pack_agents: HashMap<String, greentic_aw_runtime::AgentConfig> = HashMap::new();
for pack in &pack_runtimes {
let mut blobs = pack.manifest_agent_blobs();
// Bridge: designer-built packs cannot populate `manifest.agents`
// (old greentic-pack); they embed a `dw-agents.json` sidecar.
// Fill any agent_id the manifest lacked (manifest stays authoritative).
merge_sidecar_into(&mut blobs, pack.dw_agents_sidecar_blobs());
if blobs.is_empty() {
continue;
}
let pack_id = pack.metadata().pack_id.clone();
let configs = agent_configs_from_manifest(&pack_id, &blobs);
for (agent_id, agent_config) in configs {
if let Some(existing) = pack_agents.get(&agent_id) {
tracing::warn!(
agent_id,
prior_pack = existing.agent_id.as_str(),
new_pack = pack_id.as_str(),
"agent_id collision across packs; last pack wins"
);
}
pack_agents.insert(agent_id, agent_config);
}
}
// Operator config overrides pack-provided agents on collision.
let merged_agents = merge_agent_sources(pack_agents, config.agents.clone());
// First-boot ingest of any pack-baked knowledge corpus (W4 4c), handed
// to every registered agent-runtime extension. Runs BEFORE the agent
// runtime mounts its serving knowledge connection: embedded SurrealDB
// allows one handle per store directory, so the temporary ingest
// connection must open and drop before the serving mount (inside
// build_agent_node_handler) opens its own. No-op when no extension is
// registered or no pack carries a corpus. `runtime_ext`'s
// `boot_ingests_before_any_runtime_is_built` pins this order.
crate::runner::runtime_ext::ingest_all_corpora(&pack_runtimes, &config.tenant_ctx())
.await;
// DwAgent state-store selection. With GREENTIC_AW_REDIS_URL set, use the
// Redis-backed stores. Without it, a `desktop-agent-ephemeral` build
// uses its own process-global in-memory stores; every OTHER build
// (greentic-start, the distroless image) goes through
// `build_aw_backends`, which with no Redis URL auto-selects the
// shared in-memory KV (or redb under GREENTIC_AW_STATE_BACKEND=disk).
// So a missing Redis URL does NOT disable dw.agent in any build. The
// runtime is absent only when there are no agents, when
// GREENTIC_AW_STATE_BACKEND=redis names no URL, when Redis is
// unreachable, or when the extension runtime fails to initialise.
let redis_set = std::env::var("GREENTIC_AW_REDIS_URL")
.map(|v| !v.is_empty())
.unwrap_or(false);
// Best-effort agent-step audit sink (EPIC-B B-3), built from the
// same (possibly connected) NATS client the flow-level audit sink
// (B-2) uses. `None` when NATS is unset/unreachable, which keeps
// `dw.agent` execution on the plain `AgentRuntime::step` path
// (zero behaviour change).
let agent_audit_sink = audit_nats_client
.clone()
.map(crate::trace::audit_sink::AuditSink::new);
// `merged_agents` is MOVED into `build_agent_node_handler` below
// (redis/ephemeral branches); clone for the graph handler first so
// it can resolve a graph node's `agent_ref` (SP1) against the same
// process-level merged config map.
let graph_agents = merged_agents.clone();
// Also needed after `merged_agents` is moved into
// `build_agent_node_handler`/`_ephemeral` below, to resolve the
// in-process operala.call LLM key the same way (see the
// `operala-in-process` block after the DwAgent wiring).
#[cfg(feature = "operala-in-process")]
let operala_agents = merged_agents.clone();
// ONE billing sink for this unit, shared by dw.agent, agent-graph
// turns and in-process deep workers: the meter the embedding host
// installed (a deployed unit's `WorkerUsageMeter`), else the
// env-configured cloud-commerce sink, else none.
let billing_meter =
crate::runner::agent_node::resolve_billing_meter(installed_billing_meter);
let agent_handler = if redis_set {
crate::runner::agent_node::build_agent_node_wiring_metered(
merged_agents,
config.tenant.clone(),
Arc::clone(&secrets_manager),
ext_llm_port.clone(),
pack_runtimes.clone(),
agent_audit_sink.clone(),
stream_observers.clone(),
agent_project_id.clone(),
billing_meter.clone(),
user_ledger.clone(),
)
.await
} else {
#[cfg(feature = "desktop-agent-ephemeral")]
{
crate::runner::agent_node::build_agent_node_wiring_ephemeral_metered(
merged_agents,
config.tenant.clone(),
Arc::clone(&secrets_manager),
ext_llm_port.clone(),
pack_runtimes.clone(),
agent_audit_sink.clone(),
stream_observers.clone(),
agent_project_id.clone(),
billing_meter.clone(),
user_ledger.clone(),
)
.await
}
#[cfg(not(feature = "desktop-agent-ephemeral"))]
{
crate::runner::agent_node::build_agent_node_wiring_metered(
merged_agents,
config.tenant.clone(),
Arc::clone(&secrets_manager),
ext_llm_port.clone(),
pack_runtimes.clone(),
agent_audit_sink.clone(),
stream_observers.clone(),
agent_project_id.clone(),
billing_meter.clone(),
user_ledger.clone(),
)
.await
}
};
// The AgentRuntime behind dw.agent is also the tool surface of
// in-process deep workers (operala.call, below).
#[cfg(feature = "operala-in-process")]
let operala_agent_runtime = agent_handler
.as_ref()
.map(|wiring| Arc::clone(&wiring.runtime));
if let Some(wiring) = agent_handler {
nested_agent_handler = Some(Arc::clone(&wiring.handler));
engine.set_agent_node_handler(wiring.handler);
tracing::info!("DwAgent runtime wired into FlowEngine");
}
// In-process deep-worker runtime for `operala.call` nodes
// (`operala-in-process`; `desktop-agent-ephemeral` implies it, so
// the designer's offline Test-chat sidecar keeps it). Reuses the
// exact key-resolution policy the
// in-process dw.agent LLM backend uses (env key wins; otherwise
// the first agent's `llm.credential_ref` resolved from the
// per-tenant secrets store), then builds a
// `greentic_llm::RigBackend` — the same OpenAI-compatible,
// multi-provider client `GreenticLlmBackend` uses for dw.agent —
// and wraps it in `DeepWorkerInvoker`. No handler is wired (and
// `operala.call` falls back to the NATS `RemoteDispatchHandler`,
// failing without it) when no LLM key resolves or the provider
// fails to build.
#[cfg(feature = "operala-in-process")]
{
use crate::runner::operala_node::{
OPERALA_DISPATCH_ENV, OperalaSelection, select_operala_handler_metered,
};
use crate::runner::operala_tools::OperalaToolContext;
// Deep workers call their agent's bound tools through the SAME
// AgentRuntime dw.agent uses, so the two share one prerequisite.
// A missing Redis URL is NOT one (see the state-store selection
// above). Without a runtime — an explicit redis backend with no
// URL, an unreachable Redis, or a failed extension runtime, all of
// which also leave dw.agent unwired — deep workers run tool-less,
// which an operator must be able to see.
let operala_tools = match operala_agent_runtime {
Some(runtime) => Some(Arc::new(OperalaToolContext::new(
runtime,
&operala_agents,
agent_project_id.clone(),
))),
None => {
if operala_agents.values().any(|agent| !agent.tools.is_empty()) {
tracing::warn!(
tenant = %config.tenant,
"no agent runtime was built for this tenant (dw.agent is \
unwired too: GREENTIC_AW_STATE_BACKEND=redis without \
GREENTIC_AW_REDIS_URL, Redis unreachable, or the extension \
runtime failed; see the earlier log lines); operala.call deep \
workers will run WITHOUT the tools their agents declare"
);
}
None
}
};
// Provider/model are resolved PER WORKER from each
// `operala.call` node's `input.llm` binding (stamped by
// greentic-dw-authoring for authored deep-worker packs); the
// handler builds the LLM per dispatch. For a node that carries
// NO `input.llm` — e.g. an operala.call synthesized at runtime
// for a dw.agent's chronicle knowledge/memory retrieval — fall
// back to the agent's OWN configured provider/model (the same
// `operala_agents` the api_key is resolved from). The
// process-level env still OVERRIDES both. Only when neither the
// node, the agent config, nor the env carries a provider/model
// does the dispatch error explicitly.
let agent_llm = operala_agents
.values()
.map(|agent| &agent.llm)
.find(|llm| !llm.provider.trim().is_empty() && !llm.model.trim().is_empty());
let fallback_provider = std::env::var("GREENTIC_LLM_PROVIDER")
.ok()
.filter(|value| !value.trim().is_empty())
.or_else(|| agent_llm.map(|llm| llm.provider.clone()));
let fallback_model = std::env::var("GREENTIC_LLM_MODEL")
.ok()
.filter(|value| !value.trim().is_empty())
.or_else(|| agent_llm.map(|llm| llm.model.clone()));
let base_url = std::env::var("GREENTIC_LLM_BASE_URL")
.ok()
.filter(|value| !value.trim().is_empty());
// Same key policy the in-process dw.agent backend uses: env key
// wins; otherwise the first agent's `llm.credential_ref` from the
// per-tenant secrets store.
let key_secrets = &secrets_manager;
let key_tenant = config.tenant.as_str();
let key_agents = &operala_agents;
let resolve_key = move || async move {
let env_key = std::env::var("GREENTIC_LLM_API_KEY")
.ok()
.filter(|value| !value.trim().is_empty())
.or_else(|| {
std::env::var("OPENAI_API_KEY")
.ok()
.filter(|value| !value.trim().is_empty())
});
match env_key {
Some(key) => Some(key),
None => {
crate::runner::agent_node::resolve_in_process_llm_key(
key_secrets,
key_tenant,
key_agents,
)
.await
}
}
};
let dispatch_env = std::env::var(OPERALA_DISPATCH_ENV).ok();
match select_operala_handler_metered(
dispatch_env.as_deref(),
resolve_key,
base_url,
fallback_provider,
fallback_model,
operala_tools,
// The deep worker's OWN loop bills through the same sink
// as dw.agent, attributed to the same unit.
billing_meter.clone(),
agent_project_id.clone(),
)
.await
{
OperalaSelection::InProcess(handler) => {
engine.set_operala_node_handler(handler);
tracing::info!(
dispatch = "in-process",
"operala.call in-process deep-worker runtime wired into FlowEngine \
(provider/model resolved per-worker from node input.llm)"
);
}
OperalaSelection::Nats => {
tracing::info!(
dispatch = "nats",
"GREENTIC_OPERALA_DISPATCH=nats: operala.call dispatches over NATS; \
in-process deep-worker handler not wired"
);
if std::env::var("GREENTIC_EVENTS_NATS_URL")
.ok()
.filter(|value| !value.trim().is_empty())
.is_none()
{
tracing::warn!(
"GREENTIC_OPERALA_DISPATCH=nats but GREENTIC_EVENTS_NATS_URL is \
unset; operala.call nodes will fail (no remote dispatch \
handler). Set the NATS URL or unset the flag."
);
}
}
OperalaSelection::NoKey => {
tracing::warn!(
dispatch = "nats",
"no LLM API key resolved (env or store) for operala.call \
in-process wiring; operala.call nodes will fall back to NATS \
(and fail without it)"
);
}
}
}
// Collect agent-graph sidecars from each pack. Unlike agents (a
// manifest.cbor map), graphs arrive as a pack FILE (`agent-graph.json`)
// — one sidecar per pack — so the graph is keyed by `pack_id`. A
// sidecar that fails UTF-8 / JSON / schema validation is logged and
// skipped (lenient, mirroring `agent_configs_from_manifest`) so a bad
// graph never blocks the rest of pack loading. When the same pack_id
// appears twice (overlay), the last pack wins.
let mut graphs: HashMap<String, greentic_aw_runtime::graph::GraphConfig> =
HashMap::new();
for pack in &pack_runtimes {
let Some(bytes) = pack.read_agent_graph_sidecar() else {
continue;
};
let pack_id = pack.metadata().pack_id.clone();
if let Some(config) =
crate::runner::graph_node::graph_config_from_sidecar(&pack_id, &bytes)
&& graphs.insert(pack_id.clone(), config).is_some()
{
tracing::warn!(
pack_id = pack_id.as_str(),
"agent-graph sidecar for pack_id seen twice; last pack wins"
);
}
}
// Producer/operator-declared graphs (HostConfig.graphs) override
// pack-sidecar graphs on `graph_id` collision — mirroring the
// operator-wins merge for agents.
for (graph_id, graph_config) in config.graphs.clone() {
graphs.insert(graph_id, graph_config);
}
// Tenant, secrets manager and deployed unit are the same three
// values the `dw.agent` handler above receives, so a graph turn's
// `a2a:` tools resolve the same credentials a single-turn worker's
// would.
if let Some(handler) = crate::runner::graph_node::build_graph_node_handler_metered(
graphs,
agent_audit_sink.clone(),
Arc::new(pack_runtimes.clone()),
graph_agents,
config.tenant.clone(),
Arc::clone(&secrets_manager),
agent_project_id.clone(),
billing_meter.clone(),
)
.await
{
engine.set_graph_node_handler(handler);
tracing::info!("DwAgentGraph runtime wired into FlowEngine");
}
}
// Resolve how `dw.agent` nodes dispatch. When `GREENTIC_AW_DISPATCH=nats`
// is set, the node is rerouted over the durable agentic NATS path instead
// of the in-process handler. Must be wired while `engine` is still owned.
#[cfg(feature = "agentic-worker")]
{
let dw_dispatch =
crate::runner::agent_node::dw_agent_dispatch_mode(|k| std::env::var(k).ok());
engine.set_dw_agent_dispatch(dw_dispatch);
// Lend the handler to flow-tool engines, on the SAME
// `Arc<PackRuntime>`s the agent runtime's flow invoker holds (the
// slot lives on the instance). Only for in-process dispatch: over
// NATS a nested engine has no remote handler and must keep
// failing loudly. `GREENTIC_AW_NESTED_FLOW_AGENTS=0` opts out.
// The opt-out is reported only when it changed something: with
// nothing to lend (NATS, no handler) there is nothing opted out of.
if let Some(handlers) =
crate::runner::nested_flow::for_dispatch(dw_dispatch, nested_agent_handler.as_ref())
{
if crate::runner::nested_flow::nested_flow_agents_enabled() {
for pack in &pack_runtimes {
pack.set_nested_flow_handlers(handlers.clone());
}
tracing::info!("dw.agent handler lent to flow-tool engines");
} else {
tracing::info!(
env = crate::runner::nested_flow::NESTED_FLOW_AGENTS_ENV,
"dw.agent handler not lent to flow-tool engines (opted out)"
);
}
}
if matches!(
dw_dispatch,
crate::runner::agent_node::DwAgentDispatch::Nats
) && std::env::var("GREENTIC_EVENTS_NATS_URL")
.ok()
.filter(|s| !s.is_empty())
.is_none()
{
tracing::warn!(
"GREENTIC_AW_DISPATCH=nats but GREENTIC_EVENTS_NATS_URL is unset; \
dw.agent nodes will fail (no remote dispatch handler). \
Set the NATS URL or unset the flag."
);
}
}
let engine = Arc::new(engine);
let state_machine = Arc::new(
StateMachineRuntime::from_flow_engine_with_run_outcome_sink(
Arc::clone(&config),
Arc::clone(&engine),
pack_trace,
session_host,
Arc::clone(&session_store),
state_host,
Arc::clone(&secrets_manager),
mocks.clone(),
audit_nats_client,
run_outcome_sink,
)
.context("failed to initialise state machine runtime")?,
);
// The inbox resumes through a STRICT resumer: a decision for a gate
// that is no longer parked under exactly its nonced id is dropped and
// never starts a fresh run.
if let Some(inbox) = &approval_inbox {
inbox.attach_resumer(Arc::new(
crate::runner::runtime_session_resumer::RuntimeSessionResumer::strict(Arc::clone(
&state_machine,
)),
));
}
// Spawn the response listeners now that the ingress handle
// (`state_machine`) exists. Each listener resumes paused flows by feeding
// a synthesized ingress envelope through `StateMachineRuntime::handle`
// (see `RuntimeSessionResumer`). The resumer is runtime-agnostic (it
// resumes by correlation id), so one shared resumer serves all runtimes;
// we run one listener per runtime so every `*.call` node's responses
// (`greentic.<runtime>.response.v1`) are consumed. Only started when the
// dispatcher above connected successfully.
if let Some(client) = dispatch_nats_client {
let resumer = Arc::new(
crate::runner::runtime_session_resumer::RuntimeSessionResumer::new(Arc::clone(
&state_machine,
)),
);
for runtime_name in ["sorla", "operala", "agentic", "telco-x", "approval"] {
tokio::spawn(crate::runner::dispatch_listener::run_response_listener(
client.clone(),
runtime_name.to_string(),
Arc::clone(&resumer)
as Arc<dyn crate::runner::dispatch_listener::SessionResumer>,
));
}
// Eagerly pre-cache local-wasm MCP components when the admin publishes
// a warm event. Feature-gated behind `agentic-worker` because
// `mcp_store_pull` lives in `greentic-aw-runtime` which is only
// present when that feature is enabled.
#[cfg(feature = "agentic-worker")]
tokio::spawn(crate::runner::mcp_warm_listener::run_mcp_warm_listener(
client.clone(),
));
tracing::info!(
"Remote-dispatch (NATS) wired into runtime: sorla.call / operala.call / agentic.call / telco-x.call"
);
}
let http_client = Client::builder().build()?;
Ok(Arc::new(Self {
tenant: config.tenant.clone(),
config,
packs: pack_runtimes,
digests,
engine,
state_machine,
session_store,
http_client,
mocks,
timer_handles: Mutex::new(Vec::new()),
secrets: secrets_manager,
operator_registry,
operator_metrics,
contract_cache: ContractCache::from_env(),
approval_inbox,
}))
}
pub fn tenant(&self) -> &str {
&self.tenant
}
pub fn config(&self) -> &Arc<HostConfig> {
&self.config
}
pub fn operator_registry(&self) -> &OperatorRegistry {
&self.operator_registry
}
pub fn operator_metrics(&self) -> &OperatorMetrics {
&self.operator_metrics
}
pub fn contract_cache(&self) -> &ContractCache {
&self.contract_cache
}
pub fn contract_cache_stats(&self) -> ContractCacheStats {
self.contract_cache.stats()
}
pub fn main_pack(&self) -> &Arc<PackRuntime> {
self.packs
.first()
.expect("tenant runtime must contain at least one pack")
}
pub fn pack(&self) -> Arc<PackRuntime> {
Arc::clone(self.main_pack())
}
pub fn overlays(&self) -> Vec<Arc<PackRuntime>> {
self.packs.iter().skip(1).cloned().collect()
}
/// All packs in declaration order: main pack at index 0, overlays after.
/// Borrowed slice — no `Arc` clones, no allocation. Use this when you only
/// need to iterate the full pack list; prefer [`pack`]/[`overlays`] when
/// you need to hand out owned `Arc`s downstream.
///
/// [`pack`]: TenantRuntime::pack
/// [`overlays`]: TenantRuntime::overlays
pub fn all_packs(&self) -> &[Arc<PackRuntime>] {
&self.packs
}
/// Resolved content digest of each loaded pack, index-aligned with the pack
/// list. `Some` for revision runtimes (verified at load) and the legacy
/// index path; `None` only when a digest was unavailable.
pub fn pack_digests(&self) -> &[Option<String>] {
&self.digests
}
pub fn engine(&self) -> &Arc<FlowEngine> {
&self.engine
}
pub fn state_machine(&self) -> &Arc<StateMachineRuntime> {
&self.state_machine
}
/// Shared session store. M1.5: lets `apply_welcome_flow_override`
/// build a `FlowResumeStore` against the SAME bucket the state machine
/// will read/write — important under revision mode where each revision
/// is given its own store via `load_revision`.
pub fn session_store(&self) -> &DynSessionStore {
&self.session_store
}
pub fn http_client(&self) -> &Client {
&self.http_client
}
pub fn oauth_config(&self) -> Option<OAuthBrokerConfig> {
self.config.oauth_broker_config()
}
pub fn digest(&self) -> Option<&str> {
self.digests.first().and_then(|d| d.as_deref())
}
pub fn overlay_digests(&self) -> Vec<Option<String>> {
self.digests.iter().skip(1).cloned().collect()
}
pub fn required_secrets(&self) -> Vec<SecretRequirement> {
self.packs
.iter()
.flat_map(|pack| pack.required_secrets().iter().cloned())
.collect()
}
pub fn missing_secrets(&self) -> Vec<SecretRequirement> {
self.packs
.iter()
.flat_map(|pack| pack.missing_secrets(&self.config.tenant_ctx()))
.collect()
}
pub fn mocks(&self) -> Option<&Arc<MockLayer>> {
self.mocks.as_ref()
}
pub fn register_timers(&self, handles: Vec<JoinHandle<()>>) {
self.timer_handles.lock().extend(handles);
}
/// Read a RUNTIME-level secret, at the `_runner` pseudo-pack segment.
///
/// **Deliberately NOT unit-scoped**, unlike every pack secret a component
/// reads (see [`crate::secrets::unit_pack_segment`]). Its only caller is
/// the operator HTTP attachments path (`runner::operator::resolve_attachments`),
/// and `_runner` is not a deployed pack: nothing stages a per-unit value
/// there, in any lane. Scoping it per unit would move an address no writer
/// produces, so every currently-working `_runner` secret would resolve only
/// through the compatibility fallback — a strictly worse address for no
/// isolation gained. Revisit only if a per-unit writer for `_runner`
/// appears.
pub fn get_secret(&self, key: &str) -> Result<String> {
if crate::provider_core_only::is_enabled() {
bail!(crate::provider_core_only::blocked_message("secrets"))
}
if !self.config.secrets_policy.is_allowed(key) {
bail!("secret {key} is not permitted by bindings policy");
}
let ctx = self.config.tenant_ctx();
let canonical_key = canonicalize_secret_key(key);
let bytes =
read_secret_blocking(&self.secrets, &ctx, RUNTIME_SECRETS_PACK_ID, &canonical_key)
.context("failed to read secret from manager")?;
let value = String::from_utf8(bytes).context("secret value is not valid UTF-8")?;
Ok(value)
}
pub fn build_events_email_execution_plan(
&self,
tenant: &greentic_types::TenantCtx,
request: &EmailSendRequest,
) -> Result<EmailExecutionPlan> {
let oauth = self
.oauth_config()
.ok_or_else(|| anyhow!("oauth broker config is not configured for tenant runtime"))?;
build_email_execution_plan(&oauth, tenant, request)
}
pub async fn execute_events_email_request(
&self,
access_token: &str,
request: &EmailSendRequest,
) -> Result<()> {
execute_email_request(self.http_client(), access_token, request).await
}
pub async fn execute_events_email_with_oauth(
&self,
tenant: &greentic_types::TenantCtx,
request: &EmailSendRequest,
) -> Result<()> {
let plan = self.build_events_email_execution_plan(tenant, request)?;
let token = request_resource_token(self.http_client(), &plan.token_request).await?;
self.execute_events_email_request(&token.access_token, request)
.await
}
pub fn pack_for_component(&self, component_ref: &str) -> Option<Arc<PackRuntime>> {
self.packs
.iter()
.find(|pack| pack.contains_component(component_ref))
.cloned()
}
pub fn pack_for_component_with_digest(
&self,
component_ref: &str,
) -> Option<(Arc<PackRuntime>, Option<String>)> {
self.packs
.iter()
.zip(self.digests.iter())
.find(|(pack, _)| pack.contains_component(component_ref))
.map(|(pack, digest)| (Arc::clone(pack), digest.clone()))
}
pub fn resolve_component(&self, component_ref: &str) -> Option<ResolvedComponent> {
self.pack_for_component_with_digest(component_ref)
.map(|(pack, digest)| ResolvedComponent {
digest: digest
.or_else(|| self.digest().map(ToString::to_string))
.unwrap_or_else(|| "unknown".to_string()),
component_ref: component_ref.to_string(),
pack,
})
}
}
impl Drop for TenantRuntime {
fn drop(&mut self) {
for handle in self.timer_handles.lock().drain(..) {
handle.abort();
}
if let Some(inbox) = &self.approval_inbox {
inbox.shutdown();
}
}
}
#[cfg(test)]
mod runtime_key_tests {
use super::*;
#[test]
fn legacy_keys_match_only_on_tenant() {
assert_eq!(RuntimeKey::legacy("acme"), RuntimeKey::legacy("acme"));
assert_ne!(RuntimeKey::legacy("acme"), RuntimeKey::legacy("other"));
}
#[test]
fn legacy_and_revision_keys_never_collide() {
let key = RuntimeKey::revision(
"acme",
DeploymentId::new(),
BundleId::from("bundle-a"),
RevisionId::new(),
);
assert_ne!(RuntimeKey::legacy("acme"), key);
}
#[test]
fn revision_keys_distinguish_revision_id() {
let deployment = DeploymentId::new();
let bundle = BundleId::from("bundle-a");
let rev_a = RevisionId::new();
let rev_b = RevisionId::new();
let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
let key_b = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_b);
let same = RuntimeKey::revision("acme", deployment, bundle, rev_a);
assert_ne!(key_a, key_b);
assert_eq!(key_a, same);
}
#[test]
fn legacy_reload_preserves_revision_entries() {
let revision_key = RuntimeKey::revision(
"acme",
DeploymentId::new(),
BundleId::from("bundle-a"),
RevisionId::new(),
);
let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
prev.insert(RuntimeKey::legacy("acme"), 1); // stale legacy, refreshed below
prev.insert(RuntimeKey::legacy("retired"), 2); // dropped: not in new index
prev.insert(revision_key.clone(), 99); // revision runtime: must survive
let mut legacy: HashMap<RuntimeKey, u32> = HashMap::new();
legacy.insert(RuntimeKey::legacy("acme"), 10);
legacy.insert(RuntimeKey::legacy("newcomer"), 20);
let next = merge_legacy_reload(&prev, legacy);
assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&10));
assert_eq!(next.get(&RuntimeKey::legacy("newcomer")), Some(&20));
assert_eq!(next.get(&RuntimeKey::legacy("retired")), None);
assert_eq!(next.get(&revision_key), Some(&99));
}
#[test]
fn remove_keyed_entry_pops_only_the_targeted_key() {
let deployment = DeploymentId::new();
let bundle = BundleId::from("bundle-a");
let rev_a = RevisionId::new();
let rev_b = RevisionId::new();
let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
let key_b = RuntimeKey::revision("acme", deployment, bundle, rev_b);
let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
prev.insert(RuntimeKey::legacy("acme"), 1);
prev.insert(key_a.clone(), 10);
prev.insert(key_b.clone(), 20);
let (next, removed) = remove_keyed_entry(&prev, &key_a).expect("present");
assert_eq!(removed, 10);
assert_eq!(next.get(&key_a), None);
assert_eq!(next.get(&key_b), Some(&20));
assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&1));
}
#[test]
fn remove_keyed_entry_returns_none_for_missing_key() {
let prev: HashMap<RuntimeKey, u32> = HashMap::new();
let ghost = RuntimeKey::revision(
"acme",
DeploymentId::new(),
BundleId::from("bundle-a"),
RevisionId::new(),
);
assert!(remove_keyed_entry(&prev, &ghost).is_none());
}
#[test]
fn remove_keyed_entry_leaves_other_deployments_alone() {
let bundle = BundleId::from("bundle-a");
let dep_a = DeploymentId::new();
let dep_b = DeploymentId::new();
let rev = RevisionId::new();
let key_a = RuntimeKey::revision("acme", dep_a, bundle.clone(), rev);
let key_b = RuntimeKey::revision("acme", dep_b, bundle, rev);
let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
prev.insert(key_a.clone(), 100);
prev.insert(key_b.clone(), 200);
let (next, removed) = remove_keyed_entry(&prev, &key_a).expect("present");
assert_eq!(removed, 100);
assert_eq!(next.get(&key_b), Some(&200));
assert_eq!(next.len(), 1);
}
#[test]
fn map_lookup_separates_legacy_from_revision() {
let deployment = DeploymentId::new();
let bundle = BundleId::from("bundle-a");
let revision = RevisionId::new();
let mut map: HashMap<RuntimeKey, u32> = HashMap::new();
map.insert(RuntimeKey::legacy("acme"), 1);
map.insert(
RuntimeKey::revision("acme", deployment, bundle.clone(), revision),
2,
);
assert_eq!(map.get(&RuntimeKey::legacy("acme")), Some(&1));
assert_eq!(
map.get(&RuntimeKey::revision("acme", deployment, bundle, revision)),
Some(&2)
);
assert_eq!(map.get(&RuntimeKey::legacy("ghost")), None);
}
#[test]
fn insert_keyed_entry_adds_revision_preserving_legacy_and_siblings() {
let deployment = DeploymentId::new();
let bundle = BundleId::from("bundle-a");
let rev_a = RevisionId::new();
let rev_b = RevisionId::new();
let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
let key_b = RuntimeKey::revision("acme", deployment, bundle, rev_b);
let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
prev.insert(RuntimeKey::legacy("acme"), 1);
prev.insert(key_a.clone(), 10);
let next = insert_keyed_entry(&prev, key_b.clone(), 20);
// New revision lands; legacy entry and the sibling revision survive.
assert_eq!(next.get(&key_b), Some(&20));
assert_eq!(next.get(&key_a), Some(&10));
assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&1));
assert_eq!(next.len(), 3);
}
#[test]
fn insert_keyed_entry_replaces_existing_revision() {
let key = RuntimeKey::revision(
"acme",
DeploymentId::new(),
BundleId::from("bundle-a"),
RevisionId::new(),
);
let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
prev.insert(key.clone(), 10);
let next = insert_keyed_entry(&prev, key.clone(), 99);
assert_eq!(next.get(&key), Some(&99));
assert_eq!(next.len(), 1);
}
}
#[cfg(all(test, feature = "agentic-worker"))]
#[path = "runtime_billing_ratchet_tests.rs"]
mod runtime_billing_ratchet_tests;