*/ private \SplQueue $deltas; /** * Held weakly: the fiber's callback reaches the agent, the agent holds this observer, and a * strong reference back to the fiber would close a cycle that only the cycle collector * breaks. The weak reference is one half of what makes a consumer's abandonment release * the fiber at once; the other half is push(), which keeps no local of the fiber alive in * the fiber's own frames across its suspension. With both, the pipeline's local is the only * strong reference, and dropping the generator unwinds the fiber in that same destruction; * with either missing, the fiber (and the agent, its conversation and the provider's open * stream) lives until the collector next runs. PipelineToolsTest pins the release without * gc_collect_cycles(). * * @var \WeakReference<\Fiber>|null */ private ?\WeakReference $fiber = null; /** The text streamed so far, for the paragraph break between iterations. */ private string $streamedText = ''; /** * A paragraph break owed to the reader. Set at the start of every iteration after the first * and never cleared at an iteration boundary (update() only ORs it on), so an iteration that * calls tools and writes nothing carries it forward. It is spent by the next *non-empty* * text delta, whichever iteration that turns up in; the empty heartbeat delta pushed before * a tool call does not spend it. So the break lands where text resumes, rather than being * swallowed by a silent iteration and leaving two replies run together. */ private bool $breakPending = false; /** @var list}> calls announced and not yet answered, oldest first */ private array $pending = []; /** @var list, result_excerpt: string, ok: bool, result_bytes: int}> */ private array $toolCalls = []; private ?string $error = null; /** Says which streamed bytes are a faked tool call's markup (Kanboard #4329); the class docblock's event list says where it sits. */ private FakedToolCallStream $faked; public function __construct() { $this->deltas = new \SplQueue(); $this->faked = new FakedToolCallStream(); } /** * The fiber a delta suspends: the one the pipeline resumes after draining. * * @param \Fiber $fiber */ public function streamThrough(\Fiber $fiber): void { $this->fiber = \WeakReference::create($fiber); } public function update(\SplSubject $subject): void { if (!$subject instanceof AbstractAgent) { return; } $data = $subject->lastEventData(); switch ($subject->lastEvent()) { case 'agent.iteration': $this->breakPending = $this->breakPending || (is_int($data) && $data > 1); break; case 'agent.text_delta': $text = is_string($data) ? $data : ''; if ($this->breakPending && $text !== '') { $text = self::separated($this->streamedText, $text); $this->breakPending = false; } $this->streamedText .= $text; // One delta in, one or more out: a piece that is a faked call's markup is flagged // rather than withheld, and a few bytes that might be the start of a marker are // kept until the next delta (or flush()) settles it. A delta that is nothing but // those few bytes therefore queues nothing at all, and so suspends nothing. foreach ($this->faked->feed($text) as [$piece, $held]) { $this->push(new Delta($piece, '', $held)); } break; case 'agent.reasoning': $this->push(new Delta('', is_string($data) ? $data : '')); break; case 'agent.tool_call': if ($data instanceof ToolCall) { $this->pending[] = ['id' => $data->id, 'name' => self::bounded($data->name, self::NAME_CHARS), 'arguments' => self::boundedArguments($data->arguments)]; // The heartbeat: an empty delta, so the pipeline yields (and a streaming // transport writes) something before the tool runs. The event fires before // any tool of the iteration executes, which is the moment that matters. It // carries the hold state so a screen that is hiding a faked call's markup // keeps saying so across it. $this->push(new Delta('', '', $this->faked->open())); } break; case 'agent.tool_result': if ($data instanceof ToolResult) { $this->answer($data); } break; case 'agent.error': $this->error = is_string($data) ? $data : null; break; } } /** * The deltas queued since the last drain, in arrival order. * * @return list */ public function drain(): array { $out = []; while (!$this->deltas->isEmpty()) { $out[] = $this->deltas->dequeue(); } return $out; } /** * Queues the bytes FakedToolCallStream was still deciding about, for a run that has ended: * the pipeline calls this after the agent returns, before its last drain, so they reach the * client in their place and in the stored reply. Nothing suspends here: push() suspends only * inside the streamed fiber, and this is called after that fiber has terminated. */ public function flush(): void { foreach ($this->faked->flush() as [$text, $held]) { $this->push(new Delta($text, '', $held)); } } /** * The same bytes for a run nobody will drain again — the consumer walked away, or the turn * threw — handed back as text rather than as a delta, so send() can put them on the partial * reply it stores. Once: a second call has nothing. */ public function takeUnsent(): string { return implode('', array_column($this->faked->flush(), 0)); } /** * Every tool call heard, in the order their results arrived; a call still unanswered (the * run was cut off, or cancelled, before its result) is listed last as not ok with nothing * to show and 0 bytes, so the record still says it was made. * * @return list, result_excerpt: string, ok: bool, result_bytes: int}> */ public function toolCalls(): array { $out = $this->toolCalls; foreach ($this->pending as $call) { $out[] = ['name' => $call['name'], 'arguments' => $call['arguments'], 'result_excerpt' => '', 'ok' => false, 'result_bytes' => 0]; } return $out; } /** The message of the last `agent.error`, which is what an Error finish ended on; null when none fired. */ public function error(): ?string { return $this->error; } /** * `$text` as the continuation of `$streamed` when the two came from different model * messages: a paragraph break between them unless `$streamed` is empty or already ends a * line. The agent's iterations are separate assistant messages in its conversation ("Let * me check." with a tool call, then the answer), and the stored reply is one message, so * the join is where the boundary is kept; without it the two run together mid-word. */ public static function separated(string $streamed, string $text): string { return $streamed === '' || str_ends_with($streamed, "\n") ? $text : "\n\n" . $text; } /** * Queues the delta and, inside the streamed fiber, suspends. The identity check is a call of * its own so that no local holding the fiber is alive in this frame across the suspension: * a suspended fiber keeps its frames, and a strong reference to itself in one of them is a * cycle (the fiber holds its stack, the stack holds the fiber) that only the cycle collector * breaks. With the check's frame gone before suspend() runs, the pipeline's own local is the * last strong reference, and dropping the generator unwinds the fiber then and there. */ private function push(Delta $delta): void { $this->deltas->enqueue($delta); if ($this->insideStreamedFiber()) { \Fiber::suspend(); } } /** Whether the running fiber is the one streamThrough() named; false outside any fiber. */ private function insideStreamedFiber(): bool { $fiber = $this->fiber?->get(); return $fiber !== null && \Fiber::getCurrent() === $fiber; } private function answer(ToolResult $result): void { $index = 0; if ($result->callId !== null) { foreach ($this->pending as $i => $call) { if ($call['id'] === $result->callId) { $index = $i; break; } } } $call = $this->pending[$index] ?? null; if ($call === null) { return; } array_splice($this->pending, $index, 1); $this->toolCalls[] = [ 'name' => $call['name'], 'arguments' => $call['arguments'], 'result_excerpt' => self::bounded($result->content, self::RESULT_CHARS), 'ok' => $result->status === ToolResultStatus::Success, 'result_bytes' => strlen($result->content), ]; } /** * The arguments as the record keeps them: every string held to ARGUMENT_CHARS, and the * record as a whole to ARGUMENTS_CHARS. The whole-record bound is the one that matters for * storage; a bound on each string alone leaves a tool taking a long list of short strings, * or a model inventing keys, storing as much as it sent. * * @param array $arguments * @return array */ private static function boundedArguments(array $arguments): array { $budget = self::ARGUMENTS_CHARS; /** @var array */ return self::boundedRecord($arguments, $budget); } /** * One level of the record against the budget it shares with every other level. Each key * and each scalar value spends its characters; a string is cut to what remains of the * budget (and never past ARGUMENT_CHARS); an array recurses on the same budget. Once the * budget is spent, the entries that follow at that level are dropped and an ellipsis entry * stands in their place, so the cut is visible where it was made, as it is for a string. * Entries are kept in the order sent, so the leading arguments (a title, a URL) survive a * cut made by a large trailing one. * * @param array $record * @return array */ private static function boundedRecord(array $record, int &$budget): array { $out = []; foreach ($record as $key => $value) { if ($budget <= 0) { $out[is_int($key) ? $key : '…'] = '…'; break; } $budget -= mb_strlen((string) $key); if (is_string($value)) { $value = self::bounded($value, max(0, min(self::ARGUMENT_CHARS, $budget))); $budget -= mb_strlen($value); } elseif (is_array($value)) { $value = self::boundedRecord($value, $budget); } else { $budget -= mb_strlen((string) wp_json_encode($value)); } $out[$key] = $value; } return $out; } private static function bounded(string $text, int $chars): string { return mb_strlen($text) > $chars ? mb_substr($text, 0, $chars) . '…' : $text; } }