thread_context.py 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Propagate agent-turn context into worker threads that dispatch Hermes tools.
  2. A bare ``threading.Thread`` / ``ThreadPoolExecutor`` worker starts with an empty
  3. ``contextvars.Context`` and no thread-local approval/sudo callbacks, so tool dispatch inside it
  4. silently loses the approval ContextVars (gateway sessions then auto-approve dangerous commands)
  5. and the CLI callbacks (``prompt_dangerous_approval`` cannot reach the user, GHSA-qg5c-hvr5-hjgr).
  6. Call :func:`propagate_context_to_thread` **on the parent thread** (it snapshots at call time) and
  7. use the result as the worker target; callbacks are installed for the worker's lifetime and
  8. always cleared on exit.
  9. """
  10. from __future__ import annotations
  11. import contextvars
  12. import logging
  13. from typing import Callable
  14. logger = logging.getLogger(__name__)
  15. def _callback_api():
  16. """(getter, setter) pairs for every thread-local prompt callback a tool may need mid-dispatch
  17. (lazy: terminal_tool imports tools.approval at load, so a top-level import risks a cycle).
  18. Add a new per-thread prompt here — a callback missing from this table is silently absent on
  19. every parallel/timeout worker, so the tool believes nobody can answer."""
  20. from agent.vault_backends import unlock as vault_unlock
  21. from tools import terminal_tool as tt
  22. return ((tt._get_approval_callback, tt.set_approval_callback),
  23. (tt._get_sudo_password_callback, tt.set_sudo_password_callback),
  24. (vault_unlock.get_unlock_prompt_callback, vault_unlock.set_unlock_prompt_callback),
  25. (vault_unlock.get_save_login_prompt_callback, vault_unlock.set_save_login_prompt_callback),
  26. (vault_unlock.get_code_prompt_callback, vault_unlock.set_code_prompt_callback),
  27. # The unlock owner: a manager unlocked on a worker must still be released with its session.
  28. (vault_unlock.get_current_session_id, vault_unlock.set_current_session_id))
  29. def propagate_context_to_thread(target: Callable) -> Callable:
  30. """Wrap *target* to run with the *current* thread's ContextVars and per-thread prompt callbacks
  31. (approval, sudo, password-manager unlock).
  32. Fail-closed: if callback installation raises they stay ``None`` — dangerous commands are then
  33. denied by ``prompt_dangerous_approval`` and the gateway approval queue blocks.
  34. """
  35. ctx = contextvars.copy_context()
  36. # (setter, parent callback) pairs; None when the callback API could not be captured.
  37. installs = None
  38. try:
  39. installs = tuple((setter, getter()) for getter, setter in _callback_api())
  40. except Exception:
  41. logger.debug("Could not capture parent approval/sudo callbacks", exc_info=True)
  42. def _runner(*args, **kwargs):
  43. def _inner():
  44. if installs is None:
  45. return target(*args, **kwargs)
  46. try:
  47. for setter, cb in installs:
  48. if cb is not None:
  49. setter(cb)
  50. except Exception:
  51. logger.debug("Failed to install propagated approval/sudo callbacks; "
  52. "dangerous-command approval will fail closed", exc_info=True)
  53. try:
  54. return target(*args, **kwargs)
  55. finally:
  56. try:
  57. for setter, _cb in installs:
  58. setter(None)
  59. except Exception:
  60. logger.debug("Failed to clear propagated approval/sudo callbacks",
  61. exc_info=True)
  62. return ctx.run(_inner)
  63. return _runner