agent-protocols 0.8.0

Rust SDK for Agent Identity, Agent Profile, Agent Delegation, and Agent Discourse protocols
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
//! Local Agent Protocols MCP connector core.
//!
//! This module is transport-neutral: it exposes the standard local connector
//! tool names, schemas, structured result types, a JSON dispatcher, and local
//! room-state projection. An MCP stdio server can wrap [`LocalConnector`] without
//! giving the agent direct access to signing keys or reusable request JWTs.
//!
//! The connector itself is one deep module: [`LocalConnector`] presents a small
//! interface (construct, feed observations and records, dispatch a tool call)
//! over a large implementation. That implementation is organised into internal
//! seams that vary independently:
//!
//! - [`catalog`] — the static tool/resource surface advertised to `tools/list`.
//! - [`views`] — the structured result types callers read back.
//! - [`inputs`] — the per-tool deserialization shapes.
//! - [`state`] — the in-memory store records are projected into.
//! - [`projection`] — the pure ADP record → room-state rules and validation.
//!
//! The orchestration that ties signing, networking, and projection together
//! stays here because those methods are mutually recursive over `self`; they
//! form one body of behaviour rather than a seam something varies across.

mod catalog;
mod inputs;
mod projection;
mod state;
mod views;

#[cfg(test)]
mod tests;

pub use catalog::*;
pub use state::{LocalConnectorState, RoomKey};
pub use views::*;

use inputs::*;
use projection::*;
use state::{HeldDraftEntry, HeldDraftRequest, InboxEntry, InboxEntryState, LocalRoomState};

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{json, Value};
use std::collections::BTreeMap;

use crate::delegation::{
    is_principal_alias, validate_delegation_event_authority, DelegationCredential,
    DelegationGrantPayload, DelegationPayload, DelegationQueryRequest, DelegationRevokePayload,
    PrincipalDescriptor, PrincipalDocument,
};
use crate::discourse::{
    discourse_event, event_type, room_create_event, validate_discourse_envelope,
    validate_room_path, verify_server_record, AgentStatusInput, JoinRequestStatus,
    MessageCreatePayload, ReasonPayload, Role, RoomCreatePayload, RoomJoinPayload,
    RoomJoinRequestInput, RoomJoinReviewPayload, RoomResponse, ServerRecord, Visibility,
};
use crate::error::{Result, SdkError};
use crate::http_client::{
    DelegationClient, DiscourseClient, ProfileClient, PublicRoomsOptions, RoomEventsOptions,
};
use crate::identity::Event;
use crate::identity::{
    unix_ms, unix_secs, AgentId, AgentSigner, ClientNonceManager, Envelope, RequestBinding,
    RequestJwtClaims, DEFAULT_REQUEST_JWT_TTL_SECS,
};
use crate::profile::{profile_update_event, AgentProfile, ProfileUpdatePayload};

struct HeadMismatchState {
    sync: SyncState,
    changes: Vec<TimelineItem>,
}

pub struct LocalConnector {
    signer: AgentSigner,
    nonce_manager: ClientNonceManager,
    state: LocalConnectorState,
}

impl LocalConnector {
    pub fn new(signer: AgentSigner) -> Self {
        Self {
            signer,
            nonce_manager: ClientNonceManager::new(),
            state: LocalConnectorState::new(),
        }
    }

    pub fn with_state(signer: AgentSigner, state: LocalConnectorState) -> Self {
        Self {
            signer,
            nonce_manager: ClientNonceManager::new(),
            state,
        }
    }

    pub fn agent_id(&self) -> AgentId {
        self.signer.agent_id()
    }

    pub fn state(&self) -> &LocalConnectorState {
        &self.state
    }

    pub fn state_mut(&mut self) -> &mut LocalConnectorState {
        &mut self.state
    }

    pub fn add_host(&mut self, host: AgentProtocolsHost) {
        self.state.hosts.insert(normalize_host(&host.host), host);
    }

    pub fn observe_room(&mut self, host: impl Into<String>, room: RoomResponse) {
        let host = normalize_host(&host.into());
        self.ensure_host(&host);
        let key = (host.clone(), room.id.clone());
        let entry = self
            .state
            .rooms
            .entry(key)
            .or_insert_with(|| LocalRoomState::new(host.clone(), room.clone()));
        entry.host = host;
        entry.room = room;
        materialize_creator(entry);
    }

    pub fn accept_room_response(&mut self, host: impl Into<String>, room: RoomResponse) {
        let host = normalize_host(&host.into());
        let key = (host.clone(), room.id.clone());
        self.observe_room(host, room);
        if let Some(entry) = self.state.rooms.get_mut(&key) {
            let (head_seq, head_hash) = room_response_head(&entry.room);
            entry.head_seq = head_seq;
            entry.head_hash = Some(head_hash);
            entry.synced_seq = entry.room.seq;
            entry.synced_hash = Some(entry.room.hash.clone());
        }
    }

    /// Applies a verified record to the room identified by its `room_id`
    /// alone. Fails with an ambiguity error when the room ID matches rooms on
    /// more than one configured host; use [`Self::apply_host_record`] then.
    pub fn apply_record(&mut self, record: ServerRecord) -> Result<()> {
        let key = self.resolve_room_key(None, &record.room_id)?;
        self.apply_record_to(&key, record)
    }

    /// Applies a verified record to the room on the given host.
    pub fn apply_host_record(&mut self, host: &str, record: ServerRecord) -> Result<()> {
        let key = (normalize_host(host), record.room_id.clone());
        self.apply_record_to(&key, record)
    }

    fn apply_record_to(&mut self, key: &RoomKey, record: ServerRecord) -> Result<()> {
        validate_discourse_envelope(&record.envelope)?;
        validate_room_path(&record.envelope, &record.room_id)?;
        verify_server_record(&record)?;

        let active_agent = self.agent_id();
        let mut new_inbox = Vec::new();
        let mut cleared_status: Option<AgentId> = None;
        {
            let room = self.state.rooms.get_mut(key).ok_or_else(|| {
                SdkError::InvalidPayload(format!("room is not open locally: {}", key.1))
            })?;
            if is_duplicate_record(room, &record) {
                return Ok(());
            }
            validate_next_record(room, &record)?;
            validate_record_base_precondition(room, &record)?;

            let item = TimelineItem::from_record(&record);
            apply_record_projection(room, &record, &item, &active_agent, &mut new_inbox)?;
            if record.envelope.event.kind == event_type::ROOM_MEMBER_REMOVE {
                cleared_status =
                    serde_json::from_value::<crate::discourse::RoomMemberRemovePayload>(
                        record.envelope.event.payload.clone(),
                    )
                    .ok()
                    .map(|payload| payload.member);
            }
            if record_advances_room_head(room, &record) {
                room.head_seq = record.seq;
                room.head_hash = Some(record.hash.clone());
            }
            room.synced_seq = record.seq;
            room.synced_hash = Some(record.hash.clone());
            room.records.push(record);
            room.timeline.push(item);
        }
        // Removal ends membership; the host clears the member's transient
        // agent status, so drop the local cache entry too.
        if let Some(member) = cleared_status {
            if let Some(statuses) = self.state.agent_statuses.get_mut(key) {
                statuses.remove(&member);
            }
        }
        for item in new_inbox {
            self.insert_inbox(item);
        }
        Ok(())
    }

    /// Resolves `(host, room_id)` for a tool call. Without a `host` input the
    /// room ID must match exactly one locally known room; the connector
    /// returns an ambiguity error instead of guessing between hosts.
    fn resolve_room_key(&self, host: Option<&str>, room_id: &str) -> Result<RoomKey> {
        if let Some(host) = host {
            return Ok((normalize_host(host), room_id.to_owned()));
        }
        let mut keys = self
            .state
            .rooms
            .keys()
            .filter(|(_, known_room_id)| known_room_id == room_id);
        match (keys.next(), keys.next()) {
            (Some(key), None) => Ok(key.clone()),
            (Some(_), Some(_)) => Err(SdkError::InvalidPayload(format!(
                "room id {room_id} matches rooms on more than one host; pass host"
            ))),
            _ => Err(SdkError::InvalidPayload(format!(
                "room is not open locally: {room_id}"
            ))),
        }
    }

    pub async fn call_tool(&mut self, name: &str, input: Value) -> Result<Value> {
        match name {
            TOOL_IDENTITY_CURRENT => self.identity_current(),
            TOOL_HOSTS_LIST => self.hosts_list(),
            TOOL_PRINCIPAL_RESOLVE => self.principal_resolve(parse_input(input)?).await,
            TOOL_DELEGATION_CHECK => self.delegation_check(parse_input(input)?).await,
            TOOL_DELEGATIONS_LIST => self.delegations_list(parse_input(input)?).await,
            TOOL_DELEGATION_GRANT => self.delegation_grant(parse_input(input)?).await,
            TOOL_DELEGATION_REVOKE => self.delegation_revoke(parse_input(input)?).await,
            TOOL_ROOMS_SEARCH => self.rooms_search(parse_input(input)?).await,
            TOOL_ROOMS_LIST => self.rooms_list(parse_input(input)?),
            TOOL_ROOM_OPEN => self.room_open(parse_input(input)?).await,
            TOOL_ROOM_STATE => self.room_state(parse_input(input)?).await,
            TOOL_ROOM_MEMBERS_LIST => self.room_members_list(parse_input(input)?),
            TOOL_ROOM_MEMBER_GET => self.room_member_get(parse_input(input)?),
            TOOL_AGENT_STATUS_LIST => self.agent_status_list(parse_input(input)?).await,
            TOOL_AGENT_STATUS_GET => self.agent_status_get(parse_input(input)?).await,
            TOOL_AGENT_STATUS_SET => self.agent_status_set(parse_input(input)?).await,
            TOOL_AGENT_STATUS_CLEAR => self.agent_status_clear(parse_input(input)?).await,
            TOOL_ROOM_TIMELINE => self.room_timeline(parse_input(input)?),
            TOOL_ROOM_UNREAD => self.room_unread(parse_input(input)?),
            TOOL_ROOM_MARK_READ => self.room_mark_read(parse_input(input)?),
            TOOL_INBOX_NEXT => self.inbox_next(parse_input(input)?),
            TOOL_INBOX_ACK => self.inbox_ack(parse_input(input)?),
            TOOL_DRAFTS_LIST => self.drafts_list(parse_input(input)?),
            TOOL_DRAFT_GET => self.draft_get(parse_input(input)?),
            TOOL_DRAFT_COMMIT => self.draft_commit(parse_input(input)?).await,
            TOOL_DRAFT_DROP => self.draft_drop(parse_input(input)?),
            TOOL_PROFILE_UPDATE => self.profile_update(parse_input(input)?).await,
            TOOL_ROOM_CREATE => self.room_create(parse_input(input)?).await,
            TOOL_ROOM_JOIN => self.room_join(parse_input(input)?).await,
            TOOL_ROOM_JOIN_REQUEST => self.room_join_request(parse_input(input)?).await,
            TOOL_ROOM_JOIN_WHEN_APPROVED => self.room_join_when_approved(parse_input(input)?).await,
            TOOL_ROOM_LEAVE => self.room_leave(parse_input(input)?).await,
            TOOL_ROOM_SEND_MESSAGE => self.room_send_message(parse_input(input)?).await,
            TOOL_ROOM_SUBMIT_EVENT => self.room_submit_event(parse_input(input)?).await,
            TOOL_JOIN_REQUESTS_LIST => self.join_requests_list(parse_input(input)?).await,
            TOOL_JOIN_REQUEST_REVIEW => self.join_request_review(parse_input(input)?).await,
            _ => Err(SdkError::InvalidPayload(format!(
                "unknown local connector tool: {name}"
            ))),
        }
    }

    fn identity_current(&self) -> Result<Value> {
        let agent_id = self.agent_id();
        let public_key = URL_SAFE_NO_PAD.encode(agent_id.public_key_bytes()?);
        json_result(json!({
            "agent_id": agent_id,
            "public_key": public_key,
            "profiles": self.state.profiles.keys().collect::<Vec<_>>(),
            "hosts": self.state.hosts.values().collect::<Vec<_>>()
        }))
    }

    fn hosts_list(&self) -> Result<Value> {
        json_result(json!({ "hosts": self.state.hosts.values().collect::<Vec<_>>() }))
    }

    async fn rooms_search(&mut self, input: RoomsSearchInput) -> Result<Value> {
        let host = normalize_host(&input.host);
        self.require_allowed_host(&host)?;
        let rooms = DiscourseClient::new(&host)
            .public_rooms(&PublicRoomsOptions {
                status: input.status,
                tag: input.tag,
                keyword: input.keyword,
                creator: input.creator,
                starts_after: input.starts_after,
                ends_before: input.ends_before,
                language: input.language,
                limit: input.limit,
                cursor: input.cursor,
            })
            .await?;
        for room in &rooms {
            self.observe_room(&host, room.clone());
        }
        let summaries = rooms
            .iter()
            .map(|room| self.summary_for_response(&host, room))
            .collect::<Vec<_>>();
        json_result(json!({ "rooms": summaries }))
    }

    fn rooms_list(&self, input: RoomsListInput) -> Result<Value> {
        let rooms = self
            .state
            .rooms
            .values()
            .filter(|room| {
                input
                    .status
                    .as_deref()
                    .map(|status| {
                        serde_json::to_value(room.room.status)
                            .ok()
                            .and_then(|v| v.as_str().map(str::to_owned))
                            == Some(status.to_owned())
                    })
                    .unwrap_or(true)
            })
            .filter(|room| membership_filter(room, &self.agent_id(), input.membership))
            .skip(
                input
                    .cursor
                    .as_deref()
                    .and_then(|c| c.parse::<usize>().ok())
                    .unwrap_or(0),
            )
            .take(input.limit.unwrap_or(50))
            .map(|room| self.summary_for_room(room))
            .collect::<Vec<_>>();
        json_result(json!({ "rooms": rooms }))
    }

    async fn room_open(&mut self, input: RoomOpenInput) -> Result<Value> {
        let host = normalize_host(&input.host);
        self.require_allowed_host(&host)?;
        let key = (host.clone(), input.room_id.clone());
        let previous_seq = self
            .state
            .rooms
            .get(&key)
            .map(|room| room.synced_seq)
            .unwrap_or(0);
        if input.refresh || previous_seq == 0 {
            let client = DiscourseClient::new(&host);
            let room = client.room(&input.room_id).await?;
            self.observe_room(&host, room);
            let jwt = self.request_jwt(&host)?;
            let records = client
                .events_with_options(
                    &input.room_id,
                    &RoomEventsOptions {
                        after_seq: if previous_seq > 0 {
                            Some(previous_seq)
                        } else {
                            None
                        },
                        limit: None,
                        cursor: None,
                        jwt: Some(jwt),
                    },
                )
                .await?;
            for record in records {
                self.apply_host_record(&host, record)?;
            }
        }
        if let Some(room) = self.state.rooms.get_mut(&key) {
            room.subscribed = input.subscribe.unwrap_or(false);
        }
        let room = self.local_room(&key)?;
        json_result(json!({
            "room": self.room_state_view(room),
            "sync": self.sync_state(&key)?,
            "active_turn": room.active_turn
        }))
    }

    async fn room_state(&mut self, input: RoomStateInput) -> Result<Value> {
        let _ = input.include_types;
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        if input.refresh {
            let host = self.local_room(&key)?.host.clone();
            return self
                .room_open(RoomOpenInput {
                    host,
                    room_id: input.room_id,
                    subscribe: None,
                    refresh: true,
                })
                .await;
        }
        let room = self.local_room(&key)?;
        json_result(json!({
            "room": self.room_state_view(room),
            "sync": self.sync_state(&key)?
        }))
    }

    fn room_members_list(&self, input: RoomMembersListInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let room = self.local_room(&key)?;
        let mut members = room
            .members
            .values()
            .filter(|member| {
                input
                    .status
                    .map(|status| status == member.status)
                    .unwrap_or(true)
            })
            .filter(|member| input.role.map(|role| role == member.role).unwrap_or(true))
            .skip(
                input
                    .cursor
                    .as_deref()
                    .and_then(|c| c.parse::<usize>().ok())
                    .unwrap_or(0),
            )
            .take(input.limit.unwrap_or(100))
            .cloned()
            .collect::<Vec<_>>();
        if input.include_profiles {
            for member in &mut members {
                if member.profile.is_none() {
                    member.profile = self
                        .state
                        .profiles
                        .get(&member.agent_id)
                        .map(profile_to_member_profile);
                }
            }
        }
        json_result(json!({
            "members": members,
            "sync": self.sync_state(&key)?
        }))
    }

    fn room_member_get(&self, input: RoomMemberGetInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let room = self.local_room(&key)?;
        let member = room
            .members
            .get(&input.agent_id)
            .ok_or_else(|| SdkError::InvalidPayload("room member not found".to_owned()))?;
        let mut member = member.clone();
        if input.include_profile && member.profile.is_none() {
            member.profile = self
                .state
                .profiles
                .get(&member.agent_id)
                .map(profile_to_member_profile);
        }
        let recent = if input.include_recent_activity {
            room.timeline
                .iter()
                .filter(|item| item.actor == input.agent_id)
                .rev()
                .take(10)
                .cloned()
                .collect::<Vec<_>>()
        } else {
            Vec::new()
        };
        json_result(json!({
            "member": member,
            "recent": recent,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn agent_status_list(&mut self, input: AgentStatusListInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        if !input.refresh {
            if let Some(statuses) = self.state.agent_statuses.get(&key) {
                return json_result(json!({
                    "statuses": statuses.values().collect::<Vec<_>>(),
                    "sync": self.sync_state(&key)?
                }));
            }
        }
        let host = self.allowed_room_host(&key)?;
        let jwt = self.request_jwt(&host)?;
        let response = DiscourseClient::new(&host)
            .agent_statuses(&input.room_id, Some(&jwt))
            .await?;
        let statuses = response
            .statuses
            .into_iter()
            .map(|status| (status.agent_id.clone(), status))
            .collect::<BTreeMap<_, _>>();
        let values = statuses.values().cloned().collect::<Vec<_>>();
        self.state.agent_statuses.insert(key.clone(), statuses);
        json_result(json!({
            "statuses": values,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn agent_status_get(&mut self, input: AgentStatusGetInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        if !input.refresh {
            if let Some(status) = self
                .state
                .agent_statuses
                .get(&key)
                .and_then(|statuses| statuses.get(&input.agent_id))
                .cloned()
            {
                return json_result(json!({
                    "status": status,
                    "sync": self.sync_state(&key)?
                }));
            }
        }
        let host = self.allowed_room_host(&key)?;
        let jwt = self.request_jwt(&host)?;
        let response = DiscourseClient::new(&host)
            .agent_status(&input.room_id, &input.agent_id, Some(&jwt))
            .await?;
        self.state
            .agent_statuses
            .entry(key.clone())
            .or_default()
            .insert(response.status.agent_id.clone(), response.status.clone());
        json_result(json!({
            "status": response.status,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn agent_status_set(&mut self, input: AgentStatusSetInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let host = self.allowed_room_host(&key)?;
        let jwt = self.request_jwt(&host)?;
        let mut request = AgentStatusInput::new(input.state);
        request.expires_at = input.expires_at;
        request.summary = input.summary;
        request.seen_seq = input.seen_seq;
        request.seen_hash = input.seen_hash;
        request.claim_id = input.claim_id;
        request.activity = input.activity;
        request.extra = input.extra;
        let status = DiscourseClient::new(&host)
            .set_agent_status(&input.room_id, &jwt, &request)
            .await?;
        self.state
            .agent_statuses
            .entry(key.clone())
            .or_default()
            .insert(status.agent_id.clone(), status.clone());
        json_result(json!({
            "status": status,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn agent_status_clear(&mut self, input: AgentStatusClearInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let host = self.allowed_room_host(&key)?;
        let jwt = self.request_jwt(&host)?;
        let request = AgentStatusInput::new("away").with_expires_at(unix_ms().saturating_sub(1));
        let _ = DiscourseClient::new(&host)
            .set_agent_status(&input.room_id, &jwt, &request)
            .await?;
        let active_agent = self.agent_id();
        if let Some(statuses) = self.state.agent_statuses.get_mut(&key) {
            statuses.remove(&active_agent);
        }
        json_result(json!({
            "cleared": true,
            "room_id": input.room_id
        }))
    }

    fn room_timeline(&self, input: RoomTimelineInput) -> Result<Value> {
        let _ = (input.refresh, input.include_records);
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let room = self.local_room(&key)?;
        let items = room
            .timeline
            .iter()
            .filter(|item| input.after_seq.map(|seq| item.seq > seq).unwrap_or(true))
            .filter(|item| input.before_seq.map(|seq| item.seq < seq).unwrap_or(true))
            .filter(|item| {
                input
                    .types
                    .as_ref()
                    .map(|types| types.contains(&item.event_type))
                    .unwrap_or(true)
            })
            .filter(|item| {
                input
                    .actors
                    .as_ref()
                    .map(|actors| actors.contains(&item.actor))
                    .unwrap_or(true)
            })
            .filter(|item| !input.unread_only || item.seq > room.read_seq)
            .take(input.limit.unwrap_or(50))
            .cloned()
            .collect::<Vec<_>>();
        let next_after_seq = items.last().map(|item| item.seq);
        json_result(json!({
            "items": items,
            "sync": self.sync_state(&key)?,
            "next_after_seq": next_after_seq
        }))
    }

    fn room_unread(&mut self, input: RoomUnreadInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let room = self.local_room(&key)?;
        let mut items = room
            .timeline
            .iter()
            .filter(|item| item.seq > room.read_seq)
            .take(input.limit.unwrap_or(50))
            .cloned()
            .collect::<Vec<_>>();
        let through_seq = items.last().map(|item| item.seq);
        if input.mark_read {
            if let Some(through_seq) = through_seq {
                self.local_room_mut(&key)?.read_seq = through_seq;
            }
            items = self
                .local_room(&key)?
                .timeline
                .iter()
                .filter(|item| through_seq.map(|seq| item.seq <= seq).unwrap_or(false))
                .cloned()
                .collect();
        }
        let unread_count = self.local_room(&key)?.unread_count();
        json_result(json!({
            "items": items,
            "unread_count": unread_count,
            "sync": self.sync_state(&key)?
        }))
    }

    fn room_mark_read(&mut self, input: RoomMarkReadInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let room = self.local_room_mut(&key)?;
        room.read_seq = room.read_seq.max(input.through_seq);
        let unread_count = room.unread_count();
        json_result(json!({
            "room_id": input.room_id,
            "read_seq": room.read_seq,
            "unread_count": unread_count
        }))
    }

    fn inbox_next(&mut self, input: InboxNextInput) -> Result<Value> {
        let _ = input.wait_ms;
        let now = unix_ms();
        let mut ids = self
            .state
            .inbox
            .iter()
            .filter(|(_, entry)| inbox_entry_ready(entry, now))
            .filter(|(_, entry)| {
                input
                    .room_id
                    .as_ref()
                    .map(|room_id| entry.item.room_id.as_ref() == Some(room_id))
                    .unwrap_or(true)
            })
            .filter(|(_, entry)| {
                input
                    .kinds
                    .as_ref()
                    .map(|kinds| {
                        serde_json::to_value(&entry.item.kind)
                            .ok()
                            .and_then(|value| value.as_str().map(str::to_owned))
                            .map(|kind| kinds.contains(&kind))
                            .unwrap_or(false)
                    })
                    .unwrap_or(true)
            })
            .map(|(id, _)| id.clone())
            .collect::<Vec<_>>();
        ids.truncate(input.limit.unwrap_or(10));
        let mut items = Vec::new();
        for id in ids {
            if let Some(entry) = self.state.inbox.get_mut(&id) {
                items.push(entry.item.clone());
                if input.claim {
                    entry.state = InboxEntryState::Claimed;
                }
            }
        }
        json_result(json!({
            "items": items,
            "pending_count": self.pending_inbox_count(None)
        }))
    }

    fn inbox_ack(&mut self, input: InboxAckInput) -> Result<Value> {
        let mut acknowledged = Vec::new();
        for id in &input.ids {
            if let Some(entry) = self.state.inbox.get_mut(id) {
                entry.state = match input.action {
                    InboxAckAction::Handled | InboxAckAction::Dismissed => {
                        InboxEntryState::Acknowledged
                    }
                    InboxAckAction::Defer => {
                        InboxEntryState::Deferred(input.defer_until.unwrap_or_else(unix_ms))
                    }
                };
                acknowledged.push(id.clone());
            }
        }
        json_result(json!({
            "acknowledged": acknowledged,
            "pending_count": self.pending_inbox_count(None)
        }))
    }

    fn drafts_list(&self, input: DraftsListInput) -> Result<Value> {
        let offset = input
            .cursor
            .as_deref()
            .and_then(|cursor| cursor.parse::<usize>().ok())
            .unwrap_or(0);
        let limit = input.limit.unwrap_or(50);
        let mut drafts = self
            .state
            .drafts
            .values()
            .filter(|entry| {
                input
                    .room_id
                    .as_ref()
                    .map(|room_id| &entry.draft.room_id == room_id)
                    .unwrap_or(true)
            })
            .filter(|entry| {
                input
                    .host
                    .as_deref()
                    .map(|host| entry.draft.current_sync.host == normalize_host(host))
                    .unwrap_or(true)
            })
            .skip(offset)
            .take(limit + 1)
            .map(|entry| entry.draft.clone())
            .collect::<Vec<_>>();
        let next_cursor = if drafts.len() > limit {
            drafts.pop();
            Some((offset + limit).to_string())
        } else {
            None
        };
        json_result(json!({
            "drafts": drafts,
            "next_cursor": next_cursor
        }))
    }

    fn draft_get(&self, input: DraftGetInput) -> Result<Value> {
        let entry = self
            .state
            .drafts
            .get(&input.draft_id)
            .ok_or_else(|| SdkError::InvalidPayload("draft not found".to_owned()))?;
        let key = (
            entry.draft.current_sync.host.clone(),
            entry.draft.room_id.clone(),
        );
        let changes = self.room_changes_since(&key, entry.draft.base_seq)?;
        json_result(json!({
            "draft": entry.draft,
            "changes": changes,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn draft_commit(&mut self, input: DraftCommitInput) -> Result<Value> {
        let entry = self
            .state
            .drafts
            .get(&input.draft_id)
            .cloned()
            .ok_or_else(|| SdkError::InvalidPayload("draft not found".to_owned()))?;

        if input.action == DraftAction::StaySilent {
            self.state.drafts.remove(&input.draft_id);
            return json_result(json!({
                "status": "dropped",
                "draft_id": input.draft_id
            }));
        }

        let result = match (entry.request, input.action) {
            (HeldDraftRequest::Message(mut request), DraftAction::Revise) => {
                if let Some(content) = input.content {
                    request.content = content;
                }
                if let Some(content_type) = input.content_type {
                    request.content_type = Some(content_type);
                }
                if let Some(mentions) = input.mentions {
                    request.mentions = mentions;
                }
                if let Some(references) = input.references {
                    request.references = references;
                }
                if let Some(extra) = input.extra {
                    request.extra = extra;
                }
                request.base_seq = input.base_seq;
                request.base_hash = input.base_hash;
                request.on_head_mismatch = input.on_head_mismatch;
                self.room_send_message(request).await?
            }
            (HeldDraftRequest::Message(mut request), DraftAction::SendAsIs) => {
                request.base_seq = input.base_seq;
                request.base_hash = input.base_hash;
                request.on_head_mismatch = input.on_head_mismatch;
                self.room_send_message(request).await?
            }
            (HeldDraftRequest::Message(mut request), DraftAction::SendAnyway) => {
                request.base_seq = None;
                request.base_hash = None;
                request.on_head_mismatch = HeadMismatchPolicy::SendAnyway;
                self.submit_message_unchecked(request).await?
            }
            (HeldDraftRequest::Event(mut request), DraftAction::Revise) => {
                if let Some(event_type) = input.event_type {
                    request.event_type = event_type;
                }
                if let Some(payload) = input.payload {
                    request.payload = payload;
                }
                if let Some(mentions) = input.mentions {
                    request.mentions = mentions;
                }
                if let Some(references) = input.references {
                    request.references = references;
                }
                request.base_seq = input.base_seq;
                request.base_hash = input.base_hash;
                request.on_head_mismatch = input.on_head_mismatch;
                self.room_submit_event(request).await?
            }
            (HeldDraftRequest::Event(mut request), DraftAction::SendAsIs) => {
                request.base_seq = input.base_seq;
                request.base_hash = input.base_hash;
                request.on_head_mismatch = input.on_head_mismatch;
                self.room_submit_event(request).await?
            }
            (HeldDraftRequest::Event(mut request), DraftAction::SendAnyway) => {
                request.base_seq = None;
                request.base_hash = None;
                request.on_head_mismatch = HeadMismatchPolicy::SendAnyway;
                self.submit_event_unchecked(request).await?
            }
            (_, DraftAction::StaySilent) => unreachable!(),
        };

        if matches!(
            result.get("status").and_then(Value::as_str),
            Some("sent" | "held")
        ) {
            self.state.drafts.remove(&input.draft_id);
        }
        Ok(result)
    }

    fn draft_drop(&mut self, input: DraftDropInput) -> Result<Value> {
        self.state.drafts.remove(&input.draft_id);
        json_result(json!({
            "status": "dropped",
            "draft_id": input.draft_id,
            "pending_count": self.state.drafts.len()
        }))
    }

    /// Resolves a principal per Agent Delegation Section 3 and reports
    /// whether the requested URL is an alias the principal acknowledges. Any
    /// origin can redirect to any principal, so an unlisted URL is never
    /// presented as a name for it.
    async fn resolve_principal(&self, url: &str) -> Result<(PrincipalDocument, bool)> {
        let document = DelegationClient::new(url).principal(Some(url)).await?;
        let alias = document.id != url && is_principal_alias(&document, url);
        Ok((document, alias))
    }

    /// Resolves the principal and refuses when the active Agent ID is not one
    /// of its controller keys, so a grant that could never be accepted is not
    /// signed or transmitted.
    async fn controller_principal(&self, principal_id: &str) -> Result<PrincipalDocument> {
        let (document, _) = self.resolve_principal(principal_id).await?;
        let active = self.agent_id();
        if !document
            .controllers
            .iter()
            .any(|c| c.id == active && c.delegation.is_some() && c.valid_from <= unix_ms())
        {
            return Err(SdkError::InvalidPayload(format!(
                "active agent {active} is not a controller key of {}",
                document.id
            )));
        }
        Ok(document)
    }

    async fn principal_resolve(&self, input: PrincipalResolveInput) -> Result<Value> {
        let (document, alias) = self.resolve_principal(&input.url).await?;
        json_result(json!({
            "canonical_id": document.id,
            "requested_url": input.url,
            "alias": alias,
            "principal": document,
        }))
    }

    async fn delegation_check(&self, input: DelegationCheckInput) -> Result<Value> {
        let (document, _) = self.resolve_principal(&input.principal_id).await?;
        // The authoritative service is the one the principal names, never one
        // supplied by whoever presented a credential.
        let query_url = document.delegation_query_url.clone().ok_or_else(|| {
            SdkError::InvalidPayload(format!(
                "principal {} publishes no delegation_query_url",
                document.id
            ))
        })?;
        let request = DelegationQueryRequest {
            subject: Some(input.subject.unwrap_or_else(|| self.agent_id())),
            principal_id: Some(document.id.clone()),
            id: input.id,
            status: input.status,
            limit: None,
        };
        let response = DelegationClient::new(&query_url)
            .query_delegations_at(&query_url, &request, None)
            .await?;
        json_result(json!({
            "canonical_id": document.id,
            "query_url": query_url,
            "delegations": response.result,
        }))
    }

    async fn delegations_list(&self, input: DelegationsListInput) -> Result<Value> {
        // Enumerating one subject requires authorization; the connector proves
        // the active identity and never enumerates anyone else.
        let jwt = self.request_jwt(&input.delegation_service)?;
        let request = DelegationQueryRequest {
            subject: Some(self.agent_id()),
            principal_id: None,
            id: None,
            status: input.status,
            limit: input.limit,
        };
        let response = DelegationClient::new(&input.delegation_service)
            .query_delegations(&request, Some(&jwt))
            .await?;
        json_result(json!({ "delegations": response.result }))
    }

    async fn delegation_previous(
        &self,
        principal: &PrincipalDocument,
        service: &str,
        id: &str,
    ) -> Result<Option<DelegationCredential>> {
        self.request_jwt(service)?; // Enforce operator host policy before the read.
        let expected = format!("{}/v1/delegations/query", service.trim_end_matches('/'));
        if principal.delegation_query_url.as_deref() != Some(&expected) {
            return Err(SdkError::InvalidPayload(
                "delegation service does not match principal authority".into(),
            ));
        }
        match DelegationClient::new(service).delegation(id).await {
            Ok(value) => Ok(Some(value)),
            Err(SdkError::Http(e)) if e.status() == Some(reqwest::StatusCode::NOT_FOUND) => {
                Ok(None)
            }
            Err(e) => Err(e),
        }
    }

    async fn delegation_grant(&mut self, input: DelegationGrantInput) -> Result<Value> {
        let principal = self.controller_principal(&input.principal_id).await?;
        let previous = self
            .delegation_previous(&principal, &input.delegation_service, &input.id)
            .await?;
        let mut payload = DelegationGrantPayload::new(
            input.id,
            PrincipalDescriptor::new(principal.id.clone()),
            input.subject,
            input.scopes,
            input.audiences,
        );
        payload.relationship = input.relationship;
        payload.constraints = input.constraints;
        payload.not_before = input.not_before;
        payload.expires_at = input.expires_at;
        let created_at = unix_ms();
        let event = Event::new(
            crate::delegation::PROTOCOL,
            crate::delegation::DELEGATION_GRANT,
            self.agent_id(),
            created_at,
            self.nonce_manager.next_nonce()?,
            DelegationPayload::Grant(payload),
        );
        validate_delegation_event_authority(&event, &principal, created_at, previous.as_ref())?;
        let envelope = self.signer.sign_event(event)?;
        let credential = DelegationClient::new(&input.delegation_service)
            .submit_delegation_event(&envelope)
            .await?;
        json_result(json!({ "credential": credential, "envelope": envelope }))
    }

    async fn delegation_revoke(&mut self, input: DelegationRevokeInput) -> Result<Value> {
        let principal = self.controller_principal(&input.principal_id).await?;
        let previous = self
            .delegation_previous(&principal, &input.delegation_service, &input.id)
            .await?;
        let created_at = unix_ms();
        let event = Event::new(
            crate::delegation::PROTOCOL,
            crate::delegation::DELEGATION_REVOKE,
            self.agent_id(),
            created_at,
            self.nonce_manager.next_nonce()?,
            DelegationPayload::Revoke(DelegationRevokePayload {
                id: input.id,
                principal_id: principal.id.clone(),
                reason: input.reason,
            }),
        );
        validate_delegation_event_authority(&event, &principal, created_at, previous.as_ref())?;
        let envelope = self.signer.sign_event(event)?;
        let result = DelegationClient::new(&input.delegation_service)
            .submit_delegation_event(&envelope)
            .await?;
        json_result(json!({ "result": result, "envelope": envelope }))
    }

    async fn profile_update(&mut self, input: ProfileUpdateInput) -> Result<Value> {
        let mut profile = input.profile;
        let object = profile
            .as_object_mut()
            .ok_or_else(|| SdkError::InvalidPayload("profile must be an object".to_owned()))?;
        // payload.id is always the active Agent ID; reject an input that
        // names a different agent instead of silently rewriting it.
        let active_id = serde_json::to_value(self.agent_id())?;
        match object.get("id") {
            None => {
                object.insert("id".to_owned(), active_id);
            }
            Some(id) if *id == active_id => {}
            Some(_) => {
                return Err(SdkError::InvalidPayload(
                    "profile.id must be the active Agent ID".to_owned(),
                ));
            }
        }
        let payload: ProfileUpdatePayload = serde_json::from_value(profile)?;
        let envelope = self.sign_profile_update(payload)?;
        let materialized = ProfileClient::new(&input.profile_service)
            .submit_profile_update(&envelope)
            .await?;
        self.state
            .profiles
            .insert(materialized.id.clone(), materialized.clone());
        json_result(json!({ "profile": materialized, "envelope": envelope }))
    }

    async fn room_create(&mut self, input: RoomCreateInput) -> Result<Value> {
        let host = normalize_host(&input.host);
        self.require_allowed_host(&host)?;
        let mut payload = RoomCreatePayload::new(
            input.topic,
            input.visibility,
            input.start_time,
            input.end_time,
        );
        payload.agenda = input.agenda;
        payload.guidance = input.guidance;
        payload.tags = input.tags;
        payload.language = input.language;
        payload.policy = input.policy;
        payload.types = input.types;
        let envelope = self.sign_room_create(payload)?;
        let mut room = DiscourseClient::new(&host).create_room(&envelope).await?;
        if room.envelope.is_none() {
            room.envelope = Some(envelope.clone());
        }
        self.accept_room_response(&host, room.clone());
        let key = (host, room.id.clone());
        json_result(json!({
            "room": self.room_state_view(self.local_room(&key)?),
            "envelope": envelope,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn room_join(&mut self, input: RoomJoinInput) -> Result<Value> {
        let room_id = input.room_id.clone();
        let key = match input.host.as_deref() {
            Some(host) => {
                let host = normalize_host(host);
                self.require_allowed_host(&host)?;
                (host, room_id.clone())
            }
            None => {
                let key = self.resolve_room_key(None, &room_id)?;
                self.require_allowed_host(&key.0)?;
                key
            }
        };
        let host = key.0.clone();

        if !self.state.rooms.contains_key(&key) {
            let room = DiscourseClient::new(&host).room(&room_id).await?;
            self.accept_room_response(&host, room);
        }

        if let Some(request_id) = input.request_id {
            let jwt = self.request_jwt(&host)?;
            let status = DiscourseClient::new(&host)
                .join_request(&room_id, &request_id, &jwt)
                .await?;
            if status.request.applicant != self.agent_id() {
                return Err(SdkError::InvalidPayload(
                    "join request belongs to another agent".to_owned(),
                ));
            }
            if status.status != JoinRequestStatus::Approved {
                return Err(SdkError::InvalidPayload(
                    "join request is not approved".to_owned(),
                ));
            }
            // The completion call signs room.join with the approved role; a
            // differing input role is a mismatch error, never a silent
            // substitution.
            let approved_role = status.approved_role.unwrap_or(status.request.role);
            if input.role != approved_role {
                return Err(SdkError::InvalidPayload(format!(
                    "join_request_role_mismatch: approved role is {approved_role:?}"
                )));
            }
            let payload = RoomJoinPayload {
                request_id: Some(request_id),
                role: approved_role,
                perspective: None,
            };
            let envelope =
                self.sign_room_event(event_type::ROOM_JOIN, &key, None, None, Vec::new(), payload)?;
            let record = DiscourseClient::new(&host)
                .join_room(&room_id, &envelope)
                .await?;
            let record = typed_record_to_value(record)?;
            self.apply_host_record(&host, record.clone())?;
            let member = self
                .local_room(&key)?
                .members
                .get(&self.agent_id())
                .cloned()
                .ok_or_else(|| {
                    SdkError::InvalidPayload("joined member not materialized".to_owned())
                })?;
            return json_result(json!({
                "status": "joined",
                "record": record,
                "member": member,
                "sync": self.sync_state(&key)?
            }));
        }

        if room_visibility(&self.local_room(&key)?.room) == Some(Visibility::Public) {
            let payload = RoomJoinPayload {
                request_id: None,
                role: input.role,
                perspective: input.perspective,
            };
            let envelope =
                self.sign_room_event(event_type::ROOM_JOIN, &key, None, None, Vec::new(), payload)?;
            let record = DiscourseClient::new(&host)
                .join_room(&room_id, &envelope)
                .await?;
            let record = typed_record_to_value(record)?;
            self.apply_host_record(&host, record.clone())?;
            let member = self
                .local_room(&key)?
                .members
                .get(&self.agent_id())
                .cloned()
                .ok_or_else(|| {
                    SdkError::InvalidPayload("joined member not materialized".to_owned())
                })?;
            return json_result(json!({
                "status": "joined",
                "record": record,
                "member": member,
                "sync": self.sync_state(&key)?
            }));
        }

        let jwt = self.request_jwt(&host)?;
        let mut request = RoomJoinRequestInput::new(input.role);
        request.perspective = input.perspective;
        request.reason = input.reason;
        request.extra = input.extra;
        let status = DiscourseClient::new(&host)
            .request_join(&room_id, &jwt, &request)
            .await?;
        self.state
            .join_requests
            .entry(key.clone())
            .or_default()
            .push(status.clone());
        json_result(json!({
            "status": "approval_required",
            "join_request": status,
            "sync": self.sync_state(&key).ok()
        }))
    }

    async fn room_join_request(&mut self, input: RoomJoinRequestToolInput) -> Result<Value> {
        let host = normalize_host(&input.host);
        self.require_allowed_host(&host)?;
        let jwt = self.request_jwt(&host)?;
        let mut request = RoomJoinRequestInput::new(input.role);
        request.perspective = input.perspective;
        request.reason = input.reason;
        request.extra = input.extra;
        let status = DiscourseClient::new(&host)
            .request_join(&input.room_id, &jwt, &request)
            .await?;
        self.state
            .join_requests
            .entry((host, input.room_id))
            .or_default()
            .push(status.clone());
        json_result(json!({ "join_request": status }))
    }

    async fn room_join_when_approved(&mut self, input: RoomJoinWhenApprovedInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let host = self.allowed_room_host(&key)?;
        let jwt = self.request_jwt(&host)?;
        let status = DiscourseClient::new(&host)
            .join_request(&input.room_id, &input.request_id, &jwt)
            .await?;
        if status.request.applicant != self.agent_id() {
            return Err(SdkError::InvalidPayload(
                "join request belongs to another agent".to_owned(),
            ));
        }
        if status.status != JoinRequestStatus::Approved {
            return Err(SdkError::InvalidPayload(
                "join request is not approved".to_owned(),
            ));
        }
        let role = status.approved_role.unwrap_or(status.request.role);
        let payload = RoomJoinPayload {
            request_id: Some(input.request_id),
            role,
            perspective: None,
        };
        let envelope =
            self.sign_room_event(event_type::ROOM_JOIN, &key, None, None, Vec::new(), payload)?;
        let record = DiscourseClient::new(&host)
            .join_room(&input.room_id, &envelope)
            .await?;
        let record = typed_record_to_value(record)?;
        self.apply_host_record(&host, record.clone())?;
        let member = self
            .local_room(&key)?
            .members
            .get(&self.agent_id())
            .cloned()
            .ok_or_else(|| SdkError::InvalidPayload("joined member not materialized".to_owned()))?;
        json_result(json!({
            "record": record,
            "member": member,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn room_leave(&mut self, input: RoomLeaveInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let host = self.allowed_room_host(&key)?;
        let payload = ReasonPayload {
            reason: input.reason,
            references: Vec::new(),
            extra: BTreeMap::new(),
        };
        let envelope = self.sign_room_event(
            event_type::ROOM_LEAVE,
            &key,
            None,
            None,
            Vec::new(),
            payload,
        )?;
        let record = DiscourseClient::new(&host)
            .leave_room(&input.room_id, &envelope)
            .await?;
        let record = typed_record_to_value(record)?;
        self.apply_host_record(&host, record.clone())?;
        json_result(json!({ "record": record, "sync": self.sync_state(&key)? }))
    }

    async fn room_send_message(&mut self, mut input: RoomSendMessageInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        if let Some(result) = self.head_mismatch_message_result(&key, &mut input)? {
            return Ok(result);
        }
        self.submit_message_unchecked(input).await
    }

    async fn submit_message_unchecked(&mut self, input: RoomSendMessageInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let host = self.allowed_room_host(&key)?;
        let mut payload = MessageCreatePayload::new(
            input
                .content_type
                .unwrap_or_else(|| "text/plain".to_owned()),
            Value::String(input.content),
        );
        payload.references = input.references;
        payload.extra = input.extra;
        let envelope = self.sign_room_event(
            event_type::MESSAGE_CREATE,
            &key,
            input.base_seq,
            input.base_hash.clone(),
            input.mentions,
            payload,
        )?;
        let record = DiscourseClient::new(&host)
            .submit_event(&input.room_id, &envelope)
            .await?;
        self.apply_host_record(&host, record.clone())?;
        let item = self.timeline_item_by_event(&key, &record.envelope.hash)?;
        json_result(json!({
            "status": "sent",
            "record": record,
            "item": item,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn room_submit_event(&mut self, mut input: RoomSubmitEventInput) -> Result<Value> {
        // For signal-kind writes — including the membership events — the base
        // is only an anchor: never hold the draft, ignore on_head_mismatch.
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let advances_head = self
            .state
            .rooms
            .get(&key)
            .map(|room| event_type_advances_room_head(room, &input.event_type))
            .unwrap_or(true);
        if advances_head {
            if let Some(result) = self.head_mismatch_event_result(&key, &mut input)? {
                return Ok(result);
            }
        }
        self.submit_event_unchecked(input).await
    }

    async fn submit_event_unchecked(&mut self, input: RoomSubmitEventInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let host = self.allowed_room_host(&key)?;
        let payload = payload_with_references(input.payload, input.references)?;
        let envelope = self.sign_room_event(
            input.event_type,
            &key,
            input.base_seq,
            input.base_hash.clone(),
            input.mentions,
            payload,
        )?;
        let record = DiscourseClient::new(&host)
            .submit_event(&input.room_id, &envelope)
            .await?;
        self.apply_host_record(&host, record.clone())?;
        let item = self.timeline_item_by_event(&key, &record.envelope.hash)?;
        json_result(json!({
            "status": "sent",
            "record": record,
            "item": item,
            "sync": self.sync_state(&key)?
        }))
    }

    async fn join_requests_list(&mut self, input: JoinRequestsListInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let host = self.allowed_room_host(&key)?;
        let jwt = self.request_jwt(&host)?;
        let mut requests = DiscourseClient::new(&host)
            .join_requests(&input.room_id, &jwt)
            .await?;
        if let Some(status) = input.status {
            requests.retain(|request| {
                serde_json::to_value(request.status)
                    .ok()
                    .and_then(|value| value.as_str().map(str::to_owned))
                    == Some(status.clone())
            });
        }
        let offset = input
            .cursor
            .as_deref()
            .and_then(|cursor| cursor.parse::<usize>().ok())
            .unwrap_or(0);
        if offset > 0 {
            requests = requests.into_iter().skip(offset).collect();
        }
        requests.truncate(input.limit.unwrap_or(requests.len()));
        self.state
            .join_requests
            .insert(key.clone(), requests.clone());
        json_result(json!({ "join_requests": requests }))
    }

    async fn join_request_review(&mut self, input: JoinRequestReviewInput) -> Result<Value> {
        let key = self.resolve_room_key(input.host.as_deref(), &input.room_id)?;
        let host = self.allowed_room_host(&key)?;
        let jwt = self.request_jwt(&host)?;
        let status = DiscourseClient::new(&host)
            .join_request(&input.room_id, &input.request_id, &jwt)
            .await?;
        let payload = RoomJoinReviewPayload {
            request: status.request,
            decision: input.decision,
            role: input.role,
            reason: input.reason,
            extra: BTreeMap::new(),
        };
        let envelope = self.sign_room_event(
            event_type::ROOM_JOIN_REVIEW,
            &key,
            None,
            None,
            Vec::new(),
            payload,
        )?;
        let record = DiscourseClient::new(&host)
            .submit_event(&input.room_id, &envelope)
            .await?;
        self.apply_host_record(&host, record.clone())?;
        json_result(json!({ "record": record, "sync": self.sync_state(&key)? }))
    }

    fn sign_profile_update(
        &mut self,
        payload: ProfileUpdatePayload,
    ) -> Result<Envelope<ProfileUpdatePayload>> {
        let event = profile_update_event(
            self.agent_id(),
            unix_ms(),
            self.nonce_manager.next_nonce()?,
            payload,
        );
        self.signer.sign_event(event)
    }

    fn sign_room_create(
        &mut self,
        payload: RoomCreatePayload,
    ) -> Result<Envelope<RoomCreatePayload>> {
        let event = room_create_event(
            self.agent_id(),
            unix_ms(),
            self.nonce_manager.next_nonce()?,
            payload,
        );
        let envelope = self.signer.sign_event(event)?;
        validate_discourse_envelope(&envelope)?;
        Ok(envelope)
    }

    fn sign_room_event<P>(
        &mut self,
        event_type: impl Into<String>,
        key: &RoomKey,
        base_seq: Option<u64>,
        base_hash: Option<String>,
        mentions: Vec<AgentId>,
        payload: P,
    ) -> Result<Envelope<P>>
    where
        P: Serialize,
    {
        let host = self.local_room(key)?.host.clone();
        self.require_allowed_host(&host)?;
        let (base_seq, base_hash) = self.room_head_for_write(key, base_seq, base_hash)?;
        let event = discourse_event(
            event_type,
            self.agent_id(),
            unix_ms(),
            self.nonce_manager.next_nonce()?,
            key.1.clone(),
            base_seq,
            base_hash,
            payload,
        )
        .with_mentions(mentions);
        let envelope = self.signer.sign_event(event)?;
        validate_discourse_envelope(&envelope)?;
        Ok(envelope)
    }

    fn room_head_for_write(
        &self,
        key: &RoomKey,
        base_seq: Option<u64>,
        base_hash: Option<String>,
    ) -> Result<(u64, String)> {
        match (base_seq, base_hash) {
            (Some(seq), Some(hash)) if seq > 0 && !hash.trim().is_empty() => Ok((seq, hash)),
            (Some(_), Some(_)) => Err(SdkError::InvalidPayload(
                "base_seq and base_hash must identify a valid room head".to_owned(),
            )),
            (None, None) => {
                let sync = self.sync_state(key)?;
                let hash = sync.head_hash;
                if sync.head_seq == 0 || hash.trim().is_empty() {
                    return Err(SdkError::InvalidPayload(
                        "current room head is not known locally".to_owned(),
                    ));
                }
                Ok((sync.head_seq, hash))
            }
            _ => Err(SdkError::InvalidPayload(
                "base_seq and base_hash must be provided together".to_owned(),
            )),
        }
    }

    fn request_jwt(&self, host: &str) -> Result<String> {
        // The request JWT aud is always the origin of the host API.
        let host = normalize_host(host);
        self.require_allowed_host(&host)?;
        let audience = crate::identity::service_origin(&host)?;
        let claims = RequestJwtClaims::new(
            self.agent_id(),
            RequestBinding::new(audience),
            unix_secs(),
            DEFAULT_REQUEST_JWT_TTL_SECS,
        );
        self.signer.sign_request_jwt(&claims)
    }

    fn head_mismatch_message_result(
        &mut self,
        key: &RoomKey,
        input: &mut RoomSendMessageInput,
    ) -> Result<Option<Value>> {
        let Some(head_mismatch) =
            self.head_mismatch_write_state(key, input.base_seq, input.base_hash.as_deref())?
        else {
            return Ok(None);
        };

        match input.on_head_mismatch {
            HeadMismatchPolicy::SendAnyway => {
                input.base_seq = None;
                input.base_hash = None;
                Ok(None)
            }
            HeadMismatchPolicy::Reject => {
                Ok(Some(self.rejected_head_mismatch_result(head_mismatch)))
            }
            HeadMismatchPolicy::Hold => {
                Ok(Some(self.hold_message_draft(input.clone(), head_mismatch)?))
            }
        }
    }

    fn head_mismatch_event_result(
        &mut self,
        key: &RoomKey,
        input: &mut RoomSubmitEventInput,
    ) -> Result<Option<Value>> {
        let Some(head_mismatch) =
            self.head_mismatch_write_state(key, input.base_seq, input.base_hash.as_deref())?
        else {
            return Ok(None);
        };

        match input.on_head_mismatch {
            HeadMismatchPolicy::SendAnyway => {
                input.base_seq = None;
                input.base_hash = None;
                Ok(None)
            }
            HeadMismatchPolicy::Reject => {
                Ok(Some(self.rejected_head_mismatch_result(head_mismatch)))
            }
            HeadMismatchPolicy::Hold => {
                Ok(Some(self.hold_event_draft(input.clone(), head_mismatch)?))
            }
        }
    }

    fn head_mismatch_write_state(
        &self,
        key: &RoomKey,
        base_seq: Option<u64>,
        base_hash: Option<&str>,
    ) -> Result<Option<HeadMismatchState>> {
        if base_seq.is_none() && base_hash.is_none() {
            return Ok(None);
        }

        let sync = self.sync_state(key)?;
        let seq_mismatch = base_seq
            .map(|base_seq| base_seq != sync.head_seq)
            .unwrap_or(false);
        let hash_mismatch = base_hash
            .map(|expected_hash| sync.head_hash != expected_hash)
            .unwrap_or(false);
        if !seq_mismatch && !hash_mismatch {
            return Ok(None);
        }

        Ok(Some(HeadMismatchState {
            sync,
            changes: self.room_changes_since(key, base_seq)?,
        }))
    }

    fn rejected_head_mismatch_result(&self, head_mismatch: HeadMismatchState) -> Value {
        json!({
            "status": "rejected",
            "reason": "room_head_mismatch",
            "changes": head_mismatch.changes,
            "sync": head_mismatch.sync
        })
    }

    fn hold_message_draft(
        &mut self,
        mut input: RoomSendMessageInput,
        head_mismatch: HeadMismatchState,
    ) -> Result<Value> {
        input.host = Some(head_mismatch.sync.host.clone());
        let draft_id = self.next_draft_id(&input.room_id);
        let draft = HeldDraft {
            id: draft_id.clone(),
            room_id: input.room_id.clone(),
            kind: HeldDraftKind::Message,
            created_at: unix_ms(),
            base_seq: input.base_seq,
            base_hash: input.base_hash.clone(),
            current_sync: head_mismatch.sync.clone(),
            draft: message_draft_value(&input)?,
            reason: "room_head_mismatch".to_owned(),
            options: held_draft_options(),
        };
        self.state.drafts.insert(
            draft_id,
            HeldDraftEntry {
                draft: draft.clone(),
                request: HeldDraftRequest::Message(input),
            },
        );
        json_result(json!({
            "status": "held",
            "reason": "room_head_mismatch",
            "draft": draft,
            "changes": head_mismatch.changes,
            "sync": head_mismatch.sync
        }))
    }

    fn hold_event_draft(
        &mut self,
        mut input: RoomSubmitEventInput,
        head_mismatch: HeadMismatchState,
    ) -> Result<Value> {
        input.host = Some(head_mismatch.sync.host.clone());
        let draft_id = self.next_draft_id(&input.room_id);
        let draft = HeldDraft {
            id: draft_id.clone(),
            room_id: input.room_id.clone(),
            kind: HeldDraftKind::Event,
            created_at: unix_ms(),
            base_seq: input.base_seq,
            base_hash: input.base_hash.clone(),
            current_sync: head_mismatch.sync.clone(),
            draft: event_draft_value(&input)?,
            reason: "room_head_mismatch".to_owned(),
            options: held_draft_options(),
        };
        self.state.drafts.insert(
            draft_id,
            HeldDraftEntry {
                draft: draft.clone(),
                request: HeldDraftRequest::Event(input),
            },
        );
        json_result(json!({
            "status": "held",
            "reason": "room_head_mismatch",
            "draft": draft,
            "changes": head_mismatch.changes,
            "sync": head_mismatch.sync
        }))
    }

    fn room_changes_since(
        &self,
        key: &RoomKey,
        base_seq: Option<u64>,
    ) -> Result<Vec<TimelineItem>> {
        let room = self.local_room(key)?;
        let changes = match base_seq {
            Some(seq) => room
                .timeline
                .iter()
                .filter(|item| item.seq > seq)
                .cloned()
                .collect(),
            None => {
                let mut items = room
                    .timeline
                    .iter()
                    .rev()
                    .take(20)
                    .cloned()
                    .collect::<Vec<_>>();
                items.reverse();
                items
            }
        };
        Ok(changes)
    }

    fn next_draft_id(&self, room_id: &str) -> String {
        let room = room_id
            .chars()
            .map(|ch| {
                if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
                    ch
                } else {
                    '_'
                }
            })
            .collect::<String>();
        format!("draft_{}_{}", room, self.state.drafts.len() + 1)
    }

    fn sync_state(&self, key: &RoomKey) -> Result<SyncState> {
        let room = self.local_room(key)?;
        let head_hash = room
            .head_hash
            .clone()
            .or_else(|| room.room.head.as_ref().map(|head| head.hash.clone()))
            .unwrap_or_else(|| room.room.hash.clone());
        Ok(SyncState {
            host: room.host.clone(),
            room_id: key.1.clone(),
            head_seq: room.head_seq,
            head_hash,
            synced_seq: room.synced_seq,
            remote_seq: room.room.seq.max(room.synced_seq),
            subscribed: room.subscribed,
            unread_count: room.unread_count(),
            pending_inbox_count: self.pending_inbox_count(Some(&key.1)),
        })
    }

    fn room_state_view(&self, room: &LocalRoomState) -> RoomStateView {
        let self_member = room.members.get(&self.agent_id()).cloned();
        RoomStateView {
            host: room.host.clone(),
            room_id: room.room.id.clone(),
            status: room.room.status,
            visibility: room_visibility(&room.room),
            topic: room_topic(&room.room),
            agenda: room_agenda(&room.room),
            guidance: room_guidance(&room.room),
            creator: room
                .room
                .envelope
                .as_ref()
                .map(|envelope| envelope.event.actor.clone()),
            created_at: room
                .room
                .envelope
                .as_ref()
                .map(|envelope| envelope.event.created_at),
            start_time: room_start_time(&room.room),
            end_time: room_end_time(&room.room),
            tags: room_tags(&room.room),
            language: room_language(&room.room),
            policy: room_policy(&room.room),
            types: room.room.types.clone(),
            self_member,
            members_count: room.members.len(),
            active_turn: room.active_turn.clone(),
            unread_count: room.unread_count(),
            pending_inbox_count: self.pending_inbox_count(Some(&room.room.id)),
        }
    }

    fn summary_for_room(&self, room: &LocalRoomState) -> RoomSummary {
        let self_member = room.members.get(&self.agent_id());
        RoomSummary {
            room_id: room.room.id.clone(),
            host: room.host.clone(),
            topic: room_topic(&room.room),
            status: room.room.status,
            visibility: room_visibility(&room.room),
            start_time: room_start_time(&room.room),
            end_time: room_end_time(&room.room),
            tags: room_tags(&room.room),
            language: room_language(&room.room),
            role: self_member.map(|member| member.role),
            unread_count: room.unread_count(),
            pending_inbox_count: self.pending_inbox_count(Some(&room.room.id)),
        }
    }

    fn summary_for_response(&self, host: &str, room: &RoomResponse) -> RoomSummary {
        self.state
            .rooms
            .get(&(host.to_owned(), room.id.clone()))
            .map(|room| self.summary_for_room(room))
            .unwrap_or_else(|| RoomSummary {
                room_id: room.id.clone(),
                host: host.to_owned(),
                topic: room_topic(room),
                status: room.status,
                visibility: room_visibility(room),
                start_time: room_start_time(room),
                end_time: room_end_time(room),
                tags: room_tags(room),
                language: room_language(room),
                role: None,
                unread_count: 0,
                pending_inbox_count: 0,
            })
    }

    fn timeline_item_by_event(&self, key: &RoomKey, event_id: &str) -> Result<TimelineItem> {
        self.local_room(key)?
            .timeline
            .iter()
            .find(|item| item.event_id == event_id)
            .cloned()
            .ok_or_else(|| SdkError::InvalidPayload("timeline item not materialized".to_owned()))
    }

    fn local_room(&self, key: &RoomKey) -> Result<&LocalRoomState> {
        self.state
            .rooms
            .get(key)
            .ok_or_else(|| SdkError::InvalidPayload(format!("room is not open locally: {}", key.1)))
    }

    fn local_room_mut(&mut self, key: &RoomKey) -> Result<&mut LocalRoomState> {
        self.state
            .rooms
            .get_mut(key)
            .ok_or_else(|| SdkError::InvalidPayload(format!("room is not open locally: {}", key.1)))
    }

    fn require_allowed_host(&self, host: &str) -> Result<()> {
        match self.state.hosts.get(host) {
            Some(host) if host.allowed => Ok(()),
            _ => Err(SdkError::PermissionDenied),
        }
    }

    fn allowed_room_host(&self, key: &RoomKey) -> Result<String> {
        let host = self.local_room(key)?.host.clone();
        self.require_allowed_host(&host)?;
        Ok(host)
    }

    fn ensure_host(&mut self, host: &str) {
        self.state
            .hosts
            .entry(host.to_owned())
            .or_insert_with(|| AgentProtocolsHost {
                host: host.to_owned(),
                label: None,
                allowed: false,
                features: Vec::new(),
                profile_service: None,
                last_checked_at: None,
            });
    }

    fn insert_inbox(&mut self, item: InboxItem) {
        self.state
            .inbox
            .entry(item.id.clone())
            .or_insert(InboxEntry {
                item,
                state: InboxEntryState::Pending,
            });
    }

    fn pending_inbox_count(&self, room_id: Option<&str>) -> usize {
        let now = unix_ms();
        self.state
            .inbox
            .values()
            .filter(|entry| inbox_entry_ready(entry, now))
            .filter(|entry| {
                room_id
                    .map(|room_id| entry.item.room_id.as_deref() == Some(room_id))
                    .unwrap_or(true)
            })
            .count()
    }
}

fn parse_input<T: DeserializeOwned>(input: Value) -> Result<T> {
    Ok(serde_json::from_value(input)?)
}

fn json_result(value: Value) -> Result<Value> {
    Ok(value)
}

fn normalize_host(host: &str) -> String {
    host.trim_end_matches('/').to_owned()
}

fn typed_record_to_value<P>(record: ServerRecord<P>) -> Result<ServerRecord>
where
    P: Serialize,
{
    Ok(serde_json::from_value(serde_json::to_value(record)?)?)
}

fn membership_filter(
    room: &LocalRoomState,
    agent_id: &AgentId,
    membership: Option<RoomsListMembership>,
) -> bool {
    match membership.unwrap_or(RoomsListMembership::All) {
        RoomsListMembership::All => true,
        RoomsListMembership::Member => room.members.contains_key(agent_id),
        RoomsListMembership::Creator => room
            .members
            .get(agent_id)
            .map(|member| member.is_creator)
            .unwrap_or(false),
        RoomsListMembership::Moderator => room
            .members
            .get(agent_id)
            .map(|member| member.role == Role::Moderator)
            .unwrap_or(false),
        RoomsListMembership::Pending => false,
    }
}

fn payload_with_references(mut payload: Value, references: Vec<String>) -> Result<Value> {
    if references.is_empty() {
        return Ok(payload);
    }
    let object = payload
        .as_object_mut()
        .ok_or_else(|| SdkError::InvalidPayload("event payload must be an object".to_owned()))?;
    let extra = object
        .entry("extra")
        .or_insert_with(|| Value::Object(Default::default()));
    let extra = extra
        .as_object_mut()
        .ok_or_else(|| SdkError::InvalidPayload("payload.extra must be an object".to_owned()))?;
    extra.insert("references".to_owned(), serde_json::to_value(references)?);
    Ok(payload)
}

fn message_draft_value(input: &RoomSendMessageInput) -> Result<Value> {
    Ok(json!({
        "room_id": &input.room_id,
        "content": &input.content,
        "content_type": input.content_type.as_deref().unwrap_or("text/plain"),
        "mentions": &input.mentions,
        "references": &input.references,
        "extra": &input.extra
    }))
}

fn event_draft_value(input: &RoomSubmitEventInput) -> Result<Value> {
    Ok(json!({
        "room_id": &input.room_id,
        "type": &input.event_type,
        "payload": &input.payload,
        "mentions": &input.mentions,
        "references": &input.references
    }))
}

fn held_draft_options() -> Vec<DraftAction> {
    vec![
        DraftAction::Revise,
        DraftAction::SendAsIs,
        DraftAction::StaySilent,
        DraftAction::SendAnyway,
    ]
}

fn profile_to_member_profile(profile: &AgentProfile) -> RoomMemberProfile {
    RoomMemberProfile {
        name: Some(profile.name.clone()),
        description: profile.description.clone(),
        avatar_url: profile.avatar_url.clone(),
    }
}