turn_thread_reset.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """Make a reused turn-executor thread look like a new one to its next item.
  2. Turn code keys some state by the running thread instead of by turn: ``tools.interrupt`` bits and
  3. reasons by thread id, per-turn callbacks in module ``threading.local`` objects, and the sudo
  4. password cache's thread scope (the fallback when a turn has no session key). A new thread starts
  5. with none of it; a parked executor worker (gateway/turn_executor.py) must drop all of it before it
  6. takes another session's turn, or turn 1's interrupt, approval callback or cached sudo password is
  7. live in turn 2. Context variables need nothing here: every item runs in a fresh context.
  8. Modules are looked up in ``sys.modules`` only: one that was never imported holds no state.
  9. A new per-turn ``threading.local`` in turn code belongs in ``_PER_TURN_THREAD_LOCALS``.
  10. """
  11. from __future__ import annotations
  12. import sys
  13. import threading
  14. _PER_TURN_THREAD_LOCALS = (
  15. ("tools.terminal_tool", "_callback_tls"),
  16. ("tools.environments.base", "_activity_callback_local"),
  17. ("tools.feishu_lark", "_local"),
  18. ("agent.vault_backends.unlock", "_callback_tls"),
  19. ("agent.vault_backends.unlock", "_current_session_tls"),
  20. ("agent.auxiliary_client", "_aux_probe_state"),
  21. ("agent.auxiliary_client", "_aux_interrupt_protection"),
  22. ("agent.auxiliary_client", "_aux_progress"),
  23. ("agent.auxiliary_client", "_aux_dispatch"),
  24. ("agent.auxiliary_client", "_aux_provider_response"),
  25. ("agent.auxiliary_client", "_aux_stream_deadline"),
  26. ("agent.local_prompt_progress", "_reading"),
  27. ("hermes_cli.plugins", "_thread_tool_whitelist"),
  28. ("hermes_cli.observability.shared_metrics_events", "_compression_attempt"),
  29. ("hermes_logging", "_session_context"), # the log line's session tag + sanitizer-heal accounting key
  30. )
  31. def reset_reused_thread_state() -> None:
  32. """Drop the calling thread's turn-keyed state (call from the worker itself, between items)."""
  33. tid = threading.get_ident()
  34. interrupt = sys.modules.get("tools.interrupt")
  35. if interrupt is not None:
  36. interrupt.set_interrupt(False, tid) # clears the bit, its reason and a pending yield
  37. sudo = sys.modules.get("tools.terminal_tool_sudo")
  38. if sudo is not None:
  39. with sudo._sudo_password_cache_lock:
  40. sudo._sudo_password_cache.pop(f"thread:{tid}", None)
  41. for module_name, attr in _PER_TURN_THREAD_LOCALS:
  42. local = getattr(sys.modules.get(module_name), attr, None)
  43. if local is not None:
  44. local.__dict__.clear() # a threading.local's __dict__ is the calling thread's namespace