plugins_cmd_capabilities.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. """Capability consent (#64228): declared-vs-granted reads, the consent screen, ``hermes plugins
  2. capabilities`` and the legacy ``allow_tool_override`` grant.
  3. Sibling of :mod:`hermes_cli.plugins_cmd` (the facade re-exports the names other modules use and is
  4. imported late here, never at module level).
  5. """
  6. from __future__ import annotations
  7. from pathlib import Path
  8. from typing import Optional
  9. from hermes_cli.plugin_capabilities import _child_dict
  10. def _pc():
  11. """The facade, read at call time: tests patch ``plugins_cmd.<name>`` and sibling calls must see it."""
  12. from hermes_cli import plugins_cmd
  13. return plugins_cmd
  14. def _set_plugin_entry_flag(plugin_id: str, key: str, value: bool) -> None:
  15. """Write ``plugins.entries.<plugin_id>.<key> = value`` into config.yaml."""
  16. from hermes_cli.config import load_config, save_config
  17. config = load_config()
  18. entry = _child_dict(_child_dict(_child_dict(config, "plugins"), "entries"), plugin_id)
  19. entry[key] = bool(value)
  20. save_config(config)
  21. # ── Capability consent flow (#64228) ─────────────────────────────────────────
  22. def _declared_capabilities_from_manifest(manifest: dict, plugin_name: str = "?") -> list:
  23. """Extract + normalize the ``capabilities:`` declaration from a manifest."""
  24. from hermes_cli.plugin_capabilities import parse_declared_capabilities
  25. return parse_declared_capabilities((manifest or {}).get("capabilities"), plugin_name)
  26. def _declared_capabilities_for_key(key: str) -> list:
  27. """Read the declared capabilities for an installed/bundled plugin by key."""
  28. entry = _pc()._find_plugin_entry(key)
  29. if entry is None:
  30. return []
  31. if entry[3] == "entrypoint":
  32. from hermes_cli.plugins import discover_entrypoint_manifests
  33. for manifest in discover_entrypoint_manifests():
  34. if key in (manifest.key, manifest.name):
  35. return list(manifest.capabilities)
  36. return []
  37. if not entry[4]:
  38. return []
  39. return _declared_capabilities_from_manifest(_pc()._read_manifest(Path(entry[4])), entry[0])
  40. def _run_capability_consent(console, plugin_id: str, declared: list, *, context: str = "install") -> bool:
  41. """Show the capability consent screen and record the decision; True when granted.
  42. On consent the pending capabilities are granted under
  43. ``plugins.entries.<id>.granted_capabilities`` with a hash of the declared set. On decline —
  44. or in ANY non-interactive context — they stay ungranted (fail closed) and the plugin must
  45. degrade via ``ctx.has_capability()``. Consent + audit, NOT a sandbox.
  46. """
  47. from hermes_cli.plugin_capabilities import CAPABILITY_REGISTRY, pending_capabilities, record_consent
  48. pending = pending_capabilities(plugin_id, declared)
  49. if not pending:
  50. # Refresh the consent hash so a later declaration change is detected.
  51. if declared:
  52. record_consent(plugin_id, [], declared)
  53. return True
  54. verb = "requests" if context == "install" else "now requests"
  55. console.print(f"\n [yellow]Plugin [bold]{plugin_id}[/bold] {verb} the following capabilities:[/yellow]")
  56. for cap in pending:
  57. spec = CAPABILITY_REGISTRY.get(cap)
  58. console.print(f" [bold]{cap}[/bold] — {spec.description if spec else ''}")
  59. console.print(
  60. " [dim]Granting trusts the plugin author with these host surfaces. "
  61. "This is consent, not a sandbox — plugins run as regular Python "
  62. "in-process.[/dim]")
  63. if not _pc()._is_tty():
  64. console.print(
  65. " [yellow]Non-interactive session: capabilities NOT granted "
  66. "(fail closed).[/yellow] Run "
  67. f"`hermes plugins capabilities {plugin_id}` to review and "
  68. f"`hermes plugins enable {plugin_id}` to grant interactively.")
  69. return False
  70. if _pc()._ask_yes(" Grant these capabilities? [y/N] ", console.input):
  71. record_consent(plugin_id, pending, declared)
  72. console.print(
  73. f" [green]✓[/green] Granted: {', '.join(pending)} "
  74. f"([dim]plugins.entries.{plugin_id}.granted_capabilities[/dim])")
  75. return True
  76. console.print(
  77. f" [dim]Declined. {plugin_id} stays enabled with these capabilities "
  78. "off; it should degrade gracefully (ctx.has_capability()). Re-run "
  79. f"`hermes plugins enable {plugin_id}` to grant later.[/dim]")
  80. return False
  81. def cmd_capabilities(name: Optional[str] = None) -> None:
  82. """``hermes plugins capabilities [<id>]`` — declared vs granted."""
  83. from hermes_cli.plugin_capabilities import (
  84. CAPABILITY_REGISTRY,
  85. granted_capabilities,
  86. plugin_capability_granted,
  87. )
  88. console = _pc()._console()
  89. if name is not None:
  90. hit = _pc()._find_plugin_entry(name)
  91. if hit is None:
  92. _pc()._fail(console, _pc()._unknown_plugin_message(name))
  93. name = hit[5] or hit[0]
  94. rows = []
  95. for entry in _pc()._discover_all_plugins():
  96. key = entry[5] or entry[0]
  97. if name is not None and name not in (key, entry[0]):
  98. continue
  99. declared = _declared_capabilities_for_key(key)
  100. granted = granted_capabilities(key)
  101. # Effective state includes grants live via deprecated allow_* keys.
  102. effective = {cap for cap in CAPABILITY_REGISTRY if plugin_capability_granted(key, cap)}
  103. if not declared and not effective and name is None:
  104. continue
  105. rows.append((key, entry[3], declared, granted, effective))
  106. if name is not None and not rows:
  107. _pc()._fail(console, _pc()._unknown_plugin_message(name))
  108. if not rows:
  109. console.print("[dim]No plugins declare or hold capabilities.[/dim]")
  110. return
  111. for key, source, declared, granted, effective in sorted(rows):
  112. console.print(f"[bold]{key}[/bold] [dim]({source})[/dim]")
  113. if not declared:
  114. console.print(" declared: [dim](none)[/dim]")
  115. for cap in declared:
  116. if cap not in effective:
  117. mark = "[yellow]not granted[/yellow]"
  118. elif cap in granted:
  119. mark = "[green]granted[/green]"
  120. else:
  121. mark = "[green]granted[/green] [dim](via legacy allow_* key — deprecated)[/dim]"
  122. console.print(f" {cap}: {mark}")
  123. for cap in sorted(effective - set(declared)):
  124. console.print(f" {cap}: [green]granted[/green] [dim](not declared in manifest)[/dim]")
  125. def _resolve_tool_override_grant(console, key: str, allow_tool_override: Optional[bool]) -> None:
  126. """Resolve and persist the ``allow_tool_override`` grant for a plugin."""
  127. if allow_tool_override is None:
  128. # Default NO: a blind Enter or a non-interactive stdin denies safely.
  129. allow_tool_override = _pc()._ask_yes(
  130. "[yellow]Allow this plugin to replace built-in tools "
  131. "(e.g. shell_exec, write_file)?[/yellow]\n"
  132. " This is a privileged capability: an override can intercept "
  133. "everything the agent routes through that tool.\n"
  134. " Grant it? [y/N] ",
  135. console.input,
  136. )
  137. _set_plugin_entry_flag(key, "allow_tool_override", allow_tool_override)
  138. if allow_tool_override:
  139. console.print(
  140. f"[green]✓[/green] Granted [bold]{key}[/bold] permission to "
  141. "override built-in tools "
  142. f"([dim]plugins.entries.{key}.allow_tool_override: true[/dim]).")
  143. else:
  144. console.print(
  145. f"[dim]{key} may not override built-in tools. Re-run "
  146. f"`hermes plugins enable {key} --allow-tool-override` to grant "
  147. "this later.[/dim]")