The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
teknium1d7f5c13d7378
diff --cc gateway/platforms/api_server.pyindex 81340a5b9b4,b7b26d27303..f6ecfe7869b--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@@ -4017,11 -4012,13 +4049,14 @@@ class APIServerAdapter(OpenAICompatRoutroute: 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,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) -> tuple:+ 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)``.+ ``approval_notify_callback`` (with ``approval_session_key``) routes dangerous-command+ approval requests to the caller's stream, keyed like ``/v1/runs`` approvals (#51871).``agent_ref[0]`` receives the agent so SSE writers can interrupt it; ``active_run_id``registers it in ``_active_run_agents``. Under a confirmed model lock the actualprovider/model must match or the turn fails; ``runtime`` metadata is attached.diff --cc hermes_cli/web_server_app.pyindex 07a3795318d,00000000000..c02ed90f94dmode 100644,000000..100644--- a/hermes_cli/web_server_app.py+++ b/hermes_cli/web_server_app.py@@@ -1,190 -1,0 +1,199 @@@+"""HTTP lifespan composition; standalone backend services remain opt-in owners."""++from contextlib import asynccontextmanager+import asyncio+import logging+import os+import threading++from fastapi import FastAPI+from hermes_cli.pty_session import run_reaper++_log = logging.getLogger("hermes_cli.web_server")+++@asynccontextmanager+async def standalone_lifespan(app: "FastAPI"):+ from hermes_cli.web_server import (+ _eager_reconcile_own_session_db, _warm_gateway_module,+ _start_desktop_cron_ticker, _dashboard_selftest_loop,+ _auto_archive_ticker_loop, _terminate_desktop_managed_gateway,+ )+ from hermes_cli.web_server_chat import PTY_REGISTRY++ 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 until its owner completes schema reconciliation.+ # 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 # noqa: F401+++ 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.+ from hermes_cli.process_identity import is_desktop_owned_backend+ 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).+ try:+ from hermes_cli.gateway import _reap_unsupervised_gateway_orphans++ _reap_unsupervised_gateway_orphans()+ 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: # noqa: BLE001+ logging.getLogger(__name__).warning("local runtime boot failed: %s", exc)++ threading.Thread(target=_boot_local_runtime, daemon=True, name="local-runtime-boot").start()++ 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()+ eager_reconcile_thread.join()+ await PTY_REGISTRY.close_all()+ # 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: # noqa: BLE001+ pass+ if desktop_owned:+ _terminate_desktop_managed_gateway()+++@asynccontextmanager+async def http_lifespan(app: FastAPI):+ """The gateway already owns schema, rooms, scheduler and model services."""+ from hermes_cli.web_server import _dashboard_selftest_loop+ from hermes_cli.web_server_chat import PTY_REGISTRY++ app.state.event_channels = {}+ app.state.event_lock = asyncio.Lock()+ app.state.pty_active_session_files = {}+ app.state.chat_argv_lock = asyncio.Lock()+ tasks = [+ asyncio.create_task(run_reaper(PTY_REGISTRY), name="gateway-api-pty-reaper"),+ asyncio.create_task(_dashboard_selftest_loop(), name="gateway-api-selftest"),+ ]+ try:+ yield+ finally:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ await PTY_REGISTRY.close_all()+++@asynccontextmanager+async def app_lifespan(app: FastAPI):+ lifespan = http_lifespan if getattr(app.state, "gateway_runner", None) is not None else standalone_lifespan+ async with lifespan(app):+ yielddiff --cc tui_gateway/server.pyindex dc94f62b3f7,169b523e950..93e45b18bba--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@@ -1968,12 -3361,10 +1971,13 @@@ 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 . import ( # noqa: E402+ 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,rpc_dispatch as _rpc_dispatch,agent_callbacks as _agent_callbacks, session_history as _session_history,prompt_attachments as _prompt_attachments, session_notifications as _session_notifications,@@@ -1995,10 -3386,9 +1999,10 @@@methods_onboarding as _methods_onboarding)for _m in (+ _session_registry, _agent_factory,_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,_session_compression, _change_watcher, _tool_progress, _session_notifications,- _prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue, _rpc_dispatch,+ _prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue, _plugin_inject, _rpc_dispatch,_methods_complete_helpers, _methods_slash, _methods_voice, _methods_browser,_methods_browser_control, _methods_session, _methods_prompt, _methods_config,_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,