delegate_tool_toolsets.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. """Child toolset resolution for delegate_task: what a child may and may never use."""
  2. from __future__ import annotations
  3. import logging
  4. from typing import List, Optional
  5. from toolsets import TOOLSETS, resolve_toolset
  6. from tools.delegate_tool_config import _get_inherit_mcp_toolsets
  7. logger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module
  8. # Tools that children must never have access to
  9. DELEGATE_BLOCKED_TOOLS = frozenset(
  10. [
  11. "delegate_task", # no recursive delegation
  12. "clarify", # no user interaction
  13. "memory", # no writes to shared MEMORY.md
  14. "send_message", # no cross-platform side effects
  15. "cronjob_manage", # no scheduling more work in the parent's name
  16. ]
  17. )
  18. DEFAULT_TOOLSETS = ["terminal", "file", "web"]
  19. def _is_mcp_toolset_name(name: str) -> bool:
  20. """Return True for canonical MCP toolsets and their registered aliases."""
  21. if not name:
  22. return False
  23. if str(name).startswith("mcp-"):
  24. return True
  25. try:
  26. from tools.registry import registry
  27. target = registry.get_toolset_alias_target(str(name))
  28. except Exception:
  29. target = None
  30. return bool(target and str(target).startswith("mcp-"))
  31. def _expand_parent_toolsets(parent_toolsets: set) -> set:
  32. """Add every toolset whose tools are a subset of the parent's tools: a parent on a composite like ``hermes-cli``
  33. must still let a child request ``web``/``terminal``; bare name intersection would reject them. Both sides use
  34. the RESOLVED static surface: a composite's ``includes`` (``debugging`` -> ``web``/``file``, ``safe``) are tools
  35. the parent genuinely holds, and the child never gains a tool the parent lacks."""
  36. parent_tool_names = {
  37. t for ts_name in parent_toolsets if ts_name in TOOLSETS for t in resolve_toolset(ts_name, include_registry=False)
  38. }
  39. expanded = set(parent_toolsets)
  40. if parent_tool_names:
  41. expanded.update(
  42. ts_name for ts_name in TOOLSETS
  43. if ts_name not in expanded
  44. and (resolved := resolve_toolset(ts_name, include_registry=False))
  45. and set(resolved).issubset(parent_tool_names)
  46. )
  47. return expanded
  48. def _strip_blocked_tools(toolsets: list[str]) -> list[str]:
  49. """Remove toolsets whose tools are ALL blocked (derived from DELEGATE_BLOCKED_TOOLS so the two can't drift) plus
  50. composite toolsets children must never get (``delegation``, ``kanban``)."""
  51. blocked_toolset_names = {"delegation", "kanban"} | {
  52. name
  53. for name in TOOLSETS
  54. if (resolved_tools := resolve_toolset(name, include_registry=False))
  55. and all(tool in DELEGATE_BLOCKED_TOOLS for tool in resolved_tools)
  56. }
  57. return [t for t in toolsets if t not in blocked_toolset_names]
  58. def _blocked_toolsets_for_role(role: str) -> list[str]:
  59. """One-tool deny toolsets for the role; passed as ``disabled_toolsets`` so
  60. blocked names inside mixed bundles are subtracted AFTER composite expansion."""
  61. blocked_names = set(DELEGATE_BLOCKED_TOOLS)
  62. if role == "orchestrator":
  63. blocked_names.discard("delegate_task")
  64. return sorted(
  65. name for name, defn in TOOLSETS.items() if defn.get("tools") and set(defn.get("tools", ())).issubset(blocked_names)
  66. )
  67. def _resolve_child_toolsets(
  68. parent_agent, toolsets: Optional[list[str]], effective_role: str
  69. ) -> tuple[list[str], list[str]]:
  70. """``(enabled_toolsets, disabled_toolsets)`` for a child. Children never gain tools the parent lacks: explicit
  71. ``toolsets`` are intersected with the parent's (composite-expanded) set, else the parent's enabled set is
  72. inherited. Blocked tools are stripped twice — whole blocked toolsets here, and exact one-tool deny toolsets via
  73. ``disabled_toolsets`` so blocked names inside mixed bundles (hermes-cli) are subtracted AFTER composite
  74. expansion and survive registry refreshes. Orchestrators get ``delegation`` re-added unconditionally
  75. (role-granted, not inherited)."""
  76. # enabled_toolsets=None means "all tools", so derive from loaded tool names.
  77. parent_enabled = getattr(parent_agent, "enabled_toolsets", None)
  78. if parent_enabled is not None:
  79. parent_toolsets = set(parent_enabled)
  80. elif parent_agent and hasattr(parent_agent, "valid_tool_names"):
  81. import model_tools
  82. parent_toolsets = {
  83. ts for name in parent_agent.valid_tool_names if (ts := model_tools.get_toolset_for_tool(name)) is not None
  84. }
  85. else:
  86. parent_toolsets = set(DEFAULT_TOOLSETS)
  87. if toolsets:
  88. expanded_parent = _expand_parent_toolsets(parent_toolsets)
  89. child_toolsets = [t for t in toolsets if t in expanded_parent]
  90. if _get_inherit_mcp_toolsets():
  91. # Append any parent MCP toolsets missing from the narrowed child.
  92. child_toolsets += [
  93. name for name in sorted(parent_toolsets) if _is_mcp_toolset_name(name) and name not in child_toolsets
  94. ]
  95. elif parent_agent and parent_enabled is not None:
  96. child_toolsets = parent_enabled
  97. else:
  98. child_toolsets = sorted(parent_toolsets) or DEFAULT_TOOLSETS
  99. child_toolsets = _strip_blocked_tools(child_toolsets)
  100. raw_parent_disabled = getattr(parent_agent, "disabled_toolsets", None)
  101. inherited_disabled = (
  102. [str(name) for name in raw_parent_disabled] if isinstance(raw_parent_disabled, (list, tuple, set)) else []
  103. )
  104. if effective_role == "orchestrator":
  105. inherited_disabled = [name for name in inherited_disabled if name != "delegation"]
  106. if "delegation" not in child_toolsets:
  107. child_toolsets.append("delegation")
  108. child_disabled_toolsets = list(
  109. dict.fromkeys(inherited_disabled + _blocked_toolsets_for_role(effective_role) + ["kanban"])
  110. )
  111. return child_toolsets, child_disabled_toolsets