Skip to content

The agent that grows with you

refactor(agent/transports): lift codex _reasoning_fields, cc _normalize_tool_call/_attr_or_model_extra, unify approval routing; trim module docstrings

Teknium0d04e1b5c71c
diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py
index 08d5518f055..89703a1af32 100644
--- a/agent/transports/chat_completions.py
+++ b/agent/transports/chat_completions.py
@@ -176,6 +176,14 @@ def _model_consumes_thought_signature(model: Any) -> bool:
return "gemini" in m or "gemma" in m
+def _attr_or_model_extra(obj: Any, name: str) -> Any:
+ """``obj.<name>``, else the same key from pydantic ``model_extra`` (some SDKs park fields there)."""
+ value = getattr(obj, name, None)
+ if value is None and hasattr(obj, "model_extra"):
+ value = (obj.model_extra if isinstance(obj.model_extra, dict) else {}).get(name)
+ return value
+
+
def _dump_extra_content(extra: Any) -> Any:
"""Plain-dict form of a pydantic ``extra_content``; older pydantic lacks ``warnings=``, so retry without it."""
if hasattr(extra, "model_dump"):
@@ -457,41 +465,13 @@ class ChatCompletionsTransport(ProviderTransport):
finish_reason = (str(_fr) if isinstance(_fr, int) else _fr) or "stop" # Poolside returns int finish_reason
tool_calls = None
- message_tool_calls = getattr(msg, "tool_calls", None)
- if message_tool_calls:
- tool_calls = []
- _alias_map = self._last_wire_aliases
- for tc in message_tool_calls:
- tc_function = getattr(tc, "function", None)
- function_name = getattr(tc_function, "name", None)
- # Match Relay's codec: skip absent function/name, keep an explicit blank name.
- if tc_function is None or function_name is None:
- continue
- # Reverse only aliases THIS request emitted; a real ``hermes_tool_search`` tool stays itself.
- if _alias_map is None:
- if function_name == _XAI_TOOL_SEARCH_ALIAS:
- function_name = "tool_search"
- elif function_name in _alias_map:
- function_name = _alias_map[function_name]
- function_arguments = getattr(tc_function, "arguments", None)
- extra = getattr(tc, "extra_content", None)
- if extra is None and hasattr(tc, "model_extra"):
- extra = (tc.model_extra if isinstance(tc.model_extra, dict) else {}).get("extra_content")
- tool_calls.append(ToolCall(
- id=getattr(tc, "id", None), name=function_name,
- arguments=function_arguments if function_arguments is not None else "{}",
- provider_data=None if extra is None else {"extra_content": _dump_extra_content(extra)},
- ))
+ if getattr(msg, "tool_calls", None):
+ tool_calls = [tc for tc in (self._normalize_tool_call(tc) for tc in msg.tool_calls) if tc is not None]
usage = Usage.from_openai(response.usage) if hasattr(response, "usage") and response.usage else None
# Fields some SDKs park in pydantic ``model_extra`` rather than as attributes.
- model_extra = getattr(msg, "model_extra", None) or {}
- model_extra = model_extra if isinstance(model_extra, dict) else {}
- reasoning_content = getattr(msg, "reasoning_content", None)
- if reasoning_content is None:
- reasoning_content = model_extra.get("reasoning_content")
-
+ reasoning_content = _attr_or_model_extra(msg, "reasoning_content")
provider_data: dict[str, Any] = {}
if reasoning_content is not None:
provider_data["reasoning_content"] = reasoning_content
@@ -501,9 +481,7 @@ class ChatCompletionsTransport(ProviderTransport):
# OpenAI structured refusal (``message.refusal`` set, ``content`` empty); without
# promotion the loop retries a deterministic refusal as an empty response.
content = getattr(msg, "content", None)
- refusal = getattr(msg, "refusal", None)
- if refusal is None:
- refusal = model_extra.get("refusal")
+ refusal = _attr_or_model_extra(msg, "refusal")
if isinstance(refusal, str) and refusal.strip():
provider_data["refusal"] = refusal
# Terminal ``content_filter`` only when the refusal is the sole payload.
@@ -517,6 +495,25 @@ class ChatCompletionsTransport(ProviderTransport):
reasoning=getattr(msg, "reasoning", None), usage=usage, provider_data=provider_data or None,
)
+ def _normalize_tool_call(self, tc: Any) -> ToolCall | None:
+ """One SDK tool call -> ToolCall; None when it lacks a function/name (matches Relay's codec)."""
+ tc_function = getattr(tc, "function", None)
+ name = getattr(tc_function, "name", None)
+ if tc_function is None or name is None:
+ return None
+ # Reverse only aliases THIS request emitted; a real ``hermes_tool_search`` tool stays itself.
+ alias_map = self._last_wire_aliases
+ if alias_map is None:
+ name = "tool_search" if name == _XAI_TOOL_SEARCH_ALIAS else name
+ else:
+ name = alias_map.get(name, name)
+ arguments = getattr(tc_function, "arguments", None)
+ extra = _attr_or_model_extra(tc, "extra_content")
+ return ToolCall(
+ id=getattr(tc, "id", None), name=name, arguments="{}" if arguments is None else arguments,
+ provider_data=None if extra is None else {"extra_content": _dump_extra_content(extra)},
+ )
+
def validate_response(self, response: Any) -> bool:
"""Check that response has valid choices."""
return bool(response is not None and getattr(response, "choices", None))
diff --git a/agent/transports/codex.py b/agent/transports/codex.py
index 5538c26ae91..2af1c217801 100644
--- a/agent/transports/codex.py
+++ b/agent/transports/codex.py
@@ -109,17 +109,16 @@ def _alias_reserved_tools(
taken = {name_of(tool) for tool in response_tools if isinstance(tool, dict) and name_of(tool)}
for tool in response_tools:
name = name_of(tool) if isinstance(tool, dict) else None
- if name in reserved_names:
- base = alias = f"{_RESERVED_TOOL_ALIAS_PREFIX}{name}"
- suffix = 2
- while alias in taken:
- alias = f"{base}_{suffix}"
- suffix += 1
- taken.add(alias)
- alias_map[alias] = name
- rewritten.append(rename(tool, alias))
- else:
+ if name not in reserved_names:
rewritten.append(tool)
+ continue
+ base = alias = f"{_RESERVED_TOOL_ALIAS_PREFIX}{name}"
+ suffix = 2
+ while alias in taken:
+ alias, suffix = f"{base}_{suffix}", suffix + 1
+ taken.add(alias)
+ alias_map[alias] = name
+ rewritten.append(rename(tool, alias))
return rewritten, alias_map
@@ -338,6 +337,35 @@ def _coerce_timeout(timeout: Any) -> Optional[float]:
return None
+def _reasoning_fields(
+ model: str, params: dict[str, Any], *, effort: Any, enabled: bool, replay_encrypted_reasoning: bool,
+ is_xai_responses: bool, is_github_responses: bool,
+) -> dict[str, Any]:
+ """``reasoning`` / ``include`` request fields for the endpoint family.
+
+ xAI 400s on ``reasoning.effort`` outside its allowlist; GitHub Models takes a
+ verbatim ``github_reasoning_extra`` and never ``include``.
+ """
+ include = ["reasoning.encrypted_content"] if replay_encrypted_reasoning else []
+ fields: dict[str, Any] = {}
+ if enabled and is_xai_responses:
+ from agent.model_metadata import grok_supports_reasoning_effort
+
+ fields["include"] = include
+ if grok_supports_reasoning_effort(model):
+ fields["reasoning"] = {"effort": effort}
+ elif enabled:
+ if is_github_responses:
+ if params.get("github_reasoning_extra") is not None:
+ fields["reasoning"] = params["github_reasoning_extra"]
+ else:
+ fields["reasoning"] = {"effort": effort, "summary": "auto"}
+ fields["include"] = include
+ elif not is_github_responses and not is_xai_responses:
+ fields["include"] = []
+ return fields
+
+
class ResponsesApiTransport(ProviderTransport):
"""Transport for api_mode='codex_responses'."""
@@ -451,24 +479,11 @@ class ResponsesApiTransport(ProviderTransport):
if cache_retention:
kwargs.setdefault("prompt_cache_retention", cache_retention)
- include = ["reasoning.encrypted_content"] if replay_encrypted_reasoning else []
- if reasoning_enabled and is_xai_responses:
- from agent.model_metadata import grok_supports_reasoning_effort
-
- kwargs["include"] = include
- # xAI 400s on ``reasoning.effort`` for models outside the allowlist.
- if grok_supports_reasoning_effort(model):
- kwargs["reasoning"] = {"effort": reasoning_effort}
- elif reasoning_enabled:
- if is_github_responses:
- if params.get("github_reasoning_extra") is not None:
- kwargs["reasoning"] = params["github_reasoning_extra"]
- else:
- kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
- kwargs["include"] = include
- elif not is_github_responses and not is_xai_responses:
- kwargs["include"] = []
-
+ kwargs.update(_reasoning_fields(
+ model, params, effort=reasoning_effort, enabled=reasoning_enabled,
+ replay_encrypted_reasoning=replay_encrypted_reasoning,
+ is_xai_responses=is_xai_responses, is_github_responses=is_github_responses,
+ ))
if params.get("request_overrides"):
kwargs.update(params["request_overrides"])
@@ -491,12 +506,11 @@ class ResponsesApiTransport(ProviderTransport):
if is_codex_backend:
# SDK kwarg -> HTTP headers. ``session_id`` = raw physical id (transcript
# identity); ``x-client-request-id`` mirrors the body cache key so both agree.
- final_cache_key = kwargs.get("prompt_cache_key") or _bounded_prompt_cache_key(_cache_scope)
- headers = {}
- if session_id:
- headers["session_id"] = str(session_id)
- if final_cache_key:
- headers["x-client-request-id"] = final_cache_key
+ headers = {
+ "session_id": str(session_id) if session_id else None,
+ "x-client-request-id": kwargs.get("prompt_cache_key") or _bounded_prompt_cache_key(_cache_scope),
+ }
+ headers = {k: v for k, v in headers.items() if v}
if headers:
_merge_extra_headers(kwargs, **headers)
elif params.get("max_tokens") is not None:
diff --git a/agent/transports/codex_app_server.py b/agent/transports/codex_app_server.py
index a93d9561c69..5d1ed418aa5 100644
--- a/agent/transports/codex_app_server.py
+++ b/agent/transports/codex_app_server.py
@@ -1,10 +1,8 @@
-"""Codex app-server JSON-RPC client.
+"""Codex app-server JSON-RPC client (newline-delimited JSON-RPC 2.0 over stdio, codex 0.125+).
-Newline-delimited JSON-RPC 2.0 over stdio to ``codex app-server`` (codex 0.125+):
``initialize`` handshake, then ``thread/start`` + ``turn/start`` with streaming
``item/*`` notifications until ``turn/completed``. Wire-level speaker only —
projection, approvals and transcript handling live in sibling modules.
-Opt-in runtime gated behind ``model.openai_runtime == "codex_app_server"``.
"""
from __future__ import annotations
@@ -39,10 +37,9 @@ class CodexAppServerError(RuntimeError):
class CodexAppServerClient:
"""Minimal synchronous JSON-RPC 2.0 client for ``codex app-server`` over stdio.
- The caller drives request/response pairs; one reader thread routes replies
- to pending queues and notifications / server requests to bounded queues;
- another captures stderr. Intentionally NOT async: AIAgent.run_conversation()
- is synchronous and cancellation goes through ``turn/interrupt``.
+ One reader thread routes replies to pending queues and notifications / server
+ requests to queues; another captures stderr. Deliberately NOT async:
+ AIAgent.run_conversation() is synchronous and cancels via ``turn/interrupt``.
"""
def __init__(
@@ -50,32 +47,29 @@ class CodexAppServerClient:
extra_args: Optional[list[str]] = None, env: Optional[dict[str, str]] = None,
) -> None:
self._codex_bin = codex_bin
- # codex needs LLM provider creds (inherit_credentials=True) but must not
- # receive Tier-1 Hermes secrets (gateway/GitHub/infra tokens) — #29157.
+ # codex needs LLM provider creds but must not receive Tier-1 Hermes secrets (gateway/GitHub/infra tokens).
spawn_env = hermes_subprocess_env(inherit_credentials=True)
if env:
spawn_env.update(env)
if codex_home:
spawn_env["CODEX_HOME"] = codex_home
- app_server_args = list(extra_args or [])
+ cmd = [codex_bin, "app-server", *(extra_args or [])]
# Kanban workers must write handoff/status to the board DB outside the
# workspace: keep the sandbox on, add the Kanban root as writable.
if spawn_env.get("HERMES_KANBAN_TASK"):
kanban_db = spawn_env.get("HERMES_KANBAN_DB")
default_root = os.path.join(spawn_env.get("HERMES_HOME", os.path.expanduser("~/.hermes")), "kanban")
kanban_root = os.path.dirname(kanban_db) if kanban_db else spawn_env.get("HERMES_KANBAN_ROOT", default_root)
- app_server_args.extend([
+ cmd += [
"-c", 'sandbox_mode="workspace-write"',
"-c", f'sandbox_workspace_write.writable_roots=["{kanban_root}"]',
"-c", "sandbox_workspace_write.network_access=false",
- ])
-
- cmd = [codex_bin, "app-server"] + app_server_args
+ ]
# Codex emits tracing to stderr; default WARN keeps it quiet for users.
spawn_env.setdefault("RUST_LOG", "warn")
- # Hide the console flash on Windows (#56747); stdio pipes stay intact.
+ # Hide the console flash on Windows; stdio pipes stay intact.
from hermes_cli._subprocess_compat import windows_hide_flags
self._proc = subprocess.Popen(
diff --git a/agent/transports/codex_app_server_session.py b/agent/transports/codex_app_server_session.py
index 6b834fe2fc5..1290bf5b312 100644
--- a/agent/transports/codex_app_server_session.py
+++ b/agent/transports/codex_app_server_session.py
@@ -107,16 +107,11 @@ def _coerce_turn_input_text(user_input: Any) -> str:
if not isinstance(item, dict):
if item.strip() if isinstance(item, str) else item is not None:
parts.append(str(item))
- continue
- item_type = item.get("type")
- if item_type in {"text", "input_text"}:
- text = item.get("text") or item.get("content") or ""
- if text:
- parts.append(str(text))
- elif item_type in {"image", "image_url", "input_image"}:
+ elif item.get("type") in {"text", "input_text"}:
+ parts.append(str(item.get("text") or item.get("content") or ""))
+ elif item.get("type") in {"image", "image_url", "input_image"}:
parts.append("[image attached]")
- text = "\n\n".join(p for p in parts if p).strip()
- return text or "What do you see in this image?"
+ return "\n\n".join(p for p in parts if p).strip() or "What do you see in this image?"
# Substrings in codex stderr / JSON-RPC errors signalling expired OAuth creds.
@@ -576,7 +571,17 @@ class CodexAppServerSession:
"mcpServer/elicitation/request": _respond_elicitation,
}
- def _run_approval_callback(self, command: str, description: str, log_label: str) -> str:
+ def _run_approval_callback(self, auto_approve: bool, prompt: Callable[[], tuple[str, str]], log_label: str) -> str:
+ """Protocol routing only: auto-approve, fail-closed without a callback, else ask via ``prompt()``.
+
+ Approval mode/timeout resolution lives upstream (codex_runtime.py derives the
+ auto flags; the callback runs the shared gate). Do not re-read config here.
+ """
+ if auto_approve:
+ return "accept"
+ if self._approval_callback is None:
+ return "decline"
+ command, description = prompt()
try:
choice = self._approval_callback(command, description, allow_permanent=False)
return _approval_choice_to_codex_decision(choice)
@@ -585,35 +590,28 @@ class CodexAppServerSession:
return "decline"
def _decide_exec_approval(self, params: dict) -> str:
- """Decide a Codex exec approval — protocol routing only.
+ def prompt() -> tuple[str, str]:
+ # ``cwd`` is Optional on codex's side; fall back so the prompt is never empty.
+ description = f"Codex requests exec in {params.get('cwd') or self._cwd or '<unknown>'}"
+ if params.get("reason"):
+ description += f" — {params['reason']}"
+ return params.get("command") or "", description
- Approval mode/timeout resolution lives upstream (codex_runtime.py derives
- ``auto_approve_exec``; the callback runs the shared gate). Do not re-read config here.
- """
- if self._routing.auto_approve_exec:
- return "accept"
- if self._approval_callback is None:
- return "decline" # fail-closed when no callback wired
- # ``cwd`` is Optional on codex's side; fall back so the prompt is never empty.
- description = f"Codex requests exec in {params.get('cwd') or self._cwd or '<unknown>'}"
- if params.get("reason"):
- description += f" — {params['reason']}"
- return self._run_approval_callback(params.get("command") or "", description, "exec request")
+ return self._run_approval_callback(self._routing.auto_approve_exec, prompt, "exec request")
def _decide_apply_patch_approval(self, params: dict) -> str:
- """Decide a Codex apply_patch approval request (routing only; see _decide_exec_approval)."""
- if self._routing.auto_approve_apply_patch:
- return "accept"
- if self._approval_callback is None:
- return "decline"
- # Params carry reason + grantRoot only; the changeset comes from _track_pending_file_change.
- reason = params.get("reason")
- grant_root = params.get("grantRoot")
- change_summary = self._pending_file_changes.get(params.get("itemId") or "") or None
- description_parts = [p for p in (reason, change_summary, grant_root and f"grants write to {grant_root}") if p]
- description = "; ".join(description_parts) if description_parts else "Codex requests to apply a patch"
- detail = change_summary or reason
- return self._run_approval_callback(f"apply_patch: {detail}" if detail else "apply_patch", description, "apply_patch")
+ def prompt() -> tuple[str, str]:
+ # Params carry reason + grantRoot only; the changeset comes from _track_pending_file_change.
+ reason, grant_root = params.get("reason"), params.get("grantRoot")
+ change_summary = self._pending_file_changes.get(params.get("itemId") or "") or None
+ parts = [p for p in (reason, change_summary, grant_root and f"grants write to {grant_root}") if p]
+ detail = change_summary or reason
+ return (
+ f"apply_patch: {detail}" if detail else "apply_patch",
+ "; ".join(parts) if parts else "Codex requests to apply a patch",
+ )
+
+ return self._run_approval_callback(self._routing.auto_approve_apply_patch, prompt, "apply_patch")
def _track_pending_file_change(self, note: dict) -> None:
"""Track fileChange items (item/started -> item/completed) so the apply_patch prompt can show the changeset."""
diff --git a/agent/transports/codex_event_projector.py b/agent/transports/codex_event_projector.py
index af96848acde..3c5912c0455 100644
--- a/agent/transports/codex_event_projector.py
+++ b/agent/transports/codex_event_projector.py
@@ -1,14 +1,10 @@
-"""Projects codex app-server events into Hermes' messages list.
-
-Converts Codex ``item/*`` notifications into OpenAI-shaped
-``{role, content, tool_calls, tool_call_id}`` entries that memory/skill review
-(agent/curator.py) already reads:
- userMessage → user; agentMessage → assistant; reasoning → stashed onto the next
- assistant entry; commandExecution / fileChange / mcpToolCall / dynamicToolCall →
- assistant tool_call + tool result; anything else → opaque assistant note.
-Each item yields AT MOST one assistant + one tool entry, preserving Hermes'
-message-alternation invariants. ``is_tool_iteration`` ticks once per completed
-tool-shaped item (AIAgent._iters_since_skill skill-nudge gate).
+"""Projects codex app-server ``item/*`` notifications into OpenAI-shaped messages.
+
+userMessage → user; agentMessage → assistant; reasoning → stashed onto the next
+assistant entry; commandExecution / fileChange / mcpToolCall / dynamicToolCall →
+assistant tool_call + tool result; anything else → opaque assistant note.
+Each item yields AT MOST one assistant + one tool entry (message-alternation
+invariant). ``is_tool_iteration`` ticks once per completed tool-shaped item.
"""
from __future__ import annotations
@@ -20,8 +16,7 @@ from typing import Any, Callable, Optional
def _deterministic_call_id(item_type: str, item_id: str) -> str:
- """Stable tool_call id: the codex item id when present, else a content hash so
- replay yields the same id across sessions and prefix caches stay valid."""
+ """Stable tool_call id: the codex item id, else a hash so replay keeps prefix caches valid."""
return f"codex_{item_type}_{item_id or hashlib.sha256(f'{item_type}'.encode()).hexdigest()[:16]}"
@@ -37,11 +32,7 @@ def _dict_args(raw: Any) -> dict:
@dataclass
class ProjectionResult:
- """Output of projecting one Codex item.
-
- ``messages`` may hold two entries (assistant tool_call + tool result); empty
- means the item was ignored (e.g. a streaming delta before ``item/completed``).
- """
+ """Output of projecting one Codex item; empty ``messages`` = ignored (e.g. a streaming delta)."""
messages: list[dict] = field(default_factory=list)
is_tool_iteration: bool = False
@@ -49,21 +40,13 @@ class ProjectionResult:
class CodexEventProjector:
- """Stateful projector consuming Codex notifications in arrival order.
-
- Owns in-progress reasoning: codex emits it as separate items, Hermes stashes
- it on the next assistant message.
- """
+ """Stateful projector; stashes codex's separate reasoning items onto the next assistant message."""
def __init__(self) -> None:
self._pending_reasoning: list[str] = []
def project(self, notification: dict) -> ProjectionResult:
- """Project one notification; only ``item/completed`` materializes messages.
-
- Streaming deltas are display-only, mirroring how Hermes writes the
- assistant message only after the streaming completion event.
- """
+ """Project one notification; only ``item/completed`` materializes messages (deltas are display-only)."""
if notification.get("method", "") != "item/completed":
return ProjectionResult()
item = (notification.get("params", {}) or {}).get("item") or {}
@@ -80,9 +63,7 @@ class CodexEventProjector:
tool_projection = self._TOOL_PROJECTIONS.get(item_type)
if tool_projection is not None:
return self._project_tool_item(item, item_id, tool_projection)
- # Unknown / rare items (plan, hookPrompt, collabAgentToolCall, ...): keep an
- # opaque note so memory review sees *something* happened, without
- # fabricating tool_call structure.
+ # Unknown / rare items (plan, hookPrompt, ...): opaque note, no fabricated tool_call structure.
return self._project_opaque(item, item_type)
def _assistant_message(self, content: Optional[str], **extra: Any) -> dict[str, Any]:
@@ -110,10 +91,7 @@ class CodexEventProjector:
def _project_tool_item(
self, item: dict, item_id: str, spec: Callable[[dict], tuple[str, str, dict, str]]
) -> ProjectionResult:
- """Emit the (assistant tool_call, tool result) pair for a tool-shaped item.
-
- ``spec(item)`` returns ``(call_id_type, tool_name, args, tool_content)``.
- """
+ """Emit the (assistant tool_call, tool result) pair; ``spec(item)`` -> ``(id_type, name, args, content)``."""
id_type, name, args, content = spec(item)
call_id = _deterministic_call_id(id_type, item_id)
assistant_msg = self._assistant_message(
@@ -152,8 +130,7 @@ class CodexEventProjector:
content = f"[error] {json.dumps(error, ensure_ascii=False)[:1000]}"
else:
content = json.dumps(result, ensure_ascii=False)[:4000] if result is not None else ""
- # Mirror the native MCP name convention (mcp__server__tool) in the call id
- # so it stays consistent with registration names.
+ # Call id mirrors the native MCP name convention (mcp__server__tool).
return f"mcp__{server}__{tool}", f"mcp.{server}.{tool}", _dict_args(item.get("arguments")), content
@staticmethod
diff --git a/agent/transports/hermes_tools_mcp_server.py b/agent/transports/hermes_tools_mcp_server.py
index 05c619a932e..48909a026c1 100644
--- a/agent/transports/hermes_tools_mcp_server.py
+++ b/agent/transports/hermes_tools_mcp_server.py
@@ -1,10 +1,8 @@
"""Hermes-tools-as-MCP server for the codex_app_server runtime.
-Under the codex app-server, codex owns the loop and its own tool list, so
-Hermes' richer surface (web search, browser, vision, image gen, skills, TTS,
-kanban handoff) would be unreachable. This module exposes a curated subset over
-stdio MCP; codex registers it via ``~/.codex/config.toml [mcp_servers.hermes-tools]``.
-Run with: ``python -m agent.transports.hermes_tools_mcp_server``.
+Codex owns the loop and tool list there, so a curated subset of Hermes tools is
+exposed over stdio MCP; codex registers it via ``~/.codex/config.toml
+[mcp_servers.hermes-tools]``. Run: ``python -m agent.transports.hermes_tools_mcp_server``.
"""
from __future__ import annotations
@@ -23,8 +21,7 @@ _JSON_TO_PY = {"string": str, "integer": int, "number": float, "boolean": bool,
def _signature_from_schema(schema: dict | None) -> tuple[inspect.Signature, dict[str, type]]:
- """Build a KEYWORD_ONLY signature + annotations dict from a JSON schema's
- ``properties`` / ``required`` (optional params default to None)."""
+ """KEYWORD_ONLY signature + annotations from a JSON schema (optional params default to None)."""
props = (schema or {}).get("properties") or {}
required = set((schema or {}).get("required") or [])
params, annots = [], {}
@@ -38,12 +35,9 @@ def _signature_from_schema(schema: dict | None) -> tuple[inspect.Signature, dict
return inspect.Signature(params, return_annotation=str), annots
-# Each name MUST match a registered Hermes tool that
-# ``model_tools.handle_function_call()`` can dispatch.
-# Deliberately NOT exposed: terminal/shell, read_file/write_file/patch,
-# search_files/process, clarify — codex's built-ins cover them with codex's own
-# approval UI; delegate_task/memory/session_search/todo — ``_AGENT_LOOP_TOOLS``
-# need the running AIAgent context, which a stateless MCP callback lacks.
+# Each name MUST match a registered Hermes tool ``model_tools.handle_function_call()`` can dispatch.
+# NOT exposed: terminal/file/search/process/clarify (codex built-ins + its own approval UI);
+# delegate_task/memory/session_search/todo (need the running AIAgent context).
EXPOSED_TOOLS: tuple[str, ...] = (
"web_search", "web_extract",
"browser_navigate", "browser_click", "browser_type", "browser_press", "browser_snapshot", "browser_scroll",
@@ -59,8 +53,7 @@ EXPOSED_TOOLS: tuple[str, ...] = (
def _build_server() -> Any:
- """Create the MCP server with Hermes tools attached (lazy imports so the module
- imports without the mcp package; the clear error fires only when run)."""
+ """Create the MCP server with Hermes tools attached (lazy imports: importable without ``mcp``)."""
try:
# mcp 2.0 renamed `mcp.server.fastmcp` to `mcp.server.MCPServer` (same surface).
from mcp.server import MCPServer
@@ -88,8 +81,7 @@ def _build_server() -> Any:
}
def _make_handler(tool_name: str, schema: dict | None, description: str):
- # The SDK derives the input schema from the callable's signature (no
- # inputSchema parameter), so synthesize __signature__ from the Hermes JSON Schema.
+ # The SDK derives the input schema from the callable's signature, so synthesize it from the JSON Schema.
sig, annots = _signature_from_schema(schema)
def _dispatch(**kwargs: Any) -> str:
diff --git a/agent/transports/types.py b/agent/transports/types.py
index 82c5f5c40c0..e5e4c5c10a2 100644
--- a/agent/transports/types.py
+++ b/agent/transports/types.py
@@ -54,11 +54,7 @@ class Usage:
@classmethod
def from_openai(cls, u: Any) -> Usage:
"""Build from an OpenAI-shaped usage object, treating missing/None counts as 0."""
- return cls(
- prompt_tokens=getattr(u, "prompt_tokens", 0) or 0,
- completion_tokens=getattr(u, "completion_tokens", 0) or 0,
- total_tokens=getattr(u, "total_tokens", 0) or 0,
- )
+ return cls(**{k: getattr(u, k, 0) or 0 for k in ("prompt_tokens", "completion_tokens", "total_tokens")})
@dataclass
diff --git a/agent/vertex_adapter.py b/agent/vertex_adapter.py
index b3bef778d66..bdded472f5f 100644
--- a/agent/vertex_adapter.py
+++ b/agent/vertex_adapter.py
@@ -1,16 +1,9 @@
-"""Vertex AI (Google Cloud) adapter for Hermes Agent.
+"""Vertex AI (Google Cloud) auth + base-URL resolution for its OpenAI-compatible endpoint.
-Authentication and configuration for Vertex AI's OpenAI-compatible endpoint
-(Gemini via Google Cloud). Requires ``google-auth`` (lazy-installed).
-
-Environment variables honored (all optional, secrets):
- GOOGLE_APPLICATION_CREDENTIALS — path to a service account JSON file.
- VERTEX_CREDENTIALS_PATH — alias, takes precedence if set.
- VERTEX_PROJECT_ID — override the project_id embedded in creds.
- VERTEX_REGION — override default region ("global" unless set).
-
-Non-secret routing settings (project_id, region) also live in config.yaml
-under the ``vertex:`` section; env vars take precedence over config.yaml.
+Requires ``google-auth`` (lazy-installed). Secrets: GOOGLE_APPLICATION_CREDENTIALS /
+VERTEX_CREDENTIALS_PATH (SA JSON path; the latter wins), VERTEX_PROJECT_ID,
+VERTEX_REGION. project_id/region may also live in config.yaml ``vertex:``;
+env wins over config.
"""
import hashlib
@@ -22,13 +15,12 @@ from typing import Any, Optional, Tuple
from agent.secret_scope import get_secret as _get_secret, is_multiplex_active
-# The [vertex] extra is not in [all]; lazy_deps installs google-auth on demand
-# for users who selected a Gemini model after a plain install.
+# The [vertex] extra is not in [all]; install google-auth on demand, else fall through to the ImportError below.
try:
from tools.lazy_deps import ensure as _lazy_ensure
_lazy_ensure("provider.vertex", prompt=False)
except Exception:
- pass # lazy_deps unavailable or install failed — fall through to the real ImportError below
+ pass
try:
import google.auth
@@ -67,17 +59,15 @@ def _resolve_region(explicit: Optional[str] = None) -> str:
def _resolve_project_override() -> Optional[str]:
- """Project-ID override (VERTEX_PROJECT_ID env > config.yaml), or None to use
- the credentials' embedded project_id."""
+ """Project-ID override (VERTEX_PROJECT_ID env > config.yaml), or None to use the creds' embedded project_id."""
return _env_or_config("VERTEX_PROJECT_ID", "project_id") or None
def _resolve_credentials_path(explicit: Optional[str]) -> Optional[str]:
if explicit and os.path.exists(explicit):
return explicit
- # get_secret, not os.environ: a multiplex gateway serves several profiles
- # from one process, and os.environ reflects whichever .env loaded at boot.
- # A raw read could mint (and bill) tokens from another profile's SA file.
+ # get_secret, not os.environ: under a multiplex gateway os.environ reflects whichever
+ # .env loaded at boot, and a raw read could mint (and bill) another profile's SA tokens.
for env_var in ("VERTEX_CREDENTIALS_PATH", "GOOGLE_APPLICATION_CREDENTIALS"):
path = _get_secret(env_var)
if path and os.path.exists(path):
@@ -116,10 +106,8 @@ def _load_credentials(resolved_path: Optional[str], sa_raw: Optional[bytes]) ->
# Unreadable at key time: let the SDK try the file directly.
creds = service_account.Credentials.from_service_account_file(resolved_path, scopes=_CLOUD_PLATFORM_SCOPES)
return creds, creds.project_id
- # google.auth.default() reads GOOGLE_APPLICATION_CREDENTIALS straight from
- # os.environ, which load_dotenv() mutated at boot for whichever profile
- # loaded first. _resolve_credentials_path confirmed *this* profile doesn't
- # define the var, so refuse rather than authenticate under a stranger's identity.
+ # google.auth.default() reads GOOGLE_APPLICATION_CREDENTIALS from os.environ (set by whichever
+ # profile loaded first); this profile doesn't define it, so refuse a stranger's identity.
if is_multiplex_active() and os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):
logger.warning(
"Vertex ADC skipped for this profile: GOOGLE_APPLICATION_CREDENTIALS is set in the process environment "
@@ -140,18 +128,13 @@ def _needs_refresh(creds) -> bool:
def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:
- """Return a (fresh access_token, project_id) pair or (None, None) on failure.
-
- Caches the Credentials object per file content and refreshes it when
- within 5 minutes of expiry, so repeated calls don't thrash the token endpoint.
- """
+ """Return (fresh access_token, project_id) or (None, None); Credentials cached per file content."""
if google is None:
logger.warning("google-auth package not installed. Cannot use Vertex AI.")
return None, None
resolved_path = _resolve_credentials_path(credentials_path)
- # One read serves both the cache key and (on a miss) credential
- # construction, so the credentials always match the fingerprinted bytes.
+ # One read serves both the cache key and credential construction (creds always match the fingerprint).
sa_raw, cache_key = _sa_snapshot(resolved_path)
try:
@@ -182,12 +165,7 @@ def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Opti
def build_vertex_base_url(project_id: str, region: str = DEFAULT_REGION) -> str:
- """Build the OpenAI-compatible base URL for Vertex AI.
-
- ``global`` uses the bare ``aiplatform.googleapis.com`` host; regional
- locations use ``{region}-aiplatform.googleapis.com``. Gemini 3.x preview
- models are only served via the global endpoint.
- """
+ """OpenAI-compatible Vertex base URL; ``global`` uses the bare host (Gemini 3.x preview is global-only)."""
host = "aiplatform.googleapis.com" if region == "global" else f"{region}-aiplatform.googleapis.com"
return f"https://{host}/v1beta1/projects/{project_id}/locations/{region}/endpoints/openapi"
@@ -203,20 +181,15 @@ def get_vertex_config(
def has_vertex_credentials() -> bool:
- """Fast check (no network, no google-auth import) for configured Vertex
- credentials: a resolvable SA JSON path, or an explicit project ID
- (env or config.yaml, implying ADC is intended)."""
+ """Fast check (no network): a resolvable SA JSON path, or an explicit project ID (implies ADC)."""
return bool(_resolve_credentials_path(None) or _resolve_project_override())
def has_explicit_vertex_config() -> bool:
"""True only when the user deliberately pointed Hermes at Vertex.
- Stricter than :func:`has_vertex_credentials`: an ambient
- ``GOOGLE_APPLICATION_CREDENTIALS`` (often set for unrelated GCP work) must
- NOT mark Vertex "explicitly configured" for the model-picker gate, or a user
- could unknowingly spend against those credentials. Only Hermes-scoped signals
- count: ``VERTEX_PROJECT_ID`` / ``vertex.project_id`` or a readable ``VERTEX_CREDENTIALS_PATH``.
+ Stricter than :func:`has_vertex_credentials`: an ambient ``GOOGLE_APPLICATION_CREDENTIALS``
+ must NOT gate the model picker open (unknowing spend). Only Hermes-scoped signals count.
"""
if _resolve_project_override():
return True