vtcode-core 0.143.1

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
use crate::exec::events::{
    AgentMessageItem, ErrorItem, ItemCompletedEvent, ItemStartedEvent, ItemUpdatedEvent, ReasoningItem, ThreadEvent,
    ThreadItem, ThreadItemDetails, ToolCallStatus, ToolInvocationItem, ToolOutcome, ToolOutputItem,
    tool_outcome_from_status,
};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt::Write;

#[derive(Debug, Clone, Default)]
struct StreamingTextState {
    item_id: Option<String>,
    text: String,
    started: bool,
}

#[derive(Debug, Clone)]
struct ToolCallStreamState {
    item_id: String,
    name: Option<String>,
    arguments: String,
    started: bool,
    /// Bytes of `arguments` included in the last emitted `item.updated` event.
    /// Used to throttle per-token delta emissions — see `MIN_TOOL_ARG_UPDATE_BYTES`.
    last_emitted_args_len: usize,
    /// Number of intermediate `item.updated` events emitted for this tool call.
    /// Capped at `MAX_TOOL_ARG_UPDATE_EVENTS` to bound log growth for large arguments.
    update_events: usize,
}

/// Minimum accumulated bytes of tool-call arguments between two `item.updated`
/// events. Without this, every streaming argument delta (one per token) emits a
/// full-arguments update, producing ~30+ events per tool call and bloating the
/// session log (observed 3069 `item.updated` events for 98 tool outputs in a
/// single 3-turn session). The final `complete_tool_call` always emits the full
/// arguments, so intermediate updates are progress hints only.
const MIN_TOOL_ARG_UPDATE_BYTES: usize = 512;

/// Maximum intermediate `item.updated` events per tool call. Once reached, no
/// further streaming updates are emitted until the tool call completes.
const MAX_TOOL_ARG_UPDATE_EVENTS: usize = 8;

#[derive(Debug, Clone, PartialEq, Eq)]
/// Aggregated output from a tool execution, containing either inline text or a
/// spool file reference.
pub struct ToolOutputPayload {
    /// Combined output text from the tool execution.
    pub aggregated_output: String,
    /// Optional path to a spool file containing the full output.
    pub spool_path: Option<String>,
}

fn pluralize<'a>(count: u64, singular: &'a str, plural: &'a str) -> &'a str {
    if count == 1 { singular } else { plural }
}

fn trimmed_string_field<'a>(output: &'a Value, key: &str) -> Option<&'a str> {
    output
        .get(key)
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|text| !text.is_empty())
}

#[cold]
fn trimmed_error_message(output: &Value) -> Option<&str> {
    match output.get("error") {
        Some(Value::String(message)) => Some(message.as_str()),
        Some(Value::Object(error)) => error.get("message").and_then(Value::as_str),
        _ => None,
    }
    .map(str::trim)
    .filter(|text| !text.is_empty())
}

fn sample_strings_from_objects(items: &[Value], keys: &[&str], limit: usize) -> Vec<String> {
    let mut samples = Vec::new();

    for item in items {
        let Some(value) = keys
            .iter()
            .find_map(|key| item.get(*key).and_then(Value::as_str))
            .map(str::trim)
            .filter(|text| !text.is_empty())
        else {
            continue;
        };

        if samples.iter().any(|sample| sample == value) {
            continue;
        }

        samples.push(value.to_string());
        if samples.len() >= limit {
            break;
        }
    }

    samples
}

fn match_path_text(item: &Value) -> Option<&str> {
    item.get("path")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .or_else(|| {
            item.get("file")
                .and_then(Value::as_str)
                .map(str::trim)
                .filter(|text| !text.is_empty())
        })
        .or_else(|| {
            item.get("data")
                .and_then(Value::as_object)
                .and_then(|data| data.get("path"))
                .and_then(Value::as_object)
                .and_then(|path| path.get("text"))
                .and_then(Value::as_str)
                .map(str::trim)
                .filter(|text| !text.is_empty())
        })
}

fn sample_match_paths(matches: &[Value], limit: usize) -> Vec<String> {
    let mut samples = Vec::new();

    for item in matches {
        let Some(path) = match_path_text(item) else {
            continue;
        };

        if samples.iter().any(|sample| sample == path) {
            continue;
        }

        samples.push(path.to_string());
        if samples.len() >= limit {
            break;
        }
    }

    samples
}

fn summarize_list_items(output: &Value, items: &[Value]) -> String {
    let total = output
        .get("total")
        .or_else(|| output.get("count"))
        .and_then(Value::as_u64)
        .unwrap_or(items.len() as u64);

    let (files, directories) =
        items
            .iter()
            .fold((0u64, 0u64), |(files, directories), item| match item.get("type").and_then(Value::as_str) {
                Some("file") => (files + 1, directories),
                Some("directory") => (files, directories + 1),
                _ => (files, directories),
            });

    let mut summary = format!("Listed {total} {}", pluralize(total, "item", "items"));
    if files > 0 || directories > 0 {
        let _ = write!(
            summary,
            " ({} {}, {} {})",
            files,
            pluralize(files, "file", "files"),
            directories,
            pluralize(directories, "directory", "directories"),
        );
    }

    let samples = sample_strings_from_objects(items, &["path", "name"], 3);
    if !samples.is_empty() {
        let _ = write!(summary, ": {}", samples.join(", "));
    }

    summary
}

fn summarize_file_list(output: &Value, files: &[Value]) -> String {
    let total = output.get("total").and_then(Value::as_u64).unwrap_or(files.len() as u64);
    let mut summary = format!("Listed {total} {}", pluralize(total, "file", "files"));

    let samples = files
        .iter()
        .filter_map(Value::as_str)
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .take(3)
        .map(str::to_string)
        .collect::<Vec<_>>();
    if !samples.is_empty() {
        let _ = write!(summary, ": {}", samples.join(", "));
    }

    summary
}

fn summarize_matches(output: &Value, matches: &[Value]) -> String {
    let total = output
        .get("total_match_count")
        .or_else(|| output.get("matched_count"))
        .or_else(|| output.get("count"))
        .and_then(Value::as_u64)
        .unwrap_or(matches.len() as u64);

    if total == 0 {
        return "No matches found".to_string();
    }

    let mut summary = format!("Found {total} {}", pluralize(total, "match", "matches"));

    let samples = sample_match_paths(matches, 3);
    if !samples.is_empty() {
        let _ = write!(summary, " in {}", samples.join(", "));
    } else if let Some(path) = trimmed_string_field(output, "path") {
        let _ = write!(summary, " in {path}");
    }

    summary
}

fn append_unique_line(lines: &mut Vec<String>, line: &str) {
    if !lines.iter().any(|existing| existing == line) {
        lines.push(line.to_string());
    }
}

/// Extract a [`ToolOutputPayload`] from a tool result JSON value, preferring
/// spool path references and falling back to inline text aggregation.
pub fn tool_output_payload_from_value(output: &Value) -> ToolOutputPayload {
    if let Some(spool_path) = output.get("spool_path").and_then(Value::as_str) {
        return ToolOutputPayload {
            aggregated_output: String::new(),
            spool_path: Some(spool_path.to_string()),
        };
    }

    let mut primary_text = Vec::new();
    for key in ["output", "stdout", "stderr", "content"] {
        if let Some(text) = trimmed_string_field(output, key) {
            append_unique_line(&mut primary_text, text);
        }
    }

    if !primary_text.is_empty() {
        return ToolOutputPayload {
            aggregated_output: primary_text.join("\n"),
            spool_path: None,
        };
    }

    let structured_summary = if let Some(items) = output.get("items").and_then(Value::as_array) {
        Some(summarize_list_items(output, items))
    } else if let Some(files) = output.get("files").and_then(Value::as_array) {
        Some(summarize_file_list(output, files))
    } else if let Some(matches) = output.get("matches").and_then(Value::as_array) {
        Some(summarize_matches(output, matches))
    } else {
        output
            .as_object()
            .map(|obj| {
                obj.keys()
                    .filter(|key| key.as_str() != "success")
                    .take(4)
                    .cloned()
                    .collect::<Vec<_>>()
            })
            .filter(|keys| !keys.is_empty())
            .map(|keys| format!("Structured result with fields: {}", keys.join(", ")))
    };

    let mut parts = Vec::new();
    if let Some(summary) = structured_summary.as_deref() {
        append_unique_line(&mut parts, summary);
    }
    if let Some(text) = trimmed_error_message(output) {
        append_unique_line(&mut parts, text);
    }
    for key in ["message", "critical_note", "hint", "next_action"] {
        if let Some(text) = trimmed_string_field(output, key) {
            append_unique_line(&mut parts, text);
        }
    }

    ToolOutputPayload {
        aggregated_output: parts.join("\n"),
        spool_path: None,
    }
}

/// Shared lifecycle state for assistant text, reasoning, and model-emitted tool calls.
#[derive(Debug, Default)]
pub struct SharedLifecycleEmitter {
    next_item_index: u64,
    assistant: StreamingTextState,
    reasoning: StreamingTextState,
    reasoning_stage: Option<String>,
    tool_calls: HashMap<String, ToolCallStreamState>,
    pending_events: Vec<ThreadEvent>,
}

impl SharedLifecycleEmitter {
    /// Generate the next unique item ID for lifecycle events.
    #[must_use]
    pub fn next_item_id(&mut self) -> String {
        let id = self.next_item_index;
        self.next_item_index += 1;
        format!("item_{id}")
    }

    /// Emit a completed agent message event with the full text.
    pub fn emit_completed_agent_message(&mut self, text: &str) {
        if text.trim().is_empty() {
            return;
        }
        let item_id = self.next_item_id();
        self.pending_events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
            item: ThreadItem {
                id: item_id,
                details: ThreadItemDetails::AgentMessage(AgentMessageItem { text: text.to_string() }),
            },
        }));
    }

    /// Replace the current assistant streaming text. Returns `true` if the text changed.
    pub fn replace_assistant_text(&mut self, text: &str) -> bool {
        replace_stream_text(&mut self.assistant, text)
    }

    /// Whether the assistant text stream has been started.
    #[must_use]
    pub fn assistant_started(&self) -> bool {
        self.assistant.started
    }

    /// Length of the accumulated assistant text in bytes.
    #[must_use]
    pub fn assistant_len(&self) -> usize {
        self.assistant.text.len()
    }

    /// Append a delta to the assistant text stream. Returns `true` if content was added.
    pub fn append_assistant_delta(&mut self, delta: &str) -> bool {
        append_stream_delta(&mut self.assistant, delta)
    }

    /// Emit a snapshot of the current assistant text as an item event.
    pub fn emit_assistant_snapshot(&mut self, item_id: Option<String>) -> bool {
        let item_id = item_id.unwrap_or_else(|| self.next_item_id());
        emit_text_snapshot(&mut self.pending_events, &mut self.assistant, item_id, |text| {
            ThreadItemDetails::AgentMessage(AgentMessageItem { text })
        })
    }

    /// Complete the assistant text stream, emitting a final completed event.
    pub fn complete_assistant_stream(&mut self) -> bool {
        complete_text_stream(&mut self.pending_events, &mut self.assistant, |text| {
            ThreadItemDetails::AgentMessage(AgentMessageItem { text })
        })
    }

    /// Emit a completed reasoning event with the full text.
    pub fn emit_completed_reasoning(&mut self, text: &str) {
        if text.trim().is_empty() {
            return;
        }
        let item_id = self.next_item_id();
        self.pending_events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
            item: ThreadItem {
                id: item_id,
                details: ThreadItemDetails::Reasoning(ReasoningItem {
                    text: text.to_string(),
                    stage: self.reasoning_stage.clone(),
                }),
            },
        }));
    }

    /// Replace the current reasoning streaming text. Returns `true` if the text changed.
    pub fn replace_reasoning_text(&mut self, text: &str) -> bool {
        replace_stream_text(&mut self.reasoning, text)
    }

    /// Append a delta to the reasoning text stream. Returns `true` if content was added.
    pub fn append_reasoning_delta(&mut self, delta: &str) -> bool {
        append_stream_delta(&mut self.reasoning, delta)
    }

    /// Update the reasoning stage label. Returns `true` if the stage changed.
    pub fn set_reasoning_stage(&mut self, stage: Option<String>) -> bool {
        if self.reasoning_stage == stage {
            return false;
        }
        self.reasoning_stage = stage;
        true
    }

    /// Length of the accumulated reasoning text in bytes.
    #[must_use]
    pub fn reasoning_len(&self) -> usize {
        self.reasoning.text.len()
    }

    /// Whether the reasoning text stream has been started.
    #[must_use]
    pub fn reasoning_started(&self) -> bool {
        self.reasoning.started
    }

    /// Emit a snapshot of the current reasoning text as an item event.
    pub fn emit_reasoning_snapshot(&mut self, item_id: Option<String>) -> bool {
        let item_id = item_id.unwrap_or_else(|| self.next_item_id());
        let stage = self.reasoning_stage.clone();
        emit_text_snapshot(&mut self.pending_events, &mut self.reasoning, item_id, move |text| {
            ThreadItemDetails::Reasoning(ReasoningItem { text, stage: stage.clone() })
        })
    }

    /// Emit an update event reflecting the current reasoning stage.
    pub fn emit_reasoning_stage_update(&mut self) -> bool {
        if !self.reasoning.started {
            return false;
        }
        let Some(item_id) = self.reasoning.item_id.clone() else {
            return false;
        };
        self.pending_events.push(ThreadEvent::ItemUpdated(ItemUpdatedEvent {
            item: ThreadItem {
                id: item_id,
                details: ThreadItemDetails::Reasoning(ReasoningItem {
                    text: self.reasoning.text.clone(),
                    stage: self.reasoning_stage.clone(),
                }),
            },
        }));
        true
    }

    /// Complete the reasoning text stream, emitting a final completed event.
    pub fn complete_reasoning_stream(&mut self) -> bool {
        let stage = self.reasoning_stage.clone();
        complete_text_stream(&mut self.pending_events, &mut self.reasoning, move |text| {
            ThreadItemDetails::Reasoning(ReasoningItem { text, stage: stage.clone() })
        })
    }

    /// Start tracking a tool call, emitting an item-started event.
    pub fn start_tool_call(&mut self, call_id: &str, tool_name: Option<String>, item_id: Option<String>) -> bool {
        let generated_item_id = item_id.unwrap_or_else(|| self.next_item_id());
        let buffer = self
            .tool_calls
            .entry(call_id.to_string())
            .or_insert_with(|| ToolCallStreamState {
                item_id: generated_item_id,
                name: None,
                arguments: String::new(),
                started: false,
                last_emitted_args_len: 0,
                update_events: 0,
            });

        if buffer.name.is_none() {
            buffer.name = tool_name;
        }
        if buffer.started {
            return false;
        }

        buffer.started = true;
        self.pending_events.push(tool_started_event(
            buffer.item_id.clone(),
            buffer.name.as_deref().unwrap_or_default(),
            None,
            Some(call_id),
        ));
        true
    }

    /// Append an argument delta to an in-progress tool call.
    pub fn append_tool_call_delta(
        &mut self,
        call_id: &str,
        delta: &str,
        tool_name: Option<String>,
        item_id: Option<String>,
    ) -> bool {
        if delta.is_empty() {
            return false;
        }

        let generated_item_id = item_id.unwrap_or_else(|| self.next_item_id());
        let buffer = self
            .tool_calls
            .entry(call_id.to_string())
            .or_insert_with(|| ToolCallStreamState {
                item_id: generated_item_id,
                name: None,
                arguments: String::new(),
                started: false,
                last_emitted_args_len: 0,
                update_events: 0,
            });

        if !buffer.started {
            buffer.started = true;
            if buffer.name.is_none() {
                buffer.name = tool_name;
            }
            self.pending_events.push(tool_started_event(
                buffer.item_id.clone(),
                buffer.name.as_deref().unwrap_or_default(),
                None,
                Some(call_id),
            ));
        } else if buffer.name.is_none() {
            buffer.name = tool_name;
        }

        buffer.arguments.push_str(delta);
        // Throttle intermediate `item.updated` events: emit the first delta
        // eagerly (so the UI shows progress), then only when enough new bytes
        // have accumulated and the per-call cap hasn't been reached. The final
        // `complete_tool_call` always emits the full arguments regardless.
        let new_len = buffer.arguments.len();
        let should_emit = buffer.update_events == 0
            || (buffer.update_events < MAX_TOOL_ARG_UPDATE_EVENTS
                && new_len.saturating_sub(buffer.last_emitted_args_len) >= MIN_TOOL_ARG_UPDATE_BYTES);
        if should_emit {
            buffer.last_emitted_args_len = new_len;
            buffer.update_events += 1;
            let arguments = progress_tool_arguments(&buffer.arguments);
            self.pending_events.push(tool_invocation_updated_event(
                buffer.item_id.clone(),
                buffer.name.as_deref().unwrap_or_default(),
                Some(&arguments),
                Some(call_id),
                ToolCallStatus::InProgress,
            ));
        }
        true
    }

    pub fn complete_tool_call(&mut self, call_id: &str, status: ToolCallStatus, outcome: Option<ToolOutcome>) -> bool {
        let Some(buffer) = self.tool_calls.remove(call_id) else {
            return false;
        };
        if !buffer.started {
            return false;
        }

        let arguments = if buffer.arguments.is_empty() {
            None
        } else {
            Some(progress_tool_arguments(&buffer.arguments))
        };
        let resolved_outcome = outcome.unwrap_or_else(|| tool_outcome_from_status(&status));
        self.pending_events.push(tool_invocation_completed_event(
            buffer.item_id,
            buffer.name.as_deref().unwrap_or_default(),
            arguments.as_ref(),
            Some(call_id),
            status,
            resolved_outcome,
        ));
        true
    }

    #[must_use]
    pub fn tool_call_item_id(&self, call_id: &str) -> Option<&str> {
        self.tool_calls.get(call_id).map(|buffer| buffer.item_id.as_str())
    }

    pub fn sync_tool_call_arguments(
        &mut self,
        call_id: &str,
        arguments: &str,
        tool_name: Option<String>,
        item_id: Option<String>,
    ) -> bool {
        let generated_item_id = item_id.unwrap_or_else(|| self.next_item_id());
        let buffer = self
            .tool_calls
            .entry(call_id.to_string())
            .or_insert_with(|| ToolCallStreamState {
                item_id: generated_item_id,
                name: None,
                arguments: String::new(),
                started: false,
                last_emitted_args_len: 0,
                update_events: 0,
            });

        if buffer.name.is_none() {
            buffer.name = tool_name;
        }

        if !buffer.started {
            buffer.started = true;
            self.pending_events.push(tool_started_event(
                buffer.item_id.clone(),
                buffer.name.as_deref().unwrap_or_default(),
                None,
                Some(call_id),
            ));
        }

        if buffer.arguments == arguments {
            return false;
        }

        buffer.arguments.clear();
        buffer.arguments.push_str(arguments);
        let args = progress_tool_arguments(&buffer.arguments);
        self.pending_events.push(tool_invocation_updated_event(
            buffer.item_id.clone(),
            buffer.name.as_deref().unwrap_or_default(),
            Some(&args),
            Some(call_id),
            ToolCallStatus::InProgress,
        ));
        buffer.last_emitted_args_len = buffer.arguments.len();
        buffer.update_events = buffer.update_events.saturating_add(1);
        true
    }

    pub fn complete_open_items(&mut self) {
        self.complete_open_text_items();
        self.complete_open_tool_calls_with_status(ToolCallStatus::Completed);
    }

    pub fn complete_open_text_items(&mut self) {
        let _ = self.complete_assistant_stream();
        let _ = self.complete_reasoning_stream();
    }

    pub fn complete_open_items_with_tool_status(&mut self, status: ToolCallStatus) {
        self.complete_open_text_items();
        self.complete_open_tool_calls_with_status(status);
    }

    pub fn complete_open_tool_calls_with_status(&mut self, status: ToolCallStatus) {
        let call_ids = self.tool_calls.keys().cloned().collect::<Vec<_>>();
        for call_id in call_ids {
            let _ = self.complete_tool_call(&call_id, status.clone(), None);
        }
    }

    /// Emit a final `item.updated` carrying the full accumulated arguments for
    /// each open tool call, bypassing the intermediate-update throttle.
    ///
    /// Tool calls remain open (not completed); callers complete them via
    /// [`Self::complete_tool_call`] when execution finishes. This guarantees
    /// the authoritative streamed arguments are visible after streaming ends
    /// even when intermediate deltas were throttled (e.g. small tool calls
    /// whose completing delta fell below the byte threshold). Updates that
    /// would carry the same length as the last emitted snapshot are skipped
    /// to avoid redundant events for large tool calls whose last intermediate
    /// update already captured the full arguments.
    pub fn flush_open_tool_call_arguments(&mut self) {
        let call_ids: Vec<String> = self.tool_calls.keys().cloned().collect();
        for call_id in call_ids {
            let Some(buffer) = self.tool_calls.get_mut(&call_id) else {
                continue;
            };
            if buffer.arguments.is_empty() || buffer.last_emitted_args_len == buffer.arguments.len() {
                continue;
            }
            let arguments = progress_tool_arguments(&buffer.arguments);
            self.pending_events.push(tool_invocation_updated_event(
                buffer.item_id.clone(),
                buffer.name.as_deref().unwrap_or_default(),
                Some(&arguments),
                Some(&call_id),
                ToolCallStatus::InProgress,
            ));
            buffer.last_emitted_args_len = buffer.arguments.len();
        }
    }

    #[must_use]
    pub fn drain_events(&mut self) -> Vec<ThreadEvent> {
        std::mem::take(&mut self.pending_events)
    }
}

fn replace_stream_text(state: &mut StreamingTextState, text: &str) -> bool {
    if state.text == text {
        return false;
    }
    state.text.clear();
    state.text.push_str(text);
    true
}

fn append_stream_delta(state: &mut StreamingTextState, delta: &str) -> bool {
    if delta.is_empty() {
        return false;
    }
    state.text.push_str(delta);
    true
}

fn emit_text_snapshot(
    pending_events: &mut Vec<ThreadEvent>,
    state: &mut StreamingTextState,
    item_id: String,
    build_details: impl FnOnce(String) -> ThreadItemDetails,
) -> bool {
    if state.text.trim().is_empty() {
        return false;
    }

    let item_id = state.item_id.get_or_insert(item_id).clone();
    let item = ThreadItem {
        id: item_id,
        details: build_details(state.text.clone()),
    };

    if state.started {
        pending_events.push(ThreadEvent::ItemUpdated(ItemUpdatedEvent { item }));
    } else {
        state.started = true;
        pending_events.push(ThreadEvent::ItemStarted(ItemStartedEvent { item }));
    }
    true
}

fn complete_text_stream(
    pending_events: &mut Vec<ThreadEvent>,
    state: &mut StreamingTextState,
    build_details: impl FnOnce(String) -> ThreadItemDetails,
) -> bool {
    if !state.started {
        return false;
    }

    let Some(item_id) = state.item_id.take() else {
        state.started = false;
        state.text.clear();
        return false;
    };

    state.started = false;
    let text = std::mem::take(&mut state.text);
    pending_events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
        item: ThreadItem { id: item_id, details: build_details(text) },
    }));
    true
}

#[must_use]
pub fn tool_output_item_id(call_item_id: &str) -> String {
    format!("{call_item_id}:output")
}

fn tool_invocation_item(
    item_id: String,
    tool_name: &str,
    arguments: Option<&Value>,
    tool_call_id: Option<&str>,
    status: ToolCallStatus,
    outcome: Option<ToolOutcome>,
) -> ThreadItem {
    ThreadItem {
        id: item_id,
        details: ThreadItemDetails::ToolInvocation(ToolInvocationItem {
            tool_name: tool_name.to_string(),
            arguments: arguments.cloned(),
            tool_call_id: tool_call_id.map(str::to_string),
            status,
            outcome,
        }),
    }
}

fn tool_output_item(
    call_item_id: &str,
    tool_call_id: Option<&str>,
    status: ToolCallStatus,
    exit_code: Option<i32>,
    spool_path: Option<&str>,
    output: impl Into<String>,
) -> ThreadItem {
    ThreadItem {
        id: tool_output_item_id(call_item_id),
        details: ThreadItemDetails::ToolOutput(ToolOutputItem {
            call_id: call_item_id.to_string(),
            tool_call_id: tool_call_id.map(str::to_string),
            spool_path: spool_path.map(str::to_string),
            output: output.into(),
            exit_code,
            status,
        }),
    }
}

#[must_use]
pub fn tool_started_event(
    item_id: String,
    tool_name: &str,
    arguments: Option<&Value>,
    tool_call_id: Option<&str>,
) -> ThreadEvent {
    ThreadEvent::ItemStarted(ItemStartedEvent {
        item: tool_invocation_item(item_id, tool_name, arguments, tool_call_id, ToolCallStatus::InProgress, None),
    })
}

#[must_use]
pub fn tool_invocation_updated_event(
    item_id: String,
    tool_name: &str,
    arguments: Option<&Value>,
    tool_call_id: Option<&str>,
    status: ToolCallStatus,
) -> ThreadEvent {
    ThreadEvent::ItemUpdated(ItemUpdatedEvent {
        item: tool_invocation_item(item_id, tool_name, arguments, tool_call_id, status, None),
    })
}

#[must_use]
pub fn tool_invocation_completed_event(
    item_id: String,
    tool_name: &str,
    arguments: Option<&Value>,
    tool_call_id: Option<&str>,
    status: ToolCallStatus,
    outcome: ToolOutcome,
) -> ThreadEvent {
    ThreadEvent::ItemCompleted(ItemCompletedEvent {
        item: tool_invocation_item(item_id, tool_name, arguments, tool_call_id, status, Some(outcome)),
    })
}

#[must_use]
pub fn tool_output_started_event(call_item_id: String, tool_call_id: Option<&str>) -> ThreadEvent {
    ThreadEvent::ItemStarted(ItemStartedEvent {
        item: tool_output_item(&call_item_id, tool_call_id, ToolCallStatus::InProgress, None, None, String::new()),
    })
}

#[must_use]
pub fn tool_output_updated_event(
    call_item_id: String,
    tool_call_id: Option<&str>,
    output: impl Into<String>,
) -> ThreadEvent {
    ThreadEvent::ItemUpdated(ItemUpdatedEvent {
        item: tool_output_item(&call_item_id, tool_call_id, ToolCallStatus::InProgress, None, None, output),
    })
}

#[must_use]
pub fn tool_output_completed_event(
    call_item_id: String,
    tool_call_id: Option<&str>,
    status: ToolCallStatus,
    exit_code: Option<i32>,
    spool_path: Option<&str>,
    output: impl Into<String>,
) -> ThreadEvent {
    ThreadEvent::ItemCompleted(ItemCompletedEvent {
        item: tool_output_item(&call_item_id, tool_call_id, status, exit_code, spool_path, output),
    })
}

#[must_use]
#[cold]
pub fn error_item_completed_event(item_id: String, message: impl Into<String>) -> ThreadEvent {
    ThreadEvent::ItemCompleted(ItemCompletedEvent {
        item: ThreadItem {
            id: item_id,
            details: ThreadItemDetails::Error(ErrorItem { message: message.into() }),
        },
    })
}

fn progress_tool_arguments(arguments: &str) -> Value {
    serde_json::from_str(arguments).unwrap_or_else(|_| Value::String(arguments.to_string()))
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn tool_started_event_omits_arguments_when_absent() {
        let event = tool_started_event("item".to_string(), "shell", None, Some("call_1"));
        let ThreadEvent::ItemStarted(ItemStartedEvent { item }) = event else {
            panic!("expected started item");
        };
        let ThreadItemDetails::ToolInvocation(details) = item.details else {
            panic!("expected tool invocation");
        };
        assert!(details.arguments.is_none());
        assert_eq!(details.tool_name, "shell");
    }

    #[test]
    fn tool_output_updated_event_streams_in_progress_output() {
        let event = tool_output_updated_event("item".to_string(), Some("call_1"), "abc");
        let ThreadEvent::ItemUpdated(ItemUpdatedEvent { item }) = event else {
            panic!("expected updated item");
        };
        let ThreadItemDetails::ToolOutput(details) = item.details else {
            panic!("expected tool output");
        };
        assert_eq!(details.call_id, "item");
        assert_eq!(details.tool_call_id.as_deref(), Some("call_1"));
        assert_eq!(details.output, "abc");
        assert_eq!(details.status, ToolCallStatus::InProgress);
    }

    #[test]
    fn tool_output_payload_preserves_spool_reference() {
        let payload = tool_output_payload_from_value(&json!({
            "spool_path": ".vtcode/context/tool_outputs/run-1.txt",
            "output": "ignored"
        }));

        assert_eq!(payload.aggregated_output, "");
        assert_eq!(payload.spool_path.as_deref(), Some(".vtcode/context/tool_outputs/run-1.txt"));
    }

    #[test]
    fn tool_output_payload_summarizes_list_results() {
        let payload = tool_output_payload_from_value(&json!({
            "items": [
                {"name": "app.rs", "path": "vtcode-tui/src/app.rs", "type": "file"},
                {"name": "core_tui", "path": "vtcode-tui/src/core_tui", "type": "directory"},
                {"name": "lib.rs", "path": "vtcode-tui/src/lib.rs", "type": "file"}
            ],
            "count": 3,
            "total": 11
        }));

        assert_eq!(payload.spool_path, None);
        assert!(payload.aggregated_output.contains("Listed 11 items"));
        assert!(payload.aggregated_output.contains("2 files, 1 directory"));
        assert!(payload.aggregated_output.contains("vtcode-tui/src/app.rs"));
    }

    #[test]
    fn tool_output_payload_combines_list_summary_with_message() {
        let payload = tool_output_payload_from_value(&json!({
            "items": [
                {"name": "app.rs", "path": "vtcode-tui/src/app.rs", "type": "file"},
                {"name": "core_tui", "path": "vtcode-tui/src/core_tui", "type": "directory"}
            ],
            "count": 2,
            "total": 2,
            "message": "[+3 more items]"
        }));

        assert!(payload.aggregated_output.contains("Listed 2 items"));
        assert!(payload.aggregated_output.contains("[+3 more items]"));
    }

    #[test]
    fn tool_output_payload_summarizes_match_results() {
        let payload = tool_output_payload_from_value(&json!({
            "matches": [
                {"path": "src/main.rs", "line_number": 12},
                {"file": "src/lib.rs", "line_number": 9}
            ],
            "total_match_count": 7
        }));

        assert_eq!(payload.spool_path, None);
        assert!(payload.aggregated_output.contains("Found 7 matches"));
        assert!(payload.aggregated_output.contains("src/main.rs"));
        assert!(payload.aggregated_output.contains("src/lib.rs"));
    }

    #[test]
    fn tool_output_payload_summarizes_nested_match_paths() {
        let payload = tool_output_payload_from_value(&json!({
            "matches": [
                {
                    "type": "match",
                    "data": {
                        "path": {"text": "vtcode-tui/src/core_tui/runner/mod.rs"},
                        "line_number": 27,
                        "lines": {"text": "runloop\n"}
                    }
                }
            ],
            "total_match_count": 1
        }));

        assert!(payload.aggregated_output.contains("Found 1 match"));
        assert!(payload.aggregated_output.contains("vtcode-tui/src/core_tui/runner/mod.rs"));
    }

    #[test]
    fn tool_output_payload_reports_empty_match_set() {
        let payload = tool_output_payload_from_value(&json!({
            "matches": [],
            "path": "crates/codegen/vtcode-core/src"
        }));

        assert_eq!(payload.aggregated_output, "No matches found");
        assert_eq!(payload.spool_path, None);
    }

    #[test]
    fn tool_output_payload_includes_structured_recovery_guidance() {
        let payload = tool_output_payload_from_value(&json!({
            "matches": [],
            "path": "src/agent",
            "hint": "Pattern looks like a code fragment.",
            "next_action": "Retry with a larger parseable pattern."
        }));

        assert!(payload.aggregated_output.contains("No matches found"));
        assert!(payload.aggregated_output.contains("Pattern looks like a code fragment."));
        assert!(payload.aggregated_output.contains("Retry with a larger parseable pattern."));
    }

    #[test]
    fn tool_invocation_completed_event_embeds_outcome() {
        let event = tool_invocation_completed_event(
            "tool_1".to_string(),
            "exec_command",
            Some(&json!({"cmd": "pwd"})),
            Some("call_1"),
            ToolCallStatus::Failed,
            ToolOutcome::HookDenied,
        );
        let ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) = event else {
            panic!("expected completed item");
        };
        let ThreadItemDetails::ToolInvocation(details) = item.details else {
            panic!("expected tool invocation");
        };
        assert_eq!(details.status, ToolCallStatus::Failed);
        assert_eq!(details.outcome, Some(ToolOutcome::HookDenied));
    }

    #[test]
    fn complete_tool_call_infers_outcome_from_status() {
        let mut emitter = SharedLifecycleEmitter::default();
        let call_id = "call_1".to_string();
        emitter.start_tool_call(&call_id, Some("exec_command".to_string()), None);
        emitter.sync_tool_call_arguments(&call_id, "{\"cmd\":\"pwd\"}", Some("exec_command".to_string()), None);
        emitter.complete_tool_call(&call_id, ToolCallStatus::Completed, None);
        let events = emitter.drain_events();
        // events[0] = tool_started, events[1] = tool_invocation_updated, events[2] = tool_invocation_completed
        let ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) = &events[2] else {
            panic!("expected completed item at index 2, got {:?}", events[0]);
        };
        let ThreadItemDetails::ToolInvocation(details) = &item.details else {
            panic!("expected tool invocation");
        };
        assert_eq!(details.outcome, Some(ToolOutcome::Success));
    }

    #[test]
    fn append_tool_call_delta_throttles_intermediate_updates() {
        let mut emitter = SharedLifecycleEmitter::default();
        let call_id = "call_t".to_string();
        emitter.start_tool_call(&call_id, Some("exec_command".to_string()), None);
        // Clear the ItemStarted event so we only count delta-driven ItemUpdated events.
        let _ = emitter.drain_events();

        // Send 600 one-byte deltas. The first delta always emits (update_events == 0).
        // Subsequent deltas only emit after MIN_TOOL_ARG_UPDATE_BYTES (512) new bytes.
        // Expected ItemUpdated events: at 1 byte (first) and at 513 bytes (threshold met).
        for _ in 0..600 {
            emitter.append_tool_call_delta(&call_id, "x", None, None);
        }
        let events = emitter.drain_events();
        let item_updated_count = events.iter().filter(|e| matches!(e, ThreadEvent::ItemUpdated(_))).count();
        assert_eq!(
            item_updated_count, 2,
            "expected 2 throttled ItemUpdated events for 600 1-byte deltas, got {item_updated_count}"
        );

        // The complete event must still carry the full accumulated arguments.
        emitter.complete_tool_call(&call_id, ToolCallStatus::Completed, None);
        let events = emitter.drain_events();
        let completed = events
            .iter()
            .find_map(|e| {
                if let ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) = e {
                    Some(item)
                } else {
                    None
                }
            })
            .expect("should have a completed event");
        let ThreadItemDetails::ToolInvocation(details) = &completed.details else {
            panic!("expected tool invocation in completed event");
        };
        assert!(
            details.arguments.as_ref().is_some_and(|a| a.to_string().contains("xxx")),
            "completed event should carry the full accumulated arguments"
        );
    }

    #[test]
    fn append_tool_call_delta_caps_intermediate_update_events() {
        let mut emitter = SharedLifecycleEmitter::default();
        let call_id = "call_c".to_string();
        emitter.start_tool_call(&call_id, Some("exec_command".to_string()), None);
        let _ = emitter.drain_events();

        // Send 5000 one-byte deltas. With MIN_TOOL_ARG_UPDATE_BYTES=512 and
        // MAX_TOOL_ARG_UPDATE_EVENTS=8, emissions stop after 8 updates even
        // though the threshold keeps being met.
        for _ in 0..5000 {
            emitter.append_tool_call_delta(&call_id, "x", None, None);
        }
        let events = emitter.drain_events();
        let item_updated_count = events.iter().filter(|e| matches!(e, ThreadEvent::ItemUpdated(_))).count();
        assert_eq!(
            item_updated_count, MAX_TOOL_ARG_UPDATE_EVENTS,
            "intermediate updates should be capped at MAX_TOOL_ARG_UPDATE_EVENTS, got {item_updated_count}"
        );
    }

    #[test]
    fn flush_open_tool_call_arguments_emits_full_args_for_throttled_small_calls() {
        let mut emitter = SharedLifecycleEmitter::default();
        let call_id = "call_flush".to_string();
        emitter.start_tool_call(&call_id, Some("shell".to_string()), None);
        let _ = emitter.drain_events();

        // Stream a small JSON tool call in two deltas. The first delta emits
        // eagerly (incomplete JSON); the second is below the byte threshold
        // and is throttled out.
        emitter.append_tool_call_delta(&call_id, "{\"cmd\":\"ec", None, None);
        emitter.append_tool_call_delta(&call_id, "ho hi\"}", None, None);
        let intermediate = emitter.drain_events();
        let intermediate_updated = intermediate.iter().filter(|e| matches!(e, ThreadEvent::ItemUpdated(_))).count();
        assert_eq!(intermediate_updated, 1, "first delta emits one eager update");

        // Flush should emit a final update with the full, valid-JSON arguments.
        emitter.flush_open_tool_call_arguments();
        let flushed = emitter.drain_events();
        let updated = flushed
            .iter()
            .filter_map(|e| {
                if let ThreadEvent::ItemUpdated(ItemUpdatedEvent { item }) = e {
                    Some(&item.details)
                } else {
                    None
                }
            })
            .next_back();
        let ThreadItemDetails::ToolInvocation(details) = updated.expect("flush should emit an update") else {
            panic!("expected tool invocation update");
        };
        assert_eq!(
            details.arguments.as_ref().and_then(|a| a.get("cmd")).and_then(|c| c.as_str()),
            Some("echo hi"),
            "flush should carry the full accumulated arguments"
        );
        // Tool call should still be open (no completed event).
        assert!(flushed.iter().all(|e| !matches!(e, ThreadEvent::ItemCompleted(_))));
    }

    #[test]
    fn flush_open_tool_call_arguments_skips_redundant_flush() {
        let mut emitter = SharedLifecycleEmitter::default();
        let call_id = "call_skip".to_string();
        emitter.start_tool_call(&call_id, Some("shell".to_string()), None);
        let _ = emitter.drain_events();

        // A single large delta (>= MIN_TOOL_ARG_UPDATE_BYTES) emits with the
        // full arguments, so the last_emitted_args_len already equals the
        // accumulated length. A subsequent flush should be a no-op.
        let big = "x".repeat(MIN_TOOL_ARG_UPDATE_BYTES);
        emitter.append_tool_call_delta(&call_id, &big, None, None);
        let _ = emitter.drain_events();

        emitter.flush_open_tool_call_arguments();
        let flushed = emitter.drain_events();
        assert!(flushed.is_empty(), "flush should skip when the last update already carried the full arguments");
    }
}