turn_exit.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """Turn-result exit policy shared by CLI views and authority-owned workers.
  2. Worker identity is supplied by the caller, not inferred from a daemon's environment.
  3. """
  4. # Provider walls do not spend a Kanban task's retry budget.
  5. TRANSIENT_PROVIDER_REASONS = frozenset({
  6. "rate_limit", "upstream_rate_limit", "billing", "overloaded", "server_error", "timeout",
  7. })
  8. # These failures need an operator change; the dispatcher parks the task immediately.
  9. TERMINAL_PROVIDER_REASONS = frozenset({
  10. "auth", "auth_permanent", "model_not_found", "ssl_cert_verification", "upstream_blocked",
  11. })
  12. def turn_exit_code(
  13. result, *, kanban_worker: bool, credentials_rate_limited: bool = False,
  14. credentials_terminal: bool = False,
  15. transient_reasons=TRANSIENT_PROVIDER_REASONS, terminal_reasons=TERMINAL_PROVIDER_REASONS,
  16. ) -> int:
  17. """Preserve completion, interruption and retryable/terminal provider outcomes."""
  18. if not isinstance(result, dict):
  19. if credentials_rate_limited and kanban_worker:
  20. from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
  21. return KANBAN_RATE_LIMIT_EXIT_CODE
  22. if credentials_terminal and kanban_worker:
  23. from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
  24. return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
  25. return 1
  26. if result.get("interrupted"):
  27. return 130
  28. if not (result.get("failed") or result.get("partial") or result.get("completed") is False):
  29. return 0
  30. if kanban_worker:
  31. reason = result.get("failure_reason")
  32. if reason in transient_reasons:
  33. from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
  34. return KANBAN_RATE_LIMIT_EXIT_CODE
  35. if reason in terminal_reasons:
  36. from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
  37. return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
  38. return 1
  39. def credential_failure_flags(exc) -> dict:
  40. """``turn_exit_code`` credential kwargs for an exception raised before any turn result exists.
  41. Same predicates as the one-shot CLI's ``_ensure_runtime_credentials``: a quota/rate-limit
  42. ``AuthError`` is transient, only an explicit re-authentication requirement is terminal. The
  43. cause chain is walked because agent construction wraps the resolver's error."""
  44. from hermes_cli.auth import AuthError, is_rate_limited_auth_error
  45. seen = set()
  46. while exc is not None and id(exc) not in seen:
  47. seen.add(id(exc))
  48. if isinstance(exc, AuthError):
  49. return {"credentials_rate_limited": is_rate_limited_auth_error(exc),
  50. "credentials_terminal": bool(exc.relogin_required)}
  51. exc = exc.__cause__ or exc.__context__
  52. return {}