terminal_env_registry.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """Terminal Environment Registry.
  2. Central map of registered pluggable terminal backends, populated by plugins via
  3. :meth:`PluginContext.register_terminal_environment_provider` and consumed by
  4. :func:`tools.terminal_tool_backends._create_environment` plus the classification helpers across the
  5. terminal/file/approval/prompt surfaces. Unlike the image/video/web/browser registries there
  6. is **no active-provider resolution**: the active backend is whatever ``TERMINAL_ENV`` /
  7. ``terminal.backend`` names. Built-in names are reserved (registration raises) so a plugin can
  8. never shadow the in-tree docker/modal/... implementations. Scope semantics mirror
  9. :mod:`agent.browser_registry` (per-profile scope or the global base map).
  10. """
  11. from __future__ import annotations
  12. import logging
  13. from typing import List, Optional
  14. from agent.provider_registry import ProviderRegistry, lower_key
  15. from agent.terminal_env_provider import TerminalEnvironmentProvider
  16. logger = logging.getLogger(__name__)
  17. #: Names owned by in-tree backends in tools/environments/ — never
  18. #: registrable by plugins. Includes internal-mode aliases (managed_modal).
  19. BUILTIN_BACKEND_NAMES = frozenset({
  20. "local", "docker", "modal", "managed_modal",
  21. "daytona", "vercel_sandbox", "ssh",
  22. })
  23. def _reject_builtin_collision(name: str) -> None:
  24. raise ValueError(f"Terminal backend name '{name}' is reserved for the built-in {name} backend "
  25. "and cannot be registered by a plugin")
  26. _registry: ProviderRegistry[TerminalEnvironmentProvider] = ProviderRegistry(
  27. label="Terminal environment",
  28. provider_cls=TerminalEnvironmentProvider,
  29. logger=logger,
  30. normalize=lower_key,
  31. builtin_names=BUILTIN_BACKEND_NAMES,
  32. on_builtin_collision=_reject_builtin_collision,
  33. )
  34. _registry.export(globals())
  35. def plugin_backend_names(*, scope: Optional[str] = None) -> list[str]:
  36. """Names of all registered plugin backends (sorted)."""
  37. return [p.name.strip().lower() for p in _registry.list_providers(scope=scope)]
  38. def provider_flag(name: str, attr: str, default=False, *, scope: Optional[str] = None):
  39. """Read a classification attribute off the provider for *name*.
  40. Fail-soft: unknown backend or a raising property returns *default* so a misbehaving
  41. plugin degrades to built-in-equivalent behavior instead of taking the terminal tool down.
  42. *scope* names the profile home whose registrations to consult (default: the active home);
  43. a caller deciding for a session bound to another profile passes that profile's home.
  44. """
  45. provider = _registry.get_provider(name, scope=scope)
  46. if provider is None:
  47. return default
  48. try:
  49. return getattr(provider, attr, default)
  50. except Exception:
  51. logger.debug("Terminal environment provider '%s' attribute '%s' raised", name, attr, exc_info=True)
  52. return default
  53. def plugin_strip_env_keys() -> frozenset:
  54. """Union of every registered provider's ``strip_env_keys`` — across ALL scopes, not
  55. just the active backend: a token in the process environment is strippable regardless of
  56. which backend is selected (as MODAL_*/DAYTONA_API_KEY sit in the static tier-1 set)."""
  57. keys: set = set()
  58. with _registry._lock:
  59. all_providers = list(_registry._providers.values())
  60. for scoped in _registry._scoped_providers.values():
  61. all_providers.extend(scoped.values())
  62. for provider in all_providers:
  63. try:
  64. keys.update(provider.strip_env_keys)
  65. except Exception:
  66. logger.debug("Terminal environment provider strip_env_keys raised", exc_info=True)
  67. return frozenset(keys)