Skip to content

The agent that grows with you

Merge origin/main (#32: 36 commits to cf23a1a5cc3) into feat/unified-gateway-runtime

Teknium408cc0d12ee3
diff --cc agent/credential_pool.py
index c3f323e0354,9682aedcf62..2237a9506de
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@@ -401,7 -400,32 +401,7 @@@ def _exhausted_ttl
return base
- def _singleton_predates_entry(state: Any, entry: "PooledCredential") -> bool:
-def _parse_absolute_timestamp(value: Any) -> Optional[float]:
- """Best-effort parse of epoch seconds / epoch ms / ISO-8601 into epoch seconds."""
- if value is None or value == "":
- return None
- if isinstance(value, (int, float)):
- numeric = float(value)
- if numeric <= 0:
- return None
- return numeric / 1000.0 if numeric > 1_000_000_000_000 else numeric
- if isinstance(value, str):
- raw = value.strip()
- if not raw:
- return None
- try:
- numeric = float(raw)
- return numeric / 1000.0 if numeric > 1_000_000_000_000 else numeric
- except ValueError:
- pass
- try:
- return datetime.fromisoformat(raw).timestamp()
- except ValueError:
- return None
- return None
-
-
+ def _singleton_predates_entry(state: Any, entry: PooledCredential) -> bool:
"""True only when the auth.json singleton is PROVABLY older than *entry*.
Both sides stamp ``last_refresh`` on every successful rotation. When
diff --cc cron/jobs.py
index 9c8dc53a7a6,4a6264ad61a..c4357fdddc0
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@@ -26,9 -26,9 +26,9 @@@ try
import msvcrt
except ImportError: # pragma: no cover - non-Windows
msvcrt = None
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
-from hermes_constants import get_hermes_home
+from hermes_constants import display_hermes_home, get_hermes_home
from cron.constants import CLAIM_TTL_INACTIVITY_HEADROOM, FIRE_CLAIM_SKEW_SECONDS, FIRE_CLAIM_TTL_SECONDS
from cron.env_settings import cron_env_setting
from cron.scheduler_ownership import _claim_owner_is_dead
diff --cc gateway/control_socket.py
index 8a8bc4720c3,edcfcffde42..ebb6c9e4195
--- a/gateway/control_socket.py
+++ b/gateway/control_socket.py
@@@ -349,10 -237,10 +349,10 @@@ class GatewayControlServer
# Handlers read disk; keep that off the loop that drives every platform
# adapter so a fast-polling consumer can't stall heartbeats.
response = await asyncio.get_running_loop().run_in_executor(
- None, self.handle_request_line, raw.rstrip(b"\n"))
+ None, self.handle_request_line, raw.rstrip(b"\n"), self._posix_peer_subject(writer))
writer.write(response)
- await writer.drain()
+ await asyncio.wait_for(writer.drain(), timeout=_DEFAULT_CLIENT_TIMEOUT)
- except (asyncio.TimeoutError, ConnectionError, OSError):
+ except (TimeoutError, ConnectionError, OSError):
pass
except Exception:
logger.debug("Control socket connection handler error", exc_info=True)
diff --cc gateway/platforms/api_server.py
index 0449fa6edf4,f28b6bf4f0f..034ae38d20c
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@@ -2450,35 -2509,8 +2450,35 @@@ class APIServerAdapter(OpenAICompatRout
return _error_response("Failed to list model options.", 500, code="model_options_failed")
@_require_auth
- async def _handle_capabilities(self, request: "web.Request") -> "web.Response":
+ async def _handle_capabilities(self, request: web.Request) -> web.Response:
"""GET /v1/capabilities — the stable, machine-readable API surface for external UIs."""
+ runner = getattr(self, "gateway_runner", None)
+ features = {
+ "chat_completions": True, "chat_completions_streaming": True,
+ "responses_api": True, "responses_streaming": True, "run_submission": True,
+ "runs_idempotency": _api_runs._idempotency_capabilities(self, store_type=RunIdempotencyStore),
+ **_STATIC_FEATURE_FLAGS,
+ "run_unknown_resolution": getattr(runner, "session_authority", None) is not None,
+ "cors": bool(self._cors_origins),
+ # Always advertised for feature-detection; enabled follows config.
+ "browser_extension_control": {
+ "enabled": self._browser_control_enabled(),
+ "protocol_version": _BROWSER_CONTROL_PROTOCOL_VERSION,
+ "capabilities": sorted(BROWSER_CONTROL_CAPABILITIES),
+ "artifact_capabilities": sorted(BROWSER_CONTROL_ARTIFACT_CAPABILITIES),
+ "developer_capabilities": sorted(BROWSER_CONTROL_DEVELOPER_CAPABILITIES),
+ "developer_mode": self._browser_control_developer_mode(),
+ "artifact_transport": {
+ "upload": {"method": "POST", "path": "/v1/artifacts/upload"},
+ "download": {
+ "method": "GET", "path": "/v1/artifacts/download/{artifact_id}"},
+ "max_bytes": DEFAULT_MAX_ARTIFACT_BYTES,
+ "ttl_seconds": DEFAULT_ARTIFACT_TTL_SECONDS,
+ "allowed_mime_types": sorted(DEFAULT_ALLOWED_MIME_TYPES)},
+ "real_browser_actions": True,
+ "transports": {
+ "local_vps": "websocket-subprotocol-ticket",
+ "cloud": "authenticated-gateway-rpc"}}}
return web.json_response({
"object": "hermes.api_server.capabilities", "platform": "hermes-agent",
"model": self._model_name,
diff --cc gateway/platforms/api_server_openai_routes.py
index e4d3b50a217,0c3a134381c..1b33b2d4355
--- a/gateway/platforms/api_server_openai_routes.py
+++ b/gateway/platforms/api_server_openai_routes.py
@@@ -1146,10 -975,10 +1146,10 @@@ class OpenAICompatRoutesMixin
return response
async def _write_sse_responses(
- self, request: "web.Request", response_id: str, model: str, created_at: int, stream_q,
+ self, request: web.Request, response_id: str, model: str, created_at: int, stream_q,
agent_task, agent_ref, conversation_history: list[dict[str, str]], user_message: str,
instructions: Optional[str], conversation: Optional[str], store: bool, session_id: str,
- gateway_session_key: Optional[str] = None, durable_key=None, terminal_replay=False) -> "web.StreamResponse":
- gateway_session_key: Optional[str] = None) -> web.StreamResponse:
++ gateway_session_key: Optional[str] = None, durable_key=None, terminal_replay=False) -> web.StreamResponse:
"""Write the SSE stream for POST /v1/responses.
Events: ``response.created`` -> ``output_text.delta/done`` + ``output_item.added/done``
@@@ -1205,68 -1031,12 +1205,68 @@@
logger.error("Agent crashed mid-stream for %s: %s", response_id, str(st.agent_error)[:300])
return response
- async def _replay_sse_responses(self, request: "web.Request", replay: dict[str, Any]) -> "web.StreamResponse":
++ async def _replay_sse_responses(self, request: web.Request, replay: dict[str, Any]) -> web.StreamResponse:
+ """Re-emit a settled idempotent record as SSE. A record made by the streaming path replays
+ its exact frames; one made by the nonstreaming path gets ``created`` + its terminal event."""
+ from gateway.platforms.api_server import _sse_frame
+ headers = replay.get('headers') or {}
+ response = await self._prepare_sse_response(
+ request, headers.get('X-Hermes-Session-Id'), headers.get('X-Hermes-Session-Key'))
+ events = replay.get('events')
+ if not events:
+ env = replay['response']
+ created = {k: env[k] for k in ('id', 'object', 'created_at', 'model')}
+ created.update(status='in_progress', output=[])
+ events = [['response.created', {'type': 'response.created', 'response': created, 'sequence_number': 0}],
+ ['response.' + env['status'], {'type': 'response.' + env['status'], 'response': env,
+ 'sequence_number': 1}]]
+ for event_type, data in events:
+ await response.write(_sse_frame(data, event=event_type))
+ return response
+
- async def _responses_durable_replay(self, request: "web.Request", body: dict[str, Any], stream: bool) -> tuple:
++ async def _responses_durable_replay(self, request: web.Request, body: dict[str, Any], stream: bool) -> tuple:
+ """Canonical Idempotency-Key record for POST /v1/responses ->
+ ``(durable_key, idempotency_scope, idempotency_key, replayed_response_or_None)``."""
+ durable_key = idempotency_scope = None
+ idempotency_key = request.headers.get('Idempotency-Key')
+ canonical = getattr(self.gateway_runner, 'session_authority', None) is not None
+ if canonical and idempotency_key:
+ # An exact retry replays the committed response BEFORE the conversation name is
+ # expanded: the first success already advanced the conversation, so re-expanding
+ # would build a different admission payload and refuse the retry as a conflict.
+ # Streaming and nonstreaming share the record: transport mode is not identity.
+ from gateway.platforms.api_server import _make_request_fingerprint
+ idempotency_scope = self._run_idempotency_scope(request)
+ durable_key = (f'idem:{idempotency_scope}:{idempotency_key}',
+ _make_request_fingerprint(body, keys=_responses_fingerprint_keys(body)))
+ from gateway.platforms.api_server import _openai_error
+ from gateway.platforms.api_server_response_admissions import request_binding
+ response_store = self._current_response_store()
+ binding = request_binding(self, request, durable_key)
+ if not response_store.request_key_matches(durable_key[0], binding):
+ return durable_key, idempotency_scope, idempotency_key, web.json_response(
+ _openai_error('admission_conflict', code='admission_conflict'), status=409)
+ replay = response_store.get(durable_key[0])
+ if replay is not None:
+ if replay.get('fingerprint') != durable_key[1]:
+ return durable_key, idempotency_scope, idempotency_key, web.json_response(
+ _openai_error('admission_conflict', code='admission_conflict'), status=409)
+ if not _settled(replay):
+ # Never re-run a request whose earlier attempt may have executed.
+ return durable_key, idempotency_scope, idempotency_key, web.json_response(
+ _openai_error('unknown_execution', code='unknown_execution'), status=409)
+ if stream:
+ return (durable_key, idempotency_scope, idempotency_key,
+ await self._replay_sse_responses(request, replay))
+ return durable_key, idempotency_scope, idempotency_key, web.json_response(
+ replay['response'], headers=replay.get('headers') or {})
+ return durable_key, idempotency_scope, idempotency_key, None
+
- async def _handle_responses(self, request: "web.Request") -> "web.Response":
+ async def _handle_responses(self, request: web.Request) -> web.Response:
"""POST /v1/responses — OpenAI Responses API format."""
from gateway.platforms.api_server import (
- ThreadSafeAsyncQueue, _auto_truncate_response_history, _coerce_request_bool,
- _content_has_visible_payload, _error_response, _invalid_request,
- _multimodal_validation_error, _normalize_multimodal_content, _redact_api_error_text,
+ ThreadSafeAsyncQueue, _coerce_request_bool,
+ _error_response, _invalid_request, _redact_api_error_text,
_resolve_media_to_data_urls, _responses_usage_payload)
# Bound total in-flight agent runs (configurable; #7483).
limited = self._concurrency_limited_response()
@@@ -1395,12 -1211,9 +1395,12 @@@
response_headers = {"X-Hermes-Session-Id": _effective_session_id}
if gateway_session_key:
response_headers["X-Hermes-Session-Key"] = gateway_session_key
+ if durable_key is not None:
+ self._current_response_store().put(durable_key[0], {
+ 'fingerprint': durable_key[1], 'response': response_data, 'headers': response_headers})
return web.json_response(response_data, headers=response_headers)
- async def _handle_get_response(self, request: "web.Request") -> "web.Response":
+ async def _handle_get_response(self, request: web.Request) -> web.Response:
"""GET /v1/responses/{response_id} — retrieve a stored response."""
from gateway.platforms.api_server import _error_response
auth_err = self._check_auth(request)
diff --cc gateway/platforms/api_server_runs.py
index d66fbcc5552,bfb5b4dbee3..ace07b29ee5
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@@ -358,17 -349,11 +358,17 @@@ def _make_run_event_callback(self, run_
return _callback
+# Answering a prompt the run raised is one capability whichever tool asked: approvals
+# and clarify share the grant's ``approve`` permission. Acknowledging a lost owner epoch
+# ends the run like a stop, so ``/resolve-unknown`` rides the ``stop`` permission.
+_ROOM_CONTROL_PERMISSIONS = {
+ "/stop": "stop", "/resolve-unknown": "stop", "/approval": "approve", "/clarify": "approve"}
+
+
- def _room_permission_for(request: "web.Request") -> str:
+ def _room_permission_for(request: web.Request) -> str:
- if request.path.endswith("/stop"):
- return "stop"
- if request.path.endswith("/approval"):
- return "approve"
+ for suffix, permission in _ROOM_CONTROL_PERMISSIONS.items():
+ if request.path.endswith(suffix):
+ return permission
return "status" if request.method == "GET" else "dispatch"
@@@ -407,12 -392,8 +407,12 @@@ def _owner_alive(owner_pid: int, owner_
return False
- def _durable_run_status(self, request: "web.Request", run_id: str) -> dict[str, Any] | None:
+ def _durable_run_status(self, request: web.Request, run_id: str) -> dict[str, Any] | None:
"""Hydrate a scoped run status and fail stale owners closed."""
+ from gateway.platforms.api_server_authority_runs import run_projection
+ canonical = run_projection(self, run_id)
+ if canonical is not None:
+ return canonical
status = self._run_statuses.get(run_id)
if status is not None:
if run_id in self._run_idempotency_ids:
@@@ -637,59 -617,7 +637,59 @@@ async def run_internal_session_turn(sel
_api_server._api_request_profile.reset(token)
+def _run_idempotency_identity(self, request, body, gateway_session_key, idempotency_key) -> tuple:
+ """``(principal scope, request fingerprint)`` for a keyed POST /v1/runs; ``("", "")`` unkeyed."""
+ if not idempotency_key:
+ return "", ""
+ return self._run_idempotency_scope(request), hashlib.sha256(json.dumps(
+ {"body": body, "gateway_session_key": gateway_session_key or ""},
+ sort_keys=True, separators=(",", ":"), ensure_ascii=False,
+ ).encode()).hexdigest()
+
+
+def _run_user_message(raw_input, _openai_error) -> tuple:
+ """POST /v1/runs ``input`` -> ``(user_message, error_response_or_None)``."""
+ if not raw_input:
+ return None, _json_error(_openai_error, "Missing 'input' field", status=400)
+ if isinstance(raw_input, str):
+ user_message = raw_input
+ else:
+ user_message = raw_input[-1].get("content", "") if isinstance(raw_input, list) else ""
+ if not user_message:
+ return None, _json_error(_openai_error, "No user message found in input", status=400)
+ return user_message, None
+
+
+def _admit_run_to_authority(
+ self, launch, run_id, session_history_delivery, _declared_selected,
+ idempotency_scope, idempotency_key, _openai_error,
- ) -> Optional["web.Response"]:
++) -> Optional[web.Response]:
+ """Admit a /v1/runs turn to the session authority FIFO -> ``None``, or the 409 refusal."""
+ from gateway.session_api_turn import admit_api_turn
+ from hermes_state_runtime import RuntimeStoreError
+ try:
+ with self._profile_scope(launch.request_profile):
+ launch.admission = admit_api_turn(self, user_message=launch.user_message,
+ conversation_history=launch.conversation_history, active_run_id=run_id,
+ run_owner_scope=self._run_owners[run_id],
+ turn_author=launch.turn_author,
+ history_from_session=session_history_delivery,
+ session_history_delivery='1' if session_history_delivery else '',
+ bind_declared_conversation=_declared_selected,
+ **launch.agent_kwargs)
+ except RuntimeStoreError as exc:
+ # A refused admission owns no run: drop every reservation so an exact
+ # retry is refused again instead of replaying a run nobody executes.
+ _forget_run(
+ self, run_id, self._run_streams, self._run_streams_created, self._run_approval_sessions,
+ self._run_statuses, self._run_owners, self._run_idempotency_ids)
+ if idempotency_key:
+ self._run_idempotency_store.forget(idempotency_scope, idempotency_key)
+ return _json_error(_openai_error, exc.reason, code=exc.reason, status=409)
+ return None
+
+
- async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Response":
+ async def _handle_runs(self, request: web.Request, *, _api_server) -> web.Response:
"""POST /v1/runs — start an agent run, return run_id immediately."""
_openai_error = _api_server._openai_error
# Long-term memory scope header (see chat_completions for details).
@@@ -1164,10 -1061,9 +1164,10 @@@ async def _handle_get_run(self, request
return err or web.json_response(status)
- async def _handle_run_events(self, request: "web.Request", *, _api_server) -> "web.StreamResponse":
+ async def _handle_run_events(self, request: web.Request, *, _api_server) -> web.StreamResponse:
"""GET /v1/runs/{run_id}/events — stream structured agent lifecycle events."""
- auth_err = self._check_auth(request)
+ # Same door as GET /v1/runs/{id}: a room grant that may poll the run may stream it.
+ auth_err = self._check_run_auth(request, permission="status")
if auth_err:
return auth_err
run_id = request.match_info["run_id"]
@@@ -1324,28 -1216,7 +1324,28 @@@ async def _handle_run_approval(self, re
"resolved": resolved})
+async def _respond_authority_run(self, run_id, body, *, kind, _api_server):
+ from gateway.platforms.api_server_authority_runs import respond_run
+ from hermes_state_runtime import RuntimeStoreError
+ try:
+ result = await respond_run(self, run_id, body, kind=kind)
+ return web.json_response({'run_id': run_id, **result})
+ except RuntimeStoreError as exc:
+ return _json_error(_api_server._openai_error, exc.reason, code=exc.reason, status=409)
+
+
+async def _handle_run_clarify(self, request, *, _api_server):
+ run_id, _, _, _, err = _load_owned_run(
+ self, request, _api_server=_api_server, permission="approve", active_fallback=False)
+ if err is not None:
+ return err
+ body, err = await self._read_json_body(request)
+ if err is not None:
+ return err
+ return await _respond_authority_run(self, run_id, body, kind='clarify', _api_server=_api_server)
+
+
- async def _handle_steer_run(self, request: "web.Request", *, _api_server) -> "web.Response":
+ async def _handle_steer_run(self, request: web.Request, *, _api_server) -> web.Response:
"""POST /v1/runs/{run_id}/steer — inject guidance into a running agent."""
_openai_error = _api_server._openai_error
run_id, status, agent, _, err = _load_owned_run(
@@@ -1426,28 -1274,6 +1426,28 @@@ async def _handle_stop_run(self, reques
return web.json_response({"run_id": run_id, "status": "stopping"})
+async def _handle_resolve_unknown_run(
- self, request: "web.Request", *, _api_server
- ) -> "web.Response":
++ self, request: web.Request, *, _api_server
++) -> web.Response:
+ """POST /v1/runs/{run_id}/resolve-unknown — acknowledge one lost owner epoch."""
+ run_id, _, _, _, err = _load_owned_run(
+ self, request, _api_server=_api_server, permission="stop", active_fallback=False)
+ if err is not None:
+ return err
+ try:
+ body = await request.json()
+ except (ValueError, LookupError): # bad JSON/UTF-8 (ValueError) or unknown charset: no body
+ body = None
+ from gateway.platforms.api_server_authority_runs import resolve_unknown_run
+ from hermes_state_runtime import RuntimeStoreError
+ try:
+ result = await resolve_unknown_run(self, run_id, body)
+ return web.json_response({'run_id': run_id, **result})
+ except RuntimeStoreError as exc:
+ return _json_error(
+ _api_server._openai_error, exc.reason, code=exc.reason, status=409)
+
+
async def _sweep_orphaned_runs(self) -> None:
"""Periodically expire transport buffers and terminal status records."""
while True:
diff --cc gateway/platforms/msgraph_webhook.py
index a8a1a9602b5,540a8a26fe7..5e974634bb2
--- a/gateway/platforms/msgraph_webhook.py
+++ b/gateway/platforms/msgraph_webhook.py
@@@ -195,15 -195,15 +195,15 @@@ class MSGraphWebhookAdapter(BasePlatfor
# retrying; legitimate Graph retries carry a valid clientState → accepted/duplicate paths.
return "auth"
receipt_key = f"id:{explicit_id}" if (explicit_id := str(notification.get("id") or "").strip()) else None
+ if self._notification_scheduler is not None and receipt_key in self._seen_receipts:
+ return "duplicate"
+ await self._schedule_notification(notification, self._build_message_event(notification, receipt_key))
if receipt_key is not None:
- if receipt_key in self._seen_receipts:
- return "duplicate"
self._remember_receipt(receipt_key)
self._accepted_count += 1
- self._schedule_notification(notification, self._build_message_event(notification, receipt_key))
return "accepted"
- async def _handle_notification(self, request: "web.Request") -> "web.Response":
+ async def _handle_notification(self, request: web.Request) -> web.Response:
if not self._source_ip_allowed(request):
return web.Response(status=403)
# Graph never sends validationToken on POST, but tolerate clients replaying it in-band.
diff --cc gateway/platforms/webhook.py
index 40d04308531,786aa499756..36dff0224fd
--- a/gateway/platforms/webhook.py
+++ b/gateway/platforms/webhook.py
@@@ -22,7 -22,6 +22,7 @@@ import subproces
import time
import uuid
from collections import deque
- from datetime import datetime, timezone
++from datetime import datetime, timezone, UTC
from contextlib import nullcontext, suppress
from dataclasses import dataclass
from typing import Any, Deque, Dict, List, Optional
@@@ -316,16 -307,8 +316,16 @@@ class WebhookAdapter(BasePlatformAdapte
if is_autonomous_silence_response(content):
logger.info("[webhook] Response for %s is a silence marker — not delivering", chat_id)
return SendResult(success=True)
- delivery = self._delivery_info.get(chat_id, {})
- deliver_type = delivery.get("deliver", "log")
+ from gateway.platforms.webhook_delivery import retained_destination
+ try:
+ delivery = retained_destination(self, chat_id)
+ except Exception:
+ logger.warning("[webhook] Destination unavailable for %s", chat_id, exc_info=True)
+ return SendResult(success=False, error="Webhook destination unavailable or unauthorized")
+ return await self._deliver_to(delivery, chat_id, content)
+
- async def _deliver_to(self, delivery: Dict[str, Any], chat_id: str, content: str) -> SendResult:
++ async def _deliver_to(self, delivery: dict[str, Any], chat_id: str, content: str) -> SendResult:
+ deliver_type = delivery["deliver"]
if deliver_type == "log":
logger.info("[webhook] Response for %s: %s", chat_id, content[:200])
return SendResult(success=True)
@@@ -717,43 -695,22 +717,43 @@@
delivery_id=delivery_id, now=now, route_config=route_config, profile=profile):
return web.json_response({"status": "coalesced", "route": route_name, "event": event_type,
"delivery_id": delivery_id}, status=202)
- return self._dispatch_agent_run(request, route_config, route_name, profile, payload, prompt, event_type,
+ return await self._dispatch_agent_run(request, route_config, route_name, profile, payload, prompt, event_type,
delivery_id, now)
- def _dispatch_agent_run(self, request, route_config: dict, route_name: str, profile, payload: Any, prompt: str,
+ async def _dispatch_agent_run(self, request, route_config: dict, route_name: str, profile, payload: Any, prompt: str,
- event_type: str, delivery_id: str, now: float) -> "web.Response":
+ event_type: str, delivery_id: str, now: float) -> web.Response:
- """Spawn the agent run for one POST and return 202 immediately."""
+ """Acknowledge only after the authority commits the immutable delivery."""
logger.info("[webhook] %s event=%s route=%s prompt_len=%d delivery=%s", request.method, event_type, route_name,
len(prompt), delivery_id)
- self._spawn_agent_run(payload, prompt, delivery_id, now, route_config=route_config, route_name=route_name,
- profile=profile, event_type=event_type)
+ outcome = await self._admit_agent_run(payload, prompt, delivery_id, now, route_config=route_config,
+ route_name=route_name, profile=profile, event_type=event_type)
+ if outcome is None:
+ return _json_error("Admission unavailable; retry this delivery", 503)
+ if outcome == "duplicate":
+ return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)
return web.json_response({"status": "accepted", "route": route_name, "event": event_type,
"delivery_id": delivery_id}, status=202)
def _spawn_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,
- route_name: str, profile, event_type: str) -> "asyncio.Task":
+ route_name: str, profile, event_type: str) -> asyncio.Task:
- """Record delivery info and fire the agent run (shared by the immediate and coalesced paths)."""
+ """Coalesced-path dispatch (settled timer / disconnect flush): admit the merged event as a task
+ so ``WebhookCoalescer.flush`` can await the hand-off. The HTTP ack for these deliveries was
+ already ``coalesced``; an admission failure is logged, never retried by the producer."""
+ async def _admit_or_log():
+ outcome = await self._admit_agent_run(payload, prompt, delivery_id, now, route_config=route_config,
+ route_name=route_name, profile=profile, event_type=event_type)
+ if outcome is None:
+ logger.error("[webhook] Coalesced delivery %s on route %s was not admitted", delivery_id, route_name)
+ task = asyncio.create_task(_admit_or_log())
+ self._background_tasks.add(task)
+ task.add_done_callback(self._background_tasks.discard)
+ return task
+
+ async def _admit_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,
+ route_name: str, profile, event_type: str) -> Optional[str]:
+ """Record delivery info and admit the run through the durable producer (shared by the immediate
+ and coalesced paths). ``"accepted"`` / ``"duplicate"``, or None when admission failed."""
+ # (profile, route, delivery_id) in the session key → concurrent webhooks get independent runs.
identity = _WebhookDeliveryIdentity.from_parts(profile, route_name, delivery_id)
session_chat_id = identity.session_chat_id
# ``profile`` rides along so the reply leg (``send`` → ``_deliver_cross_platform``) egresses through
@@@ -771,52 -728,41 +771,52 @@@
if profile and isinstance(profile, str):
source.profile = profile
event = MessageEvent(text=prompt, message_type=MessageType.TEXT, source=source, raw_message=payload,
- message_id=delivery_id, timestamp=datetime.fromtimestamp(0, timezone.utc))
- message_id=delivery_id)
- # The per-delivery session is closed by ``on_processing_complete`` once the run finishes
- # (``handle_message`` is fire-and-forget, so nothing can be closed here).
- task = asyncio.create_task(self.handle_message(event))
++ message_id=delivery_id, timestamp=datetime.fromtimestamp(0, UTC))
+ from gateway.platforms.webhook_ingress import admit_producer
+ try:
+ receipt = await admit_producer(self, event)
+ except Exception:
+ logger.exception("[webhook] Durable admission failed for %s", delivery_id)
+ return None
+ if getattr(event, '_webhook_duplicate', False):
+ return "duplicate"
+ if receipt is None:
+ # A post_gateway_admission plugin consumed the delivery: nothing was committed, so the
+ # reply goes to the destination this request just validated, not a retained row.
+ reply = getattr(event, '_consumer_reply', None)
+ if reply:
+ from gateway.platforms.webhook_delivery import snapshot_destination
+ await self._deliver_to(snapshot_destination(self, self._delivery_info.get(session_chat_id)),
+ session_chat_id, reply)
+ return "accepted"
+ from gateway.session_authorities import active_authority, authority_for_profile_id
+ runner = self._message_handler.__self__
+ authority = authority_for_profile_id(runner, receipt.ref.profile_id) or active_authority(runner)
+ task = asyncio.create_task(self._finalize_delivery(event, authority, receipt))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
- return task
+ return "accepted"
- async def on_processing_complete(self, event: MessageEvent, outcome: Any) -> None:
- """Close the one-shot per-delivery session: ``prune_sessions`` only reaps rows with ``ended_at`` set, so
- unclosed webhook sessions leak unbounded. Fires at the true end of the run; ``end_session()`` is
- first-reason-wins."""
- await self._end_webhook_session(event, event.source.chat_id)
+ async def _finalize_delivery(self, event, authority, receipt):
+ from hermes_state_runtime import get_session_admission
+ try:
+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)
+ if row['status'] in {'queued', 'started'}:
+ waiter = authority.waiters.setdefault(receipt.admission_id,
+ asyncio.get_running_loop().create_future())
+ await asyncio.shield(waiter)
+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)
+ event._webhook_receipt = (authority, authority._receipt(row))
+ await self._end_webhook_session(event, event.source.chat_id)
+ except Exception:
+ logger.exception("[webhook] Could not finalize admitted delivery %s", receipt.admission_id)
- async def _end_webhook_session(self, event: "MessageEvent", session_chat_id: str) -> None:
+ async def _end_webhook_session(self, event: MessageEvent, session_chat_id: str) -> None:
- """Mark the per-delivery session ended via ``SessionDB.end_session`` (never a hand-written UPDATE),
- resolving session_id from the SAME source the run was keyed on."""
- runner = self.gateway_runner
- session_db, store = getattr(runner, "_session_db", None), getattr(runner, "session_store", None)
- key_fn = getattr(runner, "_session_key_for_source", None)
- if runner is None or session_db is None or store is None or key_fn is None:
- return
- try:
- session_key = key_fn(event.source)
- session_id = _peek_session_id(store, session_key)
- if not session_id:
- logger.debug("[webhook] No session_id to close for %s (key=%s)", session_chat_id, session_key)
- return
- # AsyncSessionDB forwards end_session via to_thread; plain SessionDB is sync.
- result = session_db.end_session(session_id, "webhook_complete")
- if asyncio.iscoroutine(result):
- await result
- logger.debug("[webhook] Closed session %s for delivery %s", session_id, session_chat_id)
- except Exception as e:
- logger.debug("[webhook] Failed to close session for %s: %s", session_chat_id, e)
+ from gateway.platforms.webhook_ingress import finalize_webhook
+ binding = getattr(event, '_webhook_receipt', None)
+ if binding is not None:
+ authority, receipt = binding
+ finalize_webhook(authority, receipt)
# --- Signature validation ---
diff --cc gateway/run.py
index 9bf5928af59,f75b987a58a..6e4e90ca0de
--- a/gateway/run.py
+++ b/gateway/run.py
@@@ -1649,13 -1638,8 +1649,13 @@@ class HygieneTurnHoldExceeded(Exception
must NOT take the idle-timeout path (AGENT_COMPRESSION_TIMEOUT, "no output", failure cooldown)."""
- def _multiplex_profile_homes(config: object) -> list[tuple[str, "Path"]]:
+ def _multiplex_profile_homes(config: object) -> list[tuple[str, Path]]:
- """Return the authoritative profile set for one multiplex gateway config."""
+ """The profile set this multiplexer SERVES: the process reservation once boot took it (grown
+ and shrunk by the hot-serve reconcile, which diffs it against what exists under ``profiles/``
+ via ``profiles_to_serve``), else the live directory read for pre-reservation callers."""
+ reserved = getattr(config, "_runtime_profile_homes", None)
+ if reserved is not None:
+ return list(reserved)
from hermes_cli.profiles import profiles_to_serve
return list(profiles_to_serve(multiplex=True))
diff --cc gateway/run_inbound.py
index 69170445da0,888d40e2bb3..3a77cac420c
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@@ -65,12 -64,49 +65,12 @@@ def strip_discord_triggering_note(event
if not message_id or not isinstance(message_text, str):
return message_text
prefix = f"{discord_triggering_note(message_id)}\n\n"
- return message_text[len(prefix):] if message_text.startswith(prefix) else message_text
+ return message_text.removeprefix(prefix)
-class GatewayInboundMixin(GatewayPluginInjectionMixin):
+class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin):
"""Inbound message pipeline (_handle_message, text/media preparation, durable-turn markers, plugin injection) for GatewayRunner."""
- async def _hm_pre_gateway_dispatch_hook(
- self, event: MessageEvent, source: SessionSource
- ) -> Optional[MessageEvent]:
- """Run the ``pre_gateway_dispatch`` plugin hook; None = drop, else the (maybe rewritten) event.
- Results: ``{"action": "skip"}`` → drop; ``{"action": "rewrite", "text"}`` → replace ``event.text``;
- ``allow``/None → normal dispatch. Runs BEFORE auth so plugins can handle unauthorized senders."""
- try:
- from hermes_cli.lifecycle import ainvoke_hook as _ainvoke_hook
- _hook_results = await _ainvoke_hook(
- "pre_gateway_dispatch", event=event, gateway=self,
- # getattr: bare-runner tests build GatewayRunner via object.__new__ without __init__.
- session_store=getattr(self, "session_store", None),
- )
- except Exception as _hook_exc:
- logger.warning("pre_gateway_dispatch invocation failed: %s", _hook_exc)
- _hook_results = []
-
- for _result in _hook_results:
- if not isinstance(_result, dict):
- continue
- _action = _result.get("action")
- if _action == "skip":
- logger.info(
- "pre_gateway_dispatch skip: reason=%s platform=%s chat=%s",
- _result.get("reason"), source.platform.value if source.platform else "unknown",
- source.chat_id or "unknown",
- )
- return None
- if _action == "rewrite":
- _new_text = _result.get("text")
- if isinstance(_new_text, str):
- event = dataclasses.replace(event, text=_new_text)
- break
- if _action == "allow":
- break
- return event
-
async def _hm_offer_pairing_code(self, source: SessionSource) -> None:
"""DM an unauthorized sender a pairing code (rate-limited; groups never reach here)."""
platform_name = source.platform.value if source.platform else "unknown"
@@@ -654,45 -690,8 +654,45 @@@
# — that copy was never consumed and grew unbounded.
running_agent.interrupt(_interrupt_text)
- async def _hm_busy_preempt(self, event: "MessageEvent", source: SessionSource, _quick_key: str) -> bool:
++ async def _hm_busy_preempt(self, event: MessageEvent, source: SessionSource, _quick_key: str) -> bool:
+ """busy_input_mode for a follow-up the durable FIFO is about to admit. Returns True when the
+ text already landed inside the running turn (steer / redirect), so it must NOT also be
+ admitted as its own turn; False when the caller should admit it (queue mode, a demotion,
+ or an interrupt — the ended turn lets the FIFO run the follow-up next)."""
+ from gateway.run import _AGENT_PENDING_SENTINEL
+ mode = self._effective_busy_input_mode(source)
+ state = self._peek_session_state(_quick_key)
+ running_agent = state.turn.agent if state else None
+ if (mode == "queue" or self._draining or running_agent is None
+ or running_agent is _AGENT_PENDING_SENTINEL or not self._hm_text_only(event)):
+ return False
+ text = (event.text or "").strip()
+ if not text:
+ return False
+ if mode == "steer":
+ if hasattr(running_agent, "steer"):
+ try:
+ return bool(self._steer_running_agent(running_agent, self._steer_text_with_origin(text, event)))
+ except Exception as exc:
+ logger.warning("PRIORITY steer failed for session %s: %s", _quick_key, exc, exc_info=True)
+ return False
+ if self._agent_has_active_subagents(running_agent):
+ logger.info("PRIORITY interrupt demoted to queue for session %s because the running agent has active subagents (#30170)", _quick_key)
+ return False
+ if await self._session_has_compression_in_flight(_quick_key):
+ logger.info("PRIORITY interrupt demoted to queue for session %s because context compression is in flight (#56391)", _quick_key)
+ return False
+ if (getattr(running_agent, "_supports_active_turn_redirect", False) is True and hasattr(running_agent, "redirect")
+ and self._redirect_active_turn(running_agent, text, _quick_key, event)):
+ logger.debug("PRIORITY redirect for session %s", _quick_key)
+ return True
+ # No redirect: end the running turn; the follow-up is admitted and runs as the next turn.
+ logger.debug("PRIORITY interrupt for session %s", _quick_key)
+ running_agent.interrupt()
+ return False
+
async def _hm_handle_running_session_message(
- self, event: "MessageEvent", source: SessionSource, _quick_key: str
+ self, event: MessageEvent, source: SessionSource, _quick_key: str
) -> Optional[str]:
"""Fast-path while this session's agent is running: interrupt by default (minimal latency);
busy_input_mode queue/steer, subagent and compression protection demote to queue."""
@@@ -745,8 -744,72 +745,8 @@@
self._queue_or_replace_pending_event(_quick_key, event)
return None
- def _hm_quick_commands(self) -> dict:
- """User-defined ``quick_commands`` mapping from config (empty dict when unset/malformed)."""
- cfg = self.config
- qc = (cfg.get("quick_commands") if isinstance(cfg, dict) else getattr(cfg, "quick_commands", None)) or {}
- return qc if isinstance(qc, dict) else {}
-
- @staticmethod
- def _hm_expand_alias_quick_command(event: MessageEvent, qcmd: dict) -> Optional[str]:
- """Rewrite ``event.text`` to an alias quick command's target; returns the new command name."""
- target = (qcmd.get("target") or "").strip()
- if not target:
- return None
- target = target if target.startswith("/") else f"/{target}"
- event.text = f"{target} {event.get_command_args().strip()}".strip()
- target_command = target.lstrip("/")
- return target_command.split()[0] if target_command else target_command
-
- async def _hm_command_hooks(
- self, event: MessageEvent, source: SessionSource, _quick_key: str, command: str, canonical: str
- ) -> tuple[bool, Optional[str], Optional[str]]:
- """Fire ``pre_command`` (observer) and ``command:<canonical>`` (interceptor) hooks →
- ``(handled, result, new_command)`` (``new_command`` set when a handler rewrote the command).
- The running-agent path deliberately does NOT fire these — a slow or hostile plugin must not
- interfere with the operator's escape hatches for a live agent."""
- raw_args = event.get_command_args().strip()
- platform = source.platform.value if source.platform else ""
- try:
- from hermes_cli.plugins import fire_pre_command_hook
- fire_pre_command_hook(
- surface="gateway", command=str(canonical), alias_used=str(command),
- args_raw=raw_args, session_key=_quick_key, platform=platform,
- )
- except Exception as _pre_cmd_err:
- logger.debug("pre_command hook dispatch failed (non-fatal): %s", _pre_cmd_err)
-
- # Handlers may return ``{"decision": "deny" | "handled" | "rewrite", ...}`` to intercept
- # dispatch; handlers returning nothing behave as plain observers.
- hook_ctx = {
- "platform": platform, "user_id": source.user_id, "command": canonical,
- "raw_command": command, "args": raw_args, "raw_args": raw_args,
- }
- try:
- hook_results = await self.hooks.emit_collect(f"command:{canonical}", hook_ctx)
- except Exception as _hook_err:
- logger.debug("command:%s hook dispatch failed (non-fatal): %s", canonical, _hook_err)
- hook_results = []
-
- for hook_result in hook_results:
- if not isinstance(hook_result, dict):
- continue
- decision = str(hook_result.get("decision", "")).strip().lower()
- message = hook_result.get("message")
- message = message if isinstance(message, str) and message else None
- if decision == "deny":
- return True, message or t("gateway.hooks.command_blocked", command=command), None
- if decision == "handled":
- return True, message, None
- if decision == "rewrite":
- new_command = str(hook_result.get("command_name", "")).strip().lstrip("/")
- if new_command:
- event.text = f"/{new_command} {str(hook_result.get('raw_args', '')).strip()}".strip()
- return False, None, event.get_command()
- return False, None, None
-
async def _hm_resolve_command(
- self, event: "MessageEvent", source: SessionSource, _quick_key: str
+ self, event: MessageEvent, source: SessionSource, _quick_key: str
) -> tuple[bool, Optional[str], Optional[str], Optional[str]]:
"""Resolve the slash command (aliases, access gate, hooks) → ``(handled, result, command,
canonical)``; when ``handled`` the caller returns ``result`` as-is (may be None)."""
@@@ -961,8 -1024,88 +961,8 @@@
return await getattr(self, f"_hm_cmd_{canonical.replace('-', '_')}")(event, source, _quick_key)
return False, None
- async def _hm_run_exec_quick_command(self, command: str, exec_cmd: str) -> str:
- """Run a ``type: exec`` quick command in the gateway process (30 s cap, sanitized env — the
- gateway process has every API key in os.environ; output is redacted too)."""
- try:
- from tools.environments.local import build_subprocess_env
- proc = await asyncio.create_subprocess_shell(
- exec_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
- env=build_subprocess_env(),
- )
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
- output = (stdout or stderr).decode().strip()
- if output:
- from agent.redact import redact_sensitive_text
- output = redact_sensitive_text(output)
- return output or t("gateway.quick_command.no_output")
- except TimeoutError:
- return t("gateway.quick_command.timed_out")
- except Exception as e:
- return t("gateway.quick_command.error", error=e)
-
- async def _hm_dispatch_quick_and_plugin_commands(
- self, event: MessageEvent, source: SessionSource, command: Optional[str]
- ) -> tuple[bool, Optional[str], Optional[str]]:
- """Drain gate, user-defined quick commands (exec/alias) and plugin slash commands →
- ``(handled, result, command)``; an alias quick command rewrites ``command``."""
- if self._draining:
- return True, t("gateway.busy.drain_rejected_new_work", action=self._status_action_gerund()), command
-
- # User-defined quick commands (bypass agent loop, no LLM call)
- qcmd = self._hm_quick_commands().get(command) if command else None
- if qcmd is not None:
- # Quick commands are slash capabilities too — and type:exec ones run a shell command in
- # the gateway process. They are never in the registry, so the early gate never fires for
- # them; apply the same admin/user policy to the raw typed name here.
- # The early gate above only fires for registry-known commands, so quick commands (never in the
- # registry) would otherwise reach this dispatch sink unchecked. (#44727)
- _denied = self._check_slash_access(source, command)
- if _denied is not None:
- return True, _denied, command
- qtype = qcmd.get("type")
- if qtype == "exec":
- exec_cmd = qcmd.get("command", "")
- if not exec_cmd:
- return True, t("gateway.quick_command.no_command", command=command), command
- return True, await self._hm_run_exec_quick_command(command, exec_cmd), command
- if qtype != "alias":
- return True, t("gateway.quick_command.unsupported_type", command=command), command
- new_command = self._hm_expand_alias_quick_command(event, qcmd)
- if new_command is None:
- return True, t("gateway.quick_command.no_target", command=command), command
- command = new_command # Fall through to normal command dispatch below
-
- # Plugin-registered slash commands. Underscores normalize to hyphens so Telegram's
- # underscored autocomplete form matches plugin commands registered with hyphens.
- if command:
- try:
- from hermes_cli.plugins import get_plugin_command_handler
- plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
- if plugin_handler:
- # The agent-turn path binds HERMES_SESSION_* via _set_session_env; this dispatch
- # sits before it, so a handler reading get_session_env() would see an empty or a
- # foreign (cron agent's os.environ) session (#108698). No session_entry exists yet,
- # so session_key is derived from source. Sync handlers run on the gateway pool
- # (contextvars carried), never the loop thread: blocking I/O there starves the
- # liveness watchdog and the process exits 75 mid-handler (#105279).
- _plugin_context = build_session_context(source, self.config)
- _plugin_context.session_key = self._session_key_for_source(source)
- user_args = event.get_command_args().strip()
- with self._session_env_scope(_plugin_context):
- if asyncio.iscoroutinefunction(plugin_handler):
- result = await plugin_handler(user_args)
- else:
- result = await self._run_in_executor_with_context(plugin_handler, user_args)
- if asyncio.iscoroutine(result):
- result = await result
- return True, str(result) if result else None, command
- except Exception as e:
- logger.warning("Plugin command dispatch failed: %s", e)
- return False, None, command
-
def _hm_bundle_slash_rewrite(
- self, event: "MessageEvent", source: SessionSource, _quick_key: str, command: str
+ self, event: MessageEvent, source: SessionSource, _quick_key: str, command: str
) -> bool:
"""Rewrite ``/<bundle>`` to the bundle invocation message; True when handled.
Skill bundles take precedence over individual skill commands (mirrors CLI dispatch)."""
diff --cc gateway/run_profile_reconcile.py
index f2a786e3bdf,c22e839725f..fdb0957f403
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@@ -132,9 -128,9 +132,9 @@@ class GatewayProfileReconcileMixin
# (wait_for cancels the still-queued await), never the event loop.
try:
pid = await asyncio.wait_for(
- self._run_housekeeping_in_executor(live_gateway_pid_for_home, current[name]),
+ self._run_housekeeping_in_executor(live_gateway_pid_for_home, live[name]),
timeout=_OWN_GATEWAY_PROBE_TIMEOUT_SECS)
- except asyncio.TimeoutError:
+ except TimeoutError:
# Unprovable is not "own gateway running": skip it this cycle without
# warning about (or remembering) a gateway that may not exist. Warn once
# per stall; a peer that stays wedged repeats at DEBUG every cycle.
diff --cc gateway/run_shutdown.py
index cb58f2313f1,7c04fc4dd1b..3ada928fca5
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@@ -2122,11 -2122,13 +2122,11 @@@ class GatewayShutdownMixin(GatewaySessi
_step("Shared SessionDB close error", _close_shared)
logger.info("Shutdown phase: SessionDB close done at +%.2fs", ctx.elapsed())
- async def _stop_persist_exit_state(self, ctx: "GatewayShutdownMixin._StopContext") -> None:
+ async def _stop_persist_exit_state(self, ctx: GatewayShutdownMixin._StopContext) -> None:
- """PID/lock release, clean-shutdown marker, restart markers, terminal runtime status."""
+ """Clean-shutdown marker, restart markers, terminal runtime status; process bootstrap
+ releases PID/lock ownership after the writer drain."""
from gateway.run import _hermes_home, _planned_restart_notification_path, _shutdown_gateway_health_export
from utils import atomic_json_write
- from gateway.status import remove_pid_file, release_gateway_runtime_lock
- remove_pid_file()
- release_gateway_runtime_lock()
# Clean-shutdown marker skips crash-turn recovery next boot; a timed-out drain left
# half-finished sessions, so no marker — the next startup recovers their turn markers.
if not ctx.timed_out:
diff --cc gateway/run_turn.py
index cf84fa93c7a,bcfd8e18fc4..95db158f339
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@@ -1626,11 -3553,11 +1626,11 @@@ class GatewayTurnMixin(GatewayTurnPrepa
"tools": tools_holder[0] or [],
"history_offset": 0,
"failed": True,
- }
+ })
async def _run_agent_await_turn_worker(
- self, worker: "GatewayRunner._RunAgentWorker", turn_ctx: TurnContext,
- _interrupt_detected: "asyncio.Event", interrupt_monitor: "asyncio.Task",
+ self, worker: GatewayRunner._RunAgentWorker, turn_ctx: TurnContext,
+ _interrupt_detected: asyncio.Event, interrupt_monitor: asyncio.Task,
) -> Any:
"""Poll the executor future (inactivity timeout + backup interrupt checks); return its result,
or a synthetic failed run dict on inactivity timeout. Polls even with an unlimited timeout
diff --cc gateway/run_turn_runner.py
index 1bf81195fb0,7e29a4cdf8c..88c9bbc4421
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@@ -111,46 -75,842 +111,46 @@@ class _ExecApprovalDeclined(RuntimeErro
"""
-class TurnRunner:
+from gateway.run_turn_progress import GatewayTurnProgressMixin
+from gateway.session_execution import GatewaySessionAgentMixin
+
+
+class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
"""Per-turn collaborator carrying ``GatewayRunner._run_agent_inner``'s tool-progress callbacks."""
+ # ``None`` is a legitimate state: a turn with no owning session authority (messaging
+ # adapters without a canonical session) publishes no execution events and takes no
+ # controls snapshot. Class-level so every publish/snapshot seam can read it unconditionally.
+ _approval_owner = None
+
- def __init__(self, runner: "GatewayRunner", ctx: TurnContext) -> None:
+ def __init__(self, runner: GatewayRunner, ctx: TurnContext) -> None:
self._runner = runner
self._ctx = ctx
-
- # ── shared thread→loop plumbing ─────────────────────────────────────────────────────────
-
- def _schedule(self, coro, log_message: str, loop=None):
- """Hop a coroutine from the agent's sync worker thread onto the gateway loop."""
- from gateway.run import safe_schedule_threadsafe
- return safe_schedule_threadsafe(
- coro, self._ctx._loop_for_step if loop is None else loop, logger=logger, log_message=log_message,
- )
-
- def _agent_interrupted(self) -> bool:
- """True once the user sent `stop` (agent_holder[0] is the shared agent handle)."""
- try:
- agent = self._ctx.agent_holder[0] if self._ctx.agent_holder else None
- return bool(agent is not None and getattr(agent, "is_interrupted", False))
- except Exception:
- return False
-
- def _stream_consumer(self):
- holder = self._ctx.stream_consumer_holder
- return holder[0] if holder else None
-
- def _drain_progress_queue(self) -> None:
- q = self._ctx.progress_queue
- with suppress(Exception):
- while not q.empty():
- q.get_nowait()
-
- def _track_progress_result(self, result) -> None:
- """Remember a delivered progress/status message id for end-of-turn cleanup."""
- ctx = self._ctx
- if ctx._cleanup_progress and getattr(result, "success", False) and getattr(result, "message_id", None):
- ctx._cleanup_msg_ids.append(str(result.message_id))
-
- def _track_future_cleanup_id(self, fut) -> None:
- try:
- res = fut.result()
- except Exception:
- return
- self._track_progress_result(res)
-
- # ── progress_callback (agent thread → progress queue) ───────────────────────────────────
-
- def progress_callback(self, event_type: str, tool_name: str | None = None, preview: str | None = None, args: dict | None = None, **kwargs):
- """Callback invoked by agent on tool lifecycle events."""
- ctx = self._ctx
- # Failed subagent → one clean user-facing notice, handled FIRST, before every progress-queue
- # gate: platforms with tool_progress off must still hear about a dead delegation.
- if event_type == "subagent.complete":
- self._progress_subagent_notice(preview, kwargs)
- return
- self._progress_live_status(event_type, tool_name, args)
- # "log" mode: append tool.started lines to the log queue, silent in chat. Handled before
- # the progress_queue guard because log mode runs without a chat progress queue.
- if ctx.log_queue is not None and event_type == "tool.started" and tool_name and tool_name != "_thinking":
- ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- preview_str = f' "{preview}"' if preview else ""
- ctx.log_queue.put(f"{ts} {tool_name}:{preview_str}".rstrip())
- if not ctx.progress_queue or not ctx._run_still_current():
- return
- if event_type == "tool.completed" and not ctx.long_tool_hint_fired[0]:
- self._progress_onboarding_hint(kwargs)
- return
- # "_thinking" is assistant scratch text between tool calls, never ordinary tool progress:
- # only relayed when the platform explicitly opted into thinking_progress.
- if event_type == "_thinking" or tool_name == "_thinking":
- thinking_text = (preview if tool_name == "_thinking" else tool_name) if ctx._thinking_enabled else None
- if thinking_text:
- ctx.progress_queue.put(t("gateway.progress.thinking_prefix", text=thinking_text))
- return
- # Native task cards consume the ID-bearing tool_start/tool_complete callbacks instead;
- # name-correlated text events would duplicate cards and mispair concurrent same-tool calls.
- if ctx._native_slack_task_cards and event_type in {"tool.started", "tool.completed"}:
- return
- # tool_progress off → only _thinking passes (above). Only tool.started renders. clarify:
- # send_clarify IS the user-facing rendering (a bubble would duplicate it, and verbose mode
- # would dump the raw args JSON right under the prompt). Post-`stop`: N parallel tool calls
- # fire N tool.started events before the interrupt check, so a late stop must not render them.
- if (
- not ctx.tool_progress_enabled
- or event_type != "tool.started"
- # The adapter's send_clarify IS the user-facing rendering (interactive buttons or the
- # numbered-text fallback), so a progress bubble is pure duplication — and in verbose mode it
- # dumps the raw tool-call args JSON into the chat. Because
- # the progress queue drains on a background task, that raw JSON typically lands right underneath
- # the rendered prompt (#52374).
- or tool_name == "clarify"
- or self._agent_interrupted()
- ):
- return
- # "new" mode: only report when tool changes
- if ctx.progress_mode == "new" and tool_name == ctx.last_tool[0]:
- return
- ctx.last_tool[0] = tool_name
- msg = self._progress_build_message(tool_name, preview, args)
- if msg is not None:
- self._progress_emit(msg)
-
- def _progress_subagent_notice(self, preview, kwargs: dict) -> None:
- """Only terminal failure statuses render (same notice rail as credit warnings)."""
- ctx = self._ctx
- from gateway.warning_notifications import render_notification
- status = kwargs.get("status")
- try:
- from tools.delegate_tool import SUBAGENT_FAILURE_STATUSES, format_subagent_failure_line
- if status in SUBAGENT_FAILURE_STATUSES and ctx._run_still_current():
- line = format_subagent_failure_line(
- kwargs.get("goal"), status, error=kwargs.get("summary") or preview,
- duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),
- )
- render_notification(
- lambda: self._schedule(self._runner._deliver_platform_notice(ctx.source, line), "subagent failure notice scheduling error"),
- platform=ctx.source.platform, user_config=ctx.user_config)
- except Exception:
- logger.debug("subagent failure notice failed", exc_info=True)
-
- def _progress_live_status(self, event_type: str, tool_name, args) -> None:
- """Live status line (Slack assistant status): stash the tool phrase on the adapter; the
- _keep_typing refresh renders it. Plain dict write, safe from the sync worker thread."""
- ctx = self._ctx
- adapter = ctx._live_status_adapter
- if adapter is None or ctx._live_status_mode == "off" or tool_name == "_thinking":
- return
- try:
- if event_type == "tool.started" and tool_name and ctx._run_still_current():
- from agent.display import build_status_phrase
- adapter.set_status_text(ctx.source.chat_id, build_status_phrase(tool_name, args if ctx._live_status_mode == "full" else None))
- elif event_type == "tool.completed":
- # Between tools the model is genuinely "thinking" again — revert to the static default.
- adapter.set_status_text(ctx.source.chat_id, None)
- except Exception as err:
- logger.debug("live status update failed: %s", err)
-
- def _progress_onboarding_hint(self, kwargs: dict) -> None:
- """First-touch onboarding: the first time a tool exceeds _LONG_TOOL_THRESHOLD_S while
- streaming every tool (progress_mode == "all"), append a one-time /verbose hint."""
- from gateway.run import _hermes_home, _load_gateway_config
- ctx = self._ctx
- try:
- if (kwargs.get("duration") or 0) >= ctx._LONG_TOOL_THRESHOLD_S and ctx.progress_mode == "all":
- from agent.onboarding import TOOL_PROGRESS_FLAG, is_seen, mark_seen, tool_progress_hint_gateway
- cfg = _load_gateway_config()
- gate_on = is_truthy_value(cfg_get(cfg, "display", "tool_progress_command"), default=False)
- if gate_on and not is_seen(cfg, TOOL_PROGRESS_FLAG):
- ctx.long_tool_hint_fired[0] = True
- ctx.progress_queue.put(tool_progress_hint_gateway())
- mark_seen(_hermes_home / "config.yaml", TOOL_PROGRESS_FLAG)
- except Exception as err:
- logger.debug("tool-progress onboarding hint failed: %s", err)
-
- @staticmethod
- def _preview_cap() -> int:
- """tool_preview_length (default 40): the one-line preview budget for "all"/"new" modes."""
- from agent.display import get_tool_preview_max_len
- pl = get_tool_preview_max_len()
- return pl if pl > 0 else 40
-
- def _progress_terminal_blocks(self, adapter, tool_name, args, emoji):
- """(full, short) fenced blocks for a terminal command on markdown platforms, else (None, None).
-
- No language tag: Slack mrkdwn renders it as a literal first code line. Verbose shows the FULL
- command; "all"/"new" truncate to one line capped at ``tool_preview_length``. Consecutive
- terminal calls drop the repeated header so back-to-back commands render as adjacent blocks.
- """
- if not (
- getattr(adapter, "supports_code_blocks", False) and tool_name == "terminal" and isinstance(args, dict)
- and isinstance(args.get("command"), str) and args["command"].strip()
- ):
- return None, None
- cmd_full = args["command"].rstrip()
- header = "" if self._ctx.last_was_terminal_block[0] else t("gateway.progress.tool_head", emoji=emoji, tool=tool_name) + "\n"
- cap = self._preview_cap()
- lines = cmd_full.splitlines()
- cmd_short = lines[0] if lines else cmd_full
- if len(cmd_short) > cap:
- cmd_short = cmd_short[:cap - 3] + "..."
- elif len(lines) > 1:
- cmd_short += " ..."
- return f"{header}```\n{cmd_full}\n```", f"{header}```\n{cmd_short}\n```"
-
- def _progress_build_message(self, tool_name, preview, args) -> Optional[str]:
- """Render the progress line. Verbose mode queues directly (no dedup) and returns None."""
- ctx = self._ctx
- from agent.display import get_tool_emoji
- emoji = get_tool_emoji(tool_name, default="⚙️")
- try:
- adapter = self._runner._delivery_adapter_for(ctx.source)
- except Exception:
- adapter = None
- code_full, code_short = self._progress_terminal_blocks(adapter, tool_name, args, emoji)
- verbose = ctx.progress_mode == "verbose"
- code = code_full if verbose else code_short
- ctx.last_was_terminal_block[0] = code is not None
- if verbose:
- if code is None and args:
- from agent.display import get_tool_preview_max_len
- pl = get_tool_preview_max_len()
- args_str = json.dumps(args, ensure_ascii=False, default=str)
- # tool_preview_length 0 (default) = no truncation in verbose mode; the user asked
- # for full detail and platform message-length limits handle the rest.
- if pl > 0 and len(args_str) > pl:
- args_str = args_str[:pl - 3] + "..."
- code = t("gateway.progress.tool_verbose", emoji=emoji, tool=tool_name, keys=list(args.keys()), args=args_str)
- elif code is None:
- code = (t("gateway.progress.tool_preview", emoji=emoji, tool=tool_name, preview=preview) if preview
- else t("gateway.progress.tool_pending", emoji=emoji, tool=tool_name))
- ctx.progress_queue.put(code)
- return None
- if code is not None:
- return code
- if not preview:
- return t("gateway.progress.tool_pending", emoji=emoji, tool=tool_name)
- from agent.display import get_tool_verb, prepare_tool_preview, tool_verb_connector, verb_drops_preview
- prepared = prepare_tool_preview(tool_name, args, fallback=preview, max_len=self._preview_cap())
- preview = adapter.format_tool_preview(prepared) if adapter is not None else prepared.text
- # Friendly labels: human-phrased line for built-in tools ("🔍 Searching the web for ...")
- # by prefixing the verb onto the computed preview, so the command/url/query is kept.
- verb = get_tool_verb(tool_name)
- if not verb:
- return t("gateway.progress.tool_preview", emoji=emoji, tool=tool_name, preview=preview)
- return f"{emoji} {verb}" if verb_drops_preview(tool_name) else f"{emoji} {verb}{tool_verb_connector(tool_name)}{preview}"
-
- def _progress_emit(self, msg: str) -> None:
- """Dedup consecutive identical lines (execute_code boilerplate), then route to the native
- stream bubble when the consumer accepts tool progress, else the progress queue."""
- ctx = self._ctx
- sc = self._stream_consumer()
- native = sc is not None and getattr(sc, "accepts_tool_progress", False)
- if msg == ctx.last_progress_msg[0]:
- ctx.repeat_count[0] += 1
- if native:
- sc.on_tool_progress(f"{msg} (×{ctx.repeat_count[0] + 1})")
- else:
- ctx.progress_queue.put(("__dedup__", msg, ctx.repeat_count[0]))
- return
- ctx.last_progress_msg[0], ctx.repeat_count[0] = msg, 0
- if native:
- sc.on_tool_progress(msg)
- else:
- ctx.progress_queue.put(msg)
-
- # ── Slack-native task cards (progress-queue drain) ──────────────────────────────────────
-
- @dataclasses.dataclass
- class _TaskCardState:
- """Task-card rail state for ``_send_native_task_card_progress``."""
- adapter: Any
- tasks: dict[str, dict[str, str]] = dataclasses.field(default_factory=dict)
- task_order: list[str] = dataclasses.field(default_factory=list)
- fallback_msg_id: Optional[str] = None
- native_failed: bool = False
- # TERMINAL for the turn, distinct from native_failed: no later publication
- # in this turn may deliver task text through the native lane OR the text
- # fallback. Two causes, both properties of the destination rather than of
- # one attempt: the connector's egress guard refused the chat, or the chat
- # cannot host a card (no thread anchor). Declared rather than set
- # dynamically so the state is visible where it lives.
- publication_suppressed: bool = False
- anonymous_seq: int = 0
-
- @staticmethod
- def _compact(value: Any, limit: int = 120) -> str:
- text = re.sub(r"\s+", " ", str(value or "")).strip()
- return text if len(text) <= limit else text[: limit - 3].rstrip() + "..."
-
- def visible_tasks(self) -> list[dict[str, str]]:
- return [self.tasks[task_id] for task_id in self.task_order[-8:]]
-
- def fallback_text(self) -> str:
- labels = {"in_progress": t("gateway.progress.task_status_running"),
- "complete": t("gateway.progress.task_status_complete"),
- "error": t("gateway.progress.task_status_error")}
- lines = [t("gateway.progress.task_line", title=task["title"], status=labels.get(task["status"], task["status"]))
- for task in self.visible_tasks()]
- return t("gateway.progress.task_card_title") + "\n" + "\n".join(lines)
-
- def _upsert(self, call_id: str, title: str) -> dict[str, str]:
- if call_id not in self.tasks:
- self.task_order.append(call_id)
- self.tasks[call_id] = {"id": call_id, "title": self._compact(title), "status": "in_progress"}
- return self.tasks[call_id]
-
- def apply_event(self, raw: Any) -> bool:
- event_type = raw.get("type") if isinstance(raw, dict) else None
- if event_type not in {"tool.started", "tool.completed"}:
- return False
- call_id = str(raw.get("tool_call_id") or "")
- if not call_id:
- self.anonymous_seq += 1
- call_id = f"anonymous_{self.anonymous_seq}"
- tool_name = str(raw.get("tool_name") or "tool")
- if event_type == "tool.started":
- preview = self._compact(raw.get("preview"), 64)
- self._upsert(call_id, f"{tool_name} - {preview}" if preview else tool_name)
- return True
- # Completion-only events are rare but valid on some runtimes; keep their real ID instead
- # of guessing a same-name pending call.
- task = self.tasks.get(call_id) or self._upsert(call_id, tool_name)
- task["status"] = "error" if raw.get("is_error") else "complete"
- return True
-
- async def _task_card_send_or_edit_fallback(self, st) -> None:
- ctx = self._ctx
- text = st.fallback_text()
- from gateway.relay.egress import declined_send
-
- if st.publication_suppressed:
- return
- if st.fallback_msg_id:
- result = await st.adapter.edit_message(
- chat_id=ctx.source.chat_id, message_id=st.fallback_msg_id, content=text, metadata=ctx._progress_metadata,
- )
- if getattr(result, "success", False):
- return
- # P5(b): R5-4 made a declined native CARD terminal but left this
- # editable-text fallback: a declined edit fell through to
- # _send_progress_text and re-sent the same task text to the refused
- # chat. The decline must set the terminal state here too.
- if declined_send(result):
- logger.warning(
- "Task-card fallback edit DECLINED by the connector's egress "
- "guard; suppressing progress delivery for the rest of this "
- "turn (the destination is not approved)"
- )
- st.publication_suppressed = True
- return
- result = await self._send_progress_text(st, text)
- if getattr(result, "success", False) and getattr(result, "message_id", None):
- st.fallback_msg_id = str(result.message_id)
-
- async def _task_card_publish(self, st) -> None:
- ctx = self._ctx
- if not st.tasks:
- return
- if st.publication_suppressed:
- # Publication was suppressed earlier in the turn (egress refusal or a chat
- # that cannot host a card); every later publication would re-deliver the
- # same task text there.
- return
- # Resolve eligibility in the owning adapter BEFORE transport I/O: a first
- # timeout/disconnect must not turn an un-cardable chat into text fallback.
- # Optional for older adapters; only an explicit False refuses publication.
- destination_supported = getattr(st.adapter, "native_task_card_destination_supported", None)
- if callable(destination_supported) and destination_supported(
- ctx.source.chat_id, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,
- ) is False:
- self._task_card_uncardable_destination(st)
- if st.publication_suppressed:
- return
- if not st.native_failed:
- result = await st.adapter.send_native_task_card_progress(
- chat_id=ctx.source.chat_id, tasks=st.visible_tasks(), title=t("gateway.progress.task_card_title"),
- reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata, fallback_text=st.fallback_text(),
- )
- if getattr(result, "success", False):
- return
- # P5(b): an AUTHORIZATION decline is not a broken card lane. The
- # fallback below sends the same task text to the same chat, which
- # turns a refused card into delivered plain text. Stop the lane
- # without re-delivering; the refusal is already logged.
- from gateway.relay.egress import declined_send
-
- if declined_send(result):
- # TERMINAL, and stored SEPARATELY from native_failed. Reusing
- # native_failed suppressed exactly ONE update: the next progress
- # event skipped this branch (the lane is already "failed") and
- # went straight to the text fallback. A refusal does not expire
- # after one tick.
- st.publication_suppressed = True
- st.native_failed = True
- logger.warning(
- "Slack native task-card progress DECLINED by the connector's "
- "egress guard — suppressing the text fallback for the rest "
- "of this turn (the destination is not approved)"
- )
- return
- st.native_failed = True
- if getattr(result, "error", None) in _CARD_DESTINATION_REFUSALS:
- self._task_card_uncardable_destination(st, getattr(result, "error", "unknown error"))
- if st.publication_suppressed:
- return
- else:
- logger.warning(
- "Slack native task-card progress failed; falling back "
- "to an editable text update: %s", getattr(result, "error", "unknown error"),
- )
- # Once the native rail fails, every later lifecycle event edits the same fallback message.
- await self._task_card_send_or_edit_fallback(st)
-
- def _task_card_uncardable_destination(self, st, reason: str = "no thread anchor") -> None:
- """The chat cannot host a card (flat DM: no thread anchor) — a property of the destination,
- not a transient outage. The text fallback exists to keep a WORKING card lane live through a
- transient failure, not to invent text bubbles the operator never asked for: with Slack's tier
- default (``tool_progress: off``) the lane goes silent for the turn. An operator who WROTE
- ``new``/``all`` asked for text progress, so the editable fallback carries it instead."""
- if self._ctx.tool_progress_enabled:
- st.native_failed = True
- logger.info(
- "Slack native task cards are unsupported for this destination (%s); "
- "tool progress continues as an editable text update", reason,
- )
- return
- st.publication_suppressed = True
- logger.info(
- "Slack native task cards are unsupported for this destination (%s); "
- "tool progress stays off for this turn", reason,
- )
-
- def _task_card_drain(self, st) -> bool:
- changed = False
- try:
- while True:
- changed = st.apply_event(self._ctx.progress_queue.get_nowait()) or changed
- except queue.Empty:
- pass
- except Exception:
- logger.debug("Slack native progress queue drain failed", exc_info=True)
- return changed
-
- async def _send_native_task_card_progress(self, adapter) -> None:
- """Drain progress into native cards; supported destinations retain editable fallback.
- Unsupported destinations and egress refusals suppress publication, never finalization.
-
- See #29483.
- """
- ctx = self._ctx
- st = self._TaskCardState(adapter)
- try:
- while ctx._run_still_current():
- try:
- raw = ctx.progress_queue.get_nowait()
- except queue.Empty:
- await asyncio.sleep(0.1)
- continue
- if not self._agent_interrupted() and st.apply_event(raw):
- await self._task_card_publish(st)
- except asyncio.CancelledError:
- if self._task_card_drain(st) and ctx._run_still_current() and not self._agent_interrupted():
- await self._task_card_publish(st)
- finally:
- if hasattr(adapter, "stop_native_task_card_progress"):
- # Best-effort on the turn-cleanup path: an escaping transport exception would skip
- # final-delivery logic (cleanup awaits catch only CancelledError).
- try:
- await adapter.stop_native_task_card_progress(
- ctx.source.chat_id, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,
- )
- except asyncio.CancelledError:
- raise
- except Exception:
- logger.debug("task-card stop failed during turn cleanup", exc_info=True)
-
- # ── editable progress bubbles (progress-queue drain) ────────────────────────────────────
-
- @dataclasses.dataclass
- class _ProgressEditState:
- """Mutable editable-bubble state shared by ``send_progress_messages`` and its helpers."""
- adapter: Any
- progress_lines: list
- progress_msg_id: Any
- can_edit: bool
- _progress_len_fn: Any
- _PROGRESS_TEXT_LIMIT: int
- _edit_accepts_metadata: bool
-
- def _progress_edit_state(self, adapter) -> TurnRunner._ProgressEditState:
- ctx = self._ctx
- len_fn = adapter.message_len_fn if isinstance(adapter, BasePlatformAdapter) else len
- try:
- raw_limit = int(getattr(adapter, "MAX_MESSAGE_LENGTH", 4000) or 4000)
- except Exception:
- raw_limit = 4000
- # Per-chat resolution (relay adapter fronting N platforms): cap and length unit follow the
- # chat's underlying platform; native adapters return their scalar/property unchanged.
- if isinstance(adapter, BasePlatformAdapter):
- with suppress(Exception):
- raw_limit = int(adapter.max_message_length_for_chat(ctx.source.chat_id) or 4000)
- len_fn = adapter.message_len_fn_for_chat(ctx.source.chat_id)
- return self._ProgressEditState(
- adapter=adapter, progress_lines=[], progress_msg_id=None,
- # "separate" = one message per tool (pre-v0.9 behavior)
- can_edit=ctx.progress_grouping != "separate",
- _progress_len_fn=len_fn,
- # Leave room for platform quirks / formatting; tiny test adapters keep a usable limit.
- _PROGRESS_TEXT_LIMIT=max(1, raw_limit - (64 if raw_limit > 128 else 0)),
- # Overflow edits pass metadata (Telegram topic/thread routing) only when edit_message takes it.
- _edit_accepts_metadata=bool(ctx._progress_metadata) and _accepts_keyword(adapter.edit_message, "metadata"),
- )
-
- async def _edit_progress_message(self, st, message_id: str, content: str):
- ctx = self._ctx
- kwargs = {"chat_id": ctx.source.chat_id, "message_id": message_id, "content": content}
- if getattr(st.adapter, "REQUIRES_EDIT_FINALIZE", False):
- kwargs["finalize"] = True
- if st._edit_accepts_metadata:
- kwargs["metadata"] = ctx._progress_metadata
- return await st.adapter.edit_message(**kwargs)
-
- @staticmethod
- def _progress_text(lines: list) -> str:
- return "\n".join(str(line) for line in lines)
-
- def _split_progress_groups(self, st, lines: list) -> list[list]:
- """Partition progress lines into platform-sized editable bubbles."""
- groups: list[list] = []
- current: list = []
- for line in lines:
- candidate = current + [line]
- if current and st._progress_len_fn(self._progress_text(candidate)) > st._PROGRESS_TEXT_LIMIT:
- groups.append(current)
- candidate = [line]
- current = candidate
- return groups + ([current] if current else [])
-
- async def _send_progress_text(self, st, text: str):
- ctx = self._ctx
- result = await st.adapter.send(
- chat_id=ctx.source.chat_id, content=text, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,
- )
- self._track_progress_result(result)
- return result
-
- async def _roll_progress_overflow_if_needed(self, st) -> bool:
- """Start fresh editable progress bubbles before a bubble exceeds limit.
-
- Returns True when it delivered/split the buffer or a transient edit failure left it
- intact for retry — either way the caller skips the normal send/edit path this tick.
- """
- if not st.progress_lines or not st.can_edit:
- return False
- groups = self._split_progress_groups(st, st.progress_lines)
- if len(groups) <= 1:
- return False
- if st.progress_msg_id is not None:
- result = await self._edit_progress_message(st, st.progress_msg_id, self._progress_text(groups[0]))
- if not result.success:
- if getattr(result, "retryable", False):
- logger.debug("[%s] Transient overflow edit failure — keeping can_edit=True", st.adapter.name)
- return True
- st.can_edit = False
- # Fall back to the existing non-edit behavior.
- return False
- groups = groups[1:]
- for group in groups:
- result = await self._send_progress_text(st, self._progress_text(group))
- if result.success and result.message_id:
- st.progress_msg_id = result.message_id
- # The newest continuation is the only mutable bubble: keep just its lines so later
- # edits update it instead of replaying the full transcript into new messages.
- st.progress_lines = groups[-1]
- return True
-
- @staticmethod
- def _is_reset_marker(raw) -> bool:
- return isinstance(raw, tuple) and len(raw) >= 1 and raw[0] == "__reset__"
-
- def _reset_progress_bubble(self, st) -> None:
- """Content bubble landed — close the tool-progress bubble so the next tool starts fresh
- below it; else tool edits hit the ORIGINAL message above (out of order)."""
- st.progress_msg_id, st.progress_lines = None, []
- self._ctx.last_progress_msg[0], self._ctx.repeat_count[0] = None, 0
-
- def _progress_absorb(self, st, raw) -> Any:
- """Fold a queue item into the bubble buffer; returns the line to render this tick."""
- if isinstance(raw, tuple) and len(raw) == 3 and raw[0] == "__dedup__":
- _, base_msg, count = raw
- if not st.progress_lines:
- return base_msg
- st.progress_lines[-1] = f"{base_msg} (×{count + 1})"
- return st.progress_lines[-1]
- st.progress_lines.append(raw)
- return raw
-
- async def _flush_progress_edit(self, st) -> None:
- if st.can_edit and st.progress_lines and st.progress_msg_id:
- with suppress(Exception):
- await self._edit_progress_message(st, st.progress_msg_id, self._progress_text(st.progress_lines))
-
- async def _drain_progress_on_cancel(self, st) -> None:
- ctx = self._ctx
- with suppress(Exception):
- while not ctx.progress_queue.empty():
- raw = ctx.progress_queue.get_nowait()
- if self._is_reset_marker(raw):
- # Content-bubble marker during drain: close the current progress bubble
- # and start a fresh one for tool lines that arrived after.
- await self._roll_progress_overflow_if_needed(st)
- await self._flush_progress_edit(st)
- self._reset_progress_bubble(st)
- else:
- self._progress_absorb(st, raw)
- await self._roll_progress_overflow_if_needed(st)
- # Final edit with all remaining tools (only if editing works)
- if st.can_edit and st.progress_lines and st.progress_msg_id:
- await self._roll_progress_overflow_if_needed(st)
- await self._flush_progress_edit(st)
-
- async def _progress_restore_typing(self, st) -> None:
- ctx = self._ctx
- await asyncio.sleep(0.3)
- if ctx._run_still_current():
- await st.adapter.send_typing(ctx.source.chat_id, metadata=ctx._progress_metadata)
-
- async def _progress_send_or_edit(self, st, msg) -> bool:
- """Deliver this tick's bubble. Returns False on a transient edit failure (retry next tick).
-
- Transient network errors (ConnectError, timeouts) must not disable editing; only permanent
- failures (not found, permissions) set can_edit=False. Flood control backs off but keeps editing.
- """
- if st.can_edit and st.progress_msg_id is not None:
- result = await self._edit_progress_message(st, st.progress_msg_id, "\n".join(st.progress_lines))
- if result.success:
- return True
- if getattr(result, "retryable", False):
- logger.debug("[%s] Transient edit failure — keeping can_edit=True", st.adapter.name)
- return False
- if any(w in (getattr(result, "error", "") or "").lower() for w in ("flood", "retry after")):
- logger.info("[%s] Progress edit flood control, backing off", st.adapter.name)
- else:
- st.can_edit = False
- await self._send_progress_text(st, msg)
- return True
- # First tool: send all accumulated text as a new message; editing unsupported: just this line.
- result = await self._send_progress_text(st, "\n".join(st.progress_lines) if st.can_edit else msg)
- if result.success and result.message_id:
- st.progress_msg_id = result.message_id
- return True
-
- async def send_progress_messages(self):
- ctx = self._ctx
- adapter = self._runner._delivery_adapter_for(ctx.source) if ctx.progress_queue else None
- if not adapter:
- return
- if ctx._native_slack_task_cards and hasattr(adapter, "send_native_task_card_progress"):
- await self._send_native_task_card_progress(adapter)
- return
- # Skip tool progress for platforms that can't edit messages (e.g. iMessage/BlueBubbles):
- # each update would be a separate bubble. getattr, not attribute access: duck-typed
- # adapters (test fakes, minimal plugins) may lack edit_message — treated as "can't edit".
- adapter_edit = getattr(type(adapter), "edit_message", None)
- if adapter_edit is None or adapter_edit is BasePlatformAdapter.edit_message:
- self._drain_progress_queue()
- return
- st = self._progress_edit_state(adapter)
- last_edit_ts = 0.0
- EDIT_INTERVAL = 1.5 # Minimum seconds between edits (Telegram flood control)
- while True:
- try:
- if not ctx._run_still_current():
- self._drain_progress_queue()
- return
- raw = ctx.progress_queue.get_nowait()
- # Drain silently when interrupted: events queued in the window between tool parse
- # and interrupt processing should not render as bubbles.
- if self._agent_interrupted():
- await asyncio.sleep(0)
- continue
- if self._is_reset_marker(raw):
- self._reset_progress_bubble(st)
- continue
- msg = self._progress_absorb(st, raw)
- if not await self._roll_progress_overflow_if_needed(st):
- # Throttle edits: batch rapid tool updates into fewer API calls (grammY pattern:
- # proactively rate-limit rather than react to 429s). Loop back to drain further
- # queued messages before sending a single batched edit.
- remaining = EDIT_INTERVAL - (time.monotonic() - last_edit_ts)
- if remaining > 0:
- await asyncio.sleep(remaining)
- continue
- if not ctx._run_still_current():
- return
- if not await self._progress_send_or_edit(st, msg):
- continue
- last_edit_ts = time.monotonic()
- await self._progress_restore_typing(st)
- except queue.Empty:
- await asyncio.sleep(0.3)
- except asyncio.CancelledError:
- await self._drain_progress_on_cancel(st)
- return
- except Exception as e:
- logger.error("Progress message error: %s", e)
- await asyncio.sleep(1)
-
- # ── ID-bearing lifecycle callbacks (agent thread) ───────────────────────────────────────
-
- def voice_ack_callback(self, call_id, tool_name, args):
- """tool_start_callback: speak a one-time ack in the voice channel."""
- ctx = self._ctx
- if ctx._voice_ack_fired[0] or ctx._voice_ack_guild[0] is None or not ctx._run_still_current():
- return
- ctx._voice_ack_fired[0] = True
- adapter = self._runner.adapters.get(Platform.DISCORD)
- if adapter is None or not hasattr(adapter, "play_ack_in_voice"):
- return
- try:
- self._schedule(
- adapter.play_ack_in_voice(ctx._voice_ack_guild[0]), "voice ack scheduling error", loop=ctx._voice_ack_loop,
- )
- except Exception as err:
- logger.debug("voice ack schedule failed: %s", err)
-
- # Slack-native task cards ride agent.tool_start_callback / tool_complete_callback so start and
- # completion correlate by the REAL tool-call id; name-correlated progress_callback text events
- # would duplicate cards and mispair concurrent calls.
-
- def _native_card_gate(self) -> bool:
- ctx = self._ctx
- return bool(ctx.progress_queue) and ctx._run_still_current() and not self._agent_interrupted()
-
- # ── Slack-native task cards: ID-bearing lifecycle callbacks (#29483) ── These ride
- # agent.tool_start_callback / agent.tool_complete_callback so start/completion events correlate by the
- # REAL tool-call id — the name-correlated text events in progress_callback would duplicate cards and
- # mispair concurrent calls to the same tool.
- def native_tool_start_callback(self, call_id, tool_name, args):
- """Queue an ID-correlated native progress start from the agent thread."""
- if not self._native_card_gate():
- return
- from agent.display import build_tool_preview
- name = str(tool_name or "tool")
- self._ctx.progress_queue.put({
- "type": "tool.started", "tool_call_id": str(call_id or ""), "tool_name": name,
- "preview": build_tool_preview(name, args or {}, max_len=64) or "",
- })
-
- def native_tool_complete_callback(self, call_id, tool_name, args, result):
- """Queue the matching native completion using the real tool-call ID."""
- if not self._native_card_gate():
- return
- from agent.display import _detect_tool_failure
- name = str(tool_name or "tool")
- is_error, _ = _detect_tool_failure(name, result)
- self._ctx.progress_queue.put({
- "type": "tool.completed", "tool_call_id": str(call_id or ""), "tool_name": name, "is_error": bool(is_error),
- })
-
- def combined_tool_start_callback(self, call_id, tool_name, args):
- """Compose the voice ack + native task-card start consumers."""
- if self._ctx._voice_ack_guild[0] is not None:
- self.voice_ack_callback(call_id, tool_name, args)
- if self._ctx._native_slack_task_cards:
- self.native_tool_start_callback(call_id, tool_name, args)
-
- # ── hook / status bridges (agent thread → gateway loop) ────────────────────────────────
-
- def _step_callback_sync(self, iteration: int, prev_tools: list) -> None:
- ctx = self._ctx
- if not ctx._run_still_current():
- return
- # prev_tools may be list[str] or list[dict] with "name"/"result" keys. Normalise so
- # "tool_names" stays backward-compatible for user hooks that do ', '.join(tool_names).
- names = [(t.get("name") or "") if isinstance(t, dict) else str(t) for t in (prev_tools or [])]
- self._schedule(
- ctx._hooks_ref.emit("agent:step", {
- "platform": ctx.source.platform.value if ctx.source.platform else "",
- "user_id": ctx.source.user_id, "session_id": ctx.session_id,
- "iteration": iteration, "tool_names": names, "tools": prev_tools,
- }),
- "agent:step hook scheduling error",
- )
-
- def _event_callback_sync(self, event_type: str, context: dict) -> None:
- ctx = self._ctx
- try:
- asyncio.run_coroutine_threadsafe(ctx._hooks_ref.emit(event_type, context), ctx._loop_for_step)
- except Exception as e:
- logger.debug("event_callback hook error: %s", e)
-
- def _status_live(self) -> bool:
- """Status adapter present and this run is still the current generation."""
- return bool(self._ctx._status_adapter) and self._ctx._run_still_current()
-
- def _send_status_text(self, text: str, metadata, log_message: str) -> None:
- ctx = self._ctx
- self._schedule(ctx._status_adapter.send(ctx._status_chat_id, text, metadata=metadata), log_message)
-
- def _attach_session_title_callback(self, agent, ctx) -> None:
- """Wire the platform thread-rename lane onto the agent as `_on_session_title`.
-
- The titler runs in the turn prologue, so attach before the run, not after it.
- """
- try:
- # Gateway auto-title failures are not user-actionable, so never surface them as messages;
- # overriding the failure sink keeps CLI on _emit_auxiliary_failure while gateway logs debug.
- agent._title_failure_callback = lambda task, exc: logger.debug(
- "Gateway auto-title failure suppressed (not user-visible): %s: %s", task, exc,
- )
- session_id = getattr(agent, "session_id", None)
- runner = self._runner
- source = runner._recover_discord_auto_thread_source(ctx.source, ctx.session_key)
- # Both lanes spend a rate-limited platform call per title, so they use the model's title
- # only (TitleCallback); renaming twice burns Discord's 2-per-10-min budget on a throwaway.
- # Relay Discord predicate is shape-only: whether the connector auto-threaded our reply is
- # only knowable AFTER delivery, so register eagerly and let the rename lane look up the
- # cache at fire time — gating registration on the cache read meant it never registered.
- if runner._is_telegram_topic_lane(source):
- lane = "_schedule_telegram_topic_title_rename"
- elif runner._is_discord_auto_thread_lane(source) or runner._is_relay_discord_channel_lane(source):
- lane = "_schedule_discord_semantic_thread_rename"
- else:
- return
- agent._on_session_title = lambda title, title_source: (
- title_source == "llm" and getattr(runner, lane)(source, session_id, title)
- )
- except Exception:
- logger.debug("Failed to attach session title callback", exc_info=True)
-
- def _status_callback_sync(self, event_type: str, message: str) -> None:
- from gateway.run import _prepare_gateway_status_message, _redact_gateway_user_facing_secrets, _send_or_update_status_coro
- from gateway.warning_notifications import is_warning_status, render_notification
- ctx = self._ctx
- if ctx.mute_notification_reply or not self._status_live():
- return
- prepared = _prepare_gateway_status_message(ctx.source.platform, event_type, message)
- if prepared is None:
- logger.debug(
- "status_callback suppressed for %s/%s: %s",
- ctx.source.platform.value if ctx.source.platform else "unknown", event_type,
- _redact_gateway_user_facing_secrets(str(message or ""))[:160],
- )
- return
- def present():
- fut = self._schedule(
- _send_or_update_status_coro(ctx._status_adapter, ctx._status_chat_id, event_type, prepared, ctx._status_thread_metadata),
- f"status_callback ({event_type}) scheduling error",
- )
- if fut is not None and ctx._cleanup_progress:
- fut.add_done_callback(self._track_future_cleanup_id)
- render_notification(present, platform=ctx.source.platform, user_config=ctx.user_config,
- diagnostic=is_warning_status(event_type, message))
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
+ if authority is not None:
+ source = getattr(ctx, 'source', None)
+ owner_id = (source.chat_id if getattr(source, 'platform', None) == Platform.LOCAL
+ else authority.logical_owner(ctx.session_id))
+ if owner_id in authority.sessions:
+ generation = authority.db.get_session(owner_id)["runtime_generation"]
+ self._approval_owner = (authority, owner_id, generation)
+
+
+ def _publish_execution(self, event_type, payload):
+ if self._approval_owner is not None:
+ authority, session_id, generation = self._approval_owner
+ return authority.publish_execution(session_id, generation, event_type, payload)
+ return False
+
+ def _publish_api_tool(self, event_type, call_id, tool_name, args, result=None):
+ """The retained tool payload reaches the API observers of this exact admission only;
+ the shared viewer stream keeps its ID-correlated frames."""
+ if self._approval_owner is not None:
+ from gateway.session_api_turn import publish_api_tool_event
+ authority, session_id, generation = self._approval_owner
+ publish_api_tool_event(authority, session_id, generation, event_type,
+ str(call_id or ""), str(tool_name or "tool"), args, result)
# ── stream consumer / interim commentary wiring ─────────────────────────────────────────
diff --cc hermes_cli/web_server.py
index f4303048ee5,b314f74391b..47ad1e1491a
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@@ -176,10 -176,172 +176,10 @@@ def _start_desktop_cron_ticker(stop_eve
_DESKTOP_MCP_DISCOVERY_DELAY_S = 1.0
-@asynccontextmanager
-async def _lifespan(app: FastAPI):
- app.state.event_channels = {} # dict[str, set]
- app.state.event_lock = asyncio.Lock()
- app.state.pty_active_session_files = {} # dict[str, Path]
- # Serializes chat-argv resolution so concurrent /api/pty connections don't
- # overlap ``npm install`` / ``npm run build``. Locks live on app.state (not
- # module globals) so they bind to the running loop, not the import-time one.
- app.state.chat_argv_lock = asyncio.Lock()
-
- # Bring state.db schema current BEFORE the first session-list poll
- # (#79531/#80037): a store left behind by `hermes update` otherwise 500s
- # every poll while the read-probe heal loses to sibling lock contention.
- # Off-thread so a locked store never delays the socket (Desktop
- # ready-probe times out at 10s, GH-73083). NOT a daemon, and joined at
- # shutdown: its sqlite connection must be closed by the thread that is
- # stepping it. A daemon copy that outlived the lifespan had its
- # connection closed from the main thread mid-probe (pytest's leaked-DB
- # sweep) and segfaulted the interpreter. The worker is time-bounded by
- # SessionDB's lock patience, so the join cannot hang shutdown.
- eager_reconcile_thread = threading.Thread(
- target=_eager_reconcile_own_session_db,
- name="statedb-eager-reconcile",
- )
- eager_reconcile_thread.start()
-
- # Import hermes_cli.gateway *before* the yield: on Windows + 3.11 the
- # import holds the GIL, so run_in_executor still froze the loop 15-22s and
- # the Desktop's 10s ready-probe timed out (GH-73083).
- _warm_gateway_module()
-
- # Snapshot the checkout revision so lazy-import paths (model picker) can
- # refuse with "restart required" after `hermes update` replaced the code
- # (#86207); the update flow does not reliably restart the dashboard.
- from gateway.code_skew import record_boot_fingerprint
-
- record_boot_fingerprint()
-
- # Hosted Bot rooms belong to the backend process. Recovery may need a
- # contended state.db migration, so keep it off the pre-yield path: Group
- # Chat must degrade on its own rather than block every Desktop feature.
- from tui_gateway import methods_groups as _hosted_groups
- import tui_gateway.server
-
- try:
- tui_gateway.server.install_tui_message_injector()
- except Exception:
- _log.warning("TUI message injector did not install", exc_info=True)
-
- hosted_room_start_cancel = threading.Event()
-
- def _start_hosted_rooms() -> None:
- try:
- _hosted_groups.start_hosted_room_service()
- except Exception:
- _log.exception("Hosted Group Chat recovery failed during backend startup")
- finally:
- if hosted_room_start_cancel.is_set():
- _hosted_groups.stop_hosted_room_service(timeout=1.0)
-
- hosted_room_start_thread = threading.Thread(
- target=_start_hosted_rooms,
- daemon=True,
- name="hosted-room-startup",
- )
- hosted_room_start_thread.start()
-
- # Desktop-spawned backends fire cron jobs themselves, since the app has no
- # gateway running the scheduler. Server `hermes dashboard` is unaffected —
- # it relies on its own gateway.
- cron_stop: threading.Event | None = None
- cron_thread: threading.Thread | None = None
- desktop_owned = is_desktop_owned_backend()
- if desktop_owned:
- # Reap an orphaned gateway from an abnormal previous exit (reparented to
- # launchd, still holding the platform WebSocket) before forking a fresh
- # one that would race the same credential (#77276). Runs
- # unconditionally; protection of a healthy standalone gateway lives
- # INSIDE the reaper (registration probed with cleanup_stale=False).
- # Startup grace: spare a gateway still claiming gateway.pid/lock (#122533).
- try:
- from hermes_cli.dashboard_procs import _REAP_MIN_AGE_SECONDS
- from hermes_cli.gateway import _reap_unsupervised_gateway_orphans
-
- _reap_unsupervised_gateway_orphans(min_age_s=_REAP_MIN_AGE_SECONDS)
- except Exception:
- _log.exception("Desktop startup: orphan gateway reap failed")
-
- cron_stop = threading.Event()
- cron_thread = threading.Thread(
- target=_start_desktop_cron_ticker,
- args=(cron_stop,),
- daemon=True,
- name="desktop-cron-ticker",
- )
- cron_thread.start()
-
- # Reap idle/dead keep-alive PTY sessions (30-min TTL).
- pty_reaper_task = asyncio.create_task(run_reaper(PTY_REGISTRY))
- # Periodic authenticated self-test feeding the ``dashboard`` component on /api/status.
- selftest_task = asyncio.create_task(_dashboard_selftest_loop())
- # Live auto-archive timer, independent of list requests.
- auto_archive_task = asyncio.create_task(_auto_archive_ticker_loop())
-
- # Managed local runtime (local_runtime.enabled): bring llama-server back so a
- # restart doesn't strand a llamacpp main model. Off-thread and best-effort;
- # failure falls back to cloud providers like a cold start. Server only —
- # models load on first inference (an empty router holds no VRAM).
- def _boot_local_runtime():
- try:
- from hermes_cli.config import load_config
- from hermes_cli.local_runtime.bootstrap import ensure_local_runtime
-
- ensure_local_runtime(load_config())
- except Exception as exc:
- logging.getLogger(__name__).warning("local runtime boot failed: %s", exc)
-
- threading.Thread(target=_boot_local_runtime, daemon=True, name="local-runtime-boot").start()
-
- # Nous free tier: the ONE place its identity is created. Inventories credentials, mints only
- # when HERMES_GUEST_ONBOARDING=1, records the answer for setup.status / free_tier.status and
- # broadcasts `setup.ready`. Off-thread so a slow portal never delays the socket; the desktop's
- # first setup.status waits on the record (bounded) instead.
- from hermes_cli.free_tier_bootstrap import start_background_bootstrap
-
- start_background_bootstrap()
-
- try:
- yield
- finally:
- try:
- tui_gateway.server.clear_tui_message_injector()
- except Exception:
- _log.debug("TUI message injector clear skipped", exc_info=True)
- hosted_room_start_cancel.set()
- _hosted_groups.stop_hosted_room_service(timeout=5.0)
- hosted_room_start_thread.join(timeout=1.0)
- if cron_stop is not None:
- cron_stop.set()
- pty_reaper_task.cancel()
- selftest_task.cancel()
- auto_archive_task.cancel()
- await PTY_REGISTRY.close_all()
-
- # PtySession.close() removes markers owned by live registry sessions.
- # This second pass cleans any channel markers left in app state,
- # including stale paths from sessions reaped earlier.
- for marker in set(_get_pty_active_session_files(app).values()):
- try:
- marker.unlink(missing_ok=True)
- except OSError:
- pass
-
- # Stop the managed llama-server with its parent (an orphan pins VRAM).
- try:
- from hermes_cli.local_runtime.bootstrap import shutdown_local_runtime
-
- shutdown_local_runtime()
- except Exception:
- pass
- if desktop_owned:
- _terminate_desktop_managed_gateway()
- eager_reconcile_thread.join()
+from hermes_cli.web_server_app import app_lifespan
- def _app_state_default(app: "FastAPI", name: str, factory):
+ def _app_state_default(app: FastAPI, name: str, factory):
"""Return ``app.state.<name>``, lazily creating it for non-``with`` TestClient usages.
The lifespan normally initialises these on the running event loop (an
diff --cc hermes_cli/web_server_chat.py
index b6a891d9bc3,3ec2fe41834..640662e4692
--- a/hermes_cli/web_server_chat.py
+++ b/hermes_cli/web_server_chat.py
@@@ -131,31 -131,70 +131,31 @@@ async def _legacy_pump(ws: WebSocket, b
await asyncio.to_thread(bridge.close)
-# Starlette's TestClient reports the peer as "testclient"; treat it as
-# loopback so tests don't need to rewrite request scope.
-_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost", "testclient"})
+from hermes_cli.web_server_boundary import _LOOPBACK_HOSTS
- def _ws_client_reason(ws: "WebSocket") -> Optional[str]:
+ def _ws_client_reason(ws: WebSocket) -> Optional[str]:
- """Return a rejection reason token for the peer IP, or None when allowed.
-
- Loopback bind: only loopback peers (the legacy ``?token=`` is the only auth,
- LAN hosts must not get to guess it); an empty peer fails closed. Explicit
- non-loopback bind (``--insecure``) or gated mode: any peer — DNS-rebinding is
- blocked by :func:`_ws_host_origin_reason`, and in gated mode
- ``ws.client.host`` is the X-Forwarded-For value anyway.
- """
+ """Return a rejection reason token for the peer IP, or None when allowed
+ (:func:`hermes_cli.web_server_boundary.ws_client_reason` on the dashboard app state)."""
from hermes_cli.web_server import app
- if getattr(app.state, "auth_required", False):
- return None
- bound_host = (getattr(app.state, "bound_host", "") or "").strip().lower()
- if bound_host and bound_host not in _LOOPBACK_HOSTS:
- return None
- client_host = ws.client.host if ws.client else ""
- if not client_host:
- return f"missing_or_empty_peer bound={bound_host or '?'}"
- if client_host in _LOOPBACK_HOSTS:
- return None
- return f"peer_not_loopback peer={client_host} bound={bound_host or '?'}"
+ from hermes_cli.web_server_boundary import ws_client_reason
+ return ws_client_reason(ws, app.state)
- def _ws_client_is_allowed(ws: "WebSocket") -> bool:
+ def _ws_client_is_allowed(ws: WebSocket) -> bool:
"""True when the peer IP passes :func:`_ws_client_reason`."""
return _ws_client_reason(ws) is None
- def _ws_host_origin_reason(ws: "WebSocket") -> Optional[str]:
+ def _ws_host_origin_reason(ws: WebSocket) -> Optional[str]:
- """Return ``host_mismatch …`` / ``origin_mismatch …``, or None when allowed.
-
- HTTP middleware does not run for WebSocket routes, so the DNS-rebinding
- Host check is repeated here; an Origin header, when present, must target the
- bound host. Non-web origins (packaged Electron: file://, null, app://) are
- trusted — the credential check is the real auth boundary there.
- """
- from hermes_cli.web_server import _is_accepted_host, app
- bound_host = getattr(app.state, "bound_host", None)
- if not bound_host:
- return None
- trusted_public_hosts = getattr(app.state, "trusted_public_hosts", frozenset())
- host_header = ws.headers.get("host", "")
- if not _is_accepted_host(host_header, bound_host, trusted_public_hosts):
- return f"host_mismatch host={host_header or '?'} bound={bound_host}"
- origin = ws.headers.get("origin", "")
- if not origin:
- return None
- try:
- parsed = urllib.parse.urlparse(origin)
- except ValueError: # malformed authority, e.g. "http://[::1" — fail closed
- parsed = None
- if parsed is not None and parsed.scheme not in {"http", "https"}:
- return None
- if parsed is None or not parsed.netloc or not _is_accepted_host(parsed.netloc, bound_host, trusted_public_hosts):
- return f"origin_mismatch origin={origin} bound={bound_host}"
- return None
+ """Return ``host_mismatch …`` / ``origin_mismatch …``, or None when allowed
+ (:func:`hermes_cli.web_server_boundary.ws_host_origin_reason` on the dashboard app state)."""
+ from hermes_cli.web_server import app
+ from hermes_cli.web_server_boundary import ws_host_origin_reason
+ return ws_host_origin_reason(ws, app.state)
- def _ws_host_origin_is_allowed(ws: "WebSocket") -> bool:
+ def _ws_host_origin_is_allowed(ws: WebSocket) -> bool:
"""True when the upgrade passes the dashboard Host/Origin guard."""
return _ws_host_origin_reason(ws) is None
@@@ -165,14 -204,25 +165,14 @@@ def _ws_request_is_allowed(ws: WebSocke
return _ws_host_origin_is_allowed(ws) and _ws_client_is_allowed(ws)
-_GATEWAY_WS_PROTOCOL = "hermes-gateway-v1"
-_GATEWAY_WS_TICKET_PROTOCOL_PREFIX = "hermes-gateway-ticket."
-
-
-def _gateway_ws_ticket_from_subprotocol(ws: WebSocket) -> tuple[str, str]:
- """Return ``(ticket, reason)`` from an unambiguous gateway protocol set."""
- raw = str(ws.headers.get("sec-websocket-protocol", "") or "")
- protocols = [value.strip() for value in raw.split(",") if value.strip()]
- ticket_protocols = [
- value for value in protocols if value.startswith(_GATEWAY_WS_TICKET_PROTOCOL_PREFIX)]
- if not ticket_protocols:
- return "", "none"
- if _GATEWAY_WS_PROTOCOL not in protocols or len(ticket_protocols) != 1:
- return "", "invalid"
- ticket = ticket_protocols[0][len(_GATEWAY_WS_TICKET_PROTOCOL_PREFIX):]
- return (ticket, "ok") if ticket else ("", "invalid")
+from hermes_cli.web_server_boundary import (
+ _GATEWAY_WS_PROTOCOL,
+ _GATEWAY_WS_TICKET_PROTOCOL_PREFIX,
+ _gateway_ws_ticket_from_subprotocol,
+)
- def _ws_request_view(ws: "WebSocket") -> "Request":
+ def _ws_request_view(ws: WebSocket) -> Request:
"""A ``Request`` facade over a ``WebSocket`` for the auth helpers.
``_verify_access_token`` only touches ``request.headers`` (X-Forwarded-For
diff --cc tests/cron/test_quota_hold.py
index 941cd529588,4307fbc0203..b8cf0eac09c
--- a/tests/cron/test_quota_hold.py
+++ b/tests/cron/test_quota_hold.py
@@@ -137,12 -136,9 +137,12 @@@ def test_quota_hold_parks_past_window_s
through (it is not a missing credential), the one delivered alert carries the hold notice,
and the job does not fire again inside the window (not even after the stale-error re-arm's
cadence+grace). The marker clears once a run reaches the model."""
- job = create_job("portfolio triage", "every 30m", deliver="local")
+ # A real (non-local) lane: the alert rides the durable delivery queue, whose enqueue is the seam.
+ (tmp_cron_home / "config.yaml").write_text(
+ "platforms:\n slack:\n enabled: true\n token: xoxb-test\n", encoding="utf-8")
+ job = create_job("portfolio triage", "every 30m", deliver="slack:alerts")
job_id = job["id"]
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
deliveries: list = []
_tick(get_job(job_id), tmp_cron_home, deliveries, _raise_quota)
diff --cc tests/e2e/core/history/_helpers.py
index 7238adff182,155a0c1f49a..c7556cdbd81
--- a/tests/e2e/core/history/_helpers.py
+++ b/tests/e2e/core/history/_helpers.py
@@@ -395,13 -395,7 +395,13 @@@ class TuiGateway
self._wlock = threading.Lock()
self.stored: dict[str, str] = {}
- def __enter__(self) -> "TuiGateway":
+ def __enter__(self) -> TuiGateway:
+ # A ``hermes chat -q`` hop leaves the always-on gateway owning this home, and the standalone
+ # stdio entry refuses a home a gateway owns (it would be a second state.db writer). Stop
+ # the owner first so each "gw" hop is still a fresh process on the same durable store.
+ subprocess.run([sys.executable, "-m", "hermes_cli.main", "gateway", "stop"], cwd=self.cwd,
+ env={**self.env, "PWD": self.cwd}, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, encoding="utf-8", timeout=120)
self.proc = self.spawned.add(subprocess.Popen(
[sys.executable, "-m", "tui_gateway.entry"], cwd=self.cwd, env={**self.env, "PWD": self.cwd},
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
diff --cc tools/bot_mode_dm.py
index e48c6b5e3a6,23dc00eb24e..df002ba91b0
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@@ -422,7 -420,61 +422,7 @@@ def _delivery_lock(argv: list[str], *,
return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2])
- def _live_intent_file(dm_file: "str | os.PathLike") -> str:
-def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, str]] = None) -> int:
- """One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits
- the transport's streams and returns its exit code. Transient failures re-run the
- same session; a context_overflow re-run lets the retried turn's pre-API compaction
- compact the transcript first (no fresh session is ever minted). Auth/quota/config never retry."""
-
- def _turn(turn_env=env):
- return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,
- capture_output=True, text=True, encoding="utf-8", errors="replace", env=turn_env)
-
- proc = _turn()
- if proc.returncode != 0:
- from tools.bot_failure_reasons import RETRY_NONE, classify_agent_error, retry_action, turn_failure_text
- from tools.bot_relay import retry_turn_env
-
- # The re-run replays the same session and payload; the failed attempt already persisted the
- # user row, so the retried process is told to resume it (RESUME_UNANSWERED_TURN_ENV).
- if retry_action(classify_agent_error(turn_failure_text(proc.stdout, proc.stderr))) != RETRY_NONE:
- proc = _turn(retry_turn_env(env))
- stderr_text = proc.stderr or ""
- reason = next((line.removeprefix("hermes-refusal-reason: ").strip()
- for line in stderr_text.splitlines()
- if line.startswith("hermes-refusal-reason: ")), None)
- # A code wins over prose, including unknown codes from newer CLIs.
- # Only older CLIs without a marker need the historical wording fallback.
- refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None
- else "already has a live owner" in stderr_text)
- if proc.returncode != 0 and refused_not_owned:
- # The target's Bot Chat is held live by another surface (Desktop); the turn
- # never ran — tell the sender plainly instead of leaking a raw lease error.
- # See #100523.
- who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate"
- print(json.dumps({
- "error": f"Delivery failed: @{who}'s Bot Chat is open on another "
- "surface right now, so your message was NOT delivered. Try again later.",
- "reason": "target_busy",
- }))
- return 1
- # Re-emit the transport's streams: stdout is the reply text the
- # completion notification carries back to the sending agent. A successful bare
- # silence marker is a delivery decision (same rule as the gateway and the live
- # Bot Chat completion): the turn stays in the target's transcript, the sender
- # never sees the marker as prose.
- from gateway.response_filters import is_intentional_silence_response
- reply = proc.stdout or ""
- if proc.returncode == 0 and is_intentional_silence_response(reply):
- reply = ""
- for stream, text in ((sys.stdout, reply), (sys.stderr, proc.stderr)):
- if text:
- stream.write(text)
- stream.flush()
- return proc.returncode
-
-
+ def _live_intent_file(dm_file: str | os.PathLike) -> str:
"""The pinned live-delivery intent beside a DM file (the cache sweep globs ``*.live.json``)."""
return f"{os.fspath(dm_file)}.live.json"
diff --cc tools/terminal_scope.py
index 79758df1bd2,6b5b707ad45..270a47a06b8
--- a/tools/terminal_scope.py
+++ b/tools/terminal_scope.py
@@@ -86,33 -86,8 +86,33 @@@ def terminal_env(name: str, default: st
return default if value is None else str(value)
+def _apply_terminal_mapping(scope: dict[str, str], mapping: dict[str, Any]) -> None:
+ from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP, _terminal_env_value
+
+ for cfg_key, value in mapping.items():
+ # cwd placeholders are resolved per-surface later; not a policy value.
+ if value is None or (cfg_key == "cwd" and str(value).strip() in {".", "auto", "cwd"}):
+ continue
+ env_var = TERMINAL_CONFIG_ENV_MAP.get(cfg_key)
+ if env_var:
+ # List/dict config values must be JSON (same contract as
+ # apply_terminal_config_to_env). str() yields Python repr, which
+ # json.loads in terminal_tool rejects.
+ scope[env_var] = _terminal_env_value(value)
+
+
+def default_terminal_scope() -> dict[str, str]:
+ """Code-default ``TERMINAL_*`` policy: what a profile-bypassing session freezes instead of
+ reading ``.env``/``config.yaml``. Total like the profile projection, minus the profile."""
+ from hermes_cli.config_defaults import DEFAULT_CONFIG
+
+ scope: dict[str, str] = {}
+ _apply_terminal_mapping(scope, {**_TOOL_LEVEL_DEFAULTS, **(DEFAULT_CONFIG.get("terminal") or {})})
+ return scope
+
+
def build_profile_terminal_scope(
- hermes_home: "Any", *, env_overlay: Optional[dict[str, str]] = None) -> dict[str, str]:
+ hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> dict[str, str]:
"""Build the COMPLETE effective ``TERMINAL_*`` policy for a profile home.
Projection: ``DEFAULT_CONFIG['terminal']`` <- profile ``.env`` TERMINAL_* <- *env_overlay*