yoyo-agent 0.1.7

A coding agent that evolves itself. Born as 200 lines of Rust, growing up in public.
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
//! Spinner, ToolProgressTimer, ThinkBlockFilter.

use super::*;
use std::io::{self, Write};
use std::sync::Arc;
use std::time::{Duration, Instant};
use yoagent::types::{Content, ToolResult};

pub const SPINNER_FRAMES: &[char] = &['', '', '', '', '', '', '', '', '', ''];

/// Get the spinner frame for a given tick index (wraps around).
pub fn spinner_frame(tick: usize) -> char {
    SPINNER_FRAMES[tick % SPINNER_FRAMES.len()]
}

/// A handle to a running spinner task. Dropping or calling `stop()` cancels it.
pub struct Spinner {
    cancel: tokio::sync::watch::Sender<bool>,
    handle: Option<tokio::task::JoinHandle<()>>,
}

impl Spinner {
    /// Start a spinner that prints frames to stderr every 100ms.
    /// The spinner shows `⠋ thinking...` cycling through braille characters.
    pub fn start() -> Self {
        let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
        let handle = tokio::spawn(async move {
            let mut tick: usize = 0;
            loop {
                // Check cancellation before printing
                if *cancel_rx.borrow() {
                    // Clear the spinner line
                    eprint!("\r\x1b[K");
                    break;
                }
                let frame = spinner_frame(tick);
                eprint!("\r{DIM}  {frame} thinking...{RESET}");
                tick = tick.wrapping_add(1);

                // Wait 100ms or until cancelled
                tokio::select! {
                    _ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {}
                    _ = cancel_rx.changed() => {
                        // Clear the spinner line
                        eprint!("\r\x1b[K");
                        break;
                    }
                }
            }
        });
        Self {
            cancel: cancel_tx,
            handle: Some(handle),
        }
    }

    /// Stop the spinner and clear its output.
    /// Clears the spinner line directly (don't rely on the async task to clear,
    /// since abort() can race with the clear sequence).
    ///
    /// render_latency_budget: This is the first-token cost (~0.1ms).
    /// The synchronous eprint + flush ensures the spinner line is cleared
    /// before any stdout text appears. The async handle abort is deferred
    /// to Drop to minimize latency on the critical path.
    pub fn stop(self) {
        let _ = self.cancel.send(true);
        // Clear the spinner line from the calling thread — this is synchronous
        // and guaranteed to complete before any subsequent stdout writes.
        eprint!("\r\x1b[K");
        let _ = io::stderr().flush();
        // Defer handle.abort() to Drop — it interacts with the tokio runtime
        // and doesn't need to complete before the first text token is printed.
        // The cancel signal already ensures the spinner task won't write again.
    }
}

impl Drop for Spinner {
    fn drop(&mut self) {
        let _ = self.cancel.send(true);
        // Clear the spinner line synchronously on drop too
        eprint!("\r\x1b[K");
        let _ = io::stderr().flush();
        if let Some(handle) = self.handle.take() {
            handle.abort();
        }
    }
}

// --- Live tool progress display ---

/// Format a live progress line for a running tool.
///
/// Shows spinner frame, tool name, elapsed time, and optional line count.
/// Example: `  ⠹ bash ⏱ 12s` or `  ⠹ bash ⏱ 1m 5s (142 lines)`
pub fn format_tool_progress(
    tool_name: &str,
    elapsed: Duration,
    tick: usize,
    line_count: Option<usize>,
) -> String {
    let frame = spinner_frame(tick);
    let time_str = format_duration_live(elapsed);
    let lines_str = match line_count {
        Some(n) if n > 0 => {
            let word = pluralize(n, "line", "lines");
            format!(" ({n} {word})")
        }
        _ => String::new(),
    };
    format!("{DIM}  {frame} {tool_name}{time_str}{lines_str}{RESET}")
}

/// Format elapsed duration for live display (compact, human-friendly).
///
/// - Under 60s: `5s`
/// - 60s+: `1m 5s`
/// - 60m+: `1h 2m`
pub fn format_duration_live(d: Duration) -> String {
    let secs = d.as_secs();
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        let m = secs / 60;
        let s = secs % 60;
        if s == 0 {
            format!("{m}m")
        } else {
            format!("{m}m {s}s")
        }
    } else {
        let h = secs / 3600;
        let m = (secs % 3600) / 60;
        if m == 0 {
            format!("{h}h")
        } else {
            format!("{h}h {m}m")
        }
    }
}

/// Format the last N lines of partial output for live display.
///
/// Returns dimmed, indented lines showing the tail of tool output.
/// Used to give users a preview of what a running command is producing.
/// Empty input returns empty string.
pub fn format_partial_tail(output: &str, max_lines: usize) -> String {
    if output.is_empty() || max_lines == 0 {
        return String::new();
    }
    let lines: Vec<&str> = output.lines().collect();
    let total = lines.len();
    let start = total.saturating_sub(max_lines);
    let tail: Vec<&str> = lines[start..].to_vec();

    let mut result = String::new();
    if start > 0 {
        let skipped = start;
        let word = pluralize(skipped, "line", "lines");
        result.push_str(&format!("{DIM}    ┆ ... {skipped} {word} above{RESET}\n"));
    }
    for line in tail {
        let truncated = truncate_with_ellipsis(line, 120);
        result.push_str(&format!("{DIM}{truncated}{RESET}\n"));
    }
    // Remove trailing newline
    if result.ends_with('\n') {
        result.pop();
    }
    result
}

/// Count the number of lines in a tool result's text content.
pub fn count_result_lines(result: &ToolResult) -> usize {
    result
        .content
        .iter()
        .filter_map(|c| match c {
            Content::Text { text } => Some(text.lines().count()),
            _ => None,
        })
        .sum()
}

/// Extract all text content from a ToolResult as a single string.
pub fn extract_result_text(result: &ToolResult) -> String {
    result
        .content
        .iter()
        .filter_map(|c| match c {
            Content::Text { text } => Some(text.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// A handle to a running tool-progress timer task.
/// Shows `  ⠹ bash ⏱ 12s` on stderr, updating every second.
/// Dropping or calling `stop()` cancels it and clears the line.
pub struct ToolProgressTimer {
    cancel: tokio::sync::watch::Sender<bool>,
    line_count: Arc<std::sync::atomic::AtomicUsize>,
    handle: Option<tokio::task::JoinHandle<()>>,
}

impl ToolProgressTimer {
    /// Start a timer that shows elapsed time for a tool on stderr.
    /// Updates every second with the current line count.
    pub fn start(tool_name: String) -> Self {
        let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
        let line_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let line_count_clone = Arc::clone(&line_count);
        let handle = tokio::spawn(async move {
            let start = Instant::now();
            let mut tick: usize = 0;
            // Wait 2 seconds before showing the timer — short commands
            // finish fast and don't need a progress display.
            tokio::select! {
                _ = tokio::time::sleep(Duration::from_secs(2)) => {}
                _ = cancel_rx.changed() => {
                    return;
                }
            }
            loop {
                if *cancel_rx.borrow() {
                    eprint!("\r\x1b[K");
                    let _ = io::stderr().flush();
                    break;
                }
                let elapsed = start.elapsed();
                let lc = line_count_clone.load(std::sync::atomic::Ordering::Relaxed);
                let lc_opt = if lc > 0 { Some(lc) } else { None };
                let progress = format_tool_progress(&tool_name, elapsed, tick, lc_opt);
                eprint!("\r\x1b[K{progress}");
                let _ = io::stderr().flush();
                tick = tick.wrapping_add(1);

                tokio::select! {
                    _ = tokio::time::sleep(Duration::from_millis(500)) => {}
                    _ = cancel_rx.changed() => {
                        eprint!("\r\x1b[K");
                        let _ = io::stderr().flush();
                        break;
                    }
                }
            }
        });
        Self {
            cancel: cancel_tx,
            line_count,
            handle: Some(handle),
        }
    }

    /// Update the line count shown in the timer display.
    pub fn set_line_count(&self, count: usize) {
        self.line_count
            .store(count, std::sync::atomic::Ordering::Relaxed);
    }

    /// Stop the timer and clear its output.
    pub fn stop(self) {
        let _ = self.cancel.send(true);
        eprint!("\r\x1b[K");
        let _ = io::stderr().flush();
    }
}

impl Drop for ToolProgressTimer {
    fn drop(&mut self) {
        let _ = self.cancel.send(true);
        eprint!("\r\x1b[K");
        let _ = io::stderr().flush();
        if let Some(handle) = self.handle.take() {
            handle.abort();
        }
    }
}

// ── Think block filter ───────────────────────────────────────────────────
// Filters `<think>...</think>` blocks from streamed text deltas.
// Some models emit reasoning as raw text (not the Thinking stream),
// and we don't want that XML leaking into the user-visible output.

/// State machine for filtering `<think>...</think>` blocks from streamed text.
/// Returns the text that should be displayed (everything outside think blocks).
pub struct ThinkBlockFilter {
    in_block: bool,
    buffer: String,
}

impl ThinkBlockFilter {
    pub fn new() -> Self {
        Self {
            in_block: false,
            buffer: String::new(),
        }
    }

    /// Process a text delta, returning only the visible (non-think) portion.
    pub fn filter(&mut self, delta: &str) -> String {
        let mut result = String::new();
        self.buffer.push_str(delta);

        loop {
            if self.in_block {
                // Look for </think>
                if let Some(end_pos) = self.buffer.find("</think>") {
                    // Skip everything up to and including </think>
                    self.buffer = self.buffer[end_pos + 8..].to_string();
                    self.in_block = false;
                } else if self.buffer.ends_with('<')
                    || self.buffer.ends_with("</")
                    || self.buffer.ends_with("</t")
                    || self.buffer.ends_with("</th")
                    || self.buffer.ends_with("</thi")
                    || self.buffer.ends_with("</thin")
                    || self.buffer.ends_with("</think")
                {
                    // Might be a partial </think> — keep buffering
                    break;
                } else {
                    // No closing tag possibility — discard buffer
                    self.buffer.clear();
                    break;
                }
            } else {
                // Look for <think>
                if let Some(start_pos) = self.buffer.find("<think>") {
                    // Emit everything before <think>
                    result.push_str(&self.buffer[..start_pos]);
                    self.buffer = self.buffer[start_pos + 7..].to_string();
                    self.in_block = true;
                } else if self.buffer.ends_with('<')
                    || self.buffer.ends_with("<t")
                    || self.buffer.ends_with("<th")
                    || self.buffer.ends_with("<thi")
                    || self.buffer.ends_with("<thin")
                    || self.buffer.ends_with("<think")
                {
                    // Might be a partial <think> — emit everything before the '<'
                    if let Some(lt_pos) = self.buffer.rfind('<') {
                        result.push_str(&self.buffer[..lt_pos]);
                        self.buffer = self.buffer[lt_pos..].to_string();
                    }
                    break;
                } else {
                    // No tag possibility — emit all
                    result.push_str(&self.buffer);
                    self.buffer.clear();
                    break;
                }
            }
        }
        result
    }

    /// Flush any remaining buffered text (call at end of stream).
    pub fn flush(&mut self) -> String {
        let remaining = std::mem::take(&mut self.buffer);
        if self.in_block {
            String::new() // Still inside think block — discard
        } else {
            remaining // Partial tag that never completed — emit as-is
        }
    }
}

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

    #[test]
    fn test_spinner_frames_not_empty() {
        assert!(!SPINNER_FRAMES.is_empty());
    }

    #[test]
    fn test_spinner_frames_are_braille() {
        // All braille characters are in the Unicode range U+2800..U+28FF
        for &frame in SPINNER_FRAMES {
            assert!(
                ('\u{2800}'..='\u{28FF}').contains(&frame),
                "Expected braille character, got {:?}",
                frame
            );
        }
    }

    #[test]
    fn test_spinner_frame_cycling() {
        // First 10 frames should match SPINNER_FRAMES exactly
        for (i, &expected) in SPINNER_FRAMES.iter().enumerate() {
            assert_eq!(spinner_frame(i), expected);
        }
    }

    #[test]
    fn test_spinner_frame_wraps_around() {
        let len = SPINNER_FRAMES.len();
        // After one full cycle, it should repeat
        assert_eq!(spinner_frame(0), spinner_frame(len));
        assert_eq!(spinner_frame(1), spinner_frame(len + 1));
        assert_eq!(spinner_frame(2), spinner_frame(len + 2));
    }

    #[test]
    fn test_spinner_frame_large_index() {
        // Should not panic even with very large indices
        let frame = spinner_frame(999_999);
        assert!(SPINNER_FRAMES.contains(&frame));
    }

    #[test]
    fn test_spinner_frames_all_unique() {
        // Each frame in the animation should be distinct
        let mut seen = std::collections::HashSet::new();
        for &frame in SPINNER_FRAMES {
            assert!(seen.insert(frame), "Duplicate spinner frame: {:?}", frame);
        }
    }

    // --- format_edit_diff tests ---

    #[test]
    fn test_format_duration_live_seconds() {
        assert_eq!(format_duration_live(Duration::from_secs(0)), "0s");
        assert_eq!(format_duration_live(Duration::from_secs(5)), "5s");
        assert_eq!(format_duration_live(Duration::from_secs(59)), "59s");
    }

    #[test]
    fn test_format_duration_live_minutes() {
        assert_eq!(format_duration_live(Duration::from_secs(60)), "1m");
        assert_eq!(format_duration_live(Duration::from_secs(65)), "1m 5s");
        assert_eq!(format_duration_live(Duration::from_secs(120)), "2m");
        assert_eq!(format_duration_live(Duration::from_secs(3599)), "59m 59s");
    }

    #[test]
    fn test_format_duration_live_hours() {
        assert_eq!(format_duration_live(Duration::from_secs(3600)), "1h");
        assert_eq!(format_duration_live(Duration::from_secs(3660)), "1h 1m");
        assert_eq!(format_duration_live(Duration::from_secs(7200)), "2h");
    }

    #[test]
    fn test_format_tool_progress_no_lines() {
        let output = format_tool_progress("bash", Duration::from_secs(5), 0, None);
        assert!(output.contains("bash"), "should contain tool name");
        assert!(output.contains(""), "should contain timer emoji");
        assert!(output.contains("5s"), "should contain elapsed time");
        // Should contain spinner frame
        assert!(
            output.contains(''),
            "should contain spinner frame for tick 0"
        );
    }

    #[test]
    fn test_format_tool_progress_with_lines() {
        let output = format_tool_progress("bash", Duration::from_secs(12), 3, Some(142));
        assert!(output.contains("bash"), "should contain tool name");
        assert!(output.contains("12s"), "should contain elapsed time");
        assert!(output.contains("142 lines"), "should contain line count");
    }

    #[test]
    fn test_format_tool_progress_single_line() {
        let output = format_tool_progress("bash", Duration::from_secs(1), 0, Some(1));
        assert!(output.contains("1 line"), "should use singular 'line'");
        assert!(!output.contains("1 lines"), "should not use plural for 1");
    }

    #[test]
    fn test_format_tool_progress_zero_lines_hidden() {
        let output = format_tool_progress("bash", Duration::from_secs(3), 0, Some(0));
        assert!(!output.contains("line"), "zero lines should be hidden");
    }

    #[test]
    fn test_format_partial_tail_empty() {
        assert_eq!(format_partial_tail("", 3), "");
    }

    #[test]
    fn test_format_partial_tail_zero_lines() {
        assert_eq!(format_partial_tail("hello\nworld", 0), "");
    }

    #[test]
    fn test_format_partial_tail_fewer_lines_than_max() {
        let output = format_partial_tail("line1\nline2", 5);
        assert!(output.contains("line1"), "should show all lines");
        assert!(output.contains("line2"), "should show all lines");
        assert!(
            !output.contains("above"),
            "should not show 'above' indicator"
        );
    }

    #[test]
    fn test_format_partial_tail_more_lines_than_max() {
        let output = format_partial_tail("line1\nline2\nline3\nline4\nline5", 2);
        assert!(!output.contains("line1"), "should not show early lines");
        assert!(!output.contains("line2"), "should not show early lines");
        assert!(!output.contains("line3"), "should not show line3");
        assert!(output.contains("line4"), "should show tail lines");
        assert!(output.contains("line5"), "should show tail lines");
        assert!(output.contains("3 lines above"), "should show skip count");
    }

    #[test]
    fn test_format_partial_tail_uses_pipe_indent() {
        let output = format_partial_tail("hello", 1);
        assert!(
            output.contains(""),
            "should use dotted pipe for indentation"
        );
    }

    #[test]
    fn test_count_result_lines() {
        let result = ToolResult {
            content: vec![Content::Text {
                text: "line1\nline2\nline3".to_string(),
            }],
            details: serde_json::Value::Null,
        };
        assert_eq!(count_result_lines(&result), 3);
    }

    #[test]
    fn test_count_result_lines_empty() {
        let result = ToolResult {
            content: vec![],
            details: serde_json::Value::Null,
        };
        assert_eq!(count_result_lines(&result), 0);
    }

    #[test]
    fn test_extract_result_text() {
        let result = ToolResult {
            content: vec![
                Content::Text {
                    text: "hello".to_string(),
                },
                Content::Text {
                    text: "world".to_string(),
                },
            ],
            details: serde_json::Value::Null,
        };
        assert_eq!(extract_result_text(&result), "hello\nworld");
    }

    #[test]
    fn test_extract_result_text_empty() {
        let result = ToolResult {
            content: vec![],
            details: serde_json::Value::Null,
        };
        assert_eq!(extract_result_text(&result), "");
    }

    // ── Streaming contract tests ──
    //
    // These tests document and lock in the current behavior of the streaming
    // pipeline (MarkdownRenderer::render_delta + flush). They exist to prevent
    // regressions when modifying the renderer. Each test describes a specific
    // contract about when content is buffered vs. emitted immediately.

    #[test]
    fn test_think_filter_simple_block() {
        let mut f = ThinkBlockFilter::new();
        let out = f.filter("Hello <think>reasoning</think> World");
        assert_eq!(out, "Hello  World");
    }

    #[test]
    fn test_think_filter_no_block() {
        let mut f = ThinkBlockFilter::new();
        let out = f.filter("Hello World");
        assert_eq!(out, "Hello World");
    }

    #[test]
    fn test_think_filter_streaming_split() {
        let mut f = ThinkBlockFilter::new();
        let out1 = f.filter("Hello <thi");
        assert_eq!(out1, "Hello ");
        let out2 = f.filter("nk>secret</think> World");
        assert_eq!(out2, " World");
    }

    #[test]
    fn test_think_filter_nested_or_repeated() {
        let mut f = ThinkBlockFilter::new();
        let out = f.filter("A<think>x</think>B<think>y</think>C");
        assert_eq!(out, "ABC");
    }

    #[test]
    fn test_think_filter_partial_at_end() {
        // Buffer has partial "<thi" that never completes — flush emits it as-is
        let mut f = ThinkBlockFilter::new();
        let out1 = f.filter("Hello <thi");
        assert_eq!(out1, "Hello ");
        let flushed = f.flush();
        assert_eq!(flushed, "<thi");
    }

    #[test]
    fn test_think_filter_flush_inside_block() {
        // Flush while inside a think block — discard remaining
        let mut f = ThinkBlockFilter::new();
        let out = f.filter("Hello <think>still going");
        assert_eq!(out, "Hello ");
        let flushed = f.flush();
        assert_eq!(flushed, "");
    }

    #[test]
    fn test_think_filter_empty_input() {
        let mut f = ThinkBlockFilter::new();
        let out = f.filter("");
        assert_eq!(out, "");
        let flushed = f.flush();
        assert_eq!(flushed, "");
    }

    #[test]
    fn test_think_filter_block_at_start() {
        let mut f = ThinkBlockFilter::new();
        let out = f.filter("<think>hidden</think>visible");
        assert_eq!(out, "visible");
    }

    #[test]
    fn test_think_filter_block_at_end() {
        let mut f = ThinkBlockFilter::new();
        let out = f.filter("visible<think>hidden</think>");
        assert_eq!(out, "visible");
    }

    #[test]
    fn test_think_filter_split_closing_tag() {
        // Closing tag split across deltas
        let mut f = ThinkBlockFilter::new();
        let out1 = f.filter("<think>hidden</thi");
        assert_eq!(out1, "");
        let out2 = f.filter("nk>visible");
        assert_eq!(out2, "visible");
    }

    #[test]
    fn test_think_filter_char_by_char() {
        // Simulate extreme token-by-token streaming
        let mut f = ThinkBlockFilter::new();
        let input = "Hi<think>x</think>!";
        let mut collected = String::new();
        for ch in input.chars() {
            collected.push_str(&f.filter(&ch.to_string()));
        }
        collected.push_str(&f.flush());
        assert_eq!(collected, "Hi!");
    }
}