aegis-orchestrator 0.15.0-pre-alpha

100monkeys.ai AEGIS orchestrator CLI and daemon
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
// Copyright (c) 2026 100monkeys.ai
// SPDX-License-Identifier: AGPL-3.0
//! HTTP client for communicating with daemon API
//!
//! # Architecture
//!
//! - **Layer:** Interface / Presentation Layer
//! - **Purpose:** Implements internal responsibilities for client

use anyhow::{Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio_stream::StreamExt;
use tracing::info;
use uuid::Uuid;

use aegis_orchestrator_core::domain::events::CorrelatedActivityEvent;
use aegis_orchestrator_sdk::AgentManifest;

#[derive(Deserialize)]
#[serde(untagged)]
enum WorkflowListResponse {
    Wrapped { workflows: Vec<serde_json::Value> },
    Bare(Vec<serde_json::Value>),
}

#[derive(Debug, Clone)]
pub struct DaemonClient {
    client: Client,
    base_url: String,
    auth_key: Option<String>,
}

impl DaemonClient {
    pub fn new(host: &str, port: u16) -> Result<Self> {
        let client = Client::builder()
            // No global timeout for CLI client as we need long-lived streams
            .build()
            .context("Failed to create HTTP client")?;

        let base_url = if host.starts_with("http://") || host.starts_with("https://") {
            format!("{host}:{port}")
        } else {
            format!("http://{host}:{port}")
        };

        Ok(Self {
            client,
            base_url,
            auth_key: None,
        })
    }

    pub fn with_auth(mut self, key: String) -> Self {
        self.auth_key = Some(key);
        self
    }

    fn request(
        &self,
        method: reqwest::Method,
        url: impl reqwest::IntoUrl,
    ) -> reqwest::RequestBuilder {
        let builder = self.client.request(method, url);
        if let Some(ref key) = self.auth_key {
            builder.header(reqwest::header::AUTHORIZATION, format!("Bearer {key}"))
        } else {
            builder
        }
    }

    pub async fn deploy_agent(
        &self,
        manifest: AgentManifest,
        force: bool,
        scope: Option<&str>,
    ) -> Result<Uuid> {
        let mut params = vec![];
        if force {
            params.push("force=true".to_string());
        }
        if let Some(s) = scope {
            params.push(format!("scope={s}"));
        }
        let query = if params.is_empty() {
            String::new()
        } else {
            format!("?{}", params.join("&"))
        };
        let url = format!("{}/v1/agents{}", self.base_url, query);
        let response = self
            .request(reqwest::Method::POST, url)
            .json(&manifest)
            .send()
            .await
            .context("Failed to deploy agent")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to deploy agent: {error_text}");
        }

        #[derive(Deserialize)]
        struct DeployResponse {
            agent_id: Uuid,
        }

        let deploy_response: DeployResponse = response
            .json()
            .await
            .context("Failed to parse deploy response")?;

        Ok(deploy_response.agent_id)
    }

    pub async fn execute_agent(
        &self,
        agent_id: Uuid,
        input: serde_json::Value,
        intent: Option<String>,
        context_overrides: Option<serde_json::Value>,
        version: Option<&str>,
    ) -> Result<Uuid> {
        #[derive(Serialize)]
        struct ExecuteRequest {
            input: serde_json::Value,
            #[serde(skip_serializing_if = "Option::is_none")]
            intent: Option<String>,
            #[serde(skip_serializing_if = "Option::is_none")]
            context_overrides: Option<serde_json::Value>,
        }

        let mut url = format!("{}/v1/agents/{}/execute", self.base_url, agent_id);
        if let Some(ver) = version {
            url.push_str(&format!("?version={ver}"));
        }

        let response = self
            .request(reqwest::Method::POST, url)
            .json(&ExecuteRequest {
                input,
                intent,
                context_overrides,
            })
            .send()
            .await
            .context("Failed to execute agent")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to execute agent: {error_text}");
        }

        #[derive(Deserialize)]
        struct ExecuteResponse {
            execution_id: Uuid,
        }

        let exec_response: ExecuteResponse = response
            .json()
            .await
            .context("Failed to parse execute response")?;

        Ok(exec_response.execution_id)
    }

    pub async fn get_execution(&self, execution_id: Uuid) -> Result<ExecutionInfo> {
        let response = self
            .request(
                reqwest::Method::GET,
                format!("{}/v1/executions/{}", self.base_url, execution_id),
            )
            .send()
            .await
            .context("Failed to get execution")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get execution: {error_text}");
        }

        response
            .json()
            .await
            .context("Failed to parse execution response")
    }

    pub async fn cancel_execution(&self, execution_id: Uuid) -> Result<()> {
        let response = self
            .request(
                reqwest::Method::POST,
                format!("{}/v1/executions/{}/cancel", self.base_url, execution_id),
            )
            .send()
            .await
            .context("Failed to cancel execution")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to cancel execution: {error_text}");
        }

        Ok(())
    }

    pub async fn list_executions(
        &self,
        agent_id: Option<Uuid>,
        limit: usize,
    ) -> Result<Vec<ExecutionInfo>> {
        let mut url = format!("{}/v1/executions?limit={}", self.base_url, limit);
        if let Some(aid) = agent_id {
            url.push_str(&format!("&agent_id={aid}"));
        }

        let response = self
            .request(reqwest::Method::GET, &url)
            .send()
            .await
            .context("Failed to list executions")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list executions: {error_text}");
        }

        response
            .json()
            .await
            .context("Failed to parse executions response")
    }

    pub async fn stream_logs(
        &self,
        execution_id: Uuid,
        follow: bool,
        errors_only: bool,
        verbose: bool,
    ) -> Result<()> {
        let mut url = format!("{}/v1/executions/{}/events", self.base_url, execution_id);
        if follow {
            url.push_str("?follow=true");
        } else {
            url.push_str("?follow=false");
        }
        if verbose {
            url.push_str("&verbose=true");
        }

        let response = self
            .request(reqwest::Method::GET, &url)
            .send()
            .await
            .context("Failed to connect to event stream")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to stream logs: {error_text}");
        }

        stream_correlated_events(response, errors_only, verbose).await
    }

    pub async fn stream_agent_logs(
        &self,
        agent_id: Uuid,
        follow: bool,
        errors_only: bool,
        verbose: bool,
    ) -> Result<()> {
        let mut url = format!("{}/v1/agents/{}/events", self.base_url, agent_id);
        if follow {
            url.push_str("?follow=true");
        } else {
            url.push_str("?follow=false");
        }
        if verbose {
            url.push_str("&verbose=true");
        }

        let response = self
            .request(reqwest::Method::GET, &url)
            .send()
            .await
            .context("Failed to connect to agent event stream")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to stream agent logs: {error_text}");
        }

        stream_correlated_events(response, errors_only, verbose).await
    }

    pub async fn delete_execution(&self, execution_id: Uuid) -> Result<()> {
        let response = self
            .request(
                reqwest::Method::DELETE,
                format!("{}/v1/executions/{}", self.base_url, execution_id),
            )
            .send()
            .await
            .context("Failed to delete execution")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to delete execution: {error_text}");
        }

        Ok(())
    }

    pub async fn list_agents(&self) -> Result<Vec<AgentInfo>> {
        let response = self
            .request(reqwest::Method::GET, format!("{}/v1/agents", self.base_url))
            .send()
            .await
            .context("Failed to list agents")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list agents: {error_text}");
        }

        response
            .json()
            .await
            .context("Failed to parse agents response")
    }

    pub async fn get_agent(&self, agent_id: Uuid) -> Result<AgentManifest> {
        let response = self
            .request(
                reqwest::Method::GET,
                format!("{}/v1/agents/{}", self.base_url, agent_id),
            )
            .send()
            .await
            .context("Failed to get agent")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get agent: {error_text}");
        }

        #[derive(Debug, Deserialize)]
        struct GetAgentResponse {
            manifest: AgentManifest,
        }

        let wrapper: GetAgentResponse = response
            .json()
            .await
            .context("Failed to parse agent manifest")?;
        Ok(wrapper.manifest)
    }

    pub async fn delete_agent(&self, agent_id: Uuid) -> Result<()> {
        let response = self
            .request(
                reqwest::Method::DELETE,
                format!("{}/v1/agents/{}", self.base_url, agent_id),
            )
            .send()
            .await
            .context("Failed to delete agent")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to delete agent: {error_text}");
        }

        Ok(())
    }
    pub async fn lookup_agent(&self, name: &str) -> Result<Option<Uuid>> {
        let response = self
            .request(
                reqwest::Method::GET,
                format!("{}/v1/agents/lookup/{}", self.base_url, name),
            )
            .send()
            .await
            .context("Failed to lookup agent")?;

        if response.status() == 404 {
            return Ok(None);
        }

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to lookup agent: {error_text}");
        }

        #[derive(Deserialize)]
        struct LookupResponse {
            id: Uuid,
        }

        let lookup_response: LookupResponse = response
            .json()
            .await
            .context("Failed to parse lookup response")?;

        Ok(Some(lookup_response.id))
    }

    pub async fn lookup_workflow(&self, name: &str) -> Result<Option<Uuid>> {
        let workflows = self.list_workflows().await?;
        Ok(workflows.iter().find_map(|workflow| {
            let workflow_name = workflow.get("name")?.as_str()?;
            if workflow_name == name {
                workflow
                    .get("id")
                    .and_then(Value::as_str)
                    .and_then(|raw| Uuid::parse_str(raw).ok())
            } else {
                None
            }
        }))
    }

    // ── Secrets ──────────────────────────────────────────────────────────────

    pub async fn put_secret(&self, path: &str, data: serde_json::Value) -> Result<()> {
        let url = format!("{}/v1/secrets/{}", self.base_url, path);
        let response = self
            .request(reqwest::Method::PUT, &url)
            .json(&data)
            .send()
            .await
            .context("Failed to write secret")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to write secret at '{path}': {err}");
        }
        Ok(())
    }

    pub async fn get_secret(&self, path: &str) -> Result<serde_json::Value> {
        let url = format!("{}/v1/secrets/{}", self.base_url, path);
        let response = self
            .request(reqwest::Method::GET, &url)
            .send()
            .await
            .context("Failed to read secret")?;

        if response.status() == reqwest::StatusCode::NOT_FOUND {
            anyhow::bail!("Secret not found at '{path}'");
        }
        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to read secret at '{path}': {err}");
        }
        response
            .json()
            .await
            .context("Failed to parse secret response")
    }

    /// Returns `None` when the server responds 501 (listing not implemented).
    pub async fn list_secrets(&self) -> Result<Option<serde_json::Value>> {
        let url = format!("{}/v1/secrets", self.base_url);
        let response = self
            .request(reqwest::Method::GET, &url)
            .send()
            .await
            .context("Failed to list secrets")?;

        if response.status() == reqwest::StatusCode::NOT_IMPLEMENTED {
            return Ok(None);
        }
        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list secrets: {err}");
        }
        let body = response
            .json()
            .await
            .context("Failed to parse list response")?;
        Ok(Some(body))
    }

    pub async fn delete_secret(&self, path: &str) -> Result<()> {
        let url = format!("{}/v1/secrets/{}", self.base_url, path);
        let response = self
            .request(reqwest::Method::DELETE, &url)
            .send()
            .await
            .context("Failed to delete secret")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to delete secret at '{path}': {err}");
        }
        Ok(())
    }

    // ── Credentials ───────────────────────────────────────────────────────────

    pub async fn store_api_key(
        &self,
        provider: &str,
        label: &str,
        scope: Option<&str>,
        value: &str,
    ) -> Result<serde_json::Value> {
        #[derive(Serialize)]
        struct StoreRequest<'a> {
            provider: &'a str,
            label: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            scope: Option<&'a str>,
            value: &'a str,
        }

        let url = format!("{}/v1/credentials/api-keys", self.base_url);
        let response = self
            .request(reqwest::Method::POST, &url)
            .json(&StoreRequest {
                provider,
                label,
                scope,
                value,
            })
            .send()
            .await
            .context("Failed to store API key")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to store API key: {err}");
        }
        response
            .json()
            .await
            .context("Failed to parse store response")
    }

    pub async fn initiate_oauth(
        &self,
        provider: &str,
        redirect_uri: &str,
    ) -> Result<serde_json::Value> {
        #[derive(Serialize)]
        struct OAuthInitRequest<'a> {
            provider: &'a str,
            redirect_uri: &'a str,
        }

        let url = format!("{}/v1/credentials/oauth/initiate", self.base_url);
        let response = self
            .request(reqwest::Method::POST, &url)
            .json(&OAuthInitRequest {
                provider,
                redirect_uri,
            })
            .send()
            .await
            .context("Failed to initiate OAuth flow")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to initiate OAuth: {err}");
        }
        response
            .json()
            .await
            .context("Failed to parse OAuth initiate response")
    }

    pub async fn list_credentials(&self) -> Result<serde_json::Value> {
        let url = format!("{}/v1/credentials", self.base_url);
        let response = self
            .request(reqwest::Method::GET, &url)
            .send()
            .await
            .context("Failed to list credentials")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list credentials: {err}");
        }
        response
            .json()
            .await
            .context("Failed to parse credentials list")
    }

    pub async fn get_credential(&self, id: &str) -> Result<serde_json::Value> {
        let url = format!("{}/v1/credentials/{}", self.base_url, id);
        let response = self
            .request(reqwest::Method::GET, &url)
            .send()
            .await
            .context("Failed to get credential")?;

        if response.status() == reqwest::StatusCode::NOT_FOUND {
            anyhow::bail!("Credential not found: {id}");
        }
        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get credential '{id}': {err}");
        }
        response
            .json()
            .await
            .context("Failed to parse credential response")
    }

    pub async fn delete_credential(&self, id: &str) -> Result<()> {
        let url = format!("{}/v1/credentials/{}", self.base_url, id);
        let response = self
            .request(reqwest::Method::DELETE, &url)
            .send()
            .await
            .context("Failed to delete credential")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to delete credential '{id}': {err}");
        }
        Ok(())
    }

    pub async fn add_credential_grant(
        &self,
        binding_id: &str,
        target_type: &str,
        target_id: Option<&str>,
        granted_by: Option<&str>,
    ) -> Result<serde_json::Value> {
        #[derive(Serialize)]
        struct GrantRequest<'a> {
            target_type: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            target_id: Option<&'a str>,
            #[serde(skip_serializing_if = "Option::is_none")]
            granted_by: Option<&'a str>,
        }

        let url = format!("{}/v1/credentials/{}/grants", self.base_url, binding_id);
        let response = self
            .request(reqwest::Method::POST, &url)
            .json(&GrantRequest {
                target_type,
                target_id,
                granted_by,
            })
            .send()
            .await
            .context("Failed to add credential grant")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to add grant for credential '{binding_id}': {err}");
        }
        response
            .json()
            .await
            .context("Failed to parse grant response")
    }

    pub async fn list_credential_grants(&self, binding_id: &str) -> Result<serde_json::Value> {
        let url = format!("{}/v1/credentials/{}/grants", self.base_url, binding_id);
        let response = self
            .request(reqwest::Method::GET, &url)
            .send()
            .await
            .context("Failed to list credential grants")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list grants for credential '{binding_id}': {err}");
        }
        response
            .json()
            .await
            .context("Failed to parse grants response")
    }

    pub async fn revoke_credential_grant(&self, binding_id: &str, grant_id: &str) -> Result<()> {
        let url = format!(
            "{}/v1/credentials/{}/grants/{}",
            self.base_url, binding_id, grant_id
        );
        let response = self
            .request(reqwest::Method::DELETE, &url)
            .send()
            .await
            .context("Failed to revoke credential grant")?;

        if !response.status().is_success() {
            let err = response.text().await.unwrap_or_default();
            anyhow::bail!(
                "Failed to revoke grant '{grant_id}' from credential '{binding_id}': {err}"
            );
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ExecutionInfo {
    pub id: Uuid,
    pub agent_id: Uuid,
    pub status: String,
    pub started_at: Option<String>,
    pub ended_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AgentInfo {
    pub id: Uuid,
    pub name: String,
    pub version: String,
    pub description: String,
    pub status: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WorkflowExecutionInfo {
    pub execution_id: Uuid,
    pub workflow_id: Uuid,
    #[serde(default)]
    pub workflow_name: Option<String>,
    pub status: String,
    #[serde(default)]
    pub current_state: Option<String>,
    #[serde(default)]
    pub started_at: Option<String>,
    #[serde(default)]
    pub last_transition_at: Option<String>,
    #[serde(default)]
    pub temporal_workflow_id: Option<String>,
    #[serde(default)]
    pub temporal_run_id: Option<String>,
    #[serde(default)]
    pub blackboard: Option<Value>,
    #[serde(default)]
    pub state_outputs: Option<Value>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WorkflowLogEvent {
    pub execution_id: Uuid,
    #[serde(default)]
    pub workflow_id: Option<Uuid>,
    #[serde(default)]
    pub workflow_name: Option<String>,
    pub event_type: String,
    pub message: String,
    #[serde(default)]
    pub state_name: Option<String>,
    #[serde(default)]
    pub iteration_number: Option<u8>,
    pub timestamp: String,
    #[serde(default)]
    pub details: Value,
    #[serde(default)]
    pub temporal_workflow_id: Option<String>,
    #[serde(default)]
    pub temporal_run_id: Option<String>,
}

#[derive(Debug, Clone, Copy)]
pub struct WorkflowLogOptions {
    pub transitions_only: bool,
    pub errors_only: bool,
    pub verbose: bool,
}

#[derive(Debug, Clone, Deserialize)]
struct WorkflowLogsResponse {
    events: Vec<WorkflowLogEvent>,
}

async fn stream_correlated_events(
    response: reqwest::Response,
    errors_only: bool,
    verbose: bool,
) -> Result<()> {
    let mut stream = response.bytes_stream();

    while let Some(chunk) = stream.next().await {
        let chunk = chunk.context("Failed to read event stream chunk")?;
        let text = String::from_utf8_lossy(&chunk);

        for line in text.lines() {
            if let Some(json_str) = line.strip_prefix("data: ") {
                if let Ok(event) = serde_json::from_str::<CorrelatedActivityEvent>(json_str) {
                    if errors_only && !is_error_event(&event) {
                        continue;
                    }
                    print_event(&event, verbose);
                }
            }
        }
    }

    Ok(())
}

async fn stream_workflow_events(
    response: reqwest::Response,
    options: WorkflowLogOptions,
) -> Result<()> {
    let mut stream = response.bytes_stream();

    while let Some(chunk) = stream.next().await {
        let chunk = chunk.context("Failed to read workflow event stream chunk")?;
        let text = String::from_utf8_lossy(&chunk);

        for line in text.lines() {
            if let Some(json_str) = line.strip_prefix("data: ") {
                if let Ok(event) = serde_json::from_str::<WorkflowLogEvent>(json_str) {
                    if should_skip_workflow_event(&event, options) {
                        continue;
                    }
                    info!(
                        execution_id = %event.execution_id,
                        event_type = %event.event_type,
                        "{}",
                        format_workflow_log_event(&event, options.verbose).trim_end()
                    );
                }
            }
        }
    }

    Ok(())
}

fn should_skip_workflow_event(event: &WorkflowLogEvent, options: WorkflowLogOptions) -> bool {
    (options.transitions_only && !is_transition_workflow_event(event))
        || (options.errors_only && !is_error_workflow_event(event))
}

fn is_transition_workflow_event(event: &WorkflowLogEvent) -> bool {
    matches!(
        canonical_event_type(&event.event_type).as_str(),
        "workflow_execution_started"
            | "workflow_state_entered"
            | "workflow_state_exited"
            | "workflow_execution_completed"
            | "workflow_execution_failed"
            | "workflow_execution_cancelled"
    )
}

fn is_error_workflow_event(event: &WorkflowLogEvent) -> bool {
    matches!(
        canonical_event_type(&event.event_type).as_str(),
        "workflow_iteration_failed" | "workflow_execution_failed"
    )
}

pub(crate) fn format_workflow_log_event(event: &WorkflowLogEvent, verbose: bool) -> String {
    let mut output = format!("[{}] {}", event.timestamp, event.message);

    if let Some(iteration) = event.iteration_number {
        output.push_str(&format!(" (iteration {iteration})"));
    }

    if !verbose {
        output.push('\n');
        return output;
    }

    output.push('\n');
    if let Some(workflow_name) = &event.workflow_name {
        output.push_str(&format!("  Workflow:   {workflow_name}\n"));
    }
    if let Some(workflow_id) = event.workflow_id {
        output.push_str(&format!("  Workflow ID: {workflow_id}\n"));
    }
    output.push_str(&format!(
        "  Event:      {}\n",
        canonical_event_type(&event.event_type)
    ));
    if let Some(state_name) = &event.state_name {
        output.push_str(&format!("  State:      {state_name}\n"));
    }
    if let Some(iteration) = event.iteration_number {
        output.push_str(&format!("  Iteration:  {iteration}\n"));
    }
    if let Some(temporal_workflow_id) = &event.temporal_workflow_id {
        output.push_str(&format!("  Temporal workflow: {temporal_workflow_id}\n"));
    }
    if let Some(temporal_run_id) = &event.temporal_run_id {
        output.push_str(&format!("  Temporal run:      {temporal_run_id}\n"));
    }
    if event.details != Value::Null && !event.details.is_null() {
        let rendered = serde_json::to_string_pretty(&event.details)
            .unwrap_or_else(|_| event.details.to_string());
        output.push_str("  Details:\n");
        for line in rendered.lines() {
            output.push_str("    ");
            output.push_str(line);
            output.push('\n');
        }
    }

    output
}

fn is_error_event(event: &CorrelatedActivityEvent) -> bool {
    let event_type = canonical_event_type(&event.event_type);

    matches!(
        event_type.as_str(),
        "iteration_failed"
            | "execution_failed"
            | "execution_timed_out"
            | "workflow_iteration_failed"
            | "workflow_execution_failed"
            | "volume_mount_failed"
            | "volume_quota_exceeded"
            | "filesystem_policy_violation"
            | "path_traversal_blocked"
            | "quota_exceeded"
            | "unauthorized_volume_access"
            | "policy_violation"
            | "invocation_failed"
            | "policy_violation_blocked"
            | "server_failed"
            | "server_unhealthy"
            | "container_run_failed"
            | "image_pull_failed"
            | "classification_failed"
            | "stimulus_rejected"
            | "secret_access_denied"
            | "token_validation_failed"
            | "jwks_cache_refresh_failed"
            | "agent_failed"
    )
}

fn extract_iteration_error_message(event: &CorrelatedActivityEvent) -> String {
    if let Some(msg) = event
        .details
        .get("error")
        .and_then(|e| e.get("message"))
        .and_then(Value::as_str)
    {
        return msg.to_string();
    }

    if let Some(msg) = event
        .details
        .get("error")
        .and_then(Value::as_str)
        .or_else(|| event.details.get("reason").and_then(Value::as_str))
    {
        return msg.to_string();
    }

    if !event.message.is_empty() {
        return event.message.clone();
    }

    "Unknown error".to_string()
}

fn print_event(event: &CorrelatedActivityEvent, verbose: bool) {
    info!(
        event_type = %event.event_type,
        category = %event.category,
        "{}",
        format_event(event, verbose)
    );
}

fn format_event(event: &CorrelatedActivityEvent, verbose: bool) -> String {
    use colored::Colorize;

    let event_type = canonical_event_type(&event.event_type);
    let timestamp = event.timestamp.to_rfc3339();
    let header = format!("[{timestamp}]").dimmed().to_string();
    let category = format!("[{}]", event.category).dimmed().to_string();

    match event_type.as_str() {
        "console_output" => {
            let stream = event
                .details
                .get("stream")
                .and_then(Value::as_str)
                .unwrap_or("stdout");
            let content = event
                .details
                .get("output")
                .and_then(Value::as_str)
                .unwrap_or(&event.message);
            let prefix = match stream {
                "stderr" => "[STDERR]".red().to_string(),
                "judge" => "[JUDGE]".magenta().bold().to_string(),
                _ => "[STDOUT]".cyan().to_string(),
            };
            format!("{prefix} {}", content.trim_end())
        }
        "llm_interaction" if verbose => {
            let model = event
                .details
                .get("model")
                .and_then(Value::as_str)
                .unwrap_or("unknown");
            let prompt = event
                .details
                .get("prompt")
                .and_then(Value::as_str)
                .unwrap_or("");
            let response = event
                .details
                .get("response")
                .and_then(Value::as_str)
                .unwrap_or("");
            format!(
                "{header} {category} {} [{model}]\n{}\n{prompt}\n{}\n{response}\n{}",
                "LLM Interaction".purple().bold(),
                "PROMPT:".dimmed(),
                "RESPONSE:".dimmed(),
                "-".repeat(40).dimmed()
            )
        }
        "llm_interaction" => {
            let model = event
                .details
                .get("model")
                .and_then(Value::as_str)
                .unwrap_or("unknown");
            format!("{header} {category} {} [{model}]", "LLM".purple())
        }
        "iteration_failed" => {
            let error = extract_iteration_error_message(event);
            format!(
                "{header} {category} {}",
                format!("Iteration failed: {error}").red().bold()
            )
        }
        "execution_failed" | "execution_timed_out" => {
            format!("{header} {category} {}", event.message.red().bold())
        }
        "execution_completed" if !verbose => format!(
            "{header} {category} {}",
            "Execution completed".green().bold()
        ),
        _ if verbose => {
            let base = format!("{header} {category} {}", event.message);
            let pretty_details = format_details(&event.details);
            if pretty_details.is_empty() {
                base
            } else {
                format!("{base}\n{pretty_details}")
            }
        }
        _ => format!("{header} {category} {}", event.message),
    }
}

fn canonical_event_type(event_type: &str) -> String {
    if event_type.bytes().any(|byte| byte.is_ascii_uppercase()) {
        let mut canonical = String::with_capacity(event_type.len() + 4);
        for (index, ch) in event_type.chars().enumerate() {
            if ch.is_ascii_uppercase() {
                if index != 0 {
                    canonical.push('_');
                }
                canonical.push(ch.to_ascii_lowercase());
            } else {
                canonical.push(ch);
            }
        }
        canonical
    } else {
        event_type.to_string()
    }
}

fn format_details(details: &Value) -> String {
    match details {
        Value::Null => String::new(),
        Value::Object(map) if map.is_empty() => String::new(),
        _ => serde_json::to_string_pretty(details).unwrap_or_default(),
    }
}

// ============================================================================
// Workflow Management Methods
// ============================================================================

impl DaemonClient {
    /// Deploy a workflow from a file with optional force overwrite.
    /// Deploy a workflow from a file with optional force overwrite and scope.
    pub async fn deploy_workflow_with_force_and_scope(
        &self,
        file: &std::path::Path,
        force: bool,
        scope: Option<&str>,
    ) -> Result<()> {
        let workflow_yaml =
            std::fs::read_to_string(file).context("Failed to read workflow file")?;
        self.deploy_workflow_manifest_with_force_and_scope(&workflow_yaml, force, scope)
            .await
    }

    /// Deploy a workflow from YAML content with optional force overwrite and scope.
    pub async fn deploy_workflow_manifest_with_force_and_scope(
        &self,
        workflow_yaml: &str,
        force: bool,
        scope: Option<&str>,
    ) -> Result<()> {
        let mut params = Vec::new();
        if force {
            params.push("force=true".to_string());
        }
        if let Some(s) = scope {
            params.push(format!("scope={s}"));
        }
        let query = if params.is_empty() {
            String::new()
        } else {
            format!("?{}", params.join("&"))
        };
        let url = format!("{}/v1/workflows{query}", self.base_url);

        let response = self
            .request(reqwest::Method::POST, url)
            .header("Content-Type", "application/x-yaml")
            .body(workflow_yaml.to_string())
            .send()
            .await
            .context("Failed to deploy workflow")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to deploy workflow: {error_text}");
        }

        Ok(())
    }

    /// Run a workflow
    pub async fn run_workflow(
        &self,
        name: &str,
        input: serde_json::Value,
        blackboard: Option<serde_json::Value>,
        version: Option<&str>,
        intent: Option<String>,
    ) -> Result<Uuid> {
        #[derive(Serialize)]
        struct RunRequest {
            input: serde_json::Value,
            #[serde(skip_serializing_if = "Option::is_none")]
            blackboard: Option<serde_json::Value>,
            #[serde(skip_serializing_if = "Option::is_none")]
            intent: Option<String>,
        }

        let mut url = format!("{}/v1/workflows/{}/run", self.base_url, name);
        if let Some(ver) = version {
            url.push_str(&format!("?version={ver}"));
        }

        let response = self
            .request(reqwest::Method::POST, url)
            .json(&RunRequest {
                input,
                blackboard,
                intent,
            })
            .send()
            .await
            .context("Failed to run workflow")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to run workflow: {error_text}");
        }

        #[derive(Deserialize)]
        struct RunResponse {
            execution_id: Uuid,
        }

        let run_response: RunResponse = response
            .json()
            .await
            .context("Failed to parse run response")?;

        Ok(run_response.execution_id)
    }

    /// List all workflows
    pub async fn list_workflows(&self) -> Result<Vec<serde_json::Value>> {
        let response = self
            .request(
                reqwest::Method::GET,
                format!("{}/v1/workflows", self.base_url),
            )
            .send()
            .await
            .context("Failed to list workflows")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list workflows: {error_text}");
        }

        let list_response: WorkflowListResponse = response
            .json()
            .await
            .context("Failed to parse list response")?;

        let workflows = match list_response {
            WorkflowListResponse::Wrapped { workflows } => workflows,
            WorkflowListResponse::Bare(workflows) => workflows,
        };

        Ok(workflows)
    }

    /// List workflows with optional scope filter or visible-all mode.
    pub async fn list_workflows_with_scope(
        &self,
        scope: Option<&str>,
        visible: bool,
    ) -> Result<Vec<serde_json::Value>> {
        let mut params = Vec::new();
        if let Some(s) = scope {
            params.push(format!("scope={s}"));
        }
        if visible {
            params.push("visible=true".to_string());
        }
        let query = if params.is_empty() {
            String::new()
        } else {
            format!("?{}", params.join("&"))
        };
        let url = format!("{}/v1/workflows{query}", self.base_url);

        let response = self
            .request(reqwest::Method::GET, url)
            .send()
            .await
            .context("Failed to list workflows")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list workflows: {error_text}");
        }

        let list_response: WorkflowListResponse = response
            .json()
            .await
            .context("Failed to parse list response")?;

        let workflows = match list_response {
            WorkflowListResponse::Wrapped { workflows } => workflows,
            WorkflowListResponse::Bare(workflows) => workflows,
        };

        Ok(workflows)
    }

    /// Change workflow scope (promote/demote).
    pub async fn change_workflow_scope(
        &self,
        name_or_id: &str,
        target_scope: &str,
    ) -> Result<serde_json::Value> {
        let url = format!("{}/v1/workflows/{}/scope", self.base_url, name_or_id);
        let body = serde_json::json!({ "target_scope": target_scope });

        let response = self
            .request(reqwest::Method::POST, &url)
            .json(&body)
            .send()
            .await
            .context("Failed to change workflow scope")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to change workflow scope: {error_text}");
        }

        let result: serde_json::Value = response
            .json()
            .await
            .context("Failed to parse scope change response")?;

        Ok(result)
    }

    /// List workflow executions (paginated, newest first)
    pub async fn list_workflow_executions(
        &self,
        limit: usize,
        workflow_id: Option<uuid::Uuid>,
    ) -> Result<Vec<WorkflowExecutionInfo>> {
        let mut url = format!("{}/v1/workflows/executions?limit={}", self.base_url, limit);
        if let Some(wid) = workflow_id {
            url.push_str(&format!("&workflow_id={wid}"));
        }

        let response = self
            .request(reqwest::Method::GET, url)
            .send()
            .await
            .context("Failed to list workflow executions")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list workflow executions: {error_text}");
        }

        let executions: Vec<WorkflowExecutionInfo> = response
            .json()
            .await
            .context("Failed to parse workflow executions response")?;

        Ok(executions)
    }

    /// Describe a workflow (get YAML definition)
    pub async fn describe_workflow(&self, name: &str) -> Result<serde_json::Value> {
        let response = self
            .request(
                reqwest::Method::GET,
                format!("{}/v1/workflows/{}", self.base_url, name),
            )
            .send()
            .await
            .context("Failed to describe workflow")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to describe workflow: {error_text}");
        }

        let value = response
            .json::<serde_json::Value>()
            .await
            .context("Failed to parse workflow JSON")?;

        Ok(value)
    }

    /// Delete a workflow
    pub async fn delete_workflow(&self, name: &str) -> Result<()> {
        let response = self
            .request(
                reqwest::Method::DELETE,
                format!("{}/v1/workflows/{}", self.base_url, name),
            )
            .send()
            .await
            .context("Failed to delete workflow")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to delete workflow: {error_text}");
        }

        Ok(())
    }

    pub async fn get_workflow_execution(
        &self,
        execution_id: Uuid,
    ) -> Result<WorkflowExecutionInfo> {
        let response = self
            .request(
                reqwest::Method::GET,
                format!("{}/v1/workflows/executions/{}", self.base_url, execution_id),
            )
            .send()
            .await
            .context("Failed to get workflow execution")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get workflow execution: {error_text}");
        }

        response
            .json()
            .await
            .context("Failed to parse workflow execution response")
    }

    pub async fn signal_workflow_execution(
        &self,
        execution_id: Uuid,
        response_text: &str,
    ) -> Result<()> {
        let response = self
            .request(
                reqwest::Method::POST,
                format!(
                    "{}/v1/workflows/executions/{}/signal",
                    self.base_url, execution_id
                ),
            )
            .json(&serde_json::json!({ "response": response_text }))
            .send()
            .await
            .context("Failed to signal workflow execution")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to signal workflow execution: {error_text}");
        }

        Ok(())
    }

    pub async fn cancel_workflow_execution(&self, execution_id: Uuid) -> Result<()> {
        let response = self
            .request(
                reqwest::Method::POST,
                format!(
                    "{}/v1/workflows/executions/{}/cancel",
                    self.base_url, execution_id
                ),
            )
            .send()
            .await
            .context("Failed to cancel workflow execution")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to cancel workflow execution: {error_text}");
        }

        Ok(())
    }

    pub async fn remove_workflow_execution(&self, execution_id: Uuid) -> Result<()> {
        let response = self
            .request(
                reqwest::Method::DELETE,
                format!("{}/v1/workflows/executions/{}", self.base_url, execution_id),
            )
            .send()
            .await
            .context("Failed to remove workflow execution")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to remove workflow execution: {error_text}");
        }

        Ok(())
    }

    pub async fn stream_workflow_logs(
        &self,
        execution_id: Uuid,
        options: WorkflowLogOptions,
    ) -> Result<()> {
        let response = self
            .request(
                reqwest::Method::GET,
                format!(
                    "{}/v1/workflows/executions/{}/logs/stream",
                    self.base_url, execution_id
                ),
            )
            .send()
            .await
            .context("Failed to connect to workflow log stream")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to stream workflow logs: {error_text}");
        }

        stream_workflow_events(response, options).await
    }

    pub async fn get_workflow_logs(
        &self,
        execution_id: Uuid,
        options: WorkflowLogOptions,
    ) -> Result<Vec<WorkflowLogEvent>> {
        let response = self
            .request(
                reqwest::Method::GET,
                format!(
                    "{}/v1/workflows/executions/{}/logs",
                    self.base_url, execution_id
                ),
            )
            .send()
            .await
            .context("Failed to get workflow logs")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get workflow logs: {error_text}");
        }

        let payload: WorkflowLogsResponse = response
            .json()
            .await
            .context("Failed to parse workflow logs response")?;

        Ok(payload
            .events
            .into_iter()
            .filter(|event| !should_skip_workflow_event(event, options))
            .collect())
    }
}

#[cfg(test)]
mod tests {
    use super::{
        extract_iteration_error_message, format_event, is_error_event, CorrelatedActivityEvent,
        WorkflowListResponse,
    };
    use chrono::Utc;
    use serde_json::{json, Value};
    use uuid::Uuid;

    #[test]
    fn test_error_object_with_message_precedence() {
        let event = CorrelatedActivityEvent {
            event_type: "IterationFailed".to_string(),
            category: "execution".to_string(),
            timestamp: Utc::now(),
            execution_id: None,
            agent_id: None,
            iteration: Some(1),
            stage: None,
            message: "top-level error".to_string(),
            details: json!({
                "error": {
                    "message": "object message",
                    "code": "SOME_CODE"
                }
            }),
        };

        let msg = extract_iteration_error_message(&event);
        assert_eq!(msg, "object message");
    }

    #[test]
    fn test_error_string_in_data_precedence() {
        let event = CorrelatedActivityEvent {
            event_type: "IterationFailed".to_string(),
            category: "execution".to_string(),
            timestamp: Utc::now(),
            execution_id: None,
            agent_id: None,
            iteration: Some(1),
            stage: None,
            message: "top-level error".to_string(),
            details: json!({
                "error": "data error string"
            }),
        };

        let msg = extract_iteration_error_message(&event);
        assert_eq!(msg, "data error string");
    }

    #[test]
    fn test_error_string_top_level_precedence() {
        let event = CorrelatedActivityEvent {
            event_type: "IterationFailed".to_string(),
            category: "execution".to_string(),
            timestamp: Utc::now(),
            execution_id: None,
            agent_id: None,
            iteration: Some(1),
            stage: None,
            message: "top-level error".to_string(),
            details: json!({}),
        };

        let msg = extract_iteration_error_message(&event);
        assert_eq!(msg, "top-level error");
    }

    #[test]
    fn test_error_fallback_unknown() {
        let event = CorrelatedActivityEvent {
            event_type: "IterationFailed".to_string(),
            category: "execution".to_string(),
            timestamp: Utc::now(),
            execution_id: None,
            agent_id: None,
            iteration: Some(1),
            stage: None,
            message: String::new(),
            details: json!({
                "error": {
                    "not_message": "no message field here"
                }
            }),
        };

        let msg = extract_iteration_error_message(&event);
        assert_eq!(msg, "Unknown error");
    }

    #[test]
    fn detects_backend_failures_as_errors() {
        let event = CorrelatedActivityEvent {
            event_type: "FilesystemPolicyViolation".to_string(),
            category: "storage".to_string(),
            timestamp: Utc::now(),
            execution_id: None,
            agent_id: None,
            iteration: None,
            stage: None,
            message: "Filesystem policy violation".to_string(),
            details: json!({}),
        };

        assert!(is_error_event(&event));
    }

    #[test]
    fn verbose_output_includes_structured_details() {
        let event = CorrelatedActivityEvent {
            event_type: "PolicyViolation".to_string(),
            category: "mcp".to_string(),
            timestamp: Utc::now(),
            execution_id: None,
            agent_id: None,
            iteration: None,
            stage: Some("fs.write".to_string()),
            message: "Tool policy violation blocked: fs.write".to_string(),
            details: json!({
                "tool_name": "fs.write",
                "details": "attempted to write outside workspace"
            }),
        };

        let rendered = format_event(&event, true);
        assert!(rendered.contains("Tool policy violation blocked: fs.write"));
        assert!(rendered.contains("\"tool_name\": \"fs.write\""));
    }

    #[test]
    fn parses_typed_correlated_activity_event() {
        let payload = json!({
            "event_type": "ContainerRunFailed",
            "category": "container_run",
            "timestamp": Utc::now(),
            "execution_id": Uuid::nil(),
            "agent_id": Value::Null,
            "iteration": Value::Null,
            "stage": "BUILD",
            "message": "Container step failed: Compile",
            "details": { "step_name": "Compile" }
        })
        .to_string();

        let parsed: CorrelatedActivityEvent = serde_json::from_str(&payload).expect("must parse");
        assert_eq!(parsed.event_type, "ContainerRunFailed");
        assert_eq!(parsed.category, "container_run");
        assert_eq!(parsed.stage.as_deref(), Some("BUILD"));
    }

    #[test]
    fn parses_wrapped_workflow_list_response() {
        let payload = r#"{"workflows":[{"name":"alpha"}]}"#;
        let parsed: WorkflowListResponse = serde_json::from_str(payload).expect("must parse");

        match parsed {
            WorkflowListResponse::Wrapped { workflows } => assert_eq!(workflows.len(), 1),
            WorkflowListResponse::Bare(_) => panic!("expected wrapped workflow list"),
        }
    }

    #[test]
    fn parses_bare_workflow_list_response() {
        let payload = r#"[{"name":"alpha"}]"#;
        let parsed: WorkflowListResponse = serde_json::from_str(payload).expect("must parse");

        match parsed {
            WorkflowListResponse::Bare(workflows) => assert_eq!(workflows.len(), 1),
            WorkflowListResponse::Wrapped { .. } => panic!("expected bare workflow list"),
        }
    }

    #[test]
    fn parses_empty_bare_workflow_list_response() {
        let payload = "[]";
        let parsed: WorkflowListResponse = serde_json::from_str(payload).expect("must parse");

        match parsed {
            WorkflowListResponse::Bare(workflows) => assert_eq!(workflows.len(), 0),
            WorkflowListResponse::Wrapped { .. } => panic!("expected bare workflow list"),
        }
    }
}