diff --git a/.mailmap b/.mailmap index 5af0a658645a4..92b91cef4b47e 100644 --- a/.mailmap +++ b/.mailmap @@ -17,6 +17,8 @@ Teknium <127238744+teknium1@users.noreply.github.com> # === Contributors — personal/work emails mapped to GitHub noreply === # Format: Canonical Name +Mike DeMott <25466867+mrkillbob@users.noreply.github.com> + # Verified via GH API email search kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> luyao618 <364939526@qq.com> <364939526@qq.com> diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index b62809ab4c602..a3ecd6034dc84 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -24,6 +24,8 @@ from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, TYPE_CHECKING from urllib.parse import urlparse, parse_qs, urlunparse +from agent.llm_egress_firewall import EgressBlocked + from agent.codex_headers import ( CODEX_AUX_BASE_URL as _CODEX_AUX_BASE_URL, apply_required_codex_headers as _apply_required_codex_headers, @@ -2383,11 +2385,119 @@ def _relay_aux_call_scope(args: tuple, kwargs: dict): _RELAY_AUX_CALL_CONTEXT.reset(token) +def _auxiliary_egress_binding( + client: Any, + *, + provider: str | None, + model: str | None, + api_mode: str | None, +) -> tuple[Any, Any] | None: + """Build the complete identity and route for protected auxiliary calls.""" + normalized_provider = _normalize_aux_provider(provider) + from agent.llm_egress_runtime import provider_uses_egress_firewall + + if not provider_uses_egress_firewall(normalized_provider): + return None + from agent.source_provenance import DEFAULT_POLICY_DIGEST + + runtime = _normalize_main_runtime(None) + raw_runtime = _RUNTIME_MAIN_CONTEXT.get() or {} + relay = _RELAY_AUX_CALL_CONTEXT.get() or {} + request_id = str(relay.get("request_id") or f"aux-{uuid.uuid4().hex}") + session_id = str( + runtime.get("session_id") + or raw_runtime.get("session_id") + or f"aux-session:{request_id}" + ) + turn_id = str( + raw_runtime.get("turn_id") + or f"{session_id}:aux:{str(relay.get('task') or 'call')}" + ) + policy_digest = str( + raw_runtime.get("policy_digest") + or raw_runtime.get("llm_egress_policy_digest") + or DEFAULT_POLICY_DIGEST + ) + # SDK clients expose httpx.URL; bind the actual auxiliary endpoint before + # considering the main runtime, which may be a different local route. + candidate_base_url = str(getattr(client, "base_url", "") or "") + if not isinstance(candidate_base_url, str) or not candidate_base_url.startswith( + ("http://", "https://") + ): + candidate_base_url = raw_runtime.get("base_url") + if not isinstance(candidate_base_url, str) or not candidate_base_url.startswith( + ("http://", "https://") + ): + if normalized_provider == "openai-codex": + candidate_base_url = "https://chatgpt.com/backend-api/codex" + elif normalized_provider == "anthropic": + candidate_base_url = "https://api.anthropic.com/v1" + else: + candidate_base_url = _NOUS_DEFAULT_BASE_URL + base_url = candidate_base_url + resolved_api_mode = str( + api_mode + or ( + "codex_responses" + if normalized_provider == "openai-codex" + else "chat_completions" + ) + ) + agent_attrs = { + "provider": normalized_provider, + "model": str(model or ""), + "base_url": base_url, + "api_mode": resolved_api_mode, + "session_id": session_id, + "_current_turn_id": turn_id, + "_current_api_request_id": request_id, + "_llm_egress_policy_digest": policy_digest, + "_llm_egress_state_dir": Path(get_hermes_home()) / "egress", + } + if str(relay.get("task") or "") == "compression": + agent_attrs.update( + _llm_egress_max_serialized_bytes=2_000_000, + _llm_egress_max_conservative_tokens=666_667, + _llm_egress_max_sanitized_bytes=2_000_000, + _llm_egress_max_sanitized_segment_bytes=32_768, + _llm_egress_max_granted_serialized_bytes=2_000_000, + _llm_egress_max_granted_conservative_tokens=666_667, + ) + agent = SimpleNamespace(**agent_attrs) + route = SimpleNamespace( + provider=normalized_provider, + model=str(model or ""), + base_url=base_url, + api_mode=resolved_api_mode, + ) + return agent, route + + +def _dispatch_auxiliary_request( + client: Any, + request: dict[str, Any], + callback: Callable[[dict[str, Any]], Any], + *, + provider: str | None, + model: str | None, + api_mode: str | None, +) -> Any: + binding = _auxiliary_egress_binding( + client, provider=provider, model=model or request.get("model"), api_mode=api_mode + ) + if binding is None: + return callback(request) + from agent.llm_egress_runtime import dispatch_authorized_agent_request + + agent, route = binding + return dispatch_authorized_agent_request(agent, request, callback, route=route) + + def _relay_auxiliary_call(callback): """Give every physical retry in one auxiliary call a shared Relay identity.""" @functools.wraps(callback) def wrapped(*args, **kwargs): - with _relay_aux_call_scope(args, kwargs): + with _relay_aux_call_scope(args, kwargs), scoped_runtime_main(kwargs.get("main_runtime")): return callback(*args, **kwargs) return wrapped @@ -2396,7 +2506,7 @@ def _relay_auxiliary_call_async(callback): """Async counterpart to :func:`_relay_auxiliary_call`.""" @functools.wraps(callback) async def wrapped(*args, **kwargs): - with _relay_aux_call_scope(args, kwargs): + with _relay_aux_call_scope(args, kwargs), scoped_runtime_main(kwargs.get("main_runtime")): return await callback(*args, **kwargs) return wrapped @@ -2440,51 +2550,131 @@ def _relay_auxiliary_metadata( def _relay_sync_completion( - client: Any, kwargs: dict[str, Any], *, provider: str | None = None, - api_mode: str | None = None, create: Callable[[dict[str, Any]], Any] | None = None, + client: Any, + kwargs: dict[str, Any], + *, + provider: str | None = None, + api_mode: str | None = None, + create: Callable[[dict[str, Any]], Any] | None = None, ) -> Any: callback = create or (lambda request: client.chat.completions.create(**request)) + raw_callback = callback + callback = lambda request: _dispatch_auxiliary_request( + client, + request, + raw_callback, + provider=provider, + model=request.get("model"), + api_mode=api_mode, + ) route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) - # Isolate only the provider callback so the owning thread can unwind its lease/DB - # transaction on hard cancel without touching the shared client. + # Protected compression calls isolate only the provider callback and stream + # aggregation. The owning thread remains free to unwind its lease/DB + # transaction on hard cancel without touching the process-shared client. if route is None: return _run_protected_sync_provider_call(callback, kwargs) provider_name, fallback_model, metadata = route from agent import relay_llm + return relay_llm.execute_current( - kwargs, lambda request: _run_protected_sync_provider_call(callback, request), - name=provider_name, model_name=str(kwargs.get("model") or fallback_model), - metadata=metadata, defer_logical_completion=True, + kwargs, + lambda request: _run_protected_sync_provider_call(callback, request), + name=provider_name, + model_name=str(kwargs.get("model") or fallback_model), + metadata=metadata, + defer_logical_completion=True, ) async def _relay_async_completion( - client: Any, kwargs: dict[str, Any], *, provider: str | None = None, - api_mode: str | None = None, create: Callable[[dict[str, Any]], Any] | None = None, + client: Any, + kwargs: dict[str, Any], + *, + provider: str | None = None, + api_mode: str | None = None, + create: Callable[[dict[str, Any]], Any] | None = None, ) -> Any: callback = create or (lambda request: client.chat.completions.create(**request)) + raw_callback = callback + + async def _authorized_callback(request: dict[str, Any]) -> Any: + binding = _auxiliary_egress_binding( + client, + provider=provider, + model=request.get("model"), + api_mode=api_mode, + ) + if binding is None: + return await raw_callback(request) + from agent.llm_egress_runtime import dispatch_authorized_agent_request + + agent, route = binding + result = dispatch_authorized_agent_request( + agent, + request, + raw_callback, + route=route, + ) + return await result if inspect.isawaitable(result) else result + + callback = _authorized_callback route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) if route is None: return await callback(kwargs) provider_name, fallback_model, metadata = route from agent import relay_llm + return await relay_llm.execute_current_async( - kwargs, callback, name=provider_name, model_name=str(kwargs.get("model") or fallback_model), - metadata=metadata, defer_logical_completion=True, + kwargs, + callback, + name=provider_name, + model_name=str(kwargs.get("model") or fallback_model), + metadata=metadata, + defer_logical_completion=True, ) def _relay_sync_stream( - client: Any, kwargs: dict[str, Any], *, provider: str | None = None, api_mode: str | None = None + client: Any, + kwargs: dict[str, Any], + *, + provider: str | None = None, + api_mode: str | None = None, ) -> Any: + # Relay may invoke the factory after call_llm's public scope has unwound. + # Bind the captured runtime at the physical callback, without holding a + # ContextVar scope open across chunks yielded to the caller. + runtime = _normalize_main_runtime(None) + relay_context = _RELAY_AUX_CALL_CONTEXT.get() + + def callback(request: dict[str, Any]) -> Any: + relay_token = _RELAY_AUX_CALL_CONTEXT.set(relay_context) + try: + with scoped_runtime_main(runtime): + return _dispatch_auxiliary_request( + client, + request, + lambda authorized: client.chat.completions.create(**authorized), + provider=provider, + model=request.get("model"), + api_mode=api_mode, + ) + finally: + _RELAY_AUX_CALL_CONTEXT.reset(relay_token) + route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) if route is None: - return client.chat.completions.create(**kwargs) + return callback(kwargs) provider_name, fallback_model, metadata = route from agent import relay_llm + return relay_llm.stream_current( - kwargs, lambda request: client.chat.completions.create(**request), name=provider_name, - model_name=str(kwargs.get("model") or fallback_model), finalizer=dict, metadata=metadata, + kwargs, + callback, + name=provider_name, + model_name=str(kwargs.get("model") or fallback_model), + finalizer=dict, + metadata=metadata, completed_response_predicate=lambda value: hasattr(value, "choices"), ) @@ -2843,7 +3033,10 @@ def _try_anthropic(explicit_api_key: str = None) -> Tuple[Optional[Any], Optiona _MAIN_RUNTIME_FIELDS = ("provider", "model", "base_url", "api_key", "api_mode", "auth_mode") -_MAIN_RUNTIME_CONTEXT_FIELDS = _MAIN_RUNTIME_FIELDS + ("requested_provider",) +_MAIN_RUNTIME_CONTEXT_FIELDS = _MAIN_RUNTIME_FIELDS + ( + "requested_provider", "session_id", "cache_scope", "turn_id", + "policy_digest", "llm_egress_policy_digest", +) def _normalize_main_runtime(main_runtime: Optional[Dict[str, Any]]) -> Dict[str, Any]: @@ -3057,6 +3250,21 @@ def _is_transient_transport_error(exc: Exception) -> bool: _TRANSIENT_RETRY_BACKOFF_BASE = 1.0 # Backoff base (seconds); overridable so tests can zero it out. +def _is_safe_egress_fallback_candidate(client: Any, provider: str, model: str) -> bool: + """Permit a blocked remote request to fall back only to local execution. + + A blocked payload must never be retried against another remote provider; + only an explicitly local/loopback fallback is eligible, and its callback + still receives a fresh request copy at the local boundary. + """ + from agent.llm_egress_firewall import DestinationClass, classify_destination + + base_url = str(getattr(client, "base_url", "") or "") + destination = classify_destination(provider, base_url, "chat_completions") + return destination in {DestinationClass.LOCAL_PROCESS, DestinationClass.LOOPBACK} + + + def _transient_retry_count() -> int: """Same-provider retries for a transient blip: ``auxiliary.transient_retries`` (default 2), clamped to [0, 6]; config-read failures fall back to default.""" @@ -6849,6 +7057,122 @@ def _ladder_provider_fallback(first_err: Exception, route: _LadderRoute): return None +def _local_egress_fallback_entry(entry: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """Screen the router's concrete endpoint before credentials or catalogs resolve. + + Built-in OAuth/discovery arms do not honor entry URLs. Named custom arms + use their provider configuration instead; ordinary API-key arms honor an + explicit URL. Never infer locality from a provider name or transport mode. + """ + from agent.llm_egress_firewall import DestinationClass, classify_destination + + raw_provider = str(entry.get("provider") or "").strip() + if not raw_provider or not str(entry.get("model") or "").strip(): + return None + provider = _normalize_aux_provider(raw_provider) + if provider in _EXPLICIT_PROVIDER_BRANCHES and provider != "custom": + return None + base_url = str(entry.get("base_url") or "").strip() + if provider == "custom": + # Pin a concrete endpoint so the custom resolver cannot discover a + # remote provider when the main/task configuration is incomplete. + base_url = ( + base_url + or str(_runtime_main_value("base_url") or "").strip() + or os.getenv("OPENAI_BASE_URL", "").strip() + or _read_main_field("base_url", readonly=True) + ) + else: + try: + from hermes_cli.runtime_provider import _get_named_custom_provider + + original_provider = raw_provider.lower() + named = ( + _get_named_custom_provider(original_provider) + if original_provider != provider else None + ) + if named is None: + named = _get_named_custom_provider(provider) + if named: + # The named-provider router ignores an entry's URL override. + base_url = str(named.get("base_url") or "").strip() + else: + from hermes_cli.auth import PROVIDER_REGISTRY + + registered = PROVIDER_REGISTRY.get(provider) + if ( + registered is None or registered.auth_type != "api_key" + or provider in {"anthropic", "copilot", "azure-foundry"} + ): + return None + env_url = ( + os.getenv(registered.base_url_env_var, "").strip() + if registered.base_url_env_var else "" + ) + # Z.AI probes remote endpoints while resolving credentials, + # before the router applies an entry's explicit URL override. + if provider == "zai" and classify_destination( + provider, env_url, "chat_completions" + ) is not DestinationClass.LOOPBACK: + return None + base_url = base_url or env_url or registered.inference_base_url + except Exception: + return None + if classify_destination(provider, base_url, "chat_completions") is not DestinationClass.LOOPBACK: + return None + return {**entry, "base_url": base_url} + + +def _egress_fallback_entries(route: _LadderRoute): + """Yield configured candidates first; read the main route only if needed.""" + if route.task: + chain = _get_auxiliary_task_config(route.task).get("fallback_chain") + if isinstance(chain, list): + for i, entry in enumerate(chain): + if isinstance(entry, dict): + yield entry, f"fallback_chain[{i}]({str(entry.get('provider') or '').strip()})" + main_provider = (_read_main_provider() or "").strip() + main_model = (_read_main_model() or "").strip() + if main_provider.lower() == "moa": + main_provider, main_model = _resolve_moa_aggregator(main_model) + if not main_provider or not main_model or _is_provider_unhealthy(main_provider): + return + yield {"provider": main_provider, "model": main_model}, f"main-agent({main_provider})" + + +def _ladder_egress_fallback(route: _LadderRoute): + """A deterministic policy rejection may only reuse the payload locally.""" + skip = _failed_backend_skip(route.resolved_provider or "auto", route.final_model) + min_ctx = _task_minimum_context_length(route.task) + for raw_entry, label in _egress_fallback_entries(route): + entry = _local_egress_fallback_entry(raw_entry) + if entry is None: + continue + provider = str(entry["provider"]).strip() + model = str(entry["model"]).strip() + if skip(provider, model, entry["base_url"]): + continue + try: + client, resolved_model = _resolve_fallback_entry(entry) + except Exception: + continue + if client is None or not _is_safe_egress_fallback_candidate(client, provider, model): + continue + model = resolved_model or model + # Context screening must use the verified local endpoint too: an empty + # or stale entry URL could otherwise trigger a remote catalog lookup. + local_entry = {**entry, "base_url": str(client.base_url)} + if label.startswith("fallback_chain[") and _context_too_small( + local_entry, provider, model, min_ctx, task=route.task, label=label, name_model=True, + ): + continue + _record_route_info(route.route_info, provider, model) + response = yield _LadderStep("fallback", (client, model, label)) + if response is not None: + return response + return _RERAISE_ORIGINAL + + def _aux_recovery_ladder( first_err: Exception, *, client: Any, kwargs: Dict[str, Any], task: Optional[str], async_mode: bool, base_info: str, resolved_provider: str, resolved_model: Optional[str], @@ -6864,6 +7188,8 @@ def _aux_recovery_ladder( route = _LadderRoute( client, task, tag, async_mode, base_info, resolved_provider, resolved_model, resolved_base_url, resolved_api_key, resolved_api_mode, final_model, main_runtime, route_info) + if isinstance(first_err, EgressBlocked): + return (yield from _ladder_egress_fallback(route)) resp, first_err, kwargs = yield from _ladder_parameter_rungs(first_err, route, kwargs, max_tokens) if first_err is None: return resp @@ -7099,7 +7425,9 @@ def _call_llm_impl( if task == "moa_aggregator" and isinstance(client, CodexAuxiliaryClient): # Responses-shim clients consume the stream internally and return a completed # object Relay's managed stream would iterate; the MoA facade wraps it as one chunk. - return client.chat.completions.create(**kwargs) + return _dispatch_auxiliary_request(client, kwargs, + lambda request: client.chat.completions.create(**request), + provider=request_provider, model=req.final_model, api_mode=req.resolved_api_mode) return _relay_sync_stream(client, kwargs, provider=request_provider, api_mode=req.resolved_api_mode) def _primary(**validate_kw: Any) -> Any: diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py index 98f4f25677e55..f6a22ebfaaa75 100644 --- a/agent/chat_completion_helpers.py +++ b/agent/chat_completion_helpers.py @@ -630,6 +630,33 @@ def _bedrock_converse_call(api_kwargs: dict, *, stream: bool, on_stream_denied=N return finish(raw_response) +def _attach_source_provenance_sidecar(agent, kwargs: dict, messages: list) -> dict: + """Carry internal read proofs around strict wire-message conversion.""" + + from agent.llm_egress_runtime import provider_uses_egress_firewall + + if not provider_uses_egress_firewall(getattr(agent, "provider", None)): + return kwargs + from agent.source_provenance_tools import build_source_provenance_sidecar + + sidecar = build_source_provenance_sidecar(messages) + if not sidecar: + return kwargs + return {**kwargs, "_hermes_source_provenance": sidecar} + + +def _dispatch_provider_request(agent, request, callback): + """Apply the exact provider-bound egress policy at a physical call site.""" + + from agent.llm_egress_runtime import provider_uses_egress_firewall + + if not provider_uses_egress_firewall(getattr(agent, "provider", None)): + return callback(request) + from agent.llm_egress_runtime import dispatch_authorized_agent_request + + return dispatch_authorized_agent_request(agent, request, callback) + + def _dispatch_nonstreaming_api_request(agent, api_kwargs: dict, *, make_client): """Run one non-streaming LLM request for the active api_mode and return it. @@ -645,7 +672,8 @@ def _dispatch_nonstreaming_api_request(agent, api_kwargs: dict, *, make_client): # Request-local client so the stale/interrupt watchdog aborts sockets # from the stranger thread while the worker owns the SDK close (#67142). request_client = make_client("anthropic_messages_request", kind="anthropic_messages") - return agent._anthropic_messages_create(api_kwargs, client=request_client) + return _dispatch_provider_request(agent, api_kwargs, + lambda request: agent._anthropic_messages_create(request, client=request_client)) if agent.api_mode == "bedrock_converse": return _bedrock_converse_call(api_kwargs, stream=False) if agent.provider == "moa": @@ -658,7 +686,9 @@ def _dispatch_nonstreaming_api_request(agent, api_kwargs: dict, *, make_client): if not callable(getattr(_completions, "prepare", None)): api_kwargs.pop("_moa_prepared_request", None) return agent.client.chat.completions.create(**api_kwargs) - return make_client("chat_completion_request").chat.completions.create(**api_kwargs) + request_client = make_client("chat_completion_request") + return _dispatch_provider_request(agent, api_kwargs, + lambda request: request_client.chat.completions.create(**request)) def should_use_direct_api_call(agent) -> bool: @@ -1532,6 +1562,7 @@ def build_api_kwargs(agent, api_messages: list, tools_for_api: list | None = Non from agent.opencode_affinity import merge_opencode_session_headers kwargs = _build_api_kwargs_for_mode(agent, api_messages, tools_for_api) + kwargs = _attach_source_provenance_sidecar(agent, kwargs, api_messages) return merge_opencode_session_headers( kwargs, getattr(agent, "provider", None), @@ -1764,6 +1795,7 @@ def _fallback_entry_unavailable_without_network(agent, fb: dict) -> Optional[str _FALLBACK_REASON_LABELS = { + FailoverReason.egress_policy_blocked: "local egress policy blocked the request", FailoverReason.auth: "authentication failed", FailoverReason.auth_permanent: "authentication permanently failed", FailoverReason.billing: "billing or quota exhausted", @@ -1790,6 +1822,42 @@ def _fallback_entry_unavailable_without_network(agent, fb: dict) -> Optional[str } +def _fallback_destination_class(fb: dict): + """Resolve a fallback's configured destination for egress-aware routing. + + Egress policy failures must never walk another remote provider with the + same unsafe request. A fallback entry may omit ``base_url`` and rely on + the provider definition in config.yaml, so resolve that URL here rather + than trusting the provider label (provider names are not a security + boundary). + """ + from agent.llm_egress_firewall import classify_destination + + base_url = (fb.get("base_url") or "").strip() + if not base_url: + try: + from hermes_cli.config import load_config + + provider_cfg = (load_config() or {}).get("providers", {}).get( + (fb.get("provider") or "").strip(), {} + ) + if isinstance(provider_cfg, dict): + base_url = str( + provider_cfg.get("api") + or provider_cfg.get("base_url") + or "" + ).strip() + except Exception: + # Unknown destination must remain unknown and therefore cannot + # inherit local trust after an egress policy rejection. + base_url = "" + return classify_destination( + str(fb.get("provider") or ""), + base_url, + fb.get("api_mode") or "chat_completions", + ) + + def _fallback_reason_text(reason: "FailoverReason | None") -> str: """Return a concise operator-facing explanation for a fallback switch.""" label = _FALLBACK_REASON_LABELS.get(reason) @@ -1891,7 +1959,7 @@ def _fallback_chain_exhausted(agent, reason: "FailoverReason | None") -> bool: return False -def _should_skip_fallback_candidate(agent, fb: dict, fb_key: tuple, fb_provider: str, fb_model: str, unavailable: set) -> bool: +def _should_skip_fallback_candidate(agent, fb: dict, fb_key: tuple, fb_provider: str, fb_model: str, unavailable: set, *, reason: "FailoverReason | None" = None) -> bool: """True when the entry is already unavailable, malformed, locally unusable, or resolves to the backend that just failed (falling back to it would loop the failure).""" if fb_key in unavailable: @@ -1899,6 +1967,29 @@ def _should_skip_fallback_candidate(agent, fb: dict, fb_key: tuple, fb_provider: return True if not fb_provider or not fb_model: return True + # An egress policy rejection is deterministic for the current payload. + # Only a local/loopback fallback can legally receive that same payload; + # skip remote and unknown entries without constructing clients or making + # another provider attempt. This preserves the fail-closed firewall while + # preventing the misleading Nous -> OpenAI -> local cascade. + if reason == FailoverReason.egress_policy_blocked: + from agent.llm_egress_firewall import DestinationClass + + destination = _fallback_destination_class(fb) + if destination not in { + DestinationClass.LOCAL_PROCESS, + DestinationClass.LOOPBACK, + }: + unavailable.add(fb_key) + logger.info( + "Fallback skip: %s/%s is not local after egress policy " + "blocked the current request (destination=%s)", + fb_provider, + fb_model, + destination.value, + ) + return True + local_skip_reason = _fallback_entry_unavailable_without_network(agent, fb) if local_skip_reason: unavailable.add(fb_key) @@ -2032,7 +2123,7 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool unavailable = agent._unavailable_fallback_keys fb_provider = (fb.get("provider") or "").strip().lower() fb_model = (fb.get("model") or "").strip() - if _should_skip_fallback_candidate(agent, fb, fb_key, fb_provider, fb_model, unavailable): + if _should_skip_fallback_candidate(agent, fb, fb_key, fb_provider, fb_model, unavailable, reason=reason): return agent._try_activate_fallback(reason) try: @@ -2177,13 +2268,19 @@ def _iteration_summary_api_messages(agent, messages: list) -> list: def _managed_summary_call(agent, api_request_id: str, request, callback, *, retry_count: int): from agent import relay_llm - return relay_llm.execute_current( - request, callback, - name=str(getattr(agent, "provider", "") or "provider"), model_name=str(getattr(agent, "model", "") or ""), - metadata={"api_mode": str(getattr(agent, "api_mode", "") or "chat_completions"), - "api_request_id": api_request_id, "call_role": "iteration_summary", "retry_count": retry_count}, - defer_logical_completion=True, - ) + + previous_request_id = getattr(agent, "_current_api_request_id", "") + agent._current_api_request_id = api_request_id + try: + return relay_llm.execute_current( + request, lambda payload: _dispatch_provider_request(agent, payload, callback), + name=str(getattr(agent, "provider", "") or "provider"), model_name=str(getattr(agent, "model", "") or ""), + metadata={"api_mode": str(getattr(agent, "api_mode", "") or "chat_completions"), + "api_request_id": api_request_id, "call_role": "iteration_summary", "retry_count": retry_count}, + defer_logical_completion=True, + ) + finally: + agent._current_api_request_id = previous_request_id def _iteration_summary_chat_kwargs(agent, api_messages: list) -> dict: @@ -2871,7 +2968,8 @@ def _open_chat_stream(self, stream_kwargs: dict[str, Any]): self.agent._create_request_openai_client(reason="chat_completion_stream_request", api_kwargs=stream_kwargs)) self.last_chunk_time["t"] = time.time() self.agent._touch_activity("waiting for provider response (streaming)") - return request_client.chat.completions.create(**stream_kwargs) + return _dispatch_provider_request(self.agent, stream_kwargs, + lambda request: request_client.chat.completions.create(**request)) def _chat_stream_created(self, raw_stream: Any) -> None: response = self._attempt_stream_response = getattr(raw_stream, "response", None) @@ -3152,7 +3250,8 @@ def _call_anthropic(self, request_client): def _open_anthropic_stream(next_api_kwargs: dict[str, Any]): final_kwargs = dict(next_api_kwargs) sanitize_anthropic_kwargs(final_kwargs, log_prefix=getattr(self.agent, "log_prefix", "")) - manager = request_client.messages.stream(**final_kwargs) + manager = _dispatch_provider_request(self.agent, final_kwargs, + lambda request: request_client.messages.stream(**request)) _stream_context["manager"] = manager return manager.__enter__() diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py index e5b282045855e..ba4c527128e45 100644 --- a/agent/codex_runtime.py +++ b/agent/codex_runtime.py @@ -1,6 +1,18 @@ -"""Codex API runtime — App Server and Responses-API streaming paths. Every entry point takes the parent -AIAgent first: ``run_codex_app_server_turn`` drives one ``codex app-server`` subprocess turn; -``run_codex_stream`` runs one streaming Codex Responses call.""" +"""Codex API runtime — App Server and Responses-API streaming paths. + +Extracted from :class:`AIAgent` to keep the agent loop file focused. +Each function takes the parent ``AIAgent`` as its first argument +(``agent``). AIAgent keeps thin forwarder methods for backward +compatibility. + +* ``run_codex_app_server_turn`` — drives one turn through the + ``codex_app_server`` subprocess client (used when a Codex CLI install + is the active provider). +* ``run_codex_stream`` — streams a Codex Responses API call (the + ``codex_responses`` api_mode). +* ``run_codex_create_stream_fallback`` — recovery path when the + Responses ``stream=True`` initial create fails. +""" from __future__ import annotations @@ -8,7 +20,6 @@ import logging import os import time -from contextlib import suppress from types import SimpleNamespace from typing import Any, Callable, Dict, List @@ -17,39 +28,65 @@ logger = logging.getLogger(__name__) -def _call_guarded(fn: Callable | None, fail_msg: str, *fail_args: Any, args: tuple = (), kwargs: dict | None = None): - """Invoke an optional display/debug callback; a buggy hook must never tear down the turn.""" - if fn is None: - return - try: - fn(*args, **(kwargs or {})) - except Exception: - logger.debug(fail_msg, *fail_args, exc_info=True) - - def _codex_request_failure_details(error: BaseException) -> tuple[int | None, str]: - """(serialized request bytes, exception class chain); the buffered ``httpx.Request`` content - on OpenAI connection errors gives the exact byte count without logging payloads or URLs.""" + """Return the serialized request size and exception class chain. + + OpenAI connection exceptions retain the final ``httpx.Request``. Reading + its already-buffered content gives us the exact byte count handed to the + transport without logging any request content. The class-only chain keeps + the underlying transport failure visible without exposing URLs or payloads + from exception messages. + """ request_body_bytes: int | None = None exception_classes: list[str] = [] current: BaseException | None = error seen: set[int] = set() + while current is not None and id(current) not in seen and len(seen) < 8: seen.add(id(current)) exception_classes.append(type(current).__name__) + if request_body_bytes is None: - content = None - with suppress(Exception): - content = getattr(getattr(current, "request", None), "content", None) - if isinstance(content, str): - request_body_bytes = len(content.encode("utf-8")) - elif isinstance(content, (bytes, bytearray, memoryview)): - request_body_bytes = len(content) - implicit_chain = current.__cause__ is None and not current.__suppress_context__ - current = current.__context__ if implicit_chain else current.__cause__ + try: + request = getattr(current, "request", None) + except Exception: + request = None + if request is not None: + try: + content = request.content + except Exception: + content = None + if isinstance(content, str): + request_body_bytes = len(content.encode("utf-8")) + elif isinstance(content, (bytes, bytearray, memoryview)): + request_body_bytes = len(content) + + cause = current.__cause__ + if cause is None and not current.__suppress_context__: + cause = current.__context__ + current = cause + return request_body_bytes, " <- ".join(exception_classes) +def _log_codex_request_failure( + agent: Any, + error: BaseException, + *, + stream_opened: bool, +) -> None: + request_body_bytes, exception_chain = _codex_request_failure_details(error) + logger.warning( + "Codex Responses request failed: " + "serialized_request_body_bytes=%s stream_opened=%s " + "exception_chain=%s model=%s", + request_body_bytes if request_body_bytes is not None else "unknown", + str(stream_opened).lower(), + exception_chain, + getattr(agent, "model", "unknown"), + ) + + def _coerce_usage_int(value: Any) -> int: if isinstance(value, bool): return 0 @@ -58,53 +95,93 @@ def _coerce_usage_int(value: Any) -> int: if isinstance(value, float): return max(int(value), 0) if isinstance(value, str): - # Only the str->int parse is guarded; a float NaN still raises like it always has. - with suppress(ValueError): + try: return max(int(value), 0) + except ValueError: + return 0 return 0 -def _queue_token_counts(agent, fail_msg: str, *fail_extra: Any, counts: Callable[[], dict]) -> None: - """Enqueue per-call accounting for the SessionDB background writer. ``counts`` is built - lazily inside the guarded try so a stub agent without a session DB is never touched.""" - if not (agent._session_db and agent.session_id): - return - try: - if not agent._session_db_created: - agent._ensure_db_session() - agent._session_db.queue_token_counts(agent.session_id, **counts()) - except Exception as exc: - logger.debug(fail_msg, agent.session_id, *fail_extra, exc) +def _record_codex_app_server_usage(agent, turn) -> dict[str, Any]: + """Translate Codex app-server token usage into Hermes accounting. + Codex app-server reports usage via thread/tokenUsage/updated as: + inputTokens, cachedInputTokens, outputTokens, reasoningOutputTokens, + totalTokens. -def _record_codex_app_server_usage(agent, turn) -> dict[str, Any]: - """Translate Codex app-server token usage into Hermes accounting. Prompt bucket = uncached + cached - input (the protocol exposes no cache-write tokens); a turn with no usage still counts as one API call.""" + Hermes' canonical prompt bucket includes uncached input + cached input. + The Codex app-server protocol does not currently expose cache-write tokens, + so that bucket remains zero on this runtime. + + Even when Codex omits usage for a turn, Hermes should still count that turn + as one API call for session/status accounting. + """ agent.session_api_calls += 1 - usage = getattr(turn, "token_usage_last", None) - compressor = getattr(agent, "context_compressor", None) - def billing(**extra): - return dict(model=agent.model, billing_provider=agent.provider, billing_base_url=agent.base_url, api_call_count=1, **extra) + usage = getattr(turn, "token_usage_last", None) if not isinstance(usage, dict) or not usage: - if compressor is not None and getattr(compressor, "awaiting_real_usage_after_compression", False): - # No usage cannot adjudicate the pending compaction; unlatch preflight deferral. + compressor = getattr(agent, "context_compressor", None) + if ( + compressor is not None + and getattr(compressor, "awaiting_real_usage_after_compression", False) + ): + # No usage means this turn cannot adjudicate the pending compaction. + # Consume the marker so a later unrelated reading is not charged to + # it and preflight deferral cannot stay latched indefinitely. compressor.update_from_response({}) - _queue_token_counts(agent, "Codex app-server api-call persistence failed (session=%s): %s", - counts=lambda: billing(billing_mode="subscription_included")) + if agent._session_db and agent.session_id: + try: + if not agent._session_db_created: + agent._ensure_db_session() + # Enqueued for the SessionDB background writer — keeps the + # per-call accounting write off the turn thread (see + # conversation_loop's queue_token_counts call). + agent._session_db.queue_token_counts( + agent.session_id, + model=agent.model, + billing_provider=agent.provider, + billing_base_url=agent.base_url, + billing_mode="subscription_included", + api_call_count=1, + ) + except Exception as exc: + logger.debug( + "Codex app-server api-call persistence failed (session=%s): %s", + agent.session_id, exc, + ) return {} + from agent.usage_pricing import CanonicalUsage, estimate_usage_cost + + input_tokens = _coerce_usage_int(usage.get("inputTokens")) + cache_read_tokens = _coerce_usage_int(usage.get("cachedInputTokens")) + output_tokens = _coerce_usage_int(usage.get("outputTokens")) + reasoning_tokens = _coerce_usage_int(usage.get("reasoningOutputTokens")) + reported_total = _coerce_usage_int(usage.get("totalTokens")) + canonical_usage = CanonicalUsage( - input_tokens=_coerce_usage_int(usage.get("inputTokens")), output_tokens=_coerce_usage_int(usage.get("outputTokens")), - cache_read_tokens=_coerce_usage_int(usage.get("cachedInputTokens")), cache_write_tokens=0, - reasoning_tokens=_coerce_usage_int(usage.get("reasoningOutputTokens")), raw_usage=usage, + input_tokens=input_tokens, + output_tokens=output_tokens, + cache_read_tokens=cache_read_tokens, + cache_write_tokens=0, + reasoning_tokens=reasoning_tokens, + raw_usage=usage, ) prompt_tokens = canonical_usage.prompt_tokens - total_tokens = _coerce_usage_int(usage.get("totalTokens")) or canonical_usage.total_tokens - token_counts = {f: getattr(canonical_usage, f) for f in - ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens")} - usage_dict = {"prompt_tokens": prompt_tokens, "completion_tokens": canonical_usage.output_tokens, - "total_tokens": total_tokens, **token_counts} + completion_tokens = canonical_usage.output_tokens + total_tokens = reported_total or canonical_usage.total_tokens + usage_dict = { + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens, + "total_tokens": total_tokens, + "input_tokens": canonical_usage.input_tokens, + "output_tokens": canonical_usage.output_tokens, + "cache_read_tokens": canonical_usage.cache_read_tokens, + "cache_write_tokens": canonical_usage.cache_write_tokens, + "reasoning_tokens": canonical_usage.reasoning_tokens, + } + + compressor = getattr(agent, "context_compressor", None) if compressor is not None: try: compressor.update_from_response(usage_dict) @@ -113,868 +190,1654 @@ def billing(**extra): compressor.context_length = context_window except Exception: logger.debug("codex app-server usage update failed", exc_info=True) - for key, value in usage_dict.items(): - setattr(agent, f"session_{key}", getattr(agent, f"session_{key}") + value) + + agent.session_prompt_tokens += prompt_tokens + agent.session_completion_tokens += completion_tokens + agent.session_total_tokens += total_tokens + agent.session_input_tokens += canonical_usage.input_tokens + agent.session_output_tokens += canonical_usage.output_tokens + agent.session_cache_read_tokens += canonical_usage.cache_read_tokens + agent.session_cache_write_tokens += canonical_usage.cache_write_tokens + agent.session_reasoning_tokens += canonical_usage.reasoning_tokens + cost_result = estimate_usage_cost( - agent.model, canonical_usage, provider=agent.provider, base_url=agent.base_url, api_key=getattr(agent, "api_key", ""), - ) - cost_usd = float(cost_result.amount_usd) if cost_result.amount_usd is not None else None - if cost_usd is not None: - agent.session_estimated_cost_usd += cost_usd - agent.session_cost_status, agent.session_cost_source = cost_result.status, cost_result.source - cost_fields = {"estimated_cost_usd": cost_usd, "cost_status": cost_result.status, "cost_source": cost_result.source} - _queue_token_counts( - agent, "Codex app-server token persistence failed (session=%s, tokens=%d): %s", total_tokens, - counts=lambda: billing(**token_counts, **cost_fields, - billing_mode="subscription_included" if cost_result.status == "included" else None), + agent.model, + canonical_usage, + provider=agent.provider, + base_url=agent.base_url, + api_key=getattr(agent, "api_key", ""), ) - return {**usage_dict, "last_prompt_tokens": prompt_tokens, **cost_fields} + if cost_result.amount_usd is not None: + agent.session_estimated_cost_usd += float(cost_result.amount_usd) + agent.session_cost_status = cost_result.status + agent.session_cost_source = cost_result.source + if agent._session_db and agent.session_id: + try: + if not agent._session_db_created: + agent._ensure_db_session() + # Enqueued for the SessionDB background writer (see above). + agent._session_db.queue_token_counts( + agent.session_id, + input_tokens=canonical_usage.input_tokens, + output_tokens=canonical_usage.output_tokens, + cache_read_tokens=canonical_usage.cache_read_tokens, + cache_write_tokens=canonical_usage.cache_write_tokens, + reasoning_tokens=canonical_usage.reasoning_tokens, + estimated_cost_usd=float(cost_result.amount_usd) + if cost_result.amount_usd is not None else None, + cost_status=cost_result.status, + cost_source=cost_result.source, + billing_provider=agent.provider, + billing_base_url=agent.base_url, + billing_mode="subscription_included" + if cost_result.status == "included" else None, + model=agent.model, + api_call_count=1, + ) + except Exception as exc: + logger.debug( + "Codex app-server token persistence failed (session=%s, tokens=%d): %s", + agent.session_id, total_tokens, exc, + ) -def _record_codex_app_server_compaction(agent, turn, *, approx_tokens: int | None = None, force: bool = False) -> bool: - """Record a Codex-native compaction boundary: the app-server owns the compacted thread, - so local transcript rows are NOT rewritten — only session event/usage counters.""" + return { + **usage_dict, + "last_prompt_tokens": prompt_tokens, + "estimated_cost_usd": float(cost_result.amount_usd) + if cost_result.amount_usd is not None else None, + "cost_status": cost_result.status, + "cost_source": cost_result.source, + } + + +def _record_codex_app_server_compaction( + agent, + turn, + *, + approx_tokens: int | None = None, + force: bool = False, +) -> bool: + """Record a Codex-native context compaction boundary in Hermes state. + + The app-server owns the compacted thread context, so Hermes should not + rewrite local transcript rows here; state.db records the boundary via the + session event/usage counters while preserving the visible transcript. + """ if not force and not getattr(turn, "compacted", False): return False - thread_id, turn_id = getattr(turn, "thread_id", None) or "", getattr(turn, "turn_id", None) or "" - logger.info("codex app-server compaction observed: session=%s thread=%s turn=%s force=%s", - getattr(agent, "session_id", None) or "none", thread_id, turn_id, force) + + thread_id = getattr(turn, "thread_id", None) or "" + turn_id = getattr(turn, "turn_id", None) or "" + logger.info( + "codex app-server compaction observed: session=%s thread=%s turn=%s force=%s", + getattr(agent, "session_id", None) or "none", + thread_id, + turn_id, + force, + ) if not force: - with suppress(Exception): + try: from agent.conversation_compression import COMPACTION_STATUS + agent._emit_status(COMPACTION_STATUS) + except Exception: + pass + compressor = getattr(agent, "context_compressor", None) if compressor is not None: - compressor.compression_count = getattr(compressor, "compression_count", 0) + 1 + compressor.compression_count = getattr( + compressor, "compression_count", 0 + ) + 1 compressor.last_compression_rough_tokens = approx_tokens or 0 - # Codex owns this summary: a prior Hermes deterministic-fallback flag must not leak into it. - record_boundary = getattr(type(compressor), "record_completed_compaction", None) + # The app server has already completed a real compaction boundary. Its + # usage update (when supplied) is therefore the same real-vs-real + # effectiveness verdict used by the normal compression path. + record_boundary = getattr( + type(compressor), "record_completed_compaction", None + ) if callable(record_boundary): + # Codex owns this summary. A prior Hermes deterministic-fallback + # flag must not leak into the native boundary's quality verdict. record_boundary(compressor, used_fallback=False) elif hasattr(compressor, "_verify_compaction_cleared_threshold"): compressor._verify_compaction_cleared_threshold = True if not getattr(turn, "token_usage_last", None): - compressor.last_prompt_tokens, compressor.last_completion_tokens = -1, 0 + compressor.last_prompt_tokens = -1 + compressor.last_completion_tokens = 0 compressor.awaiting_real_usage_after_compression = True - # Provider-side context was rewritten; the usage anchor's transcript snapshot no longer matches. - agent._usage_anchor = None - agent._turn_base_usage_anchor = None + agent._last_compaction_in_place = False - _call_guarded(getattr(agent, "event_callback", None) or None, "event_callback error on codex session:compress", - args=("session:compress", { - "platform": getattr(agent, "platform", None) or "", "session_id": getattr(agent, "session_id", None) or "", - "old_session_id": "", "in_place": False, - "compression_count": getattr(compressor, "compression_count", 0) if compressor is not None else 0, - "runtime": "codex_app_server", "thread_id": thread_id, "turn_id": turn_id, - })) - return True + try: + if getattr(agent, "event_callback", None): + agent.event_callback( + "session:compress", + { + "platform": getattr(agent, "platform", None) or "", + "session_id": getattr(agent, "session_id", None) or "", + "old_session_id": "", + "in_place": False, + "compression_count": getattr( + compressor, "compression_count", 0 + ) + if compressor is not None + else 0, + "runtime": "codex_app_server", + "thread_id": thread_id, + "turn_id": turn_id, + }, + ) + except Exception: + logger.debug("event_callback error on codex session:compress", exc_info=True) + return True -# --- Codex app-server → Hermes UI bridge ------------------------------------- -# The app-server bypasses the Hermes tool loop, so the bridge translates JSON-RPC notifications -# into the callbacks the standard runtime fires (tool_progress_callback, _fire_stream_delta, ...). -# Item types that project to a Hermes tool_call (keep in sync with agent/transports/codex_event_projector.py -# so UI names match recorded names). webSearch is codex's built-in tool: no projector entry, still gets a bubble. -_CODEX_TOOL_ITEM_TYPES = frozenset({"commandExecution", "fileChange", "mcpToolCall", "dynamicToolCall", "webSearch"}) -# Internal MCP server wrapping Hermes' native tools: its inner dispatch has no tool_progress_callback, so the -# codex-level mcpToolCall IS the display event and the mcp.hermes-tools.* prefix is stripped (users see Hermes tools). +# --------------------------------------------------------------------------- +# Codex app-server → Hermes UI bridge (#33200) +# +# The codex_app_server runtime hands the entire turn to a subprocess and +# bypasses the normal Hermes tool loop. Without this bridge gateway +# adapters (Discord, Telegram, TUI) never see live tool-progress bubbles +# or interim assistant commentary while codex is working — the user just +# stares at a quiet channel until the final answer lands. The bridge +# translates raw codex JSON-RPC notifications into the same three agent +# callbacks the standard runtime fires: +# - tool_progress_callback("tool.started"|"tool.completed", name, ...) +# - _fire_stream_delta(text) for streaming agentMessage chunks +# - _emit_interim_assistant_message({...}) for completed agentMessages +# --------------------------------------------------------------------------- + +# Codex item types that map to a Hermes tool_call in the projector (and +# therefore deserve a tool_progress bubble pair). The projector lives in +# agent/transports/codex_event_projector.py — keep these in sync so the +# tool name shown in the UI matches the name recorded in messages. +# webSearch is codex's built-in web search tool — it has no projector +# entry (codex handles it internally) but still deserves a bubble. +_CODEX_TOOL_ITEM_TYPES = frozenset( + {"commandExecution", "fileChange", "mcpToolCall", "dynamicToolCall", "webSearch"} +) + +# Internal MCP server that wraps Hermes' native tools for codex. When +# codex calls back through it, the inner dispatch runs in a SEPARATE +# hermes-tools-mcp-server subprocess that has no access to the parent +# agent's tool_progress_callback — so the inner call can never surface +# its own native progress event. The codex-level mcpToolCall event IS +# the display event for those calls; we strip the mcp.hermes-tools.* +# namespacing and emit the bare tool name (web_search, browser_navigate, +# vision_analyze, ...) since the user thinks of these as Hermes tools, +# not as MCP calls. _INTERNAL_MCP_SERVER = "hermes-tools" -_STATIC_TOOL_NAMES = {"commandExecution": "exec_command", "fileChange": "apply_patch", "webSearch": "web_search"} -_STABLE_ID_PREFIXES = {"commandExecution": "exec", "fileChange": "apply_patch"} -_MCP_LIKE_ITEM_TYPES = {"mcpToolCall", "dynamicToolCall"} -# Item types whose preview is the first 120 chars of one string field. -_PREVIEW_FIELDS = {"commandExecution": "command", "webSearch": "query"} - - -def _item_changes(item: dict) -> list[dict]: - return [c for c in (item.get("changes") or []) if isinstance(c, dict)] def _codex_item_to_tool_name(item: dict) -> str: - """Synthetic Hermes tool name for a codex item (mirrors CodexEventProjector).""" + """Synthetic Hermes tool name for a codex item. Mirrors + CodexEventProjector so the progress bubble and the projected + tool_calls entry use the same identifier.""" item_type = item.get("type") or "" + if item_type == "commandExecution": + return "exec_command" + if item_type == "fileChange": + return "apply_patch" if item_type == "mcpToolCall": - server, tool = item.get("server") or "mcp", item.get("tool") or "unknown" - return tool if server == _INTERNAL_MCP_SERVER else f"mcp.{server}.{tool}" + server = item.get("server") or "mcp" + tool = item.get("tool") or "unknown" + if server == _INTERNAL_MCP_SERVER: + return tool + return f"mcp.{server}.{tool}" if item_type == "dynamicToolCall": return item.get("tool") or "dynamic" - return _STATIC_TOOL_NAMES.get(item_type) or item_type or "unknown" + if item_type == "webSearch": + return "web_search" + return item_type or "unknown" def _codex_item_to_args(item: dict) -> dict: - """Args dict for tool_progress_callback("tool.started"); mirrors the projector shapes.""" + """Args dict surfaced to tool_progress_callback("tool.started", ...). + Mirrors the projector's _project_command / _project_file_change / + _project_mcp_tool_call / _project_dynamic_tool_call shapes.""" item_type = item.get("type") or "" if item_type == "commandExecution": - return {"command": item.get("command") or "", "cwd": item.get("cwd") or ""} + return {"command": item.get("command") or "", + "cwd": item.get("cwd") or ""} if item_type == "fileChange": - return {"changes": [{"kind": (c.get("kind") or {}).get("type") or "update", "path": c.get("path") or ""} - for c in _item_changes(item)]} - if item_type in _MCP_LIKE_ITEM_TYPES: + return {"changes": [ + {"kind": (c.get("kind") or {}).get("type") or "update", + "path": c.get("path") or ""} + for c in (item.get("changes") or []) if isinstance(c, dict) + ]} + if item_type in {"mcpToolCall", "dynamicToolCall"}: args = item.get("arguments") or {} return args if isinstance(args, dict) else {"arguments": args} - return {"query": item.get("query") or ""} if item_type == "webSearch" else {} + if item_type == "webSearch": + return {"query": item.get("query") or ""} + return {} def _codex_item_to_preview(item: dict) -> Any: - """Short preview for the tool.started bubble; None when nothing useful (UI tolerates None).""" + """Short human-readable preview for the tool.started bubble. Returns + None when no useful preview is available (Hermes' UI tolerates None).""" item_type = item.get("type") or "" - if item_type in _PREVIEW_FIELDS: - return (item.get(_PREVIEW_FIELDS[item_type]) or "")[:120] or None + if item_type == "commandExecution": + cmd = item.get("command") or "" + return cmd[:120] if cmd else None if item_type == "fileChange": - paths = [c.get("path") for c in _item_changes(item) if c.get("path")] - return (", ".join(paths[:3]) + (f", +{len(paths) - 3} more" if len(paths) > 3 else "")) if paths else None - if item_type in _MCP_LIKE_ITEM_TYPES: + paths = [c.get("path") for c in (item.get("changes") or []) + if isinstance(c, dict) and c.get("path")] + if not paths: + return None + preview = ", ".join(paths[:3]) + if len(paths) > 3: + preview += f", +{len(paths) - 3} more" + return preview + if item_type in {"mcpToolCall", "dynamicToolCall"}: args = item.get("arguments") or {} - if isinstance(args, dict) and args: - with suppress(TypeError, ValueError): - return json.dumps(args, ensure_ascii=False)[:120] + if not isinstance(args, dict) or not args: + return None + try: + return json.dumps(args, ensure_ascii=False)[:120] + except (TypeError, ValueError): + return None + if item_type == "webSearch": + query = item.get("query") or "" + return query[:120] if query else None return None def _codex_item_completion_payload(item: dict) -> tuple[str, bool]: - """(result_text, is_error) for a completed tool item; mirrors the projector's tool-result content.""" + """Return (result_text, is_error) for a completed codex tool item. + Mirrors the projector's tool-result content so the bubble shows the + same outcome string that ends up in the messages list.""" item_type = item.get("type") or "" if item_type == "commandExecution": - out, exit_code = item.get("aggregatedOutput") or "", item.get("exitCode") + out = item.get("aggregatedOutput") or "" + exit_code = item.get("exitCode") is_error = bool(exit_code is not None and exit_code != 0) - return (f"[exit {exit_code}]\n{out}" if is_error else out), is_error + if is_error: + out = f"[exit {exit_code}]\n{out}" + return out, is_error if item_type == "fileChange": status = item.get("status") or "unknown" n = len(item.get("changes") or []) - return f"apply_patch status={status}, {n} change(s)", status not in {"completed", "applied", "success"} + return ( + f"apply_patch status={status}, {n} change(s)", + status not in {"completed", "applied", "success"}, + ) if item_type == "mcpToolCall": - if error := item.get("error"): - return f"[error] {json.dumps(error, ensure_ascii=False)[:1000]}", True + error = item.get("error") + if error: + return ( + f"[error] {json.dumps(error, ensure_ascii=False)[:1000]}", + True, + ) result = item.get("result") - return (json.dumps(result, ensure_ascii=False)[:4000] if result is not None else ""), False + return ( + json.dumps(result, ensure_ascii=False)[:4000] + if result is not None else "", + False, + ) if item_type == "dynamicToolCall": - content_items, success = item.get("contentItems") or [], item.get("success", True) - has_items = isinstance(content_items, list) and content_items - return (json.dumps(content_items, ensure_ascii=False)[:4000] if has_items else f"success={success}"), not bool(success) + content_items = item.get("contentItems") or [] + if isinstance(content_items, list) and content_items: + return ( + json.dumps(content_items, ensure_ascii=False)[:4000], + not bool(item.get("success", True)), + ) + success = item.get("success", True) + return f"success={success}", not bool(success) return "", False -def _stable_call_id(item: dict, name: str) -> str: - """Deterministic tool_call id mirroring CodexEventProjector (live TUI card correlates with projected history).""" - from agent.transports.codex_event_projector import _deterministic_call_id - item_type = item.get("type") or "" - tool = item.get("tool") or "unknown" - prefix = {"mcpToolCall": f"mcp__{item.get('server') or 'mcp'}__{tool}", "dynamicToolCall": f"dyn_{tool}"}.get(item_type) - return _deterministic_call_id(prefix or _STABLE_ID_PREFIXES.get(item_type, name), item.get("id") or "") - - def make_codex_app_server_event_bridge(agent) -> Callable[[dict], None]: - """Build the ``on_event`` callback for ``CodexAppServerSession(on_event=...)``. - - Tool items fire ``tool_progress_callback`` plus the stable-ID ``tool_start_callback`` / - ``tool_complete_callback`` card hooks; deltas go to ``_fire_stream_delta`` / ``_fire_reasoning_delta``; - a completed agentMessage goes to ``_emit_interim_assistant_message`` (the gateway's ``already_streamed`` - check dedupes against streamed deltas). Every callback is guarded so a buggy display hook cannot - tear down the turn loop.""" - # item_id -> (tool_name, args, started_monotonic); duration even when codex omits durationMs. + """Build an ``on_event`` callback that wires codex app-server JSON-RPC + notifications into Hermes' gateway UI callbacks. + + Returns a single-argument callable suitable for + ``CodexAppServerSession(on_event=...)``. + + Translation map: + * ``item/started`` for tool-shaped items → ``tool_progress_callback( + "tool.started", name, preview, args)`` + * ``item/completed`` for tool-shaped items → ``tool_progress_callback( + "tool.completed", name, None, None, duration=..., is_error=..., + result=...)`` + * ``item/agentMessage/delta`` → ``_fire_stream_delta(text)`` so chat + adapters can render the assistant's reply as it streams. + * ``item/reasoning/delta`` → ``_fire_reasoning_delta(text)`` + * ``item/completed`` for ``agentMessage`` → + ``_emit_interim_assistant_message({"role": "assistant", + "content": text})``. The gateway's ``already_streamed`` check + dedupes against any text the stream-delta callback already + rendered for the same message. + + All callback invocations are guarded — a buggy display callback must + not tear down the codex turn loop. Errors are logged at DEBUG so the + notification stream keeps flowing regardless. + """ + # item_id -> (tool_name, args, started_wall_time). Populated on + # item/started and consumed on item/completed so duration is correct + # even when codex doesn't report durationMs. started: dict[str, tuple[str, dict, float]] = {} - def agent_cb(attr: str, fail_msg: str, *fail_args: Any, args: tuple = (), kwargs: dict | None = None) -> None: - _call_guarded(getattr(agent, attr, None), fail_msg, *fail_args, args=args, kwargs=kwargs) + def _stable_call_id(item: dict, name: str) -> str: + """Deterministic tool_call id mirroring CodexEventProjector, so a + live TUI tool card correlates with the same tool call after the + session is resumed and history is projected.""" + from agent.transports.codex_event_projector import _deterministic_call_id + + item_id = item.get("id") or "" + item_type = item.get("type") or "" + if item_type == "commandExecution": + return _deterministic_call_id("exec", item_id) + if item_type == "fileChange": + return _deterministic_call_id("apply_patch", item_id) + if item_type == "mcpToolCall": + server = item.get("server") or "mcp" + tool = item.get("tool") or "unknown" + return _deterministic_call_id(f"mcp__{server}__{tool}", item_id) + if item_type == "dynamicToolCall": + tool = item.get("tool") or "unknown" + return _deterministic_call_id(f"dyn_{tool}", item_id) + return _deterministic_call_id(name, item_id) def _fire_tool_started(item: dict) -> None: - item_id, name = item.get("id") or "", _codex_item_to_tool_name(item) + item_id = item.get("id") or "" + name = _codex_item_to_tool_name(item) args = _codex_item_to_args(item) if item_id: started[item_id] = (name, args, time.monotonic()) - agent_cb("tool_progress_callback", "tool_progress_callback raised on tool.started for %s", name, - args=("tool.started", name, _codex_item_to_preview(item), args)) - # Stable-ID tool card (TUI/desktop) fires alongside the progress bubble. - agent_cb("tool_start_callback", "tool_start_callback raised for %s", name, - args=(_stable_call_id(item, name), name, args)) + cb = getattr(agent, "tool_progress_callback", None) + if cb is not None: + try: + cb("tool.started", name, _codex_item_to_preview(item), args) + except Exception: + logger.debug( + "tool_progress_callback raised on tool.started for %s", + name, exc_info=True, + ) + # Authoritative stable-ID tool card (TUI / desktop). Fires + # alongside tool_progress so surfaces that render structured tool + # cards (not just progress bubbles) stay correlated with the + # projected history entry after a resume. + start_cb = getattr(agent, "tool_start_callback", None) + if start_cb is not None: + try: + start_cb(_stable_call_id(item, name), name, args) + except Exception: + logger.debug( + "tool_start_callback raised for %s", name, exc_info=True, + ) def _fire_tool_completed(item: dict) -> None: + item_id = item.get("id") or "" name = _codex_item_to_tool_name(item) - prior = started.pop(item_id, None) if (item_id := item.get("id") or "") else None - # Prefer codex's durationMs; else our started timestamp; else None (some codex + prior = started.pop(item_id, None) + # Prefer codex's own durationMs when present so the bubble shows + # exact tool wall-time; fall back to our started timestamp; fall + # back to None if we never saw an item/started (some codex # versions only emit completed for fast items). + duration: Any = None codex_ms = item.get("durationMs") - has_codex_ms = isinstance(codex_ms, (int, float)) and codex_ms >= 0 - duration: Any = codex_ms / 1000.0 if has_codex_ms else (time.monotonic() - prior[2] if prior else None) + if isinstance(codex_ms, (int, float)) and codex_ms >= 0: + duration = codex_ms / 1000.0 + elif prior is not None: + duration = time.monotonic() - prior[2] result, is_error = _codex_item_completion_payload(item) - agent_cb("tool_progress_callback", "tool_progress_callback raised on tool.completed for %s", name, - args=("tool.completed", name, None, None), - kwargs={"duration": duration, "is_error": is_error, "result": result}) - args = prior[1] if prior is not None else _codex_item_to_args(item) - agent_cb("tool_complete_callback", "tool_complete_callback raised for %s", name, - args=(_stable_call_id(item, name), name, args, result)) - - def _fire_delta(params: dict, attr: str) -> None: + cb = getattr(agent, "tool_progress_callback", None) + if cb is not None: + try: + cb("tool.completed", name, None, None, + duration=duration, is_error=is_error, result=result) + except Exception: + logger.debug( + "tool_progress_callback raised on tool.completed for %s", + name, exc_info=True, + ) + complete_cb = getattr(agent, "tool_complete_callback", None) + if complete_cb is not None: + args = prior[1] if prior is not None else _codex_item_to_args(item) + try: + complete_cb(_stable_call_id(item, name), name, args, result) + except Exception: + logger.debug( + "tool_complete_callback raised for %s", name, exc_info=True, + ) + + def _fire_text_delta(params: dict) -> None: text = params.get("delta") or params.get("text") or "" - # Single-writer guard (#65991): a superseded stream must not pollute the turn's accumulated text - # (which also feeds the interim-visible-text de-dup comparison), even when a caller reaches this - # directly (the tool-suppressed content path) rather than through _fire_stream_delta. - if isinstance(text, str) and text: - agent_cb(attr, f"{attr} raised", args=(text,)) + if not isinstance(text, str) or not text: + return + fn = getattr(agent, "_fire_stream_delta", None) + if fn is None: + return + try: + fn(text) + except Exception: + logger.debug("_fire_stream_delta raised", exc_info=True) + + def _fire_reasoning_delta(params: dict) -> None: + text = params.get("delta") or params.get("text") or "" + if not isinstance(text, str) or not text: + return + fn = getattr(agent, "_fire_reasoning_delta", None) + if fn is None: + return + try: + fn(text) + except Exception: + logger.debug("_fire_reasoning_delta raised", exc_info=True) def _fire_agent_message_completed(item: dict) -> None: text = item.get("text") or "" - # display.show_commentary=false keeps mid-turn narration off the interim path too (codex_responses contract). - if isinstance(text, str) and text.strip() and getattr(agent, "show_commentary", True): - agent_cb("_emit_interim_assistant_message", "_emit_interim_assistant_message raised", - args=({"role": "assistant", "content": text},)) + if not isinstance(text, str) or not text.strip(): + return + # display.show_commentary=false — mid-turn narration stays off the + # visible interim path on this runtime too (same contract as the + # codex_responses commentary channel). + if not getattr(agent, "show_commentary", True): + return + emit = getattr(agent, "_emit_interim_assistant_message", None) + if emit is None: + return + try: + emit({"role": "assistant", "content": text}) + except Exception: + logger.debug( + "_emit_interim_assistant_message raised", exc_info=True, + ) - def _on_item(params: dict, completed: bool) -> None: + def on_event(note: dict) -> None: + if not isinstance(note, dict): + return + method = note.get("method") or "" + params = note.get("params") or {} + if not isinstance(params, dict): + params = {} + if method == "item/agentMessage/delta": + _fire_text_delta(params) + return + if method in {"item/reasoning/delta", "item/reasoning/summaryDelta"}: + _fire_reasoning_delta(params) + return item = params.get("item") if not isinstance(item, dict): return item_type = item.get("type") or "" - if item_type in _CODEX_TOOL_ITEM_TYPES: - (_fire_tool_completed if completed else _fire_tool_started)(item) - elif completed and item_type == "agentMessage": - _fire_agent_message_completed(item) - handlers: dict[str, Callable[[dict], None]] = { - "item/agentMessage/delta": lambda p: _fire_delta(p, "_fire_stream_delta"), - "item/reasoning/delta": lambda p: _fire_delta(p, "_fire_reasoning_delta"), - "item/reasoning/summaryDelta": lambda p: _fire_delta(p, "_fire_reasoning_delta"), - "item/started": lambda p: _on_item(p, completed=False), "item/completed": lambda p: _on_item(p, completed=True), - } + if method == "item/started" and item_type in _CODEX_TOOL_ITEM_TYPES: + _fire_tool_started(item) + return + if method == "item/completed": + if item_type in _CODEX_TOOL_ITEM_TYPES: + _fire_tool_completed(item) + elif item_type == "agentMessage": + _fire_agent_message_completed(item) - def on_event(note: dict) -> None: - handler = handlers.get(note.get("method") or "") if isinstance(note, dict) else None - if handler is not None: - params = note.get("params") - handler(params if isinstance(params, dict) else {}) return on_event -# --- Codex app-server turn ---------------------------------------------------- +def run_codex_app_server_turn( + agent, + *, + user_message: str, + original_user_message: Any, + messages: List[Dict[str, Any]], + effective_task_id: str, + should_review_memory: bool = False, +) -> Dict[str, Any]: + """Codex app-server runtime path. Hands the entire turn to a `codex + app-server` subprocess and projects its events back into Hermes' + messages list so memory/skill review keep working. + + Called from run_conversation() when agent.api_mode == "codex_app_server". + Returns the same dict shape as the chat_completions path. + """ + # Defense in depth for compression.checkpoint_required: agent init + # already refuses this combination, but api_mode is a plain attribute a + # future code path could mutate on a live agent. Fail closed before the + # codex agent can compact its thread — once run_turn() executes, a + # codex-owned compaction may already have happened with no pre-compress + # checkpoint. Explicit-True check matches the compress_context() gate. + if getattr(agent, "compression_checkpoint_required", False) is True: + from agent.conversation_compression import _checkpoint_blocked + raise _checkpoint_blocked( + "codex_app_server owns the authoritative thread and compacts it " + "without a truthful pre-compaction transcript boundary" + ) -def _close_codex_session(agent) -> None: - """Drop the session so the next turn respawns codex instead of reusing a dead client.""" - with suppress(Exception): - agent._codex_session.close() - agent._codex_session = None + from agent.transports.codex_app_server_session import ( + CodexAppServerSession, + _ServerRequestRouting, + ) + # Lazy session: one CodexAppServerSession per AIAgent instance. + # Spawned on first turn, reused across turns, closed at AIAgent + # shutdown (see _cleanup hook). + if not hasattr(agent, "_codex_session") or agent._codex_session is None: + from agent.runtime_cwd import resolve_agent_cwd -def _consume_user_interrupt(agent, active: bool = True) -> tuple[bool, Any]: - """(user_interrupted, interrupt_message); clears the agent-level interrupt so a hard - stop cannot poison the next turn (mirrors the conversation-loop finalizer).""" - interrupted = bool(active and getattr(agent, "_interrupt_requested", False)) - message = getattr(agent, "_interrupt_message", None) if interrupted else None - if interrupted: - agent.clear_interrupt() - return interrupted, message - - -def _ensure_codex_session(agent) -> None: - """Lazily spawn one CodexAppServerSession per AIAgent (reused across turns, closed by the _cleanup hook).""" - if getattr(agent, "_codex_session", None) is not None: - return - from agent.runtime_cwd import resolve_agent_cwd - from agent.transports.codex_app_server_session import CodexAppServerSession, _ServerRequestRouting - # Approval callback: Hermes' standard prompt flow when a CLI thread installed one. - approval_callback = None - with suppress(Exception): - from tools.terminal_tool import _get_approval_callback - approval_callback = _get_approval_callback() - # Gateway/cron have no UI for codex approval requests, so exec/apply_patch fail closed by default. Only an - # explicit approval bypass (approvals.mode: off, /yolo, --yolo, HERMES_YOLO_MODE) hands policy to codex's sandbox. - auto_approve_requests = False - try: - from tools.approval import is_approval_bypass_active - auto_approve_requests = is_approval_bypass_active() - except Exception: - logger.debug("codex app-server: approval-bypass lookup failed; keeping fail-closed default", exc_info=True) - # Bridge codex JSON-RPC notifications (item/started, item/completed, item/agentMessage/delta, ...) into - # Hermes' gateway UI callbacks (tool_progress_callback, _fire_stream_delta, - # _emit_interim_assistant_message). Without this, Discord/Telegram users see no live tool-progress or - # interim commentary while codex_app_server is running — only the final answer (#33200). Supersedes the - # narrower item/started-only bridge from #38835. - agent._codex_session = CodexAppServerSession( - cwd=getattr(agent, "session_cwd", None) or str(resolve_agent_cwd()), approval_callback=approval_callback, - request_routing=_ServerRequestRouting(auto_approve_exec=auto_approve_requests, auto_approve_apply_patch=auto_approve_requests), - on_event=make_codex_app_server_event_bridge(agent), - ) + cwd = getattr(agent, "session_cwd", None) or str(resolve_agent_cwd()) + # Approval callback: defer to Hermes' standard prompt flow if a + # CLI thread has installed one. Gateway / cron contexts get the + # codex-side fail-closed default. + try: + from tools.terminal_tool import _get_approval_callback + approval_callback = _get_approval_callback() + except Exception: + approval_callback = None + + # Gateway / cron contexts have no UI to surface codex's approval + # requests through, so codex app-server exec / apply_patch requests + # fail closed (silently decline) by default. When the user has + # explicitly opted out of Hermes approvals — via `approvals.mode: off` + # in config, the /yolo session toggle, or --yolo / HERMES_YOLO_MODE — + # honor that and let codex's own sandbox permission profile + # (~/.codex/config.toml) be the policy gate instead of double-gating + # with a missing Hermes UI. Defaults (manual/smart/unset) preserve the + # current fail-closed behavior — this is a no-op for those users. + auto_approve_requests = False + try: + from tools.approval import is_approval_bypass_active + auto_approve_requests = is_approval_bypass_active() + except Exception: + logger.debug( + "codex app-server: approval-bypass lookup failed; " + "keeping fail-closed default", + exc_info=True, + ) + + # Bridge codex JSON-RPC notifications (item/started, item/completed, + # item/agentMessage/delta, ...) into Hermes' gateway UI callbacks + # (tool_progress_callback, _fire_stream_delta, + # _emit_interim_assistant_message). Without this, Discord/Telegram + # users see no live tool-progress or interim commentary while + # codex_app_server is running — only the final answer (#33200). + # Supersedes the narrower item/started-only bridge from #38835. + agent._codex_session = CodexAppServerSession( + cwd=cwd, + approval_callback=approval_callback, + request_routing=_ServerRequestRouting( + auto_approve_exec=auto_approve_requests, + auto_approve_apply_patch=auto_approve_requests, + ), + on_event=make_codex_app_server_event_bridge(agent), + ) + + # NOTE: the user message is ALREADY appended to messages by the + # standard run_conversation() flow (line ~11823) before the early + # return reaches us. Do NOT append again — that would duplicate. -def _persist_projected_messages(agent, turn, messages: List[Dict[str, Any]]) -> None: - """Splice the projected messages into ``messages`` and flush them to the session DB. - - Bypasses conversation_loop's per-step _persist_session(); the flush dedups via _DB_PERSISTED_MARKER so - only the new codex rows are written. The agent stays the sole persister (agent_persisted=True): a - gateway re-write would re-INSERT the user turn.""" - if not turn.projected_messages: - return - from agent.message_metadata import append_message - for projected_message in turn.projected_messages: - append_message(messages, projected_message) - if getattr(agent, "_session_db", None) is None: - return - flush_ok = False - try: - flush_ok = agent._flush_messages_to_session_db(messages) - except Exception: - logger.warning("codex app-server projected-message flush failed", exc_info=True) - if flush_ok is False: - # Output already streamed and agent_persisted cannot flip to False: surface the gap loudly. - logger.warning("codex app-server turn was delivered but could NOT be persisted to the session DB " - "(session=%s) — this turn will be missing after restart/resume", getattr(agent, "session_id", None)) - - -def _finish_codex_turn(agent, turn, messages: List[Dict[str, Any]], *, original_user_message: Any, - should_review_memory: bool) -> dict[str, Any]: - """Post-turn bookkeeping mirroring the chat_completions loop; returns usage fields.""" - # run_conversation() already bumped _turns_since_memory / _user_turn_count; only _iters_since_skill is ours. - agent._iters_since_skill = getattr(agent, "_iters_since_skill", 0) + turn.tool_iterations - _record_codex_app_server_compaction(agent, turn) - usage_result = _record_codex_app_server_usage(agent, turn) - # Skill nudge check AFTER iters were incremented (same as chat_completions). - should_review_skills = (0 < agent._skill_nudge_interval <= agent._iters_since_skill - and "skill_manage" in agent.valid_tool_names) - if should_review_skills: - agent._iters_since_skill = 0 - # External memory sync skipped on interrupt/error (no partial transcripts). - if not turn.interrupted and turn.error is None: - _call_guarded(getattr(agent, "_sync_external_memory_for_turn", None), "external memory sync raised", kwargs=dict( - original_user_message=original_user_message, final_response=turn.final_text, interrupted=False, messages=messages, - )) - # Background review fork: only when a trigger tripped AND a real final response exists. - if turn.final_text and not turn.interrupted and (should_review_memory or should_review_skills): - _call_guarded(getattr(agent, "_spawn_background_review", None), "background review spawn raised", kwargs=dict( - messages_snapshot=list(messages), review_memory=should_review_memory, review_skills=should_review_skills, - )) - return usage_result - - -def run_codex_app_server_turn(agent, *, user_message: str, original_user_message: Any, messages: List[Dict[str, Any]], - effective_task_id: str, should_review_memory: bool = False) -> Dict[str, Any]: - """Hand the turn to a ``codex app-server`` subprocess and project its events into ``messages``. - Returns the chat_completions result shape. The user message is ALREADY in ``messages`` — never append it again.""" - # Defense in depth for compression.checkpoint_required: agent init refuses the combination, but - # api_mode is mutable. Explicit-True check matches compress_context(). - if getattr(agent, "compression_checkpoint_required", False) is True: - from agent.conversation_compression import _checkpoint_blocked - raise _checkpoint_blocked("codex_app_server owns the authoritative thread and compacts it " - "without a truthful pre-compaction transcript boundary") - _ensure_codex_session(agent) try: turn = agent._codex_session.run_turn(user_input=user_message) except Exception as exc: logger.exception("codex app-server turn failed") - _close_codex_session(agent) - return _turn_result( - _consume_user_interrupt(agent), messages, api_calls=0, completed=False, error=str(exc), - final_response=f"Codex app-server turn failed: {exc}. Fall back to default runtime with `/codex-runtime auto`.", + # Crash → unconditionally drop the session so the next turn + # respawns from scratch instead of reusing a dead client. + try: + agent._codex_session.close() + except Exception: + pass + agent._codex_session = None + _user_interrupted = bool( + getattr(agent, "_interrupt_requested", False) ) - interrupt = _consume_user_interrupt(agent, turn.interrupted) - # Wedged client (deadline blown, watchdog tripped, OAuth refresh died, subprocess exited): retire it. - if getattr(turn, "should_retire", False): - logger.warning("codex app-server session retired (turn error: %s)", turn.error) - _close_codex_session(agent) - _persist_projected_messages(agent, turn, messages) - usage_result = _finish_codex_turn( - agent, turn, messages, original_user_message=original_user_message, should_review_memory=should_review_memory, + _interrupt_message = ( + getattr(agent, "_interrupt_message", None) + if _user_interrupted + else None + ) + if _user_interrupted: + agent.clear_interrupt() + return { + "final_response": ( + f"Codex app-server turn failed: {exc}. " + f"Fall back to default runtime with `/codex-runtime auto`." + ), + "messages": messages, + "api_calls": 0, + "completed": False, + "partial": True, + "interrupted": _user_interrupted, + **( + {"interrupt_message": _interrupt_message} + if _interrupt_message + else {} + ), + "error": str(exc), + } + + # This runtime bypasses the normal conversation-loop finalizer. Mirror its + # interrupt handoff/cleanup so a hard stop cannot poison the next turn and a + # message-bearing compatibility interrupt can still be replayed by callers. + _user_interrupted = bool( + turn.interrupted and getattr(agent, "_interrupt_requested", False) ) - return _turn_result( - interrupt, messages, api_calls=1, completed=not turn.interrupted and turn.error is None, error=turn.error, - # We flushed the projected rows ourselves (agent_persisted); the gateway must skip its own DB write. - final_response=turn.final_text, agent_persisted=True, codex_thread_id=turn.thread_id, codex_turn_id=turn.turn_id, - **usage_result, + _interrupt_message = ( + getattr(agent, "_interrupt_message", None) if _user_interrupted else None ) + if _user_interrupted: + agent.clear_interrupt() + + # If the turn signalled the underlying client is wedged (deadline + # blown, post-tool watchdog tripped, OAuth refresh died, subprocess + # exited), retire the session so the next turn respawns codex + # rather than riding the broken process. Mirrors openclaw beta.8's + # "retire timed-out app-server clients" fix. + if getattr(turn, "should_retire", False): + logger.warning( + "codex app-server session retired (turn error: %s)", + turn.error, + ) + try: + agent._codex_session.close() + except Exception: + pass + agent._codex_session = None + + # Splice projected messages into the conversation. The projector emits + # standard {role, content, tool_calls, tool_call_id} entries, which + # is exactly what curator.py / sessions DB expect. + if turn.projected_messages: + from agent.message_metadata import append_message + + for projected_message in turn.projected_messages: + append_message(messages, projected_message) + + # Persist the newly-projected assistant/tool messages ourselves. + # This path is an early return that bypasses conversation_loop, whose + # normal per-step _persist_session() calls would otherwise flush them. + # The inbound user turn was already flushed at turn start + # (turn_context.py _persist_session), and _flush_messages_to_session_db + # is idempotent via the intrinsic _DB_PERSISTED_MARKER — so this writes + # ONLY the new codex projected rows and does NOT re-write the user turn. + # Keeping the agent as the sole persister lets us return + # agent_persisted=True below, so the gateway skips its own DB write and + # we avoid the #860/#42039 duplicate user-message write (append_message + # is a raw INSERT with no dedup, so a gateway re-write would duplicate + # the already-flushed user turn). See gateway/run.py agent_persisted. + if getattr(agent, "_session_db", None) is not None: + try: + _codex_flush_ok = agent._flush_messages_to_session_db(messages) + except Exception: + _codex_flush_ok = False + logger.warning( + "codex app-server projected-message flush failed", + exc_info=True, + ) + if _codex_flush_ok is False: + # Unlike the chat-completions loop (which fails closed BEFORE + # projection — see conversation_loop session_persistence_failed), + # codex output has already streamed to the user by the time this + # flush runs, so there is nothing left to withhold. We cannot + # flip agent_persisted=False either: the gateway fallback write + # would re-INSERT the already-flushed user turn (#860/#42039). + # Surface the durability gap loudly instead of a silent debug. + logger.warning( + "codex app-server turn was delivered but could NOT be " + "persisted to the session DB (session=%s) — this turn " + "will be missing after restart/resume", + getattr(agent, "session_id", None), + ) -def _turn_result(interrupt: tuple[bool, Any], messages: List[Dict[str, Any]], *, api_calls: int, completed: bool, - error: Any, final_response: Any, **extra: Any) -> Dict[str, Any]: - """Result shape shared with the chat_completions path (``partial`` == ``not completed``).""" - user_interrupted, interrupt_message = interrupt + # Counter ticks for the agent-improvement loop. + # _turns_since_memory and _user_turn_count are ALREADY incremented + # in the run_conversation() pre-loop block (lines ~11793-11817) so we + # do NOT touch them here — that would double-count. + # Only _iters_since_skill needs explicit increment, since the + # chat_completions loop bumps it per tool iteration (line ~12110) + # and that loop is bypassed on this path. + agent._iters_since_skill = ( + getattr(agent, "_iters_since_skill", 0) + turn.tool_iterations + ) + _record_codex_app_server_compaction(agent, turn) + usage_result = _record_codex_app_server_usage(agent, turn) + api_calls = 1 + + # Now check the skill nudge AFTER iters were incremented — same + # pattern the chat_completions path uses (line ~15432). + should_review_skills = False + if ( + agent._skill_nudge_interval > 0 + and agent._iters_since_skill >= agent._skill_nudge_interval + and "skill_manage" in agent.valid_tool_names + ): + should_review_skills = True + agent._iters_since_skill = 0 + + # External memory provider sync (mirrors line ~15439). Skipped on + # interrupt/error to avoid feeding partial transcripts to memory. + if not turn.interrupted and turn.error is None: + try: + agent._sync_external_memory_for_turn( + original_user_message=original_user_message, + final_response=turn.final_text, + interrupted=False, + messages=messages, + ) + except Exception: + logger.debug("external memory sync raised", exc_info=True) + + # Background review fork — same cadence + signature as the default + # path (line ~15449). Only fires when a trigger actually tripped AND + # we have a real final response. + if ( + turn.final_text + and not turn.interrupted + and (should_review_memory or should_review_skills) + ): + try: + agent._spawn_background_review( + messages_snapshot=list(messages), + review_memory=should_review_memory, + review_skills=should_review_skills, + ) + except Exception: + logger.debug("background review spawn raised", exc_info=True) + return { - "final_response": final_response, "messages": messages, "api_calls": api_calls, - "completed": completed, "partial": not completed, "interrupted": user_interrupted, - **({"interrupt_message": interrupt_message} if interrupt_message else {}), - "error": error, **extra, + "final_response": turn.final_text, + "messages": messages, + "api_calls": api_calls, + "completed": not turn.interrupted and turn.error is None, + "partial": turn.interrupted or turn.error is not None, + "interrupted": _user_interrupted, + **( + {"interrupt_message": _interrupt_message} + if _interrupt_message + else {} + ), + "error": turn.error, + # The codex app-server runtime IS an early-return path that bypasses + # conversation_loop, but we flush the projected assistant/tool messages + # ourselves above (see the _flush_messages_to_session_db call after + # messages.extend). The inbound user turn was already flushed at turn + # start (turn_context._persist_session) and the flush dedups via + # _DB_PERSISTED_MARKER, so state.db ends up with each real message + # exactly once and session_search / conversation-distill see the full + # gateway conversation. Report agent_persisted=True so the gateway + # skips its own append_to_transcript DB write — writing again there + # would re-INSERT the already-flushed user turn (append_message has no + # dedup), reintroducing the #860 / #42039 duplicate-write bug. + "agent_persisted": True, + "codex_thread_id": turn.thread_id, + "codex_turn_id": turn.turn_id, + **usage_result, } -# --- Event-driven Responses streaming ----------------------------------------- -# The SDK's ``responses.stream(...)`` helper rebuilds a typed Response from ``response.completed.response.output`` -# and crashes when it is null. We consume raw ``responses.create(stream=True)`` SSE events and assemble the final -# response from ``output_item.done``, so the terminal ``output`` may be null / [] / a string / absent. +# --------------------------------------------------------------------------- +# Event-driven Responses streaming +# +# OpenAI ships its consumer Codex backend (chatgpt.com/backend-api/codex) on +# a different schedule from the openai Python SDK. The high-level +# ``client.responses.stream(...)`` helper reconstructs a typed Response from +# the terminal ``response.completed`` event's ``response.output`` field, and +# when that field drifts to ``null`` (gpt-5.5, May 2026) the SDK raises +# ``TypeError: 'NoneType' object is not iterable`` mid-iteration. +# +# We sidestep the whole class of failure by going one level lower: +# ``client.responses.create(stream=True)`` returns the raw AsyncIterable of +# SSE events, and we assemble the final response object purely from +# ``response.output_item.done`` events as they arrive. We never read +# ``response.completed.response.output`` for content reconstruction, so the +# backend can return ``null``, ``[]``, a string, or omit the field entirely +# and we don't care. +# +# This mirrors what the OpenClaw TS implementation does for the same backend +# and is structurally immune to the bug class rather than patched. +# --------------------------------------------------------------------------- + + +_TERMINAL_EVENT_TYPES = frozenset({ + "response.completed", + "response.incomplete", + "response.failed", +}) def _event_field(event: Any, name: str, default: Any = None) -> Any: - """Field access for attr-style (SDK objects) and dict (raw JSON) events/items.""" + """Field access that handles both attr-style (SDK objects) and dict (raw JSON) events.""" value = getattr(event, name, None) if value is None and isinstance(event, dict): value = event.get(name, default) return value if value is not None else default +def _item_field(item: Any, name: str, default: Any = None) -> Any: + """Field access for nested Response items (attr-style SDK object or dict).""" + value = getattr(item, name, None) + if value is None and isinstance(item, dict): + value = item.get(name, default) + return value if value is not None else default + + def _raise_stream_error(event: Any) -> None: - """Raise ``_StreamErrorEvent`` from a ``type=error`` SSE frame. The spec puts code/message/param at the - top level, but the SDK and several proxies nest them under ``error``; read top-level first, then the envelope.""" + """Raise a ``_StreamErrorEvent`` from a ``type=error`` SSE frame. + + The Responses spec puts the failure details at the top level of the + frame (``{"type": "error", "code": ..., "message": ..., "param": ...}``), + but the official OpenAI SDK and several OpenAI-compatible proxies wrap + them in an HTTP-style nested envelope instead + (``{"type": "error", "error": {"code": ..., "message": ..., "param": ...}}``). + Read the top-level fields first, then fall back to the nested envelope so + the error classifier sees the provider's real code/message (rate-limit vs + context-overflow vs entitlement) rather than the generic placeholder. + Port of anomalyco/opencode#36130. + + Imported lazily so this module stays importable from places that don't + pull in ``run_agent`` (e.g. plugin code, doc tools). + """ from run_agent import _StreamErrorEvent + nested = _event_field(event, "error") def _error_field(name: str) -> Any: value = _event_field(event, name) - return _event_field(nested, name) if value is None and nested is not None else value - raw_message = _error_field("message") - message = (str(raw_message) if raw_message is not None else "stream emitted error event").strip() or "stream emitted error event" - raise _StreamErrorEvent(message, code=_error_field("code"), param=_error_field("param")) - - -def _message_phase(item: Any) -> str | None: - phase = _event_field(item, "phase", None) - return phase.strip().lower() if isinstance(phase, str) else None + if value is None and nested is not None: + value = _item_field(nested, name) + return value + raw_message = _error_field("message") + if raw_message is not None and not isinstance(raw_message, str): + raw_message = str(raw_message) + message = (raw_message or "stream emitted error event").strip() or "stream emitted error event" + raise _StreamErrorEvent( + message, + code=_error_field("code"), + param=_error_field("param"), + ) -def _output_text_of(item: Any) -> str: - """Concatenated ``output_text`` parts of a message item ("" if content is not a list).""" - content_parts = _event_field(item, "content", []) - parts = content_parts if isinstance(content_parts, list) else [] - return "".join( - str(_event_field(part, "text", "") or "") for part in parts if _event_field(part, "type", "") == "output_text" - ).strip() - - -class _CodexResponseAssembler: - """Assemble a Response-shaped ``SimpleNamespace`` from raw Responses SSE events. - - Only ``usage`` / ``status`` / ``id`` are read from the terminal frame — never ``response.output``. Output - items come from ``output_item.done``, or are synthesized from text deltas, or settled from function calls - announced via ``output_item.added`` but never confirmed (some backends omit per-item done events on success).""" - has_tool_calls = first_delta_fired = saw_terminal = False - next_output_sequence = 0 +def _consume_codex_event_stream( + event_iter: Any, + *, + model: str, + on_text_delta=None, + on_reasoning_delta=None, + on_commentary_message=None, + on_first_delta=None, + on_event=None, + interrupt_check=None, +) -> SimpleNamespace: + """Consume a Codex Responses SSE event stream and return a final response. + + The returned object is a ``SimpleNamespace`` shaped like the SDK's typed + ``Response`` for the fields downstream code actually reads: + + * ``output``: list of output items, assembled from ``response.output_item.done``. + For tool-call turns this contains the function_call items; for plain-text + turns it contains a synthesized ``message`` item built from streamed deltas + if no message item was emitted directly. + * ``output_text``: assembled text from ``response.output_text.delta`` deltas. + * ``usage``: copied from the terminal event's ``response.usage`` (when present). + * ``status``: ``completed`` / ``incomplete`` / ``failed`` (or ``completed`` if + the stream ended without a terminal frame but produced content). + * ``id``: ``response.id`` when present. + * ``incomplete_details``: passed through for ``response.incomplete`` frames. + * ``error``: passed through for ``response.failed`` frames. + * ``model``: from kwargs (the wire model name is not authoritative). + + Critically, we never read ``response.output`` from the terminal event for + content reconstruction — only ``usage``, ``status``, ``id``. That field + being ``null`` / ``[]`` / missing is fine. + + Callbacks: + + * ``on_text_delta(str)`` — fires per ``response.output_text.delta``, suppressed + once a function_call event is seen (so tool-call turns don't bleed text + into the chat). + * ``on_reasoning_delta(str)`` — fires per ``response.reasoning.*.delta`` and + ``phase=analysis`` message deltas. When no dedicated commentary callback + is supplied, commentary also uses this legacy fallback. + * ``on_commentary_message(str)`` — fires once per completed + ``phase=commentary`` message, before any following tool item executes. + * ``on_first_delta()`` — one-shot, fires on the first text delta only. + * ``on_event(event)`` — fires for every event before any other processing. + Used for watchdog activity, debug logging, anything wire-shape-agnostic. + * ``interrupt_check()`` — returns True to break the loop early. + """ + collected_output_items: List[Any] = [] + # output_index of each collected_output_items entry, appended in lockstep + # so settled pending calls can be merged back in stream order. + collected_output_indexes: List[Any] = [] + collected_output_sequences: List[int] = [] + collected_text_deltas: List[str] = [] + has_tool_calls = False + # Function calls announced via output_item.added but not yet confirmed by + # output_item.done, keyed by item id. Some OpenAI-compatible backends omit + # per-item done events on a successful completion (upstream evidence: + # anomalyco/opencode#37159); these are settled from accumulated stream + # state at the terminal event so the tool call executes instead of being + # silently dropped. + pending_function_calls: Dict[str, Dict[str, Any]] = {} + # First-observed (sequence, output_index) per announced item id, so items + # confirmed later via output_item.done keep their announced stream + # position when merged with settled pending calls. + announced_output_order: Dict[str, tuple] = {} + first_delta_fired = False active_message_phase: str | None = None - # Reasoning summary parts carry no separator; a summary_index change is where the blank line belongs. + commentary_text_deltas: List[str] = [] + # Last reasoning summary_index seen. The Responses stream delimits summary + # parts by this index and gives each part no separator of its own, so a + # change of index is where the blank line belongs. active_summary_index: Any = None terminal_status: str = "completed" - terminal_usage = terminal_response_id = terminal_incomplete_details = terminal_error = None - # terminal_status defaults to "completed", so settlement needs an explicitly observed response.completed frame. + terminal_usage: Any = None + terminal_response_id: str = None + terminal_incomplete_details: Any = None + terminal_error: Any = None + saw_terminal = False + # Settlement of pending calls requires an actually observed successful + # terminal frame. ``terminal_status`` defaults to "completed", so it + # cannot distinguish a real response.completed from EOF/interruption. saw_response_completed = False + next_output_sequence = 0 - def __init__(self, *, model, on_text_delta, on_reasoning_delta, on_commentary_message, on_first_delta): - self.model, self.on_text_delta, self.on_reasoning_delta = model, on_text_delta, on_reasoning_delta - self.on_commentary_message, self.on_first_delta = on_commentary_message, on_first_delta - self.output_items: List[Any] = [] - # output_index / first-observed sequence per output item, in lockstep, so settled pending calls merge - # back in stream order. - self.output_indexes, self.output_sequences = [], [] - self.text_deltas, self.commentary_text_deltas = [], [] - # pending_function_calls: announced-but-unconfirmed function calls keyed by item id. announced_output_order: - # first-observed (sequence, output_index) per announced item id so a later .done keeps its announced position. - self.pending_function_calls: Dict[str, Dict[str, Any]] = {} - self.announced_output_order: Dict[str, tuple] = {} - - def _safe(self, cb: Callable | None, label: str, *args: Any) -> None: - _call_guarded(cb, f"Codex stream {label} raised", args=args) - - def _on_item_added(self, event: Any, event_type: str) -> None: - item = _event_field(event, "item") - item_type = _event_field(item, "type", "") - self.active_message_phase = _message_phase(item) if item_type == "message" else None - if self.active_message_phase == "commentary": - self.commentary_text_deltas = [] - # Record first-observed ordering for EVERY announced item; .done must reuse it or a mixed - # announced/pending stream without output_index values reorders the calls. - item_id = str(_event_field(item, "id", "")) - if item_id and item_id not in self.announced_output_order: - self.announced_output_order[item_id] = (self.next_output_sequence, _event_field(event, "output_index")) - self.next_output_sequence += 1 - if "function_call" in str(item_type): - self.has_tool_calls = True - if item_id: - announced_sequence, announced_index = self.announced_output_order[item_id] - self.pending_function_calls[item_id] = { - "item": item, "arguments": str(_event_field(item, "arguments", "") or ""), - "output_index": announced_index, "sequence": announced_sequence, - } - - def _on_text_delta(self, event: Any, event_type: str) -> None: - delta_text = _event_field(event, "delta", "") - if not delta_text: - return - # Harmony commentary/analysis text is mid-turn narration, never the final answer: route to the - # reasoning callback, keep only the item for replay. - if self.active_message_phase == "commentary": - self.commentary_text_deltas.append(delta_text) - # Legacy fallback when no first-class commentary consumer is installed. - if self.on_commentary_message is None: - self._safe(self.on_reasoning_delta, "on_reasoning_delta", delta_text) - elif self.active_message_phase == "analysis": - self._safe(self.on_reasoning_delta, "on_reasoning_delta", delta_text) - else: - self.text_deltas.append(delta_text) - if self.has_tool_calls: - return - if not self.first_delta_fired: - self.first_delta_fired = True - self._safe(self.on_first_delta, "on_first_delta") - self._safe(self.on_text_delta, "on_text_delta", delta_text) - - def _on_function_call(self, event: Any, event_type: str) -> None: - self.has_tool_calls = True - pending = self.pending_function_calls.get(str(_event_field(event, "item_id", ""))) - if pending is None: - return # the item itself lands on output_item.done - if "delta" in event_type: - pending["arguments"] += _event_field(event, "delta", "") or "" - elif event_type.endswith("function_call_arguments.done"): - # Authoritative for the accumulated string; an explicit "" (zero-arg call) counts, only a - # missing field keeps the streamed deltas. - if (done_args := _event_field(event, "arguments", None)) is not None: - pending["arguments"] = str(done_args) - - def _on_reasoning_delta(self, event: Any, event_type: str) -> None: - reasoning_text = _event_field(event, "delta", "") - if not reasoning_text or self.on_reasoning_delta is None: - return - summary_index = _event_field(event, "summary_index") - if summary_index is not None: - if self.active_summary_index is not None and summary_index != self.active_summary_index: - reasoning_text = f"\n\n{reasoning_text}" - self.active_summary_index = summary_index - self._safe(self.on_reasoning_delta, "on_reasoning_delta", reasoning_text) - - def _on_item_done(self, event: Any, event_type: str) -> None: - done_item = _event_field(event, "item") - if done_item is None: - return - self.output_items.append(done_item) - # Reuse the announced position when known (fresh tail sequence for unannounced items); the .done - # event's own output_index wins over the announced one. - done_id = str(_event_field(done_item, "id", "")) - announced_sequence, announced_index = self.announced_output_order.get(done_id, (None, None)) - if announced_sequence is None: - announced_sequence, self.next_output_sequence = self.next_output_sequence, self.next_output_sequence + 1 - self.output_indexes.append(_event_field(event, "output_index", announced_index)) - self.output_sequences.append(announced_sequence) - # Confirmed by the authoritative done event; never settle it twice. - self.pending_function_calls.pop(done_id, None) - if _message_phase(done_item) == "commentary" and self.on_commentary_message is not None: - commentary_text = "".join(self.commentary_text_deltas).strip() or _output_text_of(done_item) - if commentary_text: - self._safe(self.on_commentary_message, "on_commentary_message", commentary_text) - self.commentary_text_deltas = [] - - def _on_terminal(self, event: Any, event_type: str) -> bool: - self.saw_terminal = True - resp_obj = _event_field(event, "response") - if resp_obj is not None: - self.terminal_usage, self.terminal_response_id = _event_field(resp_obj, "usage"), _event_field(resp_obj, "id") - rstatus = _event_field(resp_obj, "status") - if isinstance(rstatus, str): - self.terminal_status = rstatus - if event_type == "response.incomplete": - self.terminal_incomplete_details = _event_field(resp_obj, "incomplete_details") - elif event_type == "response.failed": - self.terminal_error = _event_field(resp_obj, "error") - self.saw_response_completed = self.saw_response_completed or event_type == "response.completed" - self.terminal_status = self.terminal_status or event_type.removeprefix("response.") - return True - - # Exact-type handlers first, then substring-matched ones in priority order. ``error`` frames - # carry the provider's real failure reason; raise so the credential pool + classifier see the body. - _EXACT_HANDLERS = { - "error": lambda self, event, event_type: _raise_stream_error(event), - "response.output_item.added": _on_item_added, "response.output_item.done": _on_item_done, - "response.completed": _on_terminal, "response.incomplete": _on_terminal, "response.failed": _on_terminal, - } - _FUZZY_HANDLERS = ( - (lambda t: "output_text.delta" in t, _on_text_delta), (lambda t: "function_call" in t, _on_function_call), - (lambda t: "reasoning" in t and "delta" in t, _on_reasoning_delta), - ) - - def feed(self, event: Any) -> bool: - """Process one event; True when the stream hit a terminal frame.""" - event_type = _event_field(event, "type", "") - event_type = event_type if isinstance(event_type, str) else "" - handler = self._EXACT_HANDLERS.get(event_type) or next((h for m, h in self._FUZZY_HANDLERS if m(event_type)), None) - return bool(handler(self, event, event_type)) if handler is not None else False - - def _settled_output(self) -> List[Any]: - """Merge .done items with settled pending calls, keeping stream order.""" - indexed = list(zip(self.output_indexes, self.output_sequences, self.output_items)) - for pending in self.pending_function_calls.values(): - item = pending["item"] - indexed.append((pending.get("output_index"), pending["sequence"], SimpleNamespace( - type="function_call", id=_event_field(item, "id", None), call_id=_event_field(item, "call_id", None), - name=_event_field(item, "name", None), status="completed", - # Empty/whitespace arguments become "{}" so zero-delta calls stay executable; malformed - # non-empty JSON passes through untouched. - arguments=(pending["arguments"] or "").strip() or "{}", - ))) - # output_index is optional: protocol order only when every entry has one, else wire order. - if all(entry[0] is not None for entry in indexed): - with suppress(TypeError): # non-comparable index values: keep wire order - indexed.sort(key=lambda entry: entry[0]) - else: - indexed.sort(key=lambda entry: entry[1]) - return [entry[2] for entry in indexed] - - def result(self) -> SimpleNamespace: - # With only plain text deltas (no tool calls), synthesize one message item. - output: List[Any] = list(self.output_items) - if not output and self.text_deltas and not self.has_tool_calls: - content = [SimpleNamespace(type="output_text", text="".join(self.text_deltas))] - output = [SimpleNamespace(type="message", role="assistant", status="completed", content=content)] - # Done items stay authoritative; settlement only fills the gap left by backends that omit - # per-item done events on a successful completion. - if self.pending_function_calls and self.saw_response_completed: - output = self._settled_output() - # No terminal frame AND no usable content = truncated / rejected stream. - if not self.saw_terminal and not output: - raise RuntimeError("Codex Responses stream did not emit a terminal response") - return SimpleNamespace( - output=output, output_text="".join(self.text_deltas), usage=self.terminal_usage, status=self.terminal_status, - id=self.terminal_response_id, model=self.model, incomplete_details=self.terminal_incomplete_details, - error=self.terminal_error) - - -def _consume_codex_event_stream( - event_iter: Any, *, model: str, on_text_delta=None, on_reasoning_delta=None, on_commentary_message=None, - on_first_delta=None, on_event=None, interrupt_check=None, -) -> SimpleNamespace: - """Consume a Codex Responses SSE stream into a Response-shaped ``SimpleNamespace`` (see - :class:`_CodexResponseAssembler`; ``status`` is ``completed`` when the stream ended with content but no - terminal frame; ``model`` comes from kwargs). - - Callbacks: ``on_text_delta`` per output_text delta, suppressed once a function_call is seen; - ``on_reasoning_delta`` for reasoning and ``phase=analysis`` deltas (also commentary without a commentary - callback); ``on_commentary_message`` once per completed ``phase=commentary`` message, before any following - tool item; ``on_first_delta`` one-shot; ``on_event`` every event before any processing; ``interrupt_check()`` - True breaks the loop and may raise ``TimeoutError`` / ``InterruptedError`` for request retirement that - must not become a partial final response.""" - assembler = _CodexResponseAssembler(model=model, on_text_delta=on_text_delta, on_reasoning_delta=on_reasoning_delta, - on_commentary_message=on_commentary_message, on_first_delta=on_first_delta) for event in event_iter: if on_event is not None: try: on_event(event) except (TimeoutError, InterruptedError): - raise # watchdog / cancellation control flow must propagate + # Control-flow signals from watchdog/cancellation hooks must + # propagate, not get swallowed as "debug noise". + raise except Exception: + # Genuine bugs in third-party debug/log hooks shouldn't break + # stream consumption. logger.debug("Codex stream on_event hook raised", exc_info=True) - if (interrupt_check is not None and interrupt_check()) or assembler.feed(event): + if interrupt_check is not None and interrupt_check(): break - return assembler.result() + event_type = _event_field(event, "type", "") + if not isinstance(event_type, str): + event_type = "" + + # ``error`` SSE frames carry the provider's real failure reason + # (subscription / quota / model-not-available / rejected-reasoning-replay) + # but never appear in the terminal set. Surface them as a structured + # exception so the credential pool + error classifier see the body. + if event_type == "error": + _raise_stream_error(event) + + # Track the phase of the active streamed message item. Codex/Harmony + # ``commentary``/``analysis`` text is mid-turn preamble/progress + # narration, never the final answer. We still collect completed output + # items for replay, but route those deltas to the reasoning callback so + # they display like thinking text instead of assistant content. + if event_type == "response.output_item.added": + item = _event_field(event, "item") + item_type = _item_field(item, "type", "") + if item_type == "message": + phase = _item_field(item, "phase", None) + active_message_phase = phase.strip().lower() if isinstance(phase, str) else None + if active_message_phase == "commentary": + commentary_text_deltas = [] + else: + active_message_phase = None + # First-observed ordering metadata for EVERY announced item (not + # just function calls): when this item later lands via + # output_item.done, the done path must reuse the announced + # sequence/index instead of allocating a fresh tail position, or + # a mixed announced/pending stream without output_index values + # reorders the calls (review P1 on PR #92767). + item_id = str(_item_field(item, "id", "")) + if item_id and item_id not in announced_output_order: + announced_output_order[item_id] = ( + next_output_sequence, + _event_field(event, "output_index", None), + ) + next_output_sequence += 1 + if "function_call" in str(item_type): + has_tool_calls = True + if item_id: + announced_sequence, announced_index = announced_output_order[item_id] + # Seed from the announced item's own arguments when the + # backend attaches them up front, and remember the stream + # position so a settled call keeps its place in the output. + pending_function_calls[item_id] = { + "item": item, + "arguments": str(_item_field(item, "arguments", "") or ""), + "output_index": announced_index, + "sequence": announced_sequence, + } + continue + + if "output_text.delta" in event_type or event_type == "response.output_text.delta": + delta_text = _event_field(event, "delta", "") + if delta_text and active_message_phase == "commentary": + commentary_text_deltas.append(delta_text) + # Preserve CLI/backward compatibility when no first-class + # commentary consumer is installed. + if on_commentary_message is None and on_reasoning_delta is not None: + try: + on_reasoning_delta(delta_text) + except Exception: + logger.debug("Codex stream on_reasoning_delta raised", exc_info=True) + elif delta_text and active_message_phase == "analysis": + if on_reasoning_delta is not None: + try: + on_reasoning_delta(delta_text) + except Exception: + logger.debug("Codex stream on_reasoning_delta raised", exc_info=True) + elif delta_text: + collected_text_deltas.append(delta_text) + if not has_tool_calls: + if not first_delta_fired: + first_delta_fired = True + if on_first_delta is not None: + try: + on_first_delta() + except Exception: + logger.debug("Codex stream on_first_delta raised", exc_info=True) + if on_text_delta is not None: + try: + on_text_delta(delta_text) + except Exception: + logger.debug("Codex stream on_text_delta raised", exc_info=True) + continue + + if "function_call" in event_type: + has_tool_calls = True + # Accumulate streamed argument deltas for calls announced via + # output_item.added, so a stream that completes without per-item + # done events can still be settled from accumulated state. + if "delta" in event_type: + delta_args = _event_field(event, "delta", "") + pending = pending_function_calls.get(str(_event_field(event, "item_id", ""))) + if pending is not None and delta_args: + pending["arguments"] += delta_args + continue + if event_type.endswith("function_call_arguments.done"): + done_args = _event_field(event, "arguments", None) + pending = pending_function_calls.get(str(_event_field(event, "item_id", ""))) + if pending is not None and done_args is not None: + # Per-item arguments.done is authoritative for the + # accumulated string when the item itself never lands. + # An explicit empty string (zero-argument call) counts as + # authoritative; only a missing field leaves the streamed + # deltas in place. + pending["arguments"] = str(done_args) + continue + # other function_call frames fall through — function_call items still get added on output_item.done + + if "reasoning" in event_type and "delta" in event_type: + reasoning_text = _event_field(event, "delta", "") + if reasoning_text and on_reasoning_delta is not None: + # Summary parts stream one after another with no separator of + # their own; summary_index is the boundary the wire gives us. + summary_index = _event_field(event, "summary_index") + if ( + summary_index is not None + and active_summary_index is not None + and summary_index != active_summary_index + ): + reasoning_text = f"\n\n{reasoning_text}" + if summary_index is not None: + active_summary_index = summary_index + try: + on_reasoning_delta(reasoning_text) + except Exception: + logger.debug("Codex stream on_reasoning_delta raised", exc_info=True) + continue + + if event_type == "response.output_item.done": + done_item = _event_field(event, "item") + if done_item is not None: + collected_output_items.append(done_item) + # Reuse the first-observed position when this item was + # announced earlier via output_item.added; a fresh tail + # sequence is allocated only for genuinely unannounced items. + # The .done event's own output_index wins when present, with + # the announced index as its fallback. + done_id = str(_item_field(done_item, "id", "")) + announced_sequence, announced_index = announced_output_order.get( + done_id, (None, None) + ) + done_index = _event_field(event, "output_index", None) + if done_index is None: + done_index = announced_index + if announced_sequence is None: + announced_sequence = next_output_sequence + next_output_sequence += 1 + collected_output_indexes.append(done_index) + collected_output_sequences.append(announced_sequence) + # Confirmed by the authoritative per-item done event; remove + # from pending so it is not settled twice. + pending_function_calls.pop(done_id, None) + done_phase = _item_field(done_item, "phase", None) + done_phase = done_phase.strip().lower() if isinstance(done_phase, str) else None + if done_phase == "commentary" and on_commentary_message is not None: + commentary_text = "".join(commentary_text_deltas).strip() + if not commentary_text: + content_parts = _item_field(done_item, "content", []) + if isinstance(content_parts, list): + commentary_text = "".join( + str(_item_field(part, "text", "") or "") + for part in content_parts + if _item_field(part, "type", "") == "output_text" + ).strip() + if commentary_text: + try: + on_commentary_message(commentary_text) + except Exception: + logger.debug( + "Codex stream on_commentary_message raised", + exc_info=True, + ) + commentary_text_deltas = [] + continue + + if event_type in _TERMINAL_EVENT_TYPES: + saw_terminal = True + resp_obj = _event_field(event, "response") + if resp_obj is not None: + terminal_usage = getattr(resp_obj, "usage", None) + if terminal_usage is None and isinstance(resp_obj, dict): + terminal_usage = resp_obj.get("usage") + rid = getattr(resp_obj, "id", None) + if rid is None and isinstance(resp_obj, dict): + rid = resp_obj.get("id") + terminal_response_id = rid + rstatus = getattr(resp_obj, "status", None) + if rstatus is None and isinstance(resp_obj, dict): + rstatus = resp_obj.get("status") + if isinstance(rstatus, str): + terminal_status = rstatus + if event_type == "response.incomplete": + terminal_incomplete_details = getattr(resp_obj, "incomplete_details", None) + if terminal_incomplete_details is None and isinstance(resp_obj, dict): + terminal_incomplete_details = resp_obj.get("incomplete_details") + if event_type == "response.failed": + terminal_error = getattr(resp_obj, "error", None) + if terminal_error is None and isinstance(resp_obj, dict): + terminal_error = resp_obj.get("error") + if event_type == "response.completed": + saw_response_completed = True + terminal_status = terminal_status or "completed" + elif event_type == "response.incomplete": + terminal_status = terminal_status or "incomplete" + elif event_type == "response.failed": + terminal_status = terminal_status or "failed" + # Stop on terminal event. + break + + # Build the final output list. Prefer items observed via output_item.done; + # if none arrived but we streamed plain text deltas (no tool calls), synthesize + # a single message item so downstream normalization has something to work with. + if collected_output_items: + output = list(collected_output_items) + elif collected_text_deltas and not has_tool_calls: + assembled = "".join(collected_text_deltas) + output = [SimpleNamespace( + type="message", + role="assistant", + status="completed", + content=[SimpleNamespace(type="output_text", text=assembled)], + )] + else: + output = [] + + # Settle function calls that were announced via output_item.added and + # streamed argument deltas but never confirmed by output_item.done: some + # OpenAI-compatible backends omit per-item done events on a successful + # completion (anomalyco/opencode#37159). Done items stay authoritative; + # this only fills the gap so the call executes instead of vanishing. + if pending_function_calls and saw_response_completed: + # Assemble settled calls and .done items in output_index order instead + # of appending at the tail: a pending call that streamed before a later + # .done item must keep its position, or dependent side effects invert. + indexed = [ + (index, sequence, position, item) + for position, (index, sequence, item) in enumerate( + zip( + collected_output_indexes, + collected_output_sequences, + collected_output_items, + ) + ) + ] + for position, pending in enumerate(pending_function_calls.values(), start=len(indexed)): + item = pending["item"] + # Canonicalize empty/whitespace arguments so zero-delta calls stay + # executable; malformed non-empty JSON passes through untouched and + # stays rejected by downstream argument parsing. + arguments = (pending["arguments"] or "").strip() or "{}" + indexed.append((pending.get("output_index"), pending["sequence"], position, SimpleNamespace( + type="function_call", + id=_item_field(item, "id", None), + call_id=_item_field(item, "call_id", None), + name=_item_field(item, "name", None), + arguments=arguments, + status="completed", + ))) -def _sanitize_consumer_codex_request(agent: Any, request: dict[str, Any]) -> dict[str, Any]: - """Drop fields the ChatGPT OAuth Codex endpoint rejects, at the final wire boundary (after Relay / - middleware / ``request_overrides``): a late ``prompt_cache_retention``, top-level or nested in - ``extra_body``, would otherwise HTTP 400 a valid follow-up.""" + # output_index is optional in compatible Responses streams. A partial + # ordering (sorting indexed entries while interleaving unindexed ones) + # is not well-defined and can produce contradictory comparisons. Keep + # the observed wire order whenever any index is missing; use the + # protocol ordering only when every entry provides an index. + if all(entry[0] is not None for entry in indexed): + try: + indexed.sort(key=lambda entry: entry[0]) + except TypeError: + # Preserve wire order if a backend sends non-comparable index + # values instead of integers. + pass + else: + indexed.sort(key=lambda entry: entry[1]) + output = [entry[3] for entry in indexed] + + # If the stream ended without any terminal event AND produced no usable + # content (no items, no text deltas), surface that as a RuntimeError so + # callers can distinguish "stream truncated mid-flight / provider rejected + # the call" from "stream completed with empty body". This preserves the + # signal the SDK's high-level helper used to raise as + # ``RuntimeError("Didn't receive a `response.completed` event.")``. + if not saw_terminal and not output: + raise RuntimeError( + "Codex Responses stream did not emit a terminal response" + ) + + assembled_text = "".join(collected_text_deltas) + + final = SimpleNamespace( + output=output, + output_text=assembled_text, + usage=terminal_usage, + status=terminal_status, + id=terminal_response_id, + model=model, + incomplete_details=terminal_incomplete_details, + error=terminal_error, + ) + return final + + +def _sanitize_consumer_codex_request( + agent: Any, + request: dict[str, Any], +) -> dict[str, Any]: + """Drop fields the ChatGPT OAuth Codex endpoint does not accept. + + This guard intentionally lives at the final wire boundary, after Relay or + other request middleware has had a chance to transform the request. The + normal transport builder already omits ``prompt_cache_retention`` for this + endpoint, but a late mutation must not be allowed to turn a valid tool + follow-up into a non-retryable HTTP 400. + + Explicit ``request_overrides`` are subject to the same endpoint contract: + unsupported retention is dropped with a warning instead of being sent and + rejected by the provider. The check covers both the top-level kwarg and a + nested ``extra_body`` entry — the OpenAI SDK merges ``extra_body`` into + the outgoing JSON body, so either shape reaches the endpoint. + """ sanitized = dict(request) - # getattr: run_codex_stream is also driven with stand-in agents carrying only the attrs a path needs. + # Resolved defensively on purpose: run_codex_stream is also driven with + # lightweight stand-in agents that carry only the attributes a given path + # needs (see tests/agent/test_codex_request_transport_diagnostics.py), so a + # bare agent._is_codex_backend() here would raise AttributeError on them. backend_predicate = getattr(agent, "_is_codex_backend", None) - if not (callable(backend_predicate) and bool(backend_predicate())): + is_consumer_codex = ( + bool(backend_predicate()) if callable(backend_predicate) else False + ) + if not is_consumer_codex: return sanitized - dropped_from = ["top-level"] if "prompt_cache_retention" in sanitized else [] - sanitized.pop("prompt_cache_retention", None) - # Copy before editing (caller's mapping must not mutate); drop when emptied. + dropped_from: list[str] = [] + if "prompt_cache_retention" in sanitized: + sanitized.pop("prompt_cache_retention") + dropped_from.append("top-level") + # The OpenAI SDK merges ``extra_body`` into the outgoing JSON body, so a + # nested ``extra_body.prompt_cache_retention`` reaches the endpoint just + # like the top-level field would. Copy before editing — the caller's + # mapping must not be mutated — and drop the mapping when it empties. extra_body = sanitized.get("extra_body") if isinstance(extra_body, dict) and "prompt_cache_retention" in extra_body: - sanitized["extra_body"] = {k: v for k, v in extra_body.items() if k != "prompt_cache_retention"} - if not sanitized["extra_body"]: + extra_body = dict(extra_body) + extra_body.pop("prompt_cache_retention") + if extra_body: + sanitized["extra_body"] = extra_body + else: sanitized.pop("extra_body") dropped_from.append("extra_body") if dropped_from: - logger.warning("Dropped unsupported prompt_cache_retention at consumer Codex wire boundary (model=%s, via %s).", - sanitized.get("model", getattr(agent, "model", "unknown")), ", ".join(dropped_from)) + logger.warning( + "Dropped unsupported prompt_cache_retention at consumer Codex " + "wire boundary (model=%s, via %s).", + sanitized.get("model", getattr(agent, "model", "unknown")), + ", ".join(dropped_from), + ) return sanitized -# Bulk request fields carrying the conversation payload; the rest is scalar config the SDK transform handles fast. +# Bulk request fields that carry the conversation payload. Everything else in +# the request is scalar configuration the SDK transform handles in microseconds. _SDK_TRANSFORM_BYPASS_FIELDS = ("input", "tools") def _is_plain_json_data(value: Any) -> bool: - """True when ``value`` is purely JSON wire types; pydantic models / generators must keep the typed SDK path.""" + """True when ``value`` is composed purely of JSON wire types. + + The SDK's request transform exists to convert typed params (TypedDict + key aliases, pydantic models, ``PropertyInfo`` formats) into wire + format. Hermes assembles Codex payloads from JSON round-trips, so they + are already wire format — but that is only provable when every node is + a plain JSON type. Anything else must keep the typed SDK path. + """ if value is None or isinstance(value, (str, int, float, bool)): return True if isinstance(value, dict): - return all(isinstance(key, str) and _is_plain_json_data(item) for key, item in value.items()) + return all( + isinstance(key, str) and _is_plain_json_data(item) + for key, item in value.items() + ) if isinstance(value, list): return all(_is_plain_json_data(item) for item in value) return False def _bypass_sdk_request_transform(stream_kwargs: dict) -> dict: - """Route bulk payload fields around the SDK's ``maybe_transform``. - - ``responses.create`` re-walks the whole body against the ResponseCreateParams union with the GIL held — - multi-MB conversations can wedge for hours, pre-network, where no watchdog socket kill helps. The SDK - merges ``extra_body`` AFTER the transform, so moving wire-format bulk fields there yields a byte-identical - request without the walk. HERMES_CODEX_SDK_TRANSFORM=1 disables.""" - if os.environ.get("HERMES_CODEX_SDK_TRANSFORM", "").strip().lower() in {"1", "true", "yes", "on"}: + """Route bulk payload fields around the SDK's ``maybe_transform`` (#93650). + + ``responses.create`` re-walks the entire request body against the + ``ResponseCreateParams`` union graph before any byte leaves the process. + That walk runs with the GIL held, and #93650 documents it wedging for + 12+ hours on a ~1.4 MB conversation — starving every other thread, + including the TTFB/stale watchdogs whose job is to rescue this exact + call. Because the hang is client-side and pre-network, no socket kill + can unblock it. + + The SDK merges ``extra_body`` into the JSON body *after* the transform + (``_base_client._build_request``), so moving the already-wire-format + bulk fields there skips the walk entirely and produces a byte-identical + request. Fields containing anything that is not plain JSON data (e.g. + pydantic models, generators) stay on the typed path, which still needs + the transform. Set HERMES_CODEX_SDK_TRANSFORM=1 to restore the pre-fix + behavior. + """ + if os.environ.get("HERMES_CODEX_SDK_TRANSFORM", "").strip().lower() in { + "1", "true", "yes", "on" + }: return stream_kwargs - moved = {f: stream_kwargs[f] for f in _SDK_TRANSFORM_BYPASS_FIELDS - if isinstance(stream_kwargs.get(f), (dict, list)) and _is_plain_json_data(stream_kwargs[f])} + + moved = { + field: stream_kwargs[field] + for field in _SDK_TRANSFORM_BYPASS_FIELDS + if isinstance(stream_kwargs.get(field), (dict, list)) + and _is_plain_json_data(stream_kwargs[field]) + } if not moved: return stream_kwargs - bypassed = {key: value for key, value in stream_kwargs.items() if key not in moved} + + bypassed = { + key: value for key, value in stream_kwargs.items() if key not in moved + } extra_body = bypassed.get("extra_body") merged = dict(extra_body) if isinstance(extra_body, dict) else {} - # An explicit caller-provided extra_body entry keeps precedence (SDK post-transform merge). - bypassed["extra_body"] = {**merged, **{f: v for f, v in moved.items() if f not in merged}} + for field, value in moved.items(): + # An explicit caller-provided extra_body entry keeps precedence, + # matching what the SDK's post-transform merge would have done. + merged.setdefault(field, value) + bypassed["extra_body"] = merged return bypassed def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta=None): - """One streaming Responses API request over raw ``responses.create(stream=True)`` events.""" + """Execute one streaming Responses API request and return the final response. + + Uses ``responses.create(stream=True)`` (low-level raw event iteration) + rather than the high-level ``responses.stream(...)`` helper. This makes + us structurally immune to backend drift in the ``response.completed`` + payload shape — we never let the SDK reconstruct a typed object from + the terminal event's ``output`` field. + """ import httpx as _httpx from openai import APIConnectionError as _APIConnectionError + from agent import relay_llm - transport_errors = (_httpx.RemoteProtocolError, _httpx.ReadTimeout, _httpx.ConnectError, ConnectionError) + active_client = client or agent._ensure_primary_openai_client(reason="codex_stream_direct") - max_stream_retries, model = 1, api_kwargs.get("model") + max_stream_retries = 1 # Accumulate streamed text so callers / compat shims can read it. agent._codex_streamed_text_parts: list = [] - # Retirement token for THIS request (installed by ``interruptible_api_call``). A watchdog that kills the - # connection clears the agent-level token, so a worker still draining frames can tell it was retired. - # ``None`` = no watchdog; every check passes. - request_token = getattr(agent, "_active_codex_stream_request_token", None) - # Delta-sink claim for the CURRENT physical attempt (None until the stream opens). - writer_token = {"value": None} - - def _request_is_current() -> bool: - return request_token is None or getattr(agent, "_active_codex_stream_request_token", None) is request_token - - def _fenced(fn: Callable[[Any], None]) -> Callable[[Any], None]: - """Wrap a callback so a retired request's late frames never reach the agent.""" - return lambda value: fn(value) if _request_is_current() else None def _on_text_delta(text: str) -> None: agent._codex_streamed_text_parts.append(text) agent._fire_stream_delta(text) - def _on_event(event: Any) -> None: # TTFB watchdog and activity touch — once per SSE event. + def _on_reasoning_delta(text: str) -> None: + agent._fire_reasoning_delta(text) + + def _on_commentary_message(text: str) -> None: + agent._fire_streamed_codex_commentary(text) + + def _on_event(event: Any) -> None: + # TTFB watchdog and activity touch — runs once per SSE event. agent._codex_stream_last_event_ts = time.time() agent._touch_activity("receiving stream response") - def _interrupt_or_superseded() -> bool: - # A retired request must NOT break out of the consume loop (that returns a partial ``final`` with - # status "completed"); raise so the watchdog's TimeoutError is seen. - if not _request_is_current(): - raise TimeoutError("Codex Responses stream request retired before terminal response") - return bool(agent._interrupt_requested) - - def _open_codex_stream(next_api_kwargs: dict[str, Any]): - stream_kwargs = _sanitize_consumer_codex_request(agent, next_api_kwargs) - stream_kwargs["stream"] = True - return active_client.responses.create(**_bypass_sdk_request_transform(stream_kwargs)) - - def _log_failure(exc: BaseException) -> None: - request_body_bytes, exception_chain = _codex_request_failure_details(exc) - logger.warning("Codex Responses request failed: serialized_request_body_bytes=%s stream_opened=%s " - "exception_chain=%s model=%s", "unknown" if request_body_bytes is None else request_body_bytes, - str(writer_token["value"] is not None).lower(), exception_chain, getattr(agent, "model", "unknown")) - - def _codex_stream_created(_raw_stream: Any) -> None: - # Claim the delta sink for THIS attempt; a newer attempt supersedes this token. - writer_token["value"] = claim_stream_writer(agent) - - def _accept_codex_chunk(_chunk: Any) -> bool: - token = writer_token["value"] - if token is None or stream_writer_is_current(agent, token): - return True - logger.warning("Codex streaming attempt superseded by a newer stream; stopping consumption to preserve " - "the single-writer invariant (model=%s).", api_kwargs.get("model", "unknown")) - return False - - def _drain_for_finalizer(event_stream: Any) -> None: - # ``final`` is already assembled; draining only lets Relay run its finalizer. A transport error - # here must NOT discard the completed, already-billed response. - try: - for _ignored in event_stream: - pass - except (*transport_errors, _APIConnectionError) as exc: - if not isinstance(exc, transport_errors): - _log_failure(exc) - logger.warning("Codex Responses stream transport finalization failed after a terminal response was already " - "received; returning the completed response instead of retrying. %s error=%s", - agent._client_log_context(), exc) - - def _close_event_stream(event_stream: Any) -> None: - close_fn = getattr(event_stream, "close", None) # None while connect never succeeded - try: - if callable(close_fn): - close_fn() - except Exception: - # A failed close can leave this connection checked out of the httpx pool while the caller - # reuse-caches the client; poison the slot so close really closes the pool. ``client is None`` - # is the shared primary client — never force-shut. - if client is not None: - agent._abort_request_openai_client(active_client, reason="codex_stream_close_failed") - show_commentary = getattr(agent, "show_commentary", True) - wants_commentary = getattr(agent, "interim_assistant_callback", None) is not None and show_commentary - on_commentary_message = _fenced(lambda text: agent._fire_streamed_codex_commentary(text)) if wants_commentary else None - call_role = ("delegated" if getattr(agent, "is_subagent", False) - else "fallback" if int(getattr(agent, "_fallback_index", 0) or 0) > 0 else "primary") for attempt in range(max_stream_retries + 1): if agent._interrupt_requested: raise InterruptedError("Agent interrupted before Codex stream retry") - intercepted_events: list = [] - writer_token["value"] = event_stream = None + + intercepted_events = [] + writer_token = {"value": None} + + def _open_codex_stream(next_api_kwargs: dict[str, Any]): + stream_kwargs = _sanitize_consumer_codex_request( + agent, + next_api_kwargs, + ) + stream_kwargs["stream"] = True + stream_kwargs = _bypass_sdk_request_transform(stream_kwargs) + from agent.llm_egress_runtime import dispatch_authorized_agent_request + + return dispatch_authorized_agent_request( + agent, + stream_kwargs, + lambda request: active_client.responses.create(**request), + ) + + def _codex_stream_created(_raw_stream: Any) -> None: + # Claim the delta sink for THIS physical attempt. A newer attempt + # supersedes this token and fences late deltas out of the turn. + writer_token["value"] = claim_stream_writer(agent) + + def _accept_codex_chunk(_chunk: Any) -> bool: + token = writer_token["value"] + if token is None or stream_writer_is_current(agent, token): + return True + logger.warning( + "Codex streaming attempt superseded by a newer stream; " + "stopping consumption to preserve the single-writer " + "invariant (model=%s).", + api_kwargs.get("model", "unknown"), + ) + return False + + def _finalize_codex_stream() -> Any: + return _consume_codex_event_stream( + list(intercepted_events), + model=api_kwargs.get("model"), + ) + try: - try: - event_stream = relay_llm.stream( - dict(api_kwargs), _open_codex_stream, - session_id=str(getattr(agent, "session_id", "") or ""), - name=str(getattr(agent, "provider", "") or "codex"), model_name=str(model or ""), - finalizer=lambda: _consume_codex_event_stream(list(intercepted_events), model=model), - on_stream_created=_codex_stream_created, on_chunk=intercepted_events.append, - chunk_adapter=lambda chunk: chunk, accept_chunk=_accept_codex_chunk, - completed_response_predicate=lambda r: bool(hasattr(r, "output") and not hasattr(r, "__iter__")), - metadata={"api_mode": "codex_responses", "call_role": call_role, "retry_count": attempt, - "api_request_id": getattr(agent, "_current_api_request_id", None)}, - defer_logical_completion=True, + event_stream = relay_llm.stream( + dict(api_kwargs), + _open_codex_stream, + session_id=str(getattr(agent, "session_id", "") or ""), + name=str(getattr(agent, "provider", "") or "codex"), + model_name=str(api_kwargs.get("model") or ""), + finalizer=_finalize_codex_stream, + on_stream_created=_codex_stream_created, + on_chunk=intercepted_events.append, + chunk_adapter=lambda chunk: chunk, + accept_chunk=_accept_codex_chunk, + completed_response_predicate=lambda response: bool( + hasattr(response, "output") and not hasattr(response, "__iter__") + ), + metadata={ + "api_mode": "codex_responses", + "api_request_id": getattr(agent, "_current_api_request_id", None), + "call_role": ( + "delegated" + if getattr(agent, "is_subagent", False) + else "fallback" + if int(getattr(agent, "_fallback_index", 0) or 0) > 0 + else "primary" + ), + "retry_count": attempt, + }, + defer_logical_completion=True, + ) + except ( + _httpx.RemoteProtocolError, + _httpx.ReadTimeout, + _httpx.ConnectError, + ConnectionError, + ) as exc: + if attempt < max_stream_retries: + logger.debug( + "Codex Responses stream connect failed (attempt %s/%s); " + "retrying. %s error=%s", + attempt + 1, + max_stream_retries + 1, + agent._client_log_context(), + exc, ) + continue + _log_codex_request_failure( + agent, + exc, + stream_opened=writer_token["value"] is not None, + ) + raise + except _APIConnectionError as exc: + _log_codex_request_failure( + agent, + exc, + stream_opened=writer_token["value"] is not None, + ) + raise + + def _interrupt_or_superseded() -> bool: + return bool(agent._interrupt_requested) + + try: + try: final = _consume_codex_event_stream( - event_stream, model=model, on_text_delta=_fenced(_on_text_delta), - on_reasoning_delta=_fenced(lambda text: agent._fire_reasoning_delta(text)), - on_commentary_message=on_commentary_message, on_first_delta=on_first_delta, - on_event=_fenced(_on_event), interrupt_check=_interrupt_or_superseded, + event_stream, + model=api_kwargs.get("model"), + on_text_delta=_on_text_delta, + on_reasoning_delta=_on_reasoning_delta, + on_commentary_message=( + _on_commentary_message + if ( + getattr(agent, "interim_assistant_callback", None) is not None + and getattr(agent, "show_commentary", True) + ) + else None + ), + on_first_delta=on_first_delta, + on_event=_on_event, + interrupt_check=_interrupt_or_superseded, ) - except transport_errors as exc: - if attempt >= max_stream_retries: - _log_failure(exc) - raise - logger.debug( - "Codex Responses stream connect failed (attempt %s/%s); retrying. %s error=%s" if event_stream is None - else "Codex Responses stream transport failed mid-iteration (attempt %s/%s); retrying. %s error=%s", - attempt + 1, max_stream_retries + 1, agent._client_log_context(), exc, + except (_httpx.RemoteProtocolError, _httpx.ReadTimeout, _httpx.ConnectError, ConnectionError) as exc: + if attempt < max_stream_retries: + logger.debug( + "Codex Responses stream transport failed mid-iteration " + "(attempt %s/%s); retrying. %s error=%s", + attempt + 1, max_stream_retries + 1, + agent._client_log_context(), exc, + ) + continue + _log_codex_request_failure( + agent, + exc, + stream_opened=writer_token["value"] is not None, ) - continue + raise except RuntimeError: - # "No terminal response"; Relay may still hold a finalizer-assembled response. - if event_stream is not None and event_stream.final_response is not None: + if event_stream.final_response is not None: return event_stream.final_response raise except _APIConnectionError as exc: - _log_failure(exc) + _log_codex_request_failure( + agent, + exc, + stream_opened=writer_token["value"] is not None, + ) raise + + # A terminal response has already been assembled at this point + # (``final`` is built), so a transport error while draining the + # rest of the iterator — done only to let Relay run its response + # finalizer — must NOT discard it or trigger a new physical + # request. Record it as a non-fatal finalization warning and + # still return the already-completed, already-billed response. if not agent._interrupt_requested: - _drain_for_finalizer(event_stream) + try: + for _ignored in event_stream: + pass + except ( + _httpx.RemoteProtocolError, + _httpx.ReadTimeout, + _httpx.ConnectError, + ConnectionError, + ) as exc: + logger.warning( + "Codex Responses stream transport finalization failed " + "after a terminal response was already received; " + "returning the completed response instead of " + "retrying. %s error=%s", + agent._client_log_context(), exc, + ) + except _APIConnectionError as exc: + _log_codex_request_failure( + agent, + exc, + stream_opened=writer_token["value"] is not None, + ) + logger.warning( + "Codex Responses stream transport finalization failed " + "after a terminal response was already received; " + "returning the completed response instead of " + "retrying. %s error=%s", + agent._client_log_context(), exc, + ) + if final.status in {"incomplete", "failed"}: - logger.warning("Codex Responses stream terminal status=%s " - "(incomplete_details=%s, error=%s, streamed_chars=%d). %s", - final.status, final.incomplete_details, final.error, - sum(len(p) for p in agent._codex_streamed_text_parts), agent._client_log_context()) + logger.warning( + "Codex Responses stream terminal status=%s " + "(incomplete_details=%s, error=%s, streamed_chars=%d). %s", + final.status, final.incomplete_details, final.error, + sum(len(p) for p in agent._codex_streamed_text_parts), + agent._client_log_context(), + ) + return final finally: - _close_event_stream(event_stream) - - -__all__ = [ - "run_codex_app_server_turn", "run_codex_stream", - "_consume_codex_event_stream", "make_codex_app_server_event_bridge", -] - + close_fn = getattr(event_stream, "close", None) + if callable(close_fn): + try: + close_fn() + except Exception: + # A failed close can leave this response's connection + # checked out of the httpx pool while the caller's finally + # reports a reuse-reason close (e.g. interrupt_check broke + # the event loop with collected output) — caching the + # client with the leaked connection. Poison the slot so + # that close really closes the pool (owner-thread abort; + # mirrors the chat-streaming interrupt-break handling). + # ``client is None`` means the shared primary client, + # which is never reuse-cached and must not have its + # sockets force-shut here. + if client is not None: + agent._abort_request_openai_client( + active_client, reason="codex_stream_close_failed" + ) -# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- -# Names external plugins imported from this module before the Sep 2026 decomposition. -# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). -# The whole block is removed by reverting the commit that added it. def run_codex_create_stream_fallback(agent, api_kwargs: dict, client: Any = None): """Backward-compatible alias for the unified event-driven path. @@ -986,4 +1849,12 @@ def run_codex_create_stream_fallback(agent, api_kwargs: dict, client: Any = None still reference it by name. """ return run_codex_stream(agent, api_kwargs, client=client) -# ---- END PLUGIN-COMPAT ---- + + +__all__ = [ + "run_codex_app_server_turn", + "run_codex_stream", + "run_codex_create_stream_fallback", + "_consume_codex_event_stream", + "make_codex_app_server_event_bridge", +] diff --git a/agent/coding_context.py b/agent/coding_context.py index 5a6b3be08db70..582488a172640 100644 --- a/agent/coding_context.py +++ b/agent/coding_context.py @@ -1,11 +1,52 @@ -"""Coding-context awareness: the single place that decides "are we coding?". - -In a code workspace on an interactive surface Hermes adopts a **coding posture**: a -frozen :class:`RuntimeMode` built from a :class:`ContextProfile` (pure data). The -system prompt reads ``system_prompt_parts()``; the toolset collapses ONLY under opt-in -``focus`` (never strips a user-enabled toolset). ``agent.coding_context``: ``auto`` -(default, prompt-only) / ``focus`` / ``on`` / ``off``. Resolved once, immutable; the -workspace snapshot is never re-probed per turn (cache safety). +"""Coding-context awareness — base Hermes, every interactive surface. + +When the user runs Hermes inside a code workspace (CLI, TUI, desktop app, or an +editor over ACP), Hermes shifts into a **coding posture**. This module is the +single place that decides whether we're in that posture and what it implies, +so the rest of the codebase never re-derives "are we coding?" on its own. + +Architecture — one seam, many consumers +---------------------------------------- +The posture is modelled as a frozen :class:`RuntimeMode` selected from a small +:class:`ContextProfile` registry (today: ``coding`` and ``general``). A profile +is *data* — it declares the toolset to collapse to, the operating brief to +inject, and hints for other domains (model routing, memory, subagents). Every +domain reads the same resolved object instead of probing git/config itself: + + * **System prompt** — ``RuntimeMode.system_blocks()`` → the operating brief + + a live git/workspace snapshot (``agent/system_prompt.py``). + * **Toolset** — ``RuntimeMode.toolset_selection()`` → the ``coding`` toolset + plus the user's enabled MCP servers (``cli.py`` / ``tui_gateway``). Only + under the opt-in ``focus`` mode: the default posture is prompt-only and + never touches the user's configured toolsets (toolsets like messaging / + smart-home / music are off-by-default anyway, and someone who explicitly + enabled image-gen or Spotify shouldn't lose it for being in a git repo). + * **Delegation** — subagents inherit the parent's toolset and run through the + same prompt builder, so the coding posture propagates to children for free. + * **Model / memory / compression** — declared on the profile + (``model_hint``, ``memory_policy``) as the extension seam; consumers read + ``mode.profile`` rather than re-deciding. + +Cache safety +------------ +The mode is resolved **once** and is immutable. The workspace snapshot is built +once at prompt-build time and baked into the *stable* system-prompt tier — never +re-probed per turn (that would shatter the prompt cache). Branch and dirty state +drift mid-session, so the brief tells the model to re-check with ``git`` before +acting on the snapshot. A ``/coding`` flip therefore only takes effect next +session (deferred), the same contract as ``/skills install`` vs ``--now``. + +Activation (config ``agent.coding_context``): + + * ``auto`` (default) — posture (brief + snapshot) on an interactive coding + surface sitting in a code workspace (git repo or recognised project root). + Prompt-only; toolsets and the skill index untouched. + * ``focus`` — like ``auto``, but additionally collapses the toolset to the + ``coding`` set + enabled MCP servers and demotes non-coding skill + categories to names-only in the prompt's skill index (no skill is ever + hidden). Explicit opt-in for a lean schema. + * ``on`` — force the posture anywhere (incl. non-workspaces). Prompt-only. + * ``off`` — disable entirely. """ from __future__ import annotations @@ -25,42 +66,108 @@ CODING_TOOLSET = "coding" -# Surfaces where ``auto`` may adopt the posture; messaging platforms are deliberately absent. +# Surfaces where a coding posture makes sense under ``auto``. Messaging +# platforms (telegram, discord, slack, …) are intentionally absent — a chat bot +# in a group is not pair-programming. INTERACTIVE_CODING_PLATFORMS = {"cli", "tui", "acp", "desktop", ""} -# Project-root signals (cheap filename checks) marking a code workspace even without git. + +# Project-root signals that mark a directory as a code workspace even when it +# isn't (yet) a git repo. Cheap filename checks — no parsing. _PROJECT_MARKERS = ( - "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "package.json", "tsconfig.json", "deno.json", - "Cargo.toml", "go.mod", "pom.xml", "build.gradle", "build.gradle.kts", "Gemfile", "composer.json", "mix.exs", - "pubspec.yaml", "CMakeLists.txt", "Makefile", "Dockerfile", "AGENTS.md", "CLAUDE.md", ".cursorrules", + "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", + "package.json", "tsconfig.json", "deno.json", + "Cargo.toml", "go.mod", "pom.xml", "build.gradle", "build.gradle.kts", + "Gemfile", "composer.json", "mix.exs", "pubspec.yaml", + "CMakeLists.txt", "Makefile", "Dockerfile", + "AGENTS.md", "CLAUDE.md", ".cursorrules", ) + # Agent-instruction files surfaced separately from manifests in the snapshot. _CONTEXT_FILES = ("AGENTS.md", "CLAUDE.md", ".cursorrules") -# Extensions that make a manifest-less git repo a *code* workspace (a `git init` notes folder is not). +# Source-file extensions that make a git repo a *code* workspace even with no +# manifest. Without this, `git init` on a notes/writing/research folder (a huge +# non-coding use case) would flip the whole session into the coding posture just +# for having a `.git`. A manifest still wins on its own (see `_PROJECT_MARKERS`). _CODE_EXTENSIONS = frozenset({ - ".py", ".pyi", ".ipynb", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".go", ".rs", ".java", ".kt", ".kts", - ".scala", ".rb", ".php", ".c", ".h", ".cc", ".cpp", ".hpp", ".cs", ".swift", ".m", ".mm", ".dart", ".ex", ".exs", - ".lua", ".sh", ".bash", ".zsh", ".sql", ".vue", ".svelte", ".r", ".jl", ".hs", ".clj", ".erl", ".pl", + ".py", ".pyi", ".ipynb", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", + ".go", ".rs", ".java", ".kt", ".kts", ".scala", ".rb", ".php", ".c", ".h", + ".cc", ".cpp", ".hpp", ".cs", ".swift", ".m", ".mm", ".dart", ".ex", ".exs", + ".lua", ".sh", ".bash", ".zsh", ".sql", ".vue", ".svelte", ".r", ".jl", + ".hs", ".clj", ".erl", ".pl", }) + +# Dirs never worth scanning for the code check (deps/build/vcs/venv noise). _CODE_SCAN_SKIP_DIRS = frozenset({ - ".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build", "target", ".next", ".turbo", "vendor", + ".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build", + "target", ".next", ".turbo", "vendor", }) + # Bounded sweep: a code workspace reveals itself in the first handful of entries. _CODE_SCAN_MAX_ENTRIES = 500 + + +def _has_code_files(root: Path) -> bool: + """Cheap, bounded check for source files in a repo's top two levels. + + Lets a git repo of loose scripts (no manifest) still read as a code + workspace while a bare notes/writing repo does not. Scans the root and its + immediate subdirectories only, capped at ``_CODE_SCAN_MAX_ENTRIES`` stats — + a handful of readdirs at session start, not a full walk. + """ + seen = 0 + stack = [(root, True)] + while stack: + directory, is_root = stack.pop() + try: + with os.scandir(directory) as entries: + for entry in entries: + seen += 1 + if seen > _CODE_SCAN_MAX_ENTRIES: + return False + name = entry.name + try: + if entry.is_file(): + if os.path.splitext(name)[1].lower() in _CODE_EXTENSIONS: + return True + elif is_root and entry.is_dir() and name not in _CODE_SCAN_SKIP_DIRS and not name.startswith("."): + stack.append((Path(entry.path), False)) + except OSError: + continue + except OSError: + continue + return False + # Lockfile → package manager, checked in priority order. _PY_LOCKFILES = (("uv.lock", "uv"), ("poetry.lock", "poetry"), ("Pipfile.lock", "pipenv")) _JS_LOCKFILES = ( - ("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("yarn.lock", "yarn"), ("package-lock.json", "npm"), + ("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), + ("yarn.lock", "yarn"), ("package-lock.json", "npm"), ) + # package.json scripts / Makefile targets worth surfacing as verify commands. _VERIFY_TARGETS = ("test", "tests", "lint", "typecheck", "check", "build", "fmt", "format") _MAX_VERIFY_COMMANDS = 8 _MAX_FACT_FILE_BYTES = 256 * 1024 + _GIT_TIMEOUT = 2.5 -# Per-model edit-format steering toward the `patch` mode each family was trained on (unknown -# families get nothing). GPT/Codex get V4A for ALL edits incl. single-file: codex-rs ships -# apply_patch as its ONLY editor. Anthropic and most open-weight coders were RL'd on str_replace -# editors. Substrings match the model id; aligned with TOOL_USE_ENFORCEMENT_MODELS. + + +# Per-model edit-format steering. Matching the edit tool format to how a model +# was trained reduces mistakes and wasted reasoning (OpenAI/Codex handle +# patch-style diffs best; Anthropic models — and most open-weight coding +# models, whose RL scaffolds use str_replace-style editors — do best with +# string-replacement). Our `patch` tool exposes both: mode="patch" (V4A +# multi-file) and mode="replace" (find-and-swap). We nudge each family toward +# its native format. Unknown families get nothing (the brief's neutral wording +# stands). Substrings match the model id; aligned with TOOL_USE_ENFORCEMENT_MODELS. +# +# GPT/Codex get V4A for ALL edits, single-file included: in codex-rs, +# apply_patch (V4A — apply_patch.lark) is the ONLY file editor, no +# str_replace-style tool exists, and the shipped model prompts say to use +# apply_patch even "for single file edits" — so a replace-mode nudge would +# steer those models toward a format their first-party harness never taught +# them. _EDIT_FORMAT_GUIDANCE: dict[str, tuple[tuple[str, ...], str]] = { "patch": ( ("gpt", "codex"), @@ -79,7 +186,34 @@ ), } -# Operating brief. Tool names referenced here are in the coding toolset and _HERMES_CORE_TOOLS. + +def _model_family(model: Optional[str]) -> Optional[str]: + """Classify a model id into an edit-format family key, or ``None``. + + Used to steer the coding posture toward the edit tool format a model was + trained on. Family-agnostic by design: an unrecognised model gets ``None`` + and the operating brief's neutral edit wording applies. + """ + if not model: + return None + lowered = model.lower() + for family, (needles, _line) in _EDIT_FORMAT_GUIDANCE.items(): + if any(n in lowered for n in needles): + return family + return None + + +def _edit_format_line(model: Optional[str]) -> str: + """The edit-format guidance line for this model's family (``""`` if none).""" + family = _model_family(model) + if family is None: + return "" + return _EDIT_FORMAT_GUIDANCE[family][1] + + +# Operating brief for the coding posture. Tool names referenced here (read_file, +# search_files, patch, write_file, terminal, todo) are in the coding toolset and +# in _HERMES_CORE_TOOLS, so they're present on every surface this fires on. CODING_AGENT_GUIDANCE = ( "You are a coding agent pairing with the user inside their codebase. " "Operate like a careful senior engineer.\n" @@ -119,7 +253,7 @@ "paths for the same flaw and fix the class, not just the reported site.\n" "- When fixing linter/type errors on a file, stop after about three " "attempts on the same file and ask the user rather than looping.\n" - "- Track multi-step work with `todo_list`. Reference code as `path:line` instead " + "- Track multi-step work with `todo`. Reference code as `path:line` instead " "of pasting whole files.\n" "\n" "Respect the user's repo: don't commit, push, or rewrite history unless " @@ -129,69 +263,161 @@ "`git branch` before relying on it. Be concise: lead with the change or " "answer, not a preamble." ) -_TODO_SENTENCE = ( - "- Track multi-step work with `todo_list`. Reference code as " - "`path:line` instead of pasting whole files." -) -_NO_TODO_SENTENCE = "- Reference code as `path:line` instead of pasting whole files." -# Clearly non-coding skill categories (deny-list; coding-adjacent and custom ones keep full entries). -_NON_CODING_SKILL_CATEGORIES = ( - "apple", "communication", "cooking", "creative", "email", "finance", "gaming", "gifs", "health", "media", - "music", "note-taking", "productivity", "shopping", "smart-home", "social-media", "travel", "yuanbao", -) -_MODE_ALIASES = { - **dict.fromkeys(("focus", "strict", "lean"), "focus"), - **dict.fromkeys(("on", "true", "yes", "1", "always"), "on"), - **dict.fromkeys(("off", "false", "no", "0", "never"), "off"), -} + + +# ── Context profiles (declarative posture definitions) ────────────────────── @dataclass(frozen=True) class ContextProfile: - """A named operating posture (pure data). ``toolset``: collapse target under ``focus`` - (``None`` keeps the platform default). ``compact_skill_categories``: DEMOTED to - names-only under ``focus`` — deny-list, never hidden, so recall keeps working.""" + """A named operating posture. Pure data — consumers read these fields. + + ``toolset`` — collapse to this toolset (+ enabled MCP) when no explicit + selection is pinned; ``None`` keeps the platform default. + ``guidance`` — operating brief injected into the stable system prompt; + ``""`` injects nothing. + ``model_hint`` — routing preference key for smart model routing + (extension seam; not yet consumed by the router). + ``memory_policy``— memory namespace/weighting hint (extension seam). + ``compact_skill_categories`` — skill categories DEMOTED to names-only in + the system-prompt skill index under the opt-in ``focus`` + mode. Never hidden: every skill name stays visible + (so memory-anchored recall keeps working) — only the + descriptions are dropped to cut index noise. Deny-list + semantics so unknown/custom categories keep full + entries. + """ name: str toolset: Optional[str] = None guidance: str = "" model_hint: Optional[str] = None + memory_policy: str = "default" compact_skill_categories: tuple[str, ...] = () +# Skill categories that are clearly not part of a coding workflow. Demoted to +# names-only in the prompt's skill index under the opt-in ``focus`` mode only +# (deny-list — anything not listed here, incl. custom user categories, keeps +# full entries). Coding-adjacent categories (devops, github, mcp, +# data-science, diagramming, research, security, …) are intentionally absent. +_NON_CODING_SKILL_CATEGORIES = ( + "apple", "communication", "cooking", "creative", "email", "finance", + "gaming", "gifs", "health", "media", "music", "note-taking", + "productivity", "shopping", "smart-home", "social-media", "travel", + "yuanbao", +) + + GENERAL_PROFILE = ContextProfile(name="general") CODING_PROFILE = ContextProfile( - name="coding", toolset=CODING_TOOLSET, guidance=CODING_AGENT_GUIDANCE, model_hint="coding", + name="coding", + toolset=CODING_TOOLSET, + guidance=CODING_AGENT_GUIDANCE, + model_hint="coding", + memory_policy="project", compact_skill_categories=_NON_CODING_SKILL_CATEGORIES, ) +_PROFILES: dict[str, ContextProfile] = { + GENERAL_PROFILE.name: GENERAL_PROFILE, + CODING_PROFILE.name: CODING_PROFILE, +} -# ── Detection helpers ─────────────────────────────────────────────────────── -def _model_family(model: Optional[str]) -> Optional[str]: - """Edit-format family key for a model id, or ``None`` (neutral wording applies).""" - lowered = (model or "").lower() - for family, (needles, _line) in _EDIT_FORMAT_GUIDANCE.items(): - if lowered and any(n in lowered for n in needles): - return family - return None +def get_profile(name: str) -> ContextProfile: + """Return a registered profile, falling back to ``general``.""" + return _PROFILES.get(name, GENERAL_PROFILE) -def _agent_config_value(config: Optional[dict[str, Any]], key: str, default: Any, *, readonly: bool) -> Any: - """``config["agent"][key]``, loading config when none was passed.""" +# ── Helpers ───────────────────────────────────────────────────────────────── + + +def _coding_mode(config: Optional[dict[str, Any]]) -> str: + """Return the normalized ``agent.coding_context`` mode (auto/focus/on/off).""" if config is None: try: - from hermes_cli.config import load_config, load_config_readonly - config = load_config_readonly() if readonly else load_config() + from hermes_cli.config import load_config_readonly + + config = load_config_readonly() except Exception: config = {} - return ((config or {}).get("agent", {}) or {}).get(key, default) + raw = ((config or {}).get("agent", {}) or {}).get("coding_context", "auto") + mode = str(raw).strip().lower() + if mode in {"focus", "strict", "lean"}: + return "focus" + if mode in {"on", "true", "yes", "1", "always"}: + return "on" + if mode in {"off", "false", "no", "0", "never"}: + return "off" + return "auto" + + +def guarded_prompt_enabled( + *, + platform: Optional[str] = None, + cwd: Optional[str | Path] = None, + provider: Optional[str] = None, + model: Optional[str] = None, + config: Optional[dict[str, Any]] = None, +) -> bool: + """Whether this session may use the explicitly opt-in local prompt profile. + The smaller profile is deliberately fail-closed. It is available only in + a focused coding workspace and only when the active provider/model pair + is an exact entry in ``agent.guarded_prompt_mode.routes``. + """ + if config is None: + try: + from hermes_cli.config import load_config_readonly + + config = load_config_readonly() + except Exception: + return False + agent_cfg = (config or {}).get("agent", {}) or {} + if not isinstance(agent_cfg, dict) or _coding_mode(config) != "focus": + return False + raw = agent_cfg.get("guarded_prompt_mode") + if not isinstance(raw, dict) or raw.get("enabled") is not True: + return False + routes = raw.get("routes") + if not isinstance(routes, (list, tuple)): + return False + provider_name = str(provider or "").strip().lower() + model_name = str(model or "").strip().lower() + allowed_routes = { + (str(route.get("provider") or "").strip().lower(), str(route.get("model") or "").strip().lower()) + for route in routes + if isinstance(route, dict) + } + if not provider_name or not model_name or (provider_name, model_name) not in allowed_routes: + return False + return resolve_runtime_mode( + platform=platform, cwd=cwd, config=config, model=model + ).is_coding -def _coding_mode(config: Optional[dict[str, Any]]) -> str: - """Normalized ``agent.coding_context`` mode (auto/focus/on/off).""" - raw = _agent_config_value(config, "coding_context", "auto", readonly=True) - return _MODE_ALIASES.get(str(raw).strip().lower(), "auto") + +def _coding_instructions(config: Optional[dict[str, Any]]) -> str: + """Standing operator instructions for the coding posture (config). + + ``agent.coding_instructions`` — a string or list of strings appended to the + coding brief as an extra stable system block, so a user can pin project-wide + coding-workflow rules (e.g. "for UI work don't run tsc/lint until I approve; + clean the diff before committing") without editing the shipped brief. + Cache-safe: resolved once per session into the stable system-prompt tier, + like the rest of the posture. + """ + if config is None: + try: + from hermes_cli.config import load_config + + config = load_config() + except Exception: + config = {} + raw = ((config or {}).get("agent", {}) or {}).get("coding_instructions", "") + if isinstance(raw, (list, tuple)): + return "\n".join(str(item).strip() for item in raw if str(item).strip()) + return str(raw or "").strip() def _resolve_cwd(cwd: Optional[str | Path]) -> Path: @@ -199,6 +425,7 @@ def _resolve_cwd(cwd: Optional[str | Path]) -> Path: return Path(cwd).expanduser() try: from agent.runtime_cwd import resolve_agent_cwd + return resolve_agent_cwd() except Exception: return Path(os.getcwd()) @@ -206,7 +433,10 @@ def _resolve_cwd(cwd: Optional[str | Path]) -> Path: def _git_root(cwd: Path) -> Optional[Path]: current = cwd.resolve() - return next((p for p in (current, *current.parents) if (p / ".git").exists()), None) + for parent in [current, *current.parents]: + if (parent / ".git").exists(): + return parent + return None def _home() -> Optional[Path]: @@ -217,94 +447,95 @@ def _home() -> Optional[Path]: def _marker_root(cwd: Path) -> Optional[Path]: - """Nearest ancestor (≤6 levels) that looks like a project root, or ``None``. ``$HOME`` - and the shared temp root are skipped: a Makefile/AGENTS.md in the home dir is global - config, and a stray manifest in /tmp must not flip every session under it.""" + """Nearest ancestor that looks like a project root, or ``None``. + + Walks up at most a few levels so a manifest in the workspace root counts + even when the user is in a subdirectory. ``$HOME`` itself is skipped — a + Makefile or AGENTS.md sitting in the home directory is global user config, + not a project-root signal. + """ current = cwd.resolve() + home = _home() + # Shared world-writable temp roots are never project roots: a stray + # manifest in /tmp (left by any process) must not flip every session + # whose cwd lives under the temp dir into the coding posture. Same + # reasoning as the $HOME skip below. try: temp_root = Path(tempfile.gettempdir()).resolve() except Exception: temp_root = None - skip = (_home(), temp_root) - for parent in (current, *current.parents)[:7]: - if parent not in skip and any((parent / marker).exists() for marker in _PROJECT_MARKERS): - return parent + for depth, parent in enumerate([current, *current.parents]): + if depth > 6: + break + if parent == home or (temp_root is not None and parent == temp_root): + continue + for marker in _PROJECT_MARKERS: + if (parent / marker).exists(): + return parent return None -def _has_code_files(root: Path) -> bool: - """Bounded check for source files in the root and its immediate subdirs.""" - seen = 0 - stack = [(root, True)] - while stack: - directory, is_root = stack.pop() - try: - entries = os.scandir(directory) - except OSError: - continue - with entries: - for entry in entries: - seen += 1 - if seen > _CODE_SCAN_MAX_ENTRIES: - return False - try: - if entry.is_file(): - if os.path.splitext(entry.name)[1].lower() in _CODE_EXTENSIONS: - return True - elif is_root and entry.is_dir() and entry.name not in _CODE_SCAN_SKIP_DIRS and not entry.name.startswith("."): - stack.append((Path(entry.path), False)) - except OSError: - continue - return False +def _detect_profile_name(mode: str, platform: str, cwd_str: str) -> str: + """Resolve which profile applies. + + ``auto``/``focus``: coding when the surface is interactive AND the cwd is a + code workspace (a git repo or a recognised project root). ``on``: always + coding. ``off``: always general. + A git repo rooted at ``$HOME`` (the dotfiles pattern) is NOT a workspace + signal — without the guard, every session anywhere under a dotfiles-managed + home directory would silently flip to the coding posture. -def _detect_profile(mode: str, platform: str, cwd: Path) -> ContextProfile: - """``auto``/``focus``: coding when the surface is interactive AND the cwd is a code - workspace (project root, or a git repo that actually holds code; a repo rooted at - ``$HOME`` is NOT a signal). ``on``/``off`` force. Not memoized: one gateway serves many cwds.""" + Detection is intentionally not memoized: it's a handful of ``stat`` calls, + and callers resolve the mode once per session anyway. Caching here would + risk a stale posture if a long-lived process (gateway/TUI) serves sessions + from different working directories. + """ if mode == "off": - return GENERAL_PROFILE + return GENERAL_PROFILE.name if mode == "on": - return CODING_PROFILE + return CODING_PROFILE.name if platform and platform.strip().lower() not in INTERACTIVE_CODING_PLATFORMS: - return GENERAL_PROFILE + return GENERAL_PROFILE.name + cwd = Path(cwd_str) + # A recognized project root (manifest / AGENTS.md / .cursorrules) is a code + # workspace on its own — cheap stat checks, no scan. if _marker_root(cwd) is not None: - return CODING_PROFILE + return CODING_PROFILE.name git_root = _git_root(cwd) - if git_root is not None and git_root != _home() and _has_code_files(git_root): - return CODING_PROFILE - return GENERAL_PROFILE - - -def _enabled_mcp_servers(config: Optional[dict[str, Any]]) -> list[str]: - """Names of MCP servers the user has enabled — kept in the coding posture.""" - try: - from hermes_cli.config import read_raw_config - from hermes_cli.tools_config import _parse_enabled_flag - servers = read_raw_config().get("mcp_servers") or {} - return [ - str(name) for name, cfg in servers.items() - if isinstance(cfg, dict) and _parse_enabled_flag(cfg.get("enabled", True), default=True) - ] - except Exception: - return [] + if git_root is not None and git_root == _home(): + git_root = None # dotfiles repo at $HOME — not a code workspace + # A bare git repo only counts when it actually holds code, so `git init` on a + # notes/writing/research folder stays in the general posture. + if git_root is not None and _has_code_files(git_root): + return CODING_PROFILE.name + return GENERAL_PROFILE.name # ── RuntimeMode (the seam) ────────────────────────────────────────────────── + @dataclass(frozen=True) class RuntimeMode: - """The resolved operating posture for a session; immutable, built once via - :func:`resolve_runtime_mode` and never re-resolved mid-session (prompt cache). - ``config_mode``: normalized ``agent.coding_context`` (toolset collapse gated on - ``focus``); ``model``: steers edit-format guidance only; ``instructions``: - ``agent.coding_instructions``.""" + """The resolved operating posture for a session. Immutable by construction. + + Built once via :func:`resolve_runtime_mode` and consumed by every domain + that cares about the coding/general distinction. Never mutate or re-resolve + mid-session — that would break the prompt cache. + """ profile: ContextProfile surface: str cwd: Path + # The normalized ``agent.coding_context`` mode this posture was resolved + # under (auto/focus/on/off). Toolset collapse is gated on ``focus``. config_mode: str = "auto" + # The model id this session runs (e.g. "anthropic/claude-opus-4.8"). Used + # only to steer edit-format guidance toward the model's family — see + # ``_edit_format_line``. Fixed for the session, so cache-safe. model: Optional[str] = None + # Standing operator instructions (``agent.coding_instructions``), appended + # as an extra stable system block. Empty unless the user configures it. instructions: str = "" @property @@ -316,105 +547,242 @@ def is_coding(self) -> bool: return self.profile.name == CODING_PROFILE.name def toolset_selection(self, config: Optional[dict[str, Any]] = None) -> Optional[list[str]]: - """Toolset list (only under ``focus``), or ``None`` to keep the platform default. Callers - apply it only when the user hasn't pinned a selection (``--toolsets``, ``HERMES_TUI_TOOLSETS``).""" - if self.config_mode != "focus" or self.profile.toolset is None: + """Toolset list for this posture, or ``None`` to keep the platform default. + + Non-``None`` only under the opt-in ``focus`` mode. The default posture + is prompt-only: most strippable toolsets are off-by-default anyway, and + a user who explicitly enabled one (image-gen for frontend/game assets, + messaging for build notifications, …) keeps it while coding. + + Callers apply this only when the user hasn't pinned an explicit + selection (``--toolsets``, ``HERMES_TUI_TOOLSETS``, …); they never + override a pin. Returns the profile's toolset plus enabled MCP servers. + """ + if self.config_mode != "focus": + return None + if self.profile.toolset is None: return None return [self.profile.toolset, *_enabled_mcp_servers(config)] - def system_prompt_parts(self, valid_tool_names=None) -> tuple[list[str], list[str], list[str]]: - """Return (prefix, workspace, trailing) posture blocks in the historical flat order — - brief, snapshot, operator instructions — so prompt assembly can put a cache boundary - before the snapshot without changing persisted bytes. The brief carries the model-family - edit-format nudge (one cached string); ``valid_tool_names`` drops the ``todo_list`` - sentence when that tool isn't loaded; operator instructions ride their own block so - the brief stays byte-stable.""" + def system_prompt_parts( + self, valid_tool_names=None + ) -> tuple[list[str], list[str], list[str]]: + """Return prefix, workspace, and trailing posture blocks separately. + + The operating brief carries a model-family edit-format nudge appended + to it (one cached string, not a separate block) so the model is steered + toward the `patch` mode it handles best — see ``_edit_format_line``. + + ``valid_tool_names`` (when provided) tailors the brief to the session's + toolset: the ``todo`` tracking sentence is dropped when the todo tool + isn't loaded (e.g. Blank Slate), so the brief never references a tool + the model can't call. The toolset is fixed at session construction, + so the rendered brief is deterministic per session — cache-safe. + + The three lists preserve the historical flat prompt order: the brief, + the live workspace snapshot, then configured operator instructions. + Prompt assembly can therefore put a cache boundary before the snapshot + without changing the persisted system-prompt bytes. + """ if not self.is_coding: return [], [], [] prefix: list[str] = [] + workspace_parts: list[str] = [] + trailing: list[str] = [] if self.profile.guidance: brief = self.profile.guidance - if valid_tool_names is not None and "todo_list" not in valid_tool_names: - brief = brief.replace(_TODO_SENTENCE, _NO_TODO_SENTENCE) - family = _model_family(self.model) - if family is not None: - brief = f"{brief}\n{_EDIT_FORMAT_GUIDANCE[family][1]}" + if valid_tool_names is not None and "todo" not in valid_tool_names: + brief = brief.replace( + "- Track multi-step work with `todo`. Reference code as " + "`path:line` instead of pasting whole files.", + "- Reference code as `path:line` instead of pasting " + "whole files.", + ) + edit_line = _edit_format_line(self.model) + if edit_line: + brief = f"{brief}\n{edit_line}" prefix.append(brief) workspace = build_coding_workspace_block(self.cwd) - trailing = [f"Operator instructions (from config):\n{self.instructions}"] if self.instructions else [] - return prefix, [workspace] if workspace else [], trailing + if workspace: + workspace_parts.append(workspace) + # Operator instructions ride their own block so the brief (block 0) stays + # byte-stable and cache-keyed independently of user config. + if self.instructions: + trailing.append(f"Operator instructions (from config):\n{self.instructions}") + return prefix, workspace_parts, trailing def system_blocks(self) -> list[str]: - """Posture blocks as one flat list in historical order.""" + """Return posture blocks in their historical display order. + + ``system_prompt_parts`` is the cache-aware API. This compatibility + helper retains the public flat list for callers outside prompt assembly. + """ prefix, workspace, trailing = self.system_prompt_parts() return [*prefix, *workspace, *trailing] def compact_skill_categories(self) -> frozenset[str]: - """Skill categories to demote to names-only in the skill index. Gated on ``focus`` - like the toolset collapse (index changes under ``auto`` proved too surprising). - Demoted, never hidden: pruning caused silent capability loss.""" + """Skill categories to demote to names-only in the prompt's skill index. + + Gated on the opt-in ``focus`` mode, like the toolset collapse: the + default posture leaves the skill index untouched. Users who didn't ask + for a lean prompt keep full entries for every category — index changes + under ``auto`` proved too surprising in practice, even names-only ones + (a demoted description is information the model no longer weighs when + deciding what to load). + + Demoted — never hidden — even under ``focus``. An earlier revision + fully pruned these categories from the index, which caused silent + capability loss in a real workflow: agent-created skills are the + model's accumulated project memory (server-ops runbooks, learned + pitfalls, …), and models do not reliably reach for ``skills_list`` to + rediscover what the index stopped showing them. Names-only keeps every + skill loadable on recall while still cutting the description noise. + """ if not self.is_coding or self.config_mode != "focus": return frozenset() return frozenset(self.profile.compact_skill_categories) def resolve_runtime_mode( - *, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None, + *, + platform: Optional[str] = None, + cwd: Optional[str | Path] = None, + config: Optional[dict[str, Any]] = None, model: Optional[str] = None, ) -> RuntimeMode: - """Resolve the operating posture once (a handful of ``stat`` calls) — the single entry - point every domain should call; the result is safe to hold for the session. ``model`` - only steers edit-format guidance; ``agent.coding_instructions`` (str or list) becomes - the trailing block so a user can pin workflow rules without editing the shipped brief.""" + """Resolve the operating posture once. Cheap — a handful of ``stat`` calls. + + This is the single entry point every domain should call. The returned + object is immutable and safe to cache for the session. Detection itself is + intentionally *not* memoized (see ``_detect_profile_name``) so a long-lived + process can't pin a stale posture; callers resolve once per session and + hold the result. ``model`` is recorded only to steer edit-format guidance; + it never affects detection. + """ resolved_cwd = _resolve_cwd(cwd) mode = _coding_mode(config) - raw = _agent_config_value(config, "coding_instructions", "", readonly=False) - items = raw if isinstance(raw, (list, tuple)) else [raw or ""] - instructions = "\n".join(str(item).strip() for item in items if str(item).strip()) + name = _detect_profile_name( + mode, (platform or "").strip().lower(), str(resolved_cwd) + ) return RuntimeMode( - profile=_detect_profile(mode, (platform or "").strip().lower(), resolved_cwd), + profile=get_profile(name), surface=platform or "", cwd=resolved_cwd, config_mode=mode, model=model, - instructions=instructions, + instructions=_coding_instructions(config), ) -# ── Functional API (thin wrappers over RuntimeMode) ────────────────────────── +# ── Back-compat surface (thin wrappers over RuntimeMode) ──────────────────── -def is_coding_context(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> bool: + +def is_coding_context( + *, + platform: Optional[str] = None, + cwd: Optional[str | Path] = None, + config: Optional[dict[str, Any]] = None, +) -> bool: """Whether Hermes should operate in its coding posture right now.""" return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).is_coding -def coding_selection(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> Optional[list[str]]: - """Toolset selection for the coding posture (``None`` unless ``focus`` and active).""" - return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).toolset_selection(config) +def coding_selection( + *, + platform: Optional[str] = None, + cwd: Optional[str | Path] = None, + config: Optional[dict[str, Any]] = None, +) -> Optional[list[str]]: + """Toolset selection for the coding posture. + + ``None`` unless the user opted into ``focus`` mode AND the posture is + active — the default coding posture never overrides configured toolsets. + """ + return resolve_runtime_mode( + platform=platform, cwd=cwd, config=config + ).toolset_selection(config) + + +def coding_system_blocks( + *, + platform: Optional[str] = None, + cwd: Optional[str | Path] = None, + config: Optional[dict[str, Any]] = None, + model: Optional[str] = None, +) -> list[str]: + """Stable system-prompt blocks for the current posture (empty when general). + + ``model`` steers the brief's edit-format nudge toward the model's family. + """ + return resolve_runtime_mode( + platform=platform, cwd=cwd, config=config, model=model + ).system_blocks() def coding_system_prompt_parts( - *, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None, - model: Optional[str] = None, valid_tool_names=None, + *, + platform: Optional[str] = None, + cwd: Optional[str | Path] = None, + config: Optional[dict[str, Any]] = None, + model: Optional[str] = None, + valid_tool_names=None, ) -> tuple[list[str], list[str], list[str]]: """Return coding prefix, workspace snapshot, and trailing guidance.""" - mode = resolve_runtime_mode(platform=platform, cwd=cwd, config=config, model=model) - return mode.system_prompt_parts(valid_tool_names=valid_tool_names) + return resolve_runtime_mode( + platform=platform, cwd=cwd, config=config, model=model + ).system_prompt_parts(valid_tool_names=valid_tool_names) + + +def coding_compact_skill_categories( + *, + platform: Optional[str] = None, + cwd: Optional[str | Path] = None, + config: Optional[dict[str, Any]] = None, +) -> frozenset[str]: + """Skill categories the active posture demotes to names-only in the index. + + Empty outside the coding posture and outside the opt-in ``focus`` mode — + the default posture never touches the skill index. Under ``focus``, + demoted — never hidden: every skill name stays in the index and remains + loadable via ``skill_view`` / ``skills_list``; only descriptions are + dropped. + """ + return resolve_runtime_mode( + platform=platform, cwd=cwd, config=config + ).compact_skill_categories() -def coding_compact_skill_categories(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> frozenset[str]: - """Skill categories the active posture demotes to names-only (empty outside ``focus``).""" - return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).compact_skill_categories() +def _enabled_mcp_servers(config: Optional[dict[str, Any]]) -> list[str]: + """Names of MCP servers the user has enabled — kept in the coding posture. + + MCP servers (figma, browser, tophat, …) are explicitly configured and part + of the coding workflow, not noise to strip. + """ + try: + from hermes_cli.config import read_raw_config + from hermes_cli.tools_config import _parse_enabled_flag + + servers = read_raw_config().get("mcp_servers") or {} + return [ + str(name) + for name, cfg in servers.items() + if isinstance(cfg, dict) + and _parse_enabled_flag(cfg.get("enabled", True), default=True) + ] + except Exception: + return [] # ── git/workspace probe ───────────────────────────────────────────────────── + def _git(cwd: Path, *args: str) -> str: - """``git -C `` → stripped stdout, or ``""`` on any failure. bounded_git_probe - bounds post-kill cleanup on Windows — plain ``subprocess.run(timeout=...)`` deadlocked - when a killed git left a suspended descendant holding the pipe handles. + """``git -C `` → stripped stdout, or ``""`` on any failure. - See #66037. + Uses the shared :func:`bounded_git_probe` so the post-kill cleanup is bounded + on Windows — a plain ``subprocess.run(timeout=...)`` here deadlocked the agent + turn inside ``build_coding_workspace_block`` when a killed git left a suspended + descendant holding the pipe handles (issue #66037). """ return bounded_git_probe(["git", "-C", str(cwd), *args], timeout=_GIT_TIMEOUT) @@ -424,18 +792,23 @@ def _parse_status(porcelain: str) -> tuple[dict[str, str], dict[str, int]]: branch: dict[str, str] = {} counts = {"staged": 0, "modified": 0, "untracked": 0, "conflicts": 0} for line in porcelain.splitlines(): - if line.startswith(("# branch.head", "# branch.upstream")): - parts = line.split(maxsplit=2) - branch[parts[1].removeprefix("branch.")] = parts[-1] + if line.startswith("# branch.head"): + branch["head"] = line.split(maxsplit=2)[-1] + elif line.startswith("# branch.upstream"): + branch["upstream"] = line.split(maxsplit=2)[-1] elif line.startswith("# branch.ab"): parts = line.split() branch["ahead"], branch["behind"] = parts[2].lstrip("+"), parts[3].lstrip("-") elif line.startswith(("1 ", "2 ")): xy = line.split(maxsplit=2)[1] - counts["staged"] += xy[0] != "." - counts["modified"] += xy[1] != "." - elif line.startswith(("u ", "? ")): - counts["conflicts" if line[0] == "u" else "untracked"] += 1 + if xy[0] != ".": + counts["staged"] += 1 + if xy[1] != ".": + counts["modified"] += 1 + elif line.startswith("u "): + counts["conflicts"] += 1 + elif line.startswith("? "): + counts["untracked"] += 1 return branch, counts @@ -451,7 +824,12 @@ def _read_small(path: Path) -> str: @dataclass(frozen=True) class ProjectFacts: - """Structured project facts — exposed so non-prompt consumers (desktop verify UI) don't re-detect.""" + """Structured project facts — the model's verify loop, detected once. + + The same data that feeds the workspace snapshot, exposed structurally so + non-prompt consumers (e.g. the desktop verify UI) read it instead of + re-detecting and drifting from the prompt. + """ manifests: list[str] package_managers: list[str] @@ -460,7 +838,17 @@ class ProjectFacts: def detect_project_facts(root: Path) -> ProjectFacts: - """Detect manifests, package manager(s), verify commands, context files (single source of truth).""" + """Detect manifests, package manager(s), verify commands, and context files. + + Cheap: stat calls plus reads of a couple of small files. The single source + of truth for both the prompt snapshot (:func:`_project_facts`) and the + gateway's ``project.facts`` — so the UI never re-sniffs verify commands. + """ + manifests = [m for m in _PROJECT_MARKERS if m not in _CONTEXT_FILES and (root / m).is_file()] + package_managers = list( + dict.fromkeys(pm for lock, pm in (*_PY_LOCKFILES, *_JS_LOCKFILES) if (root / lock).is_file()) + ) + verify: list[str] = [] if (root / "scripts" / "run_tests.sh").is_file(): verify.append("scripts/run_tests.sh") @@ -474,32 +862,56 @@ def detect_project_facts(root: Path) -> ProjectFacts: if (root / "pytest.ini").is_file() or "[tool.pytest" in _read_small(root / "pyproject.toml"): verify.append("pytest") makefile = _read_small(root / "Makefile") - verify.extend( - f"make {name}" for name in _VERIFY_TARGETS - if makefile and re.search(rf"^{re.escape(name)}\s*:", makefile, re.MULTILINE) - ) + if makefile: + verify.extend( + f"make {name}" for name in _VERIFY_TARGETS + if re.search(rf"^{re.escape(name)}\s*:", makefile, re.MULTILINE) + ) + return ProjectFacts( - manifests=[m for m in _PROJECT_MARKERS if m not in _CONTEXT_FILES and (root / m).is_file()], - package_managers=list(dict.fromkeys( - pm for lock, pm in (*_PY_LOCKFILES, *_JS_LOCKFILES) if (root / lock).is_file() - )), + manifests=manifests, + package_managers=package_managers, verify_commands=list(dict.fromkeys(verify))[:_MAX_VERIFY_COMMANDS], context_files=[c for c in _CONTEXT_FILES if (root / c).is_file()], ) -def _workspace_roots(cwd: Optional[str | Path]) -> tuple[Optional[Path], Optional[Path]]: - """(git_root, workspace_root) for *cwd*; workspace root is git root else marker root.""" - resolved = _resolve_cwd(cwd) - git_root = _git_root(resolved) - return git_root, git_root or _marker_root(resolved) +def _project_facts(root: Path) -> list[str]: + """Render :func:`detect_project_facts` as workspace-snapshot lines. + + Hands the model its *verify loop* up front — which manifest, which package + manager, and the exact test/lint/build commands — instead of making it + rediscover them every session. Built once at prompt-build time; the string + output must stay byte-stable to preserve the prompt cache. + """ + f = detect_project_facts(root) + facts: list[str] = [] + + if f.manifests: + line = f"- Project: {', '.join(f.manifests[:6])}" + if f.package_managers: + line += f" ({'/'.join(f.package_managers)})" + facts.append(line) + if f.verify_commands: + facts.append(f"- Verify: {'; '.join(f.verify_commands)}") + if f.context_files: + facts.append(f"- Context files: {', '.join(f.context_files)}") + + return facts def project_facts_for(cwd: Optional[str | Path] = None) -> Optional[dict[str, Any]]: - """Structured project facts for ``cwd`` (desktop verify UI) — ``None`` outside a workspace.""" - _, root = _workspace_roots(cwd) + """Structured project facts for ``cwd`` — ``None`` outside a workspace. + + Same detection the system-prompt snapshot uses (git root, else marker root), + exposed for non-prompt consumers (the desktop verify UI) so they never + re-derive "are we coding?" or duplicate the verify-command sniffing. + """ + resolved = _resolve_cwd(cwd) + root = _git_root(resolved) or _marker_root(resolved) if root is None: return None + f = detect_project_facts(root) return { "root": str(root), @@ -511,77 +923,54 @@ def project_facts_for(cwd: Optional[str | Path] = None) -> Optional[dict[str, An def build_coding_workspace_block(cwd: Optional[str | Path] = None) -> str: - """Workspace snapshot for the system prompt (empty outside a workspace): git state when - in a repo, plus project facts — so marker-only (non-git) projects still get one.""" - git_root, root = _workspace_roots(cwd) + """Workspace snapshot for the system prompt (empty outside a workspace). + + Git state (branch/status/commits) when the cwd is in a repo, plus detected + project facts (manifest, package manager, verify commands, context files) + — so marker-only (non-git) projects still get a snapshot. + """ + resolved = _resolve_cwd(cwd) + git_root = _git_root(resolved) + root = git_root or _marker_root(resolved) if root is None: return "" - lines = [ - "Workspace (snapshot at session start — re-check with `git` before acting on it):", - f"- Root: {root}", - ] + + lines = ["Workspace (snapshot at session start — re-check with `git` before acting on it):"] + lines.append(f"- Root: {root}") + if git_root is not None: branch, counts = _parse_status(_git(root, "status", "--porcelain=2", "--branch")) head = branch.get("head", "") - if head == "(detached)": + if head and head != "(detached)": + line = f"- Branch: {head}" + if branch.get("upstream"): + line += f" \u2192 {branch['upstream']}" + ahead, behind = branch.get("ahead", "0"), branch.get("behind", "0") + if ahead != "0" or behind != "0": + line += f" (ahead {ahead}, behind {behind})" + lines.append(line) + elif head == "(detached)": lines.append("- Branch: (detached HEAD)") - elif head: - ahead, behind = branch.get("ahead", "0"), branch.get("behind", "0") - upstream = f" \u2192 {branch['upstream']}" if branch.get("upstream") else "" - ab = f" (ahead {ahead}, behind {behind})" if upstream and (ahead, behind) != ("0", "0") else "" - lines.append(f"- Branch: {head}{upstream}{ab}") - - # Linked worktree: say so (branches/stashes are shared state) but do NOT expose - # the primary tree path — a second absolute path makes the model run commands + + # Linked worktree: the per-worktree git dir differs from the shared common dir. + # We surface the fact that it's a worktree (so the model knows branches/stashes + # are shared state) but deliberately do NOT expose the primary tree path — + # giving the model a second absolute path causes it to sometimes run commands # in the wrong directory. git_dir, common_dir = _git(root, "rev-parse", "--git-dir"), _git(root, "rev-parse", "--git-common-dir") if git_dir and common_dir and Path(git_dir).resolve() != Path(common_dir).resolve(): lines.append("- Worktree: linked (git state shared with primary tree)") - dirty = [f"{n} {label}" for label, n in counts.items() if n] + dirty = [f"{n} {label}" for label, n in ( + ("staged", counts["staged"]), ("modified", counts["modified"]), + ("untracked", counts["untracked"]), ("conflicts", counts["conflicts"]), + ) if n] lines.append(f"- Status: {', '.join(dirty) if dirty else 'clean'}") recent = _git(root, "log", "-3", "--pretty=%h %s") if recent: - lines.extend(["- Recent commits:", *(f" {c}" for c in recent.splitlines())]) + lines.append("- Recent commits:") + lines.extend(f" {c}" for c in recent.splitlines()) - f = detect_project_facts(root) - if f.manifests: - managers = f" ({'/'.join(f.package_managers)})" if f.package_managers else "" - lines.append(f"- Project: {', '.join(f.manifests[:6])}{managers}") - if f.verify_commands: - lines.append(f"- Verify: {'; '.join(f.verify_commands)}") - if f.context_files: - lines.append(f"- Context files: {', '.join(f.context_files)}") + lines.extend(_project_facts(root)) return "\n".join(lines) - - -# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- -# Names external plugins imported from this module before the Sep 2026 decomposition. -# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). -# The whole block is removed by reverting the commit that added it. - -def coding_system_blocks( - *, - platform: Optional[str] = None, - cwd: Optional[str | Path] = None, - config: Optional[dict[str, Any]] = None, - model: Optional[str] = None, -) -> list[str]: - """Stable system-prompt blocks for the current posture (empty when general). - - ``model`` steers the brief's edit-format nudge toward the model's family. - """ - return resolve_runtime_mode( - platform=platform, cwd=cwd, config=config, model=model - ).system_blocks() - -_PROFILES: dict[str, ContextProfile] = { - GENERAL_PROFILE.name: GENERAL_PROFILE, - CODING_PROFILE.name: CODING_PROFILE, -} - -def get_profile(name: str) -> ContextProfile: - """Return a registered profile, falling back to ``general``.""" - return _PROFILES.get(name, GENERAL_PROFILE) -# ---- END PLUGIN-COMPAT ---- diff --git a/agent/context_references.py b/agent/context_references.py index 5911ff7f848a7..6fb81e90dd2bc 100644 --- a/agent/context_references.py +++ b/agent/context_references.py @@ -168,10 +168,15 @@ def parse_context_references(message: str) -> list[ContextReference]: def preprocess_context_references( message: str, *, cwd: str | Path, context_length: int, url_fetcher: UrlFetcher = None, allowed_root: str | Path | None = None, + source_provenance_registry=None, session_id: str | None = None, + turn_id: str | None = None, request_id: str | None = None, + policy_digest: str | None = None, ) -> ContextReferenceResult: """Sync wrapper; safe both without a loop (CLI) and inside a running loop (gateway).""" coro = preprocess_context_references_async( - message, cwd=cwd, context_length=context_length, url_fetcher=url_fetcher, allowed_root=allowed_root + message, cwd=cwd, context_length=context_length, url_fetcher=url_fetcher, allowed_root=allowed_root, + source_provenance_registry=source_provenance_registry, session_id=session_id, + turn_id=turn_id, request_id=request_id, policy_digest=policy_digest, ) try: asyncio.get_running_loop() @@ -185,6 +190,9 @@ def preprocess_context_references( async def preprocess_context_references_async( message: str, *, cwd: str | Path, context_length: int, url_fetcher: UrlFetcher = None, allowed_root: str | Path | None = None, + source_provenance_registry=None, session_id: str | None = None, + turn_id: str | None = None, request_id: str | None = None, + policy_digest: str | None = None, ) -> ContextReferenceResult: refs = parse_context_references(message) if not refs: @@ -195,11 +203,15 @@ async def preprocess_context_references_async( # Expand concurrently (each ref is independent; several @url: refs would otherwise # serialize web_extract round-trips). gather preserves order, so warnings/blocks # are assembled in ref order; the token-budget check runs once afterwards. + provenance_context = _build_source_provenance_context( + source_provenance_registry, session_id=session_id, turn_id=turn_id, + request_id=request_id, policy_digest=policy_digest, + ) hard_limit = max(1, int(context_length * 0.50)) soft_limit = max(1, int(context_length * 0.25)) tasks = ( _expand_reference(ref, cwd_path, url_fetcher=url_fetcher, allowed_root=allowed_root_path, - max_inline_tokens=hard_limit) + max_inline_tokens=hard_limit, provenance_context=provenance_context) for ref in refs ) expanded = await asyncio.gather(*tasks) @@ -241,10 +253,14 @@ async def preprocess_context_references_async( async def _expand_reference( ref: ContextReference, cwd: Path, *, url_fetcher: UrlFetcher = None, allowed_root: Path | None = None, max_inline_tokens: int | None = None, + provenance_context=None, ) -> Expansion: try: if ref.kind in ("file", "folder"): - return _expand_path_reference(ref, cwd, allowed_root=allowed_root, max_inline_tokens=max_inline_tokens) + return _expand_path_reference( + ref, cwd, allowed_root=allowed_root, max_inline_tokens=max_inline_tokens, + provenance_context=provenance_context, + ) if ref.kind in _GIT_REFERENCE_ARGS: git_args = _GIT_REFERENCE_ARGS[ref.kind](ref) return _expand_git_reference(ref, cwd, git_args, "git " + " ".join(git_args)) @@ -267,7 +283,7 @@ async def _expand_reference( def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Path | None = None, - max_inline_tokens: int | None = None) -> Expansion: + max_inline_tokens: int | None = None, provenance_context=None) -> Expansion: """``@file:`` / ``@folder:``: resolve, allow-check, then inline text / binary stub / listing.""" is_folder = ref.kind == "folder" path = _resolve_path(cwd, ref.target, allowed_root=allowed_root) @@ -283,9 +299,12 @@ def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Pa # A bare "not supported" warning was a dead end (the model gave up); the file IS # on disk where the agent's tools run, so hand it an actionable block instead. return None, _binary_reference_block(ref, path) - text = path.read_text(encoding="utf-8") + raw_bytes = None if ref.line_start is not None: - text = "\n".join(text.splitlines()[max(ref.line_start - 1, 0):ref.line_end or ref.line_start]) + raw_bytes = _read_bounded_reference_slice(path, ref.line_start, ref.line_end or ref.line_start) + text = raw_bytes.decode("utf-8") + else: + text = path.read_text(encoding="utf-8") lang = _FENCE_LANGUAGES.get(path.suffix.lower(), "") text_tokens = estimate_tokens_rough(text) # Check BEFORE building the fenced block: an oversized file is not going to be @@ -296,6 +315,16 @@ def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Pa # block alone carries the message (same shape as the binary path) — a warning # would duplicate it in "--- Context Warnings ---". return None, _oversized_text_reference_block(ref, path, text_tokens) + if provenance_context is not None and raw_bytes is not None: + source_path = Path(os.path.expanduser(ref.target)) + if not source_path.is_absolute(): + source_path = cwd / source_path + provenance_context.registry.issue_file_slice( + path=source_path, line_start=ref.line_start, line_end=ref.line_end or ref.line_start, + content=raw_bytes, session_id=provenance_context.session_id, + turn_id=provenance_context.turn_id, request_id=provenance_context.request_id, + policy_digest=provenance_context.policy_digest, + ) return None, f"📄 {ref.raw} ({text_tokens} tokens)\n```{lang}\n{text}\n```" @@ -347,29 +376,55 @@ def _resolve_path(cwd: Path, target: str, *, allowed_root: Path | None = None) - def _ensure_reference_path_allowed(path: Path) -> None: - """Refuse credential/internal paths. Fails CLOSED: the gateway feeds untrusted remote text here.""" from hermes_constants import get_hermes_home - home, hermes_home = Path(os.path.expanduser("~")).resolve(), get_hermes_home().resolve() - blocked_exact = {home / rel for rel in _SENSITIVE_HOME_FILES} | {hermes_home / ".env"} - blocked_dirs = [home / rel for rel in _SENSITIVE_HOME_DIRS] + [hermes_home / rel for rel in _SENSITIVE_HERMES_DIRS] + home = Path(os.path.expanduser("~")).resolve() + hermes_home = get_hermes_home().resolve() + + blocked_exact = {home / rel for rel in _SENSITIVE_HOME_FILES} + blocked_exact.add(hermes_home / ".env") + blocked_dirs = [home / rel for rel in _SENSITIVE_HOME_DIRS] + blocked_dirs.extend(hermes_home / rel for rel in _SENSITIVE_HERMES_DIRS) + if path in blocked_exact: raise ValueError("path is a sensitive credential file and cannot be attached") - if any(_is_under(path, blocked_dir) for blocked_dir in blocked_dirs): + + for blocked_dir in blocked_dirs: + try: + path.relative_to(blocked_dir) + except ValueError: + continue raise ValueError("path is a sensitive credential or internal Hermes path and cannot be attached") - # Anchor to the canonical read deny-list (agent/file_safety.get_read_block_error): the - # narrow list above never caught auth.json, .anthropic_oauth.json, mcp-tokens/, webhook - # secrets or project .env files, and it grows automatically with that deny-list. + + # Anchor to the canonical read deny-list (agent/file_safety.get_read_block_error), + # the single source of truth used by the file/terminal read path. The narrow + # list above predates that guard and never caught the real credential stores: + # provider keys (auth.json), Anthropic OAuth tokens (.anthropic_oauth.json), + # MCP OAuth material (mcp-tokens/), webhook HMAC secrets, and project-local + # .env files. That gap matters because the gateway feeds UNTRUSTED remote + # message text into reference expansion, so `@file:~/.hermes/auth.json` from a + # chat peer would otherwise read the operator's keys straight into context. + # Routing through the canonical guard closes the gap today and keeps this path + # protected automatically whenever that deny-list grows. try: from agent.file_safety import get_read_block_error - blocked = get_read_block_error(str(path)) is not None + + if get_read_block_error(str(path)) is not None: + raise ValueError( + "path is a sensitive credential or internal Hermes path and cannot be attached" + ) except ValueError: raise except Exception: - # If the canonical lookup fails, falling through would re-open the exact hole this - # guard closes; a spurious block is recoverable, a leaked credential is not. - raise ValueError("path could not be verified against the credential deny-list and cannot be attached") - if blocked: - raise ValueError("path is a sensitive credential or internal Hermes path and cannot be attached") + # Fail CLOSED on the security path. This guard exists specifically to + # cover credential stores the narrow list above misses (auth.json, + # .anthropic_oauth.json, mcp-tokens/, ...). If the canonical lookup + # ever fails, silently falling through would re-open that exact hole — + # the gateway feeds untrusted remote text here, so a probe could then + # attach the operator's keys. Refuse instead: a spurious block on a + # legitimate file is a recoverable annoyance; a leaked credential is not. + raise ValueError( + "path could not be verified against the credential deny-list and cannot be attached" + ) def _strip_trailing_punctuation(value: str) -> str: @@ -495,3 +550,55 @@ def _file_metadata(path: Path) -> str: except Exception: pass return f"{path.stat().st_size} bytes" + + +def _build_source_provenance_context( + registry, + *, + session_id: str | None, + turn_id: str | None, + request_id: str | None, + policy_digest: str | None, +): + """Return a trusted grant context only when the whole identity is present.""" + + if registry is None or not all( + isinstance(value, str) and value + for value in (session_id, turn_id, request_id, policy_digest) + ): + return None + from agent.source_provenance import SourceProvenanceContext, SourceProvenanceRegistry + + if not isinstance(registry, SourceProvenanceRegistry): + return None + return SourceProvenanceContext( + registry, + session_id, + turn_id, + request_id, + policy_digest, + ) + + +def _read_bounded_reference_slice(path: Path, line_start: int, line_end: int) -> bytes: + """Read only the requested exact line interval for a provenance candidate.""" + + from agent.source_provenance import MAX_SOURCE_SLICE_BYTES, MAX_SOURCE_SLICE_LINES + + if line_start < 1 or line_end < line_start or line_end - line_start + 1 > MAX_SOURCE_SLICE_LINES: + raise ValueError("file reference line range is not bounded") + selected: list[bytes] = [] + byte_count = 0 + with path.open("rb") as handle: + for line_number, raw_line in enumerate(handle, start=1): + if line_number < line_start: + continue + if line_number > line_end: + break + byte_count += len(raw_line) + if byte_count > MAX_SOURCE_SLICE_BYTES: + raise ValueError("file reference slice exceeds the byte limit") + selected.append(raw_line) + if len(selected) != line_end - line_start + 1: + raise ValueError("file reference line range is unavailable") + return b"".join(selected) diff --git a/agent/cross_process_file_lock.py b/agent/cross_process_file_lock.py new file mode 100644 index 0000000000000..f9d05b3c7179e --- /dev/null +++ b/agent/cross_process_file_lock.py @@ -0,0 +1,69 @@ +"""Portable blocking cross-process file lock used by security ledgers.""" + +from __future__ import annotations + +from contextlib import contextmanager +import os +from pathlib import Path +from typing import Iterator + +try: # POSIX + import fcntl as _fcntl +except ImportError: # pragma: no cover - exercised by import simulation + _fcntl = None + +try: # Windows + import msvcrt as _msvcrt +except ImportError: # pragma: no cover - POSIX + _msvcrt = None + + +def secure_file_descriptor_permissions(fd: int) -> None: + """Tighten a descriptor when the platform exposes ``os.fchmod``. + + Windows Python 3.11/3.12 lacks ``os.fchmod``; secure creation flags and + the owning user's ACL remain the platform boundary there. + """ + + fchmod = getattr(os, "fchmod", None) + if fchmod is not None: + fchmod(fd, 0o600) + + +@contextmanager +def exclusive_file_lock(path: Path) -> Iterator[None]: + """Hold one OS-backed lock file across all Hermes processes.""" + + try: + if path.is_symlink(): + raise OSError("cross-process lock path must not be a symlink") + except OSError: + raise + flags = os.O_CREAT | os.O_RDWR + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + fd = os.open(path, flags, 0o600) + try: + secure_file_descriptor_permissions(fd) + if _fcntl is not None: + _fcntl.flock(fd, _fcntl.LOCK_EX) + elif _msvcrt is not None: # pragma: no cover - Windows + if os.fstat(fd).st_size == 0: + os.write(fd, b"\0") + os.lseek(fd, 0, os.SEEK_SET) + _msvcrt.locking(fd, _msvcrt.LK_LOCK, 1) + else: + raise OSError("cross-process file locking is unavailable") + yield + finally: + try: + if _fcntl is not None: + _fcntl.flock(fd, _fcntl.LOCK_UN) + elif _msvcrt is not None: # pragma: no cover - Windows + os.lseek(fd, 0, os.SEEK_SET) + _msvcrt.locking(fd, _msvcrt.LK_UNLCK, 1) + finally: + os.close(fd) + + +__all__ = ["exclusive_file_lock", "secure_file_descriptor_permissions"] diff --git a/agent/error_classifier.py b/agent/error_classifier.py index 7bf3b8716f15d..c44708fd0c650 100644 --- a/agent/error_classifier.py +++ b/agent/error_classifier.py @@ -40,6 +40,7 @@ class FailoverReason(enum.Enum): model_not_found = "model_not_found" # 404 or invalid model — fallback to different model provider_policy_blocked = "provider_policy_blocked" # Aggregator account data/privacy policy excluded the only endpoint content_policy_blocked = "content_policy_blocked" # Provider safety filter rejected this prompt — don't retry unchanged + egress_policy_blocked = "egress_policy_blocked" # deterministic remote-policy denial; local fallback only format_error = "format_error" # 400 bad request — abort or strip + retry invalid_encrypted_content = "invalid_encrypted_content" # Responses replay blob rejected — strip replay state and retry multimodal_tool_content_unsupported = "multimodal_tool_content_unsupported" # Provider rejected list-type content in tool messages (e.g. Xiaomi MiMo) — downgrade to text and retry @@ -598,6 +599,19 @@ def classify_api_error( approx_tokens: int = 0, context_length: int = 200000, num_messages: int = 0, ) -> ClassifiedError: """Classify an API error into a structured recovery recommendation (see ``_STAGES``).""" + from agent.llm_egress_firewall import EgressBlocked + + if isinstance(error, EgressBlocked): + return ClassifiedError( + reason=FailoverReason.egress_policy_blocked, + provider=provider or None, + model=model or None, + message="remote request denied by local egress policy", + error_context={"reason_codes": error.decision.reason_codes}, + retryable=False, + should_fallback=True, + ) + status_code = _extract_status_code(error) # Copilot/GitHub Models RateLimitError may not set .status_code; force 429. if status_code is None and type(error).__name__ == "RateLimitError": diff --git a/agent/kanban_stop.py b/agent/kanban_stop.py index 5f4669bdb8506..4de2bb88bfac4 100644 --- a/agent/kanban_stop.py +++ b/agent/kanban_stop.py @@ -1,45 +1,156 @@ -"""Turn-end guard for kanban workers, which must end with ``kanban_complete`` or -``kanban_block``. Some models narrate the next step and stop with no tool calls; -Hermes treats that as a clean exit → ``rc=0`` → dispatcher ``protocol_violation``. -Policy-only: return a bounded synthetic nudge so the loop continues instead of exiting. +"""Turn-end guard for kanban workers. + +Kanban workers must end with a terminal board transition. Models +(especially GLM / Qwen families) sometimes narrate the next step +("Let me write the report now") and stop with ``finish_reason=stop`` and no +tool calls. Hermes treats that as a clean exit → ``rc=0`` → dispatcher +``protocol_violation``. + +This module is policy-only: when a kanban worker tries to finish without a +terminal board tool, return a bounded synthetic nudge so the conversation +loop continues instead of exiting. """ from __future__ import annotations +import json import os from typing import Any, Iterable, Optional -_TERMINAL_KANBAN_TOOLS = frozenset({"kanban_complete", "kanban_block"}) +_TERMINAL_KANBAN_TOOLS = frozenset( + { + "kanban_complete", + "kanban_block", + "kanban_request_review", + "kanban_request_changes", + } +) _DEFAULT_MAX_ATTEMPTS = 2 +_MAX_REVIEW_SUMMARY_CHARS = 4000 + + +def _configured_review_profile() -> str | None: + """Return an installed independent reviewer configured for stop handoffs.""" + + configured = (os.environ.get("HERMES_KANBAN_REVIEWER_PROFILE") or "").strip() + if not configured: + try: + from hermes_cli.config import load_config + + kanban = load_config().get("kanban") or {} + configured = str(kanban.get("reviewer_profile") or "").strip() + except Exception: + return None + if not configured: + return None + try: + from hermes_constants import get_default_hermes_root + + profile_dir = get_default_hermes_root() / "profiles" / configured + return configured if profile_dir.is_dir() else None + except Exception: + return None def kanban_stop_nudge_enabled() -> bool: - """On when ``HERMES_KANBAN_TASK`` is set, unless ``HERMES_KANBAN_STOP_NUDGE`` disables it.""" - if (os.environ.get("HERMES_KANBAN_STOP_NUDGE") or "").strip().lower() in {"0", "false", "no", "off"}: + """Return whether the kanban stop-guard is active for this process. + + On when ``HERMES_KANBAN_TASK`` is set (dispatcher-spawned worker), unless + ``HERMES_KANBAN_STOP_NUDGE`` explicitly disables it. + """ + env = os.environ.get("HERMES_KANBAN_STOP_NUDGE") + if env is not None and env.strip().lower() in {"0", "false", "no", "off"}: return False - return bool((os.environ.get("HERMES_KANBAN_TASK") or "").strip()) + task = (os.environ.get("HERMES_KANBAN_TASK") or "").strip() + return bool(task) def _tool_call_name(tc: Any) -> str: - """Tool name from a dict or object tool call (``function.name`` first, then ``name``).""" if isinstance(tc, dict): fn = tc.get("function") - return str((fn.get("name") if isinstance(fn, dict) else tc.get("name")) or "") + if isinstance(fn, dict): + return str(fn.get("name") or "") + return str(tc.get("name") or "") fn = getattr(tc, "function", None) - return str((getattr(fn, "name", "") if fn is not None else getattr(tc, "name", "")) or "") + if fn is not None: + return str(getattr(fn, "name", "") or "") + return str(getattr(tc, "name", "") or "") def session_called_kanban_terminal(messages: Iterable[dict] | None) -> bool: """True if this conversation already invoked a terminal kanban tool.""" - for msg in filter(lambda m: isinstance(m, dict), messages or ()): + if not messages: + return False + for msg in messages: + if not isinstance(msg, dict): + continue role = msg.get("role") - if role == "assistant" and any( - _tool_call_name(tc) in _TERMINAL_KANBAN_TOOLS for tc in msg.get("tool_calls") or [] + if role == "assistant": + for tc in msg.get("tool_calls") or []: + if _tool_call_name(tc) in _TERMINAL_KANBAN_TOOLS: + return True + elif role == "tool": + name = str(msg.get("name") or "") + if name in _TERMINAL_KANBAN_TOOLS: + return True + return False + + +def successful_kanban_terminal_transition( + *, + messages: Iterable[dict] | None, + tool_calls: Iterable[Any] | None, +) -> bool: + """Return whether this worker's current tool batch durably transitioned it. + + The conversation loop calls this only after the executor has persisted + every tool-result row. Match the current batch by tool-call id and require + the canonical Kanban ``{"ok": true}`` response; merely attempting a + terminal tool (or receiving an error) must not stop the worker before it + can correct the handoff. + """ + if not kanban_stop_nudge_enabled(): + return False + try: + from agent.delegation_context import is_dispatcher_owned_worker_context + + if not is_dispatcher_owned_worker_context(): + return False + except Exception: + return False + + terminal_ids: set[str] = set() + for tool_call in tool_calls or []: + if _tool_call_name(tool_call) not in _TERMINAL_KANBAN_TOOLS: + continue + if isinstance(tool_call, dict): + call_id = tool_call.get("id") or tool_call.get("tool_call_id") + else: + call_id = getattr(tool_call, "id", None) + if call_id: + terminal_ids.add(str(call_id)) + if not terminal_ids: + return False + + for message in messages or []: + if not isinstance(message, dict) or message.get("role") != "tool": + continue + if str(message.get("tool_call_id") or "") not in terminal_ids: + continue + if str(message.get("name") or message.get("tool_name") or "") not in ( + _TERMINAL_KANBAN_TOOLS ): - return True - if role == "tool" and str(msg.get("name") or "") in _TERMINAL_KANBAN_TOOLS: + continue + content = message.get("content") + if not isinstance(content, str): + continue + try: + payload = json.loads(content) + except (json.JSONDecodeError, TypeError): + continue + if isinstance(payload, dict) and payload.get("ok") is True: return True return False @@ -51,13 +162,17 @@ def build_kanban_stop_nudge( max_attempts: int = _DEFAULT_MAX_ATTEMPTS, task_id: Optional[str] = None, ) -> Optional[str]: - """Synthetic follow-up when a kanban worker exits without a terminal tool; ``None`` when - the guard should not fire (not a kanban worker, already completed/blocked, budget exhausted).""" - if ( - not kanban_stop_nudge_enabled() - or attempts >= max_attempts - or session_called_kanban_terminal(messages) - ): + """Return a synthetic follow-up when a kanban worker exits without a terminal tool. + + Returns ``None`` when the guard should not fire (not a kanban worker, + already completed, blocked, or handed off across review, or nudge budget + exhausted). + """ + if not kanban_stop_nudge_enabled(): + return None + if attempts >= max_attempts: + return None + if session_called_kanban_terminal(messages): return None tid = (task_id or os.environ.get("HERMES_KANBAN_TASK") or "").strip() or "this task" @@ -76,4 +191,73 @@ def build_kanban_stop_nudge( ) -__all__ = ["build_kanban_stop_nudge", "kanban_stop_nudge_enabled", "session_called_kanban_terminal"] +def reconcile_kanban_stop_to_review( + *, + messages: Iterable[dict] | None, + final_response: Any, + attempts: int, + max_attempts: int = _DEFAULT_MAX_ATTEMPTS, +) -> bool: + """Safely terminate a narrated worker after its nudge budget is spent. + + The stop guard already gave the model a bounded same-session opportunity + to call a terminal board tool. If it still returns useful text, route + that text through the *existing* ``kanban_request_review`` handler instead + of letting the process exit cleanly while its card remains ``running``. + + This deliberately requests review rather than completing the task: the + final prose is evidence for a reviewer, never authority to infer success. + The normal handler retains task/run ownership checks, redaction, and the + goal-mode acceptance judge. Any rejection or exception leaves lifecycle + ownership with the dispatcher and returns ``False``. + """ + if not kanban_stop_nudge_enabled(): + return False + if attempts < max_attempts: + return False + if session_called_kanban_terminal(messages): + return False + response_text = str(final_response or "").strip() + if not response_text: + return False + + bounded = response_text[:_MAX_REVIEW_SUMMARY_CHARS] + reviewer = _configured_review_profile() + if reviewer is None: + # A reviewerless handoff is not autonomous: the same implementer gets + # claimed from the review lane and tends to block while asking for a + # human verdict. Leave lifecycle ownership with the dispatcher so the + # attempt is recorded as a protocol violation and can follow normal + # bounded retry/watchdog policy instead. + return False + summary = ( + f"Automatic terminal handoff after {attempts} unanswered Kanban stop " + f"nudges. Worker final output:\n\n{bounded}" + ) + try: + from tools.kanban_tools import _handle_request_review + + raw = _handle_request_review( + { + "summary": summary, + "reviewer": reviewer, + "metadata": { + "source": "kanban_stop_guard", + "terminal_nudges": attempts, + "completion_inferred": False, + }, + } + ) + payload = json.loads(raw) if isinstance(raw, str) else raw + return bool(isinstance(payload, dict) and payload.get("ok") is True) + except Exception: + return False + + +__all__ = [ + "build_kanban_stop_nudge", + "kanban_stop_nudge_enabled", + "reconcile_kanban_stop_to_review", + "session_called_kanban_terminal", + "successful_kanban_terminal_transition", +] diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py new file mode 100644 index 0000000000000..817239fa660ac --- /dev/null +++ b/agent/llm_egress_firewall.py @@ -0,0 +1,1534 @@ +"""Source-bound policy checks for outbound LLM requests. + +The firewall is deliberately transport-agnostic. Callers hand it the final +logical request and resolved route immediately before invoking a provider. +It returns an immutable allow decision, or raises :class:`EgressBlocked` with +an immutable block decision. +""" + +from __future__ import annotations + +import base64 +import binascii +import ipaddress +import json +import math +import os +import re +import stat +from dataclasses import asdict, dataclass, replace +from enum import StrEnum +from hmac import compare_digest +from hashlib import sha256 +from pathlib import Path +from typing import Any, Mapping, Sequence +from urllib.parse import urlsplit + +from agent.file_safety import get_read_block_error +from agent.cross_process_file_lock import ( + exclusive_file_lock, + secure_file_descriptor_permissions, +) +from agent.redact import redact_sensitive_text + + +class DestinationClass(StrEnum): + """Trust class for an LLM destination.""" + + LOCAL_PROCESS = "local_process" + LOOPBACK = "loopback" + REMOTE = "remote" + UNKNOWN = "unknown" + + +@dataclass(frozen=True, slots=True) +class SourceGrant: + """Immutable authorization for one exact, already-read file slice.""" + + canonical_path: Path + display_path: str + line_start: int + line_end: int + content_sha256: str + byte_count: int + session_id: str + turn_id: str + request_id: str + policy_digest: str + + +@dataclass(frozen=True, slots=True) +class LiteralSegment: + """Application-owned literal text for a typed outbound request.""" + + text: str + + +@dataclass(frozen=True, slots=True) +class SanitizedSegment: + """Non-source text that must still pass final secret and encoding scans.""" + + text: str + + +@dataclass(frozen=True, slots=True) +class UntrustedProvenanceSegment: + """Content-free marker for tool bytes with no trusted origin proof.""" + + content_sha256: str + + +@dataclass(frozen=True, slots=True) +class ValidatedToolSyntaxSegment: + """Strictly parsed syntax emitted by a protected local tool result.""" + + text: str + syntax_kind: str + + +@dataclass(frozen=True, slots=True) +class SourceBoundSegment: + """Opaque reference whose text is loaded only from a verified grant.""" + + source_grant_digest: str + + +@dataclass(frozen=True, slots=True) +class SourcePresentationSegment: + """Trusted deterministic presentation of one verified source grant.""" + + source_grant_digest: str + text: str + presentation_kind: str + + +@dataclass(frozen=True, slots=True) +class OutboundText: + """Ordered typed segments that construct one outbound JSON string.""" + + segments: tuple[ + LiteralSegment + | SanitizedSegment + | ValidatedToolSyntaxSegment + | SourceBoundSegment + | SourcePresentationSegment + | UntrustedProvenanceSegment, + ..., + ] + + +@dataclass(frozen=True, slots=True) +class TypedOutboundRequest: + """Remote request recipe; no independent raw string leaf is permitted.""" + + payload: Mapping[str, Any] + session_id: str + turn_id: str + request_id: str + policy_digest: str + + +@dataclass(frozen=True, slots=True) +class EgressDecision: + """Content-free result of one egress preflight.""" + + allowed: bool + destination_class: DestinationClass + provider: str + model: str + payload_sha256: str + serialized_bytes: int + estimated_tokens: int + source_grant_count: int + source_segment_count: int + session_id: str + turn_id: str + request_id: str + policy_digest: str + reason_codes: tuple[str, ...] = () + base_url: str = "" + api_mode: str = "" + grant_digests: tuple[str, ...] = () + + +class EgressBlocked(RuntimeError): + """Raised when the final request is not authorized for its destination.""" + + def __init__(self, decision: EgressDecision): + self.decision = decision + reasons = ",".join(decision.reason_codes) or "policy_denied" + super().__init__(f"LLM egress blocked: {reasons}") + + +class SanitizedTextRejected(ValueError): + """Raised when remote text cannot earn the sanitized segment type.""" + + def __init__(self, reason_code: str): + self.reason_code = reason_code + super().__init__(f"sanitized remote text rejected: {reason_code}") + + +@dataclass(frozen=True, slots=True) +class AuthorizedEgress: + """Immutable exact bytes that a provider callback is authorized to send.""" + + decision: EgressDecision + payload_bytes: bytes + + @property + def allowed(self) -> bool: + return self.decision.allowed + + @property + def destination_class(self) -> DestinationClass: + return self.decision.destination_class + + @property + def reason_codes(self) -> tuple[str, ...]: + return self.decision.reason_codes + + def verify_payload(self, candidate: bytes) -> bytes: + """Return the authorized bytes or reject a post-preflight mutation.""" + + if not isinstance(candidate, bytes) or not compare_digest( + sha256(candidate).hexdigest(), + self.decision.payload_sha256, + ): + raise EgressBlocked( + replace( + self.decision, + allowed=False, + reason_codes=("payload_digest_mismatch",), + ) + ) + return self.payload_bytes + + +_SAFE_ID = re.compile(r"^[A-Za-z0-9_.:@/-]{0,256}$") +_LOCAL_PROCESS_MODES = frozenset({"local_process", "in_process"}) +_BASE64_CANDIDATE = re.compile( + r"(? DestinationClass: + """Classify without DNS, provider-name, or private-network trust. + + Only an explicit in-process mode or a numeric loopback literal is local. + LAN, Tailscale, container DNS, ``localhost``, and other hostnames retain + remote policy. Missing or malformed endpoint data is unknown. + """ + + del provider # Provider labels are not a security boundary. + mode = str(api_mode or "").strip().lower() + if mode in _LOCAL_PROCESS_MODES: + return DestinationClass.LOCAL_PROCESS + if not isinstance(base_url, str) or not base_url.strip(): + return DestinationClass.UNKNOWN + try: + parsed = urlsplit(base_url.strip()) + if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc: + return DestinationClass.UNKNOWN + # ``hostname`` does not validate the port. Accessing ``port`` is + # load-bearing: urllib deliberately raises for non-numeric and + # out-of-range values that must never inherit loopback trust. + try: + parsed.port + except ValueError: + return DestinationClass.UNKNOWN + if parsed.netloc.rsplit("@", 1)[-1].endswith(":"): + return DestinationClass.UNKNOWN + host = parsed.hostname + if not host: + return DestinationClass.UNKNOWN + try: + address = ipaddress.ip_address(host) + except ValueError: + return DestinationClass.REMOTE + return DestinationClass.LOOPBACK if address.is_loopback else DestinationClass.REMOTE + except (TypeError, ValueError): + return DestinationClass.UNKNOWN + + +def _route_value(route: Any, name: str, default: Any = None) -> Any: + if isinstance(route, Mapping): + return route.get(name, default) + return getattr(route, name, default) + + +def _request_identity(request: Mapping[str, Any], name: str) -> str: + value = request.get(name, "") + return value if isinstance(value, str) else str(value) + + +def _receipt_identifier(value: str) -> str: + """Keep ordinary correlation IDs while hashing unsafe or sensitive labels.""" + + try: + safe = ( + _SAFE_ID.fullmatch(value) is not None + and not value.startswith(("/", "~")) + and redact_sensitive_text( + value, + force=True, + redact_url_credentials=True, + ) + == value + ) + except Exception: + safe = False + return value if safe else f"sha256:{sha256(value.encode('utf-8')).hexdigest()}" + + +def source_grant_digest(grant: SourceGrant) -> str: + """Return the opaque identity used by a source-segment manifest.""" + + bound_fields = { + "canonical_path": str(grant.canonical_path), + "display_path": grant.display_path, + "line_start": grant.line_start, + "line_end": grant.line_end, + "content_sha256": grant.content_sha256, + "byte_count": grant.byte_count, + "session_id": grant.session_id, + "turn_id": grant.turn_id, + "request_id": grant.request_id, + "policy_digest": grant.policy_digest, + } + encoded = json.dumps(bound_fields, separators=(",", ":"), sort_keys=True).encode("utf-8") + return sha256(encoded).hexdigest() + + +def static_literal_sha256(text: str) -> str: + """Hash one exact UTF-8 static literal for a policy allowlist.""" + + if not isinstance(text, str): + raise TypeError("static literal must be text") + return sha256(text.encode("utf-8")).hexdigest() + + +def validate_tool_syntax(text: str, syntax_kind: str) -> str: + """Revalidate one complete protected tool-result syntax atom.""" + + grammar = _VALIDATED_TOOL_SYNTAX.get(syntax_kind) + if not isinstance(text, str) or grammar is None or grammar.fullmatch(text) is None: + raise ValueError("invalid_tool_syntax_segment") + if _contains_secret(text) or _contains_private_absolute_path(text): + raise ValueError("invalid_tool_syntax_segment") + return text + + +def _canonical_base64_candidate(candidate: str) -> bool: + """Recognize bounded canonical encodings without flagging ordinary IDs.""" + + if candidate in _PROTOCOL_GRAMMAR_ATOMS: + return False + if not 4 <= len(candidate) <= _MAX_BASE64_CANDIDATE_CHARS: + return False + # Short alphabetic words frequently round-trip mathematically as + # unpadded Base64 (for example "ordinary" and "review"). Require an + # encoding signal for short candidates; long all-alpha blobs remain + # suspicious even without padding. + if len(candidate) < 24 and not any( + character.isdigit() or character in "=+/-_" for character in candidate + ) and not candidate.isupper(): + return False + # Short, word-like URL-safe slugs are common model/provider identifiers. + # Keep genuinely encoding-shaped values such as ``-_8A`` eligible for the + # canonical decoder below. + if ( + len(candidate) < 16 + and any(character in "-_" for character in candidate) + and candidate[0].isalnum() + and candidate[-1].isalnum() + and sum(character.isalpha() for character in candidate) >= 2 + ): + return False + unpadded = candidate.rstrip("=") + if "=" in unpadded or len(unpadded) % 4 == 1: + return False + padded = unpadded + "=" * (-len(unpadded) % 4) + encoded = padded.encode("ascii") + for altchars in (None, b"-_"): + try: + decoded = base64.b64decode(encoded, altchars=altchars, validate=True) + except (binascii.Error, ValueError): + continue + canonical_padded = ( + base64.b64encode(decoded) + if altchars is None + else base64.urlsafe_b64encode(decoded) + ).decode("ascii") + if candidate in {canonical_padded, canonical_padded.rstrip("=")} and decoded: + return True + return False + + +def _contains_canonical_base64(value: Any, *, seen: set[int] | None = None) -> bool: + if isinstance(value, str): + # Fixed Hermes/Nous attribution tags are protocol metadata, not an + # encoded source payload. They remain subject to secret/path scans. + if value.startswith(("product=hermes-agent", "client=hermes-client-")): + return False + for match in _BASE64_CANDIDATE.finditer(value): + candidate = match.group(1) + prefix = value[max(0, match.start() - 16) : match.start()].lower() + if re.fullmatch( + r"[0-9a-f]{7,12}|[0-9a-f]{40}|[0-9a-f]{64}", + candidate.lower(), + ): + continue + if candidate.isdigit(): + before = value[: match.start(1)].rstrip()[-1:] + after = value[match.end(1) :].lstrip()[:1] + if before in {":", ",", "["} and after in {",", "]", "}"}: + # JSON numeric values in tool results are serialized + # protocol fields, not encoded text. A quoted numeric + # string remains eligible for Base64 detection. + continue + # The fixed Kanban task-id grammar carries only a 32-bit hex + # database key. It is application protocol metadata, not an + # encoded source payload. + if _HERMES_TASK_ID.fullmatch(candidate): + continue + # Provider-generated tool-call and response-item identifiers are + # opaque protocol routing metadata, not caller-supplied encoded + # content. Match their complete, fixed grammar only. + if re.fullmatch(r"(?:call|fc)_[A-Za-z0-9_-]{8,128}", candidate): + continue + if candidate in { + "HERMES_CONTROL_HOME", + "HERMES_KANBAN_DB", + "HERMES_KANBAN_WORKSPACES_ROOT", + "HERMES_PROFILE_HOME", + }: + continue + # Content-addressed cache routing is a fixed application protocol + # value: the literal ``pck_`` prefix plus exactly 96 bits of hex. + if _PROMPT_CACHE_KEY.fullmatch(candidate): + continue + if _canonical_base64_candidate(candidate): + return True + # Providers and source-control tools sometimes wrap an otherwise + # canonical encoding at a fixed column. Normalize only bounded chunks + # so ordinary prose words are not concatenated into a false candidate. + chunked = re.compile( + r"(? bool: + """Bare token assignments are credentials at the send boundary. + + Logging intentionally permits short, non-opaque token values. A final + denial predicate cannot use that heuristic. Line anchoring preserves prose; + environment references carry names rather than credential bytes. + """ + for match in _BOUNDARY_TOKEN_ASSIGNMENT.finditer(text): + value = match.group(1).strip() + if _TOKEN_REFERENCE.fullmatch(value): + continue + if value in {"***", ""}: + continue + return True + return False + + +def _contains_secret(value: Any, *, seen: set[int] | None = None) -> bool: + """Scan credential literals as well as forced logging-redactor patterns.""" + + if isinstance(value, str): + return ( + _contains_token_literal(value) + or redact_sensitive_text( + value, + force=True, + redact_url_credentials=True, + ) + != value + ) + if isinstance(value, (bytes, bytearray, memoryview)): + # Binary request material is not safely inspectable as text. + return True + if seen is None: + seen = set() + if isinstance(value, Mapping): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any( + _contains_secret(key, seen=seen) or _contains_secret(item, seen=seen) + for key, item in value.items() + ) + if isinstance(value, (list, tuple, set, frozenset)): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any(_contains_secret(item, seen=seen) for item in value) + return False + + +def _contains_exact_secret( + value: Any, + exact_values: Sequence[str], + *, + seen: set[int] | None = None, +) -> bool: + """Match authoritative applied/environment credential bytes exactly.""" + + if isinstance(value, str): + return any(secret in value for secret in exact_values) + if isinstance(value, (bytes, bytearray, memoryview)): + return True + if seen is None: + seen = set() + if isinstance(value, Mapping): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any( + _contains_exact_secret(key, exact_values, seen=seen) + or _contains_exact_secret(item, exact_values, seen=seen) + for key, item in value.items() + ) + if isinstance(value, (list, tuple, set, frozenset)): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any( + _contains_exact_secret(item, exact_values, seen=seen) for item in value + ) + return False + + +def _contains_private_absolute_path(value: Any, *, seen: set[int] | None = None) -> bool: + """Reject common host-private absolute paths without blocking API paths.""" + + if isinstance(value, str): + return _PRIVATE_ABSOLUTE_PATH.search(value) is not None + if isinstance(value, (bytes, bytearray, memoryview)): + return True + if seen is None: + seen = set() + if isinstance(value, Mapping): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any( + _contains_private_absolute_path(key, seen=seen) + or _contains_private_absolute_path(item, seen=seen) + for key, item in value.items() + ) + if isinstance(value, (list, tuple, set, frozenset)): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any(_contains_private_absolute_path(item, seen=seen) for item in value) + return False + + +def content_free_violation_locations(value: Any) -> tuple[tuple[str, tuple[str, ...]], ...]: + """Return structural indexes and reasons without returning request text.""" + + locations: list[tuple[str, tuple[str, ...]]] = [] + seen: set[int] = set() + + def visit(item: Any, path: str) -> None: + if isinstance(item, str): + reasons: list[str] = [] + if _contains_canonical_base64(item): + reasons.append("base64_payload") + if _contains_private_absolute_path(item): + reasons.append("private_absolute_path") + if reasons: + locations.append((path, tuple(reasons))) + return + if isinstance(item, Mapping): + identity = id(item) + if identity in seen: + locations.append((path, ("cyclic_container",))) + return + seen.add(identity) + for index, (key, child) in enumerate(item.items()): + visit(key, f"{path}.map[{index}].key") + visit(child, f"{path}.map[{index}].value") + return + if isinstance(item, (list, tuple, set, frozenset)): + identity = id(item) + if identity in seen: + locations.append((path, ("cyclic_container",))) + return + seen.add(identity) + for index, child in enumerate(item): + visit(child, f"{path}.sequence[{index}]") + + visit(value, "$") + return tuple(locations) + + +def _contains_grant_substring(grant_content: bytes, candidate: bytes) -> bool: + """Reject source-derived proper substrings in sanitized text. + + Newline-trimmed line grants commonly appear in JSON without their source + line ending. A fixed eight-byte window detects meaningful excerpts in + linear time and avoids quadratic work on large source slices. + """ + + if not grant_content or not candidate: + return False + grant_variants = (grant_content, grant_content.rstrip(b"\r\n")) + for variant in grant_variants: + if not variant: + continue + if variant in candidate: + return True + if len(candidate) < len(variant) and candidate in variant and len(candidate) >= 4: + return True + window = min(8, len(candidate), len(variant)) + if window >= 4: + source_windows = { + variant[offset : offset + window] + for offset in range(0, len(variant) - window + 1) + } + if any( + candidate[offset : offset + window] in source_windows + for offset in range(0, len(candidate) - window + 1) + ): + return True + return False + + +def validate_sanitized_text(text: str, *, max_bytes: int = 32_768) -> str: + """Return unchanged bounded remote-safe text or reject it fail-closed. + + This is the only constructor-side admission path for SanitizedSegment. + The firewall repeats the same scans on the final rendered payload. + """ + + if not isinstance(text, str): + raise SanitizedTextRejected("invalid_sanitized_text") + if max_bytes <= 0 or len(text.encode("utf-8")) > max_bytes: + raise SanitizedTextRejected("sanitized_bytes_exceeded") + try: + if _contains_secret(text): + raise SanitizedTextRejected("secret_detected") + except SanitizedTextRejected: + raise + except Exception as exc: + raise SanitizedTextRejected("redaction_failed") from exc + try: + if _contains_canonical_base64(text): + raise SanitizedTextRejected("base64_payload") + except SanitizedTextRejected: + raise + except Exception as exc: + raise SanitizedTextRejected("base64_scan_failed") from exc + try: + if _contains_private_absolute_path(text): + raise SanitizedTextRejected("private_absolute_path") + except SanitizedTextRejected: + raise + except Exception as exc: + raise SanitizedTextRejected("private_path_scan_failed") from exc + return text + + +def _is_strict_sanitized_only_payload( + value: Any, + *, + seen: set[int] | None = None, +) -> tuple[bool, int]: + """Recognize the one grantless remote shape approved by policy. + + Every text leaf must be an explicit :class:`SanitizedSegment`. Raw text, + static literals, source references, binary values, cycles, and unsupported + containers make the entire payload ineligible. The positive count prevents + an empty structural request from acquiring grantless status. + """ + + if isinstance(value, SanitizedSegment): + return isinstance(value.text, str), 1 if isinstance(value.text, str) else 0 + if isinstance(value, UntrustedProvenanceSegment): + return False, 0 + if isinstance(value, ValidatedToolSyntaxSegment): + try: + validate_tool_syntax(value.text, value.syntax_kind) + except (TypeError, ValueError): + return False, 0 + return True, 1 + if isinstance(value, LiteralSegment): + return isinstance(value.text, str), 0 + if isinstance(value, SourceBoundSegment): + return False, 0 + if isinstance(value, SourcePresentationSegment): + return False, 0 + if isinstance(value, OutboundText): + if not value.segments: + return False, 0 + count = 0 + for segment in value.segments: + allowed, segment_count = _is_strict_sanitized_only_payload(segment, seen=seen) + if not allowed: + return False, 0 + count += segment_count + return count > 0, count + if value is None or isinstance(value, (bool, int)): + return True, 0 + if isinstance(value, float): + return math.isfinite(value), 0 + if isinstance(value, (str, bytes, bytearray, memoryview, set, frozenset)): + return False, 0 + if seen is None: + seen = set() + if isinstance(value, Mapping): + identity = id(value) + if identity in seen: + return False, 0 + seen.add(identity) + count = 0 + for key, item in value.items(): + if not isinstance(key, str): + return False, 0 + allowed, item_count = _is_strict_sanitized_only_payload(item, seen=seen) + if not allowed: + return False, 0 + count += item_count + return True, count + if isinstance(value, (list, tuple)): + identity = id(value) + if identity in seen: + return False, 0 + seen.add(identity) + count = 0 + for item in value: + allowed, item_count = _is_strict_sanitized_only_payload(item, seen=seen) + if not allowed: + return False, 0 + count += item_count + return True, count + return False, 0 + + +class LLMEgressFirewall: + """Validate a final LLM request and record a content-free receipt.""" + + def __init__( + self, + state_dir: Path | str, + *, + max_serialized_bytes: int = 262_144, + max_sanitized_bytes: int = 32_768, + max_sanitized_segment_bytes: int = 32_768, + max_conservative_tokens: int = 87_382, + max_granted_serialized_bytes: int | None = None, + max_granted_conservative_tokens: int | None = None, + conservative_chars_per_token: int = 3, + policy_digest: str | None = None, + static_literal_hashes_by_policy: Mapping[str, Sequence[str]] | None = None, + exact_secret_values: Sequence[str] = (), + ) -> None: + if max_serialized_bytes <= 0: + raise ValueError("max_serialized_bytes must be positive") + if max_sanitized_bytes <= 0: + raise ValueError("max_sanitized_bytes must be positive") + if max_sanitized_segment_bytes <= 0: + raise ValueError("max_sanitized_segment_bytes must be positive") + if max_conservative_tokens <= 0: + raise ValueError("max_conservative_tokens must be positive") + if max_granted_serialized_bytes is not None and max_granted_serialized_bytes <= 0: + raise ValueError("max_granted_serialized_bytes must be positive") + if ( + max_granted_conservative_tokens is not None + and max_granted_conservative_tokens <= 0 + ): + raise ValueError("max_granted_conservative_tokens must be positive") + if conservative_chars_per_token <= 0: + raise ValueError("conservative_chars_per_token must be positive") + self._state_dir = Path(state_dir) + self._receipt_path = self._state_dir / "llm-egress-receipts.jsonl" + self._max_serialized_bytes = max_serialized_bytes + self._max_sanitized_bytes = max_sanitized_bytes + self._max_sanitized_segment_bytes = max_sanitized_segment_bytes + self._max_conservative_tokens = max_conservative_tokens + self._max_granted_serialized_bytes = ( + max_serialized_bytes + if max_granted_serialized_bytes is None + else max_granted_serialized_bytes + ) + self._max_granted_conservative_tokens = ( + max_conservative_tokens + if max_granted_conservative_tokens is None + else max_granted_conservative_tokens + ) + self._conservative_chars_per_token = conservative_chars_per_token + self._policy_digest = str(policy_digest or "") + self._exact_secret_values = tuple( + dict.fromkeys(value for value in exact_secret_values if isinstance(value, str) and value) + ) + self._static_literal_hashes_by_policy = { + str(policy_digest): frozenset( + digest + for digest in digests + if isinstance(digest, str) and re.fullmatch(r"[0-9a-f]{64}", digest) + ) + for policy_digest, digests in (static_literal_hashes_by_policy or {}).items() + } + + def preflight( + self, + request: Mapping[str, Any] | TypedOutboundRequest, + route: Any, + *, + grants: Sequence[SourceGrant] = (), + ) -> EgressDecision: + """Preserve the content-free Task 1 decision interface.""" + + return self.authorize(request, route, grants=grants).decision + + def authorize( + self, + request: Mapping[str, Any] | TypedOutboundRequest, + route: Any, + *, + grants: Sequence[SourceGrant] = (), + ) -> AuthorizedEgress: + """Construct and authorize immutable provider bytes or fail closed. + + Remote and unknown destinations accept only ``TypedOutboundRequest``. + Source text is loaded from verified grants while constructing the + logical request, so no independent raw source-bearing payload exists + for a caller to send after preflight. + """ + + provider = str(_route_value(route, "provider", "")) + model = str(_route_value(route, "model", "")) + destination = classify_destination( + provider, + _route_value(route, "base_url"), + _route_value(route, "api_mode"), + ) + base_url = str(_route_value(route, "base_url") or "") + api_mode = str(_route_value(route, "api_mode") or "") + typed_request = request if isinstance(request, TypedOutboundRequest) else None + if typed_request is not None: + session_id = typed_request.session_id + turn_id = typed_request.turn_id + request_id = typed_request.request_id + policy_digest = typed_request.policy_digest + else: + session_id = _request_identity(request, "session_id") + turn_id = _request_identity(request, "turn_id") + request_id = _request_identity(request, "request_id") + policy_digest = _request_identity(request, "policy_digest") + + reasons: list[str] = [] + valid_grants: list[SourceGrant] = [] + grant_contents: dict[str, tuple[SourceGrant, bytes]] = {} + grant_reasons: list[str] = [] + source_segment_count = 0 + sanitized_only = False + if typed_request is not None: + sanitized_shape, sanitized_count = _is_strict_sanitized_only_payload( + typed_request.payload + ) + sanitized_only = sanitized_shape and sanitized_count > 0 + + if destination == DestinationClass.UNKNOWN: + reasons.append("unknown_destination") + if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN} and not all( + (session_id, turn_id, request_id, policy_digest) + ): + reasons.append("missing_request_identity") + if self._policy_digest and policy_digest != self._policy_digest: + reasons.append("policy_digest_mismatch") + if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: + if typed_request is None: + reasons.append("typed_request_required") + # The sole grantless remote lane is a structurally verified request + # whose every text leaf is an explicit bounded SanitizedSegment. + # Passing even one purported grant opts back into exact source + # validation so malformed or unbound authority cannot be ignored. + if grants or not sanitized_only: + grant_reasons, valid_grants, grant_contents = self._validate_grants( + grants, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + ) + reasons.extend(grant_reasons) + + if typed_request is not None: + ( + logical_request, + construction_reasons, + source_segment_count, + scan_values, + base64_scan_values, + ) = ( + self._construct_typed_request( + typed_request, + grant_contents, + allow_sanitized_segments=True, + ) + ) + reasons.extend(construction_reasons) + else: + logical_request = request + scan_values = request + base64_scan_values = request + + try: + serialized = json.dumps( + logical_request, + ensure_ascii=False, + allow_nan=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + except (TypeError, ValueError, OverflowError): + decision = EgressDecision( + allowed=False, + destination_class=destination, + provider=provider, + model=model, + payload_sha256="", + serialized_bytes=0, + estimated_tokens=0, + source_grant_count=len(valid_grants), + source_segment_count=source_segment_count, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + reason_codes=("serialization_failed",), + base_url=base_url, + api_mode=api_mode, + grant_digests=tuple(source_grant_digest(grant) for grant in valid_grants), + ) + self._block(decision, valid_grants) + + serialized_bytes = len(serialized) + estimated_tokens = ( + serialized_bytes + self._conservative_chars_per_token - 1 + ) // self._conservative_chars_per_token + use_granted_caps = bool( + typed_request is not None + and source_segment_count > 0 + and valid_grants + and not grant_reasons + ) + serialized_byte_cap = ( + self._max_granted_serialized_bytes + if use_granted_caps + else self._max_serialized_bytes + ) + conservative_token_cap = ( + self._max_granted_conservative_tokens + if use_granted_caps + else self._max_conservative_tokens + ) + if serialized_bytes > serialized_byte_cap: + reasons.append("serialized_bytes_exceeded") + if estimated_tokens > conservative_token_cap: + reasons.append("token_cap_exceeded") + + if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: + try: + if _contains_secret(scan_values): + reasons.append("secret_detected") + except Exception: + reasons.append("redaction_failed") + try: + if _contains_exact_secret(scan_values, self._exact_secret_values): + reasons.append("exact_secret_detected") + except Exception: + reasons.append("exact_secret_scan_failed") + try: + if _contains_canonical_base64(base64_scan_values): + reasons.append("base64_payload") + except Exception: + reasons.append("base64_scan_failed") + try: + if _contains_private_absolute_path(scan_values): + reasons.append("private_absolute_path") + except Exception: + reasons.append("private_path_scan_failed") + + decision = EgressDecision( + allowed=not reasons, + destination_class=destination, + provider=provider, + model=model, + payload_sha256=sha256(serialized).hexdigest(), + serialized_bytes=serialized_bytes, + estimated_tokens=estimated_tokens, + source_grant_count=len(valid_grants), + source_segment_count=source_segment_count, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + reason_codes=tuple(dict.fromkeys(reasons)), + base_url=base_url, + api_mode=api_mode, + grant_digests=tuple(source_grant_digest(grant) for grant in valid_grants), + ) + if not decision.allowed: + self._block(decision, valid_grants) + + try: + self._append_receipt(decision, valid_grants) + except OSError: + raise EgressBlocked( + replace(decision, allowed=False, reason_codes=("receipt_unavailable",)) + ) from None + return AuthorizedEgress(decision=decision, payload_bytes=serialized) + + def _validate_grants( + self, + grants: Sequence[SourceGrant], + *, + session_id: str, + turn_id: str, + request_id: str, + policy_digest: str, + ) -> tuple[list[str], list[SourceGrant], dict[str, tuple[SourceGrant, bytes]]]: + reasons: list[str] = [] + valid: list[SourceGrant] = [] + contents: dict[str, tuple[SourceGrant, bytes]] = {} + if not grants: + return ["untrusted_provenance"], valid, contents + + for candidate in grants: + if not isinstance(candidate, SourceGrant): + reasons.append("untrusted_provenance") + continue + grant = candidate + if ( + grant.session_id != session_id + or grant.turn_id != turn_id + or grant.request_id != request_id + or grant.policy_digest != policy_digest + ): + reasons.append("grant_binding_mismatch") + continue + if ( + grant.line_start < 1 + or grant.line_end < grant.line_start + or grant.byte_count < 0 + or not re.fullmatch(r"[0-9a-f]{64}", grant.content_sha256) + ): + reasons.append("invalid_source_grant") + continue + display = Path(grant.display_path) + if display.is_absolute() or ".." in display.parts: + reasons.append("invalid_display_path") + continue + try: + canonical = Path(grant.canonical_path) + resolved = canonical.resolve(strict=True) + except (OSError, RuntimeError, ValueError, TypeError): + reasons.append("source_unavailable") + continue + if not canonical.is_absolute() or canonical != resolved: + reasons.append("source_path_not_canonical") + continue + try: + blocked = get_read_block_error(str(resolved)) + except Exception: + reasons.append("source_policy_unavailable") + continue + if blocked is not None: + reasons.append("sensitive_path") + continue + try: + lines = resolved.read_bytes().splitlines(keepends=True) + except OSError: + reasons.append("source_unavailable") + continue + if grant.line_end > len(lines): + reasons.append("source_range_mismatch") + continue + content = b"".join(lines[grant.line_start - 1 : grant.line_end]) + if len(content) != grant.byte_count or sha256(content).hexdigest() != grant.content_sha256: + reasons.append("source_hash_mismatch") + continue + valid.append(grant) + contents[source_grant_digest(grant)] = (grant, content) + + if not valid and "untrusted_provenance" not in reasons: + reasons.append("untrusted_provenance") + return reasons, valid, contents + + def _construct_typed_request( + self, + request: TypedOutboundRequest, + grant_contents: Mapping[str, tuple[SourceGrant, bytes]], + *, + allow_sanitized_segments: bool = False, + ) -> tuple[Mapping[str, Any], list[str], int, list[str], list[str]]: + """Build a plain JSON request exclusively from typed segment nodes.""" + + reasons: list[str] = [] + referenced_grants: set[str] = set() + source_segment_count = 0 + sanitized_bytes = 0 + scan_values: list[str] = [] + base64_scan_values: list[str] = [] + allowed_static_hashes = self._static_literal_hashes_by_policy.get( + request.policy_digest, + frozenset(), + ) + + def require_static_literal(text: str) -> None: + # Provenance authorization and content safety are independent. + # Every rendered text atom is scanned again immediately before + # authorization, including exact policy-bound static literals and + # structural keys/scalars. + scan_values.append(text) + base64_scan_values.append(text) + if static_literal_sha256(text) not in allowed_static_hashes: + reasons.append("static_literal_not_allowed") + + def render_text_segment( + segment: ( + LiteralSegment + | SanitizedSegment + | ValidatedToolSyntaxSegment + | SourceBoundSegment + | SourcePresentationSegment + | UntrustedProvenanceSegment + ), + ) -> str: + nonlocal sanitized_bytes, source_segment_count + if isinstance(segment, LiteralSegment): + if not isinstance(segment.text, str): + reasons.append("invalid_literal_segment") + return "" + require_static_literal(segment.text) + encoded_literal = segment.text.encode("utf-8") + if any(content and content in encoded_literal for _, content in grant_contents.values()): + reasons.append("source_bytes_in_literal") + return segment.text + if isinstance(segment, SanitizedSegment): + if not allow_sanitized_segments: + reasons.append("sanitized_segment_forbidden") + if isinstance(segment.text, str): + encoded = segment.text.encode("utf-8") + if len(encoded) > self._max_sanitized_segment_bytes: + reasons.append("sanitized_segment_bytes_exceeded") + sanitized_bytes += len(encoded) + if sanitized_bytes > self._max_sanitized_bytes: + reasons.append("sanitized_bytes_exceeded") + if any( + _contains_grant_substring(content, encoded) + for _, content in grant_contents.values() + ): + reasons.append("source_bytes_in_sanitized_segment") + scan_values.append(segment.text) + base64_scan_values.append(segment.text) + return segment.text + reasons.append("invalid_literal_segment") + return "" + if isinstance(segment, ValidatedToolSyntaxSegment): + try: + text = validate_tool_syntax(segment.text, segment.syntax_kind) + except (TypeError, ValueError): + reasons.append("invalid_tool_syntax_segment") + return "" + encoded = text.encode("utf-8") + if len(encoded) > self._max_sanitized_segment_bytes: + reasons.append("sanitized_segment_bytes_exceeded") + sanitized_bytes += len(encoded) + if sanitized_bytes > self._max_sanitized_bytes: + reasons.append("sanitized_bytes_exceeded") + scan_values.append(text) + return text + if isinstance(segment, SourceBoundSegment): + grant_and_content = grant_contents.get(segment.source_grant_digest) + if grant_and_content is None: + reasons.append("source_segment_grant_mismatch") + return "" + try: + text = grant_and_content[1].decode("utf-8") + except UnicodeDecodeError: + reasons.append("source_segment_not_text") + return "" + referenced_grants.add(segment.source_grant_digest) + source_segment_count += 1 + scan_values.append(text) + base64_scan_values.append(text) + return text + if isinstance(segment, SourcePresentationSegment): + grant_and_content = grant_contents.get(segment.source_grant_digest) + if grant_and_content is None: + reasons.append("source_segment_grant_mismatch") + return "" + if segment.presentation_kind != "read_file_json_v1": + reasons.append("invalid_source_presentation") + return "" + try: + raw_text = grant_and_content[1].decode("utf-8") + expected_content = "\n".join( + f"{line_number}|{line}" + for line_number, line in enumerate( + raw_text.split("\n"), + start=grant_and_content[0].line_start, + ) + ) + parsed = json.loads(segment.text) + except (UnicodeDecodeError, TypeError, ValueError, json.JSONDecodeError): + reasons.append("invalid_source_presentation") + return "" + if not isinstance(parsed, dict) or parsed.get("content") != expected_content: + reasons.append("invalid_source_presentation") + return "" + referenced_grants.add(segment.source_grant_digest) + source_segment_count += 1 + scan_values.append(segment.text) + base64_scan_values.append(segment.text) + return segment.text + if isinstance(segment, UntrustedProvenanceSegment): + reasons.append("untrusted_provenance") + return "" + reasons.append("invalid_source_segment") + return "" + + def render(value: Any) -> Any: + if isinstance( + value, + ( + LiteralSegment, + SanitizedSegment, + ValidatedToolSyntaxSegment, + SourceBoundSegment, + SourcePresentationSegment, + UntrustedProvenanceSegment, + ), + ): + return render_text_segment(value) + if isinstance(value, OutboundText): + return "".join(render_text_segment(segment) for segment in value.segments) + if isinstance(value, Mapping): + rendered: dict[str, Any] = {} + for key, item in value.items(): + if not isinstance(key, str): + reasons.append("invalid_request_key") + continue + require_static_literal(key) + rendered[key] = render(item) + return rendered + if isinstance(value, (list, tuple)): + return [render(item) for item in value] + if isinstance(value, float) and not math.isfinite(value): + reasons.append("non_finite_number") + return None + if value is None or isinstance(value, (bool, int, float)): + require_static_literal( + json.dumps(value, ensure_ascii=True, allow_nan=False, separators=(",", ":")) + ) + return value + # In particular, raw strings and bytes are not remote request + # material. Every outbound string must have a typed owner. + reasons.append("untyped_request_value") + return None + + rendered_payload = render(request.payload) + if not isinstance(rendered_payload, Mapping): + reasons.append("invalid_typed_request_root") + rendered_payload = {} + else: + bound_identities = { + "session_id": request.session_id, + "turn_id": request.turn_id, + "request_id": request.request_id, + "policy_digest": request.policy_digest, + } + if any( + field in rendered_payload and rendered_payload[field] != expected + for field, expected in bound_identities.items() + ): + reasons.append("request_identity_mismatch") + if set(grant_contents) - referenced_grants: + reasons.append("source_grant_unbound") + return ( + rendered_payload, + reasons, + source_segment_count, + scan_values, + base64_scan_values, + ) + + def _block( + self, + decision: EgressDecision, + grants: Sequence[SourceGrant] = (), + ) -> None: + try: + self._append_receipt(decision, grants) + except OSError: + decision = replace( + decision, + reason_codes=tuple(dict.fromkeys((*decision.reason_codes, "receipt_unavailable"))), + ) + raise EgressBlocked(decision) + + def _append_receipt( + self, + decision: EgressDecision, + grants: Sequence[SourceGrant], + ) -> None: + try: + if self._state_dir.is_symlink(): + raise OSError("egress state directory must not be a symlink") + except OSError: + raise + self._state_dir.mkdir(parents=True, exist_ok=True, mode=0o700) + receipt = asdict(decision) + receipt["destination_class"] = decision.destination_class.value + receipt["decision"] = "allow" if decision.allowed else "block" + for field in ( + "provider", + "model", + "base_url", + "api_mode", + "session_id", + "turn_id", + "request_id", + "policy_digest", + ): + receipt[field] = _receipt_identifier(receipt[field]) + receipt["source_grants"] = [ + { + "line_start": grant.line_start, + "line_end": grant.line_end, + "content_sha256": grant.content_sha256, + "byte_count": grant.byte_count, + } + for grant in grants + ] + flags = os.O_APPEND | os.O_CREAT | os.O_RDWR + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + with exclusive_file_lock(self._receipt_path.with_suffix(".lock")): + fd = os.open(self._receipt_path, flags, 0o600) + try: + secure_file_descriptor_permissions(fd) + file_size = os.fstat(fd).st_size + previous_hash = "" + if file_size: + read_start = max(0, file_size - 131_072) + os.lseek(fd, read_start, os.SEEK_SET) + prior_chunk = os.read(fd, file_size - read_start) + prior_lines = prior_chunk.splitlines() + if prior_lines: + previous_hash = sha256(prior_lines[-1]).hexdigest() + receipt["receipt_prev_sha256"] = previous_hash + receipt_material = json.dumps( + receipt, ensure_ascii=True, separators=(",", ":"), sort_keys=True + ).encode("utf-8") + receipt["receipt_sha256"] = sha256( + previous_hash.encode("ascii") + receipt_material + ).hexdigest() + encoded = ( + json.dumps(receipt, ensure_ascii=True, separators=(",", ":"), sort_keys=True) + + "\n" + ).encode("utf-8") + os.lseek(fd, 0, os.SEEK_END) + if os.write(fd, encoded) != len(encoded): + raise OSError("short receipt write") + finally: + os.close(fd) + + +__all__ = [ + "AuthorizedEgress", + "DestinationClass", + "EgressBlocked", + "EgressDecision", + "LLMEgressFirewall", + "LiteralSegment", + "OutboundText", + "SanitizedSegment", + "SourceBoundSegment", + "SourcePresentationSegment", + "SourceGrant", + "TypedOutboundRequest", + "UntrustedProvenanceSegment", + "ValidatedToolSyntaxSegment", + "classify_destination", + "source_grant_digest", + "static_literal_sha256", + "validate_tool_syntax", +] diff --git a/agent/llm_egress_runtime.py b/agent/llm_egress_runtime.py new file mode 100644 index 0000000000000..cdf82c34e1dba --- /dev/null +++ b/agent/llm_egress_runtime.py @@ -0,0 +1,731 @@ +"""Final provider-boundary enforcement for source-bound LLM egress.""" + +from __future__ import annotations + +import json +import logging +import math +import os +import re +from hashlib import sha256 +from pathlib import Path +from types import MappingProxyType +from types import SimpleNamespace +from typing import Any, Callable, Mapping, Sequence + +from agent.llm_egress_firewall import ( + AuthorizedEgress, + EgressBlocked, + LLMEgressFirewall, + LiteralSegment, + OutboundText, + SanitizedSegment, + SourceBoundSegment, + SourcePresentationSegment, + SourceGrant, + TypedOutboundRequest, + UntrustedProvenanceSegment, + DestinationClass, + classify_destination, + source_grant_digest, + static_literal_sha256, + validate_sanitized_text, + content_free_violation_locations, +) +from agent.source_provenance import DEFAULT_POLICY_DIGEST, SourceProvenanceRegistry + + +# Timeout is a non-content SDK control. Header/query values remain in the +# authorized JSON body so credentials or other caller-controlled text cannot +# be appended after the firewall receipt is written. +_SDK_CONTROL_KEYS = frozenset({"timeout"}) +_INTERNAL_EGRESS_KEYS = frozenset({"_hermes_source_provenance"}) +_PROTOCOL_LITERAL_FIELDS = frozenset({"role", "type"}) +_PROTOCOL_LITERAL_VALUES = frozenset({ + "assistant", + "computer_call_output", + "developer", + "function_call", + "function_call_output", + "input_image", + "input_text", + "output_text", + "reasoning", + "system", + "tool", + "user", +}) +_PROTECTED_REMOTE_PROVIDERS = frozenset({ + "anthropic", + "openai-codex", + "nous", + "nous-portal", + "nousresearch", +}) +logger = logging.getLogger(__name__) + +_VALIDATED_SYNTAX_TOOL_NAMES = frozenset({"terminal"}) +_CREDENTIAL_ENV_SUFFIXES = ( + "_API_KEY", + "_TOKEN", + "_SECRET", + "_KEY", + "_PASSWORD", + "_CREDENTIAL", +) + +_PRIVATE_PATH_IN_TEXT = re.compile( + r"(? Any: + """Remove host paths from protected Kanban tool results before typing. + + This deliberately does not rewrite secrets or arbitrary encoded content; + those remain visible to the fail-closed firewall scans and are denied. + """ + + if isinstance(value, str): + text = value + for name in ( + "HERMES_KANBAN_CLAIM_LOCK", + "HERMES_KANBAN_RUN_ID", + "HERMES_SESSION_ID", + "HERMES_STREAM_STALE_GIVEUP", + "HERMES_TURN_LEASE_TIMEOUT", + ): + raw = os.environ.get(name) + if raw: + text = re.sub( + rf"(?m)^(?P