ares-agent 0.11.4

Agent orchestration for ARES
Documentation
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
//! Agent execution service — single place handling conversation history loading,
//! memory injection, tool coordination, observability, usage/cost, token budget,
//! and loop detection.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use ares_types::types::{AppError, ContentPart, Message};
use cordis::{Context, CordisError, EventsService, Service};
use futures::StreamExt;

/// SSE token stream: text chunks only. Tool calls stay inside the loop.
pub type TokenStream =
    Pin<Box<dyn futures::Stream<Item = Result<String, AppError>> + Send + 'static>>;

fn once_text_stream(text: String) -> TokenStream {
    Box::pin(async_stream::stream! {
        yield Ok(text);
    })
}

#[cfg(feature = "postgres")]
struct PreparedResolvedAgent {
    agent: crate::ConfigurableAgent,
    source: AgentSource,
    user_id: String,
    run_id: String,
    agent_context: ares_types::types::AgentContext,
}

/// Result of `Execute::run` including resolution metadata.
///
/// This allows callers (v1/chat, scheduler, pipeline) to record which source the agent
/// came from and what config was used, without re-resolving.
/// Resolution tier label returned alongside the executed agent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AgentSource {
    User,
    Community,
    System,
}

impl AgentSource {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::User => "user",
            Self::Community => "community",
            Self::System => "system",
        }
    }
}

#[derive(Debug, Clone)]
pub struct ExecutionResult {
    /// The agent's response.
    pub response: crate::AgentResponse,
    /// Source tier where the agent was resolved (tenant/community/system).
    pub source: AgentSource,
    /// Name of the agent that was executed.
    pub agent_name: String,
    /// Run ID for correlation with ActiveRuns.
    pub run_id: String,
}

use crate::AgentResponse;

pub use ares_tools::Tools;

/// Canonical per-request model override used by the LLM interceptor.
///
/// Re-exporting the LLM type keeps context interception and provider policy
/// enforcement on the same `TypeId` across the agent and server crates.
pub use ares_llm::ModelOverride;

/// Request for unified agent execution.
///
/// Carries the minimal fields needed to execute any agent via the single
/// `Execute::run` entry-point.
#[derive(Clone, Default)]
pub struct AgentRequest {
    /// Agent name to execute.
    pub agent_name: String,
    /// Current user message.
    pub message: String,
    /// Prior conversation history (explicitly passed; may be augmented by
    /// `TenantDb` when available).
    pub history: Vec<Message>,
    /// Optional per-request context provider override (overrides service-level
    /// provider when `Some`).
    pub ctx_provider: Option<Arc<dyn crate::context_provider::ContextProvider>>,
    /// Multimodal parts for the current user turn (HTTP persists these via add_message_with_parts).
    pub parts: Vec<ContentPart>,
    /// OpenAI Responses continuation id for this turn.
    pub previous_response_id: Option<String>,
    /// When true, enable the LLM provider's built-in web search.
    pub web_search: bool,
}

/// Internal marker for skill-triggered executions.
///
/// Background engines attach this marker to their tenant-scoped request
/// context and still cross the same public `Execute::run` boundary as regular
/// agent requests. Keeping the marker in the context avoids a second public
/// execution API or changes to the request shape used by downstream crates.
#[derive(Clone)]
pub(crate) struct SkillDispatch {
    pub(crate) skill_id: String,
    pub(crate) tenant_id: String,
    pub(crate) input: serde_json::Value,
    pub(crate) run_id: String,
}

impl SkillDispatch {
    pub(crate) fn new(
        skill_id: impl Into<String>,
        tenant_id: impl Into<String>,
        input: serde_json::Value,
        run_id: impl Into<String>,
    ) -> Self {
        Self {
            skill_id: skill_id.into(),
            tenant_id: tenant_id.into(),
            input,
            run_id: run_id.into(),
        }
    }
}

impl Service for SkillDispatch {}

impl std::fmt::Debug for AgentRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AgentRequest")
            .field("agent_name", &self.agent_name)
            .field("message", &self.message)
            .field("history_len", &self.history.len())
            .field(
                "ctx_provider",
                &self.ctx_provider.as_ref().map(|_| "Some(ContextProvider)"),
            )
            .field("parts_len", &self.parts.len())
            .field("previous_response_id", &self.previous_response_id)
            .field("web_search", &self.web_search)
            .finish()
    }
}

/// Apply per-turn generation hints on a resolved LLM client.
pub fn apply_generation_hints(
    client: &dyn ares_llm::LLMClient,
    web_search: bool,
    previous_response_id: Option<String>,
) {
    if !web_search && previous_response_id.is_none() {
        return;
    }
    client.set_hints(ares_llm::GenerationHints {
        web_search,
        previous_response_id,
        ..Default::default()
    });
}

/// Build the in-flight user turn, attaching multimodal parts and a continuation id.
pub fn user_message_with_parts(
    content: impl Into<String>,
    parts: Vec<ContentPart>,
    previous_response_id: Option<String>,
) -> ares_llm::coordinator::ConversationMessage {
    let mut msg = ares_llm::coordinator::ConversationMessage::user(content);
    msg.parts = parts;
    msg.previous_response_id = previous_response_id;
    msg
}

/// Unified agent execution service — the single place handling:
///
/// - conversation history loading (`TenantDb`)
/// - memory injection (`ContextProvider`)
/// - `ToolCoordinator` loop
/// - fallback LLM chain (`Coordinator`)
/// - observability sink (`run_history` + `agent_runs`)
/// - usage/cost aggregation
/// - token budget check
/// - loop detection
///
/// Reachable via `ctx.get::<Execute>()` (see `Service` impl).
#[derive(Clone)]
pub struct Execute {
    context_provider: Option<Arc<dyn crate::context_provider::ContextProvider>>,
    /// Agent registry for creating agents from config (Phase 4 §15).
    agent_registry: Option<Arc<crate::registry::AgentRegistry>>,
    /// Run tracker for observability (Phase 4: extracted from root crate ActiveRuns).
    run_tracker: Option<Arc<dyn RunTracker>>,
    /// Fail closed instead of falling back: when `true`, every echo/fallback
    /// path in `execute` returns `Err` so consumers never receive echoed
    /// input or fallback-LLM content mistaken for a real agent run.
    strict_fallbacks: bool,
}

impl Execute {
    /// Create a new service with no backing stores (useful for tests and
    /// `cargo check --no-default-features`).
    pub fn new() -> Self {
        Self {
            context_provider: None,
            agent_registry: None,
            run_tracker: None,
            strict_fallbacks: false,
        }
    }

    /// Enable strict fallback mode: every echo/fallback entry in `execute`
    /// returns `Err(AppError::Unavailable)` whose message starts with
    /// `strict_fallbacks:` instead of echoing the request.
    pub fn with_strict_fallbacks(mut self, strict: bool) -> Self {
        self.strict_fallbacks = strict;
        self
    }

    /// Whether strict fallback mode is enabled.
    pub fn strict_fallbacks(&self) -> bool {
        self.strict_fallbacks
    }

    /// Emit the `agent.started` event through the Cordis event bus with
    /// `Dispatch::Parallel`, which fans out to every registered observer
    /// concurrently and awaits all of them before returning (join-all).
    ///
    /// If no `EventsService` is present in the context, or the dispatch
    /// errors, the original `payload` is returned unchanged so callers never
    /// lose data.
    pub async fn emit_agent_started(
        &self,
        ctx: &Arc<Context>,
        payload: cordis::AgentStartedPayload,
    ) -> serde_json::Value {
        let value = match serde_json::to_value(&payload) {
            Ok(v) => v,
            Err(_) => return serde_json::to_value(payload).unwrap_or(serde_json::Value::Null),
        };
        let Some(events) = ctx.get::<cordis::EventsService>() else {
            return value;
        };
        events
            .dispatch_typed::<cordis::AgentStartedEvent>(&payload)
            .await
            .unwrap_or(value)
    }

    /// Fire-and-forget observability event via Cordis `Dispatch::Emit`.
    ///
    /// Returns immediately without waiting for handlers. Missing `EventsService`
    /// is a no-op. Usage snapshot recording stays in server middleware
    /// (`UsageContext` is not in this crate).
    pub async fn emit_observability(
        &self,
        ctx: &Arc<Context>,
        event: impl Into<String>,
        payload: serde_json::Value,
    ) {
        let Some(events) = ctx.get::<cordis::EventsService>() else {
            return;
        };
        let _ = events
            .dispatch(event.into(), payload, cordis::Dispatch::Emit)
            .await;
    }

    /// Typed fire-and-forget variant of [`emit_observability`]: dispatches the
    /// payload struct for its catalog-bound event via `Dispatch::Emit`.
    pub async fn emit_observability_typed<E: cordis::TypedEvent>(
        &self,
        ctx: &Arc<Context>,
        payload: &E::Payload,
    ) {
        let Some(events) = ctx.get::<cordis::EventsService>() else {
            return;
        };
        let _ = events.dispatch_typed::<E>(payload).await;
    }

    /// Attach a context provider for memory injection.
    pub fn with_context_provider(
        mut self,
        provider: Arc<dyn crate::context_provider::ContextProvider>,
    ) -> Self {
        self.context_provider = Some(provider);
        self
    }

    /// Attach an agent registry for creating agents from resolved configs.
    pub fn with_agent_registry(mut self, registry: Arc<crate::registry::AgentRegistry>) -> Self {
        self.agent_registry = Some(registry);
        self
    }

    /// Attach a run tracker for observability.
    pub fn with_run_tracker(mut self, tracker: Arc<dyn RunTracker>) -> Self {
        self.run_tracker = Some(tracker);
        self
    }

    /// Host-injected run tracker, if any.
    pub fn run_tracker(&self) -> Option<&Arc<dyn RunTracker>> {
        self.run_tracker.as_ref()
    }

    /// Execute an agent by name using the full pipeline: resolve → create → execute.
    ///
    /// This is the PRIMARY entry point that handlers should call. It:
    /// 1. Resolves the agent via crate-private `Resolver` (3-tier: tenant → community → system)
    /// 2. Creates the agent via `AgentRegistry::create_agent_from_config_with_fallbacks`
    /// 3. Calls `agent.execute(message, context)` with the request ctx bound
    /// 4. Returns `ExecutionResult` with response + resolution metadata
    ///
    /// Run tracking (start/finish) is handled internally via `RunTracker`.
    pub async fn run(
        &self,
        req: &AgentRequest,
        ctx: &Arc<Context>,
    ) -> std::result::Result<ExecutionResult, AppError> {
        crate::admit(ctx).await?;
        let Some(events) = ctx.get::<EventsService>() else {
            return self.run_resolved_or_execute(req, ctx).await;
        };
        let payload = serde_json::to_value(cordis::AgentRunRequest {
            agent_name: req.agent_name.clone(),
            message: req.message.clone(),
        })
        .unwrap_or(serde_json::Value::Null);
        let execute = self.clone();
        let ctx_owned = Arc::clone(ctx);
        let orig = req.clone();
        let out = events
            .waterfall_around(
                cordis::events_catalog::ev::AGENT_RUN.to_string(),
                payload,
                move |payload| async move {
                    let mut run_req = orig;
                    if let Some(name) = payload.get("agent_name").and_then(|v| v.as_str()) {
                        run_req.agent_name = name.to_string();
                    }
                    if let Some(msg) = payload.get("message").and_then(|v| v.as_str()) {
                        run_req.message = msg.to_string();
                    }
                    match execute.run_resolved_or_execute(&run_req, &ctx_owned).await {
                        Ok(er) => Ok(serde_json::json!({
                            "content": er.response.content,
                            "usage": er.response.usage,
                            "metadata": er.response.metadata.as_ref().map(|m| {
                                serde_json::json!({
                                    "model_name": m.model_name,
                                    "provider_name": m.provider_name,
                                })
                            }),
                            "source": er.source,
                            "agent_name": er.agent_name,
                            "run_id": er.run_id,
                        })),
                        Err(e) => Err(CordisError::Fiber(e.to_string())),
                    }
                },
            )
            .await
            .map_err(|e| AppError::Internal(e.to_string()))?;
        if out.get("deny").and_then(|v| v.as_bool()) == Some(true) {
            let reason = out
                .get("reason")
                .and_then(|v| v.as_str())
                .unwrap_or("agent.run denied");
            return Err(AppError::InvalidInput(reason.to_string()));
        }
        let content = out
            .get("content")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let agent_name = out
            .get("agent_name")
            .and_then(|v| v.as_str())
            .unwrap_or(&req.agent_name)
            .to_string();
        let run_id = out
            .get("run_id")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let source = out
            .get("source")
            .cloned()
            .and_then(|v| serde_json::from_value(v).ok())
            .unwrap_or(AgentSource::System);
        let usage = out
            .get("usage")
            .cloned()
            .and_then(|v| serde_json::from_value(v).ok());
        let metadata = out.get("metadata").and_then(|v| {
            Some(crate::ExecutionMetadata {
                model_name: v.get("model_name")?.as_str()?.to_string(),
                provider_name: v.get("provider_name")?.as_str()?.to_string(),
            })
        });
        Ok(ExecutionResult {
            response: AgentResponse {
                content,
                usage,
                metadata,
            },
            source,
            agent_name,
            run_id,
        })
    }

    /// Stream an agent response as text chunks. Tool calls stay inside the loop.
    ///
    /// Does not wrap in `agent.run` / `waterfall_around` — a stream cannot buffer JSON.
    pub async fn run_stream(
        &self,
        req: &AgentRequest,
        ctx: &Arc<Context>,
    ) -> Result<TokenStream, AppError> {
        crate::admit(ctx).await?;
        if let Some(dispatch) = ctx.get::<SkillDispatch>() {
            let result = self.run_skill(req, ctx, &dispatch).await?;
            return Ok(once_text_stream(result.response.content));
        }
        #[cfg(feature = "postgres")]
        {
            if let Some(prepared) = self.prepare_resolved_agent(req, ctx).await {
                let prepared = prepared?;
                let PreparedResolvedAgent {
                    agent,
                    source: _,
                    user_id,
                    run_id,
                    agent_context,
                } = prepared;
                let exec = self.clone();
                let ctx_owned = Arc::clone(ctx);
                let agent_name = req.agent_name.clone();
                match agent
                    .execute_stream(req.message.clone(), agent_context)
                    .await
                {
                    Ok(inner) => {
                        return Ok(Box::pin(async_stream::stream! {
                            let mut inner = inner;
                            let mut ok = true;
                            while let Some(item) = inner.next().await {
                                if item.is_err() {
                                    ok = false;
                                }
                                yield item;
                            }
                            exec.finish_resolved_run(
                                &ctx_owned,
                                &agent_name,
                                &user_id,
                                &run_id,
                                None,
                                ok,
                            )
                            .await;
                        }));
                    }
                    Err(e) => {
                        self.finish_resolved_run(
                            ctx,
                            &req.agent_name,
                            &user_id,
                            &run_id,
                            None,
                            false,
                        )
                        .await;
                        return Err(e);
                    }
                }
            }
        }
        self.execute_stream_fallback(req.clone(), ctx).await
    }

    async fn run_resolved_or_execute(
        &self,
        req: &AgentRequest,
        ctx: &Arc<Context>,
    ) -> std::result::Result<ExecutionResult, AppError> {
        if let Some(dispatch) = ctx.get::<SkillDispatch>() {
            return self.run_skill(req, ctx, &dispatch).await;
        }
        if let Some(result) = self.try_run_resolved(req, ctx).await {
            return result;
        }
        let response = self.execute(req.clone(), ctx).await?;
        Ok(ExecutionResult {
            response,
            source: AgentSource::System,
            agent_name: req.agent_name.clone(),
            run_id: uuid::Uuid::new_v4().to_string(),
        })
    }

    #[cfg(feature = "postgres")]
    async fn run_skill(
        &self,
        req: &AgentRequest,
        ctx: &Arc<Context>,
        dispatch: &SkillDispatch,
    ) -> std::result::Result<ExecutionResult, AppError> {
        let skill_engine = ctx
            .get::<crate::skills::SkillEngine>()
            .ok_or_else(|| AppError::Unavailable("SkillEngine is not provided".to_string()))?;
        let value = skill_engine
            .execute_skill(
                &dispatch.skill_id,
                &dispatch.tenant_id,
                dispatch.input.clone(),
                &dispatch.run_id,
                ctx,
            )
            .await
            .map_err(AppError::Internal)?;
        Ok(ExecutionResult {
            response: AgentResponse {
                content: serde_json::to_string(&value)
                    .map_err(|e| AppError::Internal(e.to_string()))?,
                usage: None,
                metadata: None,
            },
            source: AgentSource::System,
            agent_name: req.agent_name.clone(),
            run_id: dispatch.run_id.clone(),
        })
    }

    #[cfg(not(feature = "postgres"))]
    async fn run_skill(
        &self,
        _req: &AgentRequest,
        _ctx: &Arc<Context>,
        _dispatch: &SkillDispatch,
    ) -> std::result::Result<ExecutionResult, AppError> {
        Err(AppError::Unavailable(
            "SkillEngine requires postgres".to_string(),
        ))
    }

    async fn try_run_resolved(
        &self,
        req: &AgentRequest,
        ctx: &Arc<Context>,
    ) -> Option<std::result::Result<ExecutionResult, AppError>> {
        #[cfg(feature = "postgres")]
        {
            return self.run_resolved(req, ctx).await;
        }
        #[cfg(not(feature = "postgres"))]
        {
            let _ = (req, ctx);
            None
        }
    }

    #[cfg(feature = "postgres")]
    async fn prepare_resolved_agent(
        &self,
        req: &AgentRequest,
        ctx: &Arc<Context>,
    ) -> Option<std::result::Result<PreparedResolvedAgent, AppError>> {
        let registry_owned = self
            .agent_registry
            .clone()
            .or_else(|| ctx.get::<crate::registry::AgentRegistry>());
        let registry = registry_owned.as_ref()?;
        let resolver = ctx.get::<crate::resolver::Resolver>().or_else(|| {
            crate::resolver::Resolver::from_ctx(ctx, Arc::clone(registry)).map(Arc::new)
        })?;
        let resolved = resolver.resolve(ctx, &req.agent_name).await;
        let (user_agent, source) = match resolved {
            Ok(v) => v,
            Err(e) => return Some(Err(e)),
        };
        let user_id = user_id_from_ctx(ctx, "");

        let mut config = crate::configurable::agent_config_from_user_agent(&user_agent);
        if let (Some(policy), Some(ovr)) = (
            ctx.get::<ares_llm::TenantModelPolicy>(),
            ctx.get::<ModelOverride>(),
        ) {
            if let Err(e) = policy.authorize(&ovr.model) {
                return Some(Err(e));
            }
        }
        if let Some(ovr) = ctx.get::<ModelOverride>() {
            tracing::info!(model=%ovr.model, agent=%req.agent_name, "model overridden via Cordis intercept");
            config.model = ovr.model.clone();
        }

        let tenant_db = ctx.get::<ares_store::TenantDb>()?;
        let fleet_secrets = ctx.get::<ares_store::FleetSecrets>()?;

        let mut agent = match registry
            .create_agent_from_config_with_fallbacks(
                &req.agent_name,
                &config,
                &user_id,
                tenant_db.pool(),
                &fleet_secrets,
            )
            .await
        {
            Ok(a) => a,
            Err(e) => return Some(Err(e)),
        };
        if let Some(tools) = ctx.get::<ares_tools::Tools>() {
            agent.set_tools(tools);
        }
        agent.bind_request_ctx(ctx.clone());
        agent.set_user_turn(
            req.parts.clone(),
            req.previous_response_id.clone(),
            req.web_search,
        );

        let run_id = uuid::Uuid::new_v4().to_string();
        if let Some(tracker) = &self.run_tracker {
            tracker.start_run(
                &run_id,
                &user_id,
                &req.agent_name,
                Some("execution_service"),
            );
        }

        if ctx.get::<cordis::EventsService>().is_some() {
            let _ = self
                .emit_agent_started(
                    ctx,
                    cordis::AgentStartedPayload {
                        agent_name: req.agent_name.clone(),
                        run_id: run_id.clone(),
                        tenant: user_id.to_string(),
                        event: cordis::events_catalog::ev::AGENT_STARTED.to_string(),
                    },
                )
                .await;
        }

        let agent_context = ares_types::types::AgentContext {
            user_id: user_id.to_string(),
            session_id: format!("exec-{}", uuid::Uuid::new_v4()),
            conversation_history: req.history.clone(),
            user_memory: None,
        };

        Some(Ok(PreparedResolvedAgent {
            agent,
            source,
            user_id: user_id.to_string(),
            run_id,
            agent_context,
        }))
    }

    #[cfg(feature = "postgres")]
    async fn finish_resolved_run(
        &self,
        ctx: &Arc<Context>,
        agent_name: &str,
        user_id: &str,
        run_id: &str,
        usage: Option<&ares_llm::client::TokenUsage>,
        ok: bool,
    ) {
        if let Some(tracker) = &self.run_tracker {
            tracker.finish_run(run_id, if ok { "completed" } else { "failed" });
        }
        if let Some(usage) = usage {
            self.emit_observability_typed::<cordis::AgentUsageEvent>(
                ctx,
                &cordis::AgentUsagePayload {
                    tenant: Some(user_id.to_string()),
                    prompt: usage.prompt_tokens as i64,
                    completion: usage.completion_tokens as i64,
                    total: usage.total_tokens as i64,
                },
            )
            .await;
        }
        self.emit_observability_typed::<cordis::AgentCompletedEvent>(
            ctx,
            &cordis::AgentCompletedPayload {
                agent_name: agent_name.to_string(),
                run_id: run_id.to_string(),
                status: if ok { "completed" } else { "failed" }.to_string(),
                event: cordis::events_catalog::ev::AGENT_COMPLETED.to_string(),
            },
        )
        .await;
        if !ok {
            self.emit_observability_typed::<cordis::AgentFailedEvent>(
                ctx,
                &cordis::AgentFailedPayload {
                    agent_name: agent_name.to_string(),
                    run_id: run_id.to_string(),
                    tenant: user_id.to_string(),
                    event: cordis::events_catalog::ev::AGENT_FAILED.to_string(),
                },
            )
            .await;
        }
    }

    #[cfg(feature = "postgres")]
    async fn run_resolved(
        &self,
        req: &AgentRequest,
        ctx: &Arc<Context>,
    ) -> Option<std::result::Result<ExecutionResult, AppError>> {
        use crate::Agent;

        let prepared = match self.prepare_resolved_agent(req, ctx).await? {
            Ok(p) => p,
            Err(e) => return Some(Err(e)),
        };
        let PreparedResolvedAgent {
            agent,
            source,
            user_id,
            run_id,
            agent_context,
        } = prepared;
        let result = agent.execute(&req.message, &agent_context).await;
        self.finish_resolved_run(
            ctx,
            &req.agent_name,
            &user_id,
            &run_id,
            result.as_ref().ok().and_then(|r| r.usage.as_ref()),
            result.is_ok(),
        )
        .await;
        Some(result.map(|response| ExecutionResult {
            response,
            source,
            agent_name: req.agent_name.clone(),
            run_id,
        }))
    }

    /// LLM/tools path used when Resolver/TenantDb are absent on ctx.
    async fn execute(
        &self,
        req: AgentRequest,
        ctx: &Arc<Context>,
    ) -> Result<AgentResponse, AppError> {
        if let Some(tenant_db) = tenant_db(ctx) {
            let _pool = tenant_db.pool();
            tracing::debug!(history_len = req.history.len(), "history load via TenantDb");
            let _ = _pool;
        }

        if let (Some(policy), Some(ovr)) = (
            ctx.get::<ares_llm::TenantModelPolicy>(),
            ctx.get::<ModelOverride>(),
        ) {
            policy.authorize(&ovr.model)?;
        }

        let tenant = tenant_from_request_ctx(ctx, None);

        let mut injected_context: Option<String> = None;
        let provider_opt: Option<Arc<dyn crate::context_provider::ContextProvider>> = req
            .ctx_provider
            .clone()
            .or_else(|| self.context_provider.clone());
        if let Some(provider) = provider_opt {
            let tid = tenant.clone().unwrap_or_default();
            let rt_ctx = crate::context_provider::AgentRuntimeContext::new(
                tid.clone(),
                &req.agent_name,
                "agent_execution",
            );
            if let Some(s) = provider.get_context_for_run(&rt_ctx).await {
                tracing::debug!(
                    len = s.len(),
                    "memory injected via ContextProvider::get_context_for_run"
                );
                injected_context = Some(s);
            } else if let Some(s) = provider.get_context(&req.agent_name, &tid).await {
                tracing::debug!(
                    len = s.len(),
                    "memory injected via ContextProvider::get_context"
                );
                injected_context = Some(s);
            }
        }

        let tools = ctx.get::<ares_tools::Tools>().unwrap_or_else(|| {
            Arc::new(ares_tools::Tools::from_static(std::iter::empty::<
                Arc<dyn ares_tools::Tool>,
            >()))
        });
        let tool_definitions = tools.list(ctx);
        tracing::debug!(
            count = tool_definitions.len(),
            has_service = true,
            "tools resolved via Tools::list"
        );
        let _resolve_probe = tools.resolve(ctx, "__probe__");

        let system_prompt = if let Some(extra) = injected_context.clone() {
            format!(
                "{}

You are {}.",
                extra, req.agent_name
            )
        } else {
            format!("You are {}.", req.agent_name)
        };

        let mut base_messages: Vec<ares_llm::coordinator::ConversationMessage> = Vec::new();
        base_messages.push(ares_llm::coordinator::ConversationMessage::system(
            system_prompt.clone(),
        ));
        for msg in &req.history {
            let mut cm = match msg.role {
                ares_types::types::MessageRole::User => {
                    ares_llm::coordinator::ConversationMessage::user(&msg.content)
                }
                ares_types::types::MessageRole::Assistant => {
                    ares_llm::coordinator::ConversationMessage::assistant(&msg.content, vec![])
                }
                _ => ares_llm::coordinator::ConversationMessage::system(&msg.content),
            };
            cm.parts = msg.parts.clone();
            base_messages.push(cm);
        }
        base_messages.push(user_message_with_parts(
            req.message.clone(),
            req.parts.clone(),
            req.previous_response_id.clone(),
        ));

        let llm = match ctx.get::<ares_llm::Llm>() {
            Some(llm) => Some(llm),
            None if self.strict_fallbacks => {
                return Err(AppError::Unavailable(
                    "strict_fallbacks: no Llm service on context".into(),
                ));
            }
            None => None,
        };
        if let Some(llm) = llm {
            match llm
                .get_client_boxed(ctx, ares_llm::CapabilityRequirements::default())
                .await
            {
                Ok(client) => {
                    apply_generation_hints(
                        client.as_ref(),
                        req.web_search,
                        req.previous_response_id.clone(),
                    );
                    if !req.parts.is_empty() || req.previous_response_id.is_some() {
                        match client
                            .generate_with_tools_and_history(&base_messages, &tool_definitions)
                            .await
                        {
                            Ok(resp) => {
                                return Ok(AgentResponse {
                                    content: resp.content,
                                    usage: resp.usage,
                                    metadata: None,
                                });
                            }
                            Err(e) => {
                                if self.strict_fallbacks {
                                    return Err(AppError::Unavailable(format!(
                                        "strict_fallbacks: generate_with_tools_and_history failed: {e}"
                                    )));
                                }
                                tracing::warn!(
                                    error = %e,
                                    "multimodal generate failed, trying fallback LLM chain"
                                );
                            }
                        }
                    } else {
                    let config = ares_llm::coordinator::ToolCallingConfig::default();
                    let coordinator = ares_llm::coordinator::ToolCoordinator::new(
                        client,
                        Arc::clone(&tools),
                        config,
                    );
                    match coordinator
                        .execute(Some(&system_prompt), &req.message, ctx)
                        .await
                    {
                        Ok(coord_result) => {
                            if let Some(_db) = tenant_db(ctx) {
                                tracing::debug!(
                                    content_len = coord_result.content.len(),
                                    "observability sink run_history/agent_runs via TenantDb"
                                );
                                let _ = _db;
                            }
                            let usage = coord_result.total_usage.clone();
                            if let Some(tdb) = tenant_db(ctx) {
                                let _pool = tdb.pool();
                                tracing::debug!(
                                    tenant = ?tenant,
                                    prompt = usage.prompt_tokens,
                                    completion = usage.completion_tokens,
                                    total = usage.total_tokens,
                                    "token budget check via TenantDb and usage aggregation"
                                );
                                let _ = _pool;
                            }
                            self.emit_observability_typed::<cordis::AgentUsageEvent>(
                                ctx,
                                &cordis::AgentUsagePayload {
                                    tenant: tenant.clone(),
                                    prompt: usage.prompt_tokens as i64,
                                    completion: usage.completion_tokens as i64,
                                    total: usage.total_tokens as i64,
                                },
                            )
                            .await;
                            let mut detector = crate::loop_detector::LoopDetector::new();
                            match detector.check(&coord_result.content) {
                                crate::loop_detector::LoopStatus::LoopDetected {
                                    repeats,
                                    action,
                                    kind,
                                } => {
                                    tracing::warn!(
                                        repeats,
                                        ?action,
                                        ?kind,
                                        "loop_detector triggered in Execute"
                                    );
                                }
                                crate::loop_detector::LoopStatus::Ok => {}
                            }
                            return Ok(AgentResponse {
                                content: coord_result.content,
                                usage: Some(usage),
                                metadata: None,
                            });
                        }
                        Err(e) => {
                            if self.strict_fallbacks {
                                return Err(AppError::Unavailable(format!(
                                    "strict_fallbacks: ToolCoordinator::execute failed: {e}"
                                )));
                            }
                            tracing::warn!(error = %e, "ToolCoordinator loop failed, trying fallback LLM chain");
                        }
                    }
                    }
                }
                Err(e) => {
                    if self.strict_fallbacks {
                        return Err(AppError::Unavailable(format!(
                            "strict_fallbacks: Llm::get_client_boxed failed: {e}"
                        )));
                    }
                    tracing::warn!(error = %e, "Llm::get_client failed");
                }
            }

            // Strict mode never reaches here (both Err arms above return
            // early), but guard anyway: fallback-LLM content is refused.
            if self.strict_fallbacks {
                return Err(AppError::Unavailable(
                    "strict_fallbacks: fallback LLM chain unavailable".into(),
                ));
            }
            if let Ok(fb_client) = llm
                .get_client(ctx, ares_llm::CapabilityRequirements::default())
                .await
            {
                apply_generation_hints(
                    fb_client.as_ref(),
                    req.web_search,
                    req.previous_response_id.clone(),
                );
                if let Ok(content) = fb_client.generate(&req.message).await {
                    if let Some(_db) = tenant_db(ctx) {
                        tracing::debug!("fallback observability run_history/agent_runs");
                        let _ = _db;
                    }
                    let mut detector = crate::loop_detector::LoopDetector::new();
                    let _ = detector.check(&content);
                    return Ok(AgentResponse {
                        content,
                        usage: None,
                        metadata: None,
                    });
                }
            }
        }

        if let Some(_db) = tenant_db(ctx) {
            tracing::debug!("echo fallback observability run_history/agent_runs");
            let _ = _db;
        }
        let mut detector = crate::loop_detector::LoopDetector::new();
        let _status = detector.check(&req.message);
        let _ = crate::loop_detector::LoopConfig::default();

        if self.strict_fallbacks {
            return Err(AppError::Unavailable(
                "strict_fallbacks: no LLM response available".into(),
            ));
        }

        Ok(AgentResponse {
            content: if req.message.is_empty() {
                system_prompt
            } else {
                req.message.clone()
            },
            usage: None,
            metadata: None,
        })
    }

    /// Stream fallback used when Resolver/TenantDb are absent on ctx.
    ///
    /// Mirrors `execute` setup (memory, tools, history with parts, hints) but
    /// streams tokens. Does not use `ToolCoordinator`.
    async fn execute_stream_fallback(
        &self,
        req: AgentRequest,
        ctx: &Arc<Context>,
    ) -> Result<TokenStream, AppError> {
        if let Some(tenant_db) = tenant_db(ctx) {
            let _pool = tenant_db.pool();
            tracing::debug!(history_len = req.history.len(), "history load via TenantDb");
            let _ = _pool;
        }

        if let (Some(policy), Some(ovr)) = (
            ctx.get::<ares_llm::TenantModelPolicy>(),
            ctx.get::<ModelOverride>(),
        ) {
            policy.authorize(&ovr.model)?;
        }

        let tenant = tenant_from_request_ctx(ctx, None);

        let mut injected_context: Option<String> = None;
        let provider_opt: Option<Arc<dyn crate::context_provider::ContextProvider>> = req
            .ctx_provider
            .clone()
            .or_else(|| self.context_provider.clone());
        if let Some(provider) = provider_opt {
            let tid = tenant.clone().unwrap_or_default();
            let rt_ctx = crate::context_provider::AgentRuntimeContext::new(
                tid.clone(),
                &req.agent_name,
                "agent_execution",
            );
            if let Some(s) = provider.get_context_for_run(&rt_ctx).await {
                tracing::debug!(
                    len = s.len(),
                    "memory injected via ContextProvider::get_context_for_run"
                );
                injected_context = Some(s);
            } else if let Some(s) = provider.get_context(&req.agent_name, &tid).await {
                tracing::debug!(
                    len = s.len(),
                    "memory injected via ContextProvider::get_context"
                );
                injected_context = Some(s);
            }
        }

        let tools = ctx.get::<ares_tools::Tools>().unwrap_or_else(|| {
            Arc::new(ares_tools::Tools::from_static(std::iter::empty::<
                Arc<dyn ares_tools::Tool>,
            >()))
        });
        let tool_definitions = tools.list(ctx);
        tracing::debug!(
            count = tool_definitions.len(),
            has_service = true,
            "tools resolved via Tools::list"
        );
        let _resolve_probe = tools.resolve(ctx, "__probe__");

        let system_prompt = if let Some(extra) = injected_context.clone() {
            format!(
                "{}

You are {}.",
                extra, req.agent_name
            )
        } else {
            format!("You are {}.", req.agent_name)
        };

        let mut base_messages: Vec<ares_llm::coordinator::ConversationMessage> = Vec::new();
        base_messages.push(ares_llm::coordinator::ConversationMessage::system(
            system_prompt.clone(),
        ));
        for msg in &req.history {
            let mut cm = match msg.role {
                ares_types::types::MessageRole::User => {
                    ares_llm::coordinator::ConversationMessage::user(&msg.content)
                }
                ares_types::types::MessageRole::Assistant => {
                    ares_llm::coordinator::ConversationMessage::assistant(&msg.content, vec![])
                }
                _ => ares_llm::coordinator::ConversationMessage::system(&msg.content),
            };
            cm.parts = msg.parts.clone();
            base_messages.push(cm);
        }
        base_messages.push(user_message_with_parts(
            req.message.clone(),
            req.parts.clone(),
            req.previous_response_id.clone(),
        ));

        let echo_text = if req.message.is_empty() {
            system_prompt.clone()
        } else {
            req.message.clone()
        };

        let llm = match ctx.get::<ares_llm::Llm>() {
            Some(llm) => Some(llm),
            None if self.strict_fallbacks => {
                return Err(AppError::Unavailable(
                    "strict_fallbacks: no Llm service on context".into(),
                ));
            }
            None => None,
        };

        if let Some(llm) = llm {
            match llm
                .get_client_boxed(ctx, ares_llm::CapabilityRequirements::default())
                .await
            {
                Ok(client) => {
                    apply_generation_hints(
                        client.as_ref(),
                        req.web_search,
                        req.previous_response_id.clone(),
                    );
                    let ctx = Arc::clone(ctx);
                    let req_message = req.message.clone();
                    let req_parts_empty = req.parts.is_empty();
                    let max_iters =
                        ares_llm::coordinator::ToolCallingConfig::default().max_iterations;
                    return Ok(Box::pin(async_stream::stream! {
                        for _iteration in 0..max_iters {
                            match client
                                .stream_with_tools_and_history(&base_messages, &tool_definitions)
                                .await
                            {
                                Ok(mut evs) => {
                                    let mut tool_calls = Vec::new();
                                    let mut text_acc = String::new();
                                    let mut failed = false;
                                    while let Some(ev) = evs.next().await {
                                        match ev {
                                            Ok(ares_llm::LlmStreamEvent::Text(chunk)) => {
                                                text_acc.push_str(&chunk);
                                                yield Ok(chunk);
                                            }
                                            Ok(ares_llm::LlmStreamEvent::ToolCalls(calls)) => {
                                                tool_calls = calls;
                                            }
                                            Err(e) => {
                                                yield Err(e);
                                                failed = true;
                                                break;
                                            }
                                        }
                                    }
                                    if failed {
                                        return;
                                    }
                                    if tool_calls.is_empty() {
                                        return;
                                    }
                                    base_messages.push(
                                        ares_llm::coordinator::ConversationMessage::assistant(
                                            &text_acc,
                                            tool_calls.clone(),
                                        ),
                                    );
                                    for tc in &tool_calls {
                                        let result = tools
                                            .execute(&ctx, &tc.name, tc.arguments.clone())
                                            .await;
                                        let result_value = match result {
                                            Ok(v) => v,
                                            Err(e) => serde_json::json!({"error": e.to_string()}),
                                        };
                                        base_messages.push(
                                            ares_llm::coordinator::ConversationMessage::tool_result(
                                                &tc.id,
                                                &result_value,
                                            ),
                                        );
                                    }
                                }
                                Err(e)
                                    if matches!(e, AppError::FeatureDisabled(_))
                                        && tool_definitions.is_empty()
                                        && req_parts_empty =>
                                {
                                    match client.stream(&req_message).await {
                                        Ok(mut s) => {
                                            while let Some(item) = s.next().await {
                                                yield item;
                                            }
                                        }
                                        Err(e) => yield Err(e),
                                    }
                                    return;
                                }
                                Err(e) => {
                                    yield Err(e);
                                    return;
                                }
                            }
                        }
                    }));
                }
                Err(e) => {
                    if self.strict_fallbacks {
                        return Err(AppError::Unavailable(format!(
                            "strict_fallbacks: Llm::get_client_boxed failed: {e}"
                        )));
                    }
                    tracing::warn!(error = %e, "Llm::get_client failed");
                }
            }
        }

        if self.strict_fallbacks {
            return Err(AppError::Unavailable(
                "strict_fallbacks: no LLM response available".into(),
            ));
        }
        Ok(once_text_stream(echo_text))
    }
}

impl Default for Execute {
    fn default() -> Self {
        Self::new()
    }
}

/// Derive tenant for `execute` without requiring the postgres-only resolver module.
/// Scope tools and execution to one tenant. Isolate wins over intercept.
pub fn tenant_scope(ctx: &Arc<Context>, tenant_id: &str) -> Arc<Context> {
    #[cfg(feature = "postgres")]
    if let Some(realms) = ctx.get::<ares_store::TenantRealms>() {
        return realms.open(ctx, tenant_id);
    }
    // Only data-bearing services are realm-isolated. `Execute` is a shared
    // stateless engine; isolating it hid the root instance and broke every
    // request path resolving it post-scope (v1/chat 503 regression).
    ctx.isolate::<ares_tools::Tools>(tenant_id)
}

/// Request-path tenant: open the realm (or isolate) then intercept `TenantContext`.
/// Background jobs keep using [`tenant_scope`] (isolate only, no intercept).
pub fn request_tenant_ctx(
    ctx: &Arc<Context>,
    tc: ares_types::models::TenantContext,
) -> Arc<Context> {
    tenant_scope(ctx, &tc.tenant_id).with_intercept(tc)
}

/// JWT `user:` isolate when no tenant is present. Does not invent `TenantContext`.
pub fn request_user_scope(ctx: &Arc<Context>, user_id: &str) -> Arc<Context> {
    let label = format!("user:{user_id}");
    ctx.isolate::<ares_tools::Tools>(&label)
}

/// Derive user/tenant scope: `Execute` isolate label (strip `tenant:`/`user:`),
/// then `TenantContext` intercept, then `fallback`.
pub fn user_id_from_ctx(ctx: &Arc<Context>, fallback: &str) -> String {
    // Legacy label first (realms created before Execute stopped being
    // isolated), then the live realm boundary on `Tools`.
    for tid in [
        std::any::TypeId::of::<Execute>(),
        std::any::TypeId::of::<ares_tools::Tools>(),
    ] {
        if let Some(label) = ctx.isolate_label(tid) {
            let trimmed = label
                .strip_prefix("tenant:")
                .or_else(|| label.strip_prefix("user:"))
                .unwrap_or(&label);
            if !trimmed.is_empty() {
                return trimmed.to_string();
            }
        }
    }
    if let Some(tc) = ctx.get::<ares_types::models::TenantContext>() {
        if !tc.tenant_id.is_empty() {
            return tc.tenant_id.clone();
        }
    }
    fallback.to_string()
}

#[cfg(feature = "postgres")]
fn tenant_db(ctx: &Arc<Context>) -> Option<Arc<ares_store::TenantDb>> {
    ctx.get::<ares_store::TenantDb>()
}

#[cfg(not(feature = "postgres"))]
struct NoTenantDb;

#[cfg(not(feature = "postgres"))]
impl NoTenantDb {
    fn pool(&self) -> &() {
        &()
    }
}

#[cfg(not(feature = "postgres"))]
fn tenant_db(_ctx: &Arc<Context>) -> Option<Arc<NoTenantDb>> {
    None
}

fn tenant_from_request_ctx(ctx: &Arc<Context>, fallback: Option<&str>) -> Option<String> {
    let id = user_id_from_ctx(ctx, fallback.unwrap_or(""));
    if id.is_empty() {
        None
    } else {
        Some(id)
    }
}

impl Service for Execute {
    fn name(&self) -> &'static str {
        "Execute"
    }

    fn init(
        &self,
        _ctx: &Arc<Context>,
    ) -> Pin<
        Box<
            dyn Future<Output = Result<Option<Box<dyn cordis::Disposable>>, CordisError>>
                + Send
                + '_,
        >,
    > {
        Box::pin(async move { Ok(None) })
    }

    fn check(&self) -> bool {
        true
    }
}

/// Trait for tracking active agent runs. Implemented by the root crate's `ActiveRuns`
/// and injected into `Execute` via the Context.
///
/// This allows `ares-agent` (a leaf crate) to track runs without depending on root-crate types.
pub trait RunTracker: Send + Sync + 'static {
    /// Register a new run as active.
    fn start_run(&self, run_id: &str, tenant_id: &str, agent_name: &str, source: Option<&str>);
    /// Update run progress.
    fn update_run(&self, run_id: &str, status: &str, step: i32);
    /// Mark run as finished with terminal status.
    fn finish_run(&self, run_id: &str, status: &str);
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::StreamExt;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    /// RED contract: the `agent.started` event must be fanned out to every
    /// registered handler via Cordis `Dispatch::Parallel` (join-all), so the
    /// dispatch awaits all handlers before returning. A fire-and-forget
    /// `Dispatch::Emit` returns immediately and may not have run any handler,
    /// so this assertion would be flaky/false under the old implementation.
    ///
    /// The harness calls the not-yet-existing public seam `emit_agent_started`,
    /// which the implement phase adds and wires into `run` in place
    /// of the `Dispatch::Emit` at line ~272.
    #[tokio::test]
    async fn agent_started_fans_out_via_parallel() {
        let svc = Execute::new();
        let ctx = Context::new_root();
        let events = ctx.provide(cordis::EventsService::new());

        let count = Arc::new(AtomicUsize::new(0));

        // Handler 1 — `Dispatch::Parallel` must run it before returning.
        let c1 = count.clone();
        let _d1 = events.on(
            cordis::events_catalog::ev::AGENT_STARTED.to_string(),
            move |payload: serde_json::Value| {
                let c = c1.clone();
                async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    Ok(payload)
                }
            },
        );

        // Handler 2 — also must be run before the dispatch returns.
        let c2 = count.clone();
        let _d2 = events.on(
            cordis::events_catalog::ev::AGENT_STARTED.to_string(),
            move |payload: serde_json::Value| {
                let c = c2.clone();
                async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    Ok(payload)
                }
            },
        );

        // Seam the implement phase adds: dispatches "agent.started" with
        // `Dispatch::Parallel` and returns the resulting value.
        svc.emit_agent_started(
            &ctx,
            cordis::AgentStartedPayload {
                agent_name: "a".into(),
                run_id: String::new(),
                tenant: String::new(),
                event: "agent.started".into(),
            },
        )
        .await;

        assert_eq!(
            count.load(Ordering::SeqCst),
            2,
            "Dispatch::Parallel must join both 'agent.started' handlers before returning"
        );
    }

    /// `Dispatch::Emit` must return before a slow handler finishes, then the
    /// handler still runs on the runtime after the call returns.
    #[tokio::test]
    async fn emit_observability_returns_without_waiting_for_slow_handler() {
        let svc = Execute::new();
        let ctx = Context::new_root();
        let events = ctx.provide(cordis::EventsService::new());

        let ran = Arc::new(AtomicBool::new(false));
        let flag = ran.clone();
        let _d = events.on(
            cordis::events_catalog::ev::AGENT_USAGE.to_string(),
            move |payload: serde_json::Value| {
                let flag = flag.clone();
                async move {
                    tokio::time::sleep(std::time::Duration::from_millis(80)).await;
                    flag.store(true, Ordering::SeqCst);
                    Ok(payload)
                }
            },
        );

        let start = std::time::Instant::now();
        svc.emit_observability(
            &ctx,
            cordis::events_catalog::ev::AGENT_USAGE,
            serde_json::json!({}),
        )
        .await;
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_millis(40),
            "emit_observability must return without awaiting handlers, elapsed {elapsed:?}"
        );

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        assert!(
            ran.load(Ordering::SeqCst),
            "slow agent.usage handler must still run after emit returns"
        );
    }

    #[tokio::test]
    async fn emit_agent_completed_and_failed_return_without_waiting() {
        let svc = Execute::new();
        let ctx = Context::new_root();
        let events = ctx.provide(cordis::EventsService::new());

        let ran = Arc::new(AtomicBool::new(false));
        let mut _guards = Vec::new();
        for event in [cordis::events_catalog::ev::AGENT_COMPLETED, "agent.failed"] {
            let flag = ran.clone();
            _guards.push(events.on(event.into(), move |payload: serde_json::Value| {
                let flag = flag.clone();
                async move {
                    tokio::time::sleep(std::time::Duration::from_millis(80)).await;
                    flag.store(true, Ordering::SeqCst);
                    Ok(payload)
                }
            }));
        }

        let start = std::time::Instant::now();
        svc.emit_observability(
            &ctx,
            cordis::events_catalog::ev::AGENT_COMPLETED,
            serde_json::json!({}),
        )
        .await;
        svc.emit_observability(
            &ctx,
            cordis::events_catalog::ev::AGENT_FAILED,
            serde_json::json!({}),
        )
        .await;
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_millis(40),
            "completed/failed must Emit without awaiting handlers, elapsed {elapsed:?}"
        );
    }

    struct ProbeTool {
        name: String,
    }

    #[async_trait::async_trait]
    impl ares_tools::Tool for ProbeTool {
        fn name(&self) -> &str {
            &self.name
        }
        fn description(&self) -> &str {
            "probe"
        }
        fn parameters_schema(&self) -> serde_json::Value {
            serde_json::json!({"type": "object", "properties": {}})
        }
        async fn execute(
            &self,
            _args: serde_json::Value,
        ) -> ares_types::types::Result<serde_json::Value> {
            Ok(serde_json::json!({"ok": true}))
        }
    }

    fn tools_with_probe() -> ares_tools::Tools {
        ares_tools::Tools::from_static([Arc::new(ProbeTool {
            name: "probe".into(),
        }) as Arc<dyn ares_tools::Tool>])
    }

    async fn execute_with_tenant_context_intercept(tenant_id: &str) {
        let svc = Execute::new();
        let ctx = Context::new_root().with_intercept(ares_types::models::TenantContext::new(
            tenant_id.into(),
            ares_types::models::TenantTier::Pro,
        ));
        let _ = ctx.provide(tools_with_probe());
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "hi".into(),
            ..Default::default()
        };
        svc.run(&req, &ctx).await.expect("echo fallback");
        let tools = ctx.get::<ares_tools::Tools>().expect("Tools on ctx");
        let names: Vec<_> = tools.list(&ctx).into_iter().map(|d| d.name).collect();
        assert!(
            names.contains(&"probe".to_string()),
            "Tools::list(ctx) sees intercept tenant tools"
        );
    }

    #[tokio::test]
    async fn execute_lists_tools_using_tenant_context_intercept() {
        execute_with_tenant_context_intercept("acme").await;
    }

    /// When `Tools` is on ctx, `run` must call `Tools::list(ctx)` /
    /// `Tools::resolve(ctx, name)` (isolate+intercept).
    #[tokio::test]
    async fn execute_lists_tools_via_tools_on_ctx() {
        let svc = Execute::new();
        let ctx = Context::new_root().with_intercept(ares_types::models::TenantContext::new(
            "acme".into(),
            ares_types::models::TenantTier::Pro,
        ));
        let _ = ctx.provide(tools_with_probe());
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "hi".into(),
            ..Default::default()
        };
        svc.run(&req, &ctx).await.expect("echo fallback");
        let tools = ctx.get::<ares_tools::Tools>().expect("Tools on ctx");
        assert!(tools.resolve(&ctx, "probe").is_some());
        assert!(tools.list(&ctx).iter().any(|d| d.name == "probe"));
    }

    /// Intercept path without an `AgentRequest` tenant field (aliases the listing test).
    #[tokio::test]
    async fn execute_uses_ctx_tenant_without_request_field() {
        execute_with_tenant_context_intercept("acme").await;
    }

    #[tokio::test]
    async fn request_tenant_ctx_keeps_root_execute_resolvable() {
        // Regression guard for v1/chat: the handler resolves `Execute` from the
        // tenant-scoped context. Root-provided Execute must stay visible inside
        // the realm (Tools stays isolated; Execute is the shared engine).
        let root = Context::new_root();
        let _fid = root.plugin(cordis::EventsService::new()).await;
        root.provide_arc(Arc::new(Execute::new()) as Arc<Execute>);
        let tc = ares_types::models::TenantContext::new(
            "acme".into(),
            ares_types::models::TenantTier::Pro,
        );
        let scoped = crate::request_tenant_ctx(&root, tc);
        assert!(
            scoped.get::<Execute>().is_some(),
            "root-provided Execute must resolve inside tenant scope"
        );
    }

    #[tokio::test]
    async fn execute_isolate_label_wins_over_intercept_for_tools() {
        let svc = Execute::new();
        let intercepted =
            Context::new_root().with_intercept(ares_types::models::TenantContext::new(
                "from-intercept".into(),
                ares_types::models::TenantTier::Pro,
            ));
        let ctx = tenant_scope(&intercepted, "from-isolate");
        let _ = ctx.provide(tools_with_probe());
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "hi".into(),
            ..Default::default()
        };
        svc.run(&req, &ctx).await.expect("echo fallback");
        assert_eq!(user_id_from_ctx(&ctx, "anon"), "from-isolate");
        let tools = ctx.get::<ares_tools::Tools>().expect("Tools on ctx");
        assert!(tools.list(&ctx).iter().any(|d| d.name == "probe"));
    }

    #[tokio::test]
    async fn execute_admit_denies_without_http() {
        let execute = Execute::new();
        let quota = ares_types::models::TenantQuota {
            tier: ares_types::models::TenantTier::Free,
            requests_per_month: 0,
            tokens_per_month: 0,
            max_agents: 1,
            requests_per_day: 0,
        };
        let tc = ares_types::models::TenantContext {
            tenant_id: "capped".into(),
            tier: ares_types::models::TenantTier::Free,
            quota,
        };
        let ctx = Context::new_root().with_intercept(tc);
        let _ = ctx.provide(cordis::EventsService::new());
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "should not run".into(),
            ..Default::default()
        };
        let err = execute.run(&req, &ctx).await.expect_err("quota deny");
        match err {
            AppError::RateLimited(msg) => {
                assert_eq!(msg, "Monthly request quota exceeded");
            }
            other => panic!("expected RateLimited, got {other:?}"),
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn agent_run_waterfall_rewrites_message() {
        let svc = Execute::new();
        let ctx = Context::new_root();
        let events = ctx.provide(cordis::EventsService::new());
        events.on_waterfall(
            cordis::events_catalog::ev::AGENT_RUN.to_string(),
            |mut payload, next| async move {
                payload["message"] = serde_json::json!("rewritten-hello");
                next(payload).await
            },
        );
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "original".into(),
            ..Default::default()
        };
        let result = svc.run(&req, &ctx).await.expect("echo fallback");
        assert!(
            result.response.content.contains("rewritten-hello"),
            "waterfall rewrite of message must reach echo execute, got {:?}",
            result.response.content
        );
    }

    #[tokio::test]
    async fn strict_fallbacks_errors_without_llm() {
        let svc = Execute::new().with_strict_fallbacks(true);
        let ctx = Context::new_root();
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "hi".into(),
            ..Default::default()
        };
        let err = svc.run(&req, &ctx).await.expect_err("strict must refuse");
        match err {
            AppError::Unavailable(m) => {
                assert!(
                    m.starts_with("strict_fallbacks:"),
                    "unexpected refusal message: {m}"
                );
            }
            other => panic!("expected Unavailable, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn default_execute_still_echoes_without_llm() {
        let svc = Execute::new();
        assert!(!svc.strict_fallbacks());
        let ctx = Context::new_root();
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "hello-echo".into(),
            ..Default::default()
        };
        let result = svc.run(&req, &ctx).await.expect("echo fallback");
        assert_eq!(result.response.content, "hello-echo");
    }

    #[tokio::test]
    async fn agent_run_short_circuit_skips_execute() {
        let svc = Execute::new();
        let ctx = Context::new_root();
        let events = ctx.provide(cordis::EventsService::new());
        events.on_waterfall(
            cordis::events_catalog::ev::AGENT_RUN.to_string(),
            |_payload, _next| async move {
                Ok(serde_json::json!({
                    "content": "short-circuit",
                    "source": "system",
                    "agent_name": "echo",
                    "run_id": "test-run",
                }))
            },
        );
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "would-echo-this-if-core-ran".into(),
            ..Default::default()
        };
        let result = svc.run(&req, &ctx).await.expect("short-circuit");
        assert_eq!(result.response.content, "short-circuit");
        assert_eq!(result.run_id, "test-run");
        assert_ne!(
            result.response.content, req.message,
            "skipping next must not run echo execute"
        );
    }

    #[tokio::test]
    async fn request_tenant_ctx_intercepts_after_scope() {
        let root = Context::new_root();
        #[cfg(feature = "postgres")]
        {
            root.provide(ares_store::TenantRealms::new(
                std::any::TypeId::of::<ares_tools::Tools>(),
                std::any::TypeId::of::<Execute>(),
            ));
        }
        let tc = ares_types::models::TenantContext::new(
            "acme".into(),
            ares_types::models::TenantTier::Pro,
        );
        let scoped = request_tenant_ctx(&root, tc);
        let got = scoped
            .get::<ares_types::models::TenantContext>()
            .expect("TenantContext intercept");
        assert_eq!(got.tenant_id, "acme");
        assert_eq!(
            scoped
                .isolate_label(std::any::TypeId::of::<ares_tools::Tools>())
                .as_deref(),
            Some("acme")
        );
        // Execute is the shared engine: no realm label, always resolvable.
        assert_eq!(
            scoped
                .isolate_label(std::any::TypeId::of::<Execute>())
                .as_deref(),
            None
        );
        #[cfg(feature = "postgres")]
        {
            let realms = root
                .get::<ares_store::TenantRealms>()
                .expect("TenantRealms");
            let realm = realms.open(&root, "acme");
            assert!(
                realm.get::<ares_types::models::TenantContext>().is_none(),
                "cached realm must stay intercept-free"
            );
            let realm2 = realms.open(&root, "acme");
            assert!(std::sync::Arc::ptr_eq(&realm, &realm2));
        }
    }

    #[tokio::test]
    async fn request_user_scope_does_not_invent_tenant_context() {
        let root = Context::new_root();
        let scoped = request_user_scope(&root, "user-1");
        assert!(scoped.get::<ares_types::models::TenantContext>().is_none());
        // Execute stays unlabeled (shared engine); Tools carries the realm.
        assert_eq!(
            scoped
                .isolate_label(std::any::TypeId::of::<Execute>())
                .as_deref(),
            None
        );
        assert_eq!(
            scoped
                .isolate_label(std::any::TypeId::of::<ares_tools::Tools>())
                .as_deref(),
            Some("user:user-1")
        );
    }

    #[tokio::test]
    async fn run_stream_echoes_without_llm() {
        let svc = Execute::new();
        let ctx = Context::new_root();
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "hello stream".into(),
            ..Default::default()
        };
        let mut stream = svc.run_stream(&req, &ctx).await.expect("stream");
        let first = stream.next().await.expect("chunk").expect("ok");
        assert_eq!(first, "hello stream");
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn run_stream_echoes_with_parts() {
        let svc = Execute::new();
        let ctx = Context::new_root();
        let req = AgentRequest {
            agent_name: "echo".into(),
            message: "caption".into(),
            parts: vec![ContentPart::Text {
                text: "img".into(),
            }],
            ..Default::default()
        };
        let mut stream = svc.run_stream(&req, &ctx).await.expect("stream");
        let first = stream.next().await.expect("chunk").expect("ok");
        assert_eq!(first, "caption");
        assert!(stream.next().await.is_none());
    }
}