copilot_acp_client.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. """Deprecated alias module: use :class:`agent.acp_client.ACPClient`.
  2. Listed catalog ACP providers were built on this module at their pinned versions
  3. (kimchi-acp-provider, kiro-acp, grok-acp, cursor-acp). They subclass ``CopilotACPClient``,
  4. import former module helpers (``ACP_MARKER_BASE_URL``, ``_build_subprocess_env``,
  5. ``_acp_supported``, ``_model_selection_request``, ``_effective_timeout``) and patch
  6. ``subprocess.Popen`` through it. So the module keeps its whole former surface: the
  7. Copilot-flavoured names keep their former defaults (launch env vars, the ``copilot-acp``
  8. placeholder, the ``copilotEnablement`` model filter, the deprecated ``gh copilot`` extension
  9. diagnosis), and the generic rest is served from :mod:`agent.acp_client`. The first access of
  10. any of these names warns once per process. Remove no sooner than two minor releases after the
  11. deprecation (the plugin compat contract in ``plugins/AGENTS.md``).
  12. """
  13. from __future__ import annotations
  14. import os
  15. import shlex
  16. # A real attribute, not served by __getattr__: plugins patch ``agent.copilot_acp_client.subprocess.Popen``
  17. # (and ``.run``). It is the stdlib module itself, so such patches reach ACPClient's spawn and probe.
  18. import subprocess
  19. import warnings
  20. from typing import Any
  21. from agent import acp_client as _acp
  22. from agent.acp_client import ACPClient
  23. _warned = False
  24. _PLACEHOLDER = "copilot-acp"
  25. _COMMAND_ENV_VARS = ("HERMES_COPILOT_ACP_COMMAND", "COPILOT_CLI_PATH")
  26. _ARGS_ENV_VAR = "HERMES_COPILOT_ACP_ARGS"
  27. # Stderr fingerprint of the deprecated `gh copilot` extension: BOTH the product name AND a deprecation
  28. # marker (the new `@github/copilot` CLI legitimately mentions "copilot-cli").
  29. _GH_EXTENSION_REQUIRED = ("gh-copilot",)
  30. _GH_EXTENSION_MARKERS = ("has been deprecated", "no commands will be executed")
  31. _GH_EXTENSION_ERROR = (
  32. "Hermes ACP mode requires the NEW GitHub Copilot CLI (github.com/github/copilot-cli), but the binary it just "
  33. "spawned is the deprecated `gh copilot` extension.\n\n"
  34. "Install the new CLI:\n npm install -g @github/copilot\n # then verify with: copilot --help\n\n"
  35. "If `copilot` already resolves to the new CLI but you still see this,\npoint Hermes at it explicitly:\n"
  36. " export HERMES_COPILOT_ACP_COMMAND=/path/to/new/copilot\n\n"
  37. "Alternative: use the `copilot` provider (no ACP, hits the Copilot API\ndirectly with a Copilot subscription "
  38. "token) via `hermes setup`.\n\nOriginal error:\n"
  39. )
  40. def _copilot_disabled(entry: dict[str, Any]) -> bool:
  41. return str((entry.get("_meta") or {}).get("copilotEnablement") or "").strip().lower() == "disabled"
  42. def _is_gh_extension_banner(stderr_text: str) -> bool:
  43. lower = stderr_text.lower()
  44. return any(req in lower for req in _GH_EXTENSION_REQUIRED) and any(m in lower for m in _GH_EXTENSION_MARKERS)
  45. class _DeprecatedCopilotACPClient(ACPClient):
  46. """ACPClient with the historical launch defaults, labels, model filter and early-exit diagnosis."""
  47. default_command = "copilot"
  48. default_args = ("--acp", "--stdio")
  49. command_env_vars = _COMMAND_ENV_VARS
  50. args_env_var = _ARGS_ENV_VAR
  51. marker_base_url = "acp://copilot"
  52. placeholder_model = _PLACEHOLDER
  53. label = "Copilot ACP"
  54. missing_command_hint = "Install GitHub Copilot CLI or set HERMES_COPILOT_ACP_COMMAND/COPILOT_CLI_PATH."
  55. unsupported_transport_hint = (
  56. "Either install a CLI that ships with --acp support (e.g. `@github/copilot` late 2025+), or set "
  57. "HERMES_COPILOT_ACP_COMMAND / HERMES_COPILOT_ACP_ARGS to a working pair.")
  58. def model_entry_disabled(self, entry: dict[str, Any]) -> bool:
  59. return _copilot_disabled(entry)
  60. def early_exit_error(self, stderr_text: str) -> str | None:
  61. return _GH_EXTENSION_ERROR + stderr_text if _is_gh_extension_banner(stderr_text) else None
  62. _DeprecatedCopilotACPClient.__name__ = _DeprecatedCopilotACPClient.__qualname__ = "CopilotACPClient"
  63. def _former_resolve_command() -> str:
  64. return next((v for name in _COMMAND_ENV_VARS if (v := os.getenv(name, "").strip())), "") or "copilot"
  65. def _former_resolve_args() -> list[str]:
  66. return shlex.split(os.getenv(_ARGS_ENV_VAR, "").strip()) or ["--acp", "--stdio"]
  67. def _former_enabled_id_list(entries: Any, key: str) -> list[str]:
  68. return _acp._enabled_id_list(entries, key, _copilot_disabled)
  69. def _former_session_model_ids(session: dict[str, Any]) -> list[str]:
  70. return _acp._session_model_ids(session, _copilot_disabled)
  71. def _former_legacy_session_model_ids(session: dict[str, Any]) -> list[str]:
  72. return _acp._legacy_session_model_ids(session, _copilot_disabled)
  73. def _former_model_selection_request(session: dict[str, Any], requested_model: str) -> tuple[str, dict[str, str]] | None:
  74. return _acp._model_selection_request(session, requested_model, placeholder=_PLACEHOLDER, disabled=_copilot_disabled)
  75. # Former names whose behaviour is Copilot-flavoured: served from here with their former defaults.
  76. _COMPAT: dict[str, Any] = {
  77. "CopilotACPClient": _DeprecatedCopilotACPClient,
  78. "ACP_MARKER_BASE_URL": "acp://copilot",
  79. "_DEPRECATION_REQUIRED": _GH_EXTENSION_REQUIRED,
  80. "_DEPRECATION_MARKERS": _GH_EXTENSION_MARKERS,
  81. "_DEPRECATED_CLI_ERROR": _GH_EXTENSION_ERROR,
  82. "_is_gh_copilot_deprecation_message": _is_gh_extension_banner,
  83. "_resolve_command": _former_resolve_command,
  84. "_resolve_args": _former_resolve_args,
  85. "_enabled_id_list": _former_enabled_id_list,
  86. "_session_model_ids": _former_session_model_ids,
  87. "_legacy_session_model_ids": _former_legacy_session_model_ids,
  88. "_model_selection_request": _former_model_selection_request,
  89. }
  90. # Former names with unchanged behaviour: the very objects agent.acp_client uses (shared caches included).
  91. _FORWARDED = frozenset({
  92. "logger", "_DEFAULT_TIMEOUT_SECONDS", "_ROLE_LABELS", "_ACP_PROBE_CACHE", "_PROMPT_PREAMBLE", "_INITIALIZE_PARAMS",
  93. "_acp_supported", "_resolve_home_dir", "_build_subprocess_env", "_jsonrpc_result", "_jsonrpc_error",
  94. "_model_config_option", "_format_messages_as_prompt", "_render_message_content", "_ensure_path_within_cwd",
  95. "_effective_timeout", "_fs_read_text_file", "_fs_write_text_file", "_FS_HANDLERS",
  96. "contextlib", "json", "logging", "queue", "re", "tempfile", "threading", "time", "deque", "Callable", "Iterator",
  97. "Path", "SimpleNamespace", "_completion_to_stream_chunks", "_extract_tool_calls_from_text",
  98. "_render_tool_bridge_sections", "get_nt_namespace_error", "get_read_block_error", "get_write_denied_error",
  99. "is_write_approval_required", "redact_sensitive_text", "resolve_agent_cwd",
  100. })
  101. def _former_attribute(name: str) -> Any:
  102. if name in _COMPAT:
  103. return _COMPAT[name]
  104. if name in _FORWARDED:
  105. return getattr(_acp, name)
  106. if name == "hermes_subprocess_env":
  107. from tools.environments.local import hermes_subprocess_env # lazy: hermes_cli.config may still be importing
  108. return hermes_subprocess_env
  109. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  110. def __getattr__(name: str) -> Any:
  111. global _warned
  112. value = _former_attribute(name)
  113. if not _warned:
  114. _warned = True
  115. warnings.warn(
  116. f"agent.copilot_acp_client.{name} is deprecated; subclass agent.acp_client.ACPClient instead.",
  117. DeprecationWarning, stacklevel=2)
  118. return value
  119. def __dir__() -> list[str]:
  120. return sorted({*globals(), *_COMPAT, *_FORWARDED, "hermes_subprocess_env"})