interrupt_compat.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """Compatibility helper for explicit agent stop producers."""
  2. from __future__ import annotations
  3. import inspect
  4. from typing import Any
  5. def _accepts_keyword(callable_obj: Any, name: str) -> bool:
  6. """Return whether a callable explicitly supports a keyword argument."""
  7. try:
  8. parameters = inspect.signature(callable_obj).parameters.values()
  9. except (TypeError, ValueError):
  10. return False
  11. return any(
  12. p.kind is inspect.Parameter.VAR_KEYWORD
  13. or (p.name == name and p.kind is not inspect.Parameter.POSITIONAL_ONLY)
  14. for p in parameters
  15. )
  16. def request_hard_interrupt(
  17. agent: Any,
  18. message: str | None = None,
  19. *,
  20. tool_reason: str | None = None,
  21. ) -> bool:
  22. """Request an explicit stop, falling back to the legacy interrupt ABI.
  23. New agents expose ``hard_interrupt(message=None)``; third-party agents and old test
  24. doubles may only expose ``interrupt(message=None)`` and must not receive keyword
  25. arguments they do not know. ``tool_reason`` is a trusted, fixed category that may be
  26. exposed in model-visible tool cancellation output, forwarded only when the callable
  27. explicitly supports it. Returns ``False`` only when neither callable is available.
  28. """
  29. # Static lookup first: a dynamic ``__getattr__`` proxy (unspecced MagicMock, RPC
  30. # facade) must not be treated as genuinely implementing the new ABI.
  31. try:
  32. inspect.getattr_static(agent, "hard_interrupt")
  33. except AttributeError:
  34. interrupt = None
  35. else:
  36. interrupt = getattr(agent, "hard_interrupt", None)
  37. if not callable(interrupt):
  38. interrupt = getattr(agent, "interrupt", None)
  39. if not callable(interrupt):
  40. return False
  41. kwargs = {}
  42. if tool_reason is not None and _accepts_keyword(interrupt, "tool_reason"):
  43. kwargs["tool_reason"] = tool_reason
  44. if message is None:
  45. interrupt(**kwargs)
  46. else:
  47. interrupt(message, **kwargs)
  48. return True