codex-codes 0.153.4

Typed Rust SDK for the OpenAI Codex agent CLI: serde models of the codex app-server JSON-RPC protocol, plus sync and async (Tokio) clients for multi-turn Codex agent sessions, tool calls, and approvals.
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
use codex_codes::io::items::{
    CommandExecutionStatus, FileChangeItem, PatchApplyStatus, PatchChangeKind, ThreadItem,
};
use codex_codes::protocol::{
    ConfigReadResponse, GetAccountRateLimitsParams, GetAccountRateLimitsResponse, McpServerStatus,
    Thread, ThreadListParams,
};
use codex_codes::{
    JsonRpcMessage, JsonRpcNotification, McpServerElicitationRequestParams, Notification,
    ParseError, ThreadEvent, ThreadItemsListResponse, ThreadRevertResponse,
    ThreadTurnsListResponse, TurnSteerResponse,
};

/// config/read round-trips snake_case wire fields and keeps unknown Config/AnalyticsConfig properties in the flatten maps.
#[test]
fn config_read_preserves_additional_properties() {
    let original = serde_json::json!({
        "config": {
            "analytics": {
                "enabled": true,
                "unknownAnalyticsSetting": "kept"
            },
            "sandbox_workspace_write": {
                "network_access": true,
                "writable_roots": ["/tmp/cache"]
            },
            "model_providers": {
                "local": {
                    "base_url": "http://localhost:11434/v1"
                }
            }
        },
        "origins": {}
    });

    let response: ConfigReadResponse =
        serde_json::from_value(original.clone()).expect("deserialize config/read response");

    assert_eq!(
        response.config.additional.get("model_providers"),
        original["config"].get("model_providers")
    );
    assert_eq!(
        response
            .config
            .analytics
            .as_ref()
            .and_then(|analytics| analytics.additional.get("unknownAnalyticsSetting")),
        Some(&serde_json::json!("kept"))
    );
    assert_eq!(
        response
            .config
            .sandbox_workspace_write
            .as_ref()
            .and_then(|sandbox| sandbox.writable_roots.as_deref()),
        Some(["/tmp/cache".to_string()].as_slice())
    );
    assert_eq!(
        serde_json::to_value(response).expect("serialize config/read response"),
        original
    );
}

/// GetAccountRateLimitsResponse decodes accountId and the backend-owned rateLimitUpsell banner, round-tripping both.
#[test]
fn account_rate_limits_include_account_and_upsell() {
    let original = serde_json::json!({
        "accountId": "workspace-123",
        "rateLimits": {},
        "rateLimitUpsell": {
            "message": "Upgrade for more usage"
        }
    });

    let response: GetAccountRateLimitsResponse =
        serde_json::from_value(original.clone()).expect("deserialize rate limits response");

    assert_eq!(response.account_id.as_deref(), Some("workspace-123"));
    assert_eq!(
        response.rate_limit_upsell.as_ref(),
        original.get("rateLimitUpsell")
    );
    assert_eq!(
        serde_json::to_value(response).expect("serialize rate limits response"),
        original
    );
}

/// GetAccountRateLimitsParams omits false capability flags (default is `{}`) and writes set ones in camelCase.
#[test]
fn account_rate_limits_params_omit_false_capabilities() {
    assert_eq!(
        serde_json::to_value(GetAccountRateLimitsParams::default()).unwrap(),
        serde_json::json!({})
    );

    let params = GetAccountRateLimitsParams {
        supports_luna_reserve: true,
        exclude_reset_credit_details: true,
    };
    let wire = serde_json::to_value(&params).unwrap();
    assert_eq!(
        wire,
        serde_json::json!({
            "supportsLunaReserve": true,
            "excludeResetCreditDetails": true
        })
    );
    let back: GetAccountRateLimitsParams = serde_json::from_value(wire).unwrap();
    assert_eq!(back, params);
}

/// GetAccountRateLimitsResponse decodes ordinaryUsageAllowed and RateLimitSnapshot.normalModelSlug, round-tripping both.
#[test]
fn account_rate_limits_decode_usage_permission_and_model_slug() {
    let original = serde_json::json!({
        "ordinaryUsageAllowed": false,
        "rateLimits": {
            "limitId": "codex",
            "normalModelSlug": "gpt-5-codex"
        }
    });

    let response: GetAccountRateLimitsResponse = serde_json::from_value(original.clone()).unwrap();
    assert_eq!(response.ordinary_usage_allowed, Some(false));
    assert_eq!(
        serde_json::to_value(&response).unwrap()["rateLimits"]["normalModelSlug"],
        "gpt-5-codex"
    );
    assert_eq!(serde_json::to_value(response).unwrap(), original);
}

/// Thread.originator and ThreadListParams.originators round-trip and stay absent when unset.
#[test]
fn thread_originator_fields_round_trip() {
    let thread: Thread = serde_json::from_value(serde_json::json!({
        "id": "thr-1",
        "originator": "codex_cli_rs"
    }))
    .unwrap();
    assert_eq!(thread.originator.as_deref(), Some("codex_cli_rs"));

    let bare: Thread = serde_json::from_value(serde_json::json!({"id": "thr-2"})).unwrap();
    assert!(serde_json::to_value(bare)
        .unwrap()
        .get("originator")
        .is_none());

    let params = ThreadListParams {
        originators: Some(vec!["codex_vscode".to_string()]),
        ..ThreadListParams::default()
    };
    assert_eq!(
        serde_json::to_value(params).unwrap(),
        serde_json::json!({"originators": ["codex_vscode"]})
    );
}

/// McpServerStatus.toolsError decodes the discovery failure message and is omitted when a catalog was returned.
#[test]
fn mcp_server_status_decodes_tools_error() {
    let status: McpServerStatus = serde_json::from_value(serde_json::json!({
        "authStatus": "unsupported",
        "name": "broken",
        "toolsError": "transport closed during tools/list"
    }))
    .unwrap();
    assert_eq!(
        status.tools_error.as_deref(),
        Some("transport closed during tools/list")
    );

    let healthy: McpServerStatus = serde_json::from_value(serde_json::json!({
        "authStatus": "unsupported",
        "name": "ok"
    }))
    .unwrap();
    assert!(serde_json::to_value(healthy)
        .unwrap()
        .get("toolsError")
        .is_none());
}

/// MCP elicitation requests with the newer camelCase "openaiForm" mode decode to the OpenAiElicitationForm arm.
#[test]
fn mcp_elicitation_accepts_current_openai_form_mode() {
    let request: McpServerElicitationRequestParams = serde_json::from_value(serde_json::json!({
        "mode": "openaiForm",
        "message": "Choose an account",
        "requestedSchema": {"type": "object"}
    }))
    .expect("deserialize openaiForm elicitation");

    assert!(matches!(
        request,
        McpServerElicitationRequestParams::OpenAiElicitationForm { .. }
    ));
}

/// Response types behind the new sync helpers (turn/steer, items/turns list, thread/revert) decode minimal wire shapes.
#[test]
fn sync_helper_response_types_decode_current_wire_shapes() {
    let steer: TurnSteerResponse =
        serde_json::from_value(serde_json::json!({"turnId": "turn-1"})).unwrap();
    let items: ThreadItemsListResponse =
        serde_json::from_value(serde_json::json!({"data": []})).unwrap();
    let turns: ThreadTurnsListResponse =
        serde_json::from_value(serde_json::json!({"data": []})).unwrap();
    let revert: ThreadRevertResponse =
        serde_json::from_value(serde_json::json!({"thread": {}})).unwrap();

    assert_eq!(steer.turn_id, "turn-1");
    assert!(items.data.is_empty());
    assert!(turns.data.is_empty());
    assert_eq!(revert.thread, codex_codes::Thread::default());
}

/// Parse every line from a JSONL capture file into ThreadEvents,
/// panicking on any deserialization failure.
fn parse_capture(jsonl: &str) -> Vec<ThreadEvent> {
    jsonl
        .lines()
        .filter(|line| !line.trim().is_empty())
        .enumerate()
        .map(|(i, line)| {
            serde_json::from_str::<ThreadEvent>(line)
                .unwrap_or_else(|e| panic!("Failed to parse line {}: {}\n  JSON: {}", i, e, line))
        })
        .collect()
}

/// Extract all ThreadItems from ItemCompleted events.
fn completed_items(events: &[ThreadEvent]) -> Vec<&ThreadItem> {
    events
        .iter()
        .filter_map(|e| match e {
            ThreadEvent::ItemCompleted(ic) => Some(&ic.item),
            _ => None,
        })
        .collect()
}

/// Every capture must start with thread.started and end with turn.completed.
fn assert_standard_envelope(events: &[ThreadEvent]) {
    assert!(
        events.len() >= 3,
        "Expected at least 3 events, got {}",
        events.len()
    );
    assert_eq!(events[0].event_type(), "thread.started");
    assert_eq!(events[1].event_type(), "turn.started");
    assert_eq!(
        events.last().unwrap().event_type(),
        "turn.completed",
        "Last event should be turn.completed"
    );

    // thread.started always carries a thread_id
    if let ThreadEvent::ThreadStarted(e) = &events[0] {
        assert!(!e.thread_id.is_empty(), "thread_id must not be empty");
    }

    // turn.completed always carries usage with non-zero tokens
    if let ThreadEvent::TurnCompleted(e) = events.last().unwrap() {
        assert!(e.usage.input_tokens > 0, "input_tokens should be > 0");
        assert!(e.usage.output_tokens > 0, "output_tokens should be > 0");
    }
}

// ── hello_world: simplest possible session ──────────────────────────

/// Every line of the captured hello-world exec stream parses into a typed event.
#[test]
fn test_hello_world_parses_all_lines() {
    let events = parse_capture(include_str!("../test_cases/captures/hello_world.jsonl"));
    assert_standard_envelope(&events);
    assert_eq!(events.len(), 5);
}

/// The hello-world capture contains both reasoning and agent-message items - the minimal turn vocabulary.
#[test]
fn test_hello_world_contains_reasoning_and_message() {
    let events = parse_capture(include_str!("../test_cases/captures/hello_world.jsonl"));
    let items = completed_items(&events);

    let reasoning_count = items
        .iter()
        .filter(|i| matches!(i, ThreadItem::Reasoning(_)))
        .count();
    let message_count = items
        .iter()
        .filter(|i| matches!(i, ThreadItem::AgentMessage(_)))
        .count();

    assert!(reasoning_count >= 1, "Expected at least one reasoning item");
    assert!(message_count >= 1, "Expected at least one agent message");

    // The final agent message should contain "hello world"
    let last_msg = items
        .iter()
        .rev()
        .find_map(|i| match i {
            ThreadItem::AgentMessage(m) => Some(&m.text),
            _ => None,
        })
        .expect("Should have an agent message");
    assert_eq!(last_msg, "hello world");
}

// ── list_files: command execution with item.started lifecycle ────────

/// Every line of the captured list-files exec stream parses into a typed event.
#[test]
fn test_list_files_parses_all_lines() {
    let events = parse_capture(include_str!("../test_cases/captures/list_files.jsonl"));
    assert_standard_envelope(&events);
    assert_eq!(events.len(), 8);
}

/// The list-files capture shows the full command lifecycle: item.started, command output, item.completed.
#[test]
fn test_list_files_command_lifecycle() {
    let events = parse_capture(include_str!("../test_cases/captures/list_files.jsonl"));

    // Find the item.started / item.completed pair for the command
    let started_cmd = events.iter().find_map(|e| match e {
        ThreadEvent::ItemStarted(is) => match &is.item {
            ThreadItem::CommandExecution(c) => Some(c),
            _ => None,
        },
        _ => None,
    });
    let completed_cmd = completed_items(&events).into_iter().find_map(|i| match i {
        ThreadItem::CommandExecution(c) => Some(c),
        _ => None,
    });

    let started = started_cmd.expect("Should have an item.started command");
    let completed = completed_cmd.expect("Should have an item.completed command");

    // Same item id
    assert_eq!(started.id, completed.id);

    // Started has in_progress status, no exit code, empty output
    assert_eq!(started.status, CommandExecutionStatus::InProgress);
    assert_eq!(started.exit_code, None);
    assert!(started
        .aggregated_output
        .as_deref()
        .unwrap_or("")
        .is_empty());

    // Completed has exit code 0, non-empty output
    assert_eq!(completed.status, CommandExecutionStatus::Completed);
    assert_eq!(completed.exit_code, Some(0));
    assert!(!completed
        .aggregated_output
        .as_deref()
        .unwrap_or("")
        .is_empty());
    assert!(completed.command.contains("ls"));
}

// ── file_create: command that creates a file ────────────────────────

/// Every line of the captured file-create exec stream parses into a typed event.
#[test]
fn test_file_create_parses_all_lines() {
    let events = parse_capture(include_str!("../test_cases/captures/file_create.jsonl"));
    assert_standard_envelope(&events);
    assert_eq!(events.len(), 8);
}

/// The file-create capture carries the command output text on the completed item.
#[test]
fn test_file_create_command_output() {
    let events = parse_capture(include_str!("../test_cases/captures/file_create.jsonl"));
    let cmd = completed_items(&events)
        .into_iter()
        .find_map(|i| match i {
            ThreadItem::CommandExecution(c) => Some(c),
            _ => None,
        })
        .expect("Should have a completed command");

    assert_eq!(cmd.exit_code, Some(0));
    assert_eq!(cmd.aggregated_output.as_deref(), Some("hello from codex"));
}

// ── failed_command: non-zero exit code ──────────────────────────────

/// Every line of the captured failed-command exec stream parses into a typed event.
#[test]
fn test_failed_command_parses_all_lines() {
    let events = parse_capture(include_str!("../test_cases/captures/failed_command.jsonl"));
    assert_standard_envelope(&events);
    assert_eq!(events.len(), 8);
}

/// A failed command reports failed status and its nonzero exit code on the completed item.
#[test]
fn test_failed_command_status_and_exit_code() {
    let events = parse_capture(include_str!("../test_cases/captures/failed_command.jsonl"));

    let started_cmd = events.iter().find_map(|e| match e {
        ThreadEvent::ItemStarted(is) => match &is.item {
            ThreadItem::CommandExecution(c) => Some(c),
            _ => None,
        },
        _ => None,
    });
    let completed_cmd = completed_items(&events).into_iter().find_map(|i| match i {
        ThreadItem::CommandExecution(c) => Some(c),
        _ => None,
    });

    let started = started_cmd.expect("Should have started command");
    let completed = completed_cmd.expect("Should have completed command");

    assert_eq!(started.status, CommandExecutionStatus::InProgress);
    assert_eq!(started.exit_code, None);

    assert_eq!(completed.status, CommandExecutionStatus::Failed);
    assert_eq!(completed.exit_code, Some(42));
    assert!(completed
        .aggregated_output
        .as_deref()
        .unwrap_or("")
        .is_empty());
}

// ── file_change: patch-based file modification ──────────────────────

/// Every line of the captured file-change exec stream parses into a typed event.
#[test]
fn test_file_change_parses_all_lines() {
    let events = parse_capture(include_str!("../test_cases/captures/file_change.jsonl"));
    assert_standard_envelope(&events);
    assert_eq!(events.len(), 12);
}

/// A fileChange item carries the changed paths and change kinds.
#[test]
fn test_file_change_item_fields() {
    let events = parse_capture(include_str!("../test_cases/captures/file_change.jsonl"));

    let fc: &FileChangeItem = completed_items(&events)
        .into_iter()
        .find_map(|i| match i {
            ThreadItem::FileChange(f) => Some(f),
            _ => None,
        })
        .expect("Should have a file_change item");

    assert_eq!(fc.status, PatchApplyStatus::Completed);
    assert_eq!(fc.changes.len(), 1);
    assert!(matches!(fc.changes[0].kind, PatchChangeKind::Update { .. }));
    assert!(fc.changes[0].path.contains("test.txt"));
}

/// The file-change capture also runs a verification command - both item kinds coexist in one turn.
#[test]
fn test_file_change_also_has_command_verification() {
    let events = parse_capture(include_str!("../test_cases/captures/file_change.jsonl"));
    let cmds: Vec<_> = completed_items(&events)
        .into_iter()
        .filter_map(|i| match i {
            ThreadItem::CommandExecution(c) => Some(c),
            _ => None,
        })
        .collect();

    assert!(!cmds.is_empty());
    assert!(cmds.iter().any(|c| c.command.contains("cat")));
    assert!(cmds.iter().any(|c| c
        .aggregated_output
        .as_deref()
        .unwrap_or("")
        .contains("new content")));
}

// ── multi_command: multiple sequential commands ─────────────────────

/// Every line of the captured multi-command exec stream parses into a typed event.
#[test]
fn test_multi_command_parses_all_lines() {
    let events = parse_capture(include_str!("../test_cases/captures/multi_command.jsonl"));
    assert_standard_envelope(&events);
    assert_eq!(events.len(), 12);
}

/// The multi-command capture executed all three requested commands.
#[test]
fn test_multi_command_three_commands_executed() {
    let events = parse_capture(include_str!("../test_cases/captures/multi_command.jsonl"));

    let cmds: Vec<_> = completed_items(&events)
        .into_iter()
        .filter_map(|i| match i {
            ThreadItem::CommandExecution(c) => Some(c),
            _ => None,
        })
        .collect();

    assert_eq!(cmds.len(), 3, "Expected exactly 3 completed commands");

    for (i, cmd) in cmds.iter().enumerate() {
        let step = format!("step{}", i + 1);
        assert!(
            cmd.command.contains(&step),
            "Command {} should contain '{}'",
            i,
            step
        );
        assert_eq!(cmd.exit_code, Some(0));
        assert_eq!(cmd.status, CommandExecutionStatus::Completed);
        assert!(
            cmd.aggregated_output
                .as_deref()
                .unwrap_or("")
                .contains(&step),
            "Output of command {} should contain '{}'",
            i,
            step
        );
    }
}

/// Every item.started in the multi-command capture has a matching item.completed - no orphaned lifecycle events.
#[test]
fn test_multi_command_started_events_match_completed() {
    let events = parse_capture(include_str!("../test_cases/captures/multi_command.jsonl"));

    let started_ids: Vec<_> = events
        .iter()
        .filter_map(|e| match e {
            ThreadEvent::ItemStarted(is) => match &is.item {
                ThreadItem::CommandExecution(c) => Some(c.id.clone()),
                _ => None,
            },
            _ => None,
        })
        .collect();

    let completed_ids: Vec<_> = completed_items(&events)
        .into_iter()
        .filter_map(|i| match i {
            ThreadItem::CommandExecution(c) => Some(c.id.clone()),
            _ => None,
        })
        .collect();

    assert_eq!(started_ids.len(), 3);
    assert_eq!(completed_ids.len(), 3);
    assert_eq!(
        started_ids, completed_ids,
        "Every started command should have a matching completed event"
    );
}

// ── cross-capture: verify all captures share structural invariants ──

/// Thread ids are unique across all captures - the identity guarantee downstream keying relies on.
#[test]
fn test_all_captures_have_unique_thread_ids() {
    let captures = [
        include_str!("../test_cases/captures/hello_world.jsonl"),
        include_str!("../test_cases/captures/list_files.jsonl"),
        include_str!("../test_cases/captures/file_create.jsonl"),
        include_str!("../test_cases/captures/failed_command.jsonl"),
        include_str!("../test_cases/captures/file_change.jsonl"),
        include_str!("../test_cases/captures/multi_command.jsonl"),
    ];

    let thread_ids: Vec<String> = captures
        .iter()
        .map(|c| {
            let events = parse_capture(c);
            match &events[0] {
                ThreadEvent::ThreadStarted(e) => e.thread_id.clone(),
                _ => panic!("First event should be ThreadStarted"),
            }
        })
        .collect();

    let mut deduped = thread_ids.clone();
    deduped.sort();
    deduped.dedup();
    assert_eq!(
        thread_ids.len(),
        deduped.len(),
        "All captures should have unique thread IDs"
    );
}

/// Every capture reports cached-token usage - the accounting field consumers bill against.
#[test]
fn test_all_captures_have_cached_tokens() {
    let captures = [
        include_str!("../test_cases/captures/hello_world.jsonl"),
        include_str!("../test_cases/captures/list_files.jsonl"),
        include_str!("../test_cases/captures/file_create.jsonl"),
        include_str!("../test_cases/captures/failed_command.jsonl"),
        include_str!("../test_cases/captures/file_change.jsonl"),
        include_str!("../test_cases/captures/multi_command.jsonl"),
    ];

    for (i, capture) in captures.iter().enumerate() {
        let events = parse_capture(capture);
        if let ThreadEvent::TurnCompleted(tc) = events.last().unwrap() {
            assert!(
                tc.usage.cached_input_tokens > 0,
                "Capture {} should have cached_input_tokens > 0",
                i
            );
        }
    }
}

/// Item ids increase sequentially within a capture - the ordering guarantee for item lists.
#[test]
fn test_all_item_ids_are_sequential_within_capture() {
    let captures = [
        include_str!("../test_cases/captures/hello_world.jsonl"),
        include_str!("../test_cases/captures/list_files.jsonl"),
        include_str!("../test_cases/captures/file_create.jsonl"),
        include_str!("../test_cases/captures/failed_command.jsonl"),
        include_str!("../test_cases/captures/file_change.jsonl"),
        include_str!("../test_cases/captures/multi_command.jsonl"),
    ];

    for capture in &captures {
        let events = parse_capture(capture);
        let ids: Vec<String> = completed_items(&events)
            .into_iter()
            .map(|item| match item {
                ThreadItem::UserMessage(u) => u.id.clone(),
                ThreadItem::AgentMessage(m) => m.id.clone(),
                ThreadItem::Reasoning(r) => r.id.clone(),
                ThreadItem::CommandExecution(c) => c.id.clone(),
                ThreadItem::FileChange(f) => f.id.clone(),
                ThreadItem::McpToolCall(m) => m.id.clone(),
                ThreadItem::WebSearch(w) => w.id.clone(),
                ThreadItem::TodoList(t) => t.id.clone(),
                ThreadItem::Error(e) => e.id.clone(),
            })
            .collect();

        // IDs follow the pattern "item_N" with increasing N
        let mut seen: Vec<usize> = Vec::new();
        for id in &ids {
            assert!(
                id.starts_with("item_"),
                "ID '{}' should start with 'item_'",
                id
            );
            let n: usize = id[5..]
                .parse()
                .unwrap_or_else(|_| panic!("ID '{}' should have a numeric suffix", id));
            if !seen.contains(&n) {
                seen.push(n);
            }
        }

        for window in seen.windows(2) {
            assert!(
                window[1] > window[0],
                "Item IDs should be monotonically increasing, got {} after {}",
                window[1],
                window[0]
            );
        }
    }
}

// ── typed-decode failure plumbing (issue #128) ───────────────────────────
//
// When a wire frame's envelope parses but the typed-payload decode fails,
// callers must still be able to recover the original `method` + `params` for
// bug reports. These tests pin the exact code path used by
// `AsyncClient::next_message` / `SyncClient::next_message`: deserialize the
// line as a `JsonRpcMessage`, run `Notification::from_envelope` /
// `ServerRequest::from_envelope`, wrap the resulting `serde_json::Error` in a
// `ParseError`, and check that nothing was dropped on the floor.

/// An unmodeled notification surfaces as a parse error carrying its method and params - named, not silently dropped.
#[test]
fn parse_error_carries_method_and_params_for_unmodeled_notification_variant() {
    // Simulates a notification whose envelope is fine but whose params don't
    // match any modeled variant — e.g. a future `FileUpdateChange.type` value
    // the crate version doesn't yet know about.
    //
    // The crate uses an `Unknown { method, params }` fallback for unmodeled
    // *methods*, so to actually trigger a typed-decode failure on a *known*
    // method we send malformed params for it.
    let line = r#"{"method":"item/completed","params":{"item":42}}"#;
    let envelope: JsonRpcMessage = serde_json::from_str(line).expect("envelope parses");
    let JsonRpcMessage::Notification(JsonRpcNotification { method, params }) = envelope else {
        panic!("expected Notification, got: {:?}", envelope);
    };

    let err = Notification::from_envelope(&method, params.clone())
        .expect_err("malformed params must fail typed decode");
    let pe = ParseError::from_envelope(method.clone(), params.clone(), err);

    assert_eq!(pe.method.as_deref(), Some("item/completed"));
    assert_eq!(pe.raw_json, params);
    assert!(
        !pe.error_message.is_empty(),
        "error_message should be populated"
    );
    // raw_line is a wire-equivalent reconstruction, parseable back into an envelope.
    let echoed: JsonRpcMessage = serde_json::from_str(&pe.raw_line)
        .unwrap_or_else(|e| panic!("raw_line should re-parse as JsonRpcMessage: {}", e));
    if let JsonRpcMessage::Notification(n) = echoed {
        assert_eq!(n.method, "item/completed");
        assert_eq!(n.params.unwrap()["item"], 42);
    } else {
        panic!("raw_line should re-parse as a Notification");
    }
}

/// A malformed envelope keeps the raw line in the parse error so the bad wire bytes are recoverable.
#[test]
fn parse_error_from_invalid_envelope_keeps_raw_line_without_method() {
    // The bare-JSON failure path: line is not a valid JsonRpcMessage.
    let line = r#"{"completely":"unexpected"}"#;
    let err = serde_json::from_str::<JsonRpcMessage>(line).expect_err("should not parse");
    let pe = ParseError::from_line(line, err);
    assert!(pe.method.is_none());
    assert_eq!(pe.raw_line, line);
    // raw_json is populated because the line was valid JSON, just not a JsonRpcMessage.
    assert_eq!(pe.raw_json.as_ref().unwrap()["completely"], "unexpected");
}