The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main (#27: 19 commits to 517b5e10feb) into feat/unified-gateway-runtime
Teknium65bec86e37ae
diff --cc acp_adapter/session.pyindex 82484990c0f,14fb5327466..fe8680ea206--- a/acp_adapter/session.py+++ b/acp_adapter/session.py@@@ -207,10 -207,16 +207,10 @@@ class SessionManagerlogger.info("Forked ACP session %s -> %s", session_id, new_id)return state- def list_sessions(self, cwd: str | None = None) -> List[Dict[str, Any]]:+ def list_sessions(self, cwd: str | None = None) -> list[dict[str, Any]]:"""Return lightweight info dicts for all sessions (memory + database)."""normalized_cwd = _normalize_cwd_for_compare(cwd) if cwd else None- db = self._get_db()- persisted_rows: dict[str, dict[str, Any]] = {}- try:- for row in (db.list_sessions_rich(source="acp", limit=1000) if db is not None else ()):- persisted_rows[str(row["id"])] = dict(row)- except Exception:- logger.debug("Failed to load ACP sessions from DB", exc_info=True)+ persisted_rows = self._catalog_rows()def _matches(session_cwd: str) -> bool:return not normalized_cwd or _normalize_cwd_for_compare(session_cwd) == normalized_cwddiff --cc agent/auxiliary_client.pyindex c33c0b2c4c7,7b5d3c4e077..4fa0f2fc254--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@@ -4187,10 -4201,8 +4187,10 @@@ async def _call_fallback_candidate_asynreasoning_config=reasoning_config,)- async def _send(client: Any, request_kwargs: Dict[str, Any], dest: _FallbackDestination) -> Any:+ async def _send(client: Any, request_kwargs: dict[str, Any], dest: _FallbackDestination) -> Any:- return _validate_llm_response(+ import asyncio+ return await asyncio.to_thread(+ _validate_llm_response,await _relay_async_completion(client, request_kwargs, provider=dest.provider, api_mode=dest.api_mode),task,)diff --cc agent/background_review.pyindex 5b2479ed0d9,3ccc84a9530..00ca5246209--- a/agent/background_review.py+++ b/agent/background_review.py@@@ -225,17 -225,9 +225,17 @@@ def _review_input_token_budgetreturn budget if budget > 0 else None- def load_background_review_settings() -> tuple[bool, Dict[str, Any]]:+ def load_background_review_settings() -> tuple[bool, dict[str, Any]]:"""Single config read -> ``(enabled, task_cfg)``. Fail-open (``enabled=True``) so a brokenconfig never silently disables reviews — but WARN so the cost is visible."""+ from agent.safe_worker_policy import safe_worker_enabled+ from gateway.session_finite import finite_turn_required++ # A finite gateway turn (`chat -q` / `-z`) is one-shot like the in-process run, whose exit+ # takes the daemon review thread with it; the long-lived gateway would otherwise fork a+ # ~30K-token review after the viewer has already gone.+ if safe_worker_enabled() or finite_turn_required() is True:+ return False, {}try:from hermes_cli.config import load_config_readonlyfrom utils import is_truthy_valuediff --cc agent/context_compressor.pyindex e8f04361ef1,8863e0190cd..4aea0000806--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@@ -34,7 -34,6 +34,7 @@@ from agent.auxiliary_client importfrom agent.context_engine import ContextEngine, sanitize_memory_contextfrom agent.context_compressor_prellm import PreLlmSkipMixinfrom agent.context_compressor_summary import SummaryDispatchMixin- from agent.context_compressor_retry import retryable_user_text # noqa: F401 — public re-export++from agent.context_compressor_retry import retryable_user_textfrom agent.error_classifier import FailoverReason, classify_api_errorfrom agent.micro_compaction import MicroCompactionMixinfrom agent.prompt_builder import STEER_DISPLAY_KIND@@@ -5378,19 -5373,13 +5378,19 @@@ Write only the summary body. Do not incself._structural_no_op_backoff_until = 0.0return telemetry- def _structural_no_op_result(self, telemetry: Dict[str, Any], failure_class: str, reason: str,- def _structural_no_op_result(self, telemetry: dict[str, Any], failure_class: str, reason: str) -> None:++ def _structural_no_op_result(self, telemetry: dict[str, Any], failure_class: str, reason: str,+ n_messages: int = 0) -> None:"""Nothing eligible to compress: transient backoff (#93022), never an ineffectiveness strike."""telemetry["failure_class"] = failure_classself._last_compression_savings_pct = 0.0- self._record_structural_no_op(reason)+ self._record_structural_no_op(reason, n_messages)++ def lift_structural_backoff_if_grown(self, n_messages: int) -> None:+ """A structural no-op said "nothing eligible among N messages"; more messages is new evidence."""+ if self._structural_no_op_backoff_until and n_messages > getattr(self, "_structural_no_op_len", 0):+ self._structural_no_op_backoff_until = 0.0- def _drop_blank_echoes(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ def _drop_blank_echoes(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:"""Remove blank platform echoes trailing the latest actionable user turn."""blank = self._blank_echo_indices_after(messages, self._find_last_user_message_idx(messages, 0))return [m for idx, m in enumerate(messages) if idx not in blank] if blank else messagesdiff --cc agent/outbound_webhooks.pyindex b2e1417f0c5,f3b152ad5dd..e9a6f48f0fb--- a/agent/outbound_webhooks.py+++ b/agent/outbound_webhooks.py@@@ -68,13 -68,9 +68,13 @@@ class WebhookTarget(_ToolMatcherMixin)return self.name or self.url- def register_from_config(cfg: Optional[Dict[str, Any]]) -> List[WebhookTarget]:+ def register_from_config(cfg: Optional[dict[str, Any]]) -> list[WebhookTarget]:"""Register every configured outbound webhook on the plugin manager. Malformed ``hooks.outbound``means zero targets — never raises. Returns the targets that ended up wired (deduplicated)."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return []if not isinstance(cfg, dict):return []from utils import env_var_enableddiff --cc agent/shell_hooks.pyindex 36c70857c12,021d3795c31..e30f247cfa1--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@@ -138,13 -138,9 +138,13 @@@ class ShellHookSpec(_ToolMatcherMixin)# --- Public API ---- def register_from_config(cfg: Optional[Dict[str, Any]], *, accept_hooks: bool = False) -> List[ShellHookSpec]:+ def register_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool = False) -> list[ShellHookSpec]:"""Register every configured shell hook (idempotent); returns the newly wired specs. Skippedentries (unknown, malformed, not allowlisted, already registered) are logged only."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return []if not isinstance(cfg, dict):return []from utils import env_var_enabled@@@ -369,14 -365,10 +369,14 @@@ def _spawn(spec: ShellHookSpec, stdin_jreturn result- def _make_callback(spec: ShellHookSpec) -> Callable[..., Optional[Dict[str, Any]]]:+ def _make_callback(spec: ShellHookSpec) -> Callable[..., Optional[dict[str, Any]]]:"""Build the closure that ``invoke_hook()`` will call per firing."""- def _callback(**kwargs: Any) -> Optional[Dict[str, Any]]:+ def _callback(**kwargs: Any) -> Optional[dict[str, Any]]:+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return Noneif spec.event in _TOOL_EVENTS and not spec.matches_tool(kwargs.get("tool_name")):return Nonereturn _evaluate_result(spec, _spawn(spec, _serialize_payload(spec.event, kwargs)))diff --cc agent/skill_utils.pyindex 118d9dc3140,eebbeb15a16..c4ed7ad92b6--- a/agent/skill_utils.py+++ b/agent/skill_utils.py@@@ -208,13 -208,8 +208,13 @@@ def _config_cache_key(config_path: Pathreturn None- def _load_raw_config() -> Dict[str, Any]:+ def _load_raw_config() -> dict[str, Any]:"""Read config.yaml with an mtime+size keyed cache (no hermes_cli.config import)."""+ from agent.safe_worker_policy import worker_config_snapshot++ snapshot = worker_config_snapshot()+ if snapshot is not None:+ return snapshotconfig_path = get_config_path()if not config_path.exists():return {}diff --cc agent/subdirectory_hints.pyindex 20791e1fc7c,86106d9f9f9..e45966ec298--- a/agent/subdirectory_hints.py+++ b/agent/subdirectory_hints.py@@@ -184,11 -180,9 +184,11 @@@ class SubdirectoryHintTrackerif found and found[1]:self._loaded_digests.add(_digest(found[1]))- def check_tool_call(self, tool_name: str, tool_args: Dict[str, Any]) -> Optional[str]:+ def check_tool_call(self, tool_name: str, tool_args: dict[str, Any]) -> Optional[str]:"""Return formatted hint text for newly visited directories, or None."""- if not self.enabled:+ from agent.safe_worker_policy import safe_worker_enabled++ if not self.enabled or safe_worker_enabled():return Noneif self._home_is_working_dir:return Nonediff --cc cron/executions.pyindex 553201cef50,78c5825391e..0d679bce2f4--- a/cron/executions.py+++ b/cron/executions.py@@@ -311,17 -311,9 +311,17 @@@ def mark_execution_running(execution_iddef finish_execution(execution_id: str, *, success: bool, error: Optional[str] = None,- delivery_outcome: Optional[str] = None,+ delivery_outcome: Optional[str] = None, departed_owner: bool = False,- ) -> Optional[Dict[str, Any]]:+ ) -> Optional[dict[str, Any]]:- """Write a terminal result once; terminal attempts cannot be rewritten."""+ """Write a terminal result once; terminal attempts cannot be rewritten.++ Only the owning process may finish its attempt. ``departed_owner`` is the one exception:+ receipt recovery (``cron.scheduler_authority.reconcile_pending``) holds the owner's+ terminal canonical result for an attempt whose firing process provably exited before its+ own bookkeeping. It settles that attempt with the receipt's verdict instead of leaving it+ ``running`` for the dead-owner sweep to rewrite as ``unknown``; a live or same-process+ owner still finishes its own row.+ """now = _hermes_now().isoformat()status = "completed" if success else "failed"detail = None if success else (str(error) if error else "unknown failure")diff --cc cron/jobs.pyindex ceacfdc7027,d9c8383391a..9c8dc53a7a6--- a/cron/jobs.py+++ b/cron/jobs.py@@@ -478,13 -478,8 +478,13 @@@ NO_AGENT_WITHOUT_SCRIPT_ERROR ="there is nothing for the job to run.")+SCRIPT_IS_COMMAND_LINE_ERROR = (+ "script must name a file under {scripts_dir} (e.g. 'watchdog.sh'), not a shell command line: "+ "{script!r} has no such file. Write the command into a script there and pass its filename."+)+- def job_payload_is_empty(job: Dict[str, Any]) -> bool:+ def job_payload_is_empty(job: dict[str, Any]) -> bool:"""True when a job record has nothing runnable (blank prompt, no script, no skills) AND atleast one payload field is explicitly present. ``no_agent`` already requires a script."""if _coerce_job_text(job.get("prompt")).strip() or _coerce_job_text(job.get("script")).strip():diff --cc cron/scheduler.pyindex ca345954db5,72b1d0f2858..33d55f23efc--- a/cron/scheduler.py+++ b/cron/scheduler.py@@@ -3508,13 -3450,7 +3508,13 @@@ def _run_one_job_bodyreturn _finish_completed_run(d, fire_owner, execution_id)- except BaseException as e: # noqa: BLE001 — deliberate: see below+ except BaseException as e:+ from cron.scheduler_authority import CronExecutionUnknown+ if isinstance(e, CronExecutionUnknown):+ from cron.jobs import pause_job+ pause_job(job["id"], reason=str(e))+ logger.error("Cron %s paused with unverified admission: %s", job["id"], e)+ return False# BaseException, not Exception: CancelledError/KeyboardInterrupt/SystemExit propagate here.# Without mark_job_run(False) a finite one-shot is wedged: claim_dispatch consumed# repeat.completed but last_run_at is never written. Record first, then re-raisediff --cc gateway/platforms/api_server.pyindex 3bf690f1154,0d2055b04fd..b16b07f7f15--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@@ -3404,12 -3471,8 +3404,12 @@@ class APIServerAdapter(OpenAICompatRouthome = Path(db.db_path).parentfrom tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner- def _admit() -> Optional[Dict[str, Any]]:+ def _admit() -> Optional[dict[str, Any]]:- owner = find_canonical_live_owner(home)+ try:+ owner = find_canonical_live_owner(home)+ except ValueError:+ # No reachable profile authority to hand the chat to: this process runs the turn.+ return None# Only the canonical Bot Chat's own lineage: a peer turn into any other session runs here.if owner is None or db.get_compression_tip(session_id) != owner["session_id"]:return None@@@ -3447,13 -3510,13 +3447,13 @@@return _error_response(record.get("error") or f"Bot Chat delivery {record['status']}", 502,code=record.get("reason") or record["status"], headers=headers)- async def _await_live_bot_chat_receipt(self, home: Path, record: Dict[str, Any], *, keepalive=None) -> Dict[str, Any]:+ async def _await_live_bot_chat_receipt(self, home: Path, record: dict[str, Any], *, keepalive=None) -> dict[str, Any]:- """Wait on the owner's mailbox record through the shared ``await_delivery_async`` primitive until it- settles or the local DM budget runs out; ``keepalive`` (async) is called every SSE keepalive interval- so a streaming caller's proxy keeps the socket."""- from tools.bot_live_delivery import await_delivery_async+ """Wait on the live Bot Chat's receipt (the authority admission's waiter, or the legacy owner+ mailbox through ``await_delivery_async``) until it settles or the local DM budget runs out;+ ``keepalive`` (async) is called every SSE keepalive interval so a streaming caller's proxy+ keeps the socket."""+ from gateway.platforms.api_server_bot_chat import await_live_deliveryfrom tools.bot_mode_dm import _LIVE_WAIT_SECONDS- delivery_id = record["delivery_id"]deadline = time.monotonic() + _LIVE_WAIT_SECONDSwhile record["status"] in ("queued", "claimed"):remaining = deadline - time.monotonic()@@@ -4128,13 -4190,12 +4128,13 @@@tool_complete_callback=None, interim_assistant_callback=None, reasoning_callback=None,status_callback=None, agent_ref: Optional[list] = None, active_run_id: Optional[str] = None,gateway_session_key: Optional[str] = None, requested_model: Optional[str] = None,- requested_provider: Optional[str] = None, model_options: Optional[Dict[str, Any]] = None,- route: Optional[Dict[str, Any]] = None, session_model: Optional[str] = None,- requested_runtime: Optional[Dict[str, Any]] = None, route_source: str = "global",+ requested_provider: Optional[str] = None, model_options: Optional[dict[str, Any]] = None,+ route: Optional[dict[str, Any]] = None, session_model: Optional[str] = None,+ requested_runtime: Optional[dict[str, Any]] = None, route_source: str = "global",confirmed_runtime_lock: bool = False, bind_declared_conversation: bool = False,+ request_id: Optional[str] = None, history_from_session: bool = False, run_owner_scope=None,- session_history_delivery: str = "", turn_author: Optional[Dict[str, Any]] = None,- relay_metadata: Optional[Dict[str, Any]] = None, notification_category: str = "result",+ session_history_delivery: str = "", turn_author: Optional[dict[str, Any]] = None,+ relay_metadata: Optional[dict[str, Any]] = None, notification_category: str = "result",resume_unanswered_turn: bool = False, approval_notify_callback=None,approval_session_key: Optional[str] = None) -> tuple:"""Create an agent and run one turn in a thread executor -> ``(result, usage)``.@@@ -4569,12 -4614,6 +4569,12 @@@"""Not used — the HTTP request/response cycle handles delivery directly."""return SendResult(success=False, error="API server uses HTTP request/response, not send()")+ async def send_clarify(self, chat_id: str, question: str, choices: Optional[list],+ clarify_id: str, session_key: str,- metadata: Optional[Dict[str, Any]] = None) -> SendResult:++ metadata: Optional[dict[str, Any]] = None) -> SendResult:+ from gateway.platforms.api_server_authority_runs import send_clarify+ return await send_clarify(self, chat_id=chat_id, clarify_id=clarify_id)+- async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:+ async def get_chat_info(self, chat_id: str) -> dict[str, Any]:"""Return basic info about the API server."""return {"name": "API Server", "type": "api", "host": self._host, "port": self._port}diff --cc gateway/platforms/api_server_openai_routes.pyindex 9917cff78ad,0ebac98fad1..89c1ba349c3--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@@ -75,34 -75,10 +75,34 @@@ def _finish_reason(completed, is_partiareturn "length"if agent_error is not None or is_failed or (not completed and err_msg):return "error"- return "stop"+ return 'cancelled' if not completed else 'stop'+++_RESPONSES_FINGERPRINT_KEYS = (+ "input", "instructions", "previous_response_id", "conversation", "conversation_history", "model",+ "provider", "model_options", "tools", "truncation",+)+++def _response_identity(store, durable_key):+ if durable_key is not None:+ import hashlib+ return ('resp_' + hashlib.sha256(durable_key[0].encode()).hexdigest()[:28],+ store.request_created_at(durable_key[0]))+ return f'resp_{uuid.uuid4().hex[:28]}', int(time.time())+++def _response_status(result):+ if result.get('interrupted'):+ return 'cancelled'+ if result.get('failed') or result.get('error'):+ return 'failed'+ if result.get('completed') is False:+ return 'incomplete'+ return 'completed'- def _hermes_extras(completed, is_partial, is_failed, err_msg, finish_reason: str) -> Dict[str, Any]:+ def _hermes_extras(completed, is_partial, is_failed, err_msg, finish_reason: str) -> dict[str, Any]:return {"completed": completed, "partial": is_partial, "failed": is_failed, "error": err_msg,"error_code": "output_truncated" if finish_reason == "length" else "agent_error"}@@@ -241,79 -217,43 +241,79 @@@ class _ResponsesStream"""def __init__(self, adapter, response, *, response_id: str, model: str, created_at: int,- conversation_history: List[Dict[str, str]], user_message: str,+ conversation_history: list[dict[str, str]], user_message: str,- instructions: Optional[str], conversation: Optional[str], store: bool, session_id: str):+ instructions: Optional[str], conversation: Optional[str], store: bool, session_id: str,+ durable_key=None, terminal_replay=False):from gateway.platforms import api_server as apiself._api = apiself.adapter, self.response, self.response_id = adapter, response, response_idself.model, self.created_at, self.conversation_history = model, created_at, conversation_historyself.user_message, self.instructions = user_message, instructionsself.conversation, self.store, self.session_id = conversation, store, session_id+ self.durable_key = durable_key+ self.terminal_replay = terminal_replay# Resolved in the request's profile scope: a snapshot written after it (disconnect) must not follow another.self.response_store = adapter._current_response_store()- self.final_text_parts: List[str] = []- self.pending_tool_calls: List[Dict[str, Any]] = [] # open function_call items, in order- self.emitted_items: List[Dict[str, Any]] = [] # output items so far (terminal payload)+ self.final_text_parts: list[str] = []+ self.pending_tool_calls: list[dict[str, Any]] = [] # open function_call items, in order+ self.emitted_items: list[dict[str, Any]] = [] # output items so far (terminal payload)self.output_index = 0self.call_counter = 0 # call_id fallback when the agent supplies no tool_call_idself.sequence_number = 0- self.message_item_id = f"msg_{uuid.uuid4().hex[:24]}"+ self._identity_counts = {}+ self._published_output_ids = []+ self._suppress_incremental = False+ self.message_item_id = self._item_id('message')self.message_output_index: Optional[int] = Noneself.message_opened = False- self.reasoning_item: Optional[Dict[str, Any]] = None # open ``reasoning`` output item+ self.reasoning_item: Optional[dict[str, Any]] = None # open ``reasoning`` output itemself.final_response_text = ""self.transformed_final = "" # non-append transform_llm_output rewrite; replaces the deltasself.agent_error: Optional[str] = None- self.usage: Dict[str, int] = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}+ self.usage: dict[str, int] = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}self.terminal_snapshot_persisted = False- self.recorded_events: List[tuple] = [] # (event_type, data) as written, for idempotent replay++ self.recorded_events: list[tuple] = [] # (event_type, data) as written, for idempotent replayself.result: Any = None- self._batch_buf: List[str] = []+ self._batch_buf: list[str] = []self._batch_timer: Optional[asyncio.Task] = Noneself._batch_lock = asyncio.Lock()- async def write_event(self, event_type: str, data: Dict[str, Any]) -> None:+ async def write_event(self, event_type: str, data: dict[str, Any]) -> None:+ if self.durable_key and 'output_index' in data:+ if self._suppress_incremental:+ return+ index = data['output_index']+ if event_type == 'response.output_item.added':+ valid = index == len(self._published_output_ids)+ if valid:+ self._published_output_ids.append(data['item']['id'])+ else:+ identity = data.get('item_id') or data.get('item', {}).get('id')+ valid = 0 <= index < len(self._published_output_ids) and (+ identity is None or self._published_output_ids[index] == identity)+ if not valid:+ # A late/backpressured observer may miss a globally allocated prefix. Keep the+ # prefix it already published; complete from the canonical terminal snapshot.+ self._suppress_incremental = True+ returnif "sequence_number" not in data:data["sequence_number"] = self.sequence_numberself.sequence_number += 1+ self.recorded_events.append((event_type, data))await self.response.write(self._api._sse_frame(data, event=event_type))+ def _item_id(self, kind, *, call_id=None, commentary=False):+ from gateway.platforms.api_server_response_identity import next_item_id+ return next_item_id(self.response_id, self._identity_counts, kind,+ call_id=call_id, commentary=commentary)++ def _output_index(self, item_id):+ index = (self.response_store.output_index(self.durable_key[0], item_id)+ if self.durable_key else self.output_index)+ self.output_index = max(self.output_index, index + 1)+ return index+- def envelope(self, status: str) -> Dict[str, Any]:+ def envelope(self, status: str) -> dict[str, Any]:return {"id": self.response_id, "object": "response", "status": status,"created_at": self.created_at, "model": self.model}@@@ -327,16 -266,12 +327,16 @@@env["usage"] = self._api._responses_usage_payload(self.usage)return env- def _history_with_user(self) -> List[Dict[str, Any]]:+ def _history_with_user(self) -> list[dict[str, Any]]:return list(self.conversation_history) + [{"role": "user", "content": self.user_message}]- def persist_snapshot(self, response_env: Dict[str, Any], *, history=None, session_id=None):+ def persist_snapshot(self, response_env: dict[str, Any], *, history=None, session_id=None):if not self.store:return+ if self.durable_key and self.response_store.get(self.durable_key[0]) is not None:+ return # A concurrent observer already committed the exact terminal envelope.+ advance_conversation = self.conversation and (not self.terminal_replay+ or self.response_store.get_conversation(self.conversation) in (None, self.response_id))self.response_store.put(self.response_id, {"response": response_env,"conversation_history": self._history_with_user() if history is None else history,@@@ -600,17 -527,9 +600,17 @@@self.terminal_snapshot_persisted = Trueawait self.write_event("response.failed", {"type": "response.failed", "response": env})- async def emit_completed(self) -> Dict[str, Any]:- async def emit_completed(self) -> None:- env = self.terminal_envelope("completed", self._final_items())++ async def emit_completed(self) -> dict[str, Any]:result = self.result+ status = _response_status(result)+ output = self._final_items()+ if self.durable_key:+ start = self.adapter._response_messages_turn_start_index(self.conversation_history, self.user_message, result)+ output = self.adapter._extract_output_items(result, start_index=start, response_id=self.response_id)+ output = self.response_store.order_output(self.durable_key[0], output)+ env = self.terminal_envelope(status, output,+ error=self._api._redact_api_error_text(result.get('error') or 'The admitted turn failed.')+ if status == 'failed' else None)full_history = self.adapter._build_response_conversation_history(self.conversation_history, self.user_message, result, self.final_response_text,tool_output_max_chars=self.adapter._history_tool_output_max_chars)@@@ -638,74 -548,6 +638,74 @@@await self.write_event("response.failed", {"type": "response.failed", "response": env})- def _parse_chat_messages(messages: List[Any]) -> tuple:++def _parse_chat_messages(messages: list[Any]) -> tuple:+ """Chat ``messages`` -> ``(system_prompt, conversation_messages, error_response_or_None)``.++ System messages -> ephemeral system prompt layered ON TOP of core, flattened to text+ (Anthropic rejects images there, OpenAI text models ignore them)."""+ from gateway.platforms.api_server import (+ _multimodal_validation_error, _normalize_chat_content, _normalize_multimodal_content)+ system_prompt = None- conversation_messages: List[Dict[str, str]] = []++ conversation_messages: list[dict[str, str]] = []+ for idx, msg in enumerate(messages):+ role = msg.get("role", "")+ raw_content = msg.get("content", "")+ if role == "system":+ content = _normalize_chat_content(raw_content)+ system_prompt = content if system_prompt is None else system_prompt + "\n" + content+ elif role in {"user", "assistant"}:+ try:+ content = _normalize_multimodal_content(raw_content)+ except ValueError as exc:+ return None, None, _multimodal_validation_error(exc, param=f"messages[{idx}].content")+ conversation_messages.append({"role": role, "content": content})+ return system_prompt, conversation_messages, None+++def _parse_responses_input(raw_input: Any) -> tuple:+ """Responses ``input`` (string or item array) -> ``(input_messages, error_response_or_None)``."""+ from gateway.platforms.api_server import (+ _error_response, _multimodal_validation_error, _normalize_multimodal_content)- input_messages: List[Dict[str, Any]] = []++ input_messages: list[dict[str, Any]] = []+ if isinstance(raw_input, str):+ input_messages = [{"role": "user", "content": raw_input}]+ elif isinstance(raw_input, list):+ for idx, item in enumerate(raw_input):+ if isinstance(item, str):+ input_messages.append({"role": "user", "content": item})+ elif _is_reasoning_input_item(item):+ continue+ elif isinstance(item, dict):+ try:+ content = _normalize_multimodal_content(item.get("content", ""))+ except ValueError as exc:+ return None, _multimodal_validation_error(exc, param=f"input[{idx}].content")+ input_messages.append({"role": item.get("role", "user"), "content": content})+ else:+ return None, _error_response("'input' must be a string or array", 400)+ return input_messages, None+++def _parse_conversation_history(raw_history: Any) -> tuple:+ """Explicit Responses ``conversation_history`` -> ``(history, error_response_or_None)``."""+ from gateway.platforms.api_server import (+ _error_response, _multimodal_validation_error, _normalize_multimodal_content)- conversation_history: List[Dict[str, Any]] = []++ conversation_history: list[dict[str, Any]] = []+ if not isinstance(raw_history, list):+ return None, _error_response("'conversation_history' must be an array of message objects", 400)+ for i, entry in enumerate(raw_history):+ if _is_reasoning_input_item(entry):+ continue+ if not isinstance(entry, dict) or "role" not in entry or "content" not in entry:+ return None, _error_response(f"conversation_history[{i}] must have 'role' and 'content' fields", 400)+ try:+ entry_content = _normalize_multimodal_content(entry["content"])+ except ValueError as exc:+ return None, _multimodal_validation_error(exc, param=f"conversation_history[{i}].content")+ conversation_history.append({"role": str(entry["role"]), "content": entry_content})+ return conversation_history, None++class OpenAICompatRoutesMixin:"""/v1/chat/completions and /v1/responses handlers + SSE writers."""@@@ -1133,9 -976,9 +1133,9 @@@async def _write_sse_responses(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,+ 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) -> "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``@@@ -1191,59 -1031,6 +1191,59 @@@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))+ 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 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":"""POST /v1/responses — OpenAI Responses API format."""from gateway.platforms.api_server import (@@@ -1469,7 -1300,7 +1469,7 @@@return out@staticmethod- def _extract_output_items(result: Dict[str, Any], start_index: int = 0, *, response_id=None) -> List[Dict[str, Any]]:- def _extract_output_items(result: dict[str, Any], start_index: int = 0) -> list[dict[str, Any]]:++ def _extract_output_items(result: dict[str, Any], start_index: int = 0, *, response_id=None) -> list[dict[str, Any]]:"""Output items from ``result["messages"][start_index:]``: ``function_call`` per assistanttool_call, ``function_call_output`` per tool message, then the final ``message``."""from gateway.platforms.api_server import _redact_api_error_textdiff --cc gateway/platforms/api_server_runs.pyindex 7a8fee4f910,7853fdf70ef..1f62dda899a--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@@ -90,15 -90,10 +90,15 @@@ _USAGE_FIELDS =("total_tokens", "session_total_tokens"), ("cache_read_tokens", "session_cache_read_tokens"),("cache_write_tokens", "session_cache_write_tokens"))# Tool-progress event -> SSE payload fields (tool_name, preview, kwargs); key order is wire format.- def _call_id(kw: Dict[str, Any]) -> Dict[str, Any]:++def _call_id(kw: dict[str, Any]) -> dict[str, Any]:+ return {"tool_call_id": kw["tool_call_id"]} if kw.get("tool_call_id") else {}++_FIXED_EVENT_FIELDS = {- "tool.started": lambda tool, preview, kw: {"tool": tool, "preview": preview},+ "tool.started": lambda tool, preview, kw: {"tool": tool, "preview": preview, **_call_id(kw)},"tool.completed": lambda tool, preview, kw: {- "tool": tool, "duration": round(kw.get("duration", 0), 3), "error": kw.get("is_error", False)},+ "tool": tool, "duration": round(kw.get("duration", 0), 3), "error": kw.get("is_error", False),+ **_call_id(kw)},"reasoning.available": lambda tool, preview, kw: {"text": preview or ""}}_TOOL_COMPLETED_PREVIEW_MAX_CHARS = 500@@@ -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 canonicalstatus = self._run_statuses.get(run_id)if status is not None:if run_id in self._run_idempotency_ids:@@@ -519,8 -500,7 +519,8 @@@ class _RunLaunchrequest_profile: Anybrowser_control_principal: Anybrowser_control_transport_family: Any- turn_author: Optional[Dict[str, Any]] = None # memory-attribution label only; grants nothing+ turn_author: Optional[dict[str, Any]] = None # memory-attribution label only; grants nothing+ admission: Any = None@propertydef approval_session_key(self) -> str:diff --cc gateway/platforms/msgraph_webhook.pyindex 038f5c2abe2,a10d32139d7..a8a1a9602b5--- a/gateway/platforms/msgraph_webhook.py+++ b/gateway/platforms/msgraph_webhook.py@@@ -308,46 -304,14 +308,46 @@@ class MSGraphWebhookAdapter(BasePlatforrendered = json.dumps(notification, indent=2, sort_keys=True)[:4000]return f"Microsoft Graph change notification:\n\n```json\n{rendered}\n```"- async def _schedule_notification(self, notification: Dict[str, Any], event: MessageEvent) -> None:- def _schedule_notification(self, notification: dict[str, Any], event: MessageEvent) -> None:++ async def _schedule_notification(self, notification: dict[str, Any], event: MessageEvent) -> None:scheduler = self._notification_scheduler- if scheduler is None:- coro = self.handle_message(event)- else:- coro = scheduler(notification, event)- if not asyncio.iscoroutine(coro):- return- task = asyncio.create_task(coro)- self._background_tasks.add(task)- task.add_done_callback(self._background_tasks.discard)+ if scheduler is not None:+ result = scheduler(notification, event)+ if asyncio.iscoroutine(result):+ await result+ return # Plugin-owned pipeline; never also start a gateway inference.+ await self._admit_notification(event)++ @property+ def token(self):+ return self._client_state++ async def _admit_notification(self, event):+ # Only _ingest_notification reaches this after resource + clientState gates;+ # the HTTP handler additionally owns source-IP and body-size authorization.+ # Reuse the existing private automation envelope: public native admission+ # continues to reject internal events and arbitrary metadata.+ from datetime import datetime, timezone+ from gateway.platforms.webhook_ingress import producer_scope+ from gateway.session_ingress_context import capture_provenance+ from hermes_state_runtime import admit_session_input, RuntimeStoreError++ async with producer_scope(self, event) as authority:+ authority._require_admission_open()+ provenance = capture_provenance(authority.runner, event)+ if provenance is None:+ raise RuntimeStoreError('permission_denied')+ ref = authority.register(event.source)+ route = authority.sessions[ref.session_id].route+ source = event.source.to_dict()+ source['is_bot'] = event.source.is_bot+ envelope = {'source': source, 'route': route, 'provenance': provenance,+ 'timestamp': datetime.fromtimestamp(0, timezone.utc).isoformat(),+ 'event': {'message_id': event.message_id},+ 'automation': {'identity': event.message_id, 'owner': ref.session_id}}+ row = admit_session_input(authority.db, epoch=authority.epoch,+ principal_id='msgraph:' + route, session_id=ref.session_id,+ request_id=event.message_id, payload={'text': event.text, 'native_text_v1': envelope})+ event._gateway_accepted = True+ authority._publish_pending(ref)+ authority._schedule(ref)+ return authority._receipt(row)diff --cc gateway/relay/adapter.pyindex 87c08ba79be,4df932ba1a3..b80bd45d1a0--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@@ -1154,9 -1139,115 +1154,9 @@@ class RelayAdapter(RelayDiscordInteract"relay passthrough_forward dropped (no handler): platform=%s method=%s path=%s",platform, getattr(forward, "method", "?"), getattr(forward, "path", "?"),)- except Exception: # noqa: BLE001 - a bad forward must never break the reader+ except Exception:logger.warning("relay passthrough_forward handling failed", exc_info=True)- def _discord_interaction_to_event(self, forward):- """Convert a forwarded Discord interaction body to a MessageEvent, or None for- an unusable body (a PING is answered at the edge and never forwarded). The- session source mirrors the connector's ``interactionSessionSource`` so the- session key matches the one the follow-up capability was bound under."""- try:- payload = json.loads(bytes(getattr(forward, "body", b"")).decode("utf-8"))- except Exception:- return None- if not isinstance(payload, dict):- return None- # type 2 = APPLICATION_COMMAND; 3 = MESSAGE_COMPONENT; 5 = MODAL_SUBMIT.- itype = payload.get("type")- data = payload.get("data") or {}- message_type = MessageType.TEXT- if itype == 2:- # Normalize to a leading-slash command string ("/name arg…"), the- # shape the dispatcher and the connector's Slack slash lane expect.- text = ("/" + str(data.get("name") or "")).rstrip("/") or ""- if text:- parts = [text] + self._render_interaction_options(data.get("options"))- text = " ".join(parts).strip()- message_type = MessageType.COMMAND- elif itype == 3:- text = str(data.get("custom_id") or "")- else:- text = ""- member = payload.get("member") or {}- user = (member.get("user") if isinstance(member, dict) else None) or payload.get("user") or {}- if not isinstance(user, dict):- user = {}- guild_id = payload.get("guild_id")- source = SessionSource(- # The LOGICAL platform, not RELAY: session keys must match the connector's- # capability binding (platform="discord"), /sethome must file under the- # logical platform, and _capture_scope skips the generic "relay".- platform=Platform.DISCORD,- chat_id=str(payload.get("channel_id") or ""),- # "group", not "channel": both the connector's capability binding and the- # native Discord adapter key guild channels as "group".- chat_type="group" if guild_id else "dm",- user_id=str(user["id"]) if user.get("id") else None,- user_name=str(user["username"]) if user.get("username") else None,- scope_id=str(guild_id) if guild_id else None,- message_id=str(payload.get("id")) if payload.get("id") else None,- # Same upstream-trust marker the relay text lane stamps. Set locally, never- # read off the wire (engages /sethome's via_relay guard).- delivered_via_upstream_relay=True,- # Profile routing (multiplex mode), mirroring _event_from_wire.- # The HERMES profile this interaction is routed to (multiplex mode) — mirrors _event_from_wire's- # profile stamping for plain relayed messages (#60586). Without this, a Team-Gateway's Discord- # slash-command/button/modal always fell back to the legacy agent:main namespace even when the- # connector resolved a specific profile for it.- profile=getattr(forward, "profile", None),- )- event = MessageEvent(text=text, message_type=message_type, source=source)- if itype == 3:- # A component press whose custom_id is a Hermes prompt token- # (hp1:<prompt_id>:<option_id>) becomes a STRUCTURED prompt answer;- # foreign custom_ids keep the best-effort TEXT shape.- decoded = self._decode_prompt_token(text)- if decoded:- prompt_id, option_id = decoded- msg = payload.get("message") or {}- prompt_message_id = str(msg["id"]) if isinstance(msg, dict) and msg.get("id") else None- event.prompt_response = {- "prompt_id": prompt_id,- "option_id": option_id,- "prompt_message_id": prompt_message_id,- }- event.text = f"/{option_id}"- event.message_type = MessageType.COMMAND- return event-- @staticmethod- def _decode_prompt_token(token: str):- """Decode an hp1:<prompt_id>:<option_id> callback token, or None (mirrors the connector's promptCodec)."""- parts = (token or "").split(":")- if len(parts) != 3 or parts[0] != "hp1":- return None- if not _PROMPT_ID_RE.match(parts[1]) or not _PROMPT_ID_RE.match(parts[2]):- return None- return parts[1], parts[2]-- @staticmethod- def _render_interaction_options(options) -> list:- """Render Discord interaction options to text parts: scalars contribute their- value (native ``f"/model {name}"`` shape); SUB_COMMAND (1) / SUB_COMMAND_GROUP- (2) contribute their name then recurse into nested options."""- parts: list = []- if not isinstance(options, list):- return parts- for opt in options:- if not isinstance(opt, dict):- continue- if opt.get("type") in (1, 2):- sub_name = str(opt.get("name") or "").strip()- if sub_name:- parts.append(sub_name)- parts.extend(RelayAdapter._render_interaction_options(opt.get("options")))- else:- value = opt.get("value")- if value is not None and str(value).strip():- parts.append(str(value).strip())- return parts-async def disconnect(self) -> None:# The runner wraps this call in wait_for(adapter disconnect budget). Monitor# teardown and go_idle eat into the transport's drain time, so measure fromdiff --cc gateway/relay/ws_transport.pyindex 0233adf6aa1,ba6aff2362a..7ad3e9c4bf7--- a/gateway/relay/ws_transport.py+++ b/gateway/relay/ws_transport.py@@@ -932,13 -932,10 +932,13 @@@ class WebSocketRelayTransportif self._descriptor_ready is not None and not self._descriptor_ready.done():self._descriptor_ready.set_result(descriptor)- async def _on_inbound(self, frame: Dict[str, Any]) -> None:+ async def _on_inbound(self, frame: dict[str, Any]) -> None:if self._inbound is None:return- await self._inbound(_event_from_wire(frame.get("event", {})))+ from gateway.session_ingress_context import relay_callback+ event = _event_from_wire(frame.get("event", {}))+ with relay_callback(self, event):+ await self._inbound(event)# A replayed buffered delivery carries a bufferId; ack AFTER the handler# has taken it so the connector advances its cursor (no dup).buffer_id = frame.get("bufferId")diff --cc gateway/run.pyindex a61345d5314,9b40970ce41..2b69d04d113--- a/gateway/run.py+++ b/gateway/run.py@@@ -961,21 -961,10 +961,21 @@@ def _warm_turn_machinery_sync() -> intTTL cache), the local Python toolchain probe (#106064), and the default route's context-windowmetadata (#105986) — a catalog HTTP probe that must not sit between the first inbound turn and itsinference request. Context files remain lazy because they need the active turn's agent."""- import run_agent # noqa: F401 # heavy import graph, cached in sys.modules+ import run_agent # heavy import graph, cached in sys.modulesimport model_tools- tool_defs = model_tools.get_tool_definitions(quiet_mode=True)+ # Warm the schemas the turn will actually build: the profile's own toolsets (`video`, `image_gen`+ # and friends rebuild their schema from a vendor catalog over the network; ``None`` = every+ # registered tool, which dials OpenRouter/DeepInfra for profiles that never enabled them).+ enabled_toolsets = None+ try:+ from hermes_cli.config import load_config_readonly+ from hermes_cli.tools_config import _get_platform_tools++ enabled_toolsets = sorted(_get_platform_tools(load_config_readonly(), "cli"))+ except Exception:+ logger.debug("platform toolset resolution failed; warming the full tool surface", exc_info=True)+ tool_defs = model_tools.get_tool_definitions(enabled_toolsets=enabled_toolsets, quiet_mode=True)from hermes_cli.config import load_config_readonlyagent_cfg = load_config_readonly().get("agent")@@@ -5099,14 -5503,6 +5099,14 @@@ def _refresh_host_gateway_record(runnerlogger.debug("host gateway record refresh failed", exc_info=True)+# Bootstrap phases bound on the facade: ``_host_attach_or_none`` reads the replace step through this+# module, and the lifecycle tests patch/drive these phases as ``gateway.run`` attributes.- from gateway.run_bootstrap import ( # noqa: E402++from gateway.run_bootstrap import (+ _start_gateway_make_shutdown_signal_handler, _start_gateway_replace_existing_instance,+ _start_gateway_shutdown_tail, _start_gateway_start_cron_and_housekeeping,+)++async def _host_attach_or_none(replace: bool, force: bool = False) -> Optional[bool]:"""Attach / rescan / refuse against the ONE host gateway; ``None`` = start normally.diff --cc gateway/run_inbound.pyindex ed66581e9e9,e1929844e9b..69170445da0--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@@ -745,9 -744,73 +745,9 @@@ class GatewayInboundMixin(GatewayInbounself._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- ) -> Tuple[bool, Optional[str], Optional[str], Optional[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)."""from hermes_cli.commands import is_gateway_known_command, resolve_command as _resolve_cmddiff --cc gateway/run_profile_reconcile.pyindex 6b37f30c170,1396dacb17b..f2a786e3bdf--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@@ -96,16 -96,12 +96,16 @@@ class GatewayProfileReconcileMixin# ── reconcile ─────────────────────────────────────────────────────────────────────────────────- async def reconcile_served_profiles(self, *, reason: str = "request") -> Dict[str, Any]:+ async def reconcile_served_profiles(self, *, reason: str = "request") -> dict[str, Any]:- """Diff ``profiles/`` against the served set: start adapters for new profiles, tear down and- unroute deleted ones, (re)build adapters for served profiles whose config/.env changed. Other- profiles' adapters are never touched. Returns ``{"added", "removed", "rescanned", "served_profiles"}``."""- from gateway.run import _multiplex_profile_homes- result: dict[str, Any] = {"added": [], "removed": [], "rescanned": [], "reason": reason}+ """Diff ``profiles/`` (what exists now) against the served set (the process reservation):+ reserve + build the runtime and start adapters for new profiles, tear down, unroute and+ unreserve deleted ones, (re)build adapters for served profiles whose config/.env changed.+ Other profiles' adapters are never touched. A new profile whose home another gateway owns or+ whose store is unusable is parked (logged, not served) and left for an explicit rescan.+ Returns ``{"added", "removed", "rescanned", "parked", "served_profiles"}``."""+ from gateway.run import MultiplexConfigError+ from hermes_cli.profiles import profiles_to_serve- result: Dict[str, Any] = {"added": [], "removed": [], "rescanned": [], "parked": [], "reason": reason}++ result: dict[str, Any] = {"added": [], "removed": [], "rescanned": [], "parked": [], "reason": reason}if not self._multiplex_on():return {**result, "multiplex": False, "served_profiles": self.served_profile_names()}if not self._running or self._served_profile_homes is None:@@@ -255,36 -210,7 +255,36 @@@result["served_profiles"] = self.served_profile_names()return result+ def _parked_profile_names(self) -> list:+ """Profiles that exist but could not be served (unusable store, home owned elsewhere); boot's+ ``initialize_gateway_runtime`` parks into the same published ``name -> reason`` map."""+ from gateway.run_runtime import parked_profile_map+ return list(parked_profile_map(self))++ async def _serve_profile_runtime(self, name: str, home: "Path") -> Optional[str]:+ """Grow the reservation by *home* and build its session authority (boot's per-secondary+ steps). Returns the park reason — reservation released — when another gateway owns the home+ (a stray per-profile daemon) or its store cannot be opened; None when served. An+ adapters-only runner (no authority registry) grows the reservation alone."""+ from gateway.run_runtime import release_profile_home, reserve_profile_home, serve_profile_runtime+ from gateway.runtime_ownership import OwnershipConflict+ try:+ reserve_profile_home(self, name, home)+ except (OwnershipConflict, OSError) as exc:+ logger.error("[MULTIPLEX] Profile '%s' not served: %s", name, exc)+ return f"home owned by another gateway: {exc}"+ if getattr(self, "session_authorities", None) is None:+ return None+ try:+ await serve_profile_runtime(self, name, home)+ except Exception as exc:+ logger.error("[MULTIPLEX] Profile '%s' not served: its session store is unusable (%s): %s",+ name, home, exc, exc_info=True)+ release_profile_home(self, home)+ return f"session store unusable: {exc}"+ return None+- def _live_resource_claims(self, active: str) -> Dict[tuple, str]:+ def _live_resource_claims(self, active: str) -> dict[tuple, str]:"""Startup's ``claimed`` map rebuilt from what is live now: primary claims plus every connectedsecondary's credential/listener, so a hot-added profile reusing a token is parked, never asecond poller."""diff --cc gateway/session.pyindex 66194428332,7b1e37eaa67..bfcf3ba21ee--- a/gateway/session.py+++ b/gateway/session.py@@@ -538,12 -536,10 +538,12 @@@ class SessionEntrytransport_profile: Optional[str] = None# Exact session-context/channel inputs from the last human turn. Append-only dataclass field so# older positional construction of transport_profile keeps its meaning.- prompt_pin: Optional[Dict[str, Any]] = None+ prompt_pin: Optional[dict[str, Any]] = None# Gateway ``/yolo`` bypass for this lane, mirrored from ``tools.approval``'s in-memory set so a restart- # keeps it; cleared with it at every conversation boundary (``_clear_session_boundary_security_state``).- yolo: bool = False+ # keeps it. Tri-state: True/False is an explicit toggle (an OFF stays off, even over a ``--yolo`` launch);+ # None means nobody toggled it (new, branched, reset, migrated, cron entries, and every conversation+ # boundary, ``_clear_session_boundary_security_state``), so the session's launch policy applies.+ yolo: Optional[bool] = None# Fields (de)serialized verbatim, in wire order (``from_dict`` reads them with# ``data.get(name, <dataclass default>)``), split around the three ISO-datetime/token keys.diff --cc hermes_cli/backup.pyindex 9545e7c2fbf,0ae83ef92b8..9b09b30de19--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@@ -911,189 -1051,6 +911,189 @@@ def run_import(args) -> Optional[int]print("Done. Your Hermes configuration has been restored.")+def _import_members(- zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int++ zf: zipfile.ZipFile, members: list[str], prefix: str, hermes_root: Path, file_count: int+) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:+ """Reserve all affected profiles before publishing even the first config file."""+ from gateway.runtime_ownership import exclusive_maintenance+ root_res = hermes_root.resolve()+ homes = {hermes_root}+ for member in members:+ if member.startswith(_EXTERNAL_PREFIX):+ continue # restored under $HOME, outside every runtime authority+ rel = member[len(prefix):] if prefix and member.startswith(prefix) else member+ parts = Path(rel).parts+ if len(parts) >= 3 and parts[0] == "profiles":+ home = hermes_root / parts[0] / parts[1]+ if home.resolve().is_relative_to(root_res):+ homes.add(home)+ target = hermes_root / rel+ if target.suffix == ".db" and target.resolve().is_relative_to(root_res):+ homes.update([target.absolute().parent, target.resolve().parent])+ with exclusive_maintenance(homes):+ return _import_members_exclusive(zf, members, prefix, hermes_root, file_count)+++def _import_external_member(- zf: zipfile.ZipFile, member: str, home_dir: Path, new_file_mode: int, errors: List[str]++ zf: zipfile.ZipFile, member: str, home_dir: Path, new_file_mode: int, errors: list[str]+) -> bool:+ """Publish one ``_external/`` member under the user's home; False (with ``errors`` appended)+ when it is a traversal or cannot be written."""+ target = home_dir / member[len(_EXTERNAL_PREFIX):]+ # Security: the resolved target must stay under the home dir.+ try:+ target.resolve().relative_to(home_dir)+ except ValueError:+ errors.append(f" {member}: path traversal blocked")+ return False+ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ _extract_member_atomically(zf, member, target, new_file_mode)+ # External provider configs commonly hold credentials.+ if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:+ try:+ os.chmod(target, 0o600)+ except OSError:+ pass+ return True+ except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:+ errors.append(f" {member}: {exc}")+ return False+++def _import_members_exclusive(- zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int++ zf: zipfile.ZipFile, members: list[str], prefix: str, hermes_root: Path, file_count: int+) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:+ """Publish every member; return ``(restored, restored_external, errors, skipped_runtime, db_shrunk)``.++ ``db_shrunk`` holds ``(rel, live_counts, imported_counts)`` for every session database the+ import replaced with one holding fewer rows — allowed, but never silently (#100960).+ """+ errors = []+ restored = 0+ restored_external = 0+ skipped_runtime: list[str] = []+ db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []+ home_dir = Path.home().resolve()+ # Resolved once: every member is published via a temp file, and mkstemp+ # would otherwise create newly restored files as 0600.+ new_file_mode = _default_new_file_mode()++ for member in members:+ # External memory-provider state captured under the reserved+ # ``_external/`` arc prefix restores to its original home-relative+ # location (e.g. ~/.honcho/config.json), NOT under HERMES_HOME.+ if member.startswith(_EXTERNAL_PREFIX):+ if not member[len(_EXTERNAL_PREFIX):]:+ continue+ if _import_external_member(zf, member, home_dir, new_file_mode, errors):+ restored += 1+ restored_external += 1+ if restored % 500 == 0:+ print(f" {restored}/{file_count} files ...")+ continue++ # Strip prefix if detected+ if prefix and member.startswith(prefix):+ rel = member[len(prefix):]+ else:+ rel = member++ if not rel:+ continue++ try:+ parts = tuple(normalize_archive_parts(rel))+ except ValueError:+ errors.append(f" {rel}: path traversal blocked")+ continue++ # Never overwrite volatile gateway/process runtime state. These are+ # namespaced to the machine/container the backup was taken on;+ # clobbering them (especially gateway_state.json) breaks the gateway+ # reconciler on the target and disconnects hosted instances from the+ # Nous portal. Matched by basename so both the root profile and+ # named profiles (profiles/<name>/gateway_state.json) are covered.+ if parts[-1] in _IMPORT_SKIP_NAMES:+ skipped_runtime.append(rel)+ continue++ # Older archives may contain PM selections pointing at another machine.+ # Match their home-root paths; a plugin's own facts.json is user data.+ if profile_root_entry(parts) in PM_RUNTIME_ROOT_DIRS:+ skipped_runtime.append(rel)+ continue++ # A ``.db`` member is page-restored into the live file below; a+ # WAL/SHM/journal member from the archive describes a different+ # database image, and installing it beside the restored file (over+ # a live sidecar, via os.replace) would replay a foreign WAL on+ # the next open. Current backups never ship these+ # (_EXCLUDED_SUFFIXES); older or hand-built archives might.+ if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):+ skipped_runtime.append(rel)+ continue++ target = hermes_root.joinpath(*parts)++ # Security: reject absolute paths and traversals+ try:+ target.resolve().relative_to(hermes_root.resolve())+ except ValueError:+ errors.append(f" {rel}: path traversal blocked")+ continue++ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ if target.suffix == ".db":+ # Count before the write: afterwards the rows this import+ # drops are gone and there is nothing left to compare.+ before = _count_session_rows(target)+ _import_db_member(zf, member, target, new_file_mode)+ after = _count_session_rows(target)+ if before and after and after[1] < before[1]:+ db_shrunk.append((rel, before, after))+ else:+ _extract_member_atomically(zf, member, target, new_file_mode)+ if target.name in _SECRET_FILE_NAMES:+ os.chmod(target, 0o600)+ restored += 1+ except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:+ errors.append(f" {rel}: {exc}")++ if restored % 500 == 0:+ print(f" {restored}/{file_count} files ...")++ return restored, restored_external, errors, skipped_runtime, db_shrunk+++def _revive_gateway_after_import(hermes_root: Path) -> None:+ """Start an installed gateway service after a restore, best-effort and prompt-free.++ Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so+ this is safe for any backup); failures print a manual fallback, never fail the import. Only+ revived when the restore landed in the default home or no other install exists: a sandbox or+ profile restore must not install a second gateway on the default service name.+ """+ native_default = _get_platform_default_hermes_home()+ if hermes_root != native_default and any(+ (native_default / marker).exists() for marker in ("config.yaml", ".env", "state.db")):+ print("\nRestored into a non-default home; leaving the gateway service alone to avoid clashing "+ f"with the install at {native_default}.\n"+ "To start a gateway for this home, run: hermes gateway run")+ return+ try:+ from hermes_cli.gateway import _is_service_running+ from hermes_cli.gateway_setup_service import ensure_gateway_service+ if not _is_service_running():+ print()+ ensure_gateway_service(context="import")+ except Exception:+ # Import boundary: the restore already succeeded; any service failure prints the+ # manual fallback instead of failing the import.+ logger.debug("gateway revive after import failed", exc_info=True)+ print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway run")+# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---@@@ -1138,7 -1095,15 +1138,7 @@@ def _newest_first(root: Path, keep_entr_CRON_JOBS_REL = "cron/jobs.json"- def _prune_oldest(newest_first: List[Path], keep: int, remove, what: str) -> int:-# Config paths the update flow must never change (#64160): model routing and the MoA section are-# consumed machine-wide, so an update/repair cycle that rewrites them silently redirects paid-# inference. Dotted paths into raw config.yaml; a single-element tuple protects a whole section.-_PROTECTED_CONFIG_PATHS: tuple[tuple[str, ...], ...] = (- ("model", "provider"), ("model", "default"), ("model", "base_url"), ("model", "api_key"),- ("moa",))--+ def _prune_oldest(newest_first: list[Path], keep: int, remove, what: str) -> int:"""``remove(path)`` every entry past the first *keep*; return how many succeeded."""deleted = 0for p in newest_first[keep:]:@@@ -1622,14 -1533,23 +1622,14 @@@ def _restore_quick_snapshot_exclusive(swith open(manifest_path, encoding="utf-8-sig") as f:meta = json.load(f)- restored = 0- auth_restore_failed = False- for rel in meta.get("files", {}):- # Security: reject absolute paths and traversals in manifest entries- src = snap_dir / rel- try:- src.resolve().relative_to(snap_dir.resolve())- except ValueError:- logger.error("Manifest path traversal blocked: %s", rel)- if rel == "auth.json":- auth_restore_failed = True- continue+ snap_res, home_res = snap_dir.resolve(), home.resolve()- def _entry_paths(rel: str) -> Optional[Tuple[Path, Path]]:- dst = home / rel- try:- dst.resolve().relative_to(home.resolve())- except ValueError:++ def _entry_paths(rel: str) -> Optional[tuple[Path, Path]]:+ # Security: reject absolute paths and traversals in manifest entries+ src, dst = snap_dir / rel, home / rel+ if not src.resolve().is_relative_to(snap_res):+ return None+ if not dst.resolve().is_relative_to(home_res):# Named profiles may deliberately share the machine-root auth store via an# auth.json symlink. Let only that exact trusted alias reach _restore_auth_json;# every other manifest destination outside the profile remains a traversal.diff --cc hermes_cli/config.pyindex 78ada640826,576562b4715..95fcbd42b8e--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@@ -1889,24 -1889,7 +1889,24 @@@ def _raw_config_cache_hit(path_key: strreturn None- def _worker_config_snapshot() -> Optional[Dict[str, Any]]:++def _worker_config_snapshot() -> Optional[dict[str, Any]]:+ """A safe worker's frozen config, or None. Install-time loads run from ``hermes_cli`` alone+ (the installer's completion step ships no ``agent`` package), and without ``agent`` there+ is no worker policy to consult."""+ try:+ from agent.safe_worker_policy import worker_config_snapshot+ except ModuleNotFoundError as exc:+ if exc.name != "agent":+ raise+ return None+ return worker_config_snapshot()++- def _read_raw_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:+ def _read_raw_config_impl(*, want_deepcopy: bool) -> dict[str, Any]:+ snapshot = _worker_config_snapshot()+ if snapshot is not None:+ return snapshot+# Lock-free fast path for cache hits — same shape as `_load_config_impl`. `_RAW_CONFIG_CACHE`# publishes each entry as ONE `(*sig, data)` tuple replaced wholesale, so a reader sees either# the complete old entry or the complete new one; `_CONFIG_LOCK` only serializes the re-parse@@@ -2327,11 -2306,7 +2327,11 @@@ def _load_config_cache_hit(path_key: streturn None- def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:+ def _load_config_impl(*, want_deepcopy: bool) -> dict[str, Any]:+ snapshot = _worker_config_snapshot()+ if snapshot is not None:+ return _deep_merge(copy.deepcopy(DEFAULT_CONFIG), snapshot)+# Lock-free fast path for cache hits — same publication contract as `_read_raw_config_impl`# above (whole-tuple replace, `_CONFIG_LOCK` only serializes rebuilds and writers). A hit costs# ~0.024ms; behind a lock held by `save_config()` the same read measured 10010ms, and on adiff --cc hermes_cli/dashboard_auth/ws_tickets.pyindex 09c55b481fd,5afb8996e21..e7b1098c730--- a/hermes_cli/dashboard_auth/ws_tickets.py+++ b/hermes_cli/dashboard_auth/ws_tickets.py@@@ -33,8 -33,7 +33,8 @@@ class TicketInvalid(Exception)"""Ticket missing, expired, or already consumed."""-def mint_ticket(*, user_id: str, provider: str, extra: Optional[dict[str, Any]] = None) -> str:+def mint_ticket(*, user_id: str, provider: str, issuer: str = "",- extra: Optional[Dict[str, Any]] = None) -> str:++ extra: Optional[dict[str, Any]] = None) -> str:"""One-shot base64url ticket (32 random bytes) bound to this identity; ``consume_ticket``hands the ``info`` dict back to the WS handler. ``extra`` rides along for routes that needserver-chosen context (the Bot Desktop bridge pins the RFB socket's profile home here so adiff --cc hermes_cli/lifecycle.pyindex a7dd1a9c2ef,de01dd04b84..6ff300d729b--- a/hermes_cli/lifecycle.py+++ b/hermes_cli/lifecycle.py@@@ -27,12 -23,8 +27,12 @@@ def _plugin_hooks(hook_name: str, **kwareturn plugins.invoke_hook(hook_name, **kwargs)- def invoke_hook(hook_name: str, **kwargs: Any) -> List[Any]:+ def invoke_hook(hook_name: str, **kwargs: Any) -> list[Any]:"""Notify first-party observers, then invoke compatibility plugin hooks."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return []_observe(hook_name, **kwargs)return _plugin_hooks(hook_name, **kwargs)diff --cc hermes_cli/plugins.pyindex 13171e7cf7f,b905d335de7..30aac7e13ce--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@@ -2196,7 -2186,44 +2196,7 @@@ def get_plugin_command_handler(name: streturn entry["handler"] if entry else None- def get_plugin_commands() -> Dict[str, dict]:-_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS = 30.0---def resolve_plugin_command_result(result: Any) -> Any:- """Resolve a plugin command result, awaiting async handlers: ``asyncio.run`` when no loop is- running, else a helper thread with its own loop (30s bound so a hung handler cannot wedge the- terminal)."""- if not inspect.isawaitable(result):- return result- try:- asyncio.get_running_loop()- except RuntimeError:- return asyncio.run(result)- outcome: dict[str, Any] = {}- failure: dict[str, BaseException] = {}- done = threading.Event()-- def _runner() -> None:- try:- outcome["value"] = asyncio.run(result)- except BaseException as exc: # pragma: no cover - re-raised below- failure["exc"] = exc- finally:- done.set()-- # copy_context: the helper thread must see the caller's profile/secret scope, else an- # async hook under a running loop reads the default HERMES_HOME and get_secret raises.- threading.Thread(target=contextvars.copy_context().run, args=(_runner,),- name="hermes-plugin-command-await", daemon=True).start()- if not done.wait(timeout=_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS):- raise TimeoutError("Plugin command async handler did not complete within "- f"{_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS:.0f}s")- if "exc" in failure:- raise failure["exc"]- return outcome.get("value")--+ def get_plugin_commands() -> dict[str, dict]:"""Plugin commands dict (name -> {handler, description, plugin}) after idempotent discovery."""return _ensure_plugins_discovered()._plugin_commandsdiff --cc hermes_cli/plugins_dispatch.pyindex 41d4dbd00ce,0297573b7ec..853b38daddc--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@@ -180,46 -180,9 +180,46 @@@ def _hook_uses_callback_timeout(hook_nareturn hook_name in _HOOK_TIMEOUT_BOUNDED_HOOKS or hook_name in _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS+_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS = 30.0+++def resolve_plugin_command_result(result: Any) -> Any:+ """Resolve a plugin command result, awaiting async handlers: ``asyncio.run`` when no loop is+ running, else a helper thread with its own loop (30s bound so a hung handler cannot wedge the+ terminal)."""+ if not inspect.isawaitable(result):+ return result+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return asyncio.run(result)- outcome: Dict[str, Any] = {}- failure: Dict[str, BaseException] = {}++ outcome: dict[str, Any] = {}++ failure: dict[str, BaseException] = {}+ done = threading.Event()++ def _runner() -> None:+ try:+ outcome["value"] = asyncio.run(result)+ except BaseException as exc: # pragma: no cover - re-raised below+ failure["exc"] = exc+ finally:+ done.set()++ # copy_context: the helper thread must see the caller's profile/secret scope, else an+ # async hook under a running loop reads the default HERMES_HOME and get_secret raises.+ threading.Thread(target=contextvars.copy_context().run, args=(_runner,),+ name="hermes-plugin-command-await", daemon=True).start()+ if not done.wait(timeout=_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS):+ raise TimeoutError("Plugin command async handler did not complete within "+ f"{_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS:.0f}s")+ if "exc" in failure:+ raise failure["exc"]+ return outcome.get("value")++class PluginDispatchMixin:@staticmethod- def _hook_callback_kwargs(callback: Callable, payload: Dict[str, Any]) -> Dict[str, Any]:+ def _hook_callback_kwargs(callback: Callable, payload: dict[str, Any]) -> dict[str, Any]:"""The slice of *payload* a callback accepts: everything for ``**kwargs`` (orun-introspectable) callbacks, only declared names for narrow legacy signatures."""try:@@@ -242,9 -205,10 +242,9 @@@are (loop-safe), otherwise the bare coroutine object is appended to the results and theplugin's body never runs (#12449)."""- from hermes_cli.plugins import resolve_plugin_command_resultreturn resolve_plugin_command_result(callback(**cls._hook_callback_kwargs(callback, payload)))- def invoke_hook(self, hook_name: str, **kwargs: Any) -> List[Any]:+ def invoke_hook(self, hook_name: str, **kwargs: Any) -> list[Any]:"""Call all callbacks for *hook_name*; return their non-``None`` results.Payloads evolve additively: ``**kwargs`` callbacks get everything, narrow signatures only@@@ -519,13 -480,9 +519,13 @@@def has_hook(self, hook_name: str) -> bool:"""Return True when at least one callback is registered for a hook."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return Falsereturn bool(self._hooks.get(hook_name))- async def ainvoke_hook(self, hook_name: str, **kwargs: Any) -> List[Any]:+ async def ainvoke_hook(self, hook_name: str, **kwargs: Any) -> list[Any]:""":meth:`invoke_hook` for callers that are already on an event loop.Same payload narrowing, per-callback isolation and result contract. The difference is@@@ -573,14 -526,10 +573,14 @@@def render_system_prompt_sections(self, session_info: Mapping[str, Any]- ) -> List[RenderedPluginSystemPromptSection]:+ ) -> list[RenderedPluginSystemPromptSection]:"""Render all registered sections deterministically and fail open."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return []frozen_info = types.MappingProxyType(dict(session_info))- rendered: List[RenderedPluginSystemPromptSection] = []+ rendered: list[RenderedPluginSystemPromptSection] = []total_chars = len(PLUGIN_SECTIONS_START) + len(PLUGIN_SECTIONS_END) + 2for _section_id, section in sorted(self._system_prompt_sections.items()):if len(rendered) >= MAX_SYSTEM_PROMPT_SECTIONS:@@@ -654,12 -599,9 +654,12 @@@next callback sees, so rewrites compose, and each callback gets its own copy of the payload andof ``original_<key>`` so an in-place edit cannot leak."""+ from agent.safe_worker_policy import safe_worker_enabledfrom hermes_cli.middleware import _safe_copy+ if safe_worker_enabled():+ return []- results: List[Any] = []+ results: list[Any] = []for cb in self._middleware.get(kind, []):call_kwargs = kwargsif _payload_key:diff --cc hermes_cli/runtime_provider_custom.pyindex 0379268085e,698f0eddafe..07ca2a60538--- a/hermes_cli/runtime_provider_custom.py+++ b/hermes_cli/runtime_provider_custom.py@@@ -188,7 -188,7 +188,7 @@@ def _match_legacy_custom_provider(requereturn None- def _get_named_custom_provider(requested_provider: str, *, config=None) -> Optional[Dict[str, Any]]:-def _get_named_custom_provider(requested_provider: str) -> Optional[dict[str, Any]]:++def _get_named_custom_provider(requested_provider: str, *, config=None) -> Optional[dict[str, Any]]:requested_norm = _normalize_custom_provider_name(requested_provider or "")if not requested_norm or requested_norm == "auto" or _shadowed_by_builtin(requested_norm):return None@@@ -523,7 -521,7 +523,7 @@@ def _opencode_family_for_custom(requestdef _resolve_named_custom_runtime(*, requested_provider: str, explicit_api_key: Optional[str] = None,explicit_base_url: Optional[str] = None,- target_model: Optional[str] = None, config=None) -> Optional[Dict[str, Any]]:- target_model: Optional[str] = None) -> Optional[dict[str, Any]]:++ target_model: Optional[str] = None, config=None) -> Optional[dict[str, Any]]:"""Runtime for a llamacpp alias, a bare-custom direct alias, or a configured custom entry.Aliases resolving to "custom" (ollama, vllm, llamacpp, …) are treated like bare ``custom``. Allamacpp alias with no explicit base_url resolves to the managed server first; an explicitdiff --cc hermes_cli/update_cmd.pyindex 06a274681fa,7413d75b324..a8768a60ef9--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@@ -103,8 -103,8 +103,8 @@@ from hermes_cli.update_cmd_git import_print_parked_branch_kept_notice, _print_parked_branch_skip_warning,_prune_orphan_rescue_refs, _push_synced_fork, _should_skip_upstream_prompt, _sync_fork_with_upstream,_sync_with_upstream_if_needed, UpstreamTargetBroken)- from hermes_cli.update_cmd_maint import ( # noqa: F401+ from hermes_cli.update_cmd_maint import (- _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE, _clear_stale_sqlite_sidecars,+ _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,_checkout_version, _ensure_acp_launcher, _ensure_fhs_path_guard, _finish_dashboard_update_cleanup,_format_time_ago, _post_update_sqlite_runtime_status, _print_bundled_skills_sync_report,_print_curator_first_run_notice, _print_curator_recent_run_notice,diff --cc hermes_cli/web_models.pyindex 07650189686,45a71904042..55ab218e3e5--- a/hermes_cli/web_models.py+++ b/hermes_cli/web_models.py@@@ -262,9 -262,7 +262,9 @@@ class BulkDeleteSessions(BaseModel)profile: Optional[str] = Noneclass SessionImport(BaseModel):+ request_id: Optional[str] = None+ expected_revision: Optional[StrictInt] = Field(None, ge=0)- sessions: List[Dict[str, Any]]+ sessions: list[dict[str, Any]]profile: Optional[str] = Noneclass SessionRename(BaseModel):diff --cc hermes_cli/web_routers/audio.pyindex 849a55ffc81,411fd8cb48a..e085aae09a0--- a/hermes_cli/web_routers/audio.py+++ b/hermes_cli/web_routers/audio.py@@@ -249,7 -246,9 +249,7 @@@ async def get_elevenlabs_voices(profile)try:- def _fetch() -> Dict[str, Any]:- loop = asyncio.get_running_loop()-+ def _fetch() -> dict[str, Any]:with urllib.request.urlopen(request, timeout=10) as response:return _read_dashboard_json_response(response)diff --cc hermes_cli/web_routers/profiles.pyindex 49ddd9f987f,7d3864ac088..de0d9256fba--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@@ -347,7 -352,14 +347,7 @@@ def _profile_state_db(home) -> Pathreturn Path(home) / "state.db"- def _slice_has_rows(slices: Dict[str, Any]) -> bool:-def _profile_heal_exhausted(home) -> bool:- """True when the one-shot writable heal already gave up on this store."""- from hermes_cli.web_server_sessions import _session_db_heal_exhausted-- return str(_profile_state_db(home)) in _session_db_heal_exhausted--+ def _slice_has_rows(slices: dict[str, Any]) -> bool:return any(slices.get(key) for key in ("recents", "cron", "messaging"))diff --cc hermes_cli/web_server.pyindex 928c31330bc,31680606f0a..f30b4a6a756--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@@ -176,7 -176,169 +176,7 @@@ def _start_desktop_cron_ticker(stop_eve_DESKTOP_MCP_DISCOVERY_DELAY_S = 1.0- from hermes_cli.web_server_app import app_lifespan # noqa: E402-@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_lifespandef _app_state_default(app: "FastAPI", name: str, factory):@@@ -201,9 -363,9 +201,9 @@@ def _get_pty_active_session_files(app:return _app_state_default(app, "pty_active_session_files", dict)-app = FastAPI(title="Hermes Agent", version=get_version_info().base_version, lifespan=_lifespan)+app = FastAPI(title="Hermes Agent", version=get_version_info().base_version, lifespan=app_lifespan)- from hermes_cli.dashboard_auth.body_limit import AuthBodyLimitMiddleware # noqa: E402+ from hermes_cli.dashboard_auth.body_limit import AuthBodyLimitMiddleware# Register first (innermost): auth gates run before this, JSON parsing after it.app.add_middleware(AuthBodyLimitMiddleware)diff --cc hermes_state_gateway.pyindex 80c02ae5a56,39e5f1f48f0..b5c35468e3b--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@@ -305,10 -304,10 +305,10 @@@ class SessionGatewayMixinON CONFLICT(scope, session_key) DO UPDATE SETentry_json = excluded.entry_json,updated_at = excluded.updated_at""",- (scope, session_key, entry_json, time.time()),+ (scope, session_key, entry_json, time.time(), entry_json),)- def replace_gateway_routing_entries(self, entries: Dict[str, str], *, scope: str = "") -> None:+ def replace_gateway_routing_entries(self, entries: dict[str, str], *, scope: str = "") -> None:"""Atomically replace the routing index for *scope* (keys absent from *entries*are removed); other scopes untouched."""now = time.time()@@@ -317,12 -316,11 +317,12 @@@if entries:conn.executemany("INSERT INTO gateway_routing (scope, session_key, entry_json, updated_at) "- "VALUES (?, ?, ?, ?)",- [(scope, k, v, now) for k, v in entries.items() if k and v])+ "SELECT ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM state_meta "+ "WHERE key='gateway.retired_session.v1.' || json_extract(?, '$.session_id'))",+ [(scope, k, v, now, v) for k, v in entries.items() if k and v])self._execute_write(_do)- def load_gateway_routing_entries(self, *, scope: str = "") -> Dict[str, str]:+ def load_gateway_routing_entries(self, *, scope: str = "") -> dict[str, str]:"""Load routing entries for *scope* as {session_key: entry_json}."""rows = self._read_all("SELECT session_key, entry_json FROM gateway_routing WHERE scope = ?", (scope,))return {r["session_key"]: r["entry_json"] for r in rows}@@@ -380,24 -378,19 +380,24 @@@return entryreturn None- def _routing_entries_for_sessions(self, session_ids: Set[str]) -> List[Tuple[str, str, str]]:- def _delete_routing_entries_for_sessions(self, session_ids: set[str]) -> int:- """Drop ``gateway_routing`` rows pointing at any of *session_ids*; the target id- lives only inside ``entry_json``, so matching is done in Python over all scopes."""++ def _routing_entries_for_sessions(self, session_ids: set[str]) -> list[tuple[str, str, str]]:+ """``(scope, session_key, session_id)`` of ``gateway_routing`` rows pointing at any of+ *session_ids*; the target id lives only inside ``entry_json``, so matching is in Python."""- found: List[Tuple[str, str, str]] = []++ found: list[tuple[str, str, str]] = []if not session_ids:- return 0- doomed: list[tuple[str, str]] = []+ return foundfor row in self._read_all("SELECT scope, session_key, entry_json FROM gateway_routing"):try:entry = json.loads(row["entry_json"] or "{}")- except Exception:+ except (ValueError, TypeError, RecursionError): # malformed / non-text / over-nested entrycontinueif isinstance(entry, dict) and entry.get("session_id") in session_ids:- doomed.append((row["scope"], row["session_key"]))+ found.append((row["scope"], row["session_key"], entry["session_id"]))+ return found+- def _delete_routing_entries_for_sessions(self, session_ids: Set[str]) -> int:++ def _delete_routing_entries_for_sessions(self, session_ids: set[str]) -> int:+ """Drop ``gateway_routing`` rows pointing at any of *session_ids*."""+ doomed = [(scope, key) for scope, key, _ in self._routing_entries_for_sessions(session_ids)]if not doomed:return 0self._write_sql("DELETE FROM gateway_routing WHERE scope = ? AND session_key = ?", doomed, many=True)@@@ -420,16 -413,10 +420,16 @@@if not candidates:return (0, 0, 0)ids = {str(row["id"]) for row in candidates}- skipped: List[str] = []+ skipped: list[str] = []+ # ``delete_sessions`` retires the deleted rows' routing entries inside its own transaction+ # (``retire_routes``), so count what pointed at the candidates before it commits; the+ # follow-up sweep then only catches entries a concurrent writer re-added.+ routed_before = self._routing_entries_for_sessions(ids)deleted = self.delete_sessions(list(ids), sessions_dir=sessions_dir, exclude_active_write_guards=True, skipped_ids=skipped)- routing_deleted = self._delete_routing_entries_for_sessions(ids - set(skipped))+ kept = set(skipped)+ self._delete_routing_entries_for_sessions(ids - kept)+ routing_deleted = sum(1 for _, _, sid in routed_before if sid not in kept)return (deleted, routing_deleted, len(skipped))def list_gateway_sessions(diff --cc hermes_state_messages.pyindex 57d82c83423,13a2c5f80e2..40f7484e914--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@@ -1018,76 -1012,64 +1017,76 @@@ class SessionMessagesMixinindex the clones naturally), and the originals are archived. NOTE: re-sequencing assigns the tailrows fresh ids; consumers that reference durable row ids re-resolve by content (see 3e8ab0610)."""+ return self._execute_transcript_write(lambda conn: self._archive_and_compact_on_conn(+ conn, session_id, compacted_messages, model_config_patch=model_config_patch,+ watermark=watermark, lock_holder=lock_holder, tail_count=tail_count,+ carried_messages=carried_messages, covered_ids=covered_ids, unresolved_held=unresolved_held), compacted_messages)++ def _archive_and_compact_on_conn(+ self, conn, session_id: str, compacted_messages: List[Dict[str, Any]], *,+ model_config_patch: Optional[Dict[str, Any]] = None, watermark: Optional[int] = None,+ lock_holder: Optional[str] = None, tail_count: int = 0,+ carried_messages: Optional[List[Dict[str, Any]]] = None,+ covered_ids: Optional[List[int]] = None,+ unresolved_held: Optional[List[Dict[str, Any]]] = None) -> int:+ """:meth:`archive_and_compact` on the caller's write transaction (never commits). The owner+ and the worker/canonical-mutation verbs share this one body so they cannot drift."""from hermes_state import SessionCompressionInProgressError- def _do(conn):- if lock_holder is not None:- lock_row = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone()- if lock_row is None or lock_row["holder"] != lock_holder or float(lock_row["expires_at"]) <= time.time():- raise SessionCompressionInProgressError(- f"Compression lease for {session_id!r} lost before commit; refusing to publish a stale compaction")- patch = model_config_patch is not None- # on_missing="raise": never commit against a vanished session row (caller keeps the original).- patched_model_config = self._merge_model_config_json(- conn, session_id, model_config_patch, on_missing="raise") if patch else None- proved = self._proved_coverage(conn, session_id, covered_ids, unresolved_held, watermark)- if proved is not None:- return self._archive_named_rows(- conn, session_id, compacted_messages, proved[0], tail_count=tail_count,- carried_messages=carried_messages, patched_model_config=patched_model_config, patch=patch,- merged_away=proved[1])- tail_ids, tail_tool_calls = ([], 0) if watermark is None else self._tail_rows_after_watermark(- conn, "SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ? ORDER BY id",- (session_id, int(watermark)))- # Rewind targets sit AT/BELOW the watermark (all the compressor saw); unbounded, a- # concurrent append would steal a LIMIT slot.- rewind_ids: list[int] = self._resolve_carried_row_ids(- conn, session_id, carried_messages or [])- if tail_count > 0:- bound = watermark is not None- rewind_ids += [int(row["id"]) for row in conn.execute(- f"SELECT id FROM messages WHERE session_id = ? AND active = 1{' AND id <= ?' if bound else ''} "- "ORDER BY id DESC LIMIT ?",- (session_id, *((int(watermark),) if bound else ()),- int(tail_count) + self._uncounted_merged_rows(compacted_messages[-int(tail_count):]))).fetchall()]- rewind_ids += tail_ids- rewind_ids = list(dict.fromkeys(rewind_ids))- if rewind_ids:- placeholders = _placeholders(rewind_ids)- conn.execute("UPDATE messages SET active = 0, compacted = 0 "- f"WHERE session_id = ? AND id IN ({placeholders})", [session_id, *rewind_ids])- conn.execute(f"{_ARCHIVE_ACTIVE_SQL} AND id NOT IN ({placeholders})", [session_id, *rewind_ids])- else:- conn.execute(_ARCHIVE_ACTIVE_SQL, (session_id,))- # Same identity carry as publish_compression_child (#59661): carried tail copies keep the- # durable row's timestamp so display dedupe still collapses generations. Donors are active-only;- # the rewound/archived originals above never donate, so this is a no-op for a clean compaction.- self._carry_parent_timestamps(conn, session_id, compacted_messages)- inserted, tool_calls_total = self._insert_message_rows(conn, session_id, compacted_messages)- if tail_ids:- self._clone_message_rows(conn, tail_ids)- inserted += len(tail_ids)- tool_calls_total += tail_tool_calls- # A carried copy whose stored identity was computed differently lands in its own- # display_order group and would project twice; re-fold before publishing (#122167).- self._reconcile_display_orders(conn, session_id)- conn.execute(f"{_SET_COUNTERS_SQL}{', model_config = ?' if patch else ''} WHERE id = ?",- (inserted, tool_calls_total, *((patched_model_config,) if patch else ()), session_id))- return inserted- return self._execute_transcript_write(_do, compacted_messages)+ if lock_holder is not None:+ lock_row = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone()+ if lock_row is None or lock_row["holder"] != lock_holder or float(lock_row["expires_at"]) <= time.time():+ raise SessionCompressionInProgressError(+ f"Compression lease for {session_id!r} lost before commit; refusing to publish a stale compaction")+ patch = model_config_patch is not None+ # on_missing="raise": never commit against a vanished session row (caller keeps the original).+ patched_model_config = self._merge_model_config_json(+ conn, session_id, model_config_patch, on_missing="raise") if patch else None+ proved = self._proved_coverage(conn, session_id, covered_ids, unresolved_held, watermark)+ if proved is not None:+ return self._archive_named_rows(+ conn, session_id, compacted_messages, proved[0], tail_count=tail_count,+ carried_messages=carried_messages, patched_model_config=patched_model_config, patch=patch,+ merged_away=proved[1])+ tail_ids, tail_tool_calls = ([], 0) if watermark is None else self._tail_rows_after_watermark(+ conn, "SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ? ORDER BY id",+ (session_id, int(watermark)))+ # Rewind targets sit AT/BELOW the watermark (all the compressor saw); unbounded, a+ # concurrent append would steal a LIMIT slot.+ rewind_ids: list[int] = self._resolve_carried_row_ids(+ conn, session_id, carried_messages or [])+ if tail_count > 0:+ bound = watermark is not None+ rewind_ids += [int(row["id"]) for row in conn.execute(+ f"SELECT id FROM messages WHERE session_id = ? AND active = 1{' AND id <= ?' if bound else ''} "+ "ORDER BY id DESC LIMIT ?",+ (session_id, *((int(watermark),) if bound else ()),+ int(tail_count) + self._uncounted_merged_rows(compacted_messages[-int(tail_count):]))).fetchall()]+ rewind_ids += tail_ids+ rewind_ids = list(dict.fromkeys(rewind_ids))+ if rewind_ids:+ placeholders = _placeholders(rewind_ids)+ conn.execute("UPDATE messages SET active = 0, compacted = 0 "+ f"WHERE session_id = ? AND id IN ({placeholders})", [session_id, *rewind_ids])+ conn.execute(f"{_ARCHIVE_ACTIVE_SQL} AND id NOT IN ({placeholders})", [session_id, *rewind_ids])+ else:+ conn.execute(_ARCHIVE_ACTIVE_SQL, (session_id,))+ # Same identity carry as publish_compression_child (#59661): carried tail copies keep the+ # durable row's timestamp so display dedupe still collapses generations. Donors are active-only;+ # the rewound/archived originals above never donate, so this is a no-op for a clean compaction.+ self._carry_parent_timestamps(conn, session_id, compacted_messages)+ inserted, tool_calls_total = self._insert_message_rows(conn, session_id, compacted_messages)+ if tail_ids:+ self._clone_message_rows(conn, tail_ids)+ inserted += len(tail_ids)+ tool_calls_total += tail_tool_calls+ # A carried copy whose stored identity was computed differently lands in its own+ # display_order group and would project twice; re-fold before publishing (#122167).+ self._reconcile_display_orders(conn, session_id)+ conn.execute(f"{_SET_COUNTERS_SQL}{', model_config = ?' if patch else ''} WHERE id = ?",+ (inserted, tool_calls_total, *((patched_model_config,) if patch else ()), session_id))+ return inserted- def _message_column_names(self, conn) -> List[str]:+ def _message_column_names(self, conn) -> list[str]:"""Column names of the messages table, cached per-connection era."""if not getattr(self, "_message_columns_cache", None):self._message_columns_cache = [r[1] for r in conn.execute("PRAGMA table_info(messages)").fetchall()]diff --cc hermes_state_sessions.pyindex 467ecddf2e5,38cf19de5df..4659c5e84e7--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@@ -217,10 -217,8 +217,10 @@@ def _collect_delegate_child_ids(conn, preturn [sid for sid in found if sid not in seeds]- def _delete_delegate_children(conn, parent_ids: List[str]) -> List[str]:+ def _delete_delegate_children(conn, parent_ids: list[str]) -> list[str]:ids = _collect_delegate_child_ids(conn, parent_ids)+ from hermes_state_mutation_retirement import retire_sessions+ retire_sessions(conn, ids)for chunk in _id_chunks(ids):ph = _session_ids_placeholders(chunk)conn.execute(f"DELETE FROM messages WHERE session_id IN ({ph})", chunk)diff --cc plugins/platforms/a2a/adapter.pyindex 34ad567dff4,6918a44d16f..1f5e2b90b2f--- a/plugins/platforms/a2a/adapter.py+++ b/plugins/platforms/a2a/adapter.py@@@ -268,14 -287,16 +268,14 @@@ class A2AAdapter(BasePlatformAdapter)self._watchdog_stop = threading.Event()# Per-adapter protocol state (not module-global).self.tasks, self._turns, self._rate_limiter = protocol.TaskStore(), protocol.TurnTracker(), protocol.RateLimiter()- # Forwarded profile sessions: (profile, agent_slug, context_id) -> session_id.- self._profile_sessions: dict[tuple[str, str, str], str] = {}- self._profile_session_locks: dict[tuple[str, str, str], threading.Lock] = {}- self._profile_session_locks_guard = threading.Lock()# Pending reply futures: task_id -> (context_id, Future). _pending_order keeps per-context# FIFO so adapter.send() — which only knows the context — resolves the oldest task.- self._pending: Dict[str, tuple[str, Future]] = {}- self._pending_order: Dict[str, deque[str]] = {}+ self._pending: dict[str, tuple[str, Future]] = {}+ self._pending_order: dict[str, deque[str]] = {}# Request ownership outlives reply Futures and also covers synchronous profile forwards.self._active_tasks: set[str] = set()+ # Admission ids this process already forwarded; a resend of one is a retry, not a new turn.+ self._forwarded_inputs: "OrderedDict[str, None]" = OrderedDict()self._pending_lock = threading.Lock()@propertydiff --cc plugins/platforms/slack/adapter.pyindex b12bd4cdd97,59ab1ccea9e..5b96f7b7fb2--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@@ -4732,10 -4732,13 +4732,10 @@@ class SlackAdapter(BasePlatformAdapter)reply_expected=reply_expected,# thread_ts is the thread root, not an explicit reply (root is in channel_context).reply_to_text=None,- auto_skill=resolve_channel_skills(self.config.extra, channel_id, None),- metadata={- "slack_team_id": team_id, "slack_channel_id": channel_id,- "slack_thread_ts": thread_ts})+ auto_skill=resolve_channel_skills(self.config.extra, channel_id, None))def _note_attachment_failure(- self, notices: List[str], detail: Optional[str], fallback_msg: str, *fallback_args: Any,+ self, notices: list[str], detail: Optional[str], fallback_msg: str, *fallback_args: Any,exc_info: bool = False) -> None:"""Record a user-facing attachment diagnostic, else log the raw failure."""if detail:diff --cc scripts/gen_gateway_contracts.pyindex 8e32d496212,30a2aa456a9..5c281a21a77--- a/scripts/gen_gateway_contracts.py+++ b/scripts/gen_gateway_contracts.py@@@ -33,12 -33,12 +33,12 @@@ from tui_gateway.contracts.connectors iConnectorToolFacet,ConnectorToolsSource,)- from tui_gateway.contracts.connectors_operation import ConnectionSettleReason, ConnectionTargetState # noqa: E402- from tui_gateway.contracts.registry import CANONICAL_METHODS, EVENTS, METHODS, SERVER_REQUESTS # noqa: E402- from tools.connectors.contract import SettleReason, TargetState # noqa: E402- from tools.connectors.gateway.wire import ConnectionStatus # noqa: E402- from tools.connectors.portal.tools_cache import ToolsRead # noqa: E402- from tools.connectors.portal.wire import ConnectorTool # noqa: E402+ from tui_gateway.contracts.connectors_operation import ConnectionSettleReason, ConnectionTargetState-from tui_gateway.contracts.registry import EVENTS, METHODS, SERVER_REQUESTS++from tui_gateway.contracts.registry import CANONICAL_METHODS, EVENTS, METHODS, SERVER_REQUESTS+ from tools.connectors.contract import SettleReason, TargetState+ from tools.connectors.gateway.wire import ConnectionStatus+ from tools.connectors.portal.tools_cache import ToolsRead+ from tools.connectors.portal.wire import ConnectorToolTS_OUT = ROOT / "apps" / "shared" / "src" / "gateway-contract.generated.ts"OPENRPC_OUT = ROOT / "apps" / "shared" / "src" / "gateway-contract.openrpc.json"diff --cc tests/cron/test_cron_empty_payload.pyindex 40b3188cfeb,0e9b7593a0c..fa769023a86--- a/tests/cron/test_cron_empty_payload.py+++ b/tests/cron/test_cron_empty_payload.py@@@ -230,9 -230,8 +230,9 @@@ def _legacy_empty_job(hermes_env)save_jobs(jobs)return dict(job, prompt=" ")-def test_run_job_fails_closed_and_never_builds_an_agent(hermes_env):++def test_run_job_fails_closed_and_never_builds_an_agent(hermes_env, cron_owner):- import cron.scheduler as scheduler+ from cron import schedulerjob = _legacy_empty_job(hermes_env)@@@ -249,13 -248,10 +249,13 @@@# Not silent: the user gets told why the job stopped.assert "auto-paused" in final-def test_run_one_job_does_not_resurrect_the_paused_job(hermes_env):++++def test_run_one_job_does_not_resurrect_the_paused_job(hermes_env, cron_owner):"""The real caller runs post-run bookkeeping (mark_job_run) after run_jobreturns. That must not undo the pause, or the job re-fires every tick."""- import cron.scheduler as scheduler+ from cron import schedulerfrom cron.jobs import get_due_jobs, get_jobjob = _legacy_empty_job(hermes_env)diff --cc tests/cron/test_cron_live_bot_delivery.pyindex 4181e3dd912,11023e49249..29e3deb012a--- a/tests/cron/test_cron_live_bot_delivery.py+++ b/tests/cron/test_cron_live_bot_delivery.py@@@ -84,12 -47,12 +84,12 @@@ def test_result_records_pending_until_tmonkeypatch.setenv("HERMES_HOME", str(tmp_path))monkeypatch.delenv("_HERMES_CRON_EXTERNAL_WORKER", raising=False)- owner = dict(profile_home=str(tmp_path.resolve()), session_id="bot", lease_id="lease",- live_session_id="live")- monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: owner)+ monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: _owner(tmp_path))+ authority = _FakeAuthority()+ monkeypatch.setattr(mailbox, "authority_delivery", authority)- monkeypatch.setattr(delivery._sched, "load_config", lambda: {})+ monkeypatch.setattr(delivery._sched, "load_config", dict)monkeypatch.setattr(config, "load_gateway_config", lambda: None)- monkeypatch.setattr(delivery, "_run_bot_chat_turn", Mock(side_effect=AssertionError("CLI")))+ monkeypatch.setattr(subprocess, "run", Mock(side_effect=AssertionError("CLI")))updates = []monkeypatch.setattr(jobs, "update_job", lambda key, values: updates.append(values))job = dict(id="digest", execution_id="run", deliver="bot-chat")diff --cc tests/cron/test_scheduler.pyindex 511ba84c609,b44b4bd3258..eb0eca11585--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@@ -1586,10 -1563,10 +1586,10 @@@ class TestRunJobWakeGateassert final == SILENT_MARKERagent_cls.assert_not_called()- def test_wake_true_runs_agent_with_injected_output(self):+ def test_wake_true_runs_agent_with_injected_output(self, tmp_path):"""When the script returns {wakeAgent: true, data: ...}, the agent isinvoked and the data line still shows up in the prompt."""- import cron.scheduler as scheduler+ from cron import schedulerfrom cron import scheduler_script as sched_scriptscript_output = '{"wakeAgent": true, "data": {"new": 3}}'diff --cc tests/e2e/core/delivery/_cron_clock.pyindex 7a78db26501,73cb953f7b3..d9fc292df4b--- a/tests/e2e/core/delivery/_cron_clock.py+++ b/tests/e2e/core/delivery/_cron_clock.py@@@ -607,48 -589,9 +607,48 @@@ def _replica_main(control: Control) ->_atomic_write(control.replica / f"res-{rnd}.json", json.dumps({"won": won}))-# --- ledger / store readers ------------------------------------------------------------------+# --- gateway drain / ledger / store readers ---------------------------------------------------++def drain_deliveries() -> int:+ """The live gateway's housekeeping drain of the durable delivery queue. No live adapters+ exist in the soak, so every send takes the standalone wire (``FakeSink``). Returns how many+ queued sends were performed."""+ import cron.scheduler as scheduler++ total = 0+ while True:+ n = scheduler.drain_delivery_queue({}, None)+ if not n:+ return total+ total += n+++def delivery_status(home: Path) -> Dict[str, str]:+ """execution id -> durable queue status (``pending``/``delivering``/``delivered``/``failed``/+ ``unknown``/``suppressed``), including tombstoned rows."""+ path = Path(home) / "cron" / "deliveries.db"+ if not path.exists():+ return {}+ conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=30)+ try:+ out = {r[0]: r[1] for r in conn.execute(+ "SELECT execution_id, terminal_status FROM delivery_tombstones")}+ out.update({r[0]: r[1] for r in conn.execute("SELECT execution_id, status FROM deliveries")})+ return out+ finally:+ conn.close()+++def effective_outcome(row: dict, deliveries: Dict[str, str]) -> Optional[str]:+ """The ledger's delivery outcome, resolved through the durable queue when the run only+ booked the handoff (``queued``): the queue's verdict is the delivery's truth."""+ outcome = row["delivery_outcome"]+ if outcome != "queued":+ return outcome+ return deliveries.get(row["id"], "queued")+- def ledger_rows(home: Path, where: str = "") -> List[dict]:+ def ledger_rows(home: Path, where: str = "") -> list[dict]:path = Path(home) / "cron" / "executions.db"if not path.exists():return []diff --cc tests/hermes_cli/test_argparse_flag_propagation.pyindex 94fb5fcc1dc,05d65a1cf23..7706362950e--- a/tests/hermes_cli/test_argparse_flag_propagation.py+++ b/tests/hermes_cli/test_argparse_flag_propagation.py@@@ -40,15 -40,18 +40,15 @@@ class TestChatVerboseArgchat_parser.set_defaults(func=main_mod.cmd_chat)args = parser.parse_args(["chat"])captured = {}- fake_cli = types.ModuleType("cli")-- def fake_main(**kwargs):- captured.update(kwargs)-- fake_cli.main = fake_main+ def launch(args):+ captured.update(vars(args))+ return 0fake_banner = types.ModuleType("hermes_cli.banner")- setattr(fake_banner, "prefetch_update_check", lambda: None)+ fake_banner.prefetch_update_check = lambda: Nonefake_skills_sync = types.ModuleType("tools.skills_sync")- setattr(fake_skills_sync, "sync_skills", lambda quiet=True: None)+ fake_skills_sync.sync_skills = lambda quiet=True: None- monkeypatch.setitem(sys.modules, "cli", fake_cli)+ monkeypatch.setattr("hermes_cli.gateway_chat.launch_from_args", launch)monkeypatch.setitem(sys.modules, "hermes_cli.banner", fake_banner)monkeypatch.setitem(sys.modules, "tools.skills_sync", fake_skills_sync)monkeypatch.setattr(main_mod, "_has_any_provider_configured", lambda: True)diff --cc tests/hermes_cli/test_profile_pm_portability.pyindex 1d01ea1f02e,98af0e9c5ec..be940a34ec4--- a/tests/hermes_cli/test_profile_pm_portability.py+++ b/tests/hermes_cli/test_profile_pm_portability.py@@@ -17,11 -17,10 +17,11 @@@ def transfer_home(tmp_path, monkeypatchfrom hermes_cli import backup, gateway, profiles# Restoring data must not install host services or modify the test user's shell.- monkeypatch.setattr(gateway, "ensure_gateway_service", lambda **kwargs: False)+ from hermes_cli import gateway_setup_service+ monkeypatch.setattr(gateway_setup_service, "ensure_gateway_service", lambda *args, **kwargs: False)monkeypatch.setattr(gateway, "_is_service_running", lambda: False)monkeypatch.setattr(profiles, "check_alias_collision", lambda name: "test has no aliases")- monkeypatch.setattr(backup, "_collect_memory_provider_external_paths", lambda: [])+ monkeypatch.setattr(backup, "_collect_memory_provider_external_paths", list)return homediff --cc tests/hermes_cli/test_status.pyindex 432d6f97b52,6d7861546df..da252cf8f30--- a/tests/hermes_cli/test_status.py+++ b/tests/hermes_cli/test_status.py@@@ -199,26 -199,26 +199,26 @@@ def test_show_status_reports_gateway_semonkeypatch.setattr(status_mod, "resolve_requested_provider", lambda requested=None: "openai-codex", raising=False)monkeypatch.setattr(status_mod, "resolve_provider", lambda requested=None, **kwargs: "openai-codex", raising=False)monkeypatch.setattr(status_mod, "provider_label", lambda provider: "OpenAI Codex", raising=False)- monkeypatch.setattr(auth_mod, "get_nous_auth_status", lambda: {}, raising=False)- monkeypatch.setattr(auth_mod, "get_codex_auth_status", lambda: {}, raising=False)- monkeypatch.setattr(auth_mod, "get_qwen_auth_status", lambda: {}, raising=False)- monkeypatch.setattr(auth_mod, "get_xai_oauth_auth_status", lambda: {}, raising=False)+ monkeypatch.setattr(auth_mod, "get_nous_auth_status", dict, raising=False)+ monkeypatch.setattr(auth_mod, "get_codex_auth_status", dict, raising=False)+ monkeypatch.setattr(auth_mod, "get_qwen_auth_status", dict, raising=False)+ monkeypatch.setattr(auth_mod, "get_xai_oauth_auth_status", dict, raising=False)monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda exclude_pids=None: [], raising=False)- class _FakeDB:- def __init__(self, **_kwargs):- pass-- def list_gateway_sessions(self, active_only=True):- return [- {"id": "gw-old", "last_active": time.time() - 7200},- {"id": "gw-new", "last_active": time.time() - 90},- ]-- def close(self):- return None-- monkeypatch.setattr(hermes_state, "SessionDB", _FakeDB)+ import sqlite3+ from contextlib import closing++ path = tmp_path / "state.db"+ db = hermes_state.SessionDB(db_path=path)+ for sid in ("gw-old", "gw-new"):+ db.create_session(sid, "telegram")+ db.close()+ with closing(sqlite3.connect(path)) as conn:+ for sid, age in (("gw-old", 7200), ("gw-new", 90)):+ conn.execute("UPDATE sessions SET session_key=?, started_at=?, last_activity_at=? WHERE id=?",+ (sid, time.time() - age, time.time() - age, sid))+ conn.commit()+ before = path.read_bytes()status_mod.show_status(SimpleNamespace(full=True, deep=False))output = capsys.readouterr().outdiff --cc tools/async_delegation.pyindex 3ba87095961,b2273f9c7af..7c5be175407--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@@ -154,9 -150,7 +154,9 @@@ def _capture_routing_origin() -> dict[sreturn {}- def _persist_dispatch(record: Dict[str, Any]) -> None:+ def _persist_dispatch(record: dict[str, Any]) -> None:+ if remote := worker_ledger():+ return remote.dispatch(record)now = time.time()try:from gateway.status import get_process_start_time@@@ -210,9 -203,7 +210,9 @@@ def _prune_durable_records() -> None)""", (pending_count - _MAX_DURABLE_PENDING,))- def _persist_completion(event: Dict[str, Any], result: Dict[str, Any]) -> None:+ def _persist_completion(event: dict[str, Any], result: dict[str, Any]) -> None:+ if remote := worker_ledger():+ return remote.complete(event, result)now = time.time()with _DB_LOCK, _transaction() as conn:conn.execute("""UPDATE async_delegations SET state=?, completed_at=?, updated_at=?,@@@ -584,9 -551,7 +584,9 @@@ def _event_delivery(fn, evt: dict[str,fn(str(evt.get("delegation_id") or ""), claim_id)- def get_durable_delegation(delegation_id: str) -> Optional[Dict[str, Any]]:+ def get_durable_delegation(delegation_id: str) -> Optional[dict[str, Any]]:+ if remote := worker_ledger():+ return remote.read(delegation_id)with _DB_LOCK, _transaction() as conn:row = conn.execute("""SELECT origin_session, state, dispatched_at, completed_at,result_json, delivery_state, delivery_attempts,diff --cc tools/mcp_tool_config.pyindex b44d8aa2051,2d1434cd6b8..8212cc94f6b--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@@ -538,11 -538,8 +538,11 @@@ def _portable_mcp_servers(safe_serverslogger.debug("Failed to load portable MCP servers", exc_info=True)- def _load_mcp_config() -> Dict[str, dict]:+ def _load_mcp_config() -> dict[str, dict]:"""``mcp_servers`` from config.yaml as ``{name: config}`` (empty on error / safe mode), ``${VAR}`` interpolated."""+ from agent.safe_worker_policy import safe_worker_enabled+ if safe_worker_enabled():+ return {}try:from hermes_cli.config import load_configfrom utils import env_var_enabled as _env_enableddiff --cc tools/mcp_tool_discovery.pyindex e375039bb76,e4bb702e07f..9bb695a4bd7--- a/tools/mcp_tool_discovery.py+++ b/tools/mcp_tool_discovery.py@@@ -532,14 -532,9 +532,14 @@@ def _log_summary(prefix: str, names, **logger.info(summary)- def register_mcp_servers(servers: Dict[str, dict]) -> List[str]:+ def register_mcp_servers(servers: dict[str, dict]) -> list[str]:"""Connect ``{name: config}`` servers and register their tools; idempotent for connectednames, ``enabled: false`` skipped without disconnecting. Returns every MCP tool name."""+ from agent.safe_worker_policy import safe_worker_enabled+ if safe_worker_enabled():+ # A troubleshooting worker never spawns MCP processes; nor may it borrow tools+ # another caller already connected in this process.+ return []if not _core._ensure_mcp_sdk():logger.debug("MCP SDK not available -- skipping explicit MCP registration")return []diff --cc tools/process_registry.pyindex c4d91ee0b17,841f50b2aaf..31ea2ca63e0--- a/tools/process_registry.py+++ b/tools/process_registry.py@@@ -691,13 -718,11 +691,13 @@@ class ProcessRegistry(ProcessTerminatio# process_loop and the gateway drain it after each agent turn to trigger new turns.import queue as _queue_modself.completion_queue: _queue_mod.Queue = _queue_mod.Queue()- # Durable delegation completions are rehydrated by restore_completions(), NOT here: the- # module-level singleton runs __init__ on `import model_tools`, and the replay opens- # (creates, migrates) the launch profile's state.db (#123265). Importing the module is+ # Durable delegation completions are NOT rehydrated here: this constructor runs at+ # import time in every process that touches the tools graph (cron clients, `hermes+ # sessions list`, workers), and restoring means writing the canonical ledger. The+ # owner replays them explicitly (GatewayRunner._start_recover_previous_run) and the+ # first consumer through restore_completions() (#123265). Importing the module is# side-effect free and keeps its import-order contract for later completion writers.- import tools.async_delegation # noqa: F401+ import tools.async_delegation# Completions the agent already consumed via wait()/read_log() (output in# hand): drain loops AND gateway/tui watchers skip them.self._completion_consumed: set = set()diff --cc tools/registry.pyindex 62dd9f1fc1b,1971910612f..4d57eafb34d--- a/tools/registry.py+++ b/tools/registry.py@@@ -123,20 -98,11 +123,20 @@@ def discover_builtin_tools(tools_dir: Oper-file AST scan costs ~145 ms over ~100 files, so verdicts are memoized on disk keyedby ``(mtime_ns, size)``; a mismatch or corrupt cache re-scans that file. The write isbest-effort and atomic, so concurrent processes race harmlessly."""+ from agent.safe_worker_policy import safe_worker_enabled+ if safe_worker_enabled():+ # Toolset filtering happens AFTER import. Keep the troubleshooting worker's+ # import graph closed over reviewed core tools, not plugin-backed wrappers+ # or a profile-writable discovery cache. Core approval/redaction stay intact.+ module_names = ["tools.file_tools", "tools.terminal_tool", "tools.process_registry"]+ for module_name in module_names:+ importlib.import_module(module_name)+ return module_namestools_path = (Path(tools_dir) if tools_dir is not None else Path(__file__).resolve().parent).resolve()cache = _load_discovery_cache()- fresh_cache: Dict[str, list] = {}+ fresh_cache: dict[str, list] = {}cache_dirty = False- module_names: List[str] = []+ module_names: list[str] = []for path in _tool_module_candidates(tools_path):if path.name in {"__init__.py", "registry.py", "mcp_tool.py"}:continue@@@ -502,14 -468,11 +502,14 @@@ class ToolRegistryself._toolset_aliases = {alias: target for alias, target in self._toolset_aliases.items() if target != toolset}- def _merged_tools(self, scope: Optional[str] = None) -> Dict[str, ToolEntry]:+ def _merged_tools(self, scope: Optional[str] = None) -> dict[str, ToolEntry]:"""Return global tools overlaid with one profile's plugin tools."""- return {**self._tools, **self._scoped_tools.get(hermes_home_key(scope), {})}+ entries = {**self._tools, **self._scoped_tools.get(hermes_home_key(scope), {})}+ if scope is None:+ entries.update(self._scoped_tools.get(_session_slot_key(), {}))+ return entries- def _toolset_entries(self, toolset: str, scope: Optional[str]) -> List[ToolEntry]:+ def _toolset_entries(self, toolset: str, scope: Optional[str]) -> list[ToolEntry]:return self._grouped(self._merged_tools(scope).values()).get(toolset, [])def _snapshot_state(diff --cc tools/session_search_tool.pyindex aa4c709b9a9,a85dfe2cb5d..3b275bb58a9--- a/tools/session_search_tool.py+++ b/tools/session_search_tool.py@@@ -601,36 -619,14 +601,36 @@@ def _dispatch(query, role_filter, limitdef session_search(query: str = "", role_filter: str = None, limit: int = 3, db=None,current_session_id: str = None, session_id: str = None, around_message_id: int = None,window: int = 5, sort: str = None, profile: str = None, detail: str = "adaptive",- after: str = None, before: str = None, exclude_session_ids: Optional[List[str]] = None) -> str:+ after: str = None, before: str = None, exclude_session_ids: Optional[list[str]] = None) -> str:"""Run session search, closing DBs opened here. Positional order is frozen for old callers;new parameters are appended after ``detail``."""- from hermes_state import format_session_db_unavailable- from hermes_state_registry import acquire, release_or_close+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB, format_session_db_unavailable+ from hermes_state_registry import release_or_close- owned_dbs: List[Any] = []+ owned_dbs: list[Any] = []+ # A raw `@session:<profile>/<id>` link as session_id: ids never contain "/", so+ # split on it and adopt the embedded profile only when none was passed.+ if isinstance(session_id, str) and "/" in session_id:+ emb_profile, _, emb_id = session_id.partition("/")+ if emb_id:+ session_id = emb_id+ if emb_profile and (profile is None or not str(profile).strip()):+ profile = emb_profile+ # Cross-profile: swap in the named profile's DB (read-only) for every shape;+ # current-lineage guards key off ids that won't collide, so they stay inert.+ try:+ profile_db = _resolve_profile_db(profile)+ except Exception as e:+ logging.debug("session_search: cannot open profile %r", profile, exc_info=True)+ return tool_error(f"profile '{profile}': {e}", success=False)+ if profile_db is not None:+ db, current_session_id = profile_db, None+ owned_dbs.append(profile_db)if db is None:- db = _quiet(acquire, None, "SessionDB unavailable for session_search")+ db = _quiet(+ lambda: SessionDB(db_path=get_hermes_home() / "state.db", read_only=True),+ None, "SessionDB unavailable for session_search",+ )if db is None:return tool_error(format_session_db_unavailable(), success=False)owned_dbs.append(db)diff --cc tools/skills_tool.pyindex 8be98e1b949,445c98f56b8..4409bb32af9--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@@ -93,14 -93,9 +93,14 @@@ def _skill_lookup_path_error(name: strreturn None- def load_env() -> Dict[str, str]:+ def load_env() -> dict[str, str]:"""Snapshot of HERMES_HOME/.env for the post-skill secret-capture diff (same tokenizer that- installs the profile scope, so a captured value never differs from the served one)."""+ installs the profile scope, so a captured value never differs from the served one). A frozen-policy+ worker never opens the profile ``.env``: ``hermes_cli.config.load_env`` owns that short-circuit."""+ from agent.safe_worker_policy import worker_config_snapshot++ if worker_config_snapshot() is not None:+ return {}from agent.secret_scope import load_env_filereturn load_env_file(get_hermes_home() / ".env")diff --cc tools/terminal_scope.pyindex 48bd15375fe,9b80ac3bdde..79758df1bd2--- a/tools/terminal_scope.py+++ b/tools/terminal_scope.py@@@ -86,33 -86,8 +86,33 @@@ def terminal_env(name: str, default: streturn default if value is None else str(value)- def _apply_terminal_mapping(scope: Dict[str, str], mapping: Dict[str, Any]) -> None:++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]:++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] = {}++ 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*diff --cc tui_gateway/server.pyindex 5e6153e3756,84c15554c4c..cb0a4117f33--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@@ -2141,10 -3652,7 +2141,10 @@@ from .mcp_rpc_helpers import summarize_# ── Split @method handler modules (see method_ctx.py): imported last so every global the handlers close# over exists; register() rebinds them onto this namespace.- from hermes_state import _BARE_BILLING_PROVIDERS # noqa: E402, F401++from hermes_state import _BARE_BILLING_PROVIDERS+- from . import ( # noqa: E402+ from . import (+ session_registry as _session_registry, agent_factory as _agent_factory,methods_voice as _methods_voice, methods_browser as _methods_browser, methods_slash as _methods_slash,methods_complete_helpers as _methods_complete_helpers, session_auto_continue as _session_auto_continue,plugin_inject as _plugin_inject,diff --cc tui_gateway/session_notifications.pyindex dc55f8a71fb,86634f45f28..588a3d8ed28--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@@ -658,9 -727,9 +658,9 @@@ def _notification_poller_scoped_loop(stprocess_registry.restore_completions() # first consumer in a TUI process (#123265)queue = process_registry.completion_queueemitted = session.setdefault("_notification_emitted", set())- handle = lambda events, deferred: _notif_handle_ready( # noqa: E731+ handle = lambda events, deferred: _notif_handle_ready(sid, session, events, emitted, process_registry, format_process_notification, deferred)- last_kanban_poll = last_loop_poll = last_bot_poll = 0.0+ last_kanban_poll = last_loop_poll = 0.0while not stop_event.is_set() and not session.get("_finalized"):now = time.monotonic()# Completions whose owner process died after this one started (#97202); throttled per profile home.