par-term-acp 0.2.1

Agent Communication Protocol (ACP) implementation for par-term
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
//! ACP (Agent Communication Protocol) message type definitions.
//!
//! These types model the JSON-RPC parameter and result objects exchanged
//! between the par-term host and an ACP-compatible agent (e.g. Claude Code).

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

// ---------------------------------------------------------------------------
// Initialize
// ---------------------------------------------------------------------------

/// Parameters for the `initialize` request sent from host to agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeParams {
    pub protocol_version: u32,
    pub client_capabilities: ClientCapabilities,
    pub client_info: ClientInfo,
}

/// Capabilities the host advertises to the agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientCapabilities {
    pub fs: FsCapabilities,
    pub terminal: bool,
    /// Whether the host supports the `config/update` RPC call.
    #[serde(default)]
    pub config: bool,
}

/// File-system capabilities exposed by the host.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FsCapabilities {
    pub read_text_file: bool,
    pub write_text_file: bool,
    #[serde(default)]
    pub list_directory: bool,
    #[serde(default)]
    pub find: bool,
}

/// Identifying information about the host client.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientInfo {
    pub name: String,
    pub title: String,
    pub version: String,
}

/// Result returned by the agent in response to `initialize`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResult {
    pub protocol_version: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_capabilities: Option<AgentCapabilities>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_methods: Option<Vec<AuthMethod>>,
}

/// Capabilities the agent advertises back to the host.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentCapabilities {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub load_session: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_capabilities: Option<PromptCapabilities>,
}

/// Content modalities the agent can handle in prompts.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PromptCapabilities {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub embedded_content: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<bool>,
}

/// An authentication method the agent supports.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthMethod {
    pub id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

// ---------------------------------------------------------------------------
// Session
// ---------------------------------------------------------------------------

/// Parameters for the `session/new` request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionNewParams {
    pub cwd: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mcp_servers: Option<Vec<Value>>,
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// Parameters for the `session/load` request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionLoadParams {
    pub cwd: String,
    pub session_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mcp_servers: Option<Vec<Value>>,
}

/// Result returned after creating or loading a session.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionResult {
    pub session_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modes: Option<ModesInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub models: Option<ModelsInfo>,
}

/// Available interaction modes reported by the agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModesInfo {
    pub available_modes: Vec<ModeEntry>,
    pub current_mode_id: String,
}

/// A single interaction mode.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModeEntry {
    pub id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Available models reported by the agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsInfo {
    pub available_models: Vec<ModelEntry>,
    pub current_model_id: String,
}

/// A single model the agent can use.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelEntry {
    pub model_id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

// ---------------------------------------------------------------------------
// Content blocks
// ---------------------------------------------------------------------------

/// A typed content block used in prompts and responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    /// Plain text content.
    Text { text: String },
    /// An embedded resource (file content, blob, etc.).
    Resource { resource: ResourceContent },
}

/// The payload of a `Resource` content block.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceContent {
    pub uri: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blob: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
}

// ---------------------------------------------------------------------------
// Prompt
// ---------------------------------------------------------------------------

/// Parameters for the `session/prompt` request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionPromptParams {
    pub session_id: String,
    pub prompt: Vec<ContentBlock>,
}

/// Result returned after a prompt completes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionPromptResult {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<String>,
}

// ---------------------------------------------------------------------------
// Session updates (notifications from agent)
// ---------------------------------------------------------------------------

/// Parameters for the `session/update` notification.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionUpdateParams {
    pub session_id: String,
    pub update: Value,
}

/// A parsed session update. These are **not** serde-derived because the
/// `sessionUpdate` discriminator field requires manual dispatch.
#[derive(Debug, Clone)]
pub enum SessionUpdate {
    /// A chunk of the agent's response text.
    AgentMessageChunk { text: String },
    /// A chunk of the agent's internal reasoning.
    AgentThoughtChunk { text: String },
    /// A chunk echoing the user's message.
    UserMessageChunk { text: String },
    /// A new or updated tool call.
    ToolCall(ToolCallInfo),
    /// An incremental update to an existing tool call.
    ToolCallUpdate(ToolCallUpdateInfo),
    /// The agent's current plan.
    Plan(PlanInfo),
    /// Updated list of available slash commands.
    AvailableCommandsUpdate(Vec<AgentCommand>),
    /// The agent switched interaction mode.
    CurrentModeUpdate { mode_id: String },
    /// Unrecognized update type — preserved as raw JSON.
    Unknown(Value),
}

impl SessionUpdate {
    /// Parse a session update from its raw JSON [`Value`].
    ///
    /// The value is expected to have a `"sessionUpdate"` string field that
    /// acts as a type discriminator.
    pub fn from_value(value: &Value) -> Self {
        let update_type = value
            .get("sessionUpdate")
            .and_then(|v| v.as_str())
            .unwrap_or("");

        match update_type {
            "agent_message_chunk" => {
                let text = value
                    .get("content")
                    .and_then(|c| c.get("text"))
                    .and_then(|t| t.as_str())
                    .unwrap_or("")
                    .to_string();
                Self::AgentMessageChunk { text }
            }
            "agent_thought_chunk" => {
                let text = value
                    .get("content")
                    .and_then(|c| c.get("text"))
                    .and_then(|t| t.as_str())
                    .unwrap_or("")
                    .to_string();
                Self::AgentThoughtChunk { text }
            }
            "user_message_chunk" => {
                let text = value
                    .get("content")
                    .and_then(|c| c.get("text"))
                    .and_then(|t| t.as_str())
                    .unwrap_or("")
                    .to_string();
                Self::UserMessageChunk { text }
            }
            "tool_call" => {
                let tool_call_id = value
                    .get("toolCallId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let title = value
                    .get("title")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let kind = value
                    .get("kind")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let status = value
                    .get("status")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let content = value.get("content").cloned();
                Self::ToolCall(ToolCallInfo {
                    tool_call_id,
                    title,
                    kind,
                    status,
                    content,
                })
            }
            "tool_call_update" => {
                let tool_call_id = value
                    .get("toolCallId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let status = value
                    .get("status")
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let title = value
                    .get("title")
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let content = value.get("content").cloned();
                Self::ToolCallUpdate(ToolCallUpdateInfo {
                    tool_call_id,
                    status,
                    title,
                    content,
                })
            }
            "plan" => {
                let entries = value
                    .get("entries")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .map(|entry| PlanEntry {
                                content: entry
                                    .get("content")
                                    .and_then(|v| v.as_str())
                                    .unwrap_or("")
                                    .to_string(),
                                status: entry
                                    .get("status")
                                    .and_then(|v| v.as_str())
                                    .unwrap_or("")
                                    .to_string(),
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                Self::Plan(PlanInfo { entries })
            }
            "available_commands_update" => {
                let commands = value
                    .get("commands")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .map(|cmd| AgentCommand {
                                name: cmd
                                    .get("name")
                                    .and_then(|v| v.as_str())
                                    .unwrap_or("")
                                    .to_string(),
                                description: cmd
                                    .get("description")
                                    .and_then(|v| v.as_str())
                                    .map(String::from),
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                Self::AvailableCommandsUpdate(commands)
            }
            "current_mode_update" => {
                let mode_id = value
                    .get("modeId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                Self::CurrentModeUpdate { mode_id }
            }
            _ => Self::Unknown(value.clone()),
        }
    }
}

/// Information about a tool call initiated by the agent.
#[derive(Debug, Clone)]
pub struct ToolCallInfo {
    pub tool_call_id: String,
    pub title: String,
    pub kind: String,
    pub status: String,
    pub content: Option<Value>,
}

/// An incremental update to an in-progress tool call.
#[derive(Debug, Clone)]
pub struct ToolCallUpdateInfo {
    pub tool_call_id: String,
    pub status: Option<String>,
    pub title: Option<String>,
    pub content: Option<Value>,
}

/// The agent's current execution plan.
#[derive(Debug, Clone)]
pub struct PlanInfo {
    pub entries: Vec<PlanEntry>,
}

/// A single step in the agent's plan.
#[derive(Debug, Clone)]
pub struct PlanEntry {
    pub content: String,
    pub status: String,
}

/// A slash-command or action the agent exposes.
#[derive(Debug, Clone)]
pub struct AgentCommand {
    pub name: String,
    pub description: Option<String>,
}

// ---------------------------------------------------------------------------
// Permission
// ---------------------------------------------------------------------------

/// Parameters for the `session/request_permission` RPC call from agent to host.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestPermissionParams {
    #[serde(default)]
    pub session_id: String,
    pub tool_call: Value,
    pub options: Vec<PermissionOption>,
}

/// A single permission option the host can choose from.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PermissionOption {
    pub option_id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
}

/// The host's response to a permission request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestPermissionResponse {
    pub outcome: PermissionOutcome,
}

/// The chosen outcome of a permission request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PermissionOutcome {
    pub outcome: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub option_id: Option<String>,
}

// ---------------------------------------------------------------------------
// File system operations
// ---------------------------------------------------------------------------

/// Parameters for the `fs/readTextFile` RPC call from agent to host.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FsReadParams {
    #[serde(default)]
    pub session_id: String,
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u64>,
}

/// Parameters for the `fs/writeTextFile` RPC call from agent to host.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FsWriteParams {
    #[serde(default)]
    pub session_id: String,
    pub path: String,
    pub content: String,
}

/// Parameters for the `fs/listDirectory` RPC call from agent to host.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FsListDirectoryParams {
    #[serde(default)]
    pub session_id: String,
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
}

/// Parameters for the `fs/find` RPC call from agent to host.
///
/// This is a par-term extension (not part of the core ACP spec) that provides
/// recursive glob-based file search, similar to Claude Code's built-in Glob tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FsFindParams {
    #[serde(default)]
    pub session_id: String,
    pub path: String,
    pub pattern: String,
}

// ---------------------------------------------------------------------------
// Config update
// ---------------------------------------------------------------------------

/// Parameters for the `config/update` RPC call from agent to host.
///
/// Allows the agent to update par-term configuration settings directly,
/// bypassing the config.yaml file to avoid race conditions with par-term's
/// own config saves.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfigUpdateParams {
    #[serde(default)]
    pub session_id: Option<String>,
    /// Map of config key -> value to update.
    /// Keys use snake_case matching config.yaml field names.
    /// Values must be the correct JSON type for the field.
    pub updates: HashMap<String, Value>,
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_session_update_parse_agent_message() {
        let value = serde_json::json!({
            "sessionUpdate": "agent_message_chunk",
            "content": { "type": "text", "text": "Hello from agent" }
        });
        match SessionUpdate::from_value(&value) {
            SessionUpdate::AgentMessageChunk { text } => assert_eq!(text, "Hello from agent"),
            other => panic!("Expected AgentMessageChunk, got {:?}", other),
        }
    }

    #[test]
    fn test_session_update_parse_tool_call() {
        let value = serde_json::json!({
            "sessionUpdate": "tool_call",
            "toolCallId": "tc-1",
            "title": "Read file",
            "kind": "read",
            "status": "in_progress"
        });
        match SessionUpdate::from_value(&value) {
            SessionUpdate::ToolCall(info) => {
                assert_eq!(info.tool_call_id, "tc-1");
                assert_eq!(info.kind, "read");
            }
            other => panic!("Expected ToolCall, got {:?}", other),
        }
    }

    #[test]
    fn test_initialize_params_serialization() {
        let params = InitializeParams {
            protocol_version: 1,
            client_capabilities: ClientCapabilities {
                fs: FsCapabilities {
                    read_text_file: true,
                    write_text_file: false,
                    list_directory: false,
                    find: false,
                },
                terminal: false,
                config: false,
            },
            client_info: ClientInfo {
                name: "par-term".to_string(),
                title: "Par Term".to_string(),
                version: "0.16.0".to_string(),
            },
        };
        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("protocolVersion"));
        assert!(json.contains("par-term"));
    }

    #[test]
    fn test_content_block_serialization() {
        let block = ContentBlock::Text {
            text: "Hello".to_string(),
        };
        let json = serde_json::to_string(&block).unwrap();
        assert!(json.contains(r#""type":"text"#));
    }

    #[test]
    fn test_session_update_parse_thought_chunk() {
        let value = serde_json::json!({
            "sessionUpdate": "agent_thought_chunk",
            "content": { "type": "text", "text": "Thinking..." }
        });
        match SessionUpdate::from_value(&value) {
            SessionUpdate::AgentThoughtChunk { text } => assert_eq!(text, "Thinking..."),
            other => panic!("Expected AgentThoughtChunk, got {:?}", other),
        }
    }

    #[test]
    fn test_session_update_parse_tool_call_update() {
        let value = serde_json::json!({
            "sessionUpdate": "tool_call_update",
            "toolCallId": "tc-2",
            "status": "completed",
            "title": "Write file"
        });
        match SessionUpdate::from_value(&value) {
            SessionUpdate::ToolCallUpdate(info) => {
                assert_eq!(info.tool_call_id, "tc-2");
                assert_eq!(info.status.as_deref(), Some("completed"));
                assert_eq!(info.title.as_deref(), Some("Write file"));
            }
            other => panic!("Expected ToolCallUpdate, got {:?}", other),
        }
    }

    #[test]
    fn test_session_update_parse_plan() {
        let value = serde_json::json!({
            "sessionUpdate": "plan",
            "entries": [
                { "content": "Step 1: Read file", "status": "completed" },
                { "content": "Step 2: Edit code", "status": "in_progress" }
            ]
        });
        match SessionUpdate::from_value(&value) {
            SessionUpdate::Plan(info) => {
                assert_eq!(info.entries.len(), 2);
                assert_eq!(info.entries[0].content, "Step 1: Read file");
                assert_eq!(info.entries[0].status, "completed");
                assert_eq!(info.entries[1].status, "in_progress");
            }
            other => panic!("Expected Plan, got {:?}", other),
        }
    }

    #[test]
    fn test_session_update_parse_available_commands() {
        let value = serde_json::json!({
            "sessionUpdate": "available_commands_update",
            "commands": [
                { "name": "/help", "description": "Show help" },
                { "name": "/clear" }
            ]
        });
        match SessionUpdate::from_value(&value) {
            SessionUpdate::AvailableCommandsUpdate(cmds) => {
                assert_eq!(cmds.len(), 2);
                assert_eq!(cmds[0].name, "/help");
                assert_eq!(cmds[0].description.as_deref(), Some("Show help"));
                assert_eq!(cmds[1].name, "/clear");
                assert!(cmds[1].description.is_none());
            }
            other => panic!("Expected AvailableCommandsUpdate, got {:?}", other),
        }
    }

    #[test]
    fn test_session_update_parse_current_mode() {
        let value = serde_json::json!({
            "sessionUpdate": "current_mode_update",
            "modeId": "agent"
        });
        match SessionUpdate::from_value(&value) {
            SessionUpdate::CurrentModeUpdate { mode_id } => assert_eq!(mode_id, "agent"),
            other => panic!("Expected CurrentModeUpdate, got {:?}", other),
        }
    }

    #[test]
    fn test_session_update_parse_unknown() {
        let value = serde_json::json!({
            "sessionUpdate": "some_future_type",
            "data": 42
        });
        match SessionUpdate::from_value(&value) {
            SessionUpdate::Unknown(v) => {
                assert_eq!(v.get("data").and_then(|d| d.as_u64()), Some(42));
            }
            other => panic!("Expected Unknown, got {:?}", other),
        }
    }

    #[test]
    fn test_initialize_result_deserialization() {
        let json = r#"{
            "protocolVersion": 1,
            "agentCapabilities": {
                "loadSession": true,
                "promptCapabilities": { "audio": false, "image": true }
            },
            "authMethods": [
                { "id": "oauth", "name": "OAuth 2.0" }
            ]
        }"#;
        let result: InitializeResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.protocol_version, 1);
        let caps = result.agent_capabilities.unwrap();
        assert_eq!(caps.load_session, Some(true));
        let prompt = caps.prompt_capabilities.unwrap();
        assert_eq!(prompt.image, Some(true));
        assert_eq!(prompt.audio, Some(false));
        assert!(prompt.embedded_content.is_none());
        let auth = result.auth_methods.unwrap();
        assert_eq!(auth.len(), 1);
        assert_eq!(auth[0].id, "oauth");
        assert!(auth[0].description.is_none());
    }

    #[test]
    fn test_session_result_deserialization() {
        let json = r#"{
            "sessionId": "sess-abc123",
            "modes": {
                "availableModes": [
                    { "id": "agent", "name": "Agent Mode" },
                    { "id": "plan", "name": "Plan Mode", "description": "Planning only" }
                ],
                "currentModeId": "agent"
            },
            "models": {
                "availableModels": [
                    { "modelId": "claude-4", "name": "Claude 4" }
                ],
                "currentModelId": "claude-4"
            }
        }"#;
        let result: SessionResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.session_id, "sess-abc123");
        let modes = result.modes.unwrap();
        assert_eq!(modes.available_modes.len(), 2);
        assert_eq!(
            modes.available_modes[1].description.as_deref(),
            Some("Planning only")
        );
        let models = result.models.unwrap();
        assert_eq!(models.available_models.len(), 1);
    }

    #[test]
    fn test_permission_roundtrip() {
        let params = RequestPermissionParams {
            session_id: "sess-1".to_string(),
            tool_call: serde_json::json!({"tool": "bash", "command": "ls"}),
            options: vec![
                PermissionOption {
                    option_id: "allow".to_string(),
                    name: "Allow".to_string(),
                    kind: Some("allow".to_string()),
                },
                PermissionOption {
                    option_id: "deny".to_string(),
                    name: "Deny".to_string(),
                    kind: None,
                },
            ],
        };
        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("sessionId"));
        assert!(json.contains("optionId"));
        let deserialized: RequestPermissionParams = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.options.len(), 2);
        assert!(deserialized.options[1].kind.is_none());
    }

    #[test]
    fn test_content_block_resource_serialization() {
        let block = ContentBlock::Resource {
            resource: ResourceContent {
                uri: "file:///tmp/test.rs".to_string(),
                text: Some("fn main() {}".to_string()),
                blob: None,
                mime_type: Some("text/x-rust".to_string()),
            },
        };
        let json = serde_json::to_string(&block).unwrap();
        assert!(json.contains(r#""type":"resource"#));
        assert!(json.contains("file:///tmp/test.rs"));
        assert!(!json.contains("blob"));
    }

    #[test]
    fn test_fs_read_params_serialization() {
        let params = FsReadParams {
            session_id: "sess-1".to_string(),
            path: "/tmp/test.txt".to_string(),
            line: Some(10),
            limit: None,
        };
        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("sessionId"));
        assert!(json.contains(r#""line":10"#));
        assert!(!json.contains("limit"));
    }

    #[test]
    fn test_fs_write_params_serialization() {
        let params = FsWriteParams {
            session_id: "sess-1".to_string(),
            path: "/tmp/test.txt".to_string(),
            content: "hello world".to_string(),
        };
        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("sessionId"));
        assert!(json.contains("hello world"));
    }

    #[test]
    fn test_fs_list_directory_params_serialization() {
        let params = FsListDirectoryParams {
            session_id: "sess-1".to_string(),
            path: "/tmp".to_string(),
            pattern: Some("*.rs".to_string()),
        };
        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("sessionId"));
        assert!(json.contains("*.rs"));
    }

    #[test]
    fn test_fs_capabilities_list_directory_default() {
        let json = r#"{"readTextFile": true, "writeTextFile": false}"#;
        let caps: FsCapabilities = serde_json::from_str(json).unwrap();
        assert!(caps.read_text_file);
        assert!(!caps.write_text_file);
        assert!(!caps.list_directory);
    }
}