The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(acp): generic public ACPClient; Copilot quirks move into the copilot-acp plugin
Teknium33566e526208
diff --git a/agent/acp_client.py b/agent/acp_client.pynew file mode 100644index 00000000000..337f755dd6f--- /dev/null+++ b/agent/acp_client.py@@ -0,0 +1,541 @@+"""Generic ACP (Agent Client Protocol) stdio client behind a minimal OpenAI-client facade.++The public base for ``external_process`` model providers: a provider profile's+``create_client`` returns an :class:`ACPClient` (or a subclass). Each request starts a+short-lived ACP session with the agent CLI, sends the formatted conversation as one prompt,+collects text chunks, and returns the minimal OpenAI-client shape.++Subclasses customise the launch defaults and vendor quirks through class attributes+(``default_command``, ``default_args``, ``command_env_vars``, ``args_env_var``,+``marker_base_url``, ``placeholder_model``, ``label``, ``missing_command_hint``,+``unsupported_transport_hint``) and two hooks (:meth:`ACPClient.model_entry_disabled`,+:meth:`ACPClient.early_exit_error`).+"""++from __future__ import annotations++import contextlib+import json+import logging+import os+import queue+import re+import shlex+import subprocess+import tempfile+import threading+import time+from collections import deque+from collections.abc import Callable, Iterator+from pathlib import Path+from types import SimpleNamespace+from typing import Any++from agent.acp_openai_bridge import (+ completion_to_stream_chunks as _completion_to_stream_chunks,+ extract_tool_calls_from_text as _extract_tool_calls_from_text,+ render_tool_bridge_sections as _render_tool_bridge_sections,+)+from agent.file_safety import (+ get_nt_namespace_error, get_read_block_error, get_write_denied_error, is_write_approval_required)+from agent.redact import redact_sensitive_text+from agent.runtime_cwd import resolve_agent_cwd++logger = logging.getLogger(__name__)+_DEFAULT_TIMEOUT_SECONDS = 900.0+_ROLE_LABELS = {"system": "System", "user": "User", "assistant": "Assistant", "tool": "Tool", "context": "Context"}+# Probe verdicts per binary path (~50ms --help paid once per process). Only definitive+# True/False is cached, so a CLI installed mid-session is picked up.+_ACP_PROBE_CACHE: dict[str, bool] = {}+_PROMPT_PREAMBLE = (+ "You are being used as the active ACP agent backend for Hermes.",+ "Use ACP capabilities to complete tasks.",+ "IMPORTANT: If you take an action with a tool, you MUST output tool calls using <tool_call>{...}</tool_call> blocks with JSON exactly in OpenAI function-call shape.",+ "If no tool is needed, answer normally.",+)+_INITIALIZE_PARAMS = {+ "protocolVersion": 1,+ "clientCapabilities": {"fs": {"readTextFile": True, "writeTextFile": True}},+ "clientInfo": {"name": "hermes-agent", "title": "Hermes Agent", "version": "0.0.0"},+}+def _acp_supported(command: str, args: list[str]) -> bool | None:+ """Tri-state ``--acp`` probe (a CLI without the flag exits 1 and the parent would wait the+ full child timeout for stdout that never arrives). True = help advertises --acp; False =+ help ran cleanly without it (caller fast-fails); None = inconclusive (binary missing /+ --help failed → normal spawn error). Skipped when ``--acp`` is not in ``args`` (custom transport)."""+ if "--acp" not in args:+ return True+ if (cached := _ACP_PROBE_CACHE.get(command)) is not None:+ return cached+ try:+ probe = subprocess.run(+ [command, "--help"],+ # Explicit codec because text=True alone decodes with the+ # locale default and crashes on non-ASCII help text under+ # GBK/CP932 locales.+ capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=5,+ stdin=subprocess.DEVNULL,+ check=False,+ )+ except (FileNotFoundError, subprocess.TimeoutExpired, OSError):+ return None+ if probe.returncode != 0:+ return None+ # ``--acp`` as a flag token; tolerate spacing and ``[--acp]`` variants.+ verdict = _ACP_PROBE_CACHE[command] = bool(re.search(r"(?:^|[\s\[])--acp(?:[\s=\],]|$)", probe.stdout, re.MULTILINE))+ return verdict+++def _resolve_home_dir() -> str:+ """Stable HOME for child ACP processes; the temp dir as a last resort so the child never starts HOME-less."""+ if home := os.environ.get("HOME", "").strip():+ return home+ if (expanded := os.path.expanduser("~")) and expanded != "~":+ return expanded+ try:+ import pwd++ return pwd.getpwuid(os.getuid()).pw_dir.strip() or tempfile.gettempdir() # windows-footgun: ok — POSIX fallback inside try/except (pwd import fails on Windows)+ except Exception:+ return tempfile.gettempdir()+++def _build_subprocess_env() -> dict[str, str]:+ # Lazy: the env policy imports hermes_cli.config, and provider plugins import this module+ # while hermes_cli.config is still initializing (discovery runs from it).+ from hermes_constants import apply_subprocess_home_env+ from tools.environments.local import hermes_subprocess_env++ # An ACP agent drives a model and needs LLM provider credentials; the central helper still+ # strips Tier-1 secrets (bot tokens, GitHub auth, infra).+ # See #29157.+ env = hermes_subprocess_env(inherit_credentials=True)+ env["HOME"] = _resolve_home_dir()+ apply_subprocess_home_env(env)+ return env+++def _jsonrpc_result(message_id: Any, result: Any) -> dict[str, Any]:+ return {"jsonrpc": "2.0", "id": message_id, "result": result}+++def _jsonrpc_error(message_id: Any, code: int, message: str) -> dict[str, Any]:+ return {"jsonrpc": "2.0", "id": message_id, "error": {"code": code, "message": message}}+++def _never_disabled(entry: dict[str, Any]) -> bool:+ return False+++def _enabled_id_list(entries: Any, key: str, disabled: Callable[[dict[str, Any]], bool] = _never_disabled) -> list[str]:+ """Ordered unique ids of the entries ``disabled`` does not reject."""+ seen: set[str] = set()+ result: list[str] = []+ for entry in entries or []:+ if not isinstance(entry, dict):+ continue+ value = str(entry.get(key) or "").strip()+ if not value or value in seen or disabled(entry):+ continue+ seen.add(value)+ result.append(value)+ return result+++def _model_config_option(session: dict[str, Any]) -> dict[str, Any] | None:+ return next((option for option in (session.get("configOptions") or []) if isinstance(option, dict)+ and "model" in (option.get("category"), option.get("id"))), None)+++def _session_model_ids(session: dict[str, Any], disabled: Callable[[dict[str, Any]], bool] = _never_disabled) -> list[str]:+ """Account-authorized model ids advertised by ``session/new`` in ACP v1 or its legacy extension."""+ if option := _model_config_option(session):+ return _enabled_id_list(option.get("options"), "value", disabled)+ return _legacy_session_model_ids(session, disabled)+++def _legacy_session_model_ids(session: dict[str, Any], disabled: Callable[[dict[str, Any]], bool] = _never_disabled) -> list[str]:+ return _enabled_id_list((session.get("models") or {}).get("availableModels"), "modelId", disabled)+++def _model_selection_request(+ session: dict[str, Any], requested_model: str, *, placeholder: str = "",+ disabled: Callable[[dict[str, Any]], bool] = _never_disabled,+) -> tuple[str, dict[str, str]] | None:+ """ACP request selecting ``requested_model`` for ``session``: stable v1+ ``session/set_config_option``, else the pre-stabilization ``session/set_model`` when no+ model config option is advertised. A reported model list is authoritative: unknown and+ ``disabled`` ids return None instead of being sent, as does the provider's ``placeholder``+ id (meaning "the session default")."""+ session_id = str(session.get("sessionId") or "").strip()+ requested_model = str(requested_model or "").strip()+ if not session_id or not requested_model or requested_model == placeholder:+ return None+ option = _model_config_option(session)+ if option:+ if requested_model not in _enabled_id_list(option.get("options"), "value", disabled):+ return None+ return "session/set_config_option", {"sessionId": session_id, "configId": str(option.get("id") or "model"), "value": requested_model}+ available = _legacy_session_model_ids(session, disabled)+ return None if available and requested_model not in available else ("session/set_model", {"sessionId": session_id, "modelId": requested_model})+++def _format_messages_as_prompt(+ messages: list[dict[str, Any]], model: str | None = None, tools: list[dict[str, Any]] | None = None, tool_choice: Any = None,+) -> str:+ # Deliberately no "requested model" line: the model is applied for real via ACP session/set_model;+ # a prompt-text mention makes a substituted backend model FALSELY self-identify as the requested+ # one. The whole Hermes toolset is forwarded; the agent's own tools run inside the agent.+ sections: list[str] = [*_PROMPT_PREAMBLE, *_render_tool_bridge_sections(tools, tool_choice)]+ transcript: list[str] = []+ for message in (m for m in messages if isinstance(m, dict)):+ role = str(message.get("role") or "unknown").strip().lower()+ if rendered := _render_message_content(message.get("content")):+ transcript.append(f"{_ROLE_LABELS.get(role, 'Context')}:\n{rendered}")+ if transcript:+ sections.append("Conversation transcript:\n\n" + "\n\n".join(transcript))+ sections.append("Continue the conversation from the latest user request.")+ return "\n\n".join(section.strip() for section in sections if section and section.strip())+++def _render_message_content(content: Any) -> str:+ if content is None:+ return ""+ if isinstance(content, dict):+ if "text" in content:+ return str(content.get("text") or "").strip()+ return content["content"].strip() if isinstance(content.get("content"), str) else json.dumps(content, ensure_ascii=True)+ if isinstance(content, list):+ parts = [item if isinstance(item, str) else item["text"].strip() for item in content if isinstance(item, str)+ or (isinstance(item, dict) and isinstance(item.get("text"), str) and item["text"].strip())]+ return "\n".join(parts).strip()+ return str(content).strip()+++def _ensure_path_within_cwd(path_text: str, cwd: str, *, verb: str) -> Path:+ # Raw-string check BEFORE resolve(): resolving an NT-namespace path is the NTLM-leak trigger.+ if nt_error := get_nt_namespace_error(path_text, verb=verb):+ raise PermissionError(nt_error)+ if not Path(path_text).is_absolute():+ raise PermissionError("ACP file-system paths must be absolute.")+ resolved, root = Path(path_text).resolve(), Path(cwd).resolve()+ try:+ resolved.relative_to(root)+ except ValueError as exc:+ raise PermissionError(f"Path '{resolved}' is outside the session cwd '{root}'.") from exc+ return resolved+++def _effective_timeout(timeout: Any) -> float:+ """Normalise a float or httpx.Timeout-like object to wall-clock seconds (largest component wins)."""+ if isinstance(timeout, (int, float)):+ return float(timeout)+ candidates = [getattr(timeout, attr, None) for attr in ("read", "write", "connect", "pool", "timeout")]+ return max((float(v) for v in candidates if isinstance(v, (int, float))), default=_DEFAULT_TIMEOUT_SECONDS)+++def _fs_read_text_file(params: dict[str, Any], cwd: str) -> Any:+ path = _ensure_path_within_cwd(str(params.get("path") or ""), cwd, verb="Read")+ if block_error := get_read_block_error(str(path)):+ raise PermissionError(block_error)+ try:+ content = path.read_text(encoding="utf-8-sig")+ except FileNotFoundError:+ content = ""+ line, limit = params.get("line"), params.get("limit")+ if isinstance(line, int) and line > 1:+ end = line - 1 + limit if isinstance(limit, int) and limit > 0 else None+ content = "".join(content.splitlines(keepends=True)[line - 1:end])+ return {"content": redact_sensitive_text(content, force=True) if content else content}+++def _fs_write_text_file(params: dict[str, Any], cwd: str) -> Any:+ path = _ensure_path_within_cwd(str(params.get("path") or ""), cwd, verb="Write")+ if denied := get_write_denied_error(str(path)):+ raise PermissionError(denied)+ if is_write_approval_required(str(path)): # soft-gated for interactive tools; the ACP shim has no human channel → fail closed+ raise PermissionError(f"Write denied: '{path}' requires interactive approval and cannot be written through the ACP file bridge.")+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(str(params.get("content") or ""), encoding="utf-8")+ return None+++_FS_HANDLERS = {"fs/read_text_file": _fs_read_text_file, "fs/write_text_file": _fs_write_text_file}+++class ACPClient:+ """Minimal OpenAI-client-compatible facade over one ACP agent CLI spoken to on stdio.++ Construct it with the resolved ``command``/``args`` (what+ ``resolve_external_process_provider_credentials`` returns for the provider); the class+ attributes below are only the fallback when a caller passes neither.+ """++ # Declared for agent/auxiliary_client.py: this shim drives an ACP subprocess over stdio, so it is+ # already a complete client (never re-dispatch through a wire adapter) and async-safe as-is.+ HERMES_SKIP_TRANSPORT_WRAP = True+ HERMES_SKIP_ASYNC_WRAP = True++ #: Binary and argv tail used when the caller passes no command/args; env vars win, in order.+ default_command: str = ""+ default_args: tuple[str, ...] = ()+ command_env_vars: tuple[str, ...] = ()+ args_env_var: str = ""+ #: ``base_url`` reported when none is passed (an ``acp://`` marker, never dialled).+ marker_base_url: str = "acp://agent"+ #: Model id meaning "the session default": never sent as a model selection.+ placeholder_model: str = "acp"+ #: Product name in errors and log lines.+ label: str = "ACP"+ #: Error text after "Could not start <label> command '<cmd>'." (default names ``command_env_vars``).+ missing_command_hint: str = ""+ #: Error text after the ``--acp`` probe rejects the CLI.+ unsupported_transport_hint: str = (+ "Either install a CLI release that supports --acp, or point the provider at a working command/args pair.")++ def model_entry_disabled(self, entry: dict[str, Any]) -> bool:+ """True when an advertised model entry is unavailable to this account (vendor ``_meta``)."""+ return False++ def early_exit_error(self, stderr_text: str) -> str | None:+ """Error message for a CLI that exited before answering, or None for the generic one."""+ return None++ def _resolve_command(self) -> str:+ return next((v for name in self.command_env_vars if (v := os.getenv(name, "").strip())), "") or self.default_command++ def _resolve_args(self) -> list[str]:+ override = os.getenv(self.args_env_var, "").strip() if self.args_env_var else ""+ return shlex.split(override) or list(self.default_args)++ def _missing_command_hint(self) -> str:+ if self.missing_command_hint:+ return self.missing_command_hint+ return f"Install the agent CLI or set {'/'.join(self.command_env_vars)}." if self.command_env_vars else "Install the agent CLI."++ def __init__(+ self, *, api_key: str | None = None, base_url: str | None = None, default_headers: dict[str, str] | None = None,+ acp_command: str | None = None, acp_args: list[str] | None = None, acp_cwd: str | None = None, command: str | None = None,+ args: list[str] | None = None, **_: Any,+ ):+ self.api_key, self.base_url = api_key or self.placeholder_model, base_url or self.marker_base_url+ self._default_headers = dict(default_headers or {})+ self._acp_command = acp_command or command or self._resolve_command()+ self._acp_args = list(acp_args or args or self._resolve_args())+ # The session's workspace, not the process cwd: under the gateway every turn runs in+ # the daemon (or a managed worker) whose own cwd is unrelated to the client's.+ self._acp_cwd = str(Path(acp_cwd or resolve_agent_cwd()).resolve())+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create_chat_completion))+ self.is_closed = False+ # Clients are cached and shared across concurrent callers (auxiliary tasks, async+ # dispatch), so several ACP sessions can be live on one instance. Track every live+ # child — a single slot would let one session's teardown kill a sibling's process+ # while its own leaked.+ self._active_processes: set[subprocess.Popen[str]] = set()+ self._active_process_lock = threading.Lock()++ @staticmethod+ def _terminate_process(proc: subprocess.Popen[str]) -> None:+ try:+ proc.terminate()+ proc.wait(timeout=2)+ except Exception:+ with contextlib.suppress(Exception):+ proc.kill()++ def _release_process(self, proc: subprocess.Popen[str]) -> None:+ """Reap one session's own child. ``is_closed`` flips only when the last live+ session drains — marking it while siblings still run would tell lifecycle code+ to rebuild a client that is mid-request."""+ with self._active_process_lock:+ self._active_processes.discard(proc)+ if not self._active_processes:+ self.is_closed = True+ self._terminate_process(proc)++ def close(self) -> None:+ with self._active_process_lock:+ procs, self._active_processes = tuple(self._active_processes), set()+ self.is_closed = True+ for proc in procs:+ self._terminate_process(proc)++ def _create_chat_completion(+ self, *, model: str | None = None, messages: list[dict[str, Any]] | None = None, timeout: float | None = None,+ tools: list[dict[str, Any]] | None = None, tool_choice: Any = None, stream: bool = False, **_: Any,+ ) -> Any:+ prompt_text = _format_messages_as_prompt(messages or [], model=model, tools=tools, tool_choice=tool_choice)+ response_text, reasoning = self._run_prompt(prompt_text, timeout_seconds=_effective_timeout(timeout), model=model)+ tool_calls, cleaned_text = _extract_tool_calls_from_text(response_text)+ message = SimpleNamespace(+ content=cleaned_text, tool_calls=tool_calls, reasoning=reasoning or None, reasoning_content=reasoning or None,+ reasoning_details=None,+ )+ completion = SimpleNamespace(+ choices=[SimpleNamespace(message=message, finish_reason="tool_calls" if tool_calls else "stop")],+ usage=SimpleNamespace(prompt_tokens=0, completion_tokens=0, total_tokens=0, prompt_tokens_details=SimpleNamespace(cached_tokens=0)),+ model=model or self.placeholder_model,+ )+ return _completion_to_stream_chunks(completion) if stream else completion++ def _spawn(self) -> subprocess.Popen[str]:+ # Fast-fail when the CLI rejects --acp (else the parent waits the full child timeout for stdout that+ # never arrives). ``None`` falls through to the spawn's established start error.+ if _acp_supported(self._acp_command, self._acp_args) is False:+ preview = " ".join(self._acp_args[:3]) if self._acp_args else "(none)"+ raise RuntimeError(+ f"ACP transport not supported by '{self._acp_command}': `{preview}` is rejected as an unknown option. This "+ "usually means the CLI is an older release (e.g. Claude Code v2.x) or a different tool than expected. "+ + self.unsupported_transport_hint+ )+ try:+ from hermes_cli._subprocess_compat import windows_hide_flags # hide the Windows console flash (#56747); pipes intact for the ACP wire++ # Hide the console the CLI child would otherwise flash on Windows (#56747). Hide-only — stdio+ # pipes stay intact for the ACP wire.+ proc = subprocess.Popen(+ [self._acp_command] + self._acp_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ text=True, encoding='utf-8', errors='replace', bufsize=1, cwd=self._acp_cwd, env=_build_subprocess_env(),+ creationflags=windows_hide_flags(),+ )+ except FileNotFoundError as exc:+ raise RuntimeError(+ f"Could not start {self.label} command '{self._acp_command}'. {self._missing_command_hint()}") from exc+ if proc.stdin is None or proc.stdout is None:+ proc.kill()+ raise RuntimeError(f"{self.label} process did not expose stdin/stdout pipes.")+ with self._active_process_lock:+ self._active_processes.add(proc)+ self.is_closed = False+ return proc++ @contextlib.contextmanager+ def _session(+ self, timeout_seconds: float, *, allow_file_requests: bool = True+ ) -> Iterator[tuple[dict[str, Any], Callable[..., Any]]]:+ """Start one ACP process and yield its ``session/new`` result plus request callable."""+ proc = self._spawn()+ inbox: queue.Queue[dict[str, Any]] = queue.Queue()+ stderr_tail: deque[str] = deque(maxlen=40)++ def _decode(line: str) -> dict[str, Any]:+ try:+ return json.loads(line)+ except Exception:+ return {"raw": line.rstrip("\n")}++ def _pump(stream, sink) -> None:+ for line in stream or ():+ sink(line)++ threading.Thread(target=_pump, args=(proc.stdout, lambda line: inbox.put(_decode(line))), daemon=True).start()+ stderr_pump = threading.Thread(+ target=_pump, args=(proc.stderr, lambda line: stderr_tail.append(line.rstrip("\n"))), daemon=True)+ stderr_pump.start()+ request_ids = iter(range(1, 1 << 62))+ # One budget for the WHOLE session (initialize + session/new + any prompt), not per+ # request: a hung CLI must not get 2x the caller's timeout on the foreground /model path.+ session_deadline = time.monotonic() + timeout_seconds++ def _request(method: str, params: dict[str, Any], *, text_parts: list[str] | None = None,+ reasoning_parts: list[str] | None = None) -> Any:+ request_id = next(request_ids)+ proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}) + "\n")+ proc.stdin.flush()+ deadline = session_deadline+ while time.monotonic() < deadline and proc.poll() is None:+ try:+ msg = inbox.get(timeout=0.1)+ except queue.Empty:+ continue+ if self._handle_server_message(+ msg, process=proc, cwd=self._acp_cwd, text_parts=text_parts,+ reasoning_parts=reasoning_parts, allow_file_requests=allow_file_requests,+ ) or msg.get("id") != request_id:+ continue+ if "error" in msg:+ err = msg.get("error") or {}+ raise RuntimeError(f"{self.label} {method} failed: {err.get('message') or err}")+ return msg.get("result")+ if proc.poll() is not None:+ # The pump can still hold the crash text when poll() first sees the exit; reading+ # it too early turned a dead CLI into a TimeoutError, which retries differently.+ stderr_pump.join(timeout=1.0)+ stderr_text = "\n".join(stderr_tail).strip()+ if (vendor_error := self.early_exit_error(stderr_text)) is not None:+ raise RuntimeError(vendor_error)+ raise RuntimeError(f"{self.label} process exited early: {stderr_text or f'exit code {proc.returncode}'}")+ raise TimeoutError(f"Timed out waiting for {self.label} response to {method}.")++ try:+ _request("initialize", _INITIALIZE_PARAMS)+ session = _request("session/new", {"cwd": self._acp_cwd, "mcpServers": []}) or {}+ if not str(session.get("sessionId") or "").strip():+ raise RuntimeError(f"{self.label} did not return a sessionId.")+ yield session, _request+ finally:+ self._release_process(proc)++ def list_models(self, *, timeout_seconds: float = 15.0) -> list[str]:+ """Return the enabled models advertised by a short-lived authenticated ACP session."""+ with self._session(timeout_seconds, allow_file_requests=False) as (session, _):+ return _session_model_ids(session, self.model_entry_disabled)++ def _run_prompt(self, prompt_text: str, *, timeout_seconds: float, model: str | None = None) -> tuple[str, str]:+ # No `--model` spawn flag: agent CLIs may validate it (an unknown id aborts the spawn) yet ignore it+ # for the session, so the model is applied over ACP after session/new instead.+ requested_model = str(model or "").strip()+ with self._session(timeout_seconds) as (session, _request):+ session_id = str(session.get("sessionId") or "").strip()+ if requested_model and requested_model != self.placeholder_model:+ try:+ selection = _model_selection_request(+ session, requested_model, placeholder=self.placeholder_model, disabled=self.model_entry_disabled)+ if selection is not None:+ _request(*selection)+ else:+ logger.warning("%s does not offer model %r; using the session default.", self.label, requested_model)+ except (RuntimeError, TimeoutError, OSError) as exc: # what _request raises (OSError: broken pipe)+ logger.warning("%s model selection for %r failed; continuing with the session default: %s",+ self.label, requested_model, exc)+ text_parts: list[str] = []+ reasoning_parts: list[str] = []+ prompt = {"sessionId": session_id, "prompt": [{"type": "text", "text": prompt_text}]}+ _request("session/prompt", prompt, text_parts=text_parts, reasoning_parts=reasoning_parts)+ return "".join(text_parts), "".join(reasoning_parts)++ def _handle_server_message(+ self, msg: dict[str, Any], *, process: subprocess.Popen[str], cwd: str, text_parts: list[str] | None, reasoning_parts: list[str] | None,+ allow_file_requests: bool = True,+ ) -> bool:+ """Consume a server->client message; True when handled (notification or request answered)."""+ method = msg.get("method")+ if not isinstance(method, str):+ return False+ if method == "session/update":+ update = (msg.get("params") or {}).get("update") or {}+ content = update.get("content") or {}+ chunk_text = str(content.get("text") or "") if isinstance(content, dict) else ""+ sinks = {"agent_message_chunk": text_parts, "agent_thought_chunk": reasoning_parts}+ if chunk_text and (sink := sinks.get(str(update.get("sessionUpdate") or "").strip())) is not None:+ sink.append(chunk_text)+ return True+ if process.stdin is None:+ return True+ message_id = msg.get("id")+ if method == "session/request_permission":+ response = _jsonrpc_result(message_id, {"outcome": {"outcome": "cancelled"}})+ elif method in _FS_HANDLERS:+ if not allow_file_requests:+ response = _jsonrpc_error(message_id, -32601, "File access is unavailable during model discovery.")+ else:+ try:+ response = _jsonrpc_result(message_id, _FS_HANDLERS[method](msg.get("params") or {}, cwd))+ except Exception as exc:+ response = _jsonrpc_error(message_id, -32602, str(exc))+ else:+ response = _jsonrpc_error(message_id, -32601, f"ACP client method '{method}' is not supported by Hermes yet.")+ process.stdin.write(json.dumps(response) + "\n")+ process.stdin.flush()+ return Truediff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.pyindex f87010ebe72..4fd414518bc 100644--- a/agent/copilot_acp_client.py+++ b/agent/copilot_acp_client.py@@ -1,510 +1,50 @@-"""OpenAI-compatible shim that forwards Hermes requests to `copilot --acp`.+"""Deprecated alias module: use :class:`agent.acp_client.ACPClient`.-Each request starts a short-lived ACP session, sends the formatted conversation-as one prompt, collects text chunks, and returns the minimal OpenAI-client shape.+Out-of-tree ACP providers (the ``kimchi-acp-provider`` catalog plugin) subclass+``CopilotACPClient`` from here. It keeps its historical launch fallbacks, error wording and+model-enablement filter so such subclasses behave as before. Remove no sooner than two minor releases after the deprecation (the plugin+compat contract in ``plugins/AGENTS.md``)."""from __future__ import annotations-import contextlib-import json-import logging-import os-import queue-import re-import shlex-import subprocess-import tempfile-import threading-import time-from collections import deque-from collections.abc import Callable, Iterator-from pathlib import Path-from types import SimpleNamespace+import warningsfrom typing import Any-from agent.acp_openai_bridge import (- completion_to_stream_chunks as _completion_to_stream_chunks,- extract_tool_calls_from_text as _extract_tool_calls_from_text,- render_tool_bridge_sections as _render_tool_bridge_sections,-)-from agent.file_safety import (- get_nt_namespace_error, get_read_block_error, get_write_denied_error, is_write_approval_required)-from agent.redact import redact_sensitive_text-from agent.runtime_cwd import resolve_agent_cwd-from tools.environments.local import hermes_subprocess_env+from agent.acp_client import ACPClient-ACP_MARKER_BASE_URL = "acp://copilot"-logger = logging.getLogger(__name__)-_DEFAULT_TIMEOUT_SECONDS = 900.0-# Stderr fingerprint of the deprecated `gh copilot` extension. Require BOTH the product name-# AND a deprecation marker: the NEW `@github/copilot` CLI legitimately mentions "copilot-cli".-_DEPRECATION_REQUIRED = ("gh-copilot",)-_DEPRECATION_MARKERS = ("has been deprecated", "no commands will be executed")-_ROLE_LABELS = {"system": "System", "user": "User", "assistant": "Assistant", "tool": "Tool", "context": "Context"}-# Probe verdicts per binary path (~50ms --help paid once per process). Only definitive-# True/False is cached, so a CLI installed mid-session is picked up.-_ACP_PROBE_CACHE: dict[str, bool] = {}-_PROMPT_PREAMBLE = (- "You are being used as the active ACP agent backend for Hermes.",- "Use ACP capabilities to complete tasks.",- "IMPORTANT: If you take an action with a tool, you MUST output tool calls using <tool_call>{...}</tool_call> blocks with JSON exactly in OpenAI function-call shape.",- "If no tool is needed, answer normally.",-)-_INITIALIZE_PARAMS = {- "protocolVersion": 1,- "clientCapabilities": {"fs": {"readTextFile": True, "writeTextFile": True}},- "clientInfo": {"name": "hermes-agent", "title": "Hermes Agent", "version": "0.0.0"},-}-_DEPRECATED_CLI_ERROR = (- "Hermes ACP mode requires the NEW GitHub Copilot CLI (github.com/github/copilot-cli), but the binary it just "- "spawned is the deprecated `gh copilot` extension.\n\n"- "Install the new CLI:\n npm install -g @github/copilot\n # then verify with: copilot --help\n\n"- "If `copilot` already resolves to the new CLI but you still see this,\npoint Hermes at it explicitly:\n"- " export HERMES_COPILOT_ACP_COMMAND=/path/to/new/copilot\n\n"- "Alternative: use the `copilot` provider (no ACP, hits the Copilot API\ndirectly with a Copilot subscription "- "token) via `hermes setup`.\n\nOriginal error:\n"-)+_warned = False-def _is_gh_copilot_deprecation_message(stderr_text: str) -> bool:- """True iff stderr looks like the deprecated gh-copilot extension's banner."""- lower = stderr_text.lower()- return any(req in lower for req in _DEPRECATION_REQUIRED) and any(m in lower for m in _DEPRECATION_MARKERS)+class _DeprecatedCopilotACPClient(ACPClient):+ """ACPClient with the historical launch defaults this module's callers relied on."""+ default_command = "copilot"+ default_args = ("--acp", "--stdio")+ command_env_vars = ("HERMES_COPILOT_ACP_COMMAND", "COPILOT_CLI_PATH")+ args_env_var = "HERMES_COPILOT_ACP_ARGS"+ marker_base_url = "acp://copilot"+ placeholder_model = "copilot-acp"+ label = "Copilot ACP"+ missing_command_hint = "Install GitHub Copilot CLI or set HERMES_COPILOT_ACP_COMMAND/COPILOT_CLI_PATH."+ unsupported_transport_hint = (+ "Either install a CLI that ships with --acp support (e.g. `@github/copilot` late 2025+), or set "+ "HERMES_COPILOT_ACP_COMMAND / HERMES_COPILOT_ACP_ARGS to a working pair.")-def _resolve_command() -> str:- return os.getenv("HERMES_COPILOT_ACP_COMMAND", "").strip() or os.getenv("COPILOT_CLI_PATH", "").strip() or "copilot"+ def model_entry_disabled(self, entry: dict[str, Any]) -> bool:+ return str((entry.get("_meta") or {}).get("copilotEnablement") or "").strip().lower() == "disabled"-def _resolve_args() -> list[str]:- return shlex.split(os.getenv("HERMES_COPILOT_ACP_ARGS", "").strip()) or ["--acp", "--stdio"]+_DeprecatedCopilotACPClient.__name__ = _DeprecatedCopilotACPClient.__qualname__ = "CopilotACPClient"-def _acp_supported(command: str, args: list[str]) -> bool | None:- """Tri-state ``--acp`` probe (a CLI without the flag exits 1 and the parent would wait the- full child timeout for stdout that never arrives). True = help advertises --acp; False =- help ran cleanly without it (caller fast-fails); None = inconclusive (binary missing /- --help failed → normal spawn error). Skipped when ``--acp`` is not in ``args`` (custom transport)."""- if "--acp" not in args:- return True- if (cached := _ACP_PROBE_CACHE.get(command)) is not None:- return cached- try:- probe = subprocess.run(- [command, "--help"],- # Explicit codec because text=True alone decodes with the- # locale default and crashes on non-ASCII help text under- # GBK/CP932 locales.- capture_output=True, text=True, encoding="utf-8",- errors="replace", timeout=5,- stdin=subprocess.DEVNULL,- check=False,- )- except (FileNotFoundError, subprocess.TimeoutExpired, OSError):- return None- if probe.returncode != 0:- return None- # ``--acp`` as a flag token; tolerate spacing and ``[--acp]`` variants.- verdict = _ACP_PROBE_CACHE[command] = bool(re.search(r"(?:^|[\s\[])--acp(?:[\s=\],]|$)", probe.stdout, re.MULTILINE))- return verdict---def _resolve_home_dir() -> str:- """Stable HOME for child ACP processes; the temp dir as a last resort so the child never starts HOME-less."""- if home := os.environ.get("HOME", "").strip():- return home- if (expanded := os.path.expanduser("~")) and expanded != "~":- return expanded- try:- import pwd-- return pwd.getpwuid(os.getuid()).pw_dir.strip() or tempfile.gettempdir() # windows-footgun: ok — POSIX fallback inside try/except (pwd import fails on Windows)- except Exception:- return tempfile.gettempdir()---def _build_subprocess_env() -> dict[str, str]:- from hermes_constants import apply_subprocess_home_env-- # Copilot ACP drives a model and needs LLM provider credentials; the central helper still- # strips Tier-1 secrets (bot tokens, GitHub auth, infra).- # See #29157.- env = hermes_subprocess_env(inherit_credentials=True)- env["HOME"] = _resolve_home_dir()- apply_subprocess_home_env(env)- return env---def _jsonrpc_result(message_id: Any, result: Any) -> dict[str, Any]:- return {"jsonrpc": "2.0", "id": message_id, "result": result}---def _jsonrpc_error(message_id: Any, code: int, message: str) -> dict[str, Any]:- return {"jsonrpc": "2.0", "id": message_id, "error": {"code": code, "message": message}}---def _enabled_id_list(entries: Any, key: str) -> list[str]:- """Ordered ids whose ``_meta.copilotEnablement`` is not ``disabled``."""- seen: set[str] = set()- result: list[str] = []- for entry in entries or []:- if not isinstance(entry, dict):- continue- value = str(entry.get(key) or "").strip()- if (not value or value in seen- or str((entry.get("_meta") or {}).get("copilotEnablement") or "").strip().lower() == "disabled"):- continue- seen.add(value)- result.append(value)- return result---def _model_config_option(session: dict[str, Any]) -> dict[str, Any] | None:- return next((option for option in (session.get("configOptions") or []) if isinstance(option, dict)- and "model" in (option.get("category"), option.get("id"))), None)---def _session_model_ids(session: dict[str, Any]) -> list[str]:- """Account-authorized model ids advertised by ``session/new`` in ACP v1 or its legacy extension."""- if option := _model_config_option(session):- return _enabled_id_list(option.get("options"), "value")- return _legacy_session_model_ids(session)---def _legacy_session_model_ids(session: dict[str, Any]) -> list[str]:- return _enabled_id_list((session.get("models") or {}).get("availableModels"), "modelId")---def _model_selection_request(session: dict[str, Any], requested_model: str) -> tuple[str, dict[str, str]] | None:- """ACP request selecting ``requested_model`` for ``session``: stable v1- ``session/set_config_option``, else Copilot's pre-stabilization ``session/set_model``- when no model config option is advertised. A reported model list is authoritative:- unknown and policy-disabled ids return None instead of being sent."""- session_id = str(session.get("sessionId") or "").strip()- requested_model = str(requested_model or "").strip()- if not session_id or not requested_model or requested_model == "copilot-acp":- return None- option = _model_config_option(session)- if option:- if requested_model not in _enabled_id_list(option.get("options"), "value"):- return None- return "session/set_config_option", {"sessionId": session_id, "configId": str(option.get("id") or "model"), "value": requested_model}- available = _legacy_session_model_ids(session)- return None if available and requested_model not in available else ("session/set_model", {"sessionId": session_id, "modelId": requested_model})---def _format_messages_as_prompt(- messages: list[dict[str, Any]], model: str | None = None, tools: list[dict[str, Any]] | None = None, tool_choice: Any = None,-) -> str:- # Deliberately no "requested model" line: the model is applied for real via ACP session/set_model;- # a prompt-text mention makes a substituted backend model FALSELY self-identify as the requested- # one. Copilot has no tools of its own that collide with Hermes', so forward the whole toolset.- sections: list[str] = [*_PROMPT_PREAMBLE, *_render_tool_bridge_sections(tools, tool_choice)]- transcript: list[str] = []- for message in (m for m in messages if isinstance(m, dict)):- role = str(message.get("role") or "unknown").strip().lower()- if rendered := _render_message_content(message.get("content")):- transcript.append(f"{_ROLE_LABELS.get(role, 'Context')}:\n{rendered}")- if transcript:- sections.append("Conversation transcript:\n\n" + "\n\n".join(transcript))- sections.append("Continue the conversation from the latest user request.")- return "\n\n".join(section.strip() for section in sections if section and section.strip())---def _render_message_content(content: Any) -> str:- if content is None:- return ""- if isinstance(content, dict):- if "text" in content:- return str(content.get("text") or "").strip()- return content["content"].strip() if isinstance(content.get("content"), str) else json.dumps(content, ensure_ascii=True)- if isinstance(content, list):- parts = [item if isinstance(item, str) else item["text"].strip() for item in content if isinstance(item, str)- or (isinstance(item, dict) and isinstance(item.get("text"), str) and item["text"].strip())]- return "\n".join(parts).strip()- return str(content).strip()---def _ensure_path_within_cwd(path_text: str, cwd: str, *, verb: str) -> Path:- # Raw-string check BEFORE resolve(): resolving an NT-namespace path is the NTLM-leak trigger.- if nt_error := get_nt_namespace_error(path_text, verb=verb):- raise PermissionError(nt_error)- if not Path(path_text).is_absolute():- raise PermissionError("ACP file-system paths must be absolute.")- resolved, root = Path(path_text).resolve(), Path(cwd).resolve()- try:- resolved.relative_to(root)- except ValueError as exc:- raise PermissionError(f"Path '{resolved}' is outside the session cwd '{root}'.") from exc- return resolved---def _effective_timeout(timeout: Any) -> float:- """Normalise a float or httpx.Timeout-like object to wall-clock seconds (largest component wins)."""- if isinstance(timeout, (int, float)):- return float(timeout)- candidates = [getattr(timeout, attr, None) for attr in ("read", "write", "connect", "pool", "timeout")]- return max((float(v) for v in candidates if isinstance(v, (int, float))), default=_DEFAULT_TIMEOUT_SECONDS)---def _fs_read_text_file(params: dict[str, Any], cwd: str) -> Any:- path = _ensure_path_within_cwd(str(params.get("path") or ""), cwd, verb="Read")- if block_error := get_read_block_error(str(path)):- raise PermissionError(block_error)- try:- content = path.read_text(encoding="utf-8-sig")- except FileNotFoundError:- content = ""- line, limit = params.get("line"), params.get("limit")- if isinstance(line, int) and line > 1:- end = line - 1 + limit if isinstance(limit, int) and limit > 0 else None- content = "".join(content.splitlines(keepends=True)[line - 1:end])- return {"content": redact_sensitive_text(content, force=True) if content else content}---def _fs_write_text_file(params: dict[str, Any], cwd: str) -> Any:- path = _ensure_path_within_cwd(str(params.get("path") or ""), cwd, verb="Write")- if denied := get_write_denied_error(str(path)):- raise PermissionError(denied)- if is_write_approval_required(str(path)): # soft-gated for interactive tools; the ACP shim has no human channel → fail closed- raise PermissionError(f"Write denied: '{path}' requires interactive approval and cannot be written through the ACP file bridge.")- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(str(params.get("content") or ""), encoding="utf-8")- return None---_FS_HANDLERS = {"fs/read_text_file": _fs_read_text_file, "fs/write_text_file": _fs_write_text_file}---class CopilotACPClient:- """Minimal OpenAI-client-compatible facade for Copilot ACP."""-- # Declared for agent/auxiliary_client.py: this shim drives an ACP subprocess over stdio, so it is- # already a complete client (never re-dispatch through a wire adapter) and async-safe as-is.- HERMES_SKIP_TRANSPORT_WRAP = True- HERMES_SKIP_ASYNC_WRAP = True-- def __init__(- self, *, api_key: str | None = None, base_url: str | None = None, default_headers: dict[str, str] | None = None,- acp_command: str | None = None, acp_args: list[str] | None = None, acp_cwd: str | None = None, command: str | None = None,- args: list[str] | None = None, **_: Any,- ):- self.api_key, self.base_url = api_key or "copilot-acp", base_url or ACP_MARKER_BASE_URL- self._default_headers = dict(default_headers or {})- self._acp_command = acp_command or command or _resolve_command()- self._acp_args = list(acp_args or args or _resolve_args())- # The session's workspace, not the process cwd: under the gateway every turn runs in- # the daemon (or a managed worker) whose own cwd is unrelated to the client's.- self._acp_cwd = str(Path(acp_cwd or resolve_agent_cwd()).resolve())- self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create_chat_completion))- self.is_closed = False- # Clients are cached and shared across concurrent callers (auxiliary tasks, async- # dispatch), so several ACP sessions can be live on one instance. Track every live- # child — a single slot would let one session's teardown kill a sibling's process- # while its own leaked.- self._active_processes: set[subprocess.Popen[str]] = set()- self._active_process_lock = threading.Lock()-- @staticmethod- def _terminate_process(proc: subprocess.Popen[str]) -> None:- try:- proc.terminate()- proc.wait(timeout=2)- except Exception:- with contextlib.suppress(Exception):- proc.kill()-- def _release_process(self, proc: subprocess.Popen[str]) -> None:- """Reap one session's own child. ``is_closed`` flips only when the last live- session drains — marking it while siblings still run would tell lifecycle code- to rebuild a client that is mid-request."""- with self._active_process_lock:- self._active_processes.discard(proc)- if not self._active_processes:- self.is_closed = True- self._terminate_process(proc)-- def close(self) -> None:- with self._active_process_lock:- procs, self._active_processes = tuple(self._active_processes), set()- self.is_closed = True- for proc in procs:- self._terminate_process(proc)-- def _create_chat_completion(- self, *, model: str | None = None, messages: list[dict[str, Any]] | None = None, timeout: float | None = None,- tools: list[dict[str, Any]] | None = None, tool_choice: Any = None, stream: bool = False, **_: Any,- ) -> Any:- prompt_text = _format_messages_as_prompt(messages or [], model=model, tools=tools, tool_choice=tool_choice)- response_text, reasoning = self._run_prompt(prompt_text, timeout_seconds=_effective_timeout(timeout), model=model)- tool_calls, cleaned_text = _extract_tool_calls_from_text(response_text)- message = SimpleNamespace(- content=cleaned_text, tool_calls=tool_calls, reasoning=reasoning or None, reasoning_content=reasoning or None,- reasoning_details=None,- )- completion = SimpleNamespace(- choices=[SimpleNamespace(message=message, finish_reason="tool_calls" if tool_calls else "stop")],- usage=SimpleNamespace(prompt_tokens=0, completion_tokens=0, total_tokens=0, prompt_tokens_details=SimpleNamespace(cached_tokens=0)),- model=model or "copilot-acp",- )- return _completion_to_stream_chunks(completion) if stream else completion-- def _spawn(self) -> subprocess.Popen[str]:- # Fast-fail when the CLI rejects --acp (else the parent waits the full child timeout for stdout that- # never arrives). ``None`` falls through to the spawn's established start error.- if _acp_supported(self._acp_command, self._acp_args) is False:- preview = " ".join(self._acp_args[:3]) if self._acp_args else "(none)"- raise RuntimeError(- f"ACP transport not supported by '{self._acp_command}': `{preview}` is rejected as an unknown option. This "- "usually means the CLI is an older release (e.g. Claude Code v2.x) or a different tool than expected. Either "- "install a CLI that ships with --acp support (e.g. `@github/copilot` late 2025+), or set "- "HERMES_COPILOT_ACP_COMMAND / HERMES_COPILOT_ACP_ARGS to a working pair."- )- try:- from hermes_cli._subprocess_compat import windows_hide_flags # hide the Windows console flash (#56747); pipes intact for the ACP wire-- # Hide the console the CLI child would otherwise flash on Windows (#56747). Hide-only — stdio- # pipes stay intact for the ACP wire.- proc = subprocess.Popen(- [self._acp_command] + self._acp_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,- text=True, encoding='utf-8', errors='replace', bufsize=1, cwd=self._acp_cwd, env=_build_subprocess_env(),- creationflags=windows_hide_flags(),- )- except FileNotFoundError as exc:- raise RuntimeError(f"Could not start Copilot ACP command '{self._acp_command}'. Install GitHub Copilot CLI or set "- "HERMES_COPILOT_ACP_COMMAND/COPILOT_CLI_PATH.") from exc- if proc.stdin is None or proc.stdout is None:- proc.kill()- raise RuntimeError("Copilot ACP process did not expose stdin/stdout pipes.")- with self._active_process_lock:- self._active_processes.add(proc)- self.is_closed = False- return proc-- @contextlib.contextmanager- def _session(- self, timeout_seconds: float, *, allow_file_requests: bool = True- ) -> Iterator[tuple[dict[str, Any], Callable[..., Any]]]:- """Start one ACP process and yield its ``session/new`` result plus request callable."""- proc = self._spawn()- inbox: queue.Queue[dict[str, Any]] = queue.Queue()- stderr_tail: deque[str] = deque(maxlen=40)-- def _decode(line: str) -> dict[str, Any]:- try:- return json.loads(line)- except Exception:- return {"raw": line.rstrip("\n")}-- def _pump(stream, sink) -> None:- for line in stream or ():- sink(line)-- threading.Thread(target=_pump, args=(proc.stdout, lambda line: inbox.put(_decode(line))), daemon=True).start()- stderr_pump = threading.Thread(- target=_pump, args=(proc.stderr, lambda line: stderr_tail.append(line.rstrip("\n"))), daemon=True)- stderr_pump.start()- request_ids = iter(range(1, 1 << 62))- # One budget for the WHOLE session (initialize + session/new + any prompt), not per- # request: a hung CLI must not get 2x the caller's timeout on the foreground /model path.- session_deadline = time.monotonic() + timeout_seconds-- def _request(method: str, params: dict[str, Any], *, text_parts: list[str] | None = None,- reasoning_parts: list[str] | None = None) -> Any:- request_id = next(request_ids)- proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}) + "\n")- proc.stdin.flush()- deadline = session_deadline- while time.monotonic() < deadline and proc.poll() is None:- try:- msg = inbox.get(timeout=0.1)- except queue.Empty:- continue- if self._handle_server_message(- msg, process=proc, cwd=self._acp_cwd, text_parts=text_parts,- reasoning_parts=reasoning_parts, allow_file_requests=allow_file_requests,- ) or msg.get("id") != request_id:- continue- if "error" in msg:- err = msg.get("error") or {}- raise RuntimeError(f"Copilot ACP {method} failed: {err.get('message') or err}")- return msg.get("result")- if proc.poll() is not None:- # The pump can still hold the crash text when poll() first sees the exit; reading- # it too early turned a dead CLI into a TimeoutError, which retries differently.- stderr_pump.join(timeout=1.0)- stderr_text = "\n".join(stderr_tail).strip()- if _is_gh_copilot_deprecation_message(stderr_text):- raise RuntimeError(_DEPRECATED_CLI_ERROR + stderr_text)- raise RuntimeError(f"Copilot ACP process exited early: {stderr_text or f'exit code {proc.returncode}'}")- raise TimeoutError(f"Timed out waiting for Copilot ACP response to {method}.")-- try:- _request("initialize", _INITIALIZE_PARAMS)- session = _request("session/new", {"cwd": self._acp_cwd, "mcpServers": []}) or {}- if not str(session.get("sessionId") or "").strip():- raise RuntimeError("Copilot ACP did not return a sessionId.")- yield session, _request- finally:- self._release_process(proc)-- def list_models(self, *, timeout_seconds: float = 15.0) -> list[str]:- """Return the enabled models advertised by a short-lived authenticated ACP session."""- with self._session(timeout_seconds, allow_file_requests=False) as (session, _):- return _session_model_ids(session)-- def _run_prompt(self, prompt_text: str, *, timeout_seconds: float, model: str | None = None) -> tuple[str, str]:- # The CLI's `--model` spawn flag is deliberately NOT used: `copilot --acp` validates it (unknown id- # aborts the spawn) but ignores it for the session; the model is applied after session/new instead.- requested_model = str(model or "").strip()- with self._session(timeout_seconds) as (session, _request):- session_id = str(session.get("sessionId") or "").strip()- if requested_model and requested_model != "copilot-acp":- try:- if (selection := _model_selection_request(session, requested_model)) is not None:- _request(*selection)- else:- logger.warning("Copilot ACP does not offer model %r; using the session default.", requested_model)- except Exception as exc:- logger.warning("Copilot ACP model selection for %r failed; continuing with the session default: %s", requested_model, exc)- text_parts: list[str] = []- reasoning_parts: list[str] = []- prompt = {"sessionId": session_id, "prompt": [{"type": "text", "text": prompt_text}]}- _request("session/prompt", prompt, text_parts=text_parts, reasoning_parts=reasoning_parts)- return "".join(text_parts), "".join(reasoning_parts)-- def _handle_server_message(- self, msg: dict[str, Any], *, process: subprocess.Popen[str], cwd: str, text_parts: list[str] | None, reasoning_parts: list[str] | None,- allow_file_requests: bool = True,- ) -> bool:- """Consume a server->client message; True when handled (notification or request answered)."""- method = msg.get("method")- if not isinstance(method, str):- return False- if method == "session/update":- update = (msg.get("params") or {}).get("update") or {}- content = update.get("content") or {}- chunk_text = str(content.get("text") or "") if isinstance(content, dict) else ""- sinks = {"agent_message_chunk": text_parts, "agent_thought_chunk": reasoning_parts}- if chunk_text and (sink := sinks.get(str(update.get("sessionUpdate") or "").strip())) is not None:- sink.append(chunk_text)- return True- if process.stdin is None:- return True- message_id = msg.get("id")- if method == "session/request_permission":- response = _jsonrpc_result(message_id, {"outcome": {"outcome": "cancelled"}})- elif method in _FS_HANDLERS:- if not allow_file_requests:- response = _jsonrpc_error(message_id, -32601, "File access is unavailable during model discovery.")- else:- try:- response = _jsonrpc_result(message_id, _FS_HANDLERS[method](msg.get("params") or {}, cwd))- except Exception as exc:- response = _jsonrpc_error(message_id, -32602, str(exc))- else:- response = _jsonrpc_error(message_id, -32601, f"ACP client method '{method}' is not supported by Hermes yet.")- process.stdin.write(json.dumps(response) + "\n")- process.stdin.flush()- return True+def __getattr__(name: str) -> Any:+ global _warned+ if name != "CopilotACPClient":+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ if not _warned:+ _warned = True+ warnings.warn(+ "agent.copilot_acp_client.CopilotACPClient is deprecated; subclass agent.acp_client.ACPClient instead.",+ DeprecationWarning, stacklevel=2)+ return _DeprecatedCopilotACPClientdiff --git a/hermes_cli/plugin_validate_private_imports.py b/hermes_cli/plugin_validate_private_imports.pyindex 834123939a7..b42d15c6e99 100644--- a/hermes_cli/plugin_validate_private_imports.py+++ b/hermes_cli/plugin_validate_private_imports.py@@ -26,8 +26,9 @@ from hermes_cli.plugin_validate_core_override import _hermes_top_level, _python_# ``module:Name`` entries allow one name. Re-harvest when those docs or PluginContext change._PUBLIC = frozenset({# developer-guide / plugins docs- "agent.account_usage", "agent.browser_provider", "agent.context_engine", "agent.credential_pool",+ "agent.account_usage", "agent.acp_client", "agent.browser_provider", "agent.context_engine", "agent.credential_pool","agent.delegation_backends", "agent.delegation_provider", "hermes_cli.auth_model_picker:prompt_model_selection",+ "hermes_cli.auth:resolve_external_process_provider_credentials","agent.image_gen_provider", "agent.memory_manager", "agent.memory_provider", "agent.secret_scope","agent.secret_sources.base", "agent.subagent_lifecycle", "agent.terminal_env_provider","agent.transports", "agent.transports.chat_completions", "agent.video_gen_provider",diff --git a/plugins/model-providers/copilot-acp/__init__.py b/plugins/model-providers/copilot-acp/__init__.pyindex 6027873a84e..7e26046f86b 100644--- a/plugins/model-providers/copilot-acp/__init__.py+++ b/plugins/model-providers/copilot-acp/__init__.py@@ -17,7 +17,7 @@ class CopilotACPProfile(ProviderProfile):def create_client(self, **client_kwargs: Any) -> Any:"""Build the ACP stdio shim rather than an HTTP client."""- from agent.copilot_acp_client import CopilotACPClient+ from .client import CopilotACPClientreturn CopilotACPClient(**client_kwargs)diff --git a/plugins/model-providers/copilot-acp/client.py b/plugins/model-providers/copilot-acp/client.pynew file mode 100644index 00000000000..486dcd8d60a--- /dev/null+++ b/plugins/model-providers/copilot-acp/client.py@@ -0,0 +1,52 @@+"""GitHub Copilot CLI (``copilot --acp --stdio``) client: the generic ACP client plus Copilot's quirks."""++from __future__ import annotations++from typing import Any++from agent.acp_client import ACPClient++# Stderr fingerprint of the deprecated `gh copilot` extension. Require BOTH the product name+# AND a deprecation marker: the NEW `@github/copilot` CLI legitimately mentions "copilot-cli".+_DEPRECATION_REQUIRED = ("gh-copilot",)+_DEPRECATION_MARKERS = ("has been deprecated", "no commands will be executed")+_DEPRECATED_CLI_ERROR = (+ "Hermes ACP mode requires the NEW GitHub Copilot CLI (github.com/github/copilot-cli), but the binary it just "+ "spawned is the deprecated `gh copilot` extension.\n\n"+ "Install the new CLI:\n npm install -g @github/copilot\n # then verify with: copilot --help\n\n"+ "If `copilot` already resolves to the new CLI but you still see this,\npoint Hermes at it explicitly:\n"+ " export HERMES_COPILOT_ACP_COMMAND=/path/to/new/copilot\n\n"+ "Alternative: use the `copilot` provider (no ACP, hits the Copilot API\ndirectly with a Copilot subscription "+ "token) via `hermes setup`.\n\nOriginal error:\n"+)+++def is_gh_copilot_deprecation_message(stderr_text: str) -> bool:+ """True iff stderr looks like the deprecated gh-copilot extension's banner."""+ lower = stderr_text.lower()+ return any(req in lower for req in _DEPRECATION_REQUIRED) and any(m in lower for m in _DEPRECATION_MARKERS)+++class CopilotACPClient(ACPClient):+ """ACP client for the GitHub Copilot CLI."""++ # Same launch spec as the copilot-acp profile's process_* fields (the fallback when a+ # caller passes no command/args).+ default_command = "copilot"+ default_args = ("--acp", "--stdio")+ command_env_vars = ("HERMES_COPILOT_ACP_COMMAND", "COPILOT_CLI_PATH")+ args_env_var = "HERMES_COPILOT_ACP_ARGS"+ marker_base_url = "acp://copilot"+ placeholder_model = "copilot-acp"+ label = "Copilot ACP"+ missing_command_hint = "Install GitHub Copilot CLI or set HERMES_COPILOT_ACP_COMMAND/COPILOT_CLI_PATH."+ unsupported_transport_hint = (+ "Either install a CLI that ships with --acp support (e.g. `@github/copilot` late 2025+), or set "+ "HERMES_COPILOT_ACP_COMMAND / HERMES_COPILOT_ACP_ARGS to a working pair.")++ def model_entry_disabled(self, entry: dict[str, Any]) -> bool:+ """Copilot marks org-policy-disabled models with ``_meta.copilotEnablement: disabled``."""+ return str((entry.get("_meta") or {}).get("copilotEnablement") or "").strip().lower() == "disabled"++ def early_exit_error(self, stderr_text: str) -> str | None:+ return _DEPRECATED_CLI_ERROR + stderr_text if is_gh_copilot_deprecation_message(stderr_text) else Nonediff --git a/tests/agent/test_acp_client.py b/tests/agent/test_acp_client.pynew file mode 100644index 00000000000..1ae405204b6--- /dev/null+++ b/tests/agent/test_acp_client.py@@ -0,0 +1,180 @@+"""Contracts of the public ACP stdio client (``agent.acp_client.ACPClient``) and its deprecated alias."""++from __future__ import annotations++import json+import os+import subprocess+import sys+import textwrap+from pathlib import Path++import pytest++from agent.acp_client import ACPClient++_REPO = Path(__file__).resolve().parents[2]++_CATALOG_SERVER = """import json+import sys++for line in sys.stdin:+ request = json.loads(line)+ method = request.get("method")+ if method == "initialize":+ result = {"protocolVersion": 1}+ elif method == "session/new":+ result = {"sessionId": "s1", "configOptions": [{"id": "model", "category": "model", "options": [+ {"value": "open-model"},+ {"value": "policy-blocked", "_meta": {"vendorPolicy": "off"}},+ {"value": "copilot-gated", "_meta": {"copilotEnablement": "disabled"}},+ ]}]}+ elif method == "session/prompt":+ print(json.dumps({"jsonrpc": "2.0", "method": "session/update", "params": {+ "update": {"sessionUpdate": "agent_message_chunk", "content": {"text": "hello"}}}}), flush=True)+ result = {"stopReason": "end_turn"}+ else:+ result = {}+ print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)+"""+++class _VendorClient(ACPClient):+ default_command = "vendor-agent"+ default_args = ("--acp",)+ command_env_vars = ("VENDOR_ACP_COMMAND", "VENDOR_CLI_PATH")+ args_env_var = "VENDOR_ACP_ARGS"+ marker_base_url = "acp://vendor"+ placeholder_model = "vendor-acp"+ label = "Vendor ACP"++ def model_entry_disabled(self, entry):+ return (entry.get("_meta") or {}).get("vendorPolicy") == "off"++ def early_exit_error(self, stderr_text):+ return "vendor CLI too old: " + stderr_text if "legacy build" in stderr_text else None+++def _server(tmp_path: Path, body: str) -> list[str]:+ script = tmp_path / "fake_agent.py"+ script.write_text(body, encoding="utf-8")+ return [sys.executable, str(script)]+++def test_subclass_launch_fallback_reads_its_env_vars_in_order(monkeypatch, tmp_path):+ for name in ("VENDOR_ACP_COMMAND", "VENDOR_CLI_PATH", "VENDOR_ACP_ARGS"):+ monkeypatch.delenv(name, raising=False)+ client = _VendorClient(acp_cwd=str(tmp_path))+ assert (client._acp_command, client._acp_args, client.base_url, client.api_key) == (+ "vendor-agent", ["--acp"], "acp://vendor", "vendor-acp")++ monkeypatch.setenv("VENDOR_CLI_PATH", "/opt/second")+ monkeypatch.setenv("VENDOR_ACP_COMMAND", "/opt/first")+ monkeypatch.setenv("VENDOR_ACP_ARGS", "--acp --stdio")+ client = _VendorClient(acp_cwd=str(tmp_path))+ assert (client._acp_command, client._acp_args) == ("/opt/first", ["--acp", "--stdio"])+ # Explicit command/args (what runtime resolution passes) always win over the fallback.+ assert _VendorClient(command="x", args=["y"], acp_cwd=str(tmp_path))._acp_args == ["y"]+++def test_model_entry_disabled_hook_owns_vendor_filtering(tmp_path):+ command, *args = _server(tmp_path, _CATALOG_SERVER)+ generic = ACPClient(command=command, args=args, acp_cwd=str(tmp_path))+ vendor = _VendorClient(command=command, args=args, acp_cwd=str(tmp_path))+ # The generic client applies no vendor _meta policy; the subclass hook does.+ assert generic.list_models(timeout_seconds=30) == ["open-model", "policy-blocked", "copilot-gated"]+ assert vendor.list_models(timeout_seconds=30) == ["open-model", "copilot-gated"]+ completion = vendor.chat.completions.create(model="vendor-acp", messages=[{"role": "user", "content": "hi"}], timeout=30)+ assert (completion.choices[0].message.content, completion.model) == ("hello", "vendor-acp")+++def test_errors_carry_the_subclass_label_and_early_exit_hook(tmp_path):+ missing = _VendorClient(command=str(tmp_path / "absent"), args=["--stdio"], acp_cwd=str(tmp_path))+ with pytest.raises(RuntimeError, match=r"Could not start Vendor ACP command .*VENDOR_ACP_COMMAND/VENDOR_CLI_PATH"):+ missing.chat.completions.create(messages=[{"role": "user", "content": "x"}], timeout=10)++ command, *args = _server(tmp_path, "import sys; print('legacy build 1.0', file=sys.stderr); sys.exit(3)")+ with pytest.raises(RuntimeError, match="vendor CLI too old: legacy build 1.0"):+ _VendorClient(command=command, args=args, acp_cwd=str(tmp_path)).list_models(timeout_seconds=30)+ with pytest.raises(RuntimeError, match="ACP process exited early: legacy build 1.0"):+ ACPClient(command=command, args=args, acp_cwd=str(tmp_path)).list_models(timeout_seconds=30)+++_FROZEN_SUBCLASS_PLUGIN = '''+"""Frozen shape of an out-of-tree ACP provider built on the deprecated alias (kimchi-acp-provider)."""+import os+from providers import register_provider+from providers.base import ProviderProfile+from agent.copilot_acp_client import CopilotACPClient as _Base+++class _Mixin:+ def __init__(self, **kwargs):+ super().__init__(**kwargs)+ if (self._acp_command or "") in ("", "copilot"):+ self._acp_command = os.environ["FROZEN_AGENT"]+ self._acp_args = [os.environ["FROZEN_SCRIPT"]]+ if self.base_url == "acp://copilot":+ self.base_url = "acp://frozen"++ def _handle_server_message(self, msg, *, process, cwd, text_parts, reasoning_parts, allow_file_requests=True):+ handled = super()._handle_server_message(msg, process=process, cwd=cwd, text_parts=text_parts,+ reasoning_parts=reasoning_parts,+ allow_file_requests=allow_file_requests)+ if handled and text_parts:+ text_parts[-1] = text_parts[-1].upper()+ return handled+++class FrozenClient(_Mixin, _Base):+ pass+++class FrozenProfile(ProviderProfile):+ def create_client(self, **kw):+ return FrozenClient(**kw)+++register_provider(FrozenProfile(name="frozen-acp", base_url="acp://frozen", auth_type="external_process",+ process_command="frozen", process_args=("--mode", "acp")))+'''++_FROZEN_DRIVER = """+import json, warnings+with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ import providers+ client = providers.get_provider_profile("frozen-acp").create_client()+ import agent.copilot_acp_client as alias+ alias.CopilotACPClient+from agent.acp_client import ACPClient+reply = client.chat.completions.create(model="copilot-acp", messages=[{"role": "user", "content": "hi"}], timeout=30)+print(json.dumps({+ "warnings": [str(w.message) for w in caught if w.category is DeprecationWarning and "acp_client" in str(w.message)],+ "is_acp_client": isinstance(client, ACPClient),+ "base_url": client.base_url,+ "models": client.list_models(timeout_seconds=30),+ "reply": reply.choices[0].message.content,+}))+"""+++def test_deprecated_alias_keeps_a_frozen_out_of_tree_subclass_working(tmp_path):+ home = tmp_path / "hermes"+ plugin = home / "plugins" / "model-providers" / "frozen-acp"+ plugin.mkdir(parents=True)+ (plugin / "__init__.py").write_text(textwrap.dedent(_FROZEN_SUBCLASS_PLUGIN), encoding="utf-8")+ (plugin / "plugin.yaml").write_text("name: frozen-acp\nkind: model-provider\nversion: 1.0.0\n", encoding="utf-8")+ script = tmp_path / "fake_acp_agent.py"+ script.write_text(_CATALOG_SERVER, encoding="utf-8")+ env = {**os.environ, "HOME": str(tmp_path), "HERMES_HOME": str(home), "FROZEN_AGENT": sys.executable, "FROZEN_SCRIPT": str(script),+ "PYTHONPATH": str(_REPO)}+ proc = subprocess.run([sys.executable, "-c", _FROZEN_DRIVER], cwd=tmp_path, env=env, capture_output=True,+ text=True, timeout=120, check=False)+ assert proc.returncode == 0, proc.stderr[-2000:]+ result = json.loads(proc.stdout.strip().splitlines()[-1])+ assert result["warnings"] == [+ "agent.copilot_acp_client.CopilotACPClient is deprecated; subclass agent.acp_client.ACPClient instead."]+ assert result["is_acp_client"] and result["base_url"] == "acp://frozen"+ assert result["models"] == ["open-model", "policy-blocked"] # the alias keeps its enablement filter+ assert result["reply"] == "HELLO"diff --git a/tests/agent/test_acp_openai_bridge.py b/tests/agent/test_acp_openai_bridge.pyindex 880bc6d545e..03cb5e3c046 100644--- a/tests/agent/test_acp_openai_bridge.py+++ b/tests/agent/test_acp_openai_bridge.py@@ -192,7 +192,7 @@ def test_a_text_only_completion_streams_without_tool_call_deltas():def test_copilot_prompt_still_carries_the_contract_and_the_tools():"""copilot-acp lost its private copy of the bridge; its prompt must notchange shape."""- from agent.copilot_acp_client import _format_messages_as_prompt+ from agent.acp_client import _format_messages_as_promptprompt = _format_messages_as_prompt([{"role": "user", "content": "hi"}], model="gpt-5", tools=_TOOLS,diff --git a/tests/agent/test_nt_namespace_guard.py b/tests/agent/test_nt_namespace_guard.pyindex 93c688e211d..456644ddd69 100644--- a/tests/agent/test_nt_namespace_guard.py+++ b/tests/agent/test_nt_namespace_guard.py@@ -61,7 +61,7 @@ class TestNtNamespaceGuard(unittest.TestCase):join would hide the prefix."""from pathlib import Path- from agent import context_references, copilot_acp_client, tool_executor+ from agent import acp_client, context_references, tool_executorfrom tools.file_tools import patch_tool, read_file_tool, search_tool, write_file_toolbad = "\\??\\UNC\\attacker.example\\share\\x"@@ -80,7 +80,7 @@ class TestNtNamespaceGuard(unittest.TestCase):checkpoint_agent = SimpleNamespace(_checkpoint_mgr=MagicMock(enabled=True))tool_executor._ensure_file_checkpoint(checkpoint_agent, "write_file", {"path": bad}, "default")checkpoint_agent._checkpoint_mgr.ensure_checkpoint.assert_not_called()- for fs_handler in (copilot_acp_client._fs_read_text_file, copilot_acp_client._fs_write_text_file):+ for fs_handler in (acp_client._fs_read_text_file, acp_client._fs_write_text_file):with self.assertRaisesRegex(PermissionError, "NT/device namespace"):fs_handler({"path": bad, "content": "x"}, "/tmp")with self.assertRaisesRegex(ValueError, "NT/device namespace"):diff --git a/tests/agent/test_provider_client_seam.py b/tests/agent/test_provider_client_seam.pyindex 2514977b0ca..db6484b0feb 100644--- a/tests/agent/test_provider_client_seam.py+++ b/tests/agent/test_provider_client_seam.py@@ -84,7 +84,7 @@ def test_a_broken_plugin_falls_through_instead_of_taking_the_turn_down(registeredef test_copilot_acp_still_gets_its_acp_client_via_its_profile():- from agent.copilot_acp_client import CopilotACPClient+ from plugins.model_providers.copilot_acp.client import CopilotACPClientassert isinstance(_build("copilot-acp", "acp://copilot"), CopilotACPClient)assert isinstance(_build("", "acp://copilot"), CopilotACPClient)@@ -92,7 +92,7 @@ def test_copilot_acp_still_gets_its_acp_client_via_its_profile():def test_skip_flags_replace_the_isinstance_checks_for_in_and_out_of_tree_clients():from agent.auxiliary_client import _maybe_wrap_anthropic, _to_async_client- from agent.copilot_acp_client import CopilotACPClient+ from plugins.model_providers.copilot_acp.client import CopilotACPClientfrom agent.gemini_native_adapter import GeminiNativeClientassert CopilotACPClient.HERMES_SKIP_TRANSPORT_WRAP and CopilotACPClient.HERMES_SKIP_ASYNC_WRAPdiff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex 131befb7080..cba7fe4fb46 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -5781,36 +5781,6 @@ class TestFallbackAnthropicProvider:assert agent._use_prompt_caching is True-def test_aiagent_uses_copilot_acp_client():- with (- patch("model_tools.get_tool_definitions", return_value=_make_tool_defs("web_search")),- patch("model_tools.check_toolset_requirements", return_value={}),- patch("agent.process_bootstrap.OpenAI") as mock_openai,- patch("agent.copilot_acp_client.CopilotACPClient") as mock_acp_client,- ):- acp_client = MagicMock()- mock_acp_client.return_value = acp_client-- agent = AIAgent(- api_key="copilot-acp",- base_url="acp://copilot",- provider="copilot-acp",- acp_command="/usr/local/bin/copilot",- acp_args=["--acp", "--stdio"],- quiet_mode=True,- skip_context_files=True,- skip_memory=True,- )-- assert agent.client is acp_client- mock_openai.assert_not_called()- mock_acp_client.assert_called_once()- assert mock_acp_client.call_args.kwargs["base_url"] == "acp://copilot"- assert mock_acp_client.call_args.kwargs["api_key"] == "copilot-acp"- assert mock_acp_client.call_args.kwargs["command"] == "/usr/local/bin/copilot"- assert mock_acp_client.call_args.kwargs["args"] == ["--acp", "--stdio"]--def test_quiet_spinner_allowed_with_explicit_print_fn(agent):agent._print_fn = lambda *_a, **_kw: Nonewith patch.object(run_agent.sys.stdout, "isatty", return_value=False):diff --git a/tests/hermes_cli/test_copilot_in_model_list.py b/tests/hermes_cli/test_copilot_in_model_list.pyindex 24193e1e928..b75cb6abf8a 100644--- a/tests/hermes_cli/test_copilot_in_model_list.py+++ b/tests/hermes_cli/test_copilot_in_model_list.py@@ -98,6 +98,15 @@ def _fresh_acp_memo(monkeypatch):monkeypatch.setattr(models, "_copilot_acp_session_memo", None)+def _copilot_acp_client():+ import providers++ providers.get_provider_profile("copilot-acp") # discovery imports the bundled plugin package+ from plugins.model_providers.copilot_acp.client import CopilotACPClient++ return CopilotACPClient++@pytest.mark.parametrize(("session_probe", "github_token", "github_models", "expected"),[@@ -111,7 +120,7 @@ def _fresh_acp_memo(monkeypatch):def test_copilot_acp_catalog_prefers_authenticated_session(_fresh_acp_memo, session_probe, github_token, github_models, expected):with patch("hermes_cli.auth.resolve_external_process_provider_credentials", return_value=_ACP_CREDS), \- patch("agent.copilot_acp_client.CopilotACPClient.list_models", **session_probe) as list_models, \+ patch.object(_copilot_acp_client(), "list_models", **session_probe) as list_models, \patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value=github_token), \patch("hermes_cli.models._fetch_github_models", return_value=github_models) as github:assert provider_model_ids("copilot-acp", force_refresh=True) == expected@@ -126,7 +135,7 @@ def test_copilot_acp_session_probe_is_memoized_across_model_switch_validation(_ffrom hermes_cli.models_validate import validate_requested_modelwith patch("hermes_cli.auth.resolve_external_process_provider_credentials", return_value=_ACP_CREDS), \- patch("agent.copilot_acp_client.CopilotACPClient.list_models", return_value=["gpt-5.6-terra"]) as list_models, \+ patch.object(_copilot_acp_client(), "list_models", return_value=["gpt-5.6-terra"]) as list_models, \patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value=""), \patch("hermes_cli.models._fetch_github_models", return_value=[]):for _ in range(3):@@ -136,7 +145,7 @@ def test_copilot_acp_session_probe_is_memoized_across_model_switch_validation(_fmodels._copilot_acp_session_memo = None # (teardown in _fresh_acp_memo restores it)with patch("hermes_cli.auth.resolve_external_process_provider_credentials", return_value=_ACP_CREDS), \- patch("agent.copilot_acp_client.CopilotACPClient.list_models", side_effect=RuntimeError("not signed in")) as list_models, \+ patch.object(_copilot_acp_client(), "list_models", side_effect=RuntimeError("not signed in")) as list_models, \patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value=""), \patch("hermes_cli.models._fetch_github_models", return_value=[]):for _ in range(3):diff --git a/tests/hermes_cli/test_mcp_catalog_env_boundary.py b/tests/hermes_cli/test_mcp_catalog_env_boundary.pyindex d8df60db2f4..2fb78c786fa 100644--- a/tests/hermes_cli/test_mcp_catalog_env_boundary.py+++ b/tests/hermes_cli/test_mcp_catalog_env_boundary.py@@ -265,12 +265,25 @@ def test_process_supplied_catalog_root_remains_supported(catalog_env: Path):assert get_entry("demo") is not None+def _copilot_acp_launch_resolvers():+ """(command, args) resolvers of the copilot-acp client's env-driven launch fallback."""+ import providers++ providers.get_provider_profile("copilot-acp") # discovery imports the bundled plugin package+ from plugins.model_providers.copilot_acp.client import CopilotACPClient++ def launch():+ return CopilotACPClient(acp_cwd=os.getcwd())++ return (lambda: launch()._acp_command), (lambda: launch()._acp_args)++def test_rejected_copilot_controls_do_not_change_live_resolvers(client: TestClient,catalog_env: Path,monkeypatch: pytest.MonkeyPatch,):- from agent.copilot_acp_client import _resolve_args, _resolve_command+ _resolve_command, _resolve_args = _copilot_acp_launch_resolvers()monkeypatch.setenv("HERMES_COPILOT_ACP_COMMAND", "/opt/trusted/copilot")monkeypatch.setenv("HERMES_COPILOT_ACP_ARGS", "--acp --stdio")@@ -302,7 +315,7 @@ def test_preexisting_copilot_controls_remain_usable(catalog_env: Path,monkeypatch: pytest.MonkeyPatch,):- from agent.copilot_acp_client import _resolve_args, _resolve_command+ _resolve_command, _resolve_args = _copilot_acp_launch_resolvers()from hermes_cli.env_loader import load_hermes_dotenvmonkeypatch.setenv("HERMES_COPILOT_ACP_COMMAND", "parent-placeholder")diff --git a/tests/agent/test_copilot_acp_client.py b/tests/plugins/model_providers/test_copilot_acp_client.pysimilarity index 87%rename from tests/agent/test_copilot_acp_client.pyrename to tests/plugins/model_providers/test_copilot_acp_client.pyindex 5c114662039..fd270b81c3e 100644--- a/tests/agent/test_copilot_acp_client.py+++ b/tests/plugins/model_providers/test_copilot_acp_client.py@@ -11,7 +11,10 @@ import unittestfrom pathlib import Pathfrom unittest.mock import patch-from agent.copilot_acp_client import CopilotACPClient+import providers++providers.get_provider_profile("copilot-acp") # discovery imports the bundled plugin package+from plugins.model_providers.copilot_acp.client import CopilotACPClientclass _FakeProcess:@@ -217,8 +220,8 @@ def test_run_prompt_preserves_real_home_when_profile_home_available(monkeypatch,# Hermeticity: the --acp support probe (PR #87308) calls subprocess.run# before Popen; stub it inconclusive so no real CLI on the host box can# flip the resolution this test asserts.- with _patch("agent.copilot_acp_client.subprocess.run", side_effect=FileNotFoundError):- with _patch("agent.copilot_acp_client.subprocess.Popen", side_effect=_fake_popen_capture(captured)):+ with _patch("agent.acp_client.subprocess.run", side_effect=FileNotFoundError):+ with _patch("agent.acp_client.subprocess.Popen", side_effect=_fake_popen_capture(captured)):with pytest.raises(RuntimeError, match="Could not start Copilot ACP command"):client._run_prompt("hello", timeout_seconds=1)@@ -236,8 +239,8 @@ def test_run_prompt_passes_home_when_parent_env_is_clean(monkeypatch, tmp_path):# Hermeticity: the --acp support probe (PR #87308) calls subprocess.run# before Popen; stub it inconclusive so no real CLI on the host box can# flip the resolution this test asserts.- with _patch("agent.copilot_acp_client.subprocess.run", side_effect=FileNotFoundError):- with _patch("agent.copilot_acp_client.subprocess.Popen", side_effect=_fake_popen_capture(captured)):+ with _patch("agent.acp_client.subprocess.run", side_effect=FileNotFoundError):+ with _patch("agent.acp_client.subprocess.Popen", side_effect=_fake_popen_capture(captured)):with pytest.raises(RuntimeError, match="Could not start Copilot ACP command"):client._run_prompt("hello", timeout_seconds=1)@@ -249,7 +252,7 @@ def test_run_prompt_passes_home_when_parent_env_is_clean(monkeypatch, tmp_path):import subprocess as _subprocess-from agent.copilot_acp_client import _ACP_PROBE_CACHE, _acp_supported+from agent.acp_client import _ACP_PROBE_CACHE, _acp_supported@pytest.fixture(autouse=True)@@ -265,7 +268,7 @@ def _completed(returncode=0, stdout=""):def test_probe_true_when_help_advertises_acp():with _patch(- "agent.copilot_acp_client.subprocess.run",+ "agent.acp_client.subprocess.run",return_value=_completed(stdout="Usage: copilot [--acp] [--stdio]"),):assert _acp_supported("copilot", ["--acp", "--stdio"]) is True@@ -274,7 +277,7 @@ def test_probe_true_when_help_advertises_acp():def test_probe_false_when_help_lacks_acp_and_run_prompt_fast_fails(tmp_path):client = _make_home_client(tmp_path)with _patch(- "agent.copilot_acp_client.subprocess.run",+ "agent.acp_client.subprocess.run",return_value=_completed(stdout="Usage: claude [--print] [--model]"),):with pytest.raises(RuntimeError, match="ACP transport not supported"):@@ -285,11 +288,11 @@ def test_probe_inconclusive_falls_through_to_spawn_error(tmp_path):"""Missing binary: probe must NOT mask the established spawn error."""client = _make_home_client(tmp_path)with _patch(- "agent.copilot_acp_client.subprocess.run",+ "agent.acp_client.subprocess.run",side_effect=FileNotFoundError("copilot not found"),):with _patch(- "agent.copilot_acp_client.subprocess.Popen",+ "agent.acp_client.subprocess.Popen",side_effect=FileNotFoundError("copilot not found"),):with pytest.raises(RuntimeError, match="Could not start Copilot ACP command"):@@ -301,7 +304,7 @@ def test_probe_inconclusive_falls_through_to_spawn_error(tmp_path):def test_probe_skipped_for_custom_args_without_acp():- with _patch("agent.copilot_acp_client.subprocess.run") as run_mock:+ with _patch("agent.acp_client.subprocess.run") as run_mock:assert _acp_supported("mycli", ["--custom-transport"]) is Truerun_mock.assert_not_called()@@ -340,9 +343,15 @@ def _session_with_config_options():}-def test_model_selection_prefers_stable_config_option():- from agent.copilot_acp_client import _model_selection_request+def _model_selection_request(session, requested_model):+ """The generic selector with the Copilot client's placeholder id and enablement hook."""+ from agent.acp_client import _model_selection_request as select++ return select(session, requested_model, placeholder=CopilotACPClient.placeholder_model,+ disabled=CopilotACPClient(acp_cwd="/tmp").model_entry_disabled)++def test_model_selection_prefers_stable_config_option():assert _model_selection_request(_session_with_config_options(), "gpt-5.6-terra") == (@@ -352,24 +361,18 @@ def test_model_selection_prefers_stable_config_option():def test_model_selection_rejects_disabled_config_option():- from agent.copilot_acp_client import _model_selection_request-assert _model_selection_request(_session_with_config_options(), "claude-fable-5") is Nonedef test_model_selection_rejects_unknown_config_option():- from agent.copilot_acp_client import _model_selection_request-assert _model_selection_request(_session_with_config_options(), "not-served-here") is Nonedef test_model_selection_falls_back_to_legacy_extension():- from agent.copilot_acp_client import _model_selection_request-legacy_session = {"sessionId": "s1","models": {@@ -386,8 +389,6 @@ def test_model_selection_falls_back_to_legacy_extension():def test_model_selection_skips_provider_virtual_slug():- from agent.copilot_acp_client import _model_selection_request-assert _model_selection_request(_session_with_config_options(), "copilot-acp") is None@@ -588,3 +589,40 @@ def test_cli_death_is_reported_as_a_crash_not_a_timeout(tmp_path):assert "exited early: fatal: agent segfaulted" in str(exc)else:raise AssertionError("session on a dead CLI must raise")+++def test_aiagent_uses_copilot_acp_client():+ from unittest.mock import MagicMock++ from run_agent import AIAgent++ tool_defs = [{"type": "function", "function": {+ "name": "web_search", "description": "web_search tool", "parameters": {"type": "object", "properties": {}}}}]+ client_module = sys.modules[CopilotACPClient.__module__]+ with (+ patch("model_tools.get_tool_definitions", return_value=tool_defs),+ patch("model_tools.check_toolset_requirements", return_value={}),+ patch("agent.process_bootstrap.OpenAI") as mock_openai,+ patch.object(client_module, "CopilotACPClient") as mock_acp_client,+ ):+ acp_client = MagicMock()+ mock_acp_client.return_value = acp_client++ agent = AIAgent(+ api_key="copilot-acp",+ base_url="acp://copilot",+ provider="copilot-acp",+ acp_command="/usr/local/bin/copilot",+ acp_args=["--acp", "--stdio"],+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ )++ assert agent.client is acp_client+ mock_openai.assert_not_called()+ mock_acp_client.assert_called_once()+ assert mock_acp_client.call_args.kwargs["base_url"] == "acp://copilot"+ assert mock_acp_client.call_args.kwargs["api_key"] == "copilot-acp"+ assert mock_acp_client.call_args.kwargs["command"] == "/usr/local/bin/copilot"+ assert mock_acp_client.call_args.kwargs["args"] == ["--acp", "--stdio"]diff --git a/tests/agent/test_copilot_acp_deprecation.py b/tests/plugins/model_providers/test_copilot_acp_deprecation.pysimilarity index 92%rename from tests/agent/test_copilot_acp_deprecation.pyrename to tests/plugins/model_providers/test_copilot_acp_deprecation.pyindex d82afc359f6..c815b8a8ac9 100644--- a/tests/agent/test_copilot_acp_deprecation.py+++ b/tests/plugins/model_providers/test_copilot_acp_deprecation.py@@ -2,7 +2,11 @@import pytest-from agent.copilot_acp_client import _is_gh_copilot_deprecation_message+import providers++providers.get_provider_profile("copilot-acp") # discovery imports the bundled plugin package+from plugins.model_providers.copilot_acp.client import (+ is_gh_copilot_deprecation_message as _is_gh_copilot_deprecation_message)class TestDeprecationPatternDetection:diff --git a/website/docs/developer-guide/model-provider-plugin.md b/website/docs/developer-guide/model-provider-plugin.mdindex 0edd2982f36..0d290a90dac 100644--- a/website/docs/developer-guide/model-provider-plugin.md+++ b/website/docs/developer-guide/model-provider-plugin.md@@ -250,7 +250,7 @@ def fetch_account_usage(self, *, api_key=None, base_url=None):## External-process (ACP) providers-An agent CLI driven over stdio is not an HTTP endpoint. Set `auth_type="external_process"`, describe how to launch the binary, and supply the client with `create_client`. No core edits are needed — `hermes -m <name>`, `/model`, credential resolution, runtime resolution and the auxiliary client (compression, vision) all key on `auth_type`, not on the provider name. `plugins/model-providers/copilot-acp/` is the in-tree example.+An agent CLI driven over stdio is not an HTTP endpoint. Set `auth_type="external_process"`, describe how to launch the binary, and supply the client with `create_client`. No core edits are needed — `hermes -m <name>`, `/model`, credential resolution, runtime resolution and the auxiliary client (compression, vision) all key on `auth_type`, not on the provider name. `plugins/model-providers/copilot-acp/` is the in-tree example (its `client.py` subclasses the public `ACPClient` below).| Field | Purpose ||---|---|@@ -261,6 +261,37 @@ An agent CLI driven over stdio is not an HTTP endpoint. Set `auth_type="externalThe client your `create_client` returns receives `command` and `args` in `client_kwargs`. If it is already complete and async-safe, declare `HERMES_SKIP_TRANSPORT_WRAP = True` / `HERMES_SKIP_ASYNC_WRAP = True` as class attributes so the auxiliary client does not re-dispatch it through an HTTP wire adapter.+#### The public ACP client: `agent.acp_client.ACPClient`++For an agent CLI that speaks the [Agent Client Protocol](https://agentclientprotocol.com) on stdio, return an `ACPClient` (or a subclass) from `create_client` instead of writing your own shim. It is an OpenAI-client facade (`client.chat.completions.create(...)`, streaming included) that starts one short-lived ACP session per request, applies the requested model over ACP (`session/set_config_option`, else `session/set_model`), forwards Hermes' tools as a prompt-level bridge, answers `fs/read_text_file` / `fs/write_text_file` inside the session cwd with Hermes' file-safety rules, cancels permission requests, and lists the session's models with `list_models(timeout_seconds=...)`. It already declares both `HERMES_SKIP_*` attributes.++```python+from agent.acp_client import ACPClient++class MyAgentClient(ACPClient):+ default_command = "myagent" # used only when the caller passes no command/args+ default_args = ("--acp",)+ command_env_vars = ("MYAGENT_ACP_COMMAND",)+ args_env_var = "MYAGENT_ACP_ARGS"+ marker_base_url = "acp://myagent"+ placeholder_model = "myagent-acp" # "session default": never sent as a model selection+ label = "MyAgent ACP" # product name in errors and logs++ def model_entry_disabled(self, entry): # optional: vendor _meta marking a model unavailable+ return False++ def early_exit_error(self, stderr_text): # optional: friendlier error for a known crash banner+ return None++class MyAgentProfile(ProviderProfile):+ def create_client(self, **client_kwargs):+ return MyAgentClient(**client_kwargs)+```++Keep the class attributes in step with the profile's `process_*` fields. Override `_handle_server_message(msg, *, process, cwd, text_parts, reasoning_parts, allow_file_requests=True)` to render extra `session/update` kinds (call `super()` for the rest). `hermes_cli.auth.resolve_external_process_provider_credentials(name)` returns the resolved `command`/`args`/`base_url` for a `fetch_models()` probe.++`agent.copilot_acp_client.CopilotACPClient` is a deprecated alias of `ACPClient` with the old GitHub Copilot launch defaults; importing it warns once per process. Subclass `ACPClient` instead (set `placeholder_model` to your own placeholder id). The alias stays for at least two minor releases.+### Picker rows for non-api-key pluginsEvery registered profile joins `CANONICAL_PROVIDERS` by slug (a plugin re-declaring a built-in slug such as `bedrock` is deduped, never doubled), so external-process and OAuth plugins appear in `hermes model`, `/model` and the Desktop model selector alongside `copilot-acp`. Visibility is gated by credentials, not by `auth_type`: