jacquard 0.12.0-beta.1

Simple and powerful AT Protocol client library for Rust
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
//! XRPC client implementation for AT Protocol
//!
//! This module provides HTTP and XRPC client traits along with session management
//! for both app password and OAuth authentication.
//!
//! ## Key types
//!
//! - [`Agent<A>`] - Unified session wrapper with convenience methods
//! - [`CredentialSession`] - App-password authentication with auto-refresh
//! - [`crate::oauth::client::OAuthSession`] - OAuth/DPoP authentication
//! - [`AgentSession`] - Common trait for both session types
//!
//! ## Modules
//!
//! - [`credential_session`] - App-password session implementation
//! - [`token`] - Token storage and persistence
//! - [`vec_update`] - Trait for fetch-modify-put patterns on array endpoints
//!
//!
//! "Agent" in this context is derived from Bluesky's own library usage of the term.
//! It represents a (persistent) user session, and includes a number of helpful
//! methods which are available via the `AgentSessionExt` extension trait
//! on anything that implements `AgentSession` + `IdentityResolver`.

//pub mod bff_session;
/// App password session implementation with auto-refresh
pub mod credential_session;
/// Agent error type
pub mod error;
/// Token storage and on-disk persistence formats
pub mod token;
/// Trait for fetch-modify-put patterns on array-based endpoints
pub mod vec_update;

use crate::client::credential_session::{CredentialSession, SessionKey};
use crate::client::vec_update::VecUpdate;
use core::future::Future;
pub use error::*;
#[cfg(feature = "api")]
use jacquard_api::com_atproto::repo::get_record::GetRecordOutput;
#[cfg(feature = "api")]
use jacquard_api::com_atproto::{
    repo::{
        create_record::CreateRecordOutput, delete_record::DeleteRecordOutput,
        get_record::GetRecordResponse, put_record::PutRecordOutput,
    },
    server::{create_session::CreateSessionOutput, refresh_session::RefreshSessionOutput},
};
use jacquard_common::deps::fluent_uri::Uri;
use jacquard_common::error::XrpcResult;
pub use jacquard_common::error::{ClientError, XrpcResult as ClientResult};
use jacquard_common::http_client::HttpClient;
pub use jacquard_common::session::{MemorySessionStore, SessionStore, SessionStoreError};
use jacquard_common::types::blob::{Blob, MimeType};
use jacquard_common::types::collection::Collection;
#[cfg(feature = "api")]
use jacquard_common::types::ident::AtIdentifier;
use jacquard_common::types::recordkey::{RecordKey, Rkey};
use jacquard_common::types::string::AtUri;
#[cfg(feature = "api")]
use jacquard_common::types::uri::RecordUri;
use jacquard_common::xrpc::XrpcResponse;
use jacquard_common::xrpc::{
    CallOptions, Response, XrpcClient, XrpcError, XrpcExt, XrpcRequest, XrpcResp,
};
use jacquard_common::{AuthorizationToken, xrpc};
use jacquard_common::{
    BosStr, CowStr, IntoStatic,
    types::string::{Did, Handle},
};
use jacquard_identity::resolver::{
    DidDocResponse, IdentityError, IdentityResolver, ResolverOptions,
};
use jacquard_identity::{JacquardResolver, slingshot_resolver_default};
use jacquard_oauth::authstore::ClientAuthStore;
use jacquard_oauth::client::{OAuthClient, OAuthSession};
use jacquard_oauth::dpop::DpopExt;
use jacquard_oauth::resolver::OAuthResolver;
use serde::Serialize;
#[cfg(feature = "api")]
use serde::de::DeserializeOwned;
use smol_str::SmolStr;
#[cfg(feature = "api")]
use std::marker::Send;
use std::option::Option;
use std::sync::Arc;
pub use token::FileAuthStore;
use tokio::sync::RwLock;

/// Identifies the active authentication mode for an agent/session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentKind {
    /// App password (Bearer) session
    AppPassword,
    /// OAuth (DPoP) session
    OAuth,
}

/// Common interface for stateful sessions used by the Agent wrapper.
///
/// Implemented by `CredentialSession` (app‑password) and `OAuthSession` (DPoP).
#[cfg_attr(not(target_arch = "wasm32"), trait_variant::make(Send))]
pub trait AgentSession: XrpcClient + HttpClient + Send + Sync {
    /// Identify the kind of session.
    fn session_kind(&self) -> AgentKind;
    /// Return current DID and an optional session id (always Some for OAuth).
    fn session_info(&self) -> impl Future<Output = Option<(Did, Option<SmolStr>)>>;
    /// Current base endpoint.
    fn endpoint(&self) -> impl Future<Output = Uri<String>>;
    /// Override per-session call options.
    fn set_options<'a>(&'a self, opts: CallOptions<'a>) -> impl Future<Output = ()>;
    /// Refresh the session and return a fresh AuthorizationToken.
    fn refresh(&self) -> impl Future<Output = ClientResult<AuthorizationToken<SmolStr>>>;
}

/// Alias for an agent over a credential (app‑password) session.
pub type CredentialAgent<S, T> = Agent<CredentialSession<S, T>>;
/// Alias for an agent over an OAuth (DPoP) session.
pub type OAuthAgent<T, S> = Agent<OAuthSession<T, S>>;

/// BasicClient: in-memory store + public resolver over a credential session.
pub type BasicClient = Agent<
    CredentialSession<
        MemorySessionStore<SessionKey, AtpSession>,
        jacquard_identity::PublicResolver,
    >,
>;

impl BasicClient {
    /// Create an unauthenticated BasicClient for public API access.
    ///
    /// Uses an in-memory session store and public resolver. Suitable for
    /// read-only operations on public data without authentication.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use jacquard::client::BasicClient;
    /// # use jacquard::types::string::AtUri;
    /// # use jacquard_api::app_bsky::feed::post::Post;
    /// use crate::jacquard::client::AgentSessionExt;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = BasicClient::unauthenticated();
    /// let uri = AtUri::new_static("at://did:plc:xyz/app.bsky.feed.post/3l5abc").unwrap();
    /// let response = client.get_record::<Post, _>(&uri).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn unauthenticated() -> Self {
        use std::sync::Arc;
        let http = reqwest::Client::new();
        let resolver = jacquard_identity::PublicResolver::new(http, Default::default());
        let store = MemorySessionStore::default();
        let session = CredentialSession::new(Arc::new(store), Arc::new(resolver));
        Agent::new(session)
    }
}

impl Default for BasicClient {
    fn default() -> Self {
        Self::unauthenticated()
    }
}

/// Unauthenticated XRPC client session with identity resolution
#[derive(Debug, Clone)]
pub struct UnauthenticatedSession<T> {
    resolver: Arc<T>,
    endpoint: Arc<RwLock<Option<Uri<String>>>>,
    options: Arc<RwLock<CallOptions<'static>>>,
}

impl Default for UnauthenticatedSession<JacquardResolver> {
    fn default() -> Self {
        Self::new_public()
    }
}

impl UnauthenticatedSession<JacquardResolver> {
    /// Create a new unauthenticated session using the public bluesky appview api as a fallback resolver
    pub fn new_public() -> Self {
        let resolver = Arc::new(JacquardResolver::default());
        let endpoint = Arc::new(RwLock::new(None));
        let options = Arc::new(RwLock::new(CallOptions::default()));
        Self {
            resolver,
            endpoint,
            options,
        }
    }

    /// Create a new unauthenticated session using the Slingshot service for handle resolution
    pub fn new_slingshot() -> Self {
        let resolver = Arc::new(slingshot_resolver_default());
        let endpoint = Arc::new(RwLock::new(None));
        let options = Arc::new(RwLock::new(CallOptions::default()));
        Self {
            resolver,
            endpoint,
            options,
        }
    }
}

impl<T: HttpClient + Sync> HttpClient for UnauthenticatedSession<T> {
    type Error = T::Error;

    #[cfg(not(target_arch = "wasm32"))]
    fn send_http(
        &self,
        request: http::Request<Vec<u8>>,
    ) -> impl Future<Output = core::result::Result<http::Response<Vec<u8>>, T::Error>> + Send {
        self.resolver.send_http(request)
    }

    #[cfg(target_arch = "wasm32")]
    fn send_http(
        &self,
        request: http::Request<Vec<u8>>,
    ) -> impl Future<Output = core::result::Result<http::Response<Vec<u8>>, T::Error>> {
        self.resolver.send_http(request)
    }
}

impl<T: HttpClient> XrpcClient for UnauthenticatedSession<T>
where
    T: Sync + Send,
{
    #[doc = " Get the base URI for the client."]
    fn base_uri(&self) -> impl Future<Output = Uri<String>> + Send {
        async move {
            self.endpoint.read().await.clone().unwrap_or_else(|| {
                Uri::parse("https://public.api.bsky.app")
                    .expect("hardcoded URI is valid")
                    .to_owned()
            })
        }
    }

    #[doc = " Send an XRPC request and parse the response"]
    #[cfg(not(target_arch = "wasm32"))]
    fn send<R>(&self, request: R) -> impl Future<Output = XrpcResult<XrpcResponse<R>>> + Send
    where
        R: XrpcRequest + Send + Sync + Serialize,
        <R as XrpcRequest>::Response: Send + Sync,
        Self: Sync,
    {
        async move {
            let opts = self.options.read().await.clone();
            self.send_with_opts(request, opts).await
        }
    }

    #[doc = " Send an XRPC request and parse the response"]
    #[cfg(not(target_arch = "wasm32"))]
    fn send_with_opts<R>(
        &self,
        request: R,
        opts: CallOptions<'_>,
    ) -> impl Future<Output = XrpcResult<XrpcResponse<R>>> + Send
    where
        R: XrpcRequest + Send + Sync + Serialize,
        <R as XrpcRequest>::Response: Send + Sync,
        Self: Sync,
    {
        async move {
            let base_uri = self.base_uri().await;
            self.resolver
                .xrpc(base_uri.borrow())
                .with_options(opts.clone())
                .send(&request)
                .await
        }
    }

    #[doc = " Send an XRPC request and parse the response"]
    #[cfg(target_arch = "wasm32")]
    fn send<R>(&self, request: R) -> impl Future<Output = XrpcResult<XrpcResponse<R>>>
    where
        R: XrpcRequest + Send + Sync + Serialize,
        <R as XrpcRequest>::Response: Send + Sync,
    {
        async move {
            let opts = self.options.read().await.clone();
            self.send_with_opts(request, opts).await
        }
    }

    #[doc = " Send an XRPC request and parse the response"]
    #[cfg(target_arch = "wasm32")]
    fn send_with_opts<R>(
        &self,
        request: R,
        opts: CallOptions<'_>,
    ) -> impl Future<Output = XrpcResult<XrpcResponse<R>>>
    where
        R: XrpcRequest + Send + Sync + Serialize,
        <R as XrpcRequest>::Response: Send + Sync,
    {
        async move {
            let base_uri = self.base_uri().await;
            self.resolver
                .xrpc(base_uri.borrow())
                .with_options(opts.clone())
                .send(&request)
                .await
        }
    }

    #[doc = " Set the base URI for the client."]
    fn set_base_uri(&self, uri: Uri<String>) -> impl Future<Output = ()> + Send {
        async move {
            let normalized = crate::xrpc::normalize_base_uri(uri);
            let mut guard = self.endpoint.write().await;
            *guard = Some(normalized);
        }
    }

    #[doc = " Get the call options for the client."]
    fn opts(&self) -> impl Future<Output = CallOptions<'_>> + Send {
        async move { self.options.read().await.clone() }
    }

    #[doc = " Set the call options for the client."]
    fn set_opts(&self, opts: CallOptions<'_>) -> impl Future<Output = ()> + Send {
        async move {
            *self.options.write().await = opts.into_static();
        }
    }
}

impl<T: IdentityResolver + HttpClient> AgentSession for UnauthenticatedSession<T>
where
    T: Sync + Send,
{
    fn session_kind(&self) -> AgentKind {
        AgentKind::AppPassword
    }

    fn session_info(&self) -> impl Future<Output = Option<(Did, Option<SmolStr>)>> {
        async { None } // no session
    }

    fn endpoint(&self) -> impl Future<Output = Uri<String>> {
        async { self.base_uri().await }
    }

    #[doc = " Override per-session call options."]
    fn set_options<'a>(&'a self, opts: CallOptions<'a>) -> impl Future<Output = ()> + Send {
        async move {
            *self.options.write().await = opts.into_static();
        }
    }

    #[doc = " Refresh the session and return a fresh AuthorizationToken."]
    fn refresh(&self) -> impl Future<Output = ClientResult<AuthorizationToken<SmolStr>>> + Send {
        async {
            Err(ClientError::auth(
                jacquard_common::error::AuthError::NotAuthenticated,
            ))
        }
    }
}

impl<T: IdentityResolver + Sync> IdentityResolver for UnauthenticatedSession<T> {
    #[doc = " Access options for validation decisions in default methods"]
    fn options(&self) -> &ResolverOptions {
        self.resolver.options()
    }

    #[doc = " Resolve handle"]
    #[cfg(not(target_arch = "wasm32"))]
    fn resolve_handle<S: BosStr + Sync>(
        &self,
        handle: &Handle<S>,
    ) -> impl Future<Output = std::result::Result<Did, IdentityError>> + Send
    where
        Self: Sync,
    {
        self.resolver.resolve_handle(handle)
    }

    #[doc = " Resolve DID document"]
    #[cfg(not(target_arch = "wasm32"))]
    fn resolve_did_doc<S: BosStr + Sync>(
        &self,
        did: &Did<S>,
    ) -> impl Future<Output = std::result::Result<DidDocResponse, IdentityError>> + Send
    where
        Self: Sync,
    {
        self.resolver.resolve_did_doc(did)
    }

    #[doc = " Resolve handle"]
    #[cfg(target_arch = "wasm32")]
    fn resolve_handle<S: BosStr + Sync>(
        &self,
        handle: &Handle<S>,
    ) -> impl Future<Output = std::result::Result<Did, IdentityError>> {
        self.resolver.resolve_handle(handle)
    }

    #[doc = " Resolve DID document"]
    #[cfg(target_arch = "wasm32")]
    fn resolve_did_doc<S: BosStr + Sync>(
        &self,
        did: &Did<S>,
    ) -> impl Future<Output = std::result::Result<DidDocResponse, IdentityError>> {
        self.resolver.resolve_did_doc(did)
    }
}

/// MemoryCredentialSession: credential session with in memory store and identity resolver
pub type MemoryCredentialSession = CredentialSession<
    MemorySessionStore<SessionKey, AtpSession>,
    jacquard_identity::PublicResolver,
>;

impl MemoryCredentialSession {
    /// Create an unauthenticated MemoryCredentialSession.
    ///
    /// Uses an in memory store and a public resolver.
    /// Equivalent to a BasicClient that isn't wrapped in Agent
    pub fn unauthenticated() -> Self {
        use std::sync::Arc;
        let http = reqwest::Client::new();
        let resolver = jacquard_identity::PublicResolver::new(http, Default::default());
        let store = MemorySessionStore::default();
        CredentialSession::new(Arc::new(store), Arc::new(resolver))
    }

    /// Create a MemoryCredentialSession and authenticate with the provided details
    ///
    /// - `identifier`: handle (preferred), DID, or `https://` PDS base URL.
    /// - `session_id`: optional session label; defaults to "session".
    /// - Persists and activates the session, and updates the base endpoint to the user's PDS.
    ///
    /// # Example
    /// ```no_run
    /// # use jacquard::client::BasicClient;
    /// # use jacquard::types::string::AtUri;
    /// # use jacquard::api::app_bsky::feed::post::Post;
    /// # use jacquard::types::string::Datetime;
    /// # use jacquard::CowStr;
    /// use jacquard::client::MemoryCredentialSession;
    /// use jacquard::client::{Agent, AgentSessionExt};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let (identifier, password, post_text): (CowStr<'_>, CowStr<'_>, CowStr<'_>)  = todo!();
    /// let (session, _) = MemoryCredentialSession::authenticated(identifier, password, None, None).await?;
    /// let agent = Agent::from(session);
    /// let post = Post::new().text(post_text).created_at(Datetime::now()).build();
    /// let output = agent.create_record(post, None).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn authenticated(
        identifier: CowStr<'_>,
        password: CowStr<'_>,
        session_id: Option<CowStr<'_>>,
        pds: Option<Uri<String>>,
    ) -> ClientResult<(Self, AtpSession)> {
        let session = MemoryCredentialSession::unauthenticated();
        let auth = session
            .login(identifier, password, session_id, None, None, pds)
            .await?;
        Ok((session, auth))
    }
}

impl Default for MemoryCredentialSession {
    fn default() -> Self {
        MemoryCredentialSession::unauthenticated()
    }
}

/// App password session information from `com.atproto.server.createSession`
///
/// Contains the access and refresh tokens along with user identity information.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AtpSession {
    /// Access token (JWT) used for authenticated requests
    pub access_jwt: SmolStr,
    /// Refresh token (JWT) used to obtain new access tokens
    pub refresh_jwt: SmolStr,
    /// User's DID (Decentralized Identifier)
    pub did: Did,
    /// User's handle (e.g., "alice.bsky.social")
    pub handle: Handle,
}

impl IntoStatic for AtpSession {
    type Output = Self;

    fn into_static(self) -> Self {
        self
    }
}

#[cfg(feature = "api")]
impl From<CreateSessionOutput> for AtpSession {
    fn from(output: CreateSessionOutput) -> Self {
        Self {
            access_jwt: output.access_jwt,
            refresh_jwt: output.refresh_jwt,
            did: output.did,
            handle: output.handle,
        }
    }
}

#[cfg(feature = "api")]
impl From<RefreshSessionOutput> for AtpSession {
    fn from(output: RefreshSessionOutput) -> Self {
        Self {
            access_jwt: output.access_jwt,
            refresh_jwt: output.refresh_jwt,
            did: output.did,
            handle: output.handle,
        }
    }
}

/// Thin wrapper over a stateful session providing a uniform `XrpcClient`.
pub struct Agent<A: AgentSession> {
    inner: A,
}

impl<A: AgentSession> Agent<A> {
    /// Wrap an existing session in an Agent.
    pub fn new(inner: A) -> Self {
        Self { inner }
    }

    /// Get a reference to the underlying session
    pub fn inner(&self) -> &A {
        &self.inner
    }

    /// Return the underlying session kind.
    pub fn kind(&self) -> AgentKind {
        self.inner.session_kind()
    }

    /// Return session info if available.
    pub async fn info(&self) -> Option<(Did, Option<SmolStr>)> {
        self.inner.session_info().await
    }

    /// Get current endpoint.
    pub async fn endpoint(&self) -> Uri<String> {
        self.inner.endpoint().await
    }

    /// Override call options for subsequent requests.
    pub async fn set_options(&self, opts: CallOptions<'_>) {
        self.inner.set_options(opts).await
    }

    /// Refresh the session and return a fresh token.
    pub async fn refresh(&self) -> ClientResult<AuthorizationToken<SmolStr>> {
        self.inner.refresh().await
    }
}

/// Output type for a collection record retrieval operation (SmolStr-backed, as returned by `into_output()`)
pub type CollectionOutput<R> = <<R as Collection>::Record as XrpcResp>::Output<SmolStr>;
/// Error type for a collection record retrieval operation
pub type CollectionErr<R> = <<R as Collection>::Record as XrpcResp>::Err;
/// Response type for the get request of a vec update operation
pub type VecGetResponse<U> = <<U as VecUpdate>::GetRequest as XrpcRequest>::Response;
/// Response type for the put request of a vec update operation
pub type VecPutResponse<U> = <<U as VecUpdate>::PutRequest as XrpcRequest>::Response;

type CollectionError<R> = <<R as Collection>::Record as XrpcResp>::Err;

type VecUpdateGetError<U> =
    <<<U as VecUpdate>::GetRequest as XrpcRequest>::Response as XrpcResp>::Err;

type VecUpdatePutError<U> =
    <<<U as VecUpdate>::PutRequest as XrpcRequest>::Response as XrpcResp>::Err;

/// Extension trait providing convenience methods for common repository operations.
///
/// This trait is automatically implemented for any type that implements both
/// [`AgentSession`] and [`IdentityResolver`]. It provides higher-level methods
/// that handle common patterns like fetch-modify-put, with automatic repo resolution
/// for at:// uris, and typed record operations.
///
/// # Available Operations
///
/// - **Basic CRUD**: [`create_record`](Self::create_record), [`get_record`](Self::get_record),
///   [`put_record`](Self::put_record), [`delete_record`](Self::delete_record)
/// - **Update patterns**: [`update_record`](Self::update_record) (fetch-modify-put for records),
///   [`update_vec`](Self::update_vec) and [`update_vec_item`](Self::update_vec_item) (for array endpoints)
/// - **Blob operations**: [`upload_blob`](Self::upload_blob)
///
/// # Example
///
/// ```no_run
/// # use jacquard::client::BasicClient;
/// # use jacquard_api::app_bsky::feed::post::Post;
/// # use jacquard_common::types::string::{AtUri, Datetime};
/// # use jacquard_common::CowStr;
/// use jacquard::client::AgentSessionExt;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let agent: BasicClient = todo!();
/// // Create a post
/// let post = Post {
///     text: CowStr::from("Hello from Jacquard!"),
///     created_at: Datetime::now(),
///     # embed: None, entities: None, facets: None, labels: None,
///     # langs: None, reply: None, tags: None, extra_data: Default::default(),
/// };
/// let output = agent.create_record(post, None).await?;
///
/// // Read it back
/// let response = agent.get_record::<Post, _>(&output.uri).await?;
/// let record = response.parse()?;
/// println!("Post: {}", record.value.text);
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "api")]
pub trait AgentSessionExt: AgentSession + IdentityResolver {
    /// Create a new record in the repository.
    ///
    /// The collection is inferred from the record type's `Collection::NSID`.
    /// The repo is automatically filled from the session info.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use jacquard::client::BasicClient;
    /// # use jacquard_api::app_bsky::feed::post::Post;
    /// # use jacquard_common::types::string::Datetime;
    /// # use jacquard_common::CowStr;
    /// use jacquard::client::AgentSessionExt;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let agent: BasicClient = todo!();
    /// let post = Post {
    ///     text: CowStr::from("Hello world!"),
    ///     created_at: Datetime::now(),
    ///     embed: None,
    ///     entities: None,
    ///     facets: None,
    ///     labels: None,
    ///     langs: None,
    ///     reply: None,
    ///     tags: None,
    ///     extra_data: Default::default(),
    /// };
    /// let output = agent.create_record(post, None).await?;
    /// println!("Created record: {}", output.uri);
    /// # Ok(())
    /// # }
    /// ```
    fn create_record<R>(
        &self,
        record: R,
        rkey: Option<RecordKey<Rkey>>,
    ) -> impl Future<Output = Result<CreateRecordOutput>>
    where
        R: Collection + serde::Serialize,
    {
        async move {
            use jacquard_api::com_atproto::repo::create_record::CreateRecord;
            use jacquard_common::types::ident::AtIdentifier;
            use jacquard_common::types::value::to_data;

            let (did, _) = self
                .session_info()
                .await
                .ok_or_else(|| AgentError::no_session().for_collection("create record", R::NSID))?;

            #[cfg(feature = "tracing")]
            let _span = tracing::debug_span!("create_record", collection = %R::nsid()).entered();

            let data =
                to_data(&record).map_err(|e| AgentError::sub_operation("serialize record", e))?;

            let request = CreateRecord::new()
                .repo(AtIdentifier::Did(did))
                .collection(R::nsid().into_static())
                .record(data)
                .rkey(rkey.map(|k| k.clone()))
                .build();

            #[cfg(feature = "tracing")]
            _span.exit();

            let response = self
                .send(request)
                .await
                .map_err(|e| e.for_collection("create record", R::NSID))?;
            response.into_output().map_err(|e| match e {
                XrpcError::Auth(auth) => AgentError::from(auth),
                XrpcError::Xrpc(typed) => AgentError::sub_operation("create record", typed),
                e => AgentError::xrpc(e),
            })
        }
    }

    /// Get a record from the repository using an at:// URI.
    ///
    /// Returns a typed `Response` that deserializes directly to the record type.
    /// Use `.parse()` to borrow from the response buffer, or `.into_output()` for owned data.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use jacquard::client::BasicClient;
    /// # use jacquard_api::app_bsky::feed::post::Post;
    /// # use jacquard_common::types::string::AtUri;
    /// # use jacquard_common::IntoStatic;
    /// use jacquard::client::AgentSessionExt;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let agent: BasicClient = todo!();
    /// let uri = AtUri::new_static("at://did:plc:xyz/app.bsky.feed.post/3l5bqm7lepk2c").unwrap();
    /// let response = agent.get_record::<Post, _>(&uri).await?;
    /// let output = response.parse()?;  // PostGetRecordOutput<'_> borrowing from buffer
    /// println!("Post text: {}", output.value.text);
    ///
    /// // Or get owned data
    /// let output_owned = response.into_output()?;
    /// # Ok(())
    /// # }
    /// ```
    fn get_record<R, S>(
        &self,
        uri: &AtUri<S>,
    ) -> impl Future<Output = ClientResult<Response<R::Record>>>
    where
        R: Collection,
        S: BosStr + Sync,
    {
        async move {
            #[cfg(feature = "tracing")]
            let _span =
                tracing::debug_span!("get_record", collection = %R::nsid(), uri = %uri).entered();

            // Validate that URI's collection matches the expected type
            if let Some(uri_collection) = uri.collection() {
                if uri_collection.as_str() != R::nsid().as_str() {
                    return Err(ClientError::invalid_request(format!(
                        "Collection mismatch: URI contains '{}' but type parameter expects '{}'",
                        uri_collection,
                        R::nsid()
                    ))
                    .with_help("ensure the URI collection matches the record type"));
                }
            }

            let rkey = uri.rkey().ok_or_else(|| {
                ClientError::invalid_request("AtUri missing rkey")
                    .with_help("ensure the URI includes a record key after the collection")
            })?;

            #[cfg(feature = "tracing")]
            _span.exit();

            // Resolve authority (DID or handle) to get DID and PDS.
            let (repo_did, pds_url) = match uri.authority() {
                AtIdentifier::Did(did) => {
                    let pds = self.pds_for_did(&did).await.map_err(|e| {
                        ClientError::from(e)
                            .with_context("DID document resolution failed during record retrieval")
                    })?;
                    (did.into_static(), pds)
                }
                AtIdentifier::Handle(handle) => {
                    self.pds_for_handle(&handle).await.map_err(|e| {
                        ClientError::from(e)
                            .with_context("handle resolution failed during record retrieval")
                    })?
                }
            };

            // Make stateless XRPC call to that PDS (no auth required for public records).
            // All fields use SmolStr backing to satisfy the builder's single S type parameter.
            use jacquard_api::com_atproto::repo::get_record::GetRecord;
            let request = GetRecord::new()
                .repo(AtIdentifier::Did(repo_did.clone()))
                .collection(R::nsid().into_static())
                .rkey(rkey.into_static())
                .build();

            let response: Response<GetRecordResponse> = {
                let http_request =
                    xrpc::build_http_request(&pds_url.borrow(), &request, &self.opts().await)?;

                let http_response = self
                    .send_http(http_request)
                    .await
                    .map_err(|e| ClientError::transport(e).for_collection("get record", R::NSID))?;

                xrpc::process_response(http_response)
                    .map_err(|e| e.for_collection("get record", R::NSID))?
            };
            Ok(response.transmute())
        }
    }

    /// Untyped, freeform record fetcher.
    /// Hits <https://slingshot.microcosm.blue>
    fn fetch_record_slingshot<S>(
        &self,
        uri: &AtUri<S>,
    ) -> impl Future<Output = Result<GetRecordOutput>>
    where
        S: BosStr + Sync,
    {
        async move {
            #[cfg(feature = "tracing")]
            let _span = tracing::debug_span!("fetch_record_slingshot", uri = %uri).entered();

            // Make stateless XRPC call to that PDS (no auth required for public records)
            use jacquard_api::com_atproto::repo::get_record::GetRecord;
            let collection = uri.collection().clone().ok_or(AgentError::sub_operation(
                "no collection",
                ClientError::invalid_request("no collection"),
            ))?;
            let rkey = uri.rkey().ok_or(AgentError::sub_operation(
                "no rkey",
                ClientError::invalid_request("no rkey"),
            ))?;
            let request = GetRecord::new()
                .repo(uri.authority().clone())
                .collection(collection.clone())
                .rkey(RecordKey(rkey.clone()))
                .build();

            #[cfg(feature = "tracing")]
            _span.exit();

            let response: Response<GetRecordResponse> = {
                let http_request = xrpc::build_http_request(
                    &Uri::parse("https://slingshot.microcosm.blue")
                        .expect("slingshot url is valid"),
                    &request,
                    &self.opts().await,
                )?;

                let http_response = self.send_http(http_request).await.map_err(|e| {
                    ClientError::transport(e).for_collection("fetch record", collection.as_str())
                })?;

                xrpc::process_response(http_response)
                    .map_err(|e| e.for_collection("fetch record", collection.as_str()))?
            };
            let output = response.into_output().map_err(|e| match e {
                XrpcError::Auth(auth) => AgentError::from(auth),
                XrpcError::Xrpc(typed) => AgentError::sub_operation("parse record", typed),
                e => AgentError::xrpc(e),
            })?;
            Ok(output)
        }
    }

    /// Fetches a record from the PDS. Returns an owned, parsed response.
    ///
    /// Takes an at:// URI annotated with the collection type, which be constructed with `R::uri(uri)`
    /// where `R` is the type of record you want (e.g. `app_bsky::feed::post::Post::uri(uri)` for Bluesky posts).
    fn fetch_record<R, S>(
        &self,
        uri: &RecordUri<S, R>,
    ) -> impl Future<Output = Result<CollectionOutput<R>>>
    where
        R: Collection,
        S: BosStr + Sync,
        CollectionOutput<R>: serde::de::DeserializeOwned,
        CollectionError<R>: Send + Sync + 'static,
    {
        let uri = uri.as_uri();
        async move {
            use smol_str::format_smolstr;

            let response = self.get_record::<R, S>(uri).await?;
            let response: Response<R::Record> = response.transmute();
            let output = response.into_output().map_err(|e| match e {
                XrpcError::Auth(auth) => AgentError::from(auth),
                XrpcError::Xrpc(typed) => AgentError::new(
                    AgentErrorKind::SubOperation {
                        step: "parse record",
                    },
                    None,
                )
                .with_details(format_smolstr!("{:?}", typed)),
                // Note: typed error formatted as Debug since CollectionErr<R> is not Display.
                e => AgentError::xrpc(e),
            })?;
            Ok(output)
        }
    }

    /// Update a record in-place with a fetch-modify-put pattern.
    ///
    /// This fetches the record using an at:// URI, converts it to owned data, applies
    /// the modification function, and puts it back. The modification function receives
    /// a mutable reference to the record data.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use jacquard::client::BasicClient;
    /// # use jacquard_api::app_bsky::actor::profile::Profile;
    /// # use jacquard_common::CowStr;
    /// # use jacquard_common::types::string::AtUri;
    /// use jacquard::client::AgentSessionExt;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let agent: BasicClient = todo!();
    /// let uri = AtUri::new_static("at://did:plc:xyz/app.bsky.actor.profile/self").unwrap();
    /// // Update profile record in-place
    /// agent.update_record::<Profile, _>(&uri, |profile| {
    ///     profile.display_name = Some(CowStr::from("New Name"));
    ///     profile.description = Some(CowStr::from("Updated bio"));
    /// }).await?;
    /// # Ok(())
    /// # }
    /// ```
    fn update_record<R, S>(
        &self,
        uri: &AtUri<S>,
        f: impl FnOnce(&mut R),
    ) -> impl Future<Output = Result<PutRecordOutput>>
    where
        R: Collection + Serialize,
        R: From<CollectionOutput<R>>,
        CollectionOutput<R>: serde::de::DeserializeOwned,
        CollectionError<R>: Send + Sync + std::error::Error + 'static,
        S: BosStr + Sync,
    {
        async move {
            // Fetch the record - Response<R::Record> where R::Record::Output<SmolStr> = R
            let response = self.get_record::<R, S>(uri).await?;

            #[cfg(feature = "tracing")]
            let _span = tracing::debug_span!("update_record", collection = %R::nsid(), uri = %uri)
                .entered();

            // Parse to get the record, borrowing from the response buffer.
            // Err is now a plain owned type; no into_static() needed.
            let record = response.parse().map_err(|e| match e {
                XrpcError::Auth(auth) => AgentError::from(auth),
                XrpcError::Xrpc(typed) => AgentError::sub_operation("parse record", typed),
                e => AgentError::xrpc(e),
            })?;

            // Convert to owned
            let mut owned = R::from(record);

            // Apply modification
            f(&mut owned);

            // Put it back
            // Convert the borrowed Rkey<&str> to an owned Rkey<SmolStr>, then wrap in RecordKey.
            // The Rkey<SmolStr> is already validated (extracted from a valid AtUri), so direct
            // construction is safe.
            let rkey = RecordKey(
                uri.rkey()
                    .ok_or_else(|| {
                        use jacquard_common::types::string::AtStrError;
                        AgentError::sub_operation(
                            "extract rkey",
                            AtStrError::missing("at-uri-scheme", &uri, "rkey"),
                        )
                    })?
                    .convert::<SmolStr>(),
            );

            #[cfg(feature = "tracing")]
            _span.exit();
            self.put_record::<R>(rkey, owned).await
        }
    }

    /// Delete a record from the repository.
    ///
    /// The collection is inferred from the type parameter.
    /// The repo is automatically filled from the session info.
    fn delete_record<R>(
        &self,
        rkey: RecordKey<Rkey>,
    ) -> impl Future<Output = Result<DeleteRecordOutput>>
    where
        R: Collection + Serialize,
    {
        async move {
            let (did, _) = self
                .session_info()
                .await
                .ok_or_else(|| AgentError::no_session().for_collection("delete record", R::NSID))?;
            #[cfg(feature = "tracing")]
            let _span = tracing::debug_span!("delete_record", collection = %R::nsid()).entered();

            use jacquard_api::com_atproto::repo::delete_record::DeleteRecord;
            use jacquard_common::types::ident::AtIdentifier;

            let request = DeleteRecord::new()
                .repo(AtIdentifier::Did(did.clone()))
                .collection(R::nsid().into_static())
                .rkey(rkey.into_static())
                .build();

            #[cfg(feature = "tracing")]
            _span.exit();

            let response = self
                .send(request)
                .await
                .map_err(|e| e.for_collection("delete record", R::NSID))?;
            response.into_output().map_err(|e| match e {
                XrpcError::Auth(auth) => AgentError::from(auth),
                XrpcError::Xrpc(typed) => AgentError::sub_operation("delete record", typed),
                e => AgentError::xrpc(e),
            })
        }
    }

    /// Put (upsert) a record in the repository.
    ///
    /// The collection is inferred from the record type's `Collection::NSID`.
    /// The repo is automatically filled from the session info.
    fn put_record<R>(
        &self,
        rkey: RecordKey<Rkey>,
        record: R,
    ) -> impl Future<Output = Result<PutRecordOutput>>
    where
        R: Collection + serde::Serialize,
    {
        async move {
            #[cfg(feature = "tracing")]
            let _span = tracing::debug_span!("put_record", collection = %R::nsid()).entered();

            use jacquard_api::com_atproto::repo::put_record::PutRecord;
            use jacquard_common::types::ident::AtIdentifier;
            use jacquard_common::types::value::to_data;

            let (did, _) = self
                .session_info()
                .await
                .ok_or_else(|| AgentError::no_session().for_collection("put record", R::NSID))?;

            let data =
                to_data(&record).map_err(|e| AgentError::sub_operation("serialize record", e))?;

            let request = PutRecord::new()
                .repo(AtIdentifier::Did(did.clone()))
                .collection(R::nsid().into_static())
                .rkey(rkey.into_static())
                .record(data)
                .build();

            #[cfg(feature = "tracing")]
            _span.exit();

            let response = self
                .send(request)
                .await
                .map_err(|e| e.for_collection("put record", R::NSID))?;
            response.into_output().map_err(|e| match e {
                XrpcError::Auth(auth) => AgentError::from(auth),
                XrpcError::Xrpc(typed) => AgentError::sub_operation("put record", typed),
                e => AgentError::xrpc(e),
            })
        }
    }

    /// Upload a blob to the repository.
    ///
    /// The mime type is sent as a Content-Type header hint, though the server also performs
    /// its own inference.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use jacquard::client::BasicClient;
    /// # use jacquard_common::types::blob::MimeType;
    /// use jacquard::client::AgentSessionExt;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let agent: BasicClient = todo!();
    /// let data = std::fs::read("image.png")?;
    /// let mime_type = MimeType::new_static("image/png");
    /// let blob_ref = agent.upload_blob(data, mime_type).await?;
    /// # Ok(())
    /// # }
    /// ```
    fn upload_blob(
        &self,
        data: impl Into<bytes::Bytes>,
        mime_type: MimeType<&str>,
    ) -> impl Future<Output = Result<Blob>> {
        async move {
            #[cfg(feature = "tracing")]
            let _span = tracing::debug_span!("upload_blob", mime_type = %mime_type).entered();

            use http::header::CONTENT_TYPE;
            use jacquard_api::com_atproto::repo::upload_blob::UploadBlob;

            let bytes = data.into();
            let request = UploadBlob { body: bytes };

            // Override Content-Type header with actual mime type instead of */*
            let mut opts = self.opts().await;

            opts.extra_headers.push((
                CONTENT_TYPE,
                http::HeaderValue::from_str(mime_type.as_str())
                    .map_err(|e| AgentError::sub_operation("set Content-Type header", e))?,
            ));

            #[cfg(feature = "tracing")]
            _span.exit();

            let response = self.send_with_opts(request, opts).await?;
            let output = response.into_output().map_err(|e| match e {
                XrpcError::Auth(auth) => AgentError::from(auth),
                XrpcError::Xrpc(typed) => AgentError::sub_operation("upload blob", typed),
                e => AgentError::xrpc(e),
            })?;
            // Blob is now SmolStr-backed (owned), so no into_static() needed.
            Ok(output.blob.blob().clone())
        }
    }

    /// Update a vec-based data structure with a fetch-modify-put pattern.
    ///
    /// This is useful for endpoints like preferences that return arrays requiring
    /// fetch-modify-put operations.
    ///
    /// # Example
    ///
    /// ```ignore
    /// agent.update_vec::<PreferencesUpdate>(|prefs| {
    ///     prefs.push(AdultContentPref::new().enabled(true).build().into());
    ///     prefs.retain(|p| !matches!(p, Preference::Hidden(_)));
    /// }).await?;
    /// ```
    fn update_vec<'a, U>(
        &self,
        modify: impl FnOnce(&mut Vec<<U as VecUpdate>::Item>),
    ) -> impl Future<Output = Result<xrpc::Response<VecPutResponse<U>>>>
    where
        U: VecUpdate,
        <U as VecUpdate>::PutRequest: Send + Sync + Serialize,
        <U as VecUpdate>::GetRequest: Send + Sync + Serialize,
        VecGetResponse<U>: Send + Sync,
        VecPutResponse<U>: Send + Sync,
        <VecGetResponse<U> as XrpcResp>::Output<SmolStr>: DeserializeOwned,
        <VecPutResponse<U> as XrpcResp>::Output<SmolStr>: DeserializeOwned,
        VecUpdateGetError<U>: Send + Sync + std::error::Error + 'static,
        VecUpdatePutError<U>: Send + Sync + std::error::Error + 'static,
    {
        async {
            // Fetch current data
            let get_request = U::build_get();
            let response = self.send(get_request).await?;
            let output = response.into_output().map_err(|e| match e {
                XrpcError::Auth(auth) => AgentError::from(auth),
                XrpcError::Xrpc(typed) => AgentError::sub_operation("update vec", typed),
                e => AgentError::xrpc(e),
            })?;

            // Extract vec
            let mut items = U::extract_vec(output);

            // Apply modification
            modify(&mut items);

            // Build put request
            let put_request = U::build_put(items);

            // Send it
            Ok(self.send(put_request).await?)
        }
    }

    /// Update a single item in a vec-based data structure.
    ///
    /// This is a convenience wrapper around `update_vec` that finds and replaces
    /// a single matching item, or appends it if not found.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let pref = AdultContentPref::new().enabled(true).build();
    /// agent.update_vec_item::<PreferencesUpdate>(pref.into()).await?;
    /// ```
    fn update_vec_item<U>(
        &self,
        item: <U as VecUpdate>::Item,
    ) -> impl Future<Output = Result<xrpc::Response<VecPutResponse<U>>>>
    where
        U: VecUpdate,
        <U as VecUpdate>::PutRequest: Send + Sync + Serialize,
        <U as VecUpdate>::GetRequest: Send + Sync + Serialize,
        VecGetResponse<U>: Send + Sync,
        VecPutResponse<U>: Send + Sync,
        <VecGetResponse<U> as XrpcResp>::Output<SmolStr>: DeserializeOwned,
        <VecPutResponse<U> as XrpcResp>::Output<SmolStr>: DeserializeOwned,
        VecUpdateGetError<U>: Send + Sync + std::error::Error + 'static,
        VecUpdatePutError<U>: Send + Sync + std::error::Error + 'static,
    {
        async {
            self.update_vec::<U>(|vec| {
                if let Some(pos) = vec.iter().position(|i| U::matches(i, &item)) {
                    vec[pos] = item;
                } else {
                    vec.push(item);
                }
            })
            .await
        }
    }
}

#[cfg(feature = "api")]
impl<T: AgentSession + IdentityResolver> AgentSessionExt for T {}

impl<S, T, W> AgentSession for CredentialSession<S, T, W>
where
    S: SessionStore<SessionKey, AtpSession> + Send + Sync + 'static,
    T: IdentityResolver + HttpClient + XrpcExt + Send + Sync + 'static,
    W: Send + Sync,
{
    fn session_kind(&self) -> AgentKind {
        AgentKind::AppPassword
    }
    fn session_info(&self) -> impl Future<Output = Option<(Did, Option<SmolStr>)>> {
        async move {
            CredentialSession::<S, T, W>::session_info(self)
                .await
                // Convert the SmolStr session id to CowStr<'static>.
                .map(|key| (key.0, Some(key.1)))
        }
    }
    fn endpoint(&self) -> impl Future<Output = Uri<String>> {
        async move { CredentialSession::<S, T, W>::endpoint(self).await }
    }
    fn set_options<'a>(&'a self, opts: CallOptions<'a>) -> impl Future<Output = ()> {
        async move { CredentialSession::<S, T, W>::set_options(self, opts).await }
    }
    fn refresh(&self) -> impl Future<Output = ClientResult<AuthorizationToken<SmolStr>>> {
        async move {
            Ok(CredentialSession::<S, T, W>::refresh(self)
                .await?
                .into_static())
        }
    }
}

impl<T, S, W> AgentSession for OAuthSession<T, S, W>
where
    S: ClientAuthStore + Send + Sync + 'static,
    T: OAuthResolver + DpopExt + XrpcExt + Send + Sync + 'static,
    W: Send + Sync,
{
    fn session_kind(&self) -> AgentKind {
        AgentKind::OAuth
    }
    fn session_info(&self) -> impl Future<Output = Option<(Did, Option<SmolStr>)>> {
        async {
            let (did, sid) = OAuthSession::<T, S, W>::session_info(self).await;
            // did is already Did<SmolStr>; convert SmolStr sid to CowStr<'static>.
            Some((did, Some(sid)))
        }
    }
    fn endpoint(&self) -> impl Future<Output = Uri<String>> {
        async { self.endpoint().await }
    }
    fn set_options<'a>(&'a self, opts: CallOptions<'a>) -> impl Future<Output = ()> {
        async { self.set_options(opts).await }
    }
    fn refresh(&self) -> impl Future<Output = ClientResult<AuthorizationToken<SmolStr>>> {
        async {
            self.refresh()
                .await
                .map(|t| t.into_static())
                .map_err(|e| ClientError::transport(e).with_context("OAuth token refresh failed"))
        }
    }
}

impl<T, S> AgentSession for OAuthClient<T, S>
where
    S: ClientAuthStore + Send + Sync + 'static,
    T: OAuthResolver + DpopExt + Send + Sync + 'static,
{
    fn session_kind(&self) -> AgentKind {
        AgentKind::OAuth
    }
    fn session_info(&self) -> impl Future<Output = Option<(Did, Option<SmolStr>)>> {
        async { None }
    }
    fn endpoint(&self) -> impl Future<Output = Uri<String>> {
        async { self.base_uri().await }
    }
    fn set_options<'a>(&'a self, opts: CallOptions<'a>) -> impl Future<Output = ()> {
        async { self.set_opts(opts).await }
    }
    fn refresh(&self) -> impl Future<Output = ClientResult<AuthorizationToken<SmolStr>>> {
        async {
            Err(ClientError::auth(
                jacquard_common::error::AuthError::NotAuthenticated,
            ))
        }
    }
}

impl<A: AgentSession> HttpClient for Agent<A> {
    type Error = <A as HttpClient>::Error;

    #[cfg(not(target_arch = "wasm32"))]
    fn send_http(
        &self,
        request: http::Request<Vec<u8>>,
    ) -> impl Future<Output = core::result::Result<http::Response<Vec<u8>>, Self::Error>> + Send
    {
        self.inner.send_http(request)
    }

    #[cfg(target_arch = "wasm32")]
    fn send_http(
        &self,
        request: http::Request<Vec<u8>>,
    ) -> impl Future<Output = core::result::Result<http::Response<Vec<u8>>, Self::Error>> {
        self.inner.send_http(request)
    }
}

#[cfg(feature = "streaming")]
impl<A> jacquard_common::http_client::HttpClientExt for Agent<A>
where
    A: AgentSession + jacquard_common::http_client::HttpClientExt,
{
    #[cfg(not(target_arch = "wasm32"))]
    fn send_http_streaming(
        &self,
        request: http::Request<Vec<u8>>,
    ) -> impl Future<
        Output = core::result::Result<
            http::Response<jacquard_common::stream::ByteStream>,
            Self::Error,
        >,
    > + Send {
        self.inner.send_http_streaming(request)
    }

    #[cfg(target_arch = "wasm32")]
    fn send_http_streaming(
        &self,
        request: http::Request<Vec<u8>>,
    ) -> impl Future<
        Output = core::result::Result<
            http::Response<jacquard_common::stream::ByteStream>,
            Self::Error,
        >,
    > {
        self.inner.send_http_streaming(request)
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn send_http_bidirectional<Str>(
        &self,
        parts: http::request::Parts,
        body: Str,
    ) -> impl Future<
        Output = core::result::Result<
            http::Response<jacquard_common::stream::ByteStream>,
            Self::Error,
        >,
    > + Send
    where
        Str: n0_future::Stream<
                Item = core::result::Result<bytes::Bytes, jacquard_common::StreamError>,
            > + Send
            + 'static,
    {
        self.inner.send_http_bidirectional(parts, body)
    }

    #[cfg(target_arch = "wasm32")]
    fn send_http_bidirectional<Str>(
        &self,
        parts: http::request::Parts,
        body: Str,
    ) -> impl Future<
        Output = core::result::Result<
            http::Response<jacquard_common::stream::ByteStream>,
            Self::Error,
        >,
    >
    where
        Str: n0_future::Stream<
                Item = core::result::Result<bytes::Bytes, jacquard_common::StreamError>,
            > + 'static,
    {
        self.inner.send_http_bidirectional(parts, body)
    }
}

impl<A: AgentSession> XrpcClient for Agent<A> {
    async fn base_uri(&self) -> Uri<String> {
        self.inner.base_uri().await
    }
    fn opts(&self) -> impl Future<Output = CallOptions<'_>> {
        self.inner.opts()
    }

    async fn set_opts(&self, opts: CallOptions<'_>) {
        self.inner.set_opts(opts).await
    }

    async fn set_base_uri(&self, uri: Uri<String>) {
        self.inner.set_base_uri(uri).await
    }
    fn send<R>(
        &self,
        request: R,
    ) -> impl Future<Output = XrpcResult<Response<<R as XrpcRequest>::Response>>>
    where
        R: XrpcRequest + Send + Sync + Serialize,
        <R as XrpcRequest>::Response: Send + Sync,
    {
        async move { self.inner.send(request).await }
    }

    async fn send_with_opts<R>(
        &self,
        request: R,
        opts: CallOptions<'_>,
    ) -> XrpcResult<Response<<R as XrpcRequest>::Response>>
    where
        R: XrpcRequest + Send + Sync + Serialize,
        <R as XrpcRequest>::Response: Send + Sync,
    {
        self.inner.send_with_opts(request, opts).await
    }
}

#[cfg(feature = "streaming")]
impl<A> jacquard_common::xrpc::XrpcStreamingClient for Agent<A>
where
    A: AgentSession + jacquard_common::xrpc::XrpcStreamingClient,
{
    #[cfg(not(target_arch = "wasm32"))]
    fn download<R>(
        &self,
        request: R,
    ) -> impl Future<
        Output = core::result::Result<
            jacquard_common::xrpc::StreamingResponse,
            jacquard_common::StreamError,
        >,
    > + Send
    where
        R: XrpcRequest + Send + Sync + Serialize,
        <R as XrpcRequest>::Response: Send + Sync,
        Self: Sync,
    {
        self.inner.download(request)
    }

    #[cfg(target_arch = "wasm32")]
    fn download<R>(
        &self,
        request: R,
    ) -> impl Future<
        Output = core::result::Result<
            jacquard_common::xrpc::StreamingResponse,
            jacquard_common::StreamError,
        >,
    >
    where
        R: XrpcRequest + Send + Sync + Serialize,
        <R as XrpcRequest>::Response: Send + Sync,
    {
        self.inner.download(request)
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn stream<S, B>(
        &self,
        stream: jacquard_common::xrpc::XrpcProcedureSend<S::Frame<B>>,
    ) -> impl Future<
        Output = core::result::Result<
            jacquard_common::xrpc::XrpcResponseStream<<<S as jacquard_common::xrpc::XrpcProcedureStream>::Response as jacquard_common::xrpc::XrpcStreamResp>::Frame<B>>,
            jacquard_common::StreamError,
        >,
    >
    where
        B: BosStr + 'static,
        S: jacquard_common::xrpc::XrpcProcedureStream + 'static,
        <<S as jacquard_common::xrpc::XrpcProcedureStream>::Response as jacquard_common::xrpc::XrpcStreamResp>::Frame<B>: jacquard_common::xrpc::XrpcStreamResp,
        Self: Sync,
    {
        self.inner.stream::<S, B>(stream)
    }

    #[cfg(target_arch = "wasm32")]
    fn stream<S>(
        &self,
        stream: jacquard_common::xrpc::XrpcProcedureSend<S::Frame<'static>>,
    ) -> impl Future<
        Output = core::result::Result<
            jacquard_common::xrpc::XrpcResponseStream<<<S as jacquard_common::xrpc::XrpcProcedureStream>::Response as jacquard_common::xrpc::XrpcStreamResp>::Frame<'static>>,
            jacquard_common::StreamError,
        >,
    >
    where
        S: jacquard_common::xrpc::XrpcProcedureStream + 'static,
        <<S as jacquard_common::xrpc::XrpcProcedureStream>::Response as jacquard_common::xrpc::XrpcStreamResp>::Frame<'static>: jacquard_common::xrpc::XrpcStreamResp,
    {
        self.inner.stream::<S>(stream)
    }
}

impl<A: AgentSession + IdentityResolver> IdentityResolver for Agent<A> {
    fn options(&self) -> &ResolverOptions {
        self.inner.options()
    }

    fn resolve_handle<S: BosStr + Sync>(
        &self,
        handle: &Handle<S>,
    ) -> impl Future<Output = core::result::Result<Did, IdentityError>> {
        async { self.inner.resolve_handle(handle).await }
    }

    fn resolve_did_doc<S: BosStr + Sync>(
        &self,
        did: &Did<S>,
    ) -> impl Future<Output = core::result::Result<DidDocResponse, IdentityError>> {
        async { self.inner.resolve_did_doc(did).await }
    }
}

impl<A: AgentSession> AgentSession for Agent<A> {
    fn session_kind(&self) -> AgentKind {
        self.kind()
    }

    fn session_info(&self) -> impl Future<Output = Option<(Did, Option<SmolStr>)>> {
        async { self.info().await }
    }

    fn endpoint(&self) -> impl Future<Output = Uri<String>> {
        async { self.endpoint().await }
    }

    fn set_options<'a>(&'a self, opts: CallOptions<'a>) -> impl Future<Output = ()> {
        async { self.set_options(opts).await }
    }

    fn refresh(&self) -> impl Future<Output = ClientResult<AuthorizationToken<SmolStr>>> {
        async { self.refresh().await }
    }
}

impl<A: AgentSession> From<A> for Agent<A> {
    fn from(inner: A) -> Self {
        Self::new(inner)
    }
}