Skip to content

The agent that grows with you

refactor(agent/gemini,acp): compact WHY comments

Teknium607162e444f0
diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.py
index d5113503799..f7fd22edfb9 100644
--- a/agent/copilot_acp_client.py
+++ b/agent/copilot_acp_client.py
@@ -33,17 +33,15 @@ 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 (repo
-# github/copilot-cli) legitimately mentions "copilot-cli" in its own banners.
+# 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 so the ~50ms --help cost is paid once per
-# process. Only definitive True/False is cached; an inconclusive probe is not,
-# so a CLI installed mid-session is picked up.
+# 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 = (
@@ -126,8 +124,8 @@ def _resolve_home_dir() -> str:
def _build_subprocess_env() -> dict[str, str]:
- # Copilot ACP drives a model and legitimately needs LLM provider credentials;
- # the central helper still strips Tier-1 secrets (bot tokens, GitHub auth, infra).
+ # Copilot ACP drives a model and needs LLM provider credentials; the central helper still
+ # strips Tier-1 secrets (bot tokens, GitHub auth, infra).
env = hermes_subprocess_env(inherit_credentials=True)
env["HOME"] = _resolve_home_dir()
from hermes_constants import apply_subprocess_home_env
@@ -186,10 +184,9 @@ 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. Identity comes from the backend.
- # Copilot has no tools of its own that collide with Hermes', so forward the whole toolset.
+ # 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 messages:
@@ -267,8 +264,8 @@ def _fs_write_text_file(params: dict[str, Any], cwd: str) -> Any:
path = _ensure_path_within_cwd(str(params.get("path") or ""), cwd)
if denied := get_write_denied_error(str(path)):
raise PermissionError(denied)
- # Approval-gated paths (e.g. ~/.ssh/config) are only soft-gated for interactive
- # tools, but the ACP shim has no human channel to confirm — fail closed.
+ # Approval-gated paths (e.g. ~/.ssh/config) are soft-gated for interactive tools; the ACP
+ # shim has no human channel to confirm — fail closed.
if is_write_approval_required(str(path)):
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)
@@ -282,9 +279,8 @@ _FS_HANDLERS = {"fs/read_text_file": _fs_read_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 it
- # through a wire adapter) and is safe to use from async code as-is.
+ # 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
@@ -338,9 +334,8 @@ class CopilotACPClient:
return _completion_to_stream_chunks(completion) if stream else completion
def _spawn(self) -> subprocess.Popen[str]:
- # Fast-fail when the CLI rejects --acp: without the probe the parent waits
- # the full child timeout for stdout that never arrives. ``None`` falls
- # through to the spawn, which raises the established start error.
+ # 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(
@@ -373,9 +368,8 @@ class CopilotACPClient:
return proc
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 via ACP-native model selection.
+ # 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()
proc = self._spawn()
inbox: queue.Queue[dict[str, Any]] = queue.Queue()
@@ -428,8 +422,7 @@ class CopilotACPClient:
session_id = str(session.get("sessionId") or "").strip()
if not session_id:
raise RuntimeError("Copilot ACP did not return a sessionId.")
- # Prefer the stable ACP v1 session-config API (category="model" select
- # option + session/set_config_option); session/set_model is the fallback.
+ # Stable ACP v1 session-config API first; session/set_model is the fallback.
if requested_model and requested_model != "copilot-acp":
try:
selection = _model_selection_request(session, requested_model)
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index 5d3c6fd4ed8..b565b544d8c 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -36,9 +36,8 @@ _API_CLIENT = f"hermes-agent/{_HERMES_VERSION}" # client context per Gemini's p
DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"
-# Published max output-token ceiling shared by every current Gemini text model.
-# Used when the caller passes max_tokens=None: unlike OpenAI-compat endpoints,
-# Gemini's native API applies a low internal default and truncates output.
+# Published max output-token ceiling shared by every current Gemini text model; used
+# for max_tokens=None because the native API's low internal default truncates output.
GEMINI_DEFAULT_MAX_OUTPUT_TOKENS = 65535
_FREE_TIER_GUIDANCE = (
@@ -55,14 +54,13 @@ _STANDARD_KEY_GUIDANCE = (
"generativelanguage.googleapis.com). Then update GEMINI_API_KEY / GOOGLE_API_KEY in ~/.hermes/.env and "
"restart your session. Details: https://ai.google.dev/gemini-api/docs/api-key"
)
-# Stands in for a model turn that never arrived (stream failure / interrupt /
-# quota fallback) when a human user text turn directly follows a tool-result
-# turn, keeping the request alternation-valid while the user's message stays a
-# turn of its own (mirrors gemini-cli's placeholder repair).
+# Stands in for a model turn that never arrived (stream failure / interrupt / quota
+# fallback) when a human user text turn directly follows a tool-result turn, keeping
+# the request alternation-valid while the user's message stays a turn of its own
+# (mirrors gemini-cli's placeholder repair).
_INTERRUPTED_RESPONSE_PLACEHOLDER = "[The previous response was interrupted before it completed.]"
-# Cross-provider tool_calls (e.g. fallback from xAI/Anthropic) carry no Gemini
-# thoughtSignature; without this sentinel Gemini 3 thinking models reject
-# replayed history with 400 INVALID_ARGUMENT.
+# Cross-provider tool_calls (e.g. fallback from xAI/Anthropic) carry no Gemini thoughtSignature;
+# without this sentinel Gemini 3 thinking models reject replayed history with 400 INVALID_ARGUMENT.
_SKIP_SIGNATURE = "skip_thought_signature_validator"
_TOOL_CHOICE_MODES = {"auto": "AUTO", "required": "ANY", "none": "NONE"}
_FINISH_REASON_MAP = {
@@ -231,13 +229,11 @@ def _translate_tool_call_to_gemini(tool_call: Dict[str, Any], include_ids: bool
def _looks_like_json_schema(node: Any) -> bool:
- """True if a parsed value contains a JSON-Schema ``$ref`` pointer (``#/...``).
-
- Gemini 3 resolves ``$ref``/``$defs`` inside functionResponse.response and
- rejects unknown pointers with HTTP 400, so a tool result that is itself a
- JSON Schema (e.g. ``tool_describe`` output) must be forwarded as opaque
- text. False positives only lose the structured shape, never the content.
- """
+ """True if a parsed value contains a JSON-Schema ``$ref`` pointer (``#/...``): Gemini 3
+ resolves ``$ref``/``$defs`` inside functionResponse.response and rejects unknown
+ pointers with HTTP 400, so a tool result that is itself a JSON Schema (e.g.
+ ``tool_describe`` output) must be forwarded as opaque text. False positives only
+ lose the structured shape, never the content."""
if isinstance(node, dict):
return any(
(key == "$ref" and isinstance(value, str) and value.startswith("#/")) or _looks_like_json_schema(value)
@@ -251,9 +247,8 @@ def _translate_tool_result_to_gemini(
*, is_gemini3: bool = False,
) -> Dict[str, Any]:
tool_call_id = str(message.get("tool_call_id") or "")
- # functionResponse.name must echo the matching functionCall.name, so the
- # call-id mapping beats the result's own name (which may be an unwrapped
- # internal name, e.g. an MCP tool via `tool_call`).
+ # functionResponse.name must echo the matching functionCall.name, so the call-id
+ # mapping beats the result's own name (may be an unwrapped MCP name via `tool_call`).
name = str((tool_name_by_call_id or {}).get(tool_call_id) or message.get("name") or tool_call_id or "tool")
raw_content = message.get("content")
content = _coerce_content_to_text(raw_content)
@@ -307,15 +302,13 @@ def _build_gemini_contents(
if parts:
contents.append({"role": "model" if role == "assistant" else "user", "parts": parts})
- # Alternation contract for generateContent:
- # 1) Adjacent same-role contents merge (else HTTP 400 "multiturn requests
- # [must] alternate").
- # 2) Exception: never fuse a human user text turn into a preceding user
- # content that only carries functionResponse parts (or vice versa) —
- # Gemini 3 accepts the fold but reads the text as a continuation of the
- # tool result and returns an empty candidate. Parallel tool results
- # (functionResponse + functionResponse) still merge.
- # 3) The split pair stays API-valid via an interposed placeholder model turn.
+ # Alternation contract for generateContent: 1) adjacent same-role contents merge
+ # (else HTTP 400 "multiturn requests [must] alternate"); 2) EXCEPT never fuse a
+ # human user text turn into a preceding user content that only carries
+ # functionResponse parts (or vice versa) — Gemini 3 accepts the fold but reads
+ # the text as a continuation of the tool result and returns an empty candidate
+ # (parallel functionResponse + functionResponse still merge); 3) the split pair
+ # stays API-valid via an interposed placeholder model turn.
merged: List[Dict[str, Any]] = []
for content in contents:
prev = merged[-1] if merged else None
@@ -377,9 +370,9 @@ def _normalize_thinking_config(config: Any) -> Optional[Dict[str, Any]]:
def _thinking_requests_output_headroom(thinking_config: Any) -> bool:
- """True when Gemini will spend output tokens on thinking (thought tokens bill
- against ``maxOutputTokens``; a global 4096/16384 cap can be consumed entirely
- by high thinking, leaving ``finishReason=MAX_TOKENS`` with no answer)."""
+ """True when Gemini will spend output tokens on thinking: thought tokens bill against
+ ``maxOutputTokens``, so a global 4096/16384 cap can be consumed entirely by high
+ thinking, leaving ``finishReason=MAX_TOKENS`` with no answer."""
normalized = _normalize_thinking_config(thinking_config)
if not normalized:
return False
@@ -390,9 +383,9 @@ def _thinking_requests_output_headroom(thinking_config: Any) -> bool:
def _effective_gemini_max_output_tokens(max_tokens: Optional[int], thinking_config: Any) -> int:
- """Native ``maxOutputTokens``: an omitted/invalid cap becomes the published
- ceiling (Gemini truncates on its low internal default); an explicit cap is
- raised to the ceiling when thinking is enabled so thoughts don't starve the answer."""
+ """Native ``maxOutputTokens``: an omitted/invalid cap becomes the published ceiling
+ (Gemini truncates on its low internal default); an explicit cap is raised to the
+ ceiling when thinking is enabled so thoughts don't starve the answer."""
try:
requested = int(max_tokens)
except (TypeError, ValueError):
@@ -605,8 +598,7 @@ def translate_stream_event(event: Dict[str, Any], model: str, tool_call_indices:
finish_chunk = _make_stream_chunk(
model=model, finish_reason="tool_calls" if tool_call_indices else _map_gemini_finish_reason(finish_reason_raw)
)
- # usageMetadata rides on the finish chunk so the streaming loop records
- # token counts like the non-streaming path does.
+ # usageMetadata rides on the finish chunk so the streaming loop records token counts.
if usage_meta := event.get("usageMetadata") or {}:
finish_chunk.usage = _usage_from_metadata(usage_meta)
chunks.append(finish_chunk)
@@ -644,12 +636,11 @@ def gemini_http_error(response: httpx.Response, *, body_text: Optional[str] = No
f"Gemini HTTP {status} ({err_status or 'error'}): {err_message}" if err_message
else f"Gemini returned HTTP {status}: {body_text[:500]}"
)
- # Users who bypassed the setup wizard (raw GOOGLE_API_KEY in .env) still
- # need to learn that the free tier cannot sustain an agent session.
+ # Users who bypassed the setup wizard (raw GOOGLE_API_KEY in .env) still need to learn
+ # the free tier cannot sustain an agent session.
if status == 429 and is_free_tier_quota_error(err_message or body_text):
message += _FREE_TIER_GUIDANCE
- # Legacy "Standard" key rejection: Google's raw 401 misleadingly asks for
- # OAuth; append the actual fix (mint a new Gemini API key in AI Studio).
+ # Legacy "Standard" key rejection: Google's raw 401 misleadingly asks for OAuth; append the real fix.
if is_standard_key_auth_error(status, err_message or body_text, reason):
message += _STANDARD_KEY_GUIDANCE
return GeminiAPIError(
@@ -663,9 +654,8 @@ class GeminiNativeClient:
"""Minimal OpenAI-SDK-compatible facade (``client.chat.completions.create(**kwargs)``)
over Gemini's native REST API."""
- # Declared for agent/auxiliary_client.py: already a complete client, so it
- # is never re-dispatched through a wire adapter. (No HERMES_SKIP_ASYNC_WRAP
- # — the async path has a real conversion, AsyncGeminiNativeClient.)
+ # Declared for agent/auxiliary_client.py: already a complete client, never re-dispatched through
+ # a wire adapter. (No HERMES_SKIP_ASYNC_WRAP — the async path has a real conversion, AsyncGeminiNativeClient.)
HERMES_SKIP_TRANSPORT_WRAP = True
def __init__(
@@ -755,8 +745,7 @@ class AsyncGeminiNativeClient:
self._sync = sync_client
self.api_key, self.base_url = sync_client.api_key, sync_client.base_url
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create_chat_completion))
- # The auxiliary cache evicts entries by leaf client; GeminiNativeClient
- # is itself the leaf (no OpenAI client beneath it).
+ # The auxiliary cache evicts entries by leaf client; GeminiNativeClient is itself the leaf.
self._real_client = sync_client
async def _create_chat_completion(self, **kwargs: Any) -> Any: