ag-agent 0.21.0

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
//! Final response and stream-line parsing for Claude, Codex, and Antigravity
//! CLI output.

use ag_contracts::{SessionDiffState, SessionStats};
use ag_protocol::{FocusedReview, ReviewMetadata, UtilityResponse};
use serde::Deserialize;

/// Parsed agent response including content text and usage statistics.
pub(crate) struct ParsedResponse {
    /// Final response text from the agent.
    pub content: String,
    /// Final response texts of later turns the same run answered, in order,
    /// such as Claude replying to a steering prompt after its turn ended.
    pub follow_up_contents: Vec<String>,
    /// Token usage statistics associated with every returned content.
    pub stats: SessionStats,
}

/// Claude CLI JSON response shape.
#[derive(Deserialize)]
struct ClaudeResponse {
    result: Option<String>,
    structured_output: Option<serde_json::Value>,
    usage: Option<ClaudeUsage>,
}

/// Token usage from a Claude CLI response.
#[derive(Deserialize)]
struct ClaudeUsage {
    input_tokens: Option<i64>,
    output_tokens: Option<i64>,
}

/// Single NDJSON event emitted by Codex CLI (`--json`).
#[derive(Deserialize)]
struct CodexEvent {
    #[serde(rename = "type")]
    event_type: Option<String>,
    item: Option<CodexItem>,
    usage: Option<CodexUsage>,
}

/// Token usage from a Codex `turn.completed` event.
#[derive(Deserialize)]
struct CodexUsage {
    input_tokens: Option<i64>,
    output_tokens: Option<i64>,
}

/// Nested item payload from a Codex stream event.
#[derive(Deserialize)]
struct CodexItem {
    delta: Option<String>,
    #[serde(rename = "type")]
    item_type: Option<String>,
    text: Option<String>,
}

/// Parses Claude output and falls back to raw output when parsing fails.
pub(super) fn parse_claude_response_with_fallback(stdout: &str, stderr: &str) -> ParsedResponse {
    parse_claude_response(stdout).unwrap_or_else(|| ParsedResponse {
        content: fallback_response(stdout, stderr),
        follow_up_contents: Vec::new(),
        stats: SessionStats::default(),
    })
}

/// Parses Codex output and falls back to raw output when parsing fails.
pub(super) fn parse_codex_response_with_fallback(stdout: &str, stderr: &str) -> ParsedResponse {
    parse_codex_response(stdout).unwrap_or_else(|| ParsedResponse {
        content: fallback_response(stdout, stderr),
        follow_up_contents: Vec::new(),
        stats: SessionStats::default(),
    })
}

/// Parses Antigravity `stream-json` output and falls back to raw output when
/// the CLI emits an unstructured diagnostic.
pub(super) fn parse_antigravity_response_with_fallback(
    stdout: &str,
    stderr: &str,
) -> ParsedResponse {
    parse_antigravity_response(stdout).unwrap_or_else(|| ParsedResponse {
        content: fallback_response(stdout, stderr),
        follow_up_contents: Vec::new(),
        stats: SessionStats::default(),
    })
}

/// Classifies one parsed Antigravity stream-line payload.
///
/// Response content is classified separately so the CLI channel can suppress
/// duplicate partial answers while still surfacing reasoning and tool
/// progress.
pub(super) fn parse_antigravity_stream_payload(
    stream_event: &serde_json::Value,
) -> Option<(String, bool)> {
    let event_label = antigravity_event_label(stream_event);
    if event_label.is_some_and(|label| {
        let label = label.to_ascii_lowercase();

        label.contains("thought") || label.contains("reason")
    }) {
        return antigravity_event_text(stream_event).map(|text| (text, false));
    }

    if let Some(progress_message) = compact_progress_message_from_json(stream_event) {
        return Some((progress_message, false));
    }

    antigravity_event_text(stream_event).map(|text| (text, true))
}

/// Parses a complete Antigravity JSON or NDJSON response.
fn parse_antigravity_response(stdout: &str) -> Option<ParsedResponse> {
    let trimmed_stdout = stdout.trim();
    if trimmed_stdout.is_empty() {
        return None;
    }

    let mut final_content: Option<String> = None;
    let mut streamed_content = String::new();
    let mut latest_stats: Option<SessionStats> = None;

    if let Ok(payload) = serde_json::from_str::<serde_json::Value>(trimmed_stdout) {
        record_antigravity_payload(
            &payload,
            &mut final_content,
            &mut streamed_content,
            &mut latest_stats,
        );
    } else {
        for line in stdout
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
        {
            let Ok(payload) = serde_json::from_str::<serde_json::Value>(line) else {
                continue;
            };
            record_antigravity_payload(
                &payload,
                &mut final_content,
                &mut streamed_content,
                &mut latest_stats,
            );
        }
    }

    let content = final_content.or_else(|| {
        if streamed_content.trim().is_empty() {
            None
        } else {
            Some(streamed_content)
        }
    })?;
    let stats = latest_stats.unwrap_or_default();

    Some(ParsedResponse {
        content,
        follow_up_contents: Vec::new(),
        stats,
    })
}

/// Records final content, streamed deltas, and usage from one Antigravity
/// payload or payload array.
fn record_antigravity_payload(
    payload: &serde_json::Value,
    final_content: &mut Option<String>,
    streamed_content: &mut String,
    latest_stats: &mut Option<SessionStats>,
) {
    if let Some(events) = payload.as_array() {
        for event in events {
            record_antigravity_payload(event, final_content, streamed_content, latest_stats);
        }

        return;
    }

    if let Some(stats) = extract_antigravity_usage_stats(payload) {
        latest_stats.replace(stats);
    }

    if antigravity_protocol_payload(payload) {
        final_content.replace(payload.to_string());

        return;
    }

    if let Some(result) = payload.get("result") {
        if let Some(content) = result.get("response").and_then(antigravity_value_text) {
            final_content.replace(content);
        }

        return;
    }

    if let Some(content) = payload.get("response").and_then(antigravity_value_text) {
        final_content.replace(content);

        return;
    }

    if antigravity_event_label(payload).is_some_and(|label| {
        let label = label.to_ascii_lowercase();

        label.contains("result") || label.contains("complete") || label.contains("final")
    }) {
        if let Some(content) = payload.get("value").and_then(antigravity_value_text) {
            final_content.replace(content);
        }

        return;
    }

    if let Some(content) = antigravity_event_text(payload) {
        streamed_content.push_str(&content);
    }
}

/// Returns whether a JSON value is the protocol response itself.
fn antigravity_protocol_payload(payload: &serde_json::Value) -> bool {
    let is_agent_response = payload.get("answer").is_some() && payload.get("questions").is_some();

    is_agent_response
        || FocusedReview::deserialize(payload).is_ok()
        || UtilityResponse::deserialize(payload).is_ok()
        || ReviewMetadata::deserialize(payload).is_ok()
}

/// Extracts string or structured content from an Antigravity event value.
fn antigravity_value_text(value: &serde_json::Value) -> Option<String> {
    if let Some(text) = value.as_str().filter(|text| !text.trim().is_empty()) {
        return Some(text.to_string());
    }

    if value.is_object() || value.is_array() {
        return Some(value.to_string());
    }

    None
}

/// Extracts response text from the fields used by Antigravity stream events.
fn antigravity_event_text(payload: &serde_json::Value) -> Option<String> {
    payload
        .get("text")
        .or_else(|| payload.get("delta"))
        .or_else(|| payload.get("content"))
        .or_else(|| payload.get("value"))
        .and_then(antigravity_value_text)
}

/// Returns the discriminator used by an Antigravity stream event.
fn antigravity_event_label(payload: &serde_json::Value) -> Option<&str> {
    payload
        .get("event")
        .or_else(|| payload.get("type"))
        .or_else(|| payload.get("state"))
        .and_then(serde_json::Value::as_str)
}

/// Extracts the latest Antigravity token counters from top-level or nested
/// usage data.
fn extract_antigravity_usage_stats(payload: &serde_json::Value) -> Option<SessionStats> {
    let usage = payload
        .get("usage")
        .or_else(|| payload.get("result").and_then(|result| result.get("usage")))?;

    Some(SessionStats {
        added_lines: 0,
        deleted_lines: 0,
        diff_state: SessionDiffState::Unknown,
        input_tokens: antigravity_token_count(usage, "input_tokens"),
        output_tokens: antigravity_token_count(usage, "output_tokens"),
    })
}

/// Reads one non-negative token counter from Antigravity usage JSON.
fn antigravity_token_count(usage: &serde_json::Value, field: &str) -> u64 {
    usage
        .get(field)
        .and_then(serde_json::Value::as_u64)
        .unwrap_or(0)
}

/// Parses one full Claude run payload from stream-json stdout.
///
/// Prefers each turn's schema-validated `structured_output` or non-empty
/// `result` field. A steerable run answers a steering prompt that arrived
/// after its turn ended in a follow-up turn, so results after the first are
/// kept in order as `follow_up_contents` and usage is summed across results.
/// When Claude emits neither field (observed in some stream-json runs), this
/// falls back to the latest assistant stream message content so callers still
/// receive the assistant reply instead of raw NDJSON.
fn parse_claude_response(stdout: &str) -> Option<ParsedResponse> {
    let trimmed_stdout = stdout.trim();
    if trimmed_stdout.is_empty() {
        return None;
    }

    if let Some(parsed_response) = parse_claude_complete_payload(trimmed_stdout) {
        return (!parsed_response.content.trim().is_empty()).then_some(parsed_response);
    }

    let mut turn_contents = Vec::new();
    let mut stats = SessionStats::default();
    let mut latest_stream_message_content: Option<String> = None;

    for line in stdout
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
    {
        if let Some(parsed_response) = parse_claude_complete_payload(line) {
            add_claude_turn_usage(&mut stats, &parsed_response.stats);
            if !parsed_response.content.trim().is_empty() {
                turn_contents.push(parsed_response.content);
            }

            continue;
        }

        let Ok(stream_event) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };

        if let Some(turn_stats) = extract_claude_usage_stats(&stream_event) {
            add_claude_turn_usage(&mut stats, &turn_stats);
        }

        if let Some(content) = extract_claude_stream_assistant_content(&stream_event) {
            latest_stream_message_content = Some(content);
        }
    }

    let mut turn_contents = turn_contents.into_iter();
    if let Some(content) = turn_contents.next() {
        return Some(ParsedResponse {
            content,
            follow_up_contents: turn_contents.collect(),
            stats,
        });
    }

    let content = latest_stream_message_content?;
    if content.trim().is_empty() {
        return None;
    }

    Some(ParsedResponse {
        content,
        follow_up_contents: Vec::new(),
        stats,
    })
}

/// Parses one complete Claude payload, either a flat result object or a JSON
/// event array.
fn parse_claude_complete_payload(payload: &str) -> Option<ParsedResponse> {
    parse_claude_response_payload(payload).or_else(|| parse_claude_response_array_payload(payload))
}

/// Adds one Claude turn's token usage to the run total.
///
/// In `stream-json` input mode each `result` reports usage for its own turn
/// only, so a run that answers several turns is the sum of its results.
fn add_claude_turn_usage(total: &mut SessionStats, turn: &SessionStats) {
    total.input_tokens = total.input_tokens.saturating_add(turn.input_tokens);
    total.output_tokens = total.output_tokens.saturating_add(turn.output_tokens);
}

/// Classifies one parsed Claude stream-line payload into display text and
/// content/progress type.
pub(super) fn parse_claude_stream_payload(
    stream_event: &serde_json::Value,
) -> Option<(String, bool)> {
    if let Some(content) = extract_claude_stream_assistant_content(stream_event) {
        return Some((content, true));
    }

    let progress_message = compact_progress_message_from_json(stream_event)?;

    Some((progress_message, false))
}

/// Parses Codex NDJSON output into the final assistant message and usage.
///
/// Synthetic completion-status `agent_message` events are ignored so trailing
/// status lines do not replace the assistant-authored reply. When both
/// `agent_message` and `reasoning`/`thought` items are present, this parser
/// always prefers `agent_message` content for the final response so internal
/// reasoning payloads (including raw JSON snippets) do not overwrite
/// user-visible assistant text.
fn parse_codex_response(stdout: &str) -> Option<ParsedResponse> {
    let mut last_agent_message: Option<String> = None;
    let mut last_reasoning_message: Option<String> = None;
    let mut total_input_tokens: u64 = 0;
    let mut total_output_tokens: u64 = 0;

    for line in stdout.lines() {
        let trimmed_line = line.trim();
        if trimmed_line.is_empty() {
            continue;
        }

        let Ok(event) = serde_json::from_str::<CodexEvent>(trimmed_line) else {
            continue;
        };

        record_codex_turn_usage(&event, &mut total_input_tokens, &mut total_output_tokens);

        if event.event_type.as_deref() != Some("item.completed") {
            continue;
        }

        let Some(item) = event.item else {
            continue;
        };

        record_codex_completed_item(item, &mut last_agent_message, &mut last_reasoning_message);
    }

    let stats = SessionStats {
        added_lines: 0,
        deleted_lines: 0,
        diff_state: SessionDiffState::Unknown,
        input_tokens: total_input_tokens,
        output_tokens: total_output_tokens,
    };

    last_agent_message
        .or(last_reasoning_message)
        .map(|content| ParsedResponse {
            content,
            follow_up_contents: Vec::new(),
            stats,
        })
}

/// Adds token usage from one Codex turn completion event.
fn record_codex_turn_usage(
    event: &CodexEvent,
    total_input_tokens: &mut u64,
    total_output_tokens: &mut u64,
) {
    if event.event_type.as_deref() != Some("turn.completed") {
        return;
    }

    let Some(usage) = event.usage.as_ref() else {
        return;
    };

    *total_input_tokens += usage.input_tokens.unwrap_or(0).cast_unsigned();
    *total_output_tokens += usage.output_tokens.unwrap_or(0).cast_unsigned();
}

/// Records visible content from one completed Codex item event.
fn record_codex_completed_item(
    item: CodexItem,
    last_agent_message: &mut Option<String>,
    last_reasoning_message: &mut Option<String>,
) {
    let Some(text) = item.text.or(item.delta) else {
        return;
    };
    if is_codex_completion_status_message(&text) {
        return;
    }

    let item_type = item.item_type.as_deref().unwrap_or_default();
    if item_type == "agent_message" || item_type == "agentmessage" {
        last_agent_message.replace(text);

        return;
    }

    if item_type == "reasoning" || item_type == "thought" {
        last_reasoning_message.replace(text);
    }
}

/// Classifies one parsed Codex stream-line payload into display text and
/// content/progress type.
pub(super) fn parse_codex_stream_payload(
    stream_event: &serde_json::Value,
) -> Option<(String, bool)> {
    let event = CodexEvent::deserialize(stream_event).ok()?;
    let event_type = event.event_type.as_deref();
    if event_type == Some("item.started") {
        let item = event.item.as_ref()?;
        let item_type = item.item_type.as_deref()?;
        let progress_message = compact_codex_progress_message(item_type)?;

        return Some((progress_message, false));
    }

    if event_type == Some("item.updated") {
        let item = event.item.as_ref()?;
        let item_type = item.item_type.as_deref()?;
        if item_type == "agent_message"
            || item_type == "agentmessage"
            || item_type == "reasoning"
            || item_type == "thought"
        {
            let delta = item.delta.as_ref().or(item.text.as_ref())?.clone();
            let is_response_content = item_type == "agent_message" || item_type == "agentmessage";

            return Some((delta, is_response_content));
        }
    }

    if event_type != Some("item.completed") {
        return None;
    }

    let item = event.item?;
    let item_type = item.item_type.as_deref()?;
    if !(item_type == "agent_message"
        || item_type == "agentmessage"
        || item_type == "reasoning"
        || item_type == "thought")
    {
        return None;
    }

    let text = item.text?;
    if is_codex_completion_status_message(&text) {
        return None;
    }

    let is_response_content = item_type == "agent_message" || item_type == "agentmessage";

    Some((text, is_response_content))
}

fn parse_claude_response_payload(stdout: &str) -> Option<ParsedResponse> {
    let response = serde_json::from_str::<ClaudeResponse>(stdout).ok()?;
    let content = response
        .structured_output
        .map(|structured_output| structured_output.to_string())
        .or(response.result)?;
    let stats = SessionStats {
        added_lines: 0,
        deleted_lines: 0,
        diff_state: SessionDiffState::Unknown,
        input_tokens: response
            .usage
            .as_ref()
            .and_then(|usage| usage.input_tokens)
            .unwrap_or(0)
            .cast_unsigned(),
        output_tokens: response
            .usage
            .as_ref()
            .and_then(|usage| usage.output_tokens)
            .unwrap_or(0)
            .cast_unsigned(),
    };

    Some(ParsedResponse {
        content,
        follow_up_contents: Vec::new(),
        stats,
    })
}

/// Parses one Claude JSON-array payload and extracts the best assistant
/// result text and usage stats.
///
/// Newer CLI variants can emit one JSON array containing init/assistant/result
/// events rather than one flat object. This parser keeps the latest
/// schema-validated `structured_output` value, then the latest non-empty
/// `result` string, and otherwise falls back to assistant message text.
fn parse_claude_response_array_payload(stdout: &str) -> Option<ParsedResponse> {
    let events = serde_json::from_str::<serde_json::Value>(stdout).ok()?;
    let events = events.as_array()?;
    let mut latest_structured_output_content: Option<String> = None;
    let mut latest_result_content: Option<String> = None;
    let mut latest_assistant_content: Option<String> = None;
    let mut latest_stats: Option<SessionStats> = None;

    for event in events {
        if let Some(stats) = extract_claude_usage_stats(event) {
            latest_stats = Some(stats);
        }

        if let Some(result_content) = event.get("result").and_then(serde_json::Value::as_str)
            && !result_content.trim().is_empty()
        {
            latest_result_content = Some(result_content.to_string());
        }

        if let Some(structured_output) = event.get("structured_output")
            && !structured_output.is_null()
        {
            latest_structured_output_content = Some(structured_output.to_string());
        }

        if let Some(assistant_content) = extract_claude_stream_assistant_content(event) {
            latest_assistant_content = Some(assistant_content);
        }
    }

    let content = latest_structured_output_content
        .or(latest_result_content)
        .or(latest_assistant_content)?;
    let stats = latest_stats.unwrap_or_default();

    Some(ParsedResponse {
        content,
        follow_up_contents: Vec::new(),
        stats,
    })
}

/// Extracts Claude usage statistics from one JSON stream event.
fn extract_claude_usage_stats(stream_event: &serde_json::Value) -> Option<SessionStats> {
    let usage = stream_event.get("usage")?;

    Some(SessionStats {
        added_lines: 0,
        deleted_lines: 0,
        diff_state: SessionDiffState::Unknown,
        input_tokens: usage
            .get("input_tokens")
            .and_then(serde_json::Value::as_i64)
            .unwrap_or(0)
            .cast_unsigned(),
        output_tokens: usage
            .get("output_tokens")
            .and_then(serde_json::Value::as_i64)
            .unwrap_or(0)
            .cast_unsigned(),
    })
}

/// Extracts assistant text chunks from one Claude `stream-json` line.
///
/// Supports both legacy `{"type":"assistant","message":...}` events and newer
/// `{"type":"message",...}` assistant events. Text blocks are joined into one
/// displayable chunk.
fn extract_claude_stream_assistant_content(stream_event: &serde_json::Value) -> Option<String> {
    let message = extract_claude_stream_assistant_message(stream_event)?;
    if message.get("role").and_then(serde_json::Value::as_str) != Some("assistant") {
        return None;
    }

    if let Some(content) = message.get("content").and_then(serde_json::Value::as_str) {
        let trimmed_content = content.trim();
        if !trimmed_content.is_empty() {
            return Some(trimmed_content.to_string());
        }
    }

    let content_blocks = message
        .get("content")
        .and_then(serde_json::Value::as_array)?;
    let text = content_blocks
        .iter()
        .filter_map(extract_claude_stream_content_block_text)
        .collect::<Vec<_>>()
        .join("");
    if text.is_empty() {
        return None;
    }

    Some(text)
}

/// Resolves the assistant message payload from one Claude stream event.
///
/// Claude has emitted both nested assistant events (`type=assistant`) and
/// direct message events (`type=message`) across releases.
fn extract_claude_stream_assistant_message(
    stream_event: &serde_json::Value,
) -> Option<&serde_json::Value> {
    let event_type = stream_event
        .get("type")
        .and_then(serde_json::Value::as_str)?;
    match event_type {
        "assistant" => stream_event.get("message"),
        "message" => Some(stream_event),
        _ => None,
    }
}

/// Returns text from one Claude assistant content block when present.
///
/// Supports both direct text blocks and nested `delta.text` payloads used by
/// partial streaming updates.
fn extract_claude_stream_content_block_text(content_block: &serde_json::Value) -> Option<&str> {
    let block_type = content_block
        .get("type")
        .and_then(serde_json::Value::as_str)?;
    if block_type != "text" && block_type != "text_delta" {
        return None;
    }

    if let Some(text) = content_block
        .get("text")
        .and_then(serde_json::Value::as_str)
    {
        return Some(text);
    }

    content_block
        .get("delta")
        .and_then(|delta| delta.get("text"))
        .and_then(serde_json::Value::as_str)
}

fn compact_progress_message_from_json(stream_event: &serde_json::Value) -> Option<String> {
    let assistant_content_type = stream_event
        .get("message")
        .and_then(|message| message.get("content"))
        .and_then(serde_json::Value::as_array)
        .and_then(|content| {
            content.iter().find_map(|content_block| {
                content_block
                    .get("type")
                    .and_then(serde_json::Value::as_str)
            })
        });
    if let Some(progress_message) =
        assistant_content_type.and_then(compact_progress_message_from_stream_label)
    {
        return Some(progress_message);
    }

    let item_type = stream_event
        .get("item")
        .and_then(|item| item.get("type"))
        .and_then(serde_json::Value::as_str);
    if let Some(progress_message) = item_type.and_then(compact_progress_message_from_stream_label) {
        return Some(progress_message);
    }

    let tool_name = stream_event
        .get("tool_name")
        .and_then(serde_json::Value::as_str);
    if let Some(progress_message) = tool_name.and_then(compact_progress_message_from_stream_label) {
        return Some(progress_message);
    }

    let name = stream_event.get("name").and_then(serde_json::Value::as_str);
    if let Some(progress_message) = name.and_then(compact_progress_message_from_stream_label) {
        return Some(progress_message);
    }

    let tool_name = stream_event
        .get("tool")
        .and_then(|tool| tool.get("name"))
        .and_then(serde_json::Value::as_str);
    if let Some(progress_message) = tool_name.and_then(compact_progress_message_from_stream_label) {
        return Some(progress_message);
    }

    let event = stream_event
        .get("event")
        .and_then(serde_json::Value::as_str);
    if let Some(progress_message) = event.and_then(compact_progress_message_from_stream_label) {
        return Some(progress_message);
    }

    let subtype = stream_event
        .get("subtype")
        .and_then(serde_json::Value::as_str);
    if let Some(progress_message) = subtype.and_then(compact_progress_message_from_stream_label) {
        return Some(progress_message);
    }

    let event_type = stream_event.get("type").and_then(serde_json::Value::as_str);
    if let Some(progress_message) = event_type.and_then(compact_progress_message_from_stream_label)
    {
        return Some(progress_message);
    }

    None
}

/// Maps one provider stream label to a compact user-facing progress message.
///
/// This intentionally recognizes broad families of labels because provider
/// stream payloads evolve over time and may rename internal phases while still
/// describing the same user-visible activity.
fn compact_progress_message_from_stream_label(label: &str) -> Option<String> {
    let normalized_label = label.to_ascii_lowercase().replace('-', "_");
    if normalized_label.contains("search") {
        return Some("Searching the web".to_string());
    }

    if normalized_label.contains("compact") || normalized_label.contains("compress") {
        return Some("Compacting context".to_string());
    }

    if normalized_label.contains("reasoning")
        || normalized_label.contains("thinking")
        || normalized_label.contains("thought")
    {
        return Some("Thinking".to_string());
    }

    if normalized_label.contains("command")
        || normalized_label.contains("bash")
        || normalized_label.contains("terminal")
        || normalized_label.contains("shell")
        || normalized_label.contains("tool_use")
        || normalized_label.contains("tool_call")
        || normalized_label.contains("toolcall")
        || normalized_label.contains("execute")
    {
        return Some("Running a command".to_string());
    }

    None
}

/// Maps a Codex item type to a compact progress message for the UI.
///
/// Returns `None` for `agent_message` since it carries response content, not
/// progress.
pub(crate) fn compact_codex_progress_message(item_type: &str) -> Option<String> {
    match item_type {
        "agent_message" => None,
        "command_execution" => Some("Running a command".to_string()),
        "context_compaction" => Some("Compacting context".to_string()),
        "reasoning" | "thought" => Some("Thinking".to_string()),
        "web_search" => Some("Searching the web".to_string()),
        other => Some(format!("Working: {}", other.replace('_', " "))),
    }
}

/// Returns whether a Codex `agent_message` is a synthetic completion status.
///
/// These short status lines are emitted for internal tool/reasoning steps and
/// should not be rendered as chat content.
pub(crate) fn is_codex_completion_status_message(message: &str) -> bool {
    let normalized_message = message.trim().trim_end_matches('.').to_ascii_lowercase();

    matches!(
        normalized_message.as_str(),
        "command completed"
            | "command execution completed"
            | "thinking completed"
            | "reasoning completed"
            | "search completed"
            | "web search completed"
    )
}

fn fallback_response(stdout: &str, stderr: &str) -> String {
    let trimmed_stdout = stdout.trim();
    if trimmed_stdout.is_empty() {
        return stderr.trim().to_string();
    }

    trimmed_stdout.to_string()
}

#[cfg(test)]
#[path = "response_parser_test.rs"]
mod tests;