Files
gabrielvidalandClaude Opus 5.5 49eaac0f55 feat(parse): stepSince — when the model step now streaming was sent
Claude Code writes an api-request record as it sends a step and the
response's blocks only once it has ended, so the last request with no
blocks after it is a response still streaming. The detail carries its send
time (stepSince): what a queued follow-up or a finished task waits behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 01:53:30 +01:00

87 lines
4.1 KiB
Python

"""Where the run's turn stands: ``TurnState`` (owned by ``ParserState`` as
``state.turn_state``) — whether the model's turn is over (``turn_end`` events,
and every event of work that reopens one) and the run's input queue
(``queue`` events)."""
from .records import _ms
from .usertext import _cancelled_text, _unwrap_inbox
from .readers.claude import ACTIVITY_RECORDS, TURN_END_SUBTYPES
from .readers.claudetext import _stop_feedback # noqa: F401
from .readers.legacy import LEGACY_TURN_END_SUBTYPES
# The turn-end records the readers turn into ``turn_end`` events: Claude
# Code's own (readers/claude.py) and the harness mirrors' (readers/legacy.py).
_TURN_END_SUBTYPES = TURN_END_SUBTYPES + LEGACY_TURN_END_SUBTYPES
# Records that mean the session is (again) at work (readers/claude.py).
_TURN_RECORDS = ACTIVITY_RECORDS
class TurnState:
"""The turn-end flag and the input queue, folded from ``turn_end`` and
``queue`` events and from every event that means work (``busy``)."""
def __init__(self):
# The model's turn is over: a ``turn_end`` (``done``, or ``error`` —
# an API error the CLI gave up on) with no turn activity after it. A
# ``held`` one (a Stop hook that blocked) or an ``interrupted`` one
# doesn't end it. What ends a conversation without a DONE.
self.turn_ended = False
# The run's input queue (``queue`` events): a prompt is `enqueue`d as
# it arrives and leaves FIFO by a `dequeue` (read as its own turn) or
# a `remove` (absorbed mid-turn — the only one naming its content).
# What is left is what a live run was sent and hasn't read yet
# ({content, at}) — see `queued_followups`.
self.queue: list[dict] = []
# When the model step now streaming was sent (a ``tick`` with
# ``request``: Claude Code writes an ``api-request`` record as it
# sends one, and the response's blocks only once it has ended). None
# once its blocks — or the turn's end — are in. What a queued
# follow-up waits behind: the model reads it only between two steps.
self.step_since: str | None = None
def busy(self) -> None:
"""The session is (again) at work."""
self.turn_ended = False
def end(self, reason) -> None:
self.turn_ended = reason in ("done", "error")
def queue_op(self, op, text, ts: str | None) -> None:
"""A ``queue`` event (``text`` = what was queued, None if not a string)."""
if op == "enqueue":
self.turn_ended = False
if isinstance(text, str):
self.queue.append({"content": text, "at": ts})
elif op == "remove" and self.queue:
i = next((k for k, q in enumerate(self.queue) if q["content"] == text), 0)
self.queue.pop(i)
elif op == "dequeue" and self.queue:
# A run reads its queue in order, so one taking the newest prompt
# the instant it arrived (a resume's own prompt) has nothing older
# left: anything still queued died with the previous process.
last = self.queue[-1]
a, b = _ms(last["at"]), _ms(ts)
if len(self.queue) > 1 and a is not None and b is not None and b - a < 1000:
self.queue.clear()
else:
self.queue.pop(0)
def queued_followups(self) -> list[dict]:
"""The user's follow-ups a live run has queued but not read yet —
`{text, at}`, oldest first. Only the ones the sidecar's inbox delivered
(its prefix): task notifications and peer sessions queue here too."""
out: list[dict] = []
for q in self.queue:
text = _unwrap_inbox(q["content"])
if text == q["content"]:
continue
gone = _cancelled_text(text)
if gone is None:
out.append({"text": text, "at": q["at"]})
continue
hit = next((i for i in range(len(out) - 1, -1, -1)
if out[i]["text"].strip() == gone), None)
if hit is not None:
out.pop(hit)
return out