A serving backend streams tokens as byte chunks. A single multi-byte character, the end-of-reasoning marker or a tool-call tag can be split across chunks, and the parser must still emit every byte it is sure about as soon as it is sure, without rescanning. Implement a state machine with three phases and incremental delimiter matching.
StreamParser(think_end="</think>", tool_open="<tool>", tool_close="</tool>")
"reasoning" until think_end is seen, then "text"; inside "text", tool_open starts a "tool" phase that ends at tool_close. Delimiters are consumed, never emitted.feed(chunk: bytes) -> list[(kind, text)]
("reasoning", text) or ("text", text); characters that might be the start of the delimiter are held. In the tool phase, content accumulates and is emitted as one ("tool", content) event when the close tag completes.finish() -> list[(kind, text)]
("tool", ...)), discard incomplete bytes, and return the events.j to the longest proper border without re-reading characters; the characters that fall out of the match window are the ones to emit.held string whose length always equals the current match length j; after each character, everything before the last j characters is confirmed.0b110xxxxx starts a 2-byte sequence, 0b1110xxxx a 3-byte one and 0b11110xxx a 4-byte one; continuation bytes are 0b10xxxxxx.