ertangle-adapter 1.8.0

Agent adapters (Claude Code, Codex, ACP) for ertangle
Documentation
//! Line buffering for streaming text.
//!
//! Structured protocols (ACP, Claude stream-json, Codex app-server) emit text **in small chunks**.
//! Treating every chunk as a separate output would turn transcripts into one character per line.
//! [`StreamBuf`] reassembles chunks into complete lines and flushes on kind switches or turn end.

const EARLY_FLUSH_CHARS: usize = 120;

/// Text ready to emit. When `append` is true, the first segment of `text`
/// continues the previously emitted line that had no trailing newline (see [`StreamBuf::idle_flush_chunk`]).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Chunk {
    pub text: String,
    pub append: bool,
}

/// Buffer that coalesces token-level chunks into complete lines.
#[derive(Default)]
pub struct StreamBuf {
    /// Current accumulated kind (e.g., `"msg"` / `"think"`); flushed before switching kind.
    kind: &'static str,
    text: String,
    /// A partial line without a trailing newline has already been emitted (see [`Self::idle_flush_chunk`]);
    /// the next emitted segment must append to that line without repeating the thought prefix.
    open: bool,
}

impl StreamBuf {
    /// Prefix each line by kind. Thoughts use the emoji-free `⋯ ` marker; a
    /// continuation of an already-prefixed line never gets a second prefix.
    fn decorate(kind: &str, line: &str, continuation: bool) -> String {
        if kind == "think" && !continuation {
            format!("⋯ {line}")
        } else {
            line.to_string()
        }
    }

    /// Pick a byte index to split an over-long thought without a newline.
    /// Prefer the last whitespace near the limit so words stay intact; the returned
    /// index is past that whitespace so the remainder never starts with a space.
    fn early_flush_split(text: &str, limit: usize) -> usize {
        let cut = text
            .char_indices()
            .nth(limit)
            .map_or(text.len(), |(i, _)| i);
        let head = &text[..cut];
        head.char_indices()
            .rev()
            .find(|(_, ch)| ch.is_whitespace())
            .map(|(i, ch)| i + ch.len_utf8())
            .filter(|end| *end >= cut.saturating_sub(24))
            .unwrap_or(cut)
    }

    /// Append a chunk and return complete lines ready to emit (may span multiple lines, with newlines).
    pub fn push(&mut self, kind: &'static str, text: &str) -> String {
        self.push_chunk(kind, text).text
    }

    /// Same as [`Self::push`], but preserves whether it appends to the previous line.
    pub fn push_chunk(&mut self, kind: &'static str, text: &str) -> Chunk {
        let append = self.open;
        let mut out = String::new();
        if self.kind != kind {
            out.push_str(&self.take().text);
            self.kind = kind;
        }
        // Only the first emitted segment can continue the open line; a kind switch
        // above has already closed it.
        let mut cont = self.open;
        self.text.push_str(text);
        while let Some(idx) = self.text.find('\n') {
            let line: String = self.text.drain(..=idx).collect();
            out.push_str(&Self::decorate(kind, &line, cont));
            cont = false;
            self.open = false;
        }
        // Long single-paragraph reasoning must stream immediately instead of waiting
        // for the end of the thought block (which may never get a trailing newline).
        if kind == "think" && self.text.chars().count() >= EARLY_FLUSH_CHARS {
            let split = Self::early_flush_split(&self.text, EARLY_FLUSH_CHARS);
            let line: String = self.text.drain(..split).collect();
            out.push_str(&Self::decorate(kind, line.trim_end(), cont));
            out.push('\n');
            self.open = false;
        }
        Chunk {
            append: append && !out.is_empty(),
            text: out,
        }
    }

    /// Finalize: flush any remaining text without a trailing newline as a line.
    pub fn flush(&mut self) -> String {
        self.take().text
    }

    /// Same as [`Self::flush`], but preserves whether it appends to the previous line.
    pub fn flush_chunk(&mut self) -> Chunk {
        self.take()
    }

    /// On stream idle, flush remaining text **without a newline** so a line (or a Markdown
    /// table row / inline code span) is not split in the middle; subsequent chunks append to the same line.
    pub fn idle_flush_chunk(&mut self) -> Chunk {
        if self.text.is_empty() {
            return Chunk::default();
        }
        let line = std::mem::take(&mut self.text);
        let append = self.open;
        self.open = true;
        Chunk {
            text: Self::decorate(self.kind, &line, append),
            append,
        }
    }

    fn take(&mut self) -> Chunk {
        let append = std::mem::take(&mut self.open);
        if self.text.is_empty() {
            // Close a dangling partial line with a bare newline.
            return if append {
                Chunk {
                    text: "\n".to_string(),
                    append: true,
                }
            } else {
                Chunk::default()
            };
        }
        let line = std::mem::take(&mut self.text);
        let mut s = Self::decorate(self.kind, &line, append);
        s.push('\n');
        Chunk { text: s, append }
    }
}

#[cfg(test)]
mod tests {
    use super::{Chunk, StreamBuf};

    #[test]
    fn coalesces_token_chunks_into_lines() {
        let mut b = StreamBuf::default();
        assert_eq!(b.push("msg", "Hel"), "");
        assert_eq!(b.push("msg", "lo"), "");
        assert_eq!(b.push("msg", " world\n"), "Hello world\n");
        assert_eq!(b.push("msg", "next"), "");
        assert_eq!(b.flush(), "next\n");
    }

    #[test]
    fn prefixes_thoughts_and_flushes_on_kind_change() {
        let mut b = StreamBuf::default();
        assert_eq!(b.push("think", "hmm"), "");
        assert_eq!(b.push("msg", "ok\n"), "⋯ hmm\nok\n");
    }

    #[test]
    fn flushes_long_thought_without_newline() {
        let mut b = StreamBuf::default();
        let chunk = "a".repeat(130);
        let out = b.push("think", &chunk);
        assert!(out.starts_with("⋯ "), "{out:?}");
        assert!(out.ends_with('\n'));
        assert_eq!(out.chars().count(), 123); // prefix (2) + 120 chars + newline
        assert_eq!(b.flush(), format!("⋯ {}\n", "a".repeat(10)));
    }

    #[test]
    fn flushes_long_thought_at_word_boundary() {
        let mut b = StreamBuf::default();
        let chunk = "word ".repeat(30);
        let out = b.push("think", &chunk);
        let body = out.strip_prefix("⋯ ").unwrap().trim_end_matches('\n');
        assert!(body.chars().count() <= 120, "{body:?}");
        assert!(body.ends_with("word"), "{body:?}");
        assert!(!b.text.is_empty());
        assert!(!b.flush().starts_with("⋯  "));
    }

    #[test]
    fn handles_multiple_lines_in_one_chunk() {
        let mut b = StreamBuf::default();
        assert_eq!(b.push("msg", "a\nb\nc"), "a\nb\n");
        assert_eq!(b.flush(), "c\n");
    }

    #[test]
    fn idle_flush_emits_partial_line_without_newline_then_appends() {
        let mut b = StreamBuf::default();
        assert_eq!(b.push_chunk("msg", "foo `00:03"), Chunk::default());
        let first = b.idle_flush_chunk();
        assert_eq!(
            first,
            Chunk {
                text: "foo `00:03".into(),
                append: false
            }
        );
        // Nothing buffered: a second idle flush is a no-op and keeps the line open.
        assert_eq!(b.idle_flush_chunk(), Chunk::default());
        let rest = b.push_chunk("msg", ":00` bar\nnext");
        assert_eq!(
            rest,
            Chunk {
                text: ":00` bar\n".into(),
                append: true
            }
        );
        assert_eq!(
            b.flush_chunk(),
            Chunk {
                text: "next\n".into(),
                append: false
            }
        );
    }

    #[test]
    fn closing_an_open_line_with_nothing_buffered_sends_bare_newline() {
        let mut b = StreamBuf::default();
        b.push_chunk("msg", "abc");
        b.idle_flush_chunk();
        assert_eq!(
            b.flush_chunk(),
            Chunk {
                text: "\n".into(),
                append: true
            }
        );
        assert_eq!(b.flush_chunk(), Chunk::default());
    }

    #[test]
    fn continuation_of_thought_has_no_second_prefix() {
        let mut b = StreamBuf::default();
        b.push_chunk("think", "hmm");
        assert_eq!(b.idle_flush_chunk().text, "⋯ hmm");
        let c = b.push_chunk("think", " more\n");
        assert_eq!(
            c,
            Chunk {
                text: " more\n".into(),
                append: true
            }
        );
    }

    #[test]
    fn kind_switch_closes_open_line_then_starts_new() {
        let mut b = StreamBuf::default();
        b.push_chunk("think", "hmm");
        b.idle_flush_chunk();
        let c = b.push_chunk("msg", "ok\n");
        assert_eq!(
            c,
            Chunk {
                text: "\nok\n".into(),
                append: true
            }
        );
    }

    #[test]
    fn flush_on_empty_is_noop() {
        let mut b = StreamBuf::default();
        assert_eq!(b.flush(), "");
        assert_eq!(b.push("msg", "\n"), "\n");
    }
}