*/ public function feed(string $text): array { $buffer = $this->tail . $text; $this->tail = ''; $out = []; while ($buffer !== '') { $marker = $this->open ? FakedToolCall::CLOSE : FakedToolCall::OPEN; $at = strpos($buffer, $marker); if ($at === false) { $keep = self::partial($buffer, $marker); self::add($out, substr($buffer, 0, strlen($buffer) - $keep), $this->open); $this->tail = $keep === 0 ? '' : substr($buffer, -$keep); break; } $end = $at + strlen($marker); if ($this->open) { // The closing marker is the block's own last bytes, so it is held with it. self::add($out, substr($buffer, 0, $end), true); } else { self::add($out, substr($buffer, 0, $at), false); self::add($out, $marker, true); } $this->open = !$this->open; $buffer = substr($buffer, $end); } return $out; } /** * Whatever feed() kept back, for the end of the run, flagged as the state it was kept in. * * @return list */ public function flush(): array { $tail = $this->tail; $this->tail = ''; return $tail === '' ? [] : [[$tail, $this->open]]; } /** Whether a block is open: an opening marker has arrived and its closing one has not. */ public function open(): bool { return $this->open; } /** * A complete `$text` as the pieces a streamed one would have become: one scanner's feed() * and flush(), joined where the two meet. * * Pipeline::agentTurn()'s tail is the caller and the reason this exists. That Delta is the * one text a streamed agent turn can emit that no live scanner has seen — an answer the * agent gave through its `done` tool, or any iteration whose content never arrived as * `agent.text_delta` — so without this it would reach the client unflagged, which is the * raw JSON this whole class exists to keep off the screen. * * A *fresh* scanner, not the observer's, and that is the point: the tail is the Output's own * content, a separate message from the one that streamed, so inheriting an open block from * text it does not continue would flag its opening bytes for a marker that was never in it. * * @return list */ public static function pieces(string $text): array { $stream = new self(); $out = $stream->feed($text); foreach ($stream->flush() as [$piece, $held]) { self::add($out, $piece, $held); } return $out; } /** The length of the longest end of `$buffer` that is a proper beginning of `$marker`. */ private static function partial(string $buffer, string $marker): int { for ($n = min(strlen($buffer), strlen($marker) - 1); $n > 0; $n--) { if (str_starts_with($marker, substr($buffer, -$n))) { return $n; } } return 0; } /** * @param list $out * @param-out list $out */ private static function add(array &$out, string $text, bool $held): void { if ($text === '') { return; } $last = count($out) - 1; if ($last >= 0 && $out[$last][1] === $held) { $out[$last][0] .= $text; return; } $out[] = [$text, $held]; } }