state.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Map agent activity → a :class:`PetState`.
  2. The one place the "what is the agent doing?" → "which row?" decision lives; CLI,
  3. TUI and Desktop (TS mirror of this priority order) feed it the signals they track.
  4. """
  5. from __future__ import annotations
  6. from collections.abc import Iterable
  7. from typing import Any
  8. from agent.pet.constants import PetState
  9. def todos_all_done(todos: Iterable[Any] | None) -> bool:
  10. """True iff ≥1 todo and all completed/cancelled (the ``JUMP`` celebrate beat; mirrors the TUI's ``isTodoDone``)."""
  11. items = list(todos or [])
  12. return bool(items) and all(
  13. (t.get("status") if isinstance(t, dict) else getattr(t, "status", None)) in ("completed", "cancelled") for t in items
  14. )
  15. def derive_pet_state(
  16. *,
  17. busy: bool = False,
  18. awaiting_input: bool = False,
  19. error: bool = False,
  20. celebrate: bool = False,
  21. just_completed: bool = False,
  22. tool_running: bool = False,
  23. reasoning: bool = False,
  24. ) -> PetState:
  25. """Resolve the animation state from coarse activity signals.
  26. Priority (highest first) — only one row can show at a time, so the most
  27. salient signal wins:
  28. 1. ``error`` → ``FAILED`` (a tool/turn just failed)
  29. 2. ``celebrate`` → ``JUMP`` (explicit success beat, e.g. todos done)
  30. 3. ``just_completed`` → ``WAVE`` (turn finished cleanly / greeting)
  31. 4. ``awaiting_input`` → ``WAITING`` (blocked on the user — outranks the in-flight
  32. signals below because the turn is paused on *you*, even mid tool call)
  33. 5. ``tool_running`` → ``RUN``
  34. 6. ``reasoning`` → ``REVIEW``
  35. 7. ``busy`` → ``RUN`` (turn in flight, unspecified work)
  36. 8. otherwise → ``IDLE``
  37. """
  38. ranked = (
  39. (error, PetState.FAILED),
  40. (celebrate, PetState.JUMP),
  41. (just_completed, PetState.WAVE),
  42. (awaiting_input, PetState.WAITING),
  43. (tool_running, PetState.RUN),
  44. (reasoning, PetState.REVIEW),
  45. (busy, PetState.RUN),
  46. )
  47. return next((state for flag, state in ranked if flag), PetState.IDLE)