-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtranscript.rs
More file actions
1626 lines (1379 loc) · 51.5 KB
/
transcript.rs
File metadata and controls
1626 lines (1379 loc) · 51.5 KB
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
//! Core types for chat transcript
//!
//! This module contains the types that represent the conversation transcript.
//! A Transcript contains Turns, and each Turn contains Blocks.
#![allow(dead_code)]
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use chrono::{DateTime, Utc};
#[cfg(feature = "cli")]
use ratatui::{
style::{Color, Modifier, Style},
text::{Line, Span},
};
use serde::{ser::SerializeStruct, Deserialize, Serialize};
#[cfg(feature = "cli")]
use crate::compaction::CompactionBlock;
use crate::config::{CODEY_DIR, TRANSCRIPTS_DIR};
#[cfg(feature = "cli")]
use crate::tools::io::{format_for_user, DEFAULT_TAB_WIDTH};
/// Global counter for unique block IDs
static NEXT_BLOCK_ID: AtomicUsize = AtomicUsize::new(1);
/// Generate a unique block ID
pub fn next_block_id() -> usize {
NEXT_BLOCK_ID.fetch_add(1, Ordering::Relaxed)
}
/// Role of the message sender
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
User,
Assistant,
System,
}
/// Status of a message, tool, or action
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
Pending,
Running,
Complete,
Error,
Denied,
Cancelled,
}
/// Block type identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockType {
Text,
Thinking,
Tool,
Compaction,
}
/// Get the transcripts directory path, creating it if necessary
fn get_transcripts_dir() -> std::io::Result<PathBuf> {
let dir = PathBuf::from(CODEY_DIR).join(TRANSCRIPTS_DIR);
if !dir.exists() {
std::fs::create_dir_all(&dir)?;
}
Ok(dir)
}
/// Find the latest transcript number by scanning the transcripts directory
fn find_latest_transcript_number(dir: &Path) -> Option<u32> {
std::fs::read_dir(dir)
.ok()?
.filter_map(|entry| entry.ok())
.filter_map(|entry| {
let name = entry.file_name();
let name = name.to_str()?;
if name.ends_with(".json") {
name.trim_end_matches(".json").parse::<u32>().ok()
} else {
None
}
})
.max()
}
/// Get the path for a transcript with a given number
fn transcript_path(dir: &Path, number: u32) -> PathBuf {
dir.join(format!("{:06}.json", number))
}
/// Trait for all blocks in a turn
#[typetag::serde(tag = "type")]
pub trait Block: Send + Sync {
/// Get the kind of this block
fn kind(&self) -> BlockType;
/// Render this block to terminal lines with given width for wrapping (CLI only)
#[cfg(feature = "cli")]
fn render(&self, width: u16) -> Vec<Line<'_>>;
/// Get the block's unique ID (0 if unassigned)
fn id(&self) -> usize {
0
}
/// Set the block's ID (called by container when adding)
fn set_id(&mut self, _id: usize) {}
/// Get the status of this block
fn status(&self) -> Status;
/// Set the status of this block
fn set_status(&mut self, status: Status);
/// Whether this block is ephemeral (rendered but not persisted)
/// Ephemeral blocks are filtered out during serialization.
fn is_ephemeral(&self) -> bool {
false
}
/// Render status icon with appropriate color (CLI only)
#[cfg(feature = "cli")]
fn render_status(&self) -> Span<'static> {
let (icon, color) = match self.status() {
Status::Pending => ("? ", Color::Yellow),
Status::Running => ("⚙ ", Color::Blue),
Status::Complete => ("✓ ", Color::Green),
Status::Error => ("✗ ", Color::Red),
Status::Denied => ("⊘ ", Color::DarkGray),
Status::Cancelled => ("⊘ ", Color::Yellow),
};
Span::styled(icon, Style::default().fg(color))
}
/// Append text content to this block (for streaming)
fn append_text(&mut self, _text: &str) {}
/// Get the text content of this block (for restoring agent context)
fn text(&self) -> Option<&str> {
None
}
/// Get the tool call ID (for restoring agent context)
fn call_id(&self) -> Option<&str> {
None
}
/// Get the tool name (for restoring agent context)
fn tool_name(&self) -> Option<&str> {
None
}
/// Get the tool params (for restoring agent context)
fn params(&self) -> Option<&serde_json::Value> {
None
}
/// Set the agent label (for sub-agent tools)
fn set_agent_label(&mut self, _label: String) {}
/// Get the agent label (for sub-agent tools)
fn agent_label(&self) -> Option<&str> {
None
}
}
/// Macro to implement common Block trait methods for blocks with text and status fields
#[macro_export]
macro_rules! impl_base_block {
($block_type:expr) => {
fn kind(&self) -> BlockType {
$block_type
}
fn id(&self) -> usize {
self.id
}
fn set_id(&mut self, id: usize) {
self.id = id;
}
fn status(&self) -> Status {
self.status
}
fn set_status(&mut self, status: Status) {
self.status = status;
}
fn append_text(&mut self, text: &str) {
self.text.push_str(text);
}
fn text(&self) -> Option<&str> {
Some(&self.text)
}
};
}
/// Macro for tool blocks that don't have their own ID field.
/// These blocks use call_id for identification instead.
#[macro_export]
macro_rules! impl_tool_block {
($block_type:expr) => {
fn kind(&self) -> BlockType {
$block_type
}
fn status(&self) -> Status {
self.status
}
fn set_status(&mut self, status: Status) {
self.status = status;
}
fn append_text(&mut self, text: &str) {
self.text.push_str(text);
}
fn text(&self) -> Option<&str> {
Some(&self.text)
}
};
}
/// Macro to define a complete tool block with minimal boilerplate.
///
/// This macro generates the struct definition, constructors, and Block trait
/// implementation. You only need to provide the custom header rendering logic.
///
/// # Usage
///
/// ```ignore
/// define_tool_block! {
/// /// Doc comment for the block
/// pub struct MyToolBlock {
/// // Maximum lines to show in result output (default: 10)
/// max_lines: 5,
/// // Type to validate params against
/// params_type: MyToolParams,
/// // Custom header rendering - returns Vec<Span>
/// render_header(self, params) {
/// vec![
/// Span::styled("my_tool", Style::default().fg(Color::Magenta)),
/// Span::styled("(", Style::default().fg(Color::DarkGray)),
/// Span::styled(params["arg"].as_str().unwrap_or(""), Style::default().fg(Color::Cyan)),
/// Span::styled(")", Style::default().fg(Color::DarkGray)),
/// ]
/// }
/// }
/// }
/// ```
#[macro_export]
macro_rules! define_tool_block {
(
$(#[$attr:meta])*
$vis:vis struct $name:ident {
max_lines: $max_lines:expr,
params_type: $params_type:ty,
render_header($self:ident, $params:ident) $render_body:block
}
) => {
$(#[$attr])*
#[derive(Debug, Clone, Serialize, Deserialize)]
$vis struct $name {
pub call_id: String,
pub tool_name: String,
pub params: serde_json::Value,
pub status: Status,
pub text: String,
#[serde(default)]
pub background: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent_label: Option<String>,
}
impl $name {
pub fn new(
call_id: impl Into<String>,
tool_name: impl Into<String>,
params: serde_json::Value,
background: bool,
) -> Self {
Self {
call_id: call_id.into(),
tool_name: tool_name.into(),
params,
status: Status::Pending,
text: String::new(),
background,
agent_label: None,
}
}
pub fn from_params(
call_id: &str,
tool_name: &str,
params: serde_json::Value,
background: bool,
) -> Option<Self> {
let _: $params_type = serde_json::from_value(params.clone()).ok()?;
Some(Self::new(call_id, tool_name, params, background))
}
#[allow(unused_variables)]
fn render_header_spans(&$self) -> Vec<Span<'static>> {
let $params = &$self.params;
$render_body
}
}
#[typetag::serde]
impl Block for $name {
$crate::impl_tool_block!(BlockType::Tool);
fn render(&self, _width: u16) -> Vec<Line<'_>> {
let mut lines = Vec::new();
// Build header line: status + agent_label + prefix + custom spans
let mut spans = vec![
self.render_status(),
render_agent_label(self.agent_label.as_deref()),
render_prefix(self.background),
];
spans.extend(self.render_header_spans());
lines.push(Line::from(spans));
// Approval prompt if pending
if self.status == Status::Pending {
lines.push(render_approval_prompt());
}
// Result output
if !self.text.is_empty() {
lines.extend(render_result(&self.text, $max_lines));
}
// Denied message
if self.status == Status::Denied {
lines.push(Line::from(Span::styled(
" Denied by user",
Style::default().fg(Color::DarkGray),
)));
}
lines
}
fn call_id(&self) -> Option<&str> {
Some(&self.call_id)
}
fn tool_name(&self) -> Option<&str> {
Some(&self.tool_name)
}
fn params(&self) -> Option<&serde_json::Value> {
Some(&self.params)
}
fn set_agent_label(&mut self, label: String) {
self.agent_label = Some(label);
}
fn agent_label(&self) -> Option<&str> {
self.agent_label.as_deref()
}
}
};
}
/// Macro for simple tool blocks without agent_label support.
/// Used for internal tools like list_agents, get_agent, list_background_tasks, etc.
#[macro_export]
macro_rules! define_simple_tool_block {
(
$(#[$attr:meta])*
$vis:vis struct $name:ident {
max_lines: $max_lines:expr,
render_header($self:ident, $params:ident) $render_body:block
}
) => {
$(#[$attr])*
#[derive(Debug, Clone, Serialize, Deserialize)]
$vis struct $name {
pub call_id: String,
pub tool_name: String,
pub params: serde_json::Value,
pub status: Status,
pub text: String,
#[serde(default)]
pub background: bool,
}
impl $name {
pub fn new(
call_id: impl Into<String>,
tool_name: impl Into<String>,
params: serde_json::Value,
background: bool,
) -> Self {
Self {
call_id: call_id.into(),
tool_name: tool_name.into(),
params,
status: Status::Pending,
text: String::new(),
background,
}
}
#[allow(unused_variables)]
fn render_header_spans(&$self) -> Vec<Span<'static>> {
let $params = &$self.params;
$render_body
}
}
#[typetag::serde]
impl Block for $name {
$crate::impl_tool_block!(BlockType::Tool);
fn render(&self, _width: u16) -> Vec<Line<'_>> {
let mut lines = Vec::new();
// Build header line: status + prefix + custom spans
let mut spans = vec![
self.render_status(),
render_prefix(self.background),
];
spans.extend(self.render_header_spans());
lines.push(Line::from(spans));
// Approval prompt if pending
if self.status == Status::Pending {
lines.push(render_approval_prompt());
}
// Result output
if !self.text.is_empty() {
lines.extend(render_result(&self.text, $max_lines));
}
// Denied message
if self.status == Status::Denied {
lines.push(Line::from(Span::styled(
" Denied by user",
Style::default().fg(Color::DarkGray),
)));
}
lines
}
fn call_id(&self) -> Option<&str> {
Some(&self.call_id)
}
fn tool_name(&self) -> Option<&str> {
Some(&self.tool_name)
}
fn params(&self) -> Option<&serde_json::Value> {
Some(&self.params)
}
}
};
}
/// Simple text content
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextBlock {
#[serde(default = "next_block_id")]
pub id: usize,
pub text: String,
pub status: Status,
}
impl TextBlock {
// TODO Delete `new` and force using a keyword to create
pub fn new(text: impl Into<String>) -> Self {
Self {
id: next_block_id(),
text: text.into(),
status: Status::Running,
}
}
pub fn pending(text: impl Into<String>) -> Self {
Self {
id: next_block_id(),
text: text.into(),
status: Status::Pending,
}
}
pub fn complete(text: impl Into<String>) -> Self {
Self {
id: next_block_id(),
text: text.into(),
status: Status::Complete,
}
}
}
#[typetag::serde]
impl Block for TextBlock {
impl_base_block!(BlockType::Text);
#[cfg(feature = "cli")]
fn render(&self, width: u16) -> Vec<Line<'_>> {
// Use ratskin for markdown rendering
let skin = ratskin::RatSkin::default();
let text = ratskin::RatSkin::parse_text(&self.text);
skin.parse(text, width)
}
}
/// Thinking/reasoning content (extended thinking)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThinkingBlock {
#[serde(default = "next_block_id")]
pub id: usize,
pub text: String,
pub status: Status,
}
impl ThinkingBlock {
pub fn new(text: impl Into<String>) -> Self {
Self {
id: next_block_id(),
text: text.into(),
status: Status::Running,
}
}
}
#[typetag::serde]
impl Block for ThinkingBlock {
impl_base_block!(BlockType::Thinking);
#[cfg(feature = "cli")]
fn render(&self, width: u16) -> Vec<Line<'_>> {
let mut lines = Vec::new();
let style = Style::default()
.fg(Color::DarkGray)
.add_modifier(Modifier::ITALIC);
let wrapped = textwrap::wrap(&self.text, width as usize);
for line in wrapped {
lines.push(Line::from(Span::styled(line, style)));
}
lines
}
}
/// Generic tool content (fallback for tools without specialized display)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolBlock {
#[serde(default = "next_block_id")]
pub id: usize,
pub call_id: String,
pub name: String,
pub params: serde_json::Value,
pub status: Status,
pub text: String,
/// If true, tool runs in background
#[serde(default)]
pub background: bool,
/// Agent label for sub-agent tools
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent_label: Option<String>,
}
impl ToolBlock {
pub fn new(
call_id: impl Into<String>,
name: impl Into<String>,
params: serde_json::Value,
background: bool,
) -> Self {
Self {
id: next_block_id(),
call_id: call_id.into(),
name: name.into(),
params,
status: Status::Pending,
text: String::new(),
background,
agent_label: None,
}
}
}
#[typetag::serde]
impl Block for ToolBlock {
impl_base_block!(BlockType::Tool);
#[cfg(feature = "cli")]
fn render(&self, _width: u16) -> Vec<Line<'_>> {
let mut lines = Vec::new();
// Tool name with status icon, optional agent label, and optional [bg] prefix
lines.push(Line::from(vec![
self.render_status(),
render_agent_label(self.agent_label.as_deref()),
render_prefix(self.background),
Span::styled(
&self.name,
Style::default()
.fg(Color::Magenta)
.add_modifier(Modifier::BOLD),
),
]));
// Params
let params_str = serde_json::to_string_pretty(&self.params).unwrap_or_default();
for param_line in params_str.lines().take(10) {
lines.push(Line::from(Span::styled(
format!(" {}", param_line),
Style::default().fg(Color::DarkGray),
)));
}
if params_str.lines().count() > 10 {
lines.push(Line::from(Span::styled(
" ...",
Style::default().fg(Color::DarkGray),
)));
}
// Approval prompt if pending
if self.status == Status::Pending {
lines.push(render_approval_prompt());
}
// Result if completed
if !self.text.is_empty() {
lines.extend(render_result(&self.text, 5));
}
// Denied message
if self.status == Status::Denied {
lines.push(Line::from(Span::styled(
" Denied by user",
Style::default().fg(Color::DarkGray),
)));
}
lines
}
fn call_id(&self) -> Option<&str> {
Some(&self.call_id)
}
fn tool_name(&self) -> Option<&str> {
Some(&self.name)
}
fn params(&self) -> Option<&serde_json::Value> {
Some(&self.params)
}
fn set_agent_label(&mut self, label: String) {
self.agent_label = Some(label);
}
fn agent_label(&self) -> Option<&str> {
self.agent_label.as_deref()
}
}
/// Notification block for mid-turn injected messages
/// These are ephemeral - rendered but not persisted to the transcript.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationBlock {
#[serde(default = "next_block_id")]
pub id: usize,
pub source: String,
pub text: String,
#[serde(skip_deserializing, default = "NotificationBlock::default_status")]
status: Status,
}
impl NotificationBlock {
pub fn new(source: impl Into<String>, text: impl Into<String>) -> Self {
Self {
id: next_block_id(),
source: source.into(),
text: text.into(),
status: Status::Complete,
}
}
fn default_status() -> Status {
Status::Complete
}
}
#[typetag::serde]
impl Block for NotificationBlock {
impl_base_block!(BlockType::Text);
fn is_ephemeral(&self) -> bool {
true // Key difference - not persisted
}
#[cfg(feature = "cli")]
fn render(&self, _width: u16) -> Vec<Line<'_>> {
// Single line: » source: text
vec![Line::from(vec![
Span::styled("» ", Style::default().fg(Color::Yellow)),
Span::styled(&self.text, Style::default().fg(Color::Yellow)),
])]
}
}
/// Helper: render prefix for background tools - "[bg] " if true, empty otherwise
#[cfg(feature = "cli")]
pub fn render_prefix(background: bool) -> Span<'static> {
if background {
Span::styled("[bg] ", Style::default().fg(Color::Cyan))
} else {
Span::raw("")
}
}
/// Helper: render agent label prefix for sub-agent tools
#[cfg(feature = "cli")]
pub fn render_agent_label(label: Option<&str>) -> Span<'static> {
match label {
Some(l) => Span::styled(format!("[{}] ", l), Style::default().fg(Color::Cyan)),
None => Span::raw(""),
}
}
/// Helper: render approval prompt
#[cfg(feature = "cli")]
pub fn render_approval_prompt() -> Line<'static> {
Line::from(vec![
Span::styled(" [", Style::default().fg(Color::DarkGray)),
Span::styled(
"y",
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
),
Span::styled("]es [", Style::default().fg(Color::DarkGray)),
Span::styled(
"n",
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
),
Span::styled("]o", Style::default().fg(Color::DarkGray)),
])
}
/// Helper: render result with line limit
#[cfg(feature = "cli")]
pub fn render_result(result: &str, max_lines: usize) -> Vec<Line<'static>> {
let mut lines = Vec::new();
let preview_lines: Vec<&str> = result.lines().take(max_lines).collect();
for line in &preview_lines {
let formatted = format_for_user(line, DEFAULT_TAB_WIDTH);
lines.push(Line::from(Span::styled(
format!(" {}", formatted),
Style::default().fg(Color::DarkGray),
)));
}
if result.lines().count() > max_lines {
lines.push(Line::from(Span::styled(
" ...",
Style::default().fg(Color::DarkGray),
)));
}
lines
}
/// Staging area for pending blocks (notifications, approvals) awaiting consumption.
/// Similar to Turn but without role/timestamp - blocks here haven't entered the conversation yet.
#[derive(Default)]
pub struct Stage {
blocks: Vec<Box<dyn Block>>,
}
impl Stage {
pub fn new() -> Self {
Self { blocks: Vec::new() }
}
/// Add a block to staging, returns its ID
pub fn push(&mut self, block: Box<dyn Block>) -> usize {
let id = block.id();
self.blocks.push(block);
id
}
/// Get a block by ID
pub fn get(&self, id: usize) -> Option<&Box<dyn Block>> {
self.blocks.iter().find(|b| b.id() == id)
}
/// Get a mutable block by ID
pub fn get_mut(&mut self, id: usize) -> Option<&mut Box<dyn Block>> {
self.blocks.iter_mut().find(|b| b.id() == id)
}
/// Remove and return a block by ID (for promotion to transcript)
pub fn remove(&mut self, id: usize) -> Option<Box<dyn Block>> {
if let Some(pos) = self.blocks.iter().position(|b| b.id() == id) {
Some(self.blocks.remove(pos))
} else {
None
}
}
/// Check if staging is empty
pub fn is_empty(&self) -> bool {
self.blocks.is_empty()
}
/// Number of staged blocks
pub fn len(&self) -> usize {
self.blocks.len()
}
/// Iterate over blocks (for rendering)
pub fn iter(&self) -> impl Iterator<Item = &Box<dyn Block>> {
self.blocks.iter()
}
/// Drain all blocks (for batch promotion)
pub fn drain_all(&mut self) -> Vec<Box<dyn Block>> {
self.blocks.drain(..).collect()
}
/// Find a tool block by call_id and return mutable reference
pub fn find_by_call_id(&mut self, call_id: &str) -> Option<&mut Box<dyn Block>> {
self.blocks.iter_mut().find(|b| b.call_id() == Some(call_id))
}
/// Remove a tool block by call_id (for promotion to transcript)
pub fn remove_by_call_id(&mut self, call_id: &str) -> Option<Box<dyn Block>> {
if let Some(pos) = self.blocks.iter().position(|b| b.call_id() == Some(call_id)) {
Some(self.blocks.remove(pos))
} else {
None
}
}
/// Render all staged blocks with given width (CLI only)
#[cfg(feature = "cli")]
pub fn render(&self, width: u16) -> Vec<Line<'_>> {
let mut lines = Vec::new();
for (i, block) in self.blocks.iter().enumerate() {
lines.extend(block.render(width));
// Add blank line between blocks (but not after last)
if i < self.blocks.len() - 1 {
lines.push(Line::from(""));
}
}
lines
}
}
/// A turn in the conversation - one user or assistant response
#[derive(Deserialize)]
pub struct Turn {
pub id: usize,
pub role: Role,
pub content: Vec<Box<dyn Block>>,
pub timestamp: DateTime<Utc>,
/// Index of the currently active (streaming) block, if any
#[serde(skip)]
pub active_block_idx: Option<usize>,
}
/// Custom serialization that filters out ephemeral blocks
impl Serialize for Turn {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
// Filter out ephemeral blocks before serializing
let persistent_content: Vec<&Box<dyn Block>> =
self.content.iter().filter(|b| !b.is_ephemeral()).collect();
let mut state = serializer.serialize_struct("Turn", 4)?;
state.serialize_field("id", &self.id)?;
state.serialize_field("role", &self.role)?;
state.serialize_field("content", &persistent_content)?;
state.serialize_field("timestamp", &self.timestamp)?;
state.end()
}
}
impl Turn {
pub fn new(id: usize, role: Role, content: Vec<Box<dyn Block>>) -> Self {
Self {
id,
role,
content,
timestamp: Utc::now(),
active_block_idx: None,
}
}
/// Add a block and return its index
pub fn add_block(&mut self, block: Box<dyn Block>) -> usize {
let idx = self.content.len();
self.content.push(block);
idx
}
/// Append text to a specific block by index
pub fn append_to_block(&mut self, idx: usize, text: &str) {
if let Some(block) = self.content.get_mut(idx) {
block.append_text(text);
}
}
/// Get a mutable block by index
pub fn get_block_mut(&mut self, idx: usize) -> Option<&mut (dyn Block + 'static)> {
self.content.get_mut(idx).map(|b| b.as_mut())
}
/// Mark a block as complete by index
pub fn complete_block(&mut self, idx: usize) {
if let Some(block) = self.get_block_mut(idx) {
block.set_status(Status::Complete);
}
}
/// Check if the active block matches the expected type
pub fn is_active_block_type(&self, expected: BlockType) -> bool {
self.active_block_idx
.and_then(|idx| self.content.get(idx))
.map(|block| block.kind() == expected)
.unwrap_or(false)
}
/// Start a new block (completes previous active block if any)
pub fn start_block(&mut self, block: Box<dyn Block>) -> usize {
if let Some(prev_idx) = self.active_block_idx {
self.complete_block(prev_idx);
}
let idx = self.add_block(block);
self.active_block_idx = Some(idx);
idx
}
/// Append text to the currently active block
pub fn append_to_active(&mut self, text: &str) {
if let Some(idx) = self.active_block_idx {
self.append_to_block(idx, text);
}
}
/// Get a mutable reference to the active block
pub fn get_active_block_mut(&mut self) -> Option<&mut (dyn Block + 'static)> {
self.active_block_idx
.and_then(|idx| self.get_block_mut(idx))
}
/// Render all blocks with given width (CLI only)
#[cfg(feature = "cli")]
pub fn render(&self, width: u16) -> Vec<Line<'_>> {
let mut lines = Vec::new();
for (i, block) in self.content.iter().enumerate() {
lines.extend(block.render(width));
// Add blank line between blocks (but not after last)
if i < self.content.len() - 1 {
lines.push(Line::from(""));
}
}
lines
}
}
/// The chat transcript - display log of all turns for UI rendering
#[derive(Serialize, Deserialize)]
pub struct Transcript {
turns: Vec<Turn>,
next_id: usize,
#[serde(skip)]
path: Option<PathBuf>,
/// ID of the current turn being streamed to (if any)
#[serde(skip)]
current_turn_id: Option<usize>,
/// Staging area for pending blocks
#[serde(skip)]
pub stage: Stage,
}
impl Transcript {
/// Create a new transcript with a specific path
pub fn with_path(path: PathBuf) -> Self {