ironflow-sdk 0.2.2

Type-safe Rust SDK for the Ironflow workflow engine API
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
//! Ergonomic HTTP client for the Ironflow API.
//!
//! Wraps [`reqwest::Client`] with Bearer auth and automatic
//! deserialization of the `{ data, meta }` response envelope.

use std::time::Duration;

use chrono::{DateTime, Utc};
pub use ironflow_types::{ApiMeta, ApiResponse};
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue};
use reqwest::{Client, RequestBuilder, Response};
use serde::Serialize;
use serde_json::{from_str, json};
use uuid::Uuid;

pub use crate::builder::{ArtifactDownload, ClientBuilder};
use crate::error::{ApiErrorEnvelope, Error};
use crate::rate_limit::RateLimiter;
use crate::retry::RetryConfig;
use crate::types;

/// Configuration for the Ironflow SDK client.
///
/// # Examples
///
/// ```
/// use ironflow_sdk::client::ClientConfig;
/// use std::time::Duration;
///
/// let config = ClientConfig {
///     base_url: "https://ironflow.example.com".to_string(),
///     api_key: "my-api-key".to_string(),
///     timeout: Duration::from_secs(60),
/// };
/// ```
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// Base URL of the Ironflow API (e.g. `https://ironflow.example.com`).
    pub base_url: String,
    /// API key for Bearer authentication.
    pub api_key: String,
    /// HTTP request timeout.
    pub timeout: Duration,
}

/// Filtering options for [`IronflowClient::list_runs_filtered`].
///
/// # Examples
///
/// ```
/// use ironflow_sdk::client::ListRunsFilter;
///
/// let filter = ListRunsFilter {
///     workflow: Some("deploy"),
///     status: Some("completed"),
///     page: Some(1),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ListRunsFilter<'a> {
    /// Filter by workflow name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow: Option<&'a str>,
    /// Filter by run status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<&'a str>,
    /// Page number (1-based).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,
    /// Items per page.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_page: Option<u32>,
    /// Filter runs that have/don't have steps.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub has_steps: Option<bool>,
    /// Filter by label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<&'a str>,
    /// Filter by author: the user ID that triggered the run.
    ///
    /// Also matches runs triggered by one of that user's API keys.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by: Option<Uuid>,
    /// Filter by concurrency group: only runs that belong to this group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub concurrency_group: Option<&'a str>,
    /// Filter by priority: only runs with exactly this priority.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<i16>,
}

/// Query options for [`IronflowClient::stats_history_with`].
///
/// The filters have the same semantics as [`ListRunsFilter`]: `workflow` is a
/// case-insensitive substring match.
///
/// # Examples
///
/// ```
/// use ironflow_sdk::client::StatsHistoryParams;
///
/// let params = StatsHistoryParams {
///     period: Some("24h"),
///     status: Some("failed"),
///     label: Some("env:prod"),
///     ..Default::default()
/// };
/// assert_eq!(params.period, Some("24h"));
/// ```
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct StatsHistoryParams<'a> {
    /// Filter by workflow name (case-insensitive substring match).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow: Option<&'a str>,
    /// Time period to query: `24h`, `7d`, `30d` or `90d`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<&'a str>,
    /// Bucket granularity: `1h`, `1d` or `1w`. Derived from the period when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub granularity: Option<&'a str>,
    /// Filter by run status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<&'a str>,
    /// Filter by labels. Comma-separated `key:value` pairs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<&'a str>,
    /// Filter runs that have/don't have steps.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub has_steps: Option<bool>,
    /// Filter by author: the user ID that triggered the run.
    ///
    /// Also matches runs triggered by one of that user's API keys.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by: Option<Uuid>,
    /// Filter by concurrency group: only runs that belong to this group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub concurrency_group: Option<&'a str>,
}

/// Query parameters for [`IronflowClient::list_steps`].
///
/// # Examples
///
/// ```
/// use ironflow_sdk::client::ListStepsParams;
///
/// let params = ListStepsParams {
///     agent_role: "Reviewer",
///     page: Some(2),
///     per_page: None,
/// };
/// assert_eq!(params.agent_role, "Reviewer");
/// ```
#[derive(Debug, Clone, Serialize)]
pub struct ListStepsParams<'a> {
    /// Name of the `AgentRole` whose agent steps to list. Matched exactly.
    pub agent_role: &'a str,
    /// Page number (1-based).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,
    /// Items per page (max 100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_page: Option<u32>,
}

/// Filtering options for [`IronflowClient::get_run_logs`].
///
/// # Examples
///
/// ```
/// use ironflow_sdk::client::ListRunLogsFilter;
/// use uuid::Uuid;
///
/// let filter = ListRunLogsFilter {
///     step_id: Some(Uuid::nil()),
///     stream: Some("stderr"),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ListRunLogsFilter<'a> {
    /// Filter by step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<Uuid>,
    /// Filter by output stream (`stdout`, `stderr`, `system`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<&'a str>,
    /// Cursor for pagination (last entry ID from previous page).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<Uuid>,
    /// Number of entries to return (default: 100, max: 1000).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Filtering options for [`IronflowClient::list_audit_logs_filtered`].
///
/// # Examples
///
/// ```
/// use ironflow_sdk::client::ListAuditLogsFilter;
///
/// let filter = ListAuditLogsFilter {
///     event_type: Some("run_created"),
///     per_page: Some(25),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ListAuditLogsFilter<'a> {
    /// Filter by event type (e.g. `run_status_changed`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_type: Option<&'a str>,
    /// Filter by run ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run_id: Option<Uuid>,
    /// Keep entries recorded at or after this instant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<DateTime<Utc>>,
    /// Keep entries recorded at or before this instant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<DateTime<Utc>>,
    /// Page number (1-based).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,
    /// Items per page.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_page: Option<u32>,
}

/// Filtering options for [`IronflowClient::list_approval_delegations_filtered`].
///
/// The user filters are honoured for an admin only; a non-admin always gets the
/// delegations they granted or received.
///
/// # Examples
///
/// ```
/// use ironflow_sdk::client::ListApprovalDelegationsFilter;
///
/// let filter = ListApprovalDelegationsFilter {
///     page: Some(2),
///     per_page: Some(50),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ListApprovalDelegationsFilter {
    /// Only delegations granted by this user.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_user_id: Option<Uuid>,
    /// Only delegations received by this user.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_user_id: Option<Uuid>,
    /// Page number (1-based).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,
    /// Items per page (max 100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_page: Option<u32>,
}

/// Filtering options for [`IronflowClient::list_signals`].
///
/// # Examples
///
/// ```
/// use ironflow_sdk::client::ListSignalsFilter;
///
/// let filter = ListSignalsFilter {
///     name: Some("ci.pipeline_finished".to_string()),
///     key: Some("4f2a9c1".to_string()),
///     ..Default::default()
/// };
/// assert!(filter.page.is_none());
/// ```
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ListSignalsFilter {
    /// Only signals with this exact name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Only signals with this exact key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    /// Page number (1-based).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,
    /// Items per page (max 100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_page: Option<u32>,
}

/// Type-safe client for the Ironflow REST API.
///
/// Handles Bearer authentication, the `{ data, meta }` response envelope,
/// and provides methods for all public API endpoints.
///
/// # Examples
///
/// ```no_run
/// use ironflow_sdk::IronflowClient;
///
/// # async fn example() -> Result<(), ironflow_sdk::Error> {
/// let client = IronflowClient::new("https://ironflow.example.com", "my-api-key");
///
/// // List runs
/// let runs = client.list_runs().await?;
/// for run in &runs.data {
///     # let _ = run;
/// }
///
/// // Get a specific workflow
/// let wf = client.get_workflow("deploy").await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct IronflowClient {
    pub(crate) http: Client,
    base_url: String,
    pub(crate) retry_config: RetryConfig,
    pub(crate) rate_limiter: RateLimiter,
}

impl IronflowClient {
    /// Create a new client with the given base URL and API key.
    ///
    /// Uses a default timeout of 30 seconds.
    ///
    /// # Panics
    ///
    /// Panics if `api_key` contains characters invalid for HTTP headers
    /// (e.g. newlines, NUL bytes, or non-visible ASCII).
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_sdk::IronflowClient;
    ///
    /// let client = IronflowClient::new("https://ironflow.example.com", "my-api-key");
    /// ```
    pub fn new(base_url: &str, api_key: &str) -> Self {
        let config = ClientConfig {
            base_url: base_url.trim_end_matches('/').to_string(),
            api_key: api_key.to_string(),
            timeout: Duration::from_secs(30),
        };
        Self::from_config(config)
    }

    /// Create a new client from a [`ClientConfig`].
    ///
    /// # Panics
    ///
    /// Panics if `config.api_key` contains characters invalid for HTTP headers
    /// (e.g. newlines, NUL bytes, or non-visible ASCII).
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_sdk::IronflowClient;
    /// use ironflow_sdk::client::ClientConfig;
    /// use std::time::Duration;
    ///
    /// let config = ClientConfig {
    ///     base_url: "https://ironflow.example.com".to_string(),
    ///     api_key: "my-api-key".to_string(),
    ///     timeout: Duration::from_secs(60),
    /// };
    /// let client = IronflowClient::from_config(config);
    /// ```
    pub fn from_config(config: ClientConfig) -> Self {
        Self::from_config_with_retry(config, RetryConfig::default(), RateLimiter::new())
    }

    /// Create a new client with custom retry and rate-limit settings.
    ///
    /// Prefer [`ClientBuilder`] for a more ergonomic interface.
    ///
    /// # Panics
    ///
    /// Panics if `config.api_key` contains characters invalid for HTTP headers.
    pub fn from_config_with_retry(
        config: ClientConfig,
        retry_config: RetryConfig,
        rate_limiter: RateLimiter,
    ) -> Self {
        let mut headers = HeaderMap::new();
        let auth_value = format!("Bearer {}", config.api_key);
        headers.insert(
            AUTHORIZATION,
            HeaderValue::from_str(&auth_value).expect("invalid API key characters"),
        );

        let http = Client::builder()
            .timeout(config.timeout)
            .default_headers(headers)
            .build()
            .expect("failed to build HTTP client");

        Self {
            http,
            base_url: config.base_url,
            retry_config,
            rate_limiter,
        }
    }

    /// Return the base URL.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    pub(crate) fn url(&self, path: &str) -> String {
        format!("{}{path}", self.base_url)
    }

    pub(crate) fn get(&self, path: &str) -> RequestBuilder {
        self.http.get(self.url(path))
    }

    pub(crate) fn post(&self, path: &str) -> RequestBuilder {
        self.http.post(self.url(path))
    }

    pub(crate) fn put(&self, path: &str) -> RequestBuilder {
        self.http.put(self.url(path))
    }

    pub(crate) fn delete(&self, path: &str) -> RequestBuilder {
        self.http.delete(self.url(path))
    }

    pub(crate) fn patch(&self, path: &str) -> RequestBuilder {
        self.http.patch(self.url(path))
    }

    /// Parse an error response into an [`Error`].
    pub(crate) async fn into_api_error(response: Response) -> Error {
        let status = response.status();
        let status_code = status.as_u16();
        let text = response.text().await.unwrap_or_default();
        from_str::<ApiErrorEnvelope>(&text)
            .map(|env| Error::api(status_code, env.error.code, env.error.message))
            .unwrap_or_else(|_| {
                Error::api(
                    status_code,
                    status.canonical_reason().unwrap_or("UNKNOWN"),
                    text,
                )
            })
    }

    // ── Health ──────────────────────────────────────────────────────

    /// `GET /api/v1/health-check`
    ///
    /// # Errors
    ///
    /// Returns [`Error::Http`] on network failure.
    pub async fn health_check(&self) -> Result<(), Error> {
        self.send_no_content(self.get("/api/v1/health-check")).await
    }

    // ── Runs ───────────────────────────────────────────────────────

    /// `GET /api/v1/runs` -- List runs with optional filtering and pagination.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 Unauthorized.
    pub async fn list_runs(&self) -> Result<ApiResponse<Vec<types::RunResponse>>, Error> {
        self.list_runs_filtered(&ListRunsFilter::default()).await
    }

    /// `GET /api/v1/runs` with query parameters.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 Unauthorized.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ironflow_sdk::IronflowClient;
    /// use ironflow_sdk::client::ListRunsFilter;
    ///
    /// # async fn example() -> Result<(), ironflow_sdk::Error> {
    /// let client = IronflowClient::new("https://ironflow.example.com", "key");
    /// let filter = ListRunsFilter {
    ///     workflow: Some("deploy"),
    ///     status: Some("completed"),
    ///     ..Default::default()
    /// };
    /// let runs = client.list_runs_filtered(&filter).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_runs_filtered(
        &self,
        filter: &ListRunsFilter<'_>,
    ) -> Result<ApiResponse<Vec<types::RunResponse>>, Error> {
        self.send_envelope(self.get("/api/v1/runs").query(filter))
            .await
    }

    /// `POST /api/v1/runs` -- Trigger a workflow.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400 (unknown workflow) or 401/403.
    pub async fn create_run(
        &self,
        request: &types::CreateRunRequest,
    ) -> Result<ApiResponse<types::RunResponse>, Error> {
        self.send_envelope_once(self.post("/api/v1/runs").json(request))
            .await
    }

    /// `POST /api/v1/runs` with an `Idempotency-Key` header -- trigger a workflow
    /// exactly once.
    ///
    /// Replaying the same key returns the run it already produced instead of
    /// creating a second one. The key stays bound for 24 hours. Use a value the
    /// caller can reproduce across retries, such as a webhook delivery id.
    ///
    /// The returned envelope is identical whether the run was created or replayed;
    /// compare `data.idempotency_key` or the run id if the distinction matters.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400 (unknown workflow or malformed key), 401/403,
    /// or 409 (`IDEMPOTENCY_KEY_CONFLICT`) when the key is already bound to a
    /// different workflow or payload.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ironflow_sdk::{IronflowClient, types};
    ///
    /// # async fn example(request: &types::CreateRunRequest) -> Result<(), ironflow_sdk::Error> {
    /// let client = IronflowClient::new("https://ironflow.example.com", "key");
    ///
    /// // Derive the key from something the caller can reproduce on retry,
    /// // such as the provider delivery id of the webhook that triggered this.
    /// let run = client
    ///     .create_run_idempotent(request, "github:8f4e2a10")
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn create_run_idempotent(
        &self,
        request: &types::CreateRunRequest,
        idempotency_key: &str,
    ) -> Result<ApiResponse<types::RunResponse>, Error> {
        self.send_envelope(
            self.post("/api/v1/runs")
                .header("Idempotency-Key", idempotency_key)
                .json(request),
        )
        .await
    }

    /// `GET /api/v1/runs/:id` -- Get run details.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 (run not found) or 401.
    pub async fn get_run(&self, id: Uuid) -> Result<ApiResponse<types::RunDetailResponse>, Error> {
        self.send_envelope(self.get(&format!("/api/v1/runs/{id}")))
            .await
    }

    /// Execute a lifecycle action on a run.
    async fn run_action(
        &self,
        id: Uuid,
        action: &str,
    ) -> Result<ApiResponse<types::RunResponse>, Error> {
        self.send_envelope(self.post(&format!("/api/v1/runs/{id}/{action}")))
            .await
    }

    /// `POST /api/v1/runs/:id/cancel` -- Cancel a run and the sub-workflow
    /// runs below it.
    ///
    /// The response carries the cancelled run's fields plus
    /// `cancelled_descendants`, the ids of the sub-runs cancelled with it.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 or 400 (invalid state transition).
    pub async fn cancel_run(
        &self,
        id: Uuid,
    ) -> Result<ApiResponse<types::CancelRunResponse>, Error> {
        self.send_envelope(self.post(&format!("/api/v1/runs/{id}/cancel")))
            .await
    }

    /// `POST /api/v1/runs/:id/pause` -- Pause a run and the sub-workflow runs
    /// below it.
    ///
    /// A running run has its step in flight interrupted, executed again on
    /// resume. The response carries
    /// the paused run's fields, with `resume_status` (the state it returns
    /// to), plus `paused_descendants`, the ids of the sub-runs paused with it.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404, 403 (not an admin) or 400 (the run
    /// already finished, is already paused, or is a sub-workflow run).
    pub async fn pause_run(&self, id: Uuid) -> Result<ApiResponse<types::PauseRunResponse>, Error> {
        self.send_envelope(self.post(&format!("/api/v1/runs/{id}/pause")))
            .await
    }

    /// `POST /api/v1/runs/:id/resume` -- Resume a paused run and the
    /// sub-workflow runs paused below it.
    ///
    /// The response carries the resumed run's fields plus
    /// `resumed_descendants`, the ids of the sub-runs resumed with it.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404, 403 (not an admin) or 400 (the run is
    /// not paused, or is a sub-workflow run).
    pub async fn resume_run(
        &self,
        id: Uuid,
    ) -> Result<ApiResponse<types::ResumeRunResponse>, Error> {
        self.send_envelope(self.post(&format!("/api/v1/runs/{id}/resume")))
            .await
    }

    /// `POST /api/v1/runs/:id/approve` -- Approve a run waiting for approval.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 or 400.
    pub async fn approve_run(&self, id: Uuid) -> Result<ApiResponse<types::RunResponse>, Error> {
        self.run_action(id, "approve").await
    }

    /// `POST /api/v1/runs/:id/reject` -- Reject a run waiting for approval.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 or 400.
    pub async fn reject_run(&self, id: Uuid) -> Result<ApiResponse<types::RunResponse>, Error> {
        self.run_action(id, "reject").await
    }

    /// `POST /api/v1/runs/:id/steps/:step_id/input` -- Answer a human input step.
    ///
    /// `value` is serialized as the JSON body and validated by the server
    /// against the schema stored on the step. On success the run resumes.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400 (the step does not wait for input), 403
    /// (the caller may not answer), 404 (unknown run or step), 409 (already
    /// answered or rejected) or 422 (the value does not match the schema).
    pub async fn submit_input<T: Serialize + ?Sized>(
        &self,
        run_id: Uuid,
        step_id: Uuid,
        value: &T,
    ) -> Result<ApiResponse<types::RunResponse>, Error> {
        self.send_envelope(
            self.post(&format!("/api/v1/runs/{run_id}/steps/{step_id}/input"))
                .json(value),
        )
        .await
    }

    /// `POST /api/v1/runs/:id/steps/:step_id/reject` -- Reject a human input step.
    ///
    /// The run resumes and the handler receives the rejection with `reason`
    /// (or a default reason naming the caller).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400 (the step does not wait for input), 403
    /// (the caller may not reject it), 404 (unknown run or step) or 409
    /// (already answered or rejected).
    pub async fn reject_input(
        &self,
        run_id: Uuid,
        step_id: Uuid,
        reason: Option<&str>,
    ) -> Result<ApiResponse<types::RunResponse>, Error> {
        self.send_envelope(
            self.post(&format!("/api/v1/runs/{run_id}/steps/{step_id}/reject"))
                .json(&json!({ "reason": reason })),
        )
        .await
    }

    /// `POST /api/v1/runs/:id/retry` -- Retry a failed run (creates a new run).
    ///
    /// When `force` is `true`, the query parameter `?force=true` is appended
    /// to override a handler version mismatch.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404, 400, or 409 (version mismatch).
    pub async fn retry_run(
        &self,
        id: Uuid,
        force: bool,
    ) -> Result<ApiResponse<types::RunResponse>, Error> {
        let action = if force { "retry?force=true" } else { "retry" };
        self.run_action(id, action).await
    }

    /// `POST /api/v1/runs/:id/replay` -- Replay a finished run on the current
    /// handler version (creates a new run).
    ///
    /// Unlike [`retry_run`](Self::retry_run), the new run always targets the
    /// handler's current version; there is no compatibility check to force.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 (run not found or workflow no longer
    /// registered) or 400 (run still in flight).
    pub async fn replay_run(&self, id: Uuid) -> Result<ApiResponse<types::RunResponse>, Error> {
        self.run_action(id, "replay").await
    }

    // ── Workflows ──────────────────────────────────────────────────

    /// `GET /api/v1/workflows` -- List registered workflows.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401.
    pub async fn list_workflows(&self) -> Result<ApiResponse<Vec<types::WorkflowSummary>>, Error> {
        self.send_envelope(self.get("/api/v1/workflows")).await
    }

    /// `GET /api/v1/workflows/:name` -- Get workflow details.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 or 401.
    pub async fn get_workflow(
        &self,
        name: &str,
    ) -> Result<ApiResponse<types::WorkflowDetailResponse>, Error> {
        self.send_envelope(self.get(&format!("/api/v1/workflows/{name}")))
            .await
    }

    /// `POST /api/v1/workflows/:name/plan` -- Build the execution plan for a workflow.
    ///
    /// Planning has no side effect: no step runs, and no run is created.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400 (invalid payload or `max_depth`), 401, or
    /// 404 (workflow not registered).
    pub async fn plan_workflow(
        &self,
        name: &str,
        request: &types::PlanWorkflowRequest,
    ) -> Result<ApiResponse<types::ExecutionPlanResponse>, Error> {
        self.send_envelope(
            self.post(&format!("/api/v1/workflows/{name}/plan"))
                .json(request),
        )
        .await
    }

    /// `POST /api/v1/workflows/:name/pause` -- Pause a workflow: workers stop
    /// picking its queued runs until it is resumed.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 (workflow not registered) or 403 (not an
    /// admin).
    pub async fn pause_workflow(
        &self,
        name: &str,
    ) -> Result<ApiResponse<types::WorkflowPauseResponse>, Error> {
        self.send_envelope(self.post(&format!("/api/v1/workflows/{name}/pause")))
            .await
    }

    /// `POST /api/v1/workflows/:name/resume` -- Resume a paused workflow.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 (workflow not registered) or 403 (not an
    /// admin).
    pub async fn resume_workflow(
        &self,
        name: &str,
    ) -> Result<ApiResponse<types::WorkflowPauseResponse>, Error> {
        self.send_envelope(self.post(&format!("/api/v1/workflows/{name}/resume")))
            .await
    }

    // ── Stats ──────────────────────────────────────────────────────

    /// `GET /api/v1/stats` -- Aggregate statistics.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401.
    pub async fn get_stats(&self) -> Result<ApiResponse<types::StatsResponse>, Error> {
        self.send_envelope(self.get("/api/v1/stats")).await
    }

    /// `GET /api/v1/stats/history` -- Time-bucketed historical statistics.
    ///
    /// Shorthand for [`stats_history_with`](Self::stats_history_with) without
    /// run filters other than `workflow`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example(client: &ironflow_sdk::IronflowClient) -> Result<(), ironflow_sdk::error::Error> {
    /// let history = client.stats_history(Some("deploy"), Some("7d"), None).await?;
    /// for bucket in &history.data.buckets {
    ///     println!(
    ///         "{}: {} completed, {} warning, {} running",
    ///         bucket.time, bucket.completed, bucket.warning, bucket.running
    ///     );
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 or 400.
    pub async fn stats_history(
        &self,
        workflow: Option<&str>,
        period: Option<&str>,
        granularity: Option<&str>,
    ) -> Result<ApiResponse<types::StatsHistoryResponse>, Error> {
        self.stats_history_with(&StatsHistoryParams {
            workflow,
            period,
            granularity,
            ..StatsHistoryParams::default()
        })
        .await
    }

    /// `GET /api/v1/stats/history` with every query parameter.
    ///
    /// Returns one bucket per granularity step over the whole period
    /// (zero-filled), each with a counter per run status and the success rate.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ironflow_sdk::client::StatsHistoryParams;
    ///
    /// # async fn example(client: &ironflow_sdk::IronflowClient) -> Result<(), ironflow_sdk::error::Error> {
    /// let params = StatsHistoryParams {
    ///     period: Some("24h"),
    ///     label: Some("env:prod"),
    ///     ..Default::default()
    /// };
    /// let history = client.stats_history_with(&params).await?;
    /// for bucket in &history.data.buckets {
    ///     println!("{}: {:?}", bucket.time, bucket.success_rate_percent);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 or 400.
    pub async fn stats_history_with(
        &self,
        params: &StatsHistoryParams<'_>,
    ) -> Result<ApiResponse<types::StatsHistoryResponse>, Error> {
        self.send_envelope(self.get("/api/v1/stats/history").query(params))
            .await
    }

    /// `GET /api/v1/stats/agent-roles` -- Cost, executions and failures per
    /// agent role over a period, all workflows combined.
    ///
    /// `period` is `24h`, `7d`, `30d` or `90d`; the server defaults to `7d`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example(client: &ironflow_sdk::IronflowClient) -> Result<(), ironflow_sdk::error::Error> {
    /// let stats = client.agent_role_stats(Some("30d")).await?;
    /// for role in &stats.data.roles {
    ///     println!("{}: {} executions", role.agent_role, role.executions);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401, 403 or 400 (invalid period).
    pub async fn agent_role_stats(
        &self,
        period: Option<&str>,
    ) -> Result<ApiResponse<types::AgentRoleStatsResponse>, Error> {
        let mut request = self.get("/api/v1/stats/agent-roles");
        if let Some(period) = period {
            request = request.query(&[("period", period)]);
        }
        self.send_envelope(request).await
    }

    // ── Steps ──────────────────────────────────────────────────────

    /// `GET /api/v1/steps` -- List the agent steps of one agent role across
    /// every run and workflow, newest first.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ironflow_sdk::client::ListStepsParams;
    ///
    /// # async fn example(client: &ironflow_sdk::IronflowClient) -> Result<(), ironflow_sdk::error::Error> {
    /// let params = ListStepsParams {
    ///     agent_role: "Reviewer",
    ///     page: None,
    ///     per_page: Some(50),
    /// };
    /// let steps = client.list_steps(&params).await?;
    /// for step in &steps.data {
    ///     println!("{} in run {}", step.name, step.run_id);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401, 403 or 400 (blank or too long role).
    pub async fn list_steps(
        &self,
        params: &ListStepsParams<'_>,
    ) -> Result<ApiResponse<Vec<types::StepResponse>>, Error> {
        self.send_envelope(self.get("/api/v1/steps").query(params))
            .await
    }

    // ── Auth ───────────────────────────────────────────────────────

    /// `POST /api/v1/auth/sign-in` -- Sign in with credentials.
    ///
    /// Returns cookies/headers for session management.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 (invalid credentials).
    pub async fn sign_in(&self, request: &types::SignInRequest) -> Result<(), Error> {
        self.send_no_content(self.post("/api/v1/auth/sign-in").json(request))
            .await
    }

    /// `POST /api/v1/auth/sign-out` -- Sign out.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401.
    pub async fn sign_out(&self) -> Result<(), Error> {
        self.send_no_content(self.post("/api/v1/auth/sign-out"))
            .await
    }

    /// `GET /api/v1/auth/me` -- Get current user info.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401.
    pub async fn me(&self) -> Result<ApiResponse<types::MeResponse>, Error> {
        self.send_envelope(self.get("/api/v1/auth/me")).await
    }

    // ── API Keys ───────────────────────────────────────────────────

    /// `GET /api/v1/api-keys` -- List API keys.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401.
    pub async fn list_api_keys(&self) -> Result<ApiResponse<Vec<types::ApiKeyResponse>>, Error> {
        self.send_envelope(self.get("/api/v1/api-keys")).await
    }

    /// `POST /api/v1/api-keys` -- Create a new API key.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400 or 401.
    pub async fn create_api_key(
        &self,
        request: &types::CreateApiKeyRequest,
    ) -> Result<ApiResponse<types::CreateApiKeyResponse>, Error> {
        self.send_envelope_once(self.post("/api/v1/api-keys").json(request))
            .await
    }

    /// `GET /api/v1/api-keys/scopes` -- List available API key scopes.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401.
    pub async fn available_scopes(&self) -> Result<ApiResponse<Vec<types::ScopeEntry>>, Error> {
        self.send_envelope(self.get("/api/v1/api-keys/scopes"))
            .await
    }

    /// `DELETE /api/v1/api-keys/:id` -- Delete an API key.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 or 401.
    pub async fn delete_api_key(&self, id: Uuid) -> Result<(), Error> {
        self.send_no_content(self.delete(&format!("/api/v1/api-keys/{id}")))
            .await
    }

    // ── Users (admin) ──────────────────────────────────────────────

    /// `GET /api/v1/users` -- List users (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 or 403.
    pub async fn list_users(&self) -> Result<ApiResponse<Vec<types::UserResponse>>, Error> {
        self.send_envelope(self.get("/api/v1/users")).await
    }

    /// `POST /api/v1/users` -- Create a user (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400, 401, 403, or 409.
    pub async fn create_user(
        &self,
        request: &types::CreateUserRequest,
    ) -> Result<ApiResponse<types::UserResponse>, Error> {
        self.send_envelope(self.post("/api/v1/users").json(request))
            .await
    }

    /// `DELETE /api/v1/users/:id` -- Delete a user (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404, 401, or 403.
    pub async fn delete_user(&self, id: Uuid) -> Result<(), Error> {
        self.send_no_content(self.delete(&format!("/api/v1/users/{id}")))
            .await
    }

    /// `PATCH /api/v1/users/:id/role` -- Update a user's role (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404, 401, or 403.
    pub async fn update_role(
        &self,
        id: Uuid,
        request: &types::UpdateRoleRequest,
    ) -> Result<ApiResponse<types::UserResponse>, Error> {
        self.send_envelope(
            self.patch(&format!("/api/v1/users/{id}/role"))
                .json(request),
        )
        .await
    }

    /// `GET /api/v1/users/:id/groups` -- List a user's groups (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401, 403, or 404.
    pub async fn get_user_groups(
        &self,
        id: Uuid,
    ) -> Result<ApiResponse<types::UserGroupsResponse>, Error> {
        self.send_envelope(self.get(&format!("/api/v1/users/{id}/groups")))
            .await
    }

    /// `PUT /api/v1/users/:id/groups` -- Replace a user's groups (admin only).
    ///
    /// Group membership restricts who may vote on an approval gate whose rule
    /// lists approver groups. An empty slice removes the user from every
    /// group.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400 (invalid group name), 401, 403, or 404.
    pub async fn update_user_groups(
        &self,
        id: Uuid,
        groups: &[String],
    ) -> Result<ApiResponse<types::UserGroupsResponse>, Error> {
        let request = types::UpdateUserGroupsRequest {
            groups: groups.to_vec(),
        };
        self.send_envelope(
            self.put(&format!("/api/v1/users/{id}/groups"))
                .json(&request),
        )
        .await
    }

    // ── Secrets (admin) ────────────────────────────────────────────

    /// `GET /api/v1/secrets` -- List secrets (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 or 403.
    pub async fn list_secrets(&self) -> Result<ApiResponse<Vec<types::SecretResponse>>, Error> {
        self.send_envelope(self.get("/api/v1/secrets")).await
    }

    /// `POST /api/v1/secrets` -- Create a secret (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400, 401, or 403.
    pub async fn create_secret(
        &self,
        request: &types::SetSecretRequest,
    ) -> Result<ApiResponse<types::SecretResponse>, Error> {
        self.send_envelope(self.post("/api/v1/secrets").json(request))
            .await
    }

    /// `PUT /api/v1/secrets/:key` -- Update a secret (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404, 401, or 403.
    pub async fn update_secret(
        &self,
        key: &str,
        request: &types::UpdateSecretRequest,
    ) -> Result<ApiResponse<types::SecretResponse>, Error> {
        self.send_envelope(self.put(&format!("/api/v1/secrets/{key}")).json(request))
            .await
    }

    /// `DELETE /api/v1/secrets/:key` -- Delete a secret (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404, 401, or 403.
    pub async fn delete_secret(&self, key: &str) -> Result<(), Error> {
        self.send_no_content(self.delete(&format!("/api/v1/secrets/{key}")))
            .await
    }

    /// `POST /api/v1/secrets/rotate` -- Re-encrypt one batch of secrets
    /// towards a key version (admin only).
    ///
    /// One call handles one batch. Loop, passing the returned `last_id` back
    /// as `after_id`, until `remaining` reaches zero or `last_id` is `None`.
    /// The operation is idempotent, so an interrupted rotation can simply be
    /// restarted.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 400 (unknown key version), 401, or 403.
    pub async fn rotate_secrets(
        &self,
        request: &types::RotateSecretsRequest,
    ) -> Result<ApiResponse<types::RotateSecretsResponse>, Error> {
        self.send_envelope(self.post("/api/v1/secrets/rotate").json(request))
            .await
    }

    /// `GET /api/v1/secrets/key-versions` -- Encryption key ring status
    /// (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 or 403.
    pub async fn secret_key_versions(
        &self,
    ) -> Result<ApiResponse<types::KeyVersionsResponse>, Error> {
        self.send_envelope(self.get("/api/v1/secrets/key-versions"))
            .await
    }

    // ── Run Logs ───────────────────────────────────────────────────

    /// `GET /api/v1/runs/:id/logs` -- Retrieve persisted log lines for a run.
    ///
    /// Returns log entries with cursor-based pagination. Pass the
    /// `next_cursor` from a previous response to fetch the next page.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 404 (run not found) or 401.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ironflow_sdk::IronflowClient;
    /// use ironflow_sdk::client::ListRunLogsFilter;
    /// use uuid::Uuid;
    ///
    /// # async fn example() -> Result<(), ironflow_sdk::Error> {
    /// let client = IronflowClient::new("https://ironflow.example.com", "key");
    /// let run_id = Uuid::nil();
    /// let logs = client.get_run_logs(run_id, &ListRunLogsFilter::default()).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_run_logs(
        &self,
        run_id: Uuid,
        filter: &ListRunLogsFilter<'_>,
    ) -> Result<ApiResponse<Vec<types::LogEntry>>, Error> {
        self.send_envelope(
            self.get(&format!("/api/v1/runs/{run_id}/logs"))
                .query(filter),
        )
        .await
    }

    // ── Audit Logs (admin) ─────────────────────────────────────────

    /// `GET /api/v1/audit-logs` -- List audit log entries (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 or 403.
    pub async fn list_audit_logs(&self) -> Result<ApiResponse<Vec<types::AuditLogEntry>>, Error> {
        self.list_audit_logs_filtered(&ListAuditLogsFilter::default())
            .await
    }

    /// `GET /api/v1/audit-logs` with query parameters (admin only).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Api`] on 401 or 403.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ironflow_sdk::IronflowClient;
    /// use ironflow_sdk::client::ListAuditLogsFilter;
    ///
    /// # async fn example() -> Result<(), ironflow_sdk::Error> {
    /// let client = IronflowClient::new("https://ironflow.example.com", "key");
    /// let filter = ListAuditLogsFilter {
    ///     event_type: Some("run_created"),
    ///     ..Default::default()
    /// };
    /// let entries = client.list_audit_logs_filtered(&filter).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_audit_logs_filtered(
        &self,
        filter: &ListAuditLogsFilter<'_>,
    ) -> Result<ApiResponse<Vec<types::AuditLogEntry>>, Error> {
        self.send_envelope(self.get("/api/v1/audit-logs").query(filter))
            .await
    }
}