plugin_command_dispatch.py 1.6 KB

1234567891011121314151617181920212223242526272829303132
  1. """Compatibility-aware call boundary for plugin slash-command handlers."""
  2. from __future__ import annotations
  3. import inspect
  4. from typing import Any, Callable
  5. _KEYWORD_KINDS = (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
  6. def invoke_plugin_command(handler: Callable, raw_args: str, **context: Any) -> Any:
  7. """Call *handler* once with *raw_args* plus the *context* keywords it declares.
  8. Every surface passes the same context (``source``, ``session_id``, ``session_key``,
  9. ``platform``); a handler opts in by naming any of them as keyword-capable parameters, or
  10. takes them all with ``**kwargs``. Legacy ``fn(raw_args)`` handlers and opaque signatures keep
  11. the one-argument call. Handler exceptions propagate; they are never retried as a legacy call.
  12. """
  13. try:
  14. parameters = list(inspect.signature(handler).parameters.values())
  15. except (TypeError, ValueError):
  16. return handler(raw_args)
  17. # The first positional parameter receives raw_args whatever its name (``def h(source, **kw)``
  18. # must not get ``source`` twice).
  19. if parameters and parameters[0].kind is not inspect.Parameter.KEYWORD_ONLY:
  20. if parameters[0].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD:
  21. context = {k: v for k, v in context.items() if k != parameters[0].name}
  22. parameters = parameters[1:]
  23. if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters):
  24. return handler(raw_args, **context)
  25. accepted = {p.name for p in parameters if p.kind in _KEYWORD_KINDS}
  26. return handler(raw_args, **{k: v for k, v in context.items() if k in accepted})