mail4agent-messenger 0.4.2

Sans-I/O Matrix Client-Server-subset sync + E2EE (Olm/Megolm) engine -- no network, no disk; shells execute OutgoingRequests and persist sealed records the core exports through a flush-before-send barrier.
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
//! [`OutgoingRequest`] / [`HttpResponseDescriptor`] — the data shapes that
//! cross the network boundary, plus one builder per Matrix Client-Server
//! API endpoint this crate needs. Every builder's path template lives as a
//! single `PATH_TEMPLATE` constant scoped to that builder's own function
//! body — greppable (`grep -n PATH_TEMPLATE`), one hit per endpoint, never
//! inlined again at a call site (plan §6.8's note, generalized to every
//! endpoint rather than just the two it called out).

use crate::ids::{EventId, RequestId, RoomId, TxnId, UserId};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Percent-encodes one path segment. Conservative on purpose: only RFC
/// 3986's `unreserved` set (`ALPHA / DIGIT / "-" / "." / "_" / "~"`) is
/// left unescaped; everything else — including Matrix's own sigils (`!`,
/// `$`, `:`, `@`), which RFC 3986's `pchar` grammar would technically
/// permit unescaped in a path segment — is escaped. This removes any
/// ambiguity between "path delimiter" and "literal sigil character" for a
/// router that naively splits on `/`, `:`, or `!`, exactly the ids this
/// crate mints into paths.
pub(crate) fn percent_encode_segment(segment: &str) -> String {
    let mut out = String::with_capacity(segment.len());
    for byte in segment.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(byte as char);
            }
            _ => {
                out.push('%');
                out.push_str(&format!("{byte:02X}"));
            }
        }
    }
    out
}

/// Reverses [`percent_encode_segment`]: decodes `%XX` escapes back to their
/// original byte values and interprets the result as UTF-8. Returns `None`
/// for a malformed escape (an incomplete or non-hex `%` sequence) or a
/// decoded byte sequence that is not valid UTF-8. Used by
/// [`crate::store`]'s record-key parser to recover the dynamic components
/// (room/user/session/request ids) this module's builders percent-encode
/// into a storage key.
pub(crate) fn percent_decode_segment(segment: &str) -> Option<String> {
    let bytes = segment.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'%' => {
                let hex = segment.get(i + 1..i + 3)?;
                let byte = u8::from_str_radix(hex, 16).ok()?;
                out.push(byte);
                i += 3;
            }
            b => {
                out.push(b);
                i += 1;
            }
        }
    }
    String::from_utf8(out).ok()
}

/// Substitutes every `{placeholder}` token in `template` with the
/// percent-encoded form of its paired value.
fn substitute(template: &str, params: &[(&str, &str)]) -> String {
    let mut path = template.to_string();
    for (placeholder, value) in params {
        path = path.replace(placeholder, &percent_encode_segment(value));
    }
    path
}

/// HTTP method for an [`OutgoingRequest`]. The Matrix Client-Server API
/// only ever uses these three verbs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HttpMethod {
    /// `GET`.
    Get,
    /// `POST`.
    Post,
    /// `PUT`.
    Put,
}

impl HttpMethod {
    /// The method's own uppercase wire form (`"GET"`, `"POST"`, `"PUT"`).
    pub fn as_str(self) -> &'static str {
        match self {
            HttpMethod::Get => "GET",
            HttpMethod::Post => "POST",
            HttpMethod::Put => "PUT",
        }
    }
}

impl fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// What kind of Matrix Client-Server API call an [`OutgoingRequest`] is —
/// a plain tag the core uses to know how to interpret the matching
/// [`HttpResponseDescriptor`] (e.g. "this one's body is a `SyncResponse`").
/// The actual path/query/body are already baked into the `OutgoingRequest`
/// itself; this enum carries no duplicate parameters.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum OutgoingRequestKind {
    /// `GET /sync` — long-poll for new events, device-list changes, and
    /// one-time-key counts.
    Sync,
    /// `POST /keys/upload` — publish device identity keys and one-time
    /// keys.
    KeysUpload,
    /// `POST /keys/query` — fetch other users' device keys.
    KeysQuery,
    /// `POST /keys/claim` — claim one-time keys to start new Olm sessions.
    KeysClaim,
    /// `GET /keys/changes` — list users whose device lists changed in a
    /// sync range.
    KeysChanges,
    /// `PUT /sendToDevice/{eventType}/{txnId}` — send one or more
    /// to-device events.
    SendToDevice,
    /// `POST /keys/device_signing/upload` — publish cross-signing keys.
    SigningKeysUpload,
    /// `POST /keys/signatures/upload` — publish cross-signing signatures.
    SignaturesUpload,
    /// `PUT /rooms/{roomId}/send/{eventType}/{txnId}` — send a timeline
    /// event.
    RoomSend,
    /// `PUT /rooms/{roomId}/redact/{eventId}/{txnId}` — redact an event.
    RoomRedact,
    /// `PUT /rooms/{roomId}/state/{eventType}/{stateKey}` — set one piece
    /// of room state.
    RoomState,
    /// `GET /rooms/{roomId}/messages` — paginate a room's timeline.
    RoomMessages,
    /// `GET /rooms/{roomId}/members` — list a room's members.
    RoomMembers,
    /// `POST /createRoom` — create a room.
    CreateRoom,
    /// `POST /rooms/{roomId}/join` — join a room by id.
    JoinRoom,
    /// `POST /rooms/{roomId}/leave` — leave a room.
    LeaveRoom,
    /// `POST /rooms/{roomId}/invite` — invite a user to a room.
    Invite,
    /// `POST /rooms/{roomId}/kick` — remove a user from a room.
    Kick,
    /// `PUT /rooms/{roomId}/typing/{userId}` — set/clear a typing
    /// indicator.
    Typing,
    /// `POST /rooms/{roomId}/receipt/{receiptType}/{eventId}` — send a
    /// read receipt.
    Receipt,
    /// `POST /rooms/{roomId}/read_markers` — set the fully-read marker.
    ReadMarkers,
    /// `PUT /user/{userId}/account_data/{type}` — set global account data.
    AccountData,
    /// `PUT /user/{userId}/rooms/{roomId}/account_data/{type}` — set
    /// room-scoped account data.
    RoomAccountData,
    /// `GET /profile/{userId}` — fetch a user's profile.
    Profile,
    /// `POST /user_directory/search` — search the user directory.
    UserDirectorySearch,
    /// `POST /publicRooms` — search the public-room directory.
    PublicRooms,
    /// `GET /room_keys/version` — fetch the current key backup version.
    BackupVersion,
    /// `GET /room_keys/keys/{roomId}/{sessionId}` — fetch one backed-up
    /// Megolm session.
    BackupKeys,
}

/// One HTTP call the core wants a shell to perform. The core never
/// performs the call itself — see the crate doc's "Contract" section.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OutgoingRequest {
    /// This crate's own correlation id — the shell passes it back
    /// unchanged to [`crate::MessengerError`]-surfacing calls (a later
    /// piece) alongside the response.
    pub id: RequestId,
    /// The HTTP method to use.
    pub method: HttpMethod,
    /// The request path, already percent-encoded and rooted at
    /// `/_matrix/client/v3/...` — ready to append to a homeserver base URL
    /// verbatim.
    pub path: String,
    /// Query-string parameters as `(name, value)` pairs, not yet
    /// percent-encoded (a shell's own HTTP client is expected to encode
    /// query parameters itself, the same way it encodes any other query
    /// string it builds).
    pub query: Vec<(String, String)>,
    /// The JSON request body, if this call has one.
    pub body: Option<serde_json::Value>,
    /// What kind of call this is.
    pub kind: OutgoingRequestKind,
}

/// The inline `/sync` filter every sync request carries: `room.include_leave`,
/// so a room this account left (or was kicked or banned from) arrives in
/// `rooms.leave` -- the server sends that section only when asked.
const SYNC_FILTER: &str = r#"{"room":{"include_leave":true}}"#;

impl OutgoingRequest {
    /// `GET /_matrix/client/v3/sync`. Always carries [`SYNC_FILTER`]: the
    /// server reports a room this account left, or was kicked or banned from,
    /// in `rooms.leave` only when the filter asks for it.
    pub fn sync(id: RequestId, since: Option<&str>, timeout_ms: Option<u64>) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/sync";
        let mut query = vec![("filter".to_string(), SYNC_FILTER.to_string())];
        if let Some(since) = since {
            query.push(("since".to_string(), since.to_string()));
        }
        if let Some(timeout_ms) = timeout_ms {
            query.push(("timeout".to_string(), timeout_ms.to_string()));
        }
        Self {
            id,
            method: HttpMethod::Get,
            path: PATH_TEMPLATE.to_string(),
            query,
            body: None,
            kind: OutgoingRequestKind::Sync,
        }
    }

    /// `POST /_matrix/client/v3/keys/upload`.
    pub fn keys_upload(id: RequestId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/keys/upload";
        Self {
            id,
            method: HttpMethod::Post,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::KeysUpload,
        }
    }

    /// `POST /_matrix/client/v3/keys/query`.
    pub fn keys_query(id: RequestId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/keys/query";
        Self {
            id,
            method: HttpMethod::Post,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::KeysQuery,
        }
    }

    /// `POST /_matrix/client/v3/keys/claim`.
    pub fn keys_claim(id: RequestId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/keys/claim";
        Self {
            id,
            method: HttpMethod::Post,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::KeysClaim,
        }
    }

    /// `GET /_matrix/client/v3/keys/changes`.
    pub fn keys_changes(id: RequestId, from: &str, to: &str) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/keys/changes";
        Self {
            id,
            method: HttpMethod::Get,
            path: PATH_TEMPLATE.to_string(),
            query: vec![("from".to_string(), from.to_string()), ("to".to_string(), to.to_string())],
            body: None,
            kind: OutgoingRequestKind::KeysChanges,
        }
    }

    /// `PUT /_matrix/client/v3/sendToDevice/{eventType}/{txnId}`.
    pub fn send_to_device(
        id: RequestId,
        event_type: &str,
        txn_id: &TxnId,
        body: serde_json::Value,
    ) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/sendToDevice/{event_type}/{txn_id}";
        let path = substitute(
            PATH_TEMPLATE,
            &[("{event_type}", event_type), ("{txn_id}", txn_id.as_str())],
        );
        Self {
            id,
            method: HttpMethod::Put,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::SendToDevice,
        }
    }

    /// `POST /_matrix/client/v3/keys/device_signing/upload`.
    pub fn signing_keys_upload(id: RequestId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/keys/device_signing/upload";
        Self {
            id,
            method: HttpMethod::Post,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::SigningKeysUpload,
        }
    }

    /// `POST /_matrix/client/v3/keys/signatures/upload`.
    pub fn signatures_upload(id: RequestId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/keys/signatures/upload";
        Self {
            id,
            method: HttpMethod::Post,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::SignaturesUpload,
        }
    }

    /// `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}`.
    pub fn room_send(
        id: RequestId,
        room_id: &RoomId,
        event_type: &str,
        txn_id: &TxnId,
        body: serde_json::Value,
    ) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/send/{event_type}/{txn_id}";
        let path = substitute(
            PATH_TEMPLATE,
            &[
                ("{room_id}", room_id.as_str()),
                ("{event_type}", event_type),
                ("{txn_id}", txn_id.as_str()),
            ],
        );
        Self {
            id,
            method: HttpMethod::Put,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::RoomSend,
        }
    }

    /// `PUT /_matrix/client/v3/rooms/{roomId}/redact/{eventId}/{txnId}`.
    pub fn room_redact(
        id: RequestId,
        room_id: &RoomId,
        event_id: &EventId,
        txn_id: &TxnId,
        body: serde_json::Value,
    ) -> Self {
        const PATH_TEMPLATE: &str =
            "/_matrix/client/v3/rooms/{room_id}/redact/{event_id}/{txn_id}";
        let path = substitute(
            PATH_TEMPLATE,
            &[
                ("{room_id}", room_id.as_str()),
                ("{event_id}", event_id.as_str()),
                ("{txn_id}", txn_id.as_str()),
            ],
        );
        Self {
            id,
            method: HttpMethod::Put,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::RoomRedact,
        }
    }

    /// `PUT /_matrix/client/v3/rooms/{roomId}/state/{eventType}/{stateKey}`.
    /// `state_key` may be `""` (the spec's own empty state key), which
    /// percent-encodes to an empty final path segment.
    pub fn room_state(
        id: RequestId,
        room_id: &RoomId,
        event_type: &str,
        state_key: &str,
        body: serde_json::Value,
    ) -> Self {
        const PATH_TEMPLATE: &str =
            "/_matrix/client/v3/rooms/{room_id}/state/{event_type}/{state_key}";
        let path = substitute(
            PATH_TEMPLATE,
            &[
                ("{room_id}", room_id.as_str()),
                ("{event_type}", event_type),
                ("{state_key}", state_key),
            ],
        );
        Self {
            id,
            method: HttpMethod::Put,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::RoomState,
        }
    }

    /// `GET /_matrix/client/v3/rooms/{roomId}/messages`.
    pub fn room_messages(
        id: RequestId,
        room_id: &RoomId,
        from: &str,
        dir: &str,
        limit: Option<u32>,
    ) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/messages";
        let path = substitute(PATH_TEMPLATE, &[("{room_id}", room_id.as_str())]);
        let mut query = vec![("from".to_string(), from.to_string()), ("dir".to_string(), dir.to_string())];
        if let Some(limit) = limit {
            query.push(("limit".to_string(), limit.to_string()));
        }
        Self {
            id,
            method: HttpMethod::Get,
            path,
            query,
            body: None,
            kind: OutgoingRequestKind::RoomMessages,
        }
    }

    /// Latest page, `dir=b`, no `from`. The server starts at the tip.
    /// An encrypted push carries no ciphertext, and a `/sync` token that
    /// has already moved on will not return that event again.
    pub fn room_messages_latest(id: RequestId, room_id: &RoomId, limit: u32) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/messages";
        let path = substitute(PATH_TEMPLATE, &[("{room_id}", room_id.as_str())]);
        Self {
            id,
            method: HttpMethod::Get,
            path,
            query: vec![
                ("dir".to_string(), "b".to_string()),
                ("limit".to_string(), limit.to_string()),
            ],
            body: None,
            kind: OutgoingRequestKind::RoomMessages,
        }
    }

    /// `GET /_matrix/client/v3/rooms/{roomId}/members`.
    pub fn room_members(id: RequestId, room_id: &RoomId) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/members";
        let path = substitute(PATH_TEMPLATE, &[("{room_id}", room_id.as_str())]);
        Self {
            id,
            method: HttpMethod::Get,
            path,
            query: Vec::new(),
            body: None,
            kind: OutgoingRequestKind::RoomMembers,
        }
    }

    /// `POST /_matrix/client/v3/createRoom`.
    pub fn create_room(id: RequestId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/createRoom";
        Self {
            id,
            method: HttpMethod::Post,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::CreateRoom,
        }
    }

    /// `POST /_matrix/client/v3/rooms/{roomId}/join`. This crate only ever
    /// joins by room id. It does not speak `/join/{roomIdOrAlias}`.
    pub fn join_room(id: RequestId, room_id: &str) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/join";
        let path = substitute(PATH_TEMPLATE, &[("{room_id}", room_id)]);
        Self {
            id,
            method: HttpMethod::Post,
            path,
            query: Vec::new(),
            body: None,
            kind: OutgoingRequestKind::JoinRoom,
        }
    }

    /// `POST /_matrix/client/v3/rooms/{roomId}/leave`.
    pub fn leave_room(id: RequestId, room_id: &RoomId) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/leave";
        let path = substitute(PATH_TEMPLATE, &[("{room_id}", room_id.as_str())]);
        Self {
            id,
            method: HttpMethod::Post,
            path,
            query: Vec::new(),
            body: None,
            kind: OutgoingRequestKind::LeaveRoom,
        }
    }

    /// `POST /_matrix/client/v3/rooms/{roomId}/invite`.
    pub fn invite(id: RequestId, room_id: &RoomId, user_id: &UserId) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/invite";
        let path = substitute(PATH_TEMPLATE, &[("{room_id}", room_id.as_str())]);
        Self {
            id,
            method: HttpMethod::Post,
            path,
            query: Vec::new(),
            body: Some(serde_json::json!({ "user_id": user_id.as_str() })),
            kind: OutgoingRequestKind::Invite,
        }
    }

    /// `POST /_matrix/client/v3/rooms/{roomId}/kick`.
    pub fn kick(id: RequestId, room_id: &RoomId, user_id: &UserId, reason: Option<&str>) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/kick";
        let path = substitute(PATH_TEMPLATE, &[("{room_id}", room_id.as_str())]);
        let mut body = serde_json::json!({ "user_id": user_id.as_str() });
        if let Some(reason) = reason {
            body["reason"] = serde_json::Value::String(reason.to_string());
        }
        Self {
            id,
            method: HttpMethod::Post,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::Kick,
        }
    }

    /// `PUT /_matrix/client/v3/rooms/{roomId}/typing/{userId}`.
    pub fn typing(
        id: RequestId,
        room_id: &RoomId,
        user_id: &UserId,
        typing: bool,
        timeout_ms: Option<u64>,
    ) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/typing/{user_id}";
        let path = substitute(
            PATH_TEMPLATE,
            &[("{room_id}", room_id.as_str()), ("{user_id}", user_id.as_str())],
        );
        let mut body = serde_json::json!({ "typing": typing });
        if let Some(timeout_ms) = timeout_ms {
            body["timeout"] = serde_json::Value::from(timeout_ms);
        }
        Self {
            id,
            method: HttpMethod::Put,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::Typing,
        }
    }

    /// `POST /_matrix/client/v3/rooms/{roomId}/receipt/{receiptType}/{eventId}`.
    pub fn receipt(id: RequestId, room_id: &RoomId, receipt_type: &str, event_id: &EventId) -> Self {
        const PATH_TEMPLATE: &str =
            "/_matrix/client/v3/rooms/{room_id}/receipt/{receipt_type}/{event_id}";
        let path = substitute(
            PATH_TEMPLATE,
            &[
                ("{room_id}", room_id.as_str()),
                ("{receipt_type}", receipt_type),
                ("{event_id}", event_id.as_str()),
            ],
        );
        Self {
            id,
            method: HttpMethod::Post,
            path,
            query: Vec::new(),
            body: Some(serde_json::json!({})),
            kind: OutgoingRequestKind::Receipt,
        }
    }

    /// `POST /_matrix/client/v3/rooms/{roomId}/read_markers`.
    pub fn read_markers(id: RequestId, room_id: &RoomId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/rooms/{room_id}/read_markers";
        let path = substitute(PATH_TEMPLATE, &[("{room_id}", room_id.as_str())]);
        Self {
            id,
            method: HttpMethod::Post,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::ReadMarkers,
        }
    }

    /// `PUT /_matrix/client/v3/user/{userId}/account_data/{type}`.
    pub fn account_data(
        id: RequestId,
        user_id: &UserId,
        event_type: &str,
        body: serde_json::Value,
    ) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/user/{user_id}/account_data/{event_type}";
        let path = substitute(
            PATH_TEMPLATE,
            &[("{user_id}", user_id.as_str()), ("{event_type}", event_type)],
        );
        Self {
            id,
            method: HttpMethod::Put,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::AccountData,
        }
    }

    /// `PUT /_matrix/client/v3/user/{userId}/rooms/{roomId}/account_data/{type}`.
    pub fn room_account_data(
        id: RequestId,
        user_id: &UserId,
        room_id: &RoomId,
        event_type: &str,
        body: serde_json::Value,
    ) -> Self {
        const PATH_TEMPLATE: &str =
            "/_matrix/client/v3/user/{user_id}/rooms/{room_id}/account_data/{event_type}";
        let path = substitute(
            PATH_TEMPLATE,
            &[
                ("{user_id}", user_id.as_str()),
                ("{room_id}", room_id.as_str()),
                ("{event_type}", event_type),
            ],
        );
        Self {
            id,
            method: HttpMethod::Put,
            path,
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::RoomAccountData,
        }
    }

    /// `GET /_matrix/client/v3/profile/{userId}`.
    pub fn profile(id: RequestId, user_id: &UserId) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/profile/{user_id}";
        let path = substitute(PATH_TEMPLATE, &[("{user_id}", user_id.as_str())]);
        Self {
            id,
            method: HttpMethod::Get,
            path,
            query: Vec::new(),
            body: None,
            kind: OutgoingRequestKind::Profile,
        }
    }

    /// `POST /_matrix/client/v3/user_directory/search`.
    pub fn user_directory_search(id: RequestId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/user_directory/search";
        Self {
            id,
            method: HttpMethod::Post,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::UserDirectorySearch,
        }
    }

    /// `POST /_matrix/client/v3/publicRooms`.
    pub fn public_rooms(id: RequestId, body: serde_json::Value) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/publicRooms";
        Self {
            id,
            method: HttpMethod::Post,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: Some(body),
            kind: OutgoingRequestKind::PublicRooms,
        }
    }

    /// `GET /_matrix/client/v3/room_keys/version` — the current backup
    /// version. Creating/updating a version is a different endpoint,
    /// deferred to whichever piece implements key backup (plan §5, M9).
    pub fn backup_version(id: RequestId) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/room_keys/version";
        Self {
            id,
            method: HttpMethod::Get,
            path: PATH_TEMPLATE.to_string(),
            query: Vec::new(),
            body: None,
            kind: OutgoingRequestKind::BackupVersion,
        }
    }

    /// `GET /_matrix/client/v3/room_keys/keys/{roomId}/{sessionId}` — the
    /// single-session lookup shape the plan's §4.3 UTD-recovery walkthrough
    /// uses. The bulk (`/room_keys/keys`) and per-room
    /// (`/room_keys/keys/{roomId}`) variants are deferred to M9, which owns
    /// key backup end to end (plan §6.8: exact backup paths/queries are
    /// still open pending the sibling server plan).
    pub fn backup_keys(id: RequestId, room_id: &RoomId, session_id: &str, version: &str) -> Self {
        const PATH_TEMPLATE: &str = "/_matrix/client/v3/room_keys/keys/{room_id}/{session_id}";
        let path = substitute(
            PATH_TEMPLATE,
            &[("{room_id}", room_id.as_str()), ("{session_id}", session_id)],
        );
        Self {
            id,
            method: HttpMethod::Get,
            path,
            query: vec![("version".to_string(), version.to_string())],
            body: None,
            kind: OutgoingRequestKind::BackupKeys,
        }
    }
}

/// One HTTP response a shell hands back for a prior [`OutgoingRequest`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HttpResponseDescriptor {
    /// The HTTP status code.
    pub status: u16,
    /// The raw response body bytes.
    pub body: Vec<u8>,
}

impl HttpResponseDescriptor {
    /// Parses `body` as a Matrix-shaped error response
    /// (`{"errcode": "...", "error": "..."}`), returning
    /// `(errcode, error)` if the body is JSON and carries an `errcode`
    /// string field. `error` defaults to `""` if absent (the spec makes it
    /// optional). Returns `None` for a non-JSON body or a JSON body with
    /// no `errcode` field, regardless of `status` — callers that only want
    /// this on failure responses should check `status` themselves first.
    pub fn matrix_error(&self) -> Option<(String, String)> {
        let value: serde_json::Value = serde_json::from_slice(&self.body).ok()?;
        let errcode = value.get("errcode")?.as_str()?.to_string();
        let error = value
            .get("error")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        Some((errcode, error))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn id() -> RequestId {
        RequestId::next(0)
    }

    #[test]
    fn percent_encode_segment_escapes_matrix_sigils() {
        assert_eq!(percent_encode_segment("!abc:example.org"), "%21abc%3Aexample.org");
        assert_eq!(percent_encode_segment("safe-._~123"), "safe-._~123");
    }

    #[test]
    fn percent_decode_segment_reverses_percent_encode_segment() {
        for raw in ["!abc:example.org", "safe-._~123", "curve/25519+key=", ""] {
            let encoded = percent_encode_segment(raw);
            assert_eq!(percent_decode_segment(&encoded).as_deref(), Some(raw));
        }
    }

    #[test]
    fn percent_decode_segment_rejects_a_malformed_escape() {
        assert_eq!(percent_decode_segment("%2"), None);
        assert_eq!(percent_decode_segment("%zz"), None);
    }

    #[test]
    fn room_send_percent_encodes_the_room_id_in_the_path() {
        let room_id = RoomId::parse("!abc:example.org").expect("valid room id");
        let txn_id = TxnId::new(0);
        let req = OutgoingRequest::room_send(
            id(),
            &room_id,
            "m.room.message",
            &txn_id,
            serde_json::json!({ "body": "hi" }),
        );
        assert_eq!(
            req.path,
            format!(
                "/_matrix/client/v3/rooms/%21abc%3Aexample.org/send/m.room.message/{}",
                txn_id.as_str()
            )
        );
        assert_eq!(req.method, HttpMethod::Put);
        assert_eq!(req.kind, OutgoingRequestKind::RoomSend);
    }

    #[test]
    fn send_to_device_percent_encodes_the_txn_id_in_the_path() {
        let txn_id = TxnId::new(0);
        let req = OutgoingRequest::send_to_device(
            id(),
            "m.room.encrypted",
            &txn_id,
            serde_json::json!({ "messages": {} }),
        );
        assert!(req.path.starts_with("/_matrix/client/v3/sendToDevice/m.room.encrypted/"));
        assert!(!req.path.contains(':'), "txn id's own characters carry no raw ':'");
    }

    #[test]
    fn sync_carries_since_and_timeout_as_query_params_only_when_present() {
        let filter = ("filter".to_string(), SYNC_FILTER.to_string());
        let bare = OutgoingRequest::sync(id(), None, None);
        assert_eq!(bare.query, vec![filter.clone()]);

        let full = OutgoingRequest::sync(id(), Some("s123"), Some(30_000));
        assert_eq!(
            full.query,
            vec![filter, ("since".to_string(), "s123".to_string()), ("timeout".to_string(), "30000".to_string())]
        );
    }

    #[test]
    fn sync_filter_asks_for_left_rooms() {
        let parsed: serde_json::Value = serde_json::from_str(SYNC_FILTER).expect("the filter is JSON");
        assert_eq!(parsed["room"]["include_leave"], serde_json::Value::Bool(true));
    }

    #[test]
    fn outgoing_request_kind_round_trips_serde() {
        for kind in [
            OutgoingRequestKind::Sync,
            OutgoingRequestKind::KeysUpload,
            OutgoingRequestKind::RoomSend,
            OutgoingRequestKind::BackupKeys,
        ] {
            let json = serde_json::to_string(&kind).expect("serialize");
            let back: OutgoingRequestKind = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(back, kind);
        }
    }

    #[test]
    fn outgoing_request_round_trips_serde() {
        let room_id = RoomId::parse("!abc:example.org").expect("valid room id");
        let req = OutgoingRequest::room_members(id(), &room_id);
        let json = serde_json::to_string(&req).expect("serialize");
        let back: OutgoingRequest = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, req);
    }

    #[test]
    fn matrix_error_parses_errcode_and_error() {
        let resp = HttpResponseDescriptor {
            status: 403,
            body: br#"{"errcode":"M_FORBIDDEN","error":"Guest access is forbidden"}"#.to_vec(),
        };
        assert_eq!(
            resp.matrix_error(),
            Some(("M_FORBIDDEN".to_string(), "Guest access is forbidden".to_string()))
        );
    }

    #[test]
    fn matrix_error_defaults_a_missing_error_field_to_empty() {
        let resp = HttpResponseDescriptor {
            status: 429,
            body: br#"{"errcode":"M_LIMIT_EXCEEDED"}"#.to_vec(),
        };
        assert_eq!(resp.matrix_error(), Some(("M_LIMIT_EXCEEDED".to_string(), String::new())));
    }

    #[test]
    fn matrix_error_is_none_for_a_non_json_body() {
        let resp = HttpResponseDescriptor { status: 200, body: b"not json".to_vec() };
        assert_eq!(resp.matrix_error(), None);
    }

    #[test]
    fn matrix_error_is_none_when_errcode_is_absent() {
        let resp = HttpResponseDescriptor {
            status: 200,
            body: br#"{"next_batch":"s1"}"#.to_vec(),
        };
        assert_eq!(resp.matrix_error(), None);
    }
}