anyclaw-sdk-types 0.6.1

Shared types for the anyclaw agent-channel-tool SDK
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
use serde::{Deserialize, Serialize};

/// Channel capabilities advertised during initialize handshake.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChannelCapabilities {
    /// Whether the channel supports streaming (chunked) delivery.
    pub streaming: bool,
    /// Whether the channel supports rich text (Markdown, HTML).
    pub rich_text: bool,
}

/// Initialize handshake — anyclaw sends to channel subprocess.
// Extensible: channel-specific options have channel-defined schemas (D-03)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChannelInitializeParams {
    /// ACP protocol version for compatibility negotiation.
    pub protocol_version: u32,
    /// Unique identifier for this channel instance.
    pub channel_id: String,
    /// Optional ack configuration for reactions and typing indicators.
    #[serde(default)]
    pub ack: Option<ChannelAckConfig>,
    /// Channel-specific configuration from `anyclaw.yaml` `options` section.
    #[serde(default)]
    pub options: std::collections::HashMap<String, serde_json::Value>,
}

/// Initialize handshake — channel subprocess responds.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChannelInitializeResult {
    /// ACP protocol version the channel supports.
    pub protocol_version: u32,
    /// Capabilities the channel advertises.
    pub capabilities: ChannelCapabilities,
    /// Default option values reported by the extension.
    /// The manager merges these into the channel's options at startup (user-provided values win).
    /// D-03: extension defaults are arbitrary key-value maps defined by each channel.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub defaults: Option<std::collections::HashMap<String, serde_json::Value>>,
}

/// Anyclaw → Channel: deliver agent message/streaming update.
// Pass-through: agents manager mutates raw JSON (timestamps, normalization, command injection)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeliverMessage {
    /// ACP session that produced this content.
    pub session_id: String,
    /// Agent content payload (streaming update, result, thought, etc.).
    pub content: serde_json::Value,
}

/// Peer identity information for inbound messages.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PeerInfo {
    /// Name of the originating channel (e.g., `"telegram"`, `"debug-http"`).
    pub channel_name: String,
    /// Opaque identifier for the peer within the channel.
    pub peer_id: String,
    /// Conversation kind (e.g., `"direct"`, `"group"`, `"local"`).
    pub kind: String,
}

/// Channel → Anyclaw: user sent a message.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChannelSendMessage {
    /// Identity of the user who sent the message.
    pub peer_info: PeerInfo,
    /// User message text content.
    pub content: String,
}

/// Helper for channel implementations to extract thought content from DeliverMessage.
/// When DeliverMessage.content has type "agent_thought_chunk", channels can use this
/// to deserialize the thought payload.
///
/// # Example
/// ```
/// use anyclaw_sdk_types::channel::ThoughtContent;
/// let content = serde_json::json!({
///     "sessionId": "s1",
///     "type": "agent_thought_chunk",
///     "content": "thinking..."
/// });
/// if let Some(thought) = ThoughtContent::from_content(&content) {
///     assert_eq!(thought.content, "thinking...");
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ThoughtContent {
    /// ACP session that produced the thought.
    pub session_id: String,
    /// Content type discriminator (always `"agent_thought_chunk"`).
    #[serde(rename = "type")]
    pub update_type: String,
    /// The thought text content.
    pub content: String,
}

impl ThoughtContent {
    /// Try to extract thought content from a DeliverMessage content value.
    /// Returns Some if the content type is "agent_thought_chunk", None otherwise.
    pub fn from_content(content: &serde_json::Value) -> Option<Self> {
        let update_type = content.get("type")?.as_str()?;
        if update_type == "agent_thought_chunk" {
            serde_json::from_value(content.clone()).ok()
        } else {
            None
        }
    }
}

/// Typed dispatch over all content update types in a `DeliverMessage`.
///
/// Channels receive `DeliverMessage` with a JSON `content` field. Instead of
/// matching raw `content["update"]["sessionUpdate"]` strings, use
/// `ContentKind::from_content(&msg.content)` for typed dispatch.
///
/// # Example
/// ```
/// use anyclaw_sdk_types::channel::ContentKind;
/// let content = serde_json::json!({
///     "update": {
///         "sessionUpdate": "agent_message_chunk",
///         "content": "hello"
///     }
/// });
/// match ContentKind::from_content(&content) {
///     ContentKind::MessageChunk { text } => assert_eq!(text, "hello"),
///     _ => panic!("expected MessageChunk"),
/// }
/// ```
// ContentKind dispatches over raw DeliverMessage.content (Value pass-through)
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ContentKind {
    /// Agent thinking/reasoning content.
    Thought(ThoughtContent),
    /// Streaming chunk of agent response text.
    MessageChunk {
        /// The chunk text.
        text: String,
    },
    /// Final result text from the agent.
    Result {
        /// The result text.
        text: String,
        /// Whether the result represents an error.
        is_error: bool,
    },
    /// Echo of user message chunk (for display).
    UserMessageChunk {
        /// The echoed user text.
        text: String,
    },
    /// Token usage update notification (no content fields).
    UsageUpdate,
    /// Agent invoked a tool.
    ToolCall {
        /// Tool name being called.
        name: String,
        /// Unique identifier for this tool invocation.
        tool_call_id: String,
        /// Tool input arguments, if any.
        // Extensible: tool input schema is tool-defined (D-03)
        input: Option<serde_json::Value>,
    },
    /// Progress/completion update for a tool call.
    ToolCallUpdate {
        /// Tool name.
        name: String,
        /// Unique identifier for this tool invocation.
        tool_call_id: String,
        /// Status string: `"in_progress"`, `"completed"`, or `"failed"`.
        status: String,
        /// Tool output text, if any.
        output: Option<String>,
        /// Tool input arguments, if any.
        input: Option<serde_json::Value>,
        /// Process exit code from `rawOutput.metadata.exit`, if present.
        exit_code: Option<i64>,
    },
    /// Agent-provided list of available commands (e.g., for Telegram / menu).
    AvailableCommandsUpdate {
        /// The commands payload from the agent (array of command objects).
        // Extensible: command descriptors have agent-defined schemas (D-03)
        commands: serde_json::Value,
    },
    /// Unrecognized content type.
    Unknown,
}

impl ContentKind {
    /// Classify a `DeliverMessage.content` value into a typed variant.
    ///
    /// Reads `content["update"]["sessionUpdate"]` as the type discriminator
    /// (the actual wire format both channels use).
    pub fn from_content(content: &serde_json::Value) -> Self {
        let Some(update) = content.get("update") else {
            return ContentKind::Unknown;
        };
        let Some(session_update) = update.get("sessionUpdate").and_then(|v| v.as_str()) else {
            return ContentKind::Unknown;
        };
        match session_update {
            "agent_thought_chunk" => {
                let text = extract_content_text(update);
                ContentKind::Thought(ThoughtContent {
                    session_id: String::new(),
                    update_type: "agent_thought_chunk".into(),
                    content: text,
                })
            }
            "agent_message_chunk" => ContentKind::MessageChunk {
                text: extract_content_text(update),
            },
            "result" => ContentKind::Result {
                text: extract_content_text(update),
                is_error: update
                    .get("isError")
                    .and_then(serde_json::Value::as_bool)
                    .unwrap_or(false),
            },
            "user_message_chunk" => ContentKind::UserMessageChunk {
                text: extract_content_text(update),
            },
            "usage_update" => ContentKind::UsageUpdate,
            "tool_call" => {
                let tool_call_id = update
                    .get("toolCallId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let name = update
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let input = update.get("input").cloned();
                ContentKind::ToolCall {
                    name,
                    tool_call_id,
                    input,
                }
            }
            "tool_call_update" => {
                let tool_call_id = update
                    .get("toolCallId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let name = update
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let status = update
                    .get("status")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let output = update
                    .get("output")
                    .and_then(|v| v.as_str())
                    .map(std::string::ToString::to_string);
                let input = update.get("input").cloned();
                let exit_code = update
                    .get("rawOutput")
                    .and_then(|r| r.get("metadata"))
                    .and_then(|m| m.get("exit"))
                    .and_then(serde_json::Value::as_i64);
                ContentKind::ToolCallUpdate {
                    name,
                    tool_call_id,
                    status,
                    output,
                    input,
                    exit_code,
                }
            }
            "available_commands_update" => ContentKind::AvailableCommandsUpdate {
                commands: update
                    .get("availableCommands")
                    .cloned()
                    .unwrap_or(serde_json::Value::Array(vec![])),
            },
            _ => ContentKind::Unknown,
        }
    }
}

/// Extract displayable text from `update["content"]`.
/// Handles content-part object format `{type, text}`,
/// plain string values, and falls back to empty string.
fn extract_content_text(update: &serde_json::Value) -> String {
    match update.get("content") {
        Some(c) => {
            if let Some(text) = c.get("text").and_then(|t| t.as_str()) {
                return text.to_string();
            }
            if let Some(s) = c.as_str() {
                return s.to_string();
            }
            String::new()
        }
        None => String::new(),
    }
}

/// Anyclaw → Channel: acknowledge message receipt.
/// Channel uses this to add emoji reaction and/or show typing indicator.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AckNotification {
    /// ACP session the ack relates to.
    pub session_id: String,
    /// Channel that should display the ack.
    pub channel_name: String,
    /// Peer whose message triggered the ack.
    pub peer_id: String,
    /// Platform-specific message ID, if available.
    pub message_id: Option<String>,
}

/// Anyclaw → Channel: ack lifecycle event.
/// Channel uses this to remove/replace reaction based on its ack config.
///
/// Actions:
/// - `"response_started"` — agent began streaming a response
/// - `"response_completed"` — agent finished responding (session idle)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AckLifecycleNotification {
    /// ACP session the lifecycle event relates to.
    pub session_id: String,
    /// Lifecycle action: `"response_started"` or `"response_completed"`.
    pub action: String,
    /// Why the agent stopped, if this is a completion event.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<crate::acp::StopReason>,
}

/// Ack configuration passed to channels via initialize handshake.
/// Lightweight mirror of config crate's AckConfig — SDK types must not depend on config.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChannelAckConfig {
    /// Whether to add emoji reactions on message receipt.
    pub reaction: bool,
    /// Whether to show typing indicators while processing.
    pub typing: bool,
    /// Emoji to use for the ack reaction (e.g., `"👀"`).
    pub reaction_emoji: String,
    /// How to handle the reaction when response starts (e.g., `"remove"`).
    pub reaction_lifecycle: String,
}

/// Channel → Anyclaw: user responded to permission prompt.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChannelRespondPermission {
    /// Identifier matching the originating permission request.
    pub request_id: String,
    /// The option the user selected.
    pub option_id: String,
}

/// Anyclaw → Channel: notify channel that a session was created for a peer.
/// Channels can use this to map ACP session IDs back to their internal identifiers
/// (e.g., Telegram chat IDs).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SessionCreated {
    /// Newly created ACP session identifier.
    pub session_id: String,
    /// Peer whose message triggered session creation.
    pub peer_info: PeerInfo,
}

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

    #[test]
    fn when_serializing_channel_capabilities_then_uses_camel_case() {
        let caps = ChannelCapabilities {
            streaming: true,
            rich_text: false,
        };
        let json = serde_json::to_value(&caps).unwrap();
        assert_eq!(json["streaming"], true);
        assert_eq!(json["richText"], false);
        assert!(json.get("rich_text").is_none());
        let deser: ChannelCapabilities = serde_json::from_value(json).unwrap();
        assert_eq!(deser, caps);
    }

    #[test]
    fn when_serializing_peer_info_then_uses_camel_case() {
        let info = PeerInfo {
            channel_name: "debug-http".into(),
            peer_id: "local:dev".into(),
            kind: "local".into(),
        };
        let json = serde_json::to_value(&info).unwrap();
        assert_eq!(json["channelName"], "debug-http");
        assert_eq!(json["peerId"], "local:dev");
        assert!(json.get("channel_name").is_none());
        let deser: PeerInfo = serde_json::from_value(json).unwrap();
        assert_eq!(deser, info);
    }

    #[test]
    fn when_serializing_deliver_message_then_uses_camel_case() {
        let msg = DeliverMessage {
            session_id: "sess-1".into(),
            content: serde_json::json!({"text": "hello"}),
        };
        let json = serde_json::to_value(&msg).unwrap();
        assert_eq!(json["sessionId"], "sess-1");
        assert!(json.get("session_id").is_none());
        let deser: DeliverMessage = serde_json::from_value(json).unwrap();
        assert_eq!(deser, msg);
    }

    #[test]
    fn when_serializing_channel_send_message_then_uses_camel_case() {
        let msg = ChannelSendMessage {
            peer_info: PeerInfo {
                channel_name: "debug-http".into(),
                peer_id: "local:dev".into(),
                kind: "local".into(),
            },
            content: "hello agent".into(),
        };
        let json = serde_json::to_value(&msg).unwrap();
        assert_eq!(json["peerInfo"]["channelName"], "debug-http");
        assert_eq!(json["content"], "hello agent");
        let deser: ChannelSendMessage = serde_json::from_value(json).unwrap();
        assert_eq!(deser, msg);
    }

    #[test]
    fn when_serializing_channel_respond_permission_then_uses_camel_case() {
        let resp = ChannelRespondPermission {
            request_id: "req-1".into(),
            option_id: "allow".into(),
        };
        let json = serde_json::to_value(&resp).unwrap();
        assert_eq!(json["requestId"], "req-1");
        assert_eq!(json["optionId"], "allow");
        assert!(json.get("request_id").is_none());
        let deser: ChannelRespondPermission = serde_json::from_value(json).unwrap();
        assert_eq!(deser, resp);
    }

    #[test]
    fn when_serializing_channel_initialize_params_then_uses_camel_case() {
        let params = ChannelInitializeParams {
            protocol_version: 1,
            channel_id: "ch-1".into(),
            ack: None,
            options: std::collections::HashMap::new(),
        };
        let json = serde_json::to_value(&params).unwrap();
        assert_eq!(json["protocolVersion"], 1);
        assert_eq!(json["channelId"], "ch-1");
        let deser: ChannelInitializeParams = serde_json::from_value(json).unwrap();
        assert_eq!(deser, params);
    }

    #[test]
    fn when_content_type_is_agent_thought_chunk_then_extracts_thought() {
        let content = serde_json::json!({
            "sessionId": "s1",
            "type": "agent_thought_chunk",
            "content": "Analyzing..."
        });
        let thought = ThoughtContent::from_content(&content).unwrap();
        assert_eq!(thought.session_id, "s1");
        assert_eq!(thought.update_type, "agent_thought_chunk");
        assert_eq!(thought.content, "Analyzing...");
    }

    #[test]
    fn when_content_type_is_not_agent_thought_chunk_then_returns_none() {
        let content = serde_json::json!({
            "sessionId": "s1",
            "type": "agent_message_chunk",
            "content": "Hello"
        });
        assert!(ThoughtContent::from_content(&content).is_none());
    }

    #[test]
    fn when_serializing_thought_content_then_uses_camel_case() {
        let thought = ThoughtContent {
            session_id: "s1".into(),
            update_type: "agent_thought_chunk".into(),
            content: "Thinking...".into(),
        };
        let json = serde_json::to_value(&thought).unwrap();
        assert_eq!(json["sessionId"], "s1");
        assert_eq!(json["type"], "agent_thought_chunk");
        let deser: ThoughtContent = serde_json::from_value(json).unwrap();
        assert_eq!(deser, thought);
    }

    #[test]
    fn when_deliver_message_content_is_thought_then_extracts_thought() {
        let msg = DeliverMessage {
            session_id: "sess-1".into(),
            content: serde_json::json!({
                "sessionId": "sess-1",
                "type": "agent_thought_chunk",
                "content": "deep thought"
            }),
        };
        let thought = ThoughtContent::from_content(&msg.content).unwrap();
        assert_eq!(thought.content, "deep thought");
    }

    #[test]
    fn when_serializing_channel_initialize_result_then_uses_camel_case() {
        let result = ChannelInitializeResult {
            protocol_version: 1,
            capabilities: ChannelCapabilities {
                streaming: true,
                rich_text: false,
            },
            defaults: None,
        };
        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(json["protocolVersion"], 1);
        assert_eq!(json["capabilities"]["streaming"], true);
        let deser: ChannelInitializeResult = serde_json::from_value(json).unwrap();
        assert_eq!(deser, result);
    }

    #[test]
    fn when_serializing_ack_notification_then_uses_camel_case() {
        let ack = AckNotification {
            session_id: "sess-1".into(),
            channel_name: "telegram".into(),
            peer_id: "telegram:12345".into(),
            message_id: Some("msg-42".into()),
        };
        let json = serde_json::to_value(&ack).unwrap();
        assert_eq!(json["sessionId"], "sess-1");
        assert_eq!(json["channelName"], "telegram");
        assert_eq!(json["peerId"], "telegram:12345");
        assert_eq!(json["messageId"], "msg-42");
        assert!(json.get("session_id").is_none());
        let deser: AckNotification = serde_json::from_value(json).unwrap();
        assert_eq!(deser, ack);
    }

    #[test]
    fn when_ack_notification_has_no_message_id_then_field_is_null() {
        let ack = AckNotification {
            session_id: "sess-1".into(),
            channel_name: "debug-http".into(),
            peer_id: "local".into(),
            message_id: None,
        };
        let json = serde_json::to_value(&ack).unwrap();
        assert!(json["messageId"].is_null());
        let deser: AckNotification = serde_json::from_value(json).unwrap();
        assert_eq!(deser.message_id, None);
    }

    #[test]
    fn when_serializing_ack_lifecycle_notification_then_uses_camel_case() {
        let lifecycle = AckLifecycleNotification {
            session_id: "sess-1".into(),
            action: "response_started".into(),
            stop_reason: None,
        };
        let json = serde_json::to_value(&lifecycle).unwrap();
        assert_eq!(json["sessionId"], "sess-1");
        assert_eq!(json["action"], "response_started");
        let deser: AckLifecycleNotification = serde_json::from_value(json).unwrap();
        assert_eq!(deser, lifecycle);
    }

    #[test]
    fn when_serializing_channel_ack_config_then_uses_camel_case() {
        let cfg = ChannelAckConfig {
            reaction: true,
            typing: true,
            reaction_emoji: "👀".into(),
            reaction_lifecycle: "remove".into(),
        };
        let json = serde_json::to_value(&cfg).unwrap();
        assert_eq!(json["reaction"], true);
        assert_eq!(json["typing"], true);
        assert_eq!(json["reactionEmoji"], "👀");
        assert_eq!(json["reactionLifecycle"], "remove");
        assert!(json.get("reaction_emoji").is_none());
        let deser: ChannelAckConfig = serde_json::from_value(json).unwrap();
        assert_eq!(deser, cfg);
    }

    #[test]
    fn when_channel_initialize_params_has_ack_then_ack_serialized_nested() {
        let params = ChannelInitializeParams {
            protocol_version: 1,
            channel_id: "telegram".into(),
            ack: Some(ChannelAckConfig {
                reaction: true,
                typing: true,
                reaction_emoji: "👀".into(),
                reaction_lifecycle: "remove".into(),
            }),
            options: std::collections::HashMap::new(),
        };
        let json = serde_json::to_value(&params).unwrap();
        assert_eq!(json["ack"]["reaction"], true);
        assert_eq!(json["ack"]["reactionEmoji"], "👀");
        let deser: ChannelInitializeParams = serde_json::from_value(json).unwrap();
        assert_eq!(deser, params);
    }

    #[test]
    fn when_channel_initialize_params_has_no_ack_field_then_ack_is_none() {
        let json = serde_json::json!({
            "protocolVersion": 1,
            "channelId": "debug-http"
        });
        let deser: ChannelInitializeParams = serde_json::from_value(json).unwrap();
        assert_eq!(deser.ack, None);
    }

    #[rstest]
    fn when_content_is_thought_chunk_then_returns_thought() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "agent_thought_chunk",
                "content": "analyzing the problem..."
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::Thought(t) => assert_eq!(t.content, "analyzing the problem..."),
            other => panic!("expected Thought, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_is_message_chunk_then_returns_message_chunk() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "agent_message_chunk",
                "content": "hello world"
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::MessageChunk { text } => assert_eq!(text, "hello world"),
            other => panic!("expected MessageChunk, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_is_result_then_returns_result() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "result",
                "content": "done"
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::Result { text, .. } => assert_eq!(text, "done"),
            other => panic!("expected Result, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_is_usage_update_then_returns_usage_update() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "usage_update",
                "content": {}
            }
        });
        let kind = ContentKind::from_content(&content);
        assert_eq!(kind, ContentKind::UsageUpdate);
    }

    #[rstest]
    fn when_content_is_user_message_chunk_then_returns_user_message_chunk() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "user_message_chunk",
                "content": "user said this"
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::UserMessageChunk { text } => assert_eq!(text, "user said this"),
            other => panic!("expected UserMessageChunk, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_has_unknown_update_type_then_returns_unknown() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "some_future_type",
                "content": "whatever"
            }
        });
        assert_eq!(ContentKind::from_content(&content), ContentKind::Unknown);
    }

    #[rstest]
    fn when_content_has_no_update_key_then_returns_unknown() {
        let content = serde_json::json!({"text": "plain message"});
        assert_eq!(ContentKind::from_content(&content), ContentKind::Unknown);
    }

    #[rstest]
    fn when_content_is_tool_call_then_returns_tool_call() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "tool_call",
                "toolCallId": "tc-1",
                "name": "read_file",
                "input": {"path": "/tmp/foo.txt"}
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::ToolCall {
                name,
                tool_call_id,
                input,
            } => {
                assert_eq!(name, "read_file");
                assert_eq!(tool_call_id, "tc-1");
                assert!(input.is_some());
            }
            other => panic!("expected ToolCall, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_is_tool_call_without_optional_fields_then_returns_tool_call_with_defaults() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "tool_call"
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::ToolCall {
                name,
                tool_call_id,
                input,
            } => {
                assert_eq!(name, "");
                assert_eq!(tool_call_id, "");
                assert!(input.is_none());
            }
            other => panic!("expected ToolCall, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_is_tool_call_update_then_returns_tool_call_update() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "tool_call_update",
                "toolCallId": "tc-1",
                "name": "read_file",
                "status": "completed",
                "output": "file contents here"
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::ToolCallUpdate {
                name,
                tool_call_id,
                status,
                output,
                ..
            } => {
                assert_eq!(name, "read_file");
                assert_eq!(tool_call_id, "tc-1");
                assert_eq!(status, "completed");
                assert_eq!(output.as_deref(), Some("file contents here"));
            }
            other => panic!("expected ToolCallUpdate, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_is_tool_call_update_without_optional_fields_then_returns_defaults() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "tool_call_update",
                "toolCallId": "tc-2"
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::ToolCallUpdate {
                name,
                tool_call_id,
                status,
                output,
                exit_code,
                ..
            } => {
                assert_eq!(tool_call_id, "tc-2");
                assert_eq!(name, "");
                assert_eq!(status, "");
                assert!(output.is_none());
                assert!(exit_code.is_none());
            }
            other => panic!("expected ToolCallUpdate, got {:?}", other),
        }
    }

    #[rstest]
    fn when_tool_call_update_has_nonzero_exit_then_exit_code_extracted() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "tool_call_update",
                "toolCallId": "tc-3",
                "name": "bash",
                "status": "completed",
                "rawOutput": { "metadata": { "exit": 1 } }
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::ToolCallUpdate {
                exit_code, status, ..
            } => {
                assert_eq!(status, "completed");
                assert_eq!(exit_code, Some(1));
            }
            other => panic!("expected ToolCallUpdate, got {:?}", other),
        }
    }

    #[rstest]
    fn when_tool_call_update_has_zero_exit_then_exit_code_is_zero() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "tool_call_update",
                "toolCallId": "tc-4",
                "status": "completed",
                "rawOutput": { "metadata": { "exit": 0 } }
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::ToolCallUpdate { exit_code, .. } => {
                assert_eq!(exit_code, Some(0));
            }
            other => panic!("expected ToolCallUpdate, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_is_thought_with_opencode_wrapper_then_extracts_text() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "agent_thought_chunk",
                "content": {"type": "text", "text": "wrapped thought"}
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::Thought(t) => assert_eq!(t.content, "wrapped thought"),
            other => panic!("expected Thought, got {:?}", other),
        }
    }

    #[test]
    fn when_session_created_serialized_then_uses_camel_case() {
        let sc = SessionCreated {
            session_id: "acp-sess-42".into(),
            peer_info: PeerInfo {
                channel_name: "telegram".into(),
                peer_id: "tg:99999".into(),
                kind: "user".into(),
            },
        };
        let json = serde_json::to_value(&sc).unwrap();
        assert_eq!(json["sessionId"], "acp-sess-42");
        assert!(json.get("session_id").is_none());
        assert_eq!(json["peerInfo"]["channelName"], "telegram");
        assert_eq!(json["peerInfo"]["peerId"], "tg:99999");
        assert!(json.get("peer_info").is_none());
        let deser: SessionCreated = serde_json::from_value(json).unwrap();
        assert_eq!(deser, sc);
    }

    #[rstest]
    fn when_content_has_available_commands_update_then_content_kind_is_available_commands_update() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "available_commands_update",
                "availableCommands": [{"name": "start", "description": "Start the bot"}]
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::AvailableCommandsUpdate { commands } => {
                assert!(commands.is_array());
                assert_eq!(commands.as_array().unwrap().len(), 1);
            }
            other => panic!("expected AvailableCommandsUpdate, got {:?}", other),
        }
    }

    #[rstest]
    fn when_content_has_available_commands_update_without_commands_then_defaults_to_empty_array() {
        let content = serde_json::json!({
            "update": {
                "sessionUpdate": "available_commands_update"
            }
        });
        let kind = ContentKind::from_content(&content);
        match kind {
            ContentKind::AvailableCommandsUpdate { commands } => {
                assert_eq!(commands, serde_json::Value::Array(vec![]));
            }
            other => panic!("expected AvailableCommandsUpdate, got {:?}", other),
        }
    }

    // ── Round-trip serde tests (04-02 Task 1) ──────────────────────────

    #[rstest]
    fn when_channel_capabilities_round_trips_then_identical() {
        let original = ChannelCapabilities {
            streaming: true,
            rich_text: false,
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ChannelCapabilities = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_channel_initialize_params_round_trips_then_identical() {
        let mut opts = std::collections::HashMap::new();
        opts.insert("token".into(), serde_json::json!("abc123"));
        let original = ChannelInitializeParams {
            protocol_version: 1,
            channel_id: "telegram".into(),
            ack: Some(ChannelAckConfig {
                reaction: true,
                typing: false,
                reaction_emoji: "👀".into(),
                reaction_lifecycle: "remove".into(),
            }),
            options: opts,
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ChannelInitializeParams = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_channel_initialize_params_empty_options_round_trips_then_identical() {
        let original = ChannelInitializeParams {
            protocol_version: 1,
            channel_id: "debug-http".into(),
            ack: None,
            options: std::collections::HashMap::new(),
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ChannelInitializeParams = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_channel_initialize_result_round_trips_then_identical() {
        let original = ChannelInitializeResult {
            protocol_version: 1,
            capabilities: ChannelCapabilities {
                streaming: true,
                rich_text: true,
            },
            defaults: None,
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ChannelInitializeResult = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_deliver_message_round_trips_then_identical() {
        let original = DeliverMessage {
            session_id: "ses-1".into(),
            content: serde_json::json!({"update": {"sessionUpdate": "result", "content": "done"}}),
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: DeliverMessage = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_peer_info_round_trips_then_identical() {
        let original = PeerInfo {
            channel_name: "telegram".into(),
            peer_id: "user-42".into(),
            kind: "direct".into(),
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: PeerInfo = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_channel_send_message_round_trips_then_identical() {
        let original = ChannelSendMessage {
            peer_info: PeerInfo {
                channel_name: "debug-http".into(),
                peer_id: "dev".into(),
                kind: "local".into(),
            },
            content: "hello agent".into(),
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ChannelSendMessage = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_thought_content_round_trips_then_identical() {
        let original = ThoughtContent {
            session_id: "ses-1".into(),
            update_type: "agent_thought_chunk".into(),
            content: "analyzing...".into(),
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ThoughtContent = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_ack_notification_round_trips_then_identical() {
        let original = AckNotification {
            session_id: "ses-1".into(),
            channel_name: "telegram".into(),
            peer_id: "alice".into(),
            message_id: Some("msg-42".into()),
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: AckNotification = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_ack_notification_no_message_id_round_trips_then_identical() {
        let original = AckNotification {
            session_id: "ses-1".into(),
            channel_name: "debug-http".into(),
            peer_id: "dev".into(),
            message_id: None,
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: AckNotification = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_ack_lifecycle_notification_round_trips_then_identical() {
        let original = AckLifecycleNotification {
            session_id: "ses-1".into(),
            action: "response_started".into(),
            stop_reason: None,
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: AckLifecycleNotification = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_channel_ack_config_round_trips_then_identical() {
        let original = ChannelAckConfig {
            reaction: true,
            typing: true,
            reaction_emoji: "👀".into(),
            reaction_lifecycle: "remove".into(),
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ChannelAckConfig = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_channel_respond_permission_round_trips_then_identical() {
        let original = ChannelRespondPermission {
            request_id: "req-1".into(),
            option_id: "allow".into(),
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: ChannelRespondPermission = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_session_created_round_trips_then_identical() {
        let original = SessionCreated {
            session_id: "acp-sess-42".into(),
            peer_info: PeerInfo {
                channel_name: "telegram".into(),
                peer_id: "tg:99999".into(),
                kind: "direct".into(),
            },
        };
        let json = serde_json::to_value(&original).unwrap();
        let restored: SessionCreated = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_channel_initialize_result_has_defaults_then_round_trips() {
        let mut defaults = std::collections::HashMap::new();
        defaults.insert("timeout".into(), serde_json::json!(30));
        defaults.insert("retry".into(), serde_json::json!(true));
        let original = ChannelInitializeResult {
            protocol_version: 1,
            capabilities: ChannelCapabilities {
                streaming: false,
                rich_text: false,
            },
            defaults: Some(defaults),
        };
        let json = serde_json::to_value(&original).unwrap();
        assert_eq!(json["defaults"]["timeout"], 30);
        assert_eq!(json["defaults"]["retry"], true);
        let restored: ChannelInitializeResult = serde_json::from_value(json).unwrap();
        assert_eq!(original, restored);
    }

    #[rstest]
    fn when_channel_initialize_result_has_no_defaults_then_field_absent_in_json() {
        let original = ChannelInitializeResult {
            protocol_version: 1,
            capabilities: ChannelCapabilities {
                streaming: true,
                rich_text: false,
            },
            defaults: None,
        };
        let json = serde_json::to_value(&original).unwrap();
        assert!(json.get("defaults").is_none());
    }
}