provider_projection.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """Fold an agent-as-provider's own activity back into Hermes' turn state.
  2. Agent providers (ACP CLI shims, the codex app-server) run their own tools, so that
  3. work must never come back as pending ``tool_calls`` (Hermes would re-run it) — but
  4. the self-improvement loop (replays ``messages``) and the skill-review nudge
  5. (``_iters_since_skill`` counter) go blind if it is merely summarised into
  6. ``reasoning``. The client hands back ``hermes_projected_messages`` (completed
  7. assistant/tool rows) and ``hermes_provider_tool_iterations`` on the completion
  8. object; this helper applies them append-only via ``append_message`` (timestamped,
  9. persisted). Ordinary OpenAI-compatible clients set neither and are unaffected.
  10. """
  11. from __future__ import annotations
  12. import logging
  13. from typing import Any
  14. from agent.message_metadata import append_message
  15. logger = logging.getLogger(__name__)
  16. __all__ = ["splice_provider_projection"]
  17. def splice_provider_projection(agent: Any, response: Any, messages: list[dict[str, Any]]) -> int:
  18. """Append the provider's projected history rows and tick the nudge counter.
  19. Returns the number of rows spliced. Tolerates absent/garbage attributes so a
  20. third-party OpenAI-compatible client can't break the turn.
  21. """
  22. projected = getattr(response, "hermes_projected_messages", None)
  23. rows = [m for m in projected if isinstance(m, dict)] if isinstance(projected, list) else []
  24. for row in rows:
  25. append_message(messages, row)
  26. if rows:
  27. logger.debug(
  28. "spliced %d provider-projected transcript row(s) from %s", len(rows), getattr(agent, "provider", "?"),
  29. )
  30. try:
  31. iterations = int(getattr(response, "hermes_provider_tool_iterations", 0) or 0)
  32. except (TypeError, ValueError):
  33. iterations = 0
  34. if iterations > 0:
  35. agent._iters_since_skill = getattr(agent, "_iters_since_skill", 0) + iterations
  36. return len(rows)