Skip to content

The agent that grows with you

Merge commit '09fbc27a4a93' into fix/106742-thread-resolution

teknium1b0aa41586e2f
diff --cc agent/agent_init.py
index d6f41877b68,918b9fe2313..cb47c7a841b
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@@ -2354,15 -2350,8 +2359,15 @@@ def init_agent
checkpoint_max_snapshots: int = 20, checkpoint_max_total_size_mb: int = 500,
checkpoint_max_file_size_mb: int = 10, pass_session_id: bool = False,
requested_provider: str = None, capabilities: Optional[Dict[str, bool]] = None, cwd: Optional[str] = None,
- side_agent: bool = False,
+ side_agent: bool = False, memory_manager=None,
):
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ skip_context_files = skip_memory = skip_background_review = True
+ load_soul_identity = False
+ prefill_messages = []
+ fallback_model = {}
_install_safe_stdio()
_params = locals()
diff --cc apps/desktop/electron/quit-guard.test.ts
index b3459e39d43,fdef3c5b051..ddedc3f4dcc
--- a/apps/desktop/electron/quit-guard.test.ts
+++ b/apps/desktop/electron/quit-guard.test.ts
@@@ -55,24 -50,3 +53,17 @@@ test('quitPromptFor summarizes past th
assert.ok(!prompt.detail.includes('• e'))
assert.ok(prompt.detail.includes('• 5 more'))
})
+
- test('quitPromptFor speaks singular for one chat', () => {
- const prompt = quitPromptFor({ count: 1, titles: [] }, false)
-
- assert.ok(prompt)
- assert.equal(prompt.message, 'Hermes is still working on 1 chat.')
- })
-
+test('active-work reports with unknown lifecycle keep a scoped confirmation, not a work-loss claim', () => {
+ // The real IPC summary has no connection identity or Desktop-tool activity.
+ // Neither named nor untitled work proves it is independent of the client.
+ for (const titles of [[], ['Fix login']]) {
+ const work = mergeActiveWork([normalizeActiveWork({ count: 1, titles })])
+ const prompt = quitPromptFor(work, false)
+
+ assert.ok(prompt)
+ assert.match(prompt.detail, /[Rr]unning and queued work on a persistent gateway continues after Desktop quits/)
+ assert.match(prompt.detail, /[Aa]ctivity that depends on this app or an older connection may be interrupted/)
+ assert.doesNotMatch(prompt.detail, /work.*(?:lost|stops)|stops the agent|all work continues/i)
+ }
+})
diff --cc apps/desktop/src/app/chat/composer/controls.test.tsx
index a01686960e1,ac96d645c42..b141eb737d3
--- a/apps/desktop/src/app/chat/composer/controls.test.tsx
+++ b/apps/desktop/src/app/chat/composer/controls.test.tsx
@@@ -140,29 -140,11 +140,11 @@@ describe('narrow tiles', () =>
})
})
- // The controls row groups contributed actions with the send cluster in one
- // right-aligned sub-group — the row owns the ml-auto margin. If the cluster kept
- // its own auto margin, it would pin itself right and orphan a contributed
- // action at the row start when the row stacks (#116332).
- describe('contributed-actions grouping', () => {
- it('leaves right-alignment to the controls row instead of pushing itself with ml-auto', () => {
- const { container } = renderControls()
-
- expect(container.firstElementChild?.classList.contains('ml-auto')).toBe(false)
- })
- })
-
describe('ComposerControls shortcut tooltips', () => {
- it('shows Enter for Send', async () => {
- renderControls()
-
- await expectShortcutTooltip('Send', '↵')
- })
-
- it('keeps Send (not Steer) while a turn is running if there is a payload', async () => {
+ it('labels busy Send with the effective configured action', async () => {
renderControls({ busy: true, busyAction: 'steer' })
- await expectShortcutTooltip('Send', '↵')
+ await expectShortcutTooltip('Steer the current run', '↵')
})
it('shows Stop only when the composer is empty mid-turn', async () => {
diff --cc apps/desktop/src/components/notifications.test.tsx
index 277f2033b02,fc240ba0dcc..23f07b1fd99
--- a/apps/desktop/src/components/notifications.test.tsx
+++ b/apps/desktop/src/components/notifications.test.tsx
@@@ -1,14 -1,12 +1,10 @@@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'
--import { I18nProvider } from '@/i18n'
-import { $notifications, clearNotifications, notify, notifyError } from '@/store/notifications'
-import { $poolLimitsSettingsRequest } from '@/store/pool-limits'
+import { clearNotifications, notify } from '@/store/notifications'
import { stubResizeObserver } from '@/test/jsdom'
- import { NotificationStack, toastTitleClassName } from './notifications'
-
- const LONG_TITLE = 'This turn is no longer in server history (it may have been compressed away).'
- const DETAIL = 'target user message is no longer in session history'
+ import { NotificationStack } from './notifications'
beforeAll(stubResizeObserver)
@@@ -20,18 -19,9 +16,8 @@@ describe('toast titles', () =>
afterEach(() => {
cleanup()
clearNotifications()
- $poolLimitsSettingsRequest.set(0)
})
- it('drops the one-line clamp so a long error title can wrap', () => {
- const className = toastTitleClassName()
-
- expect(className).toMatch(/\bline-clamp-none\b/)
- expect(className).not.toMatch(/\bline-clamp-1\b/)
- expect(className).toMatch(/\bwhitespace-normal\b/)
- expect(className).toContain('max-h-[4.5em]')
- expect(className).toMatch(/\boverflow-y-auto\b/)
- })
-
it.each(['default', 'bottom-right'] as const)(
'caps the %s toast stack at one back edge and keeps older notifications reachable',
async placement => {
@@@ -49,23 -39,38 +35,4 @@@
await waitFor(() => expect(screen.queryByText('Notice 6')).toBeNull())
}
)
--
- it('renders the full title and body instead of truncating them', () => {
- notify({ kind: 'error', title: LONG_TITLE, message: DETAIL })
- it('makes a local pool-slot timeout actionable without changing ordinary errors', () => {
- notifyError(
- new Error(
- `Error invoking remote method 'hermes:connection': Error: Local backend start for "research" timed out while waiting for a free slot.`
- ),
- 'Failed to switch to profile "research"'
- )
--
-- render(
-- <I18nProvider configClient={null} initialLocale="en">
-- <NotificationStack />
-- </I18nProvider>
-- )
--
- const title = screen.getByText(LONG_TITLE)
- expect(screen.getByText(/Too many bots are running at once/)).toBeTruthy()
--
- expect(title.textContent).toBe(LONG_TITLE)
- expect(title.getAttribute('title')).toBe(LONG_TITLE)
- expect(title.className).toMatch(/\bline-clamp-none\b/)
- expect(title.className).not.toMatch(/\bline-clamp-1\b/)
- expect(title.className).toMatch(/\boverflow-y-auto\b/)
- expect(screen.getByText(DETAIL)).toBeTruthy()
- fireEvent.click(screen.getByRole('button', { name: 'Open Advanced Settings' }))
-
- expect($poolLimitsSettingsRequest.get()).toBe(1)
- expect($notifications.get()).toHaveLength(0)
-
- notifyError(new Error('gateway unavailable'), 'Failed to switch profile')
- expect($notifications.get()[0]?.action).toBeUndefined()
- })
-
- it('keeps background pool-slot timeouts quiet if they reach the renderer', () => {
- notifyError(
- new Error('Local backend start for "background" timed out while waiting for a free slot. (background)'),
- 'Background profile warm-up failed'
- )
-
- expect($notifications.get()[0]?.action).toBeUndefined()
-- })
})
diff --cc gateway/run_bootstrap.py
index fa4be0780ab,00000000000..ecb309fc448
mode 100644,000000..100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@@ -1,750 -1,0 +1,761 @@@
+"""Process startup phases; diagnostics remain in the gateway facade."""
+from __future__ import annotations
+
+import threading
+from typing import Any, Optional
+
+from gateway.config import GatewayConfig
+
+async def _start_gateway_replace_existing_instance(existing_pid: int, replace: bool) -> bool:
+ """Handle a live gateway PID under this HERMES_HOME: replace it (``--replace``) or refuse.
+ Returns False when startup must abort (refused, permission denied, target still alive)."""
+ from gateway.run import (_clear_takeover_marker_quiet, _replace_target_belongs_to_other_profile, _wait_for_pid_exit, get_hermes_home, logger, suppress)
+ from gateway.status import get_process_start_time, remove_pid_file, terminate_pid
+ if not replace:
+ hermes_home = str(get_hermes_home())
+ logger.error(
+ "Another gateway instance is already running (PID %d, HERMES_HOME=%s) and did not "
+ "publish a host record this process could attach to.",
+ existing_pid, hermes_home)
+ print(
+ f"\n❌ A gateway already owns this host (PID {existing_pid}).\n"
+ f" One gateway per host serves every profile, so there is nothing to start here.\n"
+ f" Attach is impossible: PID {existing_pid} published no usable host record\n"
+ f" (an older build, or an unwritable lock directory).\n"
+ f" Take the host over: hermes gateway run --replace\n"
+ f" Or stop it first: hermes gateway stop\n")
+ return False
+
+ # Never signal a process not provably ours (a poisoned PID record → cross-profile restart loop).
+ if _replace_target_belongs_to_other_profile(existing_pid):
+ from gateway.status import _get_process_hermes_home
+ logger.error(
+ "Refusing --replace: PID %d cannot be proven to belong "
+ "to this profile's gateway (HERMES_HOME %s). Remove the "
+ "stale PID record or stop the owning profile explicitly.",
+ existing_pid, _get_process_hermes_home())
+ return False
+ existing_start_time = get_process_start_time(existing_pid)
+ logger.info("Replacing existing gateway instance (PID %d) with --replace.", existing_pid)
+ # Takeover marker: target exits 0 on our SIGTERM (exit 1 → systemd Restart=on-failure flap loop).
+ try:
+ from gateway.status import write_takeover_marker
+ write_takeover_marker(existing_pid)
+ except Exception as e:
+ logger.debug("Could not write takeover marker: %s", e)
+ # Snapshot children BEFORE signalling: reparented orphans are invisible yet hold scoped token locks.
+ try:
+ from gateway.status import _snapshot_gateway_children
+ _old_gateway_children = _snapshot_gateway_children(existing_pid)
+ except Exception:
+ _old_gateway_children = []
+ try:
+ terminate_pid(existing_pid, force=False)
+ except ProcessLookupError:
+ pass # Already gone
+ except (PermissionError, OSError):
+ logger.error("Permission denied killing PID %d. Cannot replace.", existing_pid)
+ _clear_takeover_marker_quiet()
+ return False
+ # Up to 10s for SIGTERM, then SIGKILL.
+ if not await _wait_for_pid_exit(existing_pid, 20, 0.5):
+ logger.warning("Old gateway (PID %d) did not exit after SIGTERM, sending SIGKILL.", existing_pid)
+ old_gateway_exited = False
+ try:
+ terminate_pid(existing_pid, force=True, expected_start_time=existing_start_time)
+ except ProcessLookupError:
+ old_gateway_exited = True
+ except (PermissionError, OSError):
+ pass
+ # Confirm SIGKILL took (D-state/zombie) before clearing PID/locks, or two gateways share a token.
+ if not old_gateway_exited and not await _wait_for_pid_exit(existing_pid, 20, 0.25):
+ logger.error(
+ "Old gateway (PID %d) still appears alive after SIGKILL; "
+ "aborting replacement to avoid a duplicate gateway.", existing_pid)
+ _clear_takeover_marker_quiet()
+ return False
+ # Reap orphaned children (POSIX; mirrors Windows taskkill /T) so they stop holding scoped token locks.
+ try:
+ from gateway.status import reap_gateway_children
+ reap_gateway_children(_old_gateway_children, parent_pid=existing_pid)
+ except Exception:
+ logger.debug("Child reap for replaced gateway PID %d failed", existing_pid, exc_info=True)
+ remove_pid_file()
+ # remove_pid_file() is a no-op when the PID doesn't match; force-unlink covers a crashed old process.
+ with suppress(Exception):
+ (get_hermes_home() / "gateway.pid").unlink(missing_ok=True)
+ # The old process may not have consumed the marker (SIGKILL'd before its handler read it).
+ _clear_takeover_marker_quiet()
+ # Stopped (Ctrl+Z) processes don't release scoped locks on exit; stale lock files block the new gateway.
+ try:
+ from gateway.status import release_all_scoped_locks
+ _released = release_all_scoped_locks(owner_pid=existing_pid, owner_start_time=existing_start_time)
+ if _released:
+ logger.info("Released %d stale scoped lock(s) from old gateway.", _released)
+ except Exception:
+ pass
+ return True
+
+
+def _start_gateway_configure_logging(verbosity: Optional[int]) -> None:
+ """Sync bundled skills, set up file logging + startup security audit, and the -v/-q stderr handler."""
+ from gateway.run import (_best_effort, _gateway_stderr_formatter, _hermes_home, logging)
+ def _sync_skills() -> None:
+ from tools.skills_sync import sync_skills
+ sync_skills(quiet=True)
+
+ _best_effort(_sync_skills)
+
+ # Centralized logging (agent.log INFO+, errors.log WARNING+, gateway.log gateway-only); idempotent.
+ from hermes_logging import setup_logging, _safe_stderr
+ setup_logging(hermes_home=_hermes_home, mode="gateway")
+
+ def _security_audit() -> None:
+ # Warn-on-load, never blocks: surfaces root / weak-SSH / unauthenticated-listener exposure.
+ from hermes_cli.security_audit_startup import log_startup_security_warnings
+
+ def _raw_cfg():
+ from hermes_cli.config import read_raw_config
+ return read_raw_config()
+
+ log_startup_security_warnings(hermes_home=_hermes_home, config=_best_effort(_raw_cfg))
+
+ _best_effort(_security_audit, "Startup security audit failed (non-fatal): %s")
+
+ # Optional stderr handler from -v/-q: None (quiet) = none; 0 = WARNING; 1 = INFO; 2+ = DEBUG.
+ if verbosity is not None:
+ _stderr_level = {0: logging.WARNING, 1: logging.INFO}.get(verbosity, logging.DEBUG)
+ _stderr_handler = logging.StreamHandler(_safe_stderr())
+ _stderr_handler.setLevel(_stderr_level)
+ _stderr_handler.setFormatter(_gateway_stderr_formatter())
+ root = logging.getLogger()
+ root.addHandler(_stderr_handler)
+ if _stderr_level < root.level: # so DEBUG records can reach the handler
+ root.setLevel(_stderr_level)
+
+
+def _start_gateway_make_shutdown_signal_handler(runner, _signal_initiated_shutdown: list):
+ """Build the SIGINT/SIGTERM handler; ``_signal_initiated_shutdown[0]`` records an unplanned signal."""
+ from gateway.run import (_best_effort, _hermes_home, asyncio, logger, signal)
++ planned_stop_seen = [False]
++
+ def shutdown_signal_handler(received_signal=None):
+ # Planned --replace takeover (sibling marked this PID): exit 0 so systemd won't revive us.
+ def _takeover() -> bool:
+ from gateway.status import consume_takeover_marker_for_self
+ return consume_takeover_marker_for_self()
+
+ # Planned stop: CLI marks first, else its SIGTERM looks like an external kill. SIGINT = Ctrl+C.
+ def _planned_stop() -> bool:
+ from gateway.status import consume_planned_stop_marker_for_self
+ return consume_planned_stop_marker_for_self()
+
+ # Fast (<10ms) sync snapshot: stdlib + /proc, no subprocesses (`ps aux` here once blocked ~3s).
+ def _snapshot():
+ from gateway.shutdown_forensics import snapshot_shutdown_context
+ return snapshot_shutdown_context(received_signal)
+
+ planned_takeover = bool(_best_effort(_takeover, "Takeover marker check failed: %s"))
+ planned_stop = received_signal == signal.SIGINT or (
+ not planned_takeover and bool(_best_effort(_planned_stop, "Planned stop marker check failed: %s")))
++ # `hermes gateway stop` writes the marker, THEN signals: the planned-stop watcher can consume
++ # the marker in between, and the CLI's own SIGTERM must not then read as an external kill.
++ if planned_stop:
++ planned_stop_seen[0] = True
++ elif planned_stop_seen[0] and not planned_takeover:
++ planned_stop = True
+ _shutdown_ctx = _best_effort(_snapshot, "snapshot_shutdown_context failed: %s")
+ sig_name = _shutdown_ctx["signal"] if _shutdown_ctx else None
+
+ if planned_takeover:
+ logger.info("Received %s as a planned --replace takeover — exiting cleanly", sig_name or "SIGTERM")
+ elif planned_stop:
+ logger.info("Received %s as a planned gateway stop — exiting cleanly", sig_name or "SIGTERM/SIGINT")
+ else:
+ # Mirrored onto the runner so _stop_impl suppresses the gateway_state=stopped persist for
+ # unexpected signals; operator stops take the `planned_stop` branch and leave it False (DO persist).
+ _signal_initiated_shutdown[0] = runner._signal_initiated_shutdown = True
+ logger.info("Received %s — initiating shutdown", sig_name or "SIGTERM/SIGINT")
+
+ if _shutdown_ctx is not None:
+ def _log_context() -> None:
+ # The most useful line for "gateway keeps dying" tickets.
+ from gateway.shutdown_forensics import format_context_for_log
+ logger.warning("Shutdown context: %s", format_context_for_log(_shutdown_ctx))
+
+ def _diagnostic() -> None:
+ # Heavyweight (ps auxf, pstree, dmesg), detached so it finishes even if our cgroup is torn
+ # down; bounded by an internal timeout, never blocks.
+ from gateway.shutdown_forensics import spawn_async_diagnostic
+ spawn_async_diagnostic(
+ _hermes_home / "logs" / "gateway-shutdown-diag.log", _shutdown_ctx["signal"], timeout_seconds=5.0)
+
+ _best_effort(_log_context, "format_context_for_log failed: %s")
+ _best_effort(_diagnostic, "spawn_async_diagnostic failed: %s")
+ if not planned_takeover:
+ # Supervisor/operator SIGNAL stop (bootout, kickstart -k, systemd, s6, bare kill) — the
+ # only kind launchd times with ExitTimeOut. In-band SIGUSR1 restarts never pass through
+ # here, and a sibling-driven --replace takeover is not launchd-timed either, so both
+ # keep the configured drain. _stop_impl uses this to cap the drain to the live budget.
+ runner._stop_requested_by_signal = True
+ asyncio.create_task(runner.stop())
+ return shutdown_signal_handler
+
+
+def _start_gateway_claim_pid_file(force: bool = False) -> bool:
+ """Claim the runtime lock + PID file (O_EXCL winner is the authoritative gateway). False = lost."""
+ from gateway.run import (_claim_host_gateway_role, logger, os)
+ import atexit
+ from gateway.status import (
+ acquire_gateway_runtime_lock, get_running_pid, release_gateway_runtime_lock,
+ remove_pid_file, write_pid_file)
+ _current_pid = get_running_pid()
+ if _current_pid is not None and _current_pid != os.getpid():
+ logger.error("Another gateway instance (PID %d) started during our startup. "
+ "Exiting to avoid double-running.", _current_pid)
+ return False
+ if not acquire_gateway_runtime_lock():
+ logger.error("Gateway runtime lock is already held by another instance. Exiting.")
+ return False
+ try:
+ write_pid_file()
+ except FileExistsError:
+ release_gateway_runtime_lock()
+ logger.error("PID file race lost to another gateway instance. Exiting.")
+ return False
+ atexit.register(remove_pid_file)
+ atexit.register(release_gateway_runtime_lock)
+ _claim_host_gateway_role(force=force)
+ return True
+
+
+async def _start_gateway_start_control_socket(runner):
+ """Start the gateway control socket (identify/status/pause-for-update); None when unavailable."""
+ from gateway.run import (asyncio, logger, os, threading)
+ import atexit
+ import concurrent.futures
+ _control_server = None
+ try:
+ # Started immediately after the PID-file claim: winning that O_EXCL race is the moment this process
+ # becomes the authoritative gateway for its HERMES_HOME, so from here on "does a socket answer?" is
+ # a truthful liveness/identity query for updater and fleet consumers. Strictly non-fatal: a bind
+ # failure only means consumers fall back to the process-scan/state-file layer, exactly as before
+ # this feature. See #92091.
+ from gateway.control_socket import GatewayControlServer, build_identify_payload
+ from gateway.run_profile_reconcile import migrate_profile_identity_verb, purge_profile_identity_verb
+ from gateway.run_plugin_rewire import reload_plugins_verb
+ descriptor = runner.session_runtime_descriptor
+
+ def _identify_runtime():
+ payload = build_identify_payload()
+ payload.update({key: descriptor[key] for key in (
+ "instance_id", "runtime_protocol", "authority_epoch", "state", "api_origin",
+ "served_profiles", "parked_profiles", "capabilities") if key in descriptor})
+ if getattr(runner, '_draining', False):
+ payload.update(state='draining', capabilities=[])
+ payload["supervisor"] = {"manual": "none", "desktop": "none"}.get(
+ payload.get("supervisor"), payload.get("supervisor", "none"))
+ return payload
+ # pause-for-update: the updater asks us to drain + exit (freeing venv handles) vs. a tree-kill
+ # (same path as SIGUSR1). Handler runs on the socket executor thread, so marshal onto the loop.
+ # pause-for-update (#92091 step 2): the updater asks this gateway to drain in-flight turns and exit
+ # cleanly — releasing every venv file handle — instead of being tree-killed mid-turn. Same drain
+ # path as SIGUSR1/service restarts (request_restart(via_service=True)); the updater (or the service
+ # manager) relaunches after the code swap.
+ _main_loop = asyncio.get_running_loop()
+
+ def _pause_for_update_handler() -> dict:
+ try:
+ from hermes_cli.gateway import _get_restart_drain_timeout
+ _drain = float(_get_restart_drain_timeout())
+ except Exception:
+ _drain = 30.0
+ accepted_box: list[bool] = []
+ _done = threading.Event()
+
+ def _request() -> None:
+ try:
+ accepted_box.append(runner.request_restart(detached=False, via_service=True))
+ finally:
+ _done.set()
+
+ _main_loop.call_soon_threadsafe(_request)
+ _done.wait(timeout=5.0)
+ accepted = bool(accepted_box and accepted_box[0])
+ return {
+ "pausing": accepted, "already_stopping": not accepted,
+ "pid": os.getpid(), "drain_timeout": _drain}
+
+ def _rescan_profiles_handler() -> dict:
+ """``hermes profile create/delete`` asks the multiplexer to reconcile ``profiles/`` now
+ (the watcher also rescans periodically). Runs on the socket executor: marshal onto the loop
+ and wait briefly so the caller learns whether the profile is served."""
+ if not getattr(runner.config, "multiplex_profiles", False):
+ return {"multiplex": False, "served_profiles": runner.served_profile_names()}
+ future = asyncio.run_coroutine_threadsafe(
+ runner.reconcile_served_profiles(reason="control-socket"), _main_loop)
+ try:
+ # Bounded: a token-less create reconciles in milliseconds; a credential-add whose adapter
+ # connect outlasts this keeps running and the caller sees ``pending`` (not an error).
+ return {"multiplex": True, **future.result(timeout=5.0)}
+ except concurrent.futures.TimeoutError:
+ return {"multiplex": True, "pending": True, "served_profiles": runner.served_profile_names()}
+
+ _control_server = GatewayControlServer(
+ verb_handlers={"pause-for-update": _pause_for_update_handler, "identify": _identify_runtime,
+ "rescan-profiles": _rescan_profiles_handler,
+ "migrate-profile-identity": migrate_profile_identity_verb(runner),
+ "purge-profile-identity": purge_profile_identity_verb(runner),
+ # A plugin installed/enabled by another process loads now and re-wires the
+ # live adapters' handlers (#87770); tools/prompt still wait for the next session.
+ "reload-plugins": reload_plugins_verb(runner, _main_loop)})
+ _control_server.ticket_store = runner.session_ticket_store
+ if not await _control_server.start():
+ _control_server = None
+ else:
+ atexit.register(_control_server.cleanup_files)
+ # Hosted-room transports install onto this listener; bind it here so every launcher
+ # that starts the control socket (not only start_gateway) exposes it.
+ runner.session_control_server = _control_server
+ except Exception as _cs_exc:
+ logger.debug("Control socket startup failed (non-fatal): %s", _cs_exc)
+ _control_server = None
+ return _control_server
+
+
+def _start_gateway_start_cron_and_housekeeping(runner):
+ """Start the cron scheduler thread + gateway housekeeping thread; returns
+ ``(cron_stop, cron_provider, cron_thread, housekeeping_thread)``."""
+ from gateway.run import (Dict, Platform, _cron_profile_gate, _cron_tick_profile_homes, _start_gateway_housekeeping, asyncio, logger, threading)
+ # The event loop is passed so cron delivery can use live adapters (E2EE support).
+ from cron.scheduler_provider import (
+ InProcessCronScheduler, resolve_cron_scheduler, scheduler_for_profile_mode)
+ cron_stop = threading.Event()
+ # ONE gateway process per host multiplexes every profile, so its cron ticker owns EVERY
+ # profile's store — `gateway.multiplex_profiles` gates adapters, not cron. Gating the tick set
+ # on that flag left every non-launch profile's jobs in a store no ticker visited: they
+ # silently never fired.
+ try:
+ cron_profile_homes = _cron_tick_profile_homes(runner.config)
+ except Exception as exc:
+ logger.warning("Could not resolve profile homes for cron: %s", exc)
+ cron_profile_homes = []
+ # External providers own one unscoped remote registry, so they can only serve a single home.
+ cron_provider = scheduler_for_profile_mode(
+ resolve_cron_scheduler(), multiplex_profiles=len(cron_profile_homes) > 1)
+ cron_start_kwargs: Dict[str, Any] = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}
+
+ if isinstance(cron_provider, InProcessCronScheduler) and cron_profile_homes:
+ # Live enumerator: the ticker re-reads profiles/ every cycle so a profile created while
+ # the gateway runs gets its jobs fired without a restart (hot-serve).
+ cron_start_kwargs["profile_homes"] = lambda: _cron_tick_profile_homes(runner.config)
+ # Stand down, per tick, for a profile whose OWN gateway process ticks it.
+ cron_start_kwargs["profile_gate"] = _cron_profile_gate
+ # Per-profile adapters so each profile's cron output goes via its own bot, not the
+ # default's. Absent (no multiplexed adapters), delivery for a secondary profile falls
+ # back to the primary's routed adapters or fails closed — the job still FIRES.
+ cron_start_kwargs["profile_adapters"] = getattr(runner, "_profile_adapters", None)
+ # runner.adapters belongs to the LAUNCH profile (``default``, or the ``--profile``
+ # name); naming it keeps the ticker from routing a secondary's cron through that bot
+ # and lets a named multiplexer's own jobs reuse its live adapters.
+ cron_start_kwargs["default_profile"] = runner._primary_profile_name
+ logger.info(
+ "Cron scheduler will tick %d profile(s): %s", len(cron_profile_homes),
+ [p[0] if isinstance(p, tuple) else p for p in cron_profile_homes])
+
+ # Only the in-process ticker polls local due jobs, so only it gets the external-drain dispatch gate.
+ if isinstance(cron_provider, InProcessCronScheduler):
+ cron_start_kwargs["can_dispatch"] = lambda: not (
+ runner._draining or runner._external_drain_active)
+ # Supervised: a ticker that dies without a stop request is respawned by housekeeping (#111010).
+ from cron.scheduler_thread import SupervisedTickerThread
+ cron_thread = SupervisedTickerThread(
+ cron_provider.start, args=(cron_stop,), kwargs=cron_start_kwargs, stop_event=cron_stop)
+ from gateway.runtime_ownership import process_ownership
+ process_ownership.start_writer(cron_thread)
+
+ # External providers fire over loopback HTTP to THIS process's api_server; if it never came up (usually
+ # API_SERVER_KEY missing) every fire fails while manual runs work — misread as a job bug. Say it ONCE.
+ if not isinstance(cron_provider, InProcessCronScheduler):
+ try:
+ _has_api_server = Platform.API_SERVER in (runner.adapters or {})
+ except Exception:
+ _has_api_server = True # never let the tell break startup
+ if not _has_api_server:
+ logger.warning(
+ "Cron provider '%s' is active but the api_server adapter is "
+ "NOT running in this gateway — scheduled fires arrive over "
+ "loopback HTTP and will all fail (jobs only run when "
+ "triggered manually). Most common cause: API_SERVER_KEY is "
+ "missing from this gateway process's environment. Restart "
+ "the gateway through its supervisor (`hermes gateway "
+ "restart`) so the profile env loads.",
+ getattr(cron_provider, "name", "external"))
+
+ # Gateway-only housekeeping runs independently of the cron provider; shares cron_stop for shutdown.
+ housekeeping_thread = threading.Thread(
+ target=_start_gateway_housekeeping, args=(cron_stop,),
+ kwargs={"adapters": runner.adapters, "loop": asyncio.get_running_loop(),
+ "cron_provider": cron_provider, "runner": runner, "cron_thread": cron_thread},
+ daemon=True, name="gateway-housekeeping")
+ process_ownership.start_writer(housekeeping_thread)
+ return cron_stop, cron_provider, cron_thread, housekeeping_thread
+
+
+async def _start_gateway_shutdown_tail(
+ runner, _control_server, cron_stop: threading.Event, cron_provider,
+ cron_thread: Any, housekeeping_thread: threading.Thread,
+ _planned_stop_watcher_stop: threading.Event, _planned_stop_watcher_thread: threading.Thread,
+ _signal_initiated_shutdown: list) -> bool:
+ """Post-``wait_for_shutdown`` teardown; returns the process exit verdict (True = exit 0)."""
+ from gateway.run import (_CRON_SHUTDOWN_DRAIN_TIMEOUT, _HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT, _await_thread_exit, _best_effort, _resolve_gateway_exit_verdict, _shutdown_mcp_servers_nonblocking, _stop_cron_provider, logger, suppress)
+ # Control socket first: once shutdown begins we are no longer a truthful "serving here" answer and a
+ # successor must be able to bind. Early-exit paths rely on the atexit cleanup_files hook instead.
+ if _control_server is not None:
+ try:
+ await _control_server.stop()
+ except Exception:
+ logger.debug("Control socket stop failed (non-fatal)", exc_info=True)
+
+ def _stop_keepalive() -> None:
+ from hermes_cli.nous_auth_keepalive import stop_nous_auth_keepalive
+ stop_nous_auth_keepalive()
+
+ _best_effort(_stop_keepalive)
+
+ # Never join(): an in-flight cron delivery is a coroutine on THIS loop; a sync join would drop it.
+ # Stop cron scheduler + housekeeping cleanly. These MUST be awaited cooperatively, not join()ed. A cron
+ # delivery in flight when the gateway restarts is a coroutine scheduled onto THIS event loop
+ # (safe_schedule_threadsafe); the ticker thread is blocked on its future.result(). A synchronous
+ # cron_thread.join() would block the loop, so that delivery could never run — it timed out and the
+ # message was silently dropped (#58818). Awaiting keeps the loop alive so the in-flight delivery
+ # finishes before we tear down.
+ cron_stop.set()
+ _stop_cron_provider(cron_provider)
+ if not await _await_thread_exit(cron_thread, timeout=_CRON_SHUTDOWN_DRAIN_TIMEOUT):
+ logger.warning("Cron ticker did not exit within %.0fs of shutdown — an in-flight "
+ "delivery may have been dropped.", _CRON_SHUTDOWN_DRAIN_TIMEOUT)
+ await _await_thread_exit(housekeeping_thread, timeout=_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT)
+
+ # Stop the planned-stop watcher (daemon=True so this is belt-and-suspenders).
+ _planned_stop_watcher_stop.set()
+ _planned_stop_watcher_thread.join(timeout=2)
+
+ # Never suppressed: a raise here is a real teardown failure (it once hid a changed signature,
+ # leaving every MCP connection and the shared loop up while the gateway reported a clean exit).
+ try:
+ await _shutdown_mcp_servers_nonblocking(config=getattr(runner, "config", None))
+ except Exception:
+ logger.warning("MCP shutdown failed; connections may be left open", exc_info=True)
+
+ # The failure verdict comes AFTER the cooperative teardown: returning early here leaked the
+ # cron ticker + housekeeping threads (and open MCP connections) for embedded callers (#12175).
+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])
+
+
+
+def _launch_home_may_multiplex(config=None) -> bool:
+ """A named profile serving ``default`` as a secondary splits default's local sessions between
+ the two stores (routing rows follow the launch home, receipts follow the authority), so the
+ multiplexer is the default profile's job.
+
+ An EXPLICIT ``gateway.multiplex_profiles: true`` (config.yaml or ``GATEWAY_MULTIPLEX_PROFILES``)
+ on a named launch home exits EX_CONFIG: a config verdict, never a retry. The implicit default
+ (unset key, or the retired ``false`` that ``resolve_multiplex_mode`` settles like unset) is not
+ the operator's choice, so it is downgraded the way every other implicit-multiplex blocker is:
+ this process comes up standalone, says why, and *config* is flipped in place so the boot below
+ reserves and serves only the launch profile."""
+ from hermes_constants import profile_name_for_home
+ from gateway.run import get_hermes_home, logger
+ name = profile_name_for_home(get_hermes_home())
+ if name in (None, "default"):
+ return True
+ from hermes_cli.gateway_multiplex_mode import explicit_multiplex_flag
+ if config is not None and not explicit_multiplex_flag(get_hermes_home()):
+ from hermes_cli.gateway_multiplex_mode import MultiplexDecision, log_multiplex_decision
+ decision = MultiplexDecision(
+ False, "guard",
+ f"profile {name!r} launched the gateway, and only the default profile runs the multiplexer "
+ "(start it with `hermes gateway run` from the default profile to serve every profile)")
+ config.multiplex_profiles = False
+ log_multiplex_decision(decision)
+ return True
+ from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE
+ from gateway.run import _write_runtime_status_quiet
+ logger.error(
+ "gateway.multiplex_profiles is set on profile %r, but only the default profile can run the "
+ "multiplexer. Unset the flag in this profile's config.yaml, or start the gateway from the "
+ "default profile (`hermes gateway run`), which serves this profile too.", name)
+ _write_runtime_status_quiet(gateway_state="startup_failed", exit_reason="multiplex_requires_default_profile")
+ raise SystemExit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
+
+
+async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False,
+ verbosity: Optional[int] = 0, force: bool = False) -> bool:
+ """Start the gateway and run until interrupted; False if it failed to start (non-zero exit so
+ systemd can auto-restart). ``replace`` kills any existing instance first (avoids restart-loop
+ deadlocks); ``force`` starts without consulting the host owner at all."""
+ from gateway.run import (
+ GatewayRunner,
+ _best_effort,
+ _discover_gateway_mcp_tools,
+ _enable_multiplex_log_routing,
+ _ensure_windows_gateway_venv_imports,
+ _gateway_loop_exception_handler,
+ _host_attach_or_none,
+ _log_standalone_profiles_at_boot,
+ _multiplex_profile_homes,
+ _refresh_host_gateway_record,
+ _resolve_gateway_exit_verdict,
+ _run_planned_stop_watcher,
+ _shutdown_gateway_health_export,
+ _shutdown_mcp_servers_nonblocking,
+ _start_gateway_make_restart_signal_handler,
+ asyncio,
+ get_hermes_home,
+ load_gateway_config_for_runner,
+ logger,
+ os,
+ signal,
+ suppress,
+ threading,
+ )
+ # Set here (not at import) so incidental gateway.run imports from CLI code don't poison it.
+ os.environ["HERMES_EXEC_ASK"] = "1"
+
+ from hermes_cli.resource_limits import apply_nofile_soft_limit
+ apply_nofile_soft_limit()
+
+ # Snapshot the revision while sys.modules matches disk so a later `git pull` is detected safely.
+ from gateway.code_skew import record_boot_fingerprint
+ record_boot_fingerprint()
+
+ # Config verdicts come before the duplicate-instance guard: `--replace` must not stop a healthy
+ # gateway for a launch that cannot start.
+ resolved_config = config if config is not None else load_gateway_config_for_runner()
+ profile_homes = (_multiplex_profile_homes(resolved_config)
+ if getattr(resolved_config, 'multiplex_profiles', False) else [])
+ if profile_homes and not _launch_home_may_multiplex(resolved_config):
+ return False
+ if profile_homes and not getattr(resolved_config, 'multiplex_profiles', False):
+ profile_homes = [] # implicit default downgraded: this named launch serves only itself
+
+ # Multiplex-only: the ONE host gateway decides first. Attach to it, make it serve this profile,
+ # replace it (--replace) or refuse — before anything below binds a port or claims a PID file.
+ _host_decision = await _host_attach_or_none(replace, force)
+ if _host_decision is not None:
+ return _host_decision
+
+ # Duplicate-instance guard scoped to HERMES_HOME (the host record is absent or unusable here).
+ from gateway.status import get_running_pid
+ existing_pid = get_running_pid()
+ if (existing_pid is not None and existing_pid != os.getpid()
+ and not await _start_gateway_replace_existing_instance(existing_pid, replace)):
+ return False
+
+ from gateway.runtime_ownership import process_ownership, OwnershipConflict
+ from gateway.status import remove_pid_file, release_gateway_runtime_lock
+ try:
+ process_ownership.reserve([get_hermes_home(), *(home for _, home in profile_homes)])
+ except OwnershipConflict as exc:
+ logger.error("Cannot reserve gateway profiles: %s", exc)
+ # A named profile that the LIVE default multiplexer already serves is a configuration
+ # verdict (gateway.multiplex_profiles), not a transient fault: exit EX_CONFIG so systemd's
+ # RestartPreventExitStatus=78 parks the unit instead of restart-looping (#51228, #97120).
+ # Any other same-user contender keeps the ordinary "already running" exit 1.
+ from hermes_cli.gateway import named_profile_served_by_running_multiplexer
+ if named_profile_served_by_running_multiplexer():
+ from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE
+ from gateway.run import _write_runtime_status_quiet
+ logger.error(
+ "The default gateway is running as a profile multiplexer and already serves this profile. "
+ "Manage it with `hermes gateway restart` from the default profile instead of starting a "
+ "second gateway for the profile.")
+ _write_runtime_status_quiet(gateway_state="startup_failed", exit_reason=str(exc))
+ raise SystemExit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
+ return False
+ except OSError as exc:
+ logger.error("Cannot reserve gateway profiles: %s", exc)
+ return False
+ # Freeze discovery: later profile additions must restart and reserve before opening stores.
+ if profile_homes:
+ resolved_config._runtime_profile_homes = tuple(profile_homes)
+ # PID file BEFORE adapters: of two concurrent `run --replace`, only the O_EXCL winner opens sockets.
- if not _start_gateway_claim_pid_file(force=force or replace):
++ # Only --force skips the host-lock refusal. Every generated unit carries --replace, so reading it as
++ # --force there disabled the one arbiter of the two-units-at-once race; a replace that took the
++ # owner over already freed the lock with that process.
++ if not _start_gateway_claim_pid_file(force=force):
+ release_gateway_runtime_lock()
+ return False
+
+ _control_server = None
+ runner = None
+ _planned_stop_watcher_stop = None
+ try:
+ _start_gateway_configure_logging(verbosity)
+
+ runner = GatewayRunner(resolved_config)
+ from gateway.run_runtime import initialize_gateway_runtime
+ await initialize_gateway_runtime(runner)
+ # Multiplex: swap the launch-home file handlers for per-profile routers so each profile's records
+ # land in its own logs/. Must run after the runner resolved (possibly None) config and setup_logging.
+ # See #82936.
+ _enable_multiplex_log_routing(runner.config)
+ # ``--replace`` is explicit startup authority, not a durable reconnect policy: GatewayRunner scopes
+ # it to cold adapter connects and clears it before the background reconnect watcher starts.
+ runner._platform_lock_takeover_on_start = bool(replace)
+
+ # Unexpected signals exit non-zero so service managers revive us; planned stops write a marker first.
+ _signal_initiated_shutdown = [False]
+
+ shutdown_signal_handler = _start_gateway_make_shutdown_signal_handler(
+ runner, _signal_initiated_shutdown)
+
+ restart_signal_handler = _start_gateway_make_restart_signal_handler(runner)
+
+ loop = asyncio.get_running_loop()
+
+ # Swallow transient network errors from background tasks; one unhandled httpx error would kill us.
+ # Issues #31066 / #31110: an unhandled ``telegram.error.TimedOut`` (or peer NetworkError / httpx
+ # connection error) in any awaited coroutine would propagate to the loop and kill the gateway process,
+ # taking down every profile attached to the same runner. systemd then restarts the service after ~5s but
+ # the active conversation turn is lost. The fix is intentionally narrow: only well-known transient
+ # network errors are swallowed (and logged with full traceback so the originating call site is still
+ # discoverable). Anything else is forwarded to the default handler so real bugs still surface.
+ loop.set_exception_handler(_gateway_loop_exception_handler)
+
+ if threading.current_thread() is threading.main_thread():
+ # add_signal_handler raises NotImplementedError on Windows; SIGUSR1 is POSIX-only.
+ handlers = [(sig, shutdown_signal_handler, (sig,)) for sig in (signal.SIGINT, signal.SIGTERM)]
+ if hasattr(signal, "SIGUSR1"):
+ handlers.append((signal.SIGUSR1, restart_signal_handler, ())) # windows-footgun: ok — hasattr-guarded
+ for sig, handler, args in handlers:
+ with suppress(NotImplementedError):
+ loop.add_signal_handler(sig, handler, *args) # windows-footgun: ok — suppress(NotImplementedError)
+ else:
+ logger.info("Skipping signal handlers (not running in main thread).")
+
+ # Windows has no add_signal_handler, so `hermes gateway stop`'s SIGTERM would never drain; poll the
+ # planned-stop marker (written BEFORE the kill) instead. Runs everywhere so masked-SIGTERM drains.
+ # Windows fallback: asyncio.add_signal_handler raises NotImplementedError on Windows, so `hermes gateway
+ # stop`'s SIGTERM (which Python maps to TerminateProcess on Windows) never invokes
+ # shutdown_signal_handler. That means the drain loop never runs, mark_resume_pending never fires, and
+ # sessions are silently lost across restarts (issue #33778). The fix is a marker-polling thread: `hermes
+ # gateway stop` writes the planned-stop marker BEFORE killing, and this thread notices it and drives the
+ # same shutdown path the signal handler would have. Runs on every platform (cheap, defensive) so
+ # non-signal-bearing environments (Windows native, sandboxed CI runners that mask SIGTERM) still get a
+ # clean drain.
+ _planned_stop_watcher_stop = threading.Event()
+ _planned_stop_watcher_thread = threading.Thread(
+ target=_run_planned_stop_watcher,
+ args=(_planned_stop_watcher_stop, runner, loop, shutdown_signal_handler), daemon=True,
+ name="planned-stop-watcher")
+ _planned_stop_watcher_thread.start()
+
+ # Right after the PID claim (which makes us authoritative); non-fatal — consumers fall back to scan.
+ _control_server = await _start_gateway_start_control_socket(runner)
+ if _control_server is None:
+ raise RuntimeError("gateway session bootstrap control listener unavailable")
+ # Now the attach channel answers: republish the host record with the settled served set.
+ _refresh_host_gateway_record(runner)
+ _log_standalone_profiles_at_boot(runner)
+ from gateway.run_runtime import start_gateway_runtime_api
+ await start_gateway_runtime_api(runner)
+
+ def _lifecycle_record_startup() -> None:
+ # Report if the previous life died uncleanly (SIGKILL / OOM / VM death), then claim the
+ # sentinel for this life. After the PID-file claim so a --replace loser can't clobber it.
+ from gateway.lifecycle_ledger import record_startup
+ record_startup()
+
+ def _start_keepalive() -> None:
+ from hermes_cli.nous_auth_keepalive import start_nous_auth_keepalive
+ start_nous_auth_keepalive()
+
+ _best_effort(_lifecycle_record_startup, "Lifecycle ledger startup record failed: %s")
+ _best_effort(_start_keepalive, "Nous auth keepalive did not start: %s")
+ _ensure_windows_gateway_venv_imports()
+
+ # discover_mcp_tools() blocks up to 120s; on the loop thread it would freeze platform heartbeats.
+ try:
+ # MCP tool discovery — run in an executor so the asyncio event loop stays responsive even when a
+ # configured MCP server is slow or unreachable. discover_mcp_tools() uses a blocking 120s wait
+ # internally; calling it from the loop thread would freeze platform heartbeats (Discord shard,
+ # Telegram polling) until it returned. See #16856.
+ await _discover_gateway_mcp_tools(runner.config)
+ except Exception as e:
+ logger.debug("MCP tool discovery failed: %s", e)
+
+ try:
+ success = await runner.start()
+ except BaseException:
+ _shutdown_gateway_health_export(runner)
+ raise
+ if not success:
+ _shutdown_gateway_health_export(runner)
+ return False
+
+ def _recover_pending() -> None:
+ from gateway.shutdown_flush import recover_pending_to_db
+ recovered = recover_pending_to_db(
+ session_resolver=runner.session_store.resolve_session_id_for_key,
+ )
+ if recovered:
+ logger.info("Recovered %d pending message(s) from shutdown flush", recovered)
+
+ _best_effort(_recover_pending)
+ if runner.should_exit_cleanly:
+ _shutdown_gateway_health_export(runner)
+ if runner.exit_reason:
+ logger.error("Gateway exiting cleanly: %s", runner.exit_reason)
+ # Explicit exit codes (GATEWAY_FATAL_CONFIG_EXIT_CODE) must propagate so s6 finish maps 78 → 125.
+ if runner.exit_code is not None:
+ raise SystemExit(runner.exit_code)
+ return True
+ if not runner._running:
+ # Startup aborted by restart/shutdown before running mode; preserve that path without starting cron.
+ try:
+ await runner.wait_for_shutdown()
+ try:
+ await _shutdown_mcp_servers_nonblocking(config=getattr(runner, "config", None))
+ except Exception:
+ logger.warning("MCP shutdown failed; connections may be left open", exc_info=True)
+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])
+ finally:
+ _shutdown_gateway_health_export(runner)
+
+ cron_stop, cron_provider, cron_thread, housekeeping_thread = (
+ _start_gateway_start_cron_and_housekeeping(runner))
+
+ # READY only once adapters, cron and housekeeping run; missing systemd state just disables watchdog.
+ from gateway.run_runtime import publish_gateway_runtime_ready
+ publish_gateway_runtime_ready(runner)
+ runner._start_systemd_watchdog()
+
+ from gateway.run_runtime import wait_gateway_runtime
+ try:
+ await wait_gateway_runtime(runner)
+ finally:
+ try:
+ await runner.stop()
+ finally:
+ verdict = await _start_gateway_shutdown_tail(
+ runner, _control_server, cron_stop, cron_provider, cron_thread, housekeeping_thread,
+ _planned_stop_watcher_stop, _planned_stop_watcher_thread, _signal_initiated_shutdown)
+ return verdict
+
+ finally:
+ try:
+ if runner is not None:
+ from gateway.run_runtime import drain_gateway_runtime
+ await drain_gateway_runtime(runner)
+ # Startup may have opened adapters before an exception. The same
+ # stop path owns their writers and DB handles on every exit.
+ await runner.stop()
+ finally:
+ if _planned_stop_watcher_stop is not None:
+ _planned_stop_watcher_stop.set()
+ if _control_server is not None:
+ await _control_server.stop()
+ remove_pid_file()
+ release_gateway_runtime_lock()
diff --cc gateway/run_turn.py
index 3c0e132ba3d,6b436aedc2d..98726a310a6
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@@ -825,16 -2767,16 +838,14 @@@ class GatewayTurnMixin(GatewayTurnPrepa
return self._proxy_error_result("⚠️ Proxy URL not configured (GATEWAY_PROXY_URL or gateway.proxy_url)")
# The proxy key is a per-profile credential: honor the installed secret scope under multiplex.
-- # Only UnscopedSecretError / import failures fall back to the env; any other get_secret()
-- # error propagates (same as BASE) rather than silently degrading to the ambient key.
-- try:
-- from agent.secret_scope import UnscopedSecretError, get_secret
++ # Only UnscopedSecretError (the unscoped default-profile path) falls back to the env; any
++ # other get_secret() error propagates (same as BASE) rather than silently degrading to the
++ # ambient key, which may hold another profile's credential.
++ from agent.secret_scope import UnscopedSecretError, get_secret
-- try:
-- proxy_key = (get_secret("GATEWAY_PROXY_KEY") or "").strip()
-- except UnscopedSecretError:
-- proxy_key = os.getenv("GATEWAY_PROXY_KEY", "").strip()
-- except Exception:
++ try:
++ proxy_key = (get_secret("GATEWAY_PROXY_KEY") or "").strip()
++ except UnscopedSecretError:
proxy_key = os.getenv("GATEWAY_PROXY_KEY", "").strip()
_run_still_current = self._run_still_current_fn(session_key, run_generation)
diff --cc gateway/run_turn_prepare.py
index 43edd8d7954,00000000000..7e8375a6887
mode 100644,000000..100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@@ -1,685 -1,0 +1,702 @@@
+"""Gateway turn prepare phases; inherited by GatewayTurnMixin."""
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING
+import asyncio
+import dataclasses
+import inspect
+import json
+import os
+import queue
+import threading
+import time
+from agent.i18n import t
+from agent.session_activity import format_iteration_progress
+from contextlib import nullcontext, suppress
+from contextvars import copy_context
+from gateway.config import Platform
+from gateway.media_repair import repair_explicit_computer_use_media_paths
+from gateway.platforms.base import BasePlatformAdapter
+from gateway.platforms.event import MessageEvent
+from gateway.session import (
+ SessionSource, _session_key_namespace, build_channel_continuity_note,
+ build_session_context,
+)
+from gateway.session_transcript import TranscriptReadError
+from gateway.turn_context import TurnContext
+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError
+from hermes_constants import get_hermes_home_override
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional, Tuple
+from utils import base_url_hostname
+
+if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
+ from gateway.run import GatewayRunner # noqa: F401
+ from gateway.run_turn_runner import TurnRunner # noqa: F401
+
+# Log-record parity with the origin module.
+logger = logging.getLogger("gateway.run")
+
+
+class GatewayTurnPrepareMixin:
+ def _resolve_session_agent_runtime(
+ self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,
+ user_config: Optional[dict] = None,
+ ) -> tuple[str, dict]:
+ """Resolve model/runtime for a session.
+
+ Priority (highest first): session ``/model`` → ``channel_overrides`` → global config/env
+ (``_resolve_gateway_model(user_config)`` and default provider resolution)."""
+ from gateway.run import (
+ _credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,
+ _resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,
+ )
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(self, source) if source is not None else None
+ if policy is not None:
+ from hermes_cli.runtime_provider import resolve_runtime_provider
+ from gateway.run import _runtime_agent_kwargs
+ from gateway.session_policy import launch_key
+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self)
+ frozen = policy.config(authority)
+ key = launch_key(authority, policy)
+ import json
+ runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,
+ explicit_api_key=key, explicit_base_url=json.loads(policy.request_json).get('base_url'),
+ target_model=policy.model, config=frozen)
+ if runtime is None:
+ if key is None:
+ key = frozen.get('model', {}).get('api_key')
+ runtime = resolve_runtime_provider(requested=policy.provider,
+ explicit_api_key=key, explicit_base_url=policy.base_url, target_model=policy.model)
+ return policy.model, _runtime_agent_kwargs(runtime)
+ skey = self._resolve_session_key_or_none(source, session_key)
+ # Every exit path starts clean: the /model-override fast path returns before the pop below,
+ # and hygiene/inbound callers resolve without a turn runner consuming the stash — a stale
+ # notice must never attach to another session's next turn (#74349).
+ self._pre_agent_fallback_notice = None
+
+ model = _resolve_gateway_model(user_config)
+ if skey:
+ self._rehydrate_session_model_override(skey)
+ _override_state = self._peek_session_state(skey) if skey else None
+ override = _override_state.conversation.model_override if _override_state else None
+ if override:
+ override_model = override.get("model", model)
+ override_runtime = {
+ k: override.get(k) for k in (
+ "provider", "requested_provider", "api_key", "base_url", "api_mode",
+ "max_tokens", "credential_pool", "request_overrides", "capabilities",
+ )
+ }
+ override_runtime["capabilities"] = dict(override_runtime["capabilities"] or {})
+ if override_runtime.get("api_key"):
+ if override_runtime.get("credential_pool") is None:
+ override_runtime["credential_pool"] = _credential_pool_for_provider(override.get("provider"))
+ logger.debug(
+ "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s",
+ skey or "", model, override_model, override_runtime.get("provider"),
+ )
+ return override_model, override_runtime
- # No api_key on the override: env-based resolution below, override model/provider on top.
++ # No api_key on the override (credentials failed to re-resolve at rehydrate): resolve them
++ # for the override's own provider below, never layer it over the default provider's runtime.
+ logger.debug(
+ "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",
+ skey or "", model, override_model,
+ )
+ else:
+ logger.debug(
+ "No session model override: session=%s config_model=%s override_keys=%s",
+ skey or "", model,
+ [
+ _key for _key, _st in list(self._sessions_map().items())
+ if _st.conversation.model_override is not None
+ ][:5] or "[]",
+ )
+
- runtime_kwargs = _resolve_runtime_agent_kwargs()
++ runtime_kwargs, unavailable_override = None, None
++ if override and override.get("provider"):
++ try:
++ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(
++ override["provider"], target_model=override.get("model") or None)
++ except Exception as exc:
++ # Layering the override on the default runtime sent its model to the default provider's
++ # endpoint (openai-codex on the Nous URL). Run this turn on the whole default route and say
++ # so; the persisted override is kept, so the next turn retries it.
++ logger.warning("Session /model override provider %s unavailable: %s", override["provider"], exc)
++ unavailable_override, override = override, None
++ if runtime_kwargs is None:
++ runtime_kwargs = _resolve_runtime_agent_kwargs()
+ # Private notice metadata must never reach an ``AIAgent(**runtime_kwargs)`` spread; the turn
+ # runner surfaces it through the agent's one-shot fallback notice (#74349).
+ self._pre_agent_fallback_notice = runtime_kwargs.pop("_fallback_notice", None)
+ runtime_model = runtime_kwargs.pop("model", None)
+ if runtime_model:
+ logger.info("Runtime provider supplied explicit model override: %s -> %s", model, runtime_model)
+ model = runtime_model
++ if unavailable_override and not self._pre_agent_fallback_notice:
++ from hermes_cli.fallback_config import pre_agent_fallback_notice
++ self._pre_agent_fallback_notice = pre_agent_fallback_notice(
++ unavailable_override["provider"], unavailable_override.get("model"), runtime_kwargs.get("provider"), model)
+
+ cfg = getattr(self, "config", None) # getattr: bare object.__new__ test runners
+ if cfg and source is not None:
+ ch = _get_channel_override(
+ cfg, source.platform, str(source.chat_id) if source.chat_id else "",
+ thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,
+ parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,
+ )
+ if ch:
+ if ch.model:
+ model = ch.model
+ if ch.provider:
+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(ch.provider, target_model=model or None)
+ ch_runtime_model = runtime_kwargs.pop("model", None)
+ # Adopt the provider's bundled model only when the override named none.
+ if ch_runtime_model and not ch.model:
+ model = ch_runtime_model
+
+ if override and skey:
+ model, runtime_kwargs = self._apply_session_model_override(skey, model, runtime_kwargs)
+
+ # Provider resolved but no model.default (`hermes auth add` without `hermes model`): use the
+ # provider's first catalog model.
+ if not model and runtime_kwargs.get("provider"):
+ with suppress(Exception):
+ from hermes_cli.models import get_default_model_for_provider
+ model = get_default_model_for_provider(runtime_kwargs["provider"])
+ if model:
+ logger.info(
+ "No model configured — defaulting to %s for provider %s", model, runtime_kwargs["provider"],
+ )
+
+ # Final safety net: an empty model (transient config-cache miss) makes every API call 400 and
+ # the session goes silent — reuse the last model resolved for this session, else process-wide.
+ if not model:
+ _lr_state = self._peek_session_state(skey) if skey else None
+ _lr_star = self._peek_session_state("*")
+ _recovered = (
+ (_lr_state.conversation.last_resolved_model if _lr_state else "")
+ or (_lr_star.conversation.last_resolved_model if _lr_star else "")
+ )
+ if _recovered:
+ logger.warning(
+ "Empty model resolved for session=%s — recovering "
+ "last-known-good model %s (config read likely returned "
+ "empty; see #35314)", skey or "", _recovered,
+ )
+ model = _recovered
+ else:
+ # Cache the good resolution for future recovery turns.
+ if skey:
+ self._session_state(skey).conversation.last_resolved_model = model
+ self._session_state("*").conversation.last_resolved_model = model
+
+ return model, runtime_kwargs
+
+ def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:
+ """Effective model/runtime config for one turn. With `/fast` priority on, fast-mode
+ ``request_overrides`` are deep-merged OVER the per-provider ones so both reach the model."""
+ from gateway.run import _deep_merge_request_overrides
+ from hermes_cli.models import resolve_fast_mode_overrides
+ # Tests bind this method onto bare namespaces, so no class-level tables here.
+ runtime = {
+ k: runtime_kwargs.get(k) for k in (
+ "api_key", "base_url", "provider", "requested_provider", "api_mode", "command", "args",
+ "credential_pool", "max_tokens", "capabilities",
+ )
+ }
+ runtime["args"] = list(runtime["args"] or [])
+ runtime["capabilities"] = dict(runtime["capabilities"] or {})
+ base_request_overrides = dict(runtime_kwargs.get("request_overrides") or {})
+ route = {
+ "model": model,
+ "runtime": runtime,
+ "signature": (
+ model, runtime["provider"], runtime["requested_provider"], runtime["base_url"],
+ runtime["api_mode"], runtime["command"], tuple(runtime["args"]),
+ ),
+ }
+ if getattr(self, "_service_tier", None) != "priority":
+ # None / auto / cold: the bounded window is applied per request by agent.fast_mode.
+ route["request_overrides"] = base_request_overrides
+ return route
+ try:
+ overrides = resolve_fast_mode_overrides(
+ route["model"], provider=runtime["provider"], base_url=runtime["base_url"],
+ )
+ except Exception:
+ overrides = None
+ # Fast-mode keys (service_tier / speed) are top-level and don't collide with extra_body.
+ route["request_overrides"] = _deep_merge_request_overrides(base_request_overrides, overrides or {})
+ return route
+
+ def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:
+ """Persist the runtime model/provider a gateway turn actually used (provider fallback can
+ switch them after the row was created). Runs in the ``run_sync`` executor thread, so it
+ uses the sync ``SessionDB`` (``_db``), not the AsyncSessionDB forwarder."""
+ if not session_id or agent is None or self._session_db is None:
+ return
+ model = getattr(agent, "model", None)
+ if not model:
+ return
+ runtime = {k: getattr(agent, k, None) for k in ("provider", "base_url", "api_mode")}
+ runtime["fallback_active"] = bool(getattr(agent, "_fallback_activated", False))
+ runtime = {k: v for k, v in runtime.items() if v not in (None, "")}
+ try:
+ db = self._session_db._db
+ row = db.get_session(session_id)
+ if not row:
+ return
+ # Legacy backfill: canonical Bot Chats created BEFORE the follow_profile_config contract existed
+ # carry no marker, yet they are still the plugin-owned forever-DM. The plugin's own identity
+ # rule is "the profile's session titled exactly 'Bot Chat'" (UNIQUE(title) makes that an exact
+ # registry, and pre-policy rows may be visible OR hidden), so mirror that rule here. Without
+ # this, every Bot Chat that already exists in the field stays pinned to its stale stored
+ # provider until the user deletes it — the exact live-report shape (#89497 / #94818).
+ raw_config = row.get("model_config")
+ config = {}
+ with suppress(Exception):
+ config = json.loads(raw_config) if raw_config else {}
+ if not isinstance(config, dict):
+ config = {}
+ gateway_runtime = dict(config.get("gateway_runtime") or {})
+ if row.get("model") == model and all(gateway_runtime.get(k) == v for k, v in runtime.items()):
+ return
+ config["gateway_runtime"] = runtime
+ db.update_session_meta(session_id, json.dumps(config), model=model)
+ except Exception:
+ logger.debug("Failed to sync gateway session model metadata", exc_info=True)
+
+ async def _hmwa_resolve_session(self, event, source):
+ """Resolve ``source`` to its session entry (topic recovery, internal-route guards, Telegram
+ topic-binding heal). Returns ``(source, session_entry, session_key)`` or ``None`` to drop
+ the event."""
+ # Topic-mode DMs: rewrite a stale/foreign thread_id to the user's last-active topic so a
+ # cross-topic Reply doesn't fragment the conversation.
+ event_metadata = getattr(event, "metadata", None) or {}
+ expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()
+ recovered = (await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
+ if not expected_session_key else None)
+ if recovered is not None:
+ logger.info(
+ "telegram topic recovery: chat=%s user=%s %r -> %s",
+ source.chat_id, source.user_id, source.thread_id, recovered,
+ )
+ source = dataclasses.replace(source, thread_id=recovered)
+ with suppress(Exception):
+ event.source = source
+
+ if expected_session_key:
+ derived_session_key = self._session_key_for_source(source)
+ if derived_session_key != expected_session_key:
+ logger.warning(
+ "Dropping internally routed event after route recovery: expected session=%s derived=%s",
+ expected_session_key, derived_session_key,
+ )
+ return
+
+ strict_session = bool(event_metadata.get("gateway_session_strict"))
+ pinned_session_id = str(event_metadata.get("gateway_session_id") or "").strip()
+ if strict_session:
+ session_entry = await self.async_session_store.lookup_by_session_key(expected_session_key)
+ if session_entry is None or not pinned_session_id or session_entry.session_id != pinned_session_id:
+ logger.warning(
+ "Dropping internally routed event: expected session id=%s is no longer current for key=%s",
+ pinned_session_id or "missing", expected_session_key or "missing",
+ )
+ return
+ else:
+ # Internal wakes observe reset policy without counting as user activity, or periodic
+ # notifications keep the routing key alive across every daily/idle boundary.
+ session_entry = await self.async_session_store.get_or_create_session(
+ source, touch_activity=not bool(getattr(event, "internal", False)),
+ )
+ session_key = session_entry.session_key
+ if not strict_session and pinned_session_id:
+ resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id)
+ if resolved_entry is None:
+ return
+ session_entry = resolved_entry
+ self._cache_session_source(session_key, source)
+ if await asyncio.to_thread(self._is_telegram_topic_lane, source):
+ session_entry = await self._hmwa_heal_telegram_topic_binding(source, session_entry, session_key)
+ from gateway.run_heartbeat_acceptance import resolve_heartbeat_owner
+ if not await resolve_heartbeat_owner(self, event, session_entry):
+ return
+ return source, session_entry, session_key
+
+ async def _hmwa_heal_telegram_topic_binding(self, source, session_entry, session_key):
+ """Follow the (chat_id, thread_id) topic binding — healed to its compression tip — or record
+ a fresh one. Returns the (possibly switched) session entry."""
+ binding = None
+ try:
+ if self._session_db:
+ binding = await self._session_db.get_telegram_topic_binding(
+ chat_id=str(source.chat_id), thread_id=str(source.thread_id),
+ profile_name=self._telegram_topic_profile_name(source),
+ )
+ except Exception:
+ logger.debug("Failed to read Telegram topic binding", exc_info=True)
+ if not binding:
+ try:
+ await asyncio.to_thread(self._record_telegram_topic_binding, source, session_entry)
+ except Exception:
+ logger.debug("Failed to record Telegram topic binding", exc_info=True)
+ return session_entry
+ stored_session_id = str(binding.get("session_id") or "")
+ bound_session_id = stored_session_id
+ # A binding pointing at a pre-compression parent is walked forward to the tip so the next
+ # message resumes the compressed child instead of reloading the oversized parent.
+ # Returns the input unchanged when the session isn't a compression parent, so this is cheap and
+ # safe. See #20470, #29712, #33414.
+ if bound_session_id and self._session_db is not None:
+ try:
+ canonical_session_id = await self._session_db.get_compression_tip(bound_session_id)
+ except Exception:
+ logger.debug("compression-tip lookup failed for %s", bound_session_id, exc_info=True)
+ canonical_session_id = bound_session_id
+ if canonical_session_id and canonical_session_id != bound_session_id:
+ bound_session_id = canonical_session_id
+ if bound_session_id and bound_session_id != session_entry.session_id:
+ # Route through SessionStore so the key → id mapping persists and the previous lane
+ # session ends cleanly (in-place mutation split-brained the JSON index). The two DB
+ # awaits above are a window for /new or /resume to move the route; the CAS on the
+ # snapshot id lets that win instead of being clobbered by a stale binding.
+ switched = await self.async_session_store.switch_session(
+ session_key, bound_session_id, expected_session_id=session_entry.session_id,
+ )
+ if switched is not None:
+ session_entry = switched
+ if bound_session_id and bound_session_id != stored_session_id:
+ # The stored binding pointed at a parent: rewrite it to the canonical descendant.
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-tip-walk",
+ )
+ return session_entry
+
+ async def _hmwa_open_session(self, session_entry, session_key, source):
+ """Consume auto-reset / fresh-reset flags and emit ``session:start`` for new sessions.
+ Returns ``(_was_auto_reset, _is_new_session)``."""
+ # Consume was_auto_reset immediately so it cannot re-fire and wipe overrides set between turns.
+ # Capture and immediately consume was_auto_reset so it does not re-fire on subsequent messages —
+ # preventing the cleanup from wiping model/reasoning overrides set between turns (Closes #48031).
+ _was_auto_reset = getattr(session_entry, "was_auto_reset", False)
+ if _was_auto_reset:
+ # Conversation boundary: the funnel clears every conversation-scoped dict; evict the cached
+ # agent so context_compressor._previous_summary cannot leak into new summaries.
+ # Treat auto-reset as a full conversation boundary — clear every conversation-scoped per-session
+ # dict in one funnel call so the fresh session does not inherit the previous conversation's
+ # model/reasoning overrides, a queued "/model switched" note, or a stale resolved-model cache
+ # (#48031, #58403). See _CONVERSATION_SCOPED_STATE.
+ self._clear_conversation_scope(session_key, reason="auto_reset")
+ self._evict_cached_agent(session_key)
+ session_entry.was_auto_reset = False
+
+ _is_fresh_reset = getattr(session_entry, "is_fresh_reset", False)
+ _is_new_session = session_entry.created_at == session_entry.updated_at or _was_auto_reset or _is_fresh_reset
+ # Consume is_fresh_reset so it doesn't leak onto later messages in the same session.
+ if _is_fresh_reset:
+ # See #6508.
+ session_entry.is_fresh_reset = False
+ if _is_new_session:
+ await self.hooks.emit("session:start", {
+ "platform": source.platform.value if source.platform else "",
+ "user_id": source.user_id,
+ "session_id": session_entry.session_id,
+ "session_key": session_key,
+ })
+ return _was_auto_reset, _is_new_session
+
+ async def _hmwa_deliver_auto_reset_notice(self, session_entry, source, turn_sidecar_notes):
+ """Stage the auto-reset sidecar note for the agent and notify the user (policy-gated)."""
+ from gateway.run import _AUTO_RESET_CONTEXT_NOTES
+ reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'suspended'
+ context_note = _AUTO_RESET_CONTEXT_NOTES.get(reset_reason, _AUTO_RESET_CONTEXT_NOTES["suspended"])
+ # Long-lived channels: point the agent at the prior same-channel session for session_search.
+ try:
+ # Returns None (appends nothing) for other platforms or when there's no prior activity to
+ # recall. Deterministic — no extra API/DB calls (#36220).
+ continuity_note = build_channel_continuity_note(session_entry, source)
+ except Exception:
+ continuity_note = None
+ if continuity_note:
+ context_note = context_note + "\n\n" + continuity_note
+ turn_sidecar_notes.append(context_note)
+
+ try:
+ should_notify = reset_reason == "suspended"
+ adapter = self._delivery_adapter_for(source) if should_notify else None
+ if adapter:
+ notice = (
+ "◐ Session reset after being stopped. "
+ f"Conversation history cleared.\n"
+ f"Use /resume to browse and restore a previous session.\n"
+ )
+ with suppress(Exception):
+ session_info = await asyncio.to_thread(self._reset_notice_session_info, source)
+ if session_info:
+ notice = f"{notice}\n\n{session_info}"
+ await adapter.send(source.chat_id, notice, metadata=self._thread_metadata_for_source(source))
+ except Exception as e:
+ logger.debug("Auto-reset notification failed (non-fatal): %s", e)
+
+ # was_auto_reset was consumed in _hmwa_open_session; only the reason needs clearing.
+ session_entry.auto_reset_reason = None
+
+ def _hmwa_auto_load_skills(self, event, _auto, _quick_key, session_key):
+ """Prepend topic/channel-bound skill payload(s) to ``event.text`` on a new session."""
+ _skill_names = [_auto] if isinstance(_auto, str) else list(_auto)
+ try:
+ from agent.skill_commands import _load_skill_payload, _build_skill_message
+ _combined_parts: list[str] = []
+ _loaded_names: list[str] = []
+ for _sname in _skill_names:
+ _loaded = _load_skill_payload(_sname, task_id=_quick_key)
+ if not _loaded:
+ logger.warning("[Gateway] Auto-skill '%s' not found", _sname)
+ continue
+ _loaded_skill, _skill_dir, _display_name = _loaded
+ _part = _build_skill_message(
+ _loaded_skill, _skill_dir,
+ f'[IMPORTANT: The "{_display_name}" skill is auto-loaded. '
+ f"Follow its instructions for this session.]",
+ )
+ if _part:
+ _combined_parts.append(_part)
+ _loaded_names.append(_sname)
+ if _combined_parts:
+ _combined_parts.append(event.text) # user's original text after the payloads
+ event.text = "\n\n".join(_combined_parts)
+ logger.info("[Gateway] Auto-loaded skill(s) %s for session %s", _loaded_names, session_key)
+ except Exception as e:
+ logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e)
+
+ async def _hmwa_acquire_turn_lease(self, _quick_key, run_generation, session_entry, _session_env_tokens):
+ """Serialize [load history → run → flush] per resolved SESSION_ID so another routing key on
+ the same session waits for the prior flush. Fail-closed on timeout (outer dispatch returns
+ a resend notice). Released in _handle_message's finally, granted per (routing key, run
+ generation) so a stale unwind can't release a newer turn's."""
+ from gateway.run import _float_env
+ _lease_registry = getattr(self, "_turn_leases", None)
+ if _lease_registry is None:
+ return
+ try:
+ _lease_token = await _lease_registry.acquire(
+ session_entry.session_id, owner_key=_quick_key, generation=run_generation,
+ timeout=_float_env("HERMES_TURN_LEASE_TIMEOUT", DEFAULT_LEASE_WAIT),
+ )
+ except TurnLeaseTimeoutError:
+ # The cleanup finally starts later; restore the tokens here or this exit leaks identity.
+ self._clear_session_env(_session_env_tokens)
+ raise
+ if _lease_token is not None:
+ self._session_state(_quick_key).turn.lease_tokens[run_generation] = _lease_token
+
+ async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes):
+ """First-ever-message onboarding note + one-time 'no home channel' prompt (both only when
+ the session has no history). Delivered on the user message (sidecar), NOT the ephemeral
+ system prompt: present-on-turn-1/absent-on-turn-2 was a guaranteed prompt diff + rebuild."""
+ from gateway.run import _hermes_home, _home_target_env_var, _load_gateway_config
+ if history:
+ return
+ if not await self.async_session_store.has_any_sessions():
+ _intro_note = (
+ "[System note: This is the user's very first message ever. "
+ "Briefly introduce yourself and mention that /help shows available commands. "
+ "Keep the introduction concise -- one or two sentences max.]"
+ )
+ # onboarding.profile_build == "ask" (default) and not yet offered: swap the plain intro for
+ # a consent-gated profile-build directive. Fires at most once.
+ try:
+ from agent.onboarding import (
+ PROFILE_BUILD_FLAG, is_seen, mark_seen, profile_build_directive,
+ profile_build_mode,
+ )
+ _onb_cfg = _load_gateway_config()
+ if profile_build_mode(_onb_cfg) == "ask" and not is_seen(_onb_cfg, PROFILE_BUILD_FLAG):
+ turn_sidecar_notes.append(profile_build_directive().strip())
+ mark_seen(_hermes_home / "config.yaml", PROFILE_BUILD_FLAG)
+ else:
+ turn_sidecar_notes.append(_intro_note)
+ except Exception as _pb_err:
+ logger.debug("Profile-build onboarding directive failed, using plain intro: %s", _pb_err)
+ turn_sidecar_notes.append(_intro_note)
+
+ # One-time prompt if no home channel is set (webhooks deliver to configured targets instead).
+ if not source.platform or source.platform in (Platform.LOCAL, Platform.WEBHOOK):
+ return
+ platform_name = source.platform.value
+ env_key = _home_target_env_var(platform_name)
+ # Multiplex: the home channel may live only in the profile secret scope, not os.environ.
+ home_env = ""
+ if env_key:
+ # A secondary with no home channel must not borrow the default profile's from
+ # os.environ; only an UNSCOPED single-profile read may fall back to the process env.
+ from agent.secret_scope import UnscopedSecretError, get_secret
+ try:
+ home_env = (get_secret(env_key) or "").strip()
+ except UnscopedSecretError:
+ home_env = (os.getenv(env_key) or "").strip()
+ except Exception:
+ home_env = ""
+ # Also honor in-memory / yaml home_channel on this platform.
+ with suppress(Exception):
+ if not home_env and self.config.get_home_channel(source.platform):
+ home_env = "set"
+ # Secondary-profile platforms may only exist under that profile's config — re-read in scope.
+ if not home_env:
+ with suppress(Exception):
+ from gateway.config import load_gateway_config as _lgc
+ prof = (getattr(source, "profile", None) or "").strip()
+ if prof and prof != "default" and _lgc().get_home_channel(source.platform):
+ home_env = "set"
+ if not home_env:
+ # Slack routes every command through the parent `/hermes`; bare `/sethome` would fail.
+ sethome_cmd = "/hermes sethome" if source.platform == Platform.SLACK else "/sethome"
+ await self._deliver_platform_notice(
+ source, f"📬 No home channel is set for {platform_name.title()}. "
+ f"A home channel is where Hermes delivers cron job results and cross-platform "
+ f"messages.\n\nType {sethome_cmd} to make this chat your home channel, or ignore "
+ f"to skip.",
+ )
+
+ def _hmwa_apply_message_timestamp(self, event, message_text):
+ """Capture the platform event time as message metadata and keep the persisted transcript
+ clean — strip any leading timestamp prefix and the Discord triggering-message note (a
+ model instruction, not authored text) — regardless of the toggle; only the in-context
+ RENDER is gated behind gateway.message_timestamps.enabled (default OFF)."""
+ from gateway.run import _load_gateway_config, _message_timestamps_enabled
+ from gateway.run_inbound import strip_discord_triggering_note
+ persist_user_message = None
+ persist_user_timestamp = None
+ try:
+ from hermes_time import get_timezone as _get_evt_tz
+ from gateway.message_timestamps import (
+ coerce_message_timestamp as _coerce_msg_ts,
+ render_user_content_with_timestamp as _render_msg_ts,
+ strip_leading_message_timestamps as _strip_msg_ts,
+ )
+ _evt_tz = _get_evt_tz()
+ if message_text and isinstance(message_text, str):
+ _clean_message_text, _embedded_ts = _strip_msg_ts(message_text, tz=_evt_tz)
+ persist_user_message = strip_discord_triggering_note(event, _clean_message_text)
+ _event_epoch = _coerce_msg_ts(getattr(event, "timestamp", None), tz=_evt_tz)
+ persist_user_timestamp = _event_epoch if _event_epoch is not None else _embedded_ts
+ if _message_timestamps_enabled(_load_gateway_config()):
+ message_text = _render_msg_ts(_clean_message_text, persist_user_timestamp, tz=_evt_tz)
+ else:
+ # Toggle off: the model sees the clean message; timestamp stored for later opt-in.
+ message_text = _clean_message_text
+ except Exception as _ts_err:
+ logger.debug("Message timestamp injection failed (non-fatal): %s", _ts_err)
+ return message_text, persist_user_message, persist_user_timestamp
+
+ @dataclasses.dataclass
+ class _PreparedTurn:
+ """Inputs to the agent run assembled by ``_hmwa_prepare_turn``."""
+
+ history: Any
+ context_prompt: str
+ message_text: Any
+ persist_user_message: Any
+ persist_user_timestamp: Any
+ persist_user_display_kind: Optional[str]
+ persistence_session_id: Optional[str] = None
+ persistence_owner: Optional[str] = None
+
+ async def _hmwa_prepare_turn(self, event, source, session_entry, session_key, _quick_key, run_generation):
+ """Everything between session resolution and the agent run: session open, task-local env,
+ context prompt, sidecar notes, turn lease, transcript load + hygiene, inbound text. Returns
+ ``(_PreparedTurn, env_tokens)``; a ``str`` first element is a reply to send instead of
+ running (history unreadable); ``None`` drops the turn (inbound text rejected)."""
+ from gateway.run import _load_gateway_config
+ _was_auto_reset, _is_new_session = await self._hmwa_open_session(session_entry, session_key, source)
+ context = build_session_context(source, self.config, session_entry)
+ # Session context variables for tools (task-local, concurrency-safe)
+ _session_env_tokens = self._set_session_env(context)
+ # Self-injected turns (MessageEvent(internal=True)) persist with a DB-only display_kind so
+ # UIs render timeline notices, not user bubbles; role/content untouched.
+ from gateway.response_filters import display_kind_for_event
+ persist_user_display_kind = display_kind_for_event(event)
+ _redact_pii = False # privacy.redact_pii, re-read per message
+ with suppress(Exception):
+ _redact_pii = bool((_load_gateway_config().get("privacy") or {}).get("redact_pii", False))
+
+ # The context prompt render is pinned per session, keyed by a hash of the renderer inputs, so
+ # the system prompt cannot drift turn-over-turn; a miss (thread rename, /sethome) re-renders.
+ context_prompt = self._pinned_session_context_prompt(context, _redact_pii, session_key)
+
+ # Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt
+ # (appending to the ephemeral system prompt forced a full agent rebuild).
+ turn_sidecar_notes: List[str] = []
+ if _was_auto_reset:
+ await self._hmwa_deliver_auto_reset_notice(session_entry, source, turn_sidecar_notes)
+
+ # Auto-load bound skill(s) only on NEW sessions; ongoing ones carry the content in history.
+ _auto = getattr(event, "auto_skill", None)
+ if _is_new_session and _auto:
+ self._hmwa_auto_load_skills(event, _auto, _quick_key, session_key)
+
+ await self._hmwa_acquire_turn_lease(_quick_key, run_generation, session_entry, _session_env_tokens)
+
+ # A turn becomes durable recovery work only after it owns the per-session lease; marking
+ # earlier would falsely recover a message that never began processing.
+ await self._mark_durable_active_turn(event, session_entry.session_key)
+
+ # An unreadable store is not an empty conversation: stop before the agent invents continuity
+ # from []. Restore task-local context here (before the broad cleanup finally).
+ try:
+ history = await self.async_session_store.load_transcript(session_entry.session_id)
+ history = await self._hmwa_run_session_hygiene(
+ event, source, session_entry, session_key, history, _quick_key, run_generation,
+ )
+ except TranscriptReadError:
+ self._clear_session_env(_session_env_tokens)
+ return (
+ "⚠️ This session's history is temporarily unavailable, so this message was not "
+ "processed. Ask the operator to inspect state.db, then resend after it is healthy. "
+ "Use /reset only if you intentionally want to start a new conversation."
+ ), _session_env_tokens
+
+ await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes)
+
+ # Voice channel state rides the user message ONLY when changed (in the system prompt it
+ # forced a rebuild + prompt-cache re-key per message).
+ _vc_note = self._voice_channel_sidecar_note(event, source, session_key)
+ if _vc_note:
+ turn_sidecar_notes.append(_vc_note)
+
+ # Auto-analyze user images so the model gets a description plus the local path.
+ message_text = await self._prepare_profile_scoped_inbound_message_text(
+ event=event, source=source, history=history, session_key=session_key,
+ )
+ if message_text is None:
+ return None, _session_env_tokens
+
+ message_text, persist_user_message, persist_user_timestamp = (
+ self._hmwa_apply_message_timestamp(event, message_text)
+ )
+
+ # Stage the notes (one-shot; consumed in run_sync) AFTER the early-out so an aborted turn
+ # cannot leak them into the next turn.
+ if turn_sidecar_notes and session_key:
+ self._set_pending_turn_sidecar_notes(session_key, turn_sidecar_notes)
+
+ # Bind this run generation to the adapter so deferred post-delivery callbacks are released
+ # by the run that registered them.
+ self._bind_adapter_run_generation(self._delivery_adapter_for(source), session_key, run_generation)
+ # Delivery IDs are only unique in their transport namespace. Keyless turns
+ # need their own identity, even when another process writes to this session.
+ import uuid
+ namespace = [source.platform.value, source.profile, source.scope_id,
+ source.chat_id, source.thread_id, str(event.message_id)]
+ owner = (str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(namespace)))
+ if event.message_id else str(uuid.uuid4()))
+ return self._PreparedTurn(
+ history, context_prompt, message_text, persist_user_message, persist_user_timestamp,
+ persist_user_display_kind, session_entry.session_id, owner,
+ ), _session_env_tokens
diff --cc gateway/status.py
index 7b7f0cc40a5,4a1df50be5b..574ffab8f81
--- a/gateway/status.py
+++ b/gateway/status.py
@@@ -1396,15 -1426,13 +1404,18 @@@ def get_runtime_status_running_pid
pid = _live_pid_from_record(payload)
if pid is None:
return None
+ # A record we wrote ourselves earlier in this boot (the multiplex verdict is persisted before
+ # the PID claim) is not a rival gateway; reporting it made a restart over a SIGKILLed owner
+ # lose the "PID file race" to its own process and skip the stale gateway.pid cleanup.
+ if pid == os.getpid():
+ return None
- # Active-profile context: the record's hermes_home must match this process so a stale record
- # cannot lend another profile's identity.
+ # The record's hermes_home must match the home asked about (this process unscoped) so a stale
+ # or copied record cannot lend another home's gateway identity; legacy records without the
+ # stamp prove nothing either way and fall through to the live command-line check.
if expected_home is None and not _pid_record_belongs_to_current_profile(payload):
return None
+ if expected_home is not None and recorded_gateway_home_conflicts(payload, expected_home=expected_home):
+ return None
if not _record_matches_live_gateway_pid(payload, pid, expected_home=expected_home):
return None
return pid
diff --cc hermes_cli/dashboard_auth/ws_tickets.py
index 313d3e76933,65391ae239f..09c55b481fd
--- a/hermes_cli/dashboard_auth/ws_tickets.py
+++ b/hermes_cli/dashboard_auth/ws_tickets.py
@@@ -33,13 -33,13 +33,16 @@@ class TicketInvalid(Exception)
"""Ticket missing, expired, or already consumed."""
- def mint_ticket(*, user_id: str, provider: str, issuer: str = "") -> str:
-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:
"""One-shot base64url ticket (32 random bytes) bound to this identity; ``consume_ticket``
- hands the ``info`` dict back to the WS handler."""
+ hands the ``info`` dict back to the WS handler. ``extra`` rides along for routes that need
+ server-chosen context (the Bot Desktop bridge pins the RFB socket's profile home here so a
+ client can never pick another profile's screen)."""
ticket = secrets.token_urlsafe(32)
- info = {"user_id": user_id, "provider": provider, "minted_at": int(time.time())}
+ info = {"user_id": user_id, "provider": provider, "minted_at": int(time.time()), **(extra or {})}
+ if issuer:
+ info["issuer"] = issuer
with _lock:
_tickets[ticket] = (int(time.time()) + TTL_SECONDS, info)
_gc_expired_locked()
diff --cc hermes_cli/web_routers/chat_workspaces.py
index 00000000000,fc63eb35562..d8e3c4078b1
mode 000000,100644..100644
--- a/hermes_cli/web_routers/chat_workspaces.py
+++ b/hermes_cli/web_routers/chat_workspaces.py
@@@ -1,0 -1,69 +1,77 @@@
+ """Chat workspace picker: which host directories a NEW dashboard chat can start in.
+
+ The dashboard's ``/chat`` tab used to spawn every fresh TUI in the dashboard process's own
+ launch directory, so from a phone or browser there was no way to say "work in ~/code/foo".
+ This lists the same projects and discovered repositories the Desktop sidebar shows (the
+ per-profile ``projects.db`` plus session-derived and scanned git roots) so the SPA can offer
+ a picker, and ``/api/pty?cwd=`` (``chat_ws``) honours the choice.
+ """
+
+ from __future__ import annotations
+
+ import os
+ from pathlib import Path
+ from typing import Optional
+
+ from fastapi import APIRouter, HTTPException
+
+ from hermes_cli.web_deps import late
+ from hermes_cli.web_routers._common import http_failure, scoped_to_thread
+
+ router = APIRouter()
+
+ _open_session_db_for_profile = late("_open_session_db_for_profile", "hermes_cli.web_server_sessions")
+
+
+ def resolve_chat_cwd(raw: Optional[str]) -> Optional[str]:
+ """Validate a ``?cwd=`` for a fresh chat: an existing host directory, or None when unset.
+
+ A dead or relative path fails closed (400) instead of silently falling back to the launch
+ dir — the user picked a workspace and would otherwise get a session in the wrong place.
+ """
+ text = (raw or "").strip()
+ if not text:
+ return None
+ resolved = os.path.abspath(os.path.expanduser(text))
+ if not os.path.isdir(resolved):
+ raise HTTPException(status_code=400, detail=f"Working directory does not exist: {text}")
+ return resolved
+
+
+ def _collect_workspaces(profile: Optional[str], scan: bool) -> dict:
+ # The dashboard hosts the in-process gateway (``web_server`` imports ``tui_gateway.server``
+ # at startup), so the sidebar's repo-discovery helpers are already bound there.
+ import tui_gateway.server as gateway
+ from hermes_cli import projects_db as pdb
+
- db = _open_session_db_for_profile(profile, read_only=True)
++ # Browsing never bootstraps the owner's session store: a profile whose gateway has not
++ # yet initialized state.db simply contributes no session-derived roots (``db=None``).
++ try:
++ db = _open_session_db_for_profile(profile, read_only=True)
++ except HTTPException as exc:
++ if exc.status_code != 503:
++ raise
++ db = None
+ try:
+ with pdb.connect_closing() as conn:
+ policy = gateway._repo_discovery_policy()
+ if scan and policy["enabled"]:
+ gateway._scan_discovered_repos_remote(conn, policy)
+ projects = [p.to_dict() for p in pdb.list_projects(conn)]
+ repos = gateway._discover_repos_payload(
+ db, conn=conn, backfill=False, include_cached=policy["enabled"])
+ finally:
- db.close()
++ if db is not None:
++ db.close()
+ default_cwd = gateway._completion_cwd({"profile": profile} if profile else {})
+ return {
+ "projects": projects, "repos": repos, "default_cwd": default_cwd,
+ "home": str(Path.home()), "scan_enabled": bool(policy["enabled"])}
+
+
+ @router.get("/api/chat/workspaces")
+ async def get_chat_workspaces(profile: Optional[str] = None, scan: bool = False):
+ """Projects + discovered repos a fresh chat may start in; ``scan=1`` rescans the
+ configured discovery roots on the host first (headless installs have no Desktop to do it)."""
+ with http_failure("GET /api/chat/workspaces failed", 500, "Failed to list workspaces"):
+ return await scoped_to_thread(profile, lambda: _collect_workspaces(profile, scan))
diff --cc tests/cron/test_codex_execution_paths.py
index 6cd4e71089c,3172958c2d1..ae97f6883ea
--- a/tests/cron/test_codex_execution_paths.py
+++ b/tests/cron/test_codex_execution_paths.py
@@@ -9,56 -7,10 +9,53 @@@ sys.modules.setdefault("fire", types.Si
sys.modules.setdefault("firecrawl", types.SimpleNamespace(Firecrawl=object))
sys.modules.setdefault("fal_client", types.SimpleNamespace())
- import gateway.run as gateway_run
-import cron.scheduler as cron_scheduler
import run_agent
- from gateway.config import Platform
- from gateway.session import SessionSource
+def _run_owned_job(job, tmp_path):
+ """Exercise the production owner bridge with an isolated canonical store."""
+ from gateway.session_contract import SessionRef
+ from gateway.session_cron import current_execution, execute
+ from hermes_state_registry import acquire, release
+
+ ref = SessionRef("test-profile", "cron-owner-session")
+ admission_id = "cron-owner-admission"
+ request_id = "cron-owner-request"
+ db = acquire(tmp_path / "state.db")
+ db.create_session(ref.session_id, source="cron")
+ authority = SimpleNamespace(
+ db=db,
+ sessions={ref.session_id: SimpleNamespace(source=SimpleNamespace(user_id="cron-owner"))},
+ pending_results={},
+ )
+ row = {
+ "admission_id": admission_id, "request_id": request_id,
+ "principal_id": "cron-owner", "payload": {"text": ""},
+ }
+ policy = SimpleNamespace(request_json=json.dumps({
+ "cron_job": job, "extra_prompt": None, "request_id": request_id,
+ }))
+
+ async def run():
+ previous = current_execution()
+ try:
+ await execute(authority, ref, row, policy)
+ except RuntimeError as exc:
+ # Failed scheduler tuples are published before execute raises.
+ saved = authority.pending_results.get(admission_id)
+ if saved is None:
+ raise
+ assert str(exc) == saved["result"]["cron_result"][3]
+ assert current_execution() is previous
+ assert authority._cron_cancellations == {}
+ return tuple(authority.pending_results[admission_id]["result"]["cron_result"])
+
+ try:
+ return asyncio.run(run())
+ finally:
+ release(db)
+
+
def _patch_agent_bootstrap(monkeypatch):
monkeypatch.setattr(
"model_tools.get_tool_definitions",
diff --cc tests/cron/test_cron_empty_payload.py
index 4c28b99463c,cb62bf2f14f..54a5ae719f4
--- a/tests/cron/test_cron_empty_payload.py
+++ b/tests/cron/test_cron_empty_payload.py
@@@ -288,23 -273,9 +273,9 @@@ def test_run_job_fails_closed_and_never
assert "auto-paused" in final
- def test_run_job_pauses_the_job_on_disk(hermes_env, cron_owner):
- """Fail-closed isn't enough — the job must stop being scheduled."""
- import cron.scheduler as scheduler
- from cron.jobs import get_job
-
- job = _legacy_empty_job(hermes_env)
-
- scheduler.run_job(job)
-
- stored = get_job(job["id"])
- assert stored["enabled"] is False
- assert stored["state"] == "paused"
- assert "nothing to run" in (stored["paused_reason"] or "")
- assert stored["paused_at"]
-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_job
returns. That must not undo the pause, or the job re-fires every tick."""
import cron.scheduler as scheduler
diff --cc tests/cron/test_scheduler.py
index a7c41f205ba,8fa216b0989..7f485953565
--- a/tests/cron/test_scheduler.py
+++ b/tests/cron/test_scheduler.py
@@@ -5,9 -4,7 +5,8 @@@ import contextli
import contextvars
import itertools
import json
- import logging
import os
+from types import SimpleNamespace
from unittest.mock import AsyncMock, patch, MagicMock
import pytest
@@@ -24,55 -21,9 +23,54 @@@ from cron.scheduler import
)
from cron.scheduler_delivery import _resolve_origin, _send_media_via_adapter
from tools.env_passthrough import clear_env_passthrough
- from tools.credential_files import clear_credential_files
+def _run_owned_job(job, tmp_path, db=None):
+ """Run the production owner bridge, preserving each test's agent/DB probes."""
+ from gateway.session_contract import SessionRef
+ from gateway.session_cron import current_execution, execute
+ from hermes_state_registry import acquire, release
+
+ ref = SessionRef("test-profile", "canonical-cron-session")
+ admission_id = "cron-owner-admission"
+ request_id = "cron-owner-request"
+ owns_db = db is None
+ if owns_db:
+ db = acquire(tmp_path / "state.db")
+ db.create_session(ref.session_id, source="cron")
+ else:
+ db.db_path = str(tmp_path / "state.db")
+ authority = SimpleNamespace(
+ db=db,
+ sessions={ref.session_id: SimpleNamespace(source=SimpleNamespace(user_id="cron-owner"))},
+ pending_results={},
+ )
+ row = {
+ "admission_id": admission_id, "request_id": request_id,
+ "principal_id": "cron-owner", "payload": {"text": ""},
+ }
+ policy = SimpleNamespace(request_json=json.dumps({
+ "cron_job": job, "extra_prompt": None, "request_id": request_id,
+ }))
+
+ async def run():
+ previous = current_execution()
+ try:
+ await execute(authority, ref, row, policy)
+ except RuntimeError as exc:
+ saved = authority.pending_results.get(admission_id)
+ if saved is None:
+ raise
+ assert str(exc) == saved["result"]["cron_result"][3]
+ assert current_execution() is previous
+ assert authority._cron_cancellations == {}
+ return tuple(authority.pending_results[admission_id]["result"]["cron_result"])
+
+ try:
+ return asyncio.run(run())
+ finally:
+ if owns_db:
+ release(db)
def test_cron_cleanup_worker_inherits_caller_contextvars():
"""Profile-scoped secrets must remain visible during threaded cleanup."""
profile_scope = contextvars.ContextVar("test_cron_cleanup_profile_scope")
@@@ -1554,22 -1396,9 +1412,9 @@@ class TestSilentDelivery
patch("cron.scheduler.claim_job_for_fire", return_value=True), \
patch("cron.scheduler.run_job", return_value=(True, "# output", "[SILENT]", None)), \
patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
- patch("cron.scheduler._deliver_result") as deliver_mock, \
+ patch("cron.delivery_queue.enqueue", return_value={"status": "queued"}) as deliver_mock, \
patch("cron.scheduler.mark_job_run"):
from cron.scheduler import tick
- with caplog.at_level(logging.INFO, logger="cron.scheduler"):
- tick(verbose=False)
- deliver_mock.assert_not_called()
- assert any(SILENT_MARKER in r.message for r in caplog.records)
-
- def test_silent_with_note_suppresses_delivery(self):
- with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \
- patch("cron.scheduler.claim_job_for_fire", return_value=True), \
- patch("cron.scheduler.run_job", return_value=(True, "# output", "[SILENT] No changes detected", None)), \
- patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
- patch("cron.delivery_queue.enqueue", return_value={"status": "queued"}) as deliver_mock, \
- patch("cron.scheduler.mark_job_run"):
- from cron.scheduler import tick
tick(verbose=False)
deliver_mock.assert_not_called()
@@@ -1663,14 -1493,8 +1509,9 @@@
tick(verbose=False)
deliver_mock.assert_not_called()
+ assert mark_mock.call_args.kwargs["execution_id"]
- mark_mock.assert_called_once_with(
- "monitor-job",
- False,
- "Agent completed but produced empty response (model error, timeout, or misconfiguration)",
- delivery_error=None,
- execution_id=mark_mock.call_args.kwargs["execution_id"],
- )
+ mark_mock.assert_called_once()
+ assert mark_mock.call_args[0][:2] == ("monitor-job", False)
class TestOneShotDispatchClaim:
@@@ -1818,10 -1609,9 +1626,9 @@@ class TestRunJobWakeGate
assert success is True
assert err is None
assert final == SILENT_MARKER
- assert "Script gate returned `wakeAgent=false`" in doc
agent_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 is
invoked and the data line still shows up in the prompt."""
import cron.scheduler as scheduler
diff --cc tests/cron/test_sessiondb_init_hang.py
index c2884f46218,2189d15407b..0cb9780c4f4
--- a/tests/cron/test_sessiondb_init_hang.py
+++ b/tests/cron/test_sessiondb_init_hang.py
@@@ -7,186 -23,335 +7,160 @@@ local writer or an agent without persis
import concurrent.futures
import threading
import time
+from types import SimpleNamespace
from unittest.mock import MagicMock, patch
-from cron.scheduler import run_job
-
-# Hold the real class: patching cron.scheduler.concurrent.futures.ThreadPoolExecutor
-# also replaces concurrent.futures.ThreadPoolExecutor (same module object).
-_REAL_TPE = concurrent.futures.ThreadPoolExecutor
-
-_RUNTIME = {
- "api_key": "test-key",
- "base_url": "https://example.invalid/v1",
- "provider": "openrouter",
- "api_mode": "chat_completions",
-}
-
-
-def _session_db_executor(timeouts: list, *, instant_timeout: bool = True):
- """Wrap ``ThreadPoolExecutor`` so SessionDB's ``result(timeout=...)`` is observable.
-
- ``run_job`` is the only caller that passes a timeout to ``Future.result`` on
- this path (``submit(SessionDB).result(timeout=...)``). Other pools used by
- ``tick`` / the agent inactivity watchdog call ``result()`` with no timeout
- and are left alone. When ``instant_timeout`` is True, the timed wait raises
- immediately instead of sleeping — the production hang path without a clock.
- """
-
- def factory(max_workers=1, *args, **kwargs):
- real = _REAL_TPE(max_workers=max_workers)
- orig_submit = real.submit
-
- def submit(fn, *a, **k):
- fut = orig_submit(fn, *a, **k)
- orig_result = fut.result
-
- def result(*ra, **rk):
- timeout = ra[0] if ra else rk.get("timeout")
- if timeout is not None:
- timeouts.append(timeout)
- if instant_timeout:
- raise concurrent.futures.TimeoutError()
- return orig_result(*ra, **rk)
-
- fut.result = result
- return fut
-
- real.submit = submit
- return real
-
- return factory
-
-
-class TestSessionDbInitTimeout:
- def test_sessiondb_init_preserves_multiplex_profile_context(
- self, tmp_path, monkeypatch
- ):
- """The timeout worker must construct SessionDB under the active profile."""
- from hermes_constants import (
- get_hermes_home,
- reset_hermes_home_override,
- set_hermes_home_override,
- )
-
- default_home = tmp_path / "default"
- profile_home = tmp_path / "profiles" / "jobsearch"
- monkeypatch.setenv("HERMES_HOME", str(default_home))
- observed_homes = []
- fake_db = MagicMock()
-
- def make_session_db(*args, **kwargs):
- observed_homes.append(get_hermes_home())
- return fake_db
-
- job = {"id": "profile-sessiondb", "name": "test", "prompt": "hello"}
- profile_token = set_hermes_home_override(profile_home)
+import pytest
+
+from cron import scheduler
+from gateway import session_cron
+
+
+def owner_run(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ db = MagicMock(db_path=tmp_path / "state.db")
+ db.get_compression_tip.return_value = None
+ owner = SimpleNamespace(db=db)
+ job = {"id": "owner-db", "name": "test", "prompt": "hello"}
+ execution_id = "owner-fire"
+ token = session_cron._execution.set((owner, "owner-session", job["id"], execution_id))
+ monkeypatch.setattr(scheduler, "_hermes_home", tmp_path)
+ monkeypatch.setattr(scheduler, "_reload_dotenv_and_publish_delivery_target", lambda *_: None)
+ monkeypatch.setattr(scheduler, "_resolve_cron_agent_setup", lambda *_: scheduler._CronAgentSetup(
+ model="test", runtime={"provider": "test"}))
+ with patch("run_agent.AIAgent") as agent_cls:
+ agent_cls.return_value.run_conversation.return_value = {"final_response": "ok"}
try:
- with patch("cron.scheduler._hermes_home", None), \
- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \
- patch("hermes_cli.env_loader.load_hermes_dotenv"), \
- patch("hermes_cli.env_loader.reset_secret_source_cache"), \
- patch("hermes_state_registry.acquire", side_effect=make_session_db), \
- patch(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- return_value=_RUNTIME,
- ), \
- patch("run_agent.AIAgent") as mock_agent_cls:
- mock_agent = MagicMock()
- mock_agent.run_conversation.return_value = {"final_response": "ok"}
- mock_agent_cls.return_value = mock_agent
-
- success, _output, final_response, error = run_job(job)
+ yield owner, job, execution_id, agent_cls
finally:
- reset_hermes_home_override(profile_token)
-
- assert success is True
- assert error is None
- assert final_response == "ok"
- assert observed_homes == [profile_home]
-
- def test_run_job_does_not_hang_when_sessiondb_init_wedges(self, tmp_path, monkeypatch):
- """run_job proceeds without a session store when SessionDB init times out."""
- monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.2")
- job = {"id": "wedged-sessiondb", "name": "test", "prompt": "hello"}
- timeouts: list = []
-
- with patch("cron.scheduler._hermes_home", tmp_path), \
- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \
- patch("hermes_cli.env_loader.load_hermes_dotenv"), \
- patch("hermes_cli.env_loader.reset_secret_source_cache"), \
- patch("hermes_state_registry.acquire"), \
- patch(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- return_value=_RUNTIME,
- ), \
- patch("run_agent.AIAgent") as mock_agent_cls, \
- patch(
- "cron.scheduler.concurrent.futures.ThreadPoolExecutor",
- side_effect=_session_db_executor(timeouts),
- ):
- mock_agent = MagicMock()
- mock_agent.run_conversation.return_value = {"final_response": "ok"}
- mock_agent_cls.return_value = mock_agent
-
- success, output, final_response, error = run_job(job)
-
- # Env-resolved bound was passed to Future.result — not the 10s default,
- # and not an unbounded call.
- assert timeouts == [0.2]
- assert success is True
- assert final_response == "ok"
- assert mock_agent_cls.call_args.kwargs["session_db"] is None
-
-
- def test_timeout_resolved_from_config_yaml(self, tmp_path, monkeypatch):
- """cron.session_db_timeout_seconds in config.yaml is respected when
- the env var is not set — the canonical config-first resolution path."""
- import yaml
-
+ session_cron._execution.reset(token)
+
+
+def test_sessiondb_init_preserves_multiplex_profile_context(owner_run, tmp_path):
+ from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override
+
+ owner, job, execution_id, agent_cls = owner_run
+ profile_home = tmp_path / "profiles" / "jobsearch"
+ owner.db.db_path = profile_home / "state.db"
+ observed = []
+
+ def acquire(path):
+ observed.append((path, get_hermes_home()))
+ return owner.db
+
+ token = set_hermes_home_override(profile_home)
+ try:
+ with patch("hermes_state_registry.acquire", side_effect=acquire):
+ success, _, response, error = scheduler.run_job(job, execution_id=execution_id)
+ finally:
+ reset_hermes_home_override(token)
+ assert (success, response, error) == (True, "ok", None)
+ assert observed == [(profile_home / "state.db", profile_home)]
+ assert agent_cls.call_args.kwargs["session_db"] is owner.db
+
+
[email protected]("setting", ["env", "config"])
+def test_run_job_does_not_hang_when_sessiondb_init_wedges(owner_run, tmp_path, monkeypatch, setting):
+ owner, job, execution_id, agent_cls = owner_run
+ if setting == "env":
+ monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.02")
+ else:
monkeypatch.delenv("HERMES_CRON_SESSION_DB_TIMEOUT", raising=False)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- (tmp_path / "config.yaml").write_text(
- yaml.safe_dump({"cron": {"session_db_timeout_seconds": 0.2}})
- )
- job = {"id": "config-timeout", "name": "test", "prompt": "hello"}
- timeouts: list = []
-
- with patch("cron.scheduler._hermes_home", tmp_path), \
- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \
- patch("hermes_cli.env_loader.load_hermes_dotenv"), \
- patch("hermes_cli.env_loader.reset_secret_source_cache"), \
- patch("hermes_state_registry.acquire"), \
- patch(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- return_value=_RUNTIME,
- ), \
- patch("run_agent.AIAgent") as mock_agent_cls, \
- patch(
- "cron.scheduler.concurrent.futures.ThreadPoolExecutor",
- side_effect=_session_db_executor(timeouts),
- ):
- mock_agent = MagicMock()
- mock_agent.run_conversation.return_value = {"final_response": "ok"}
- mock_agent_cls.return_value = mock_agent
-
- success, output, final_response, error = run_job(job)
-
- # Config value was passed through — not the 10s default.
- assert timeouts == [0.2]
- assert success is True
- assert mock_agent_cls.call_args.kwargs["session_db"] is None
-
-
-class TestDispatchGuardReleasedAfterHang:
- """End-to-end: the real bug symptom was every later tick silently
- skipping the job forever. Confirm the fix actually clears that path."""
-
- def test_guard_is_released_and_job_refires_after_sessiondb_hang(self, tmp_path, monkeypatch):
- import cron.scheduler as sched
-
- monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.2")
- sched._parallel_pools.clear()
- sched._parallel_pool_max_workers.clear()
- sched._running_job_ids.clear()
-
- job = {
- "id": "guard-sessiondb-hang",
- "name": "guard-sessiondb-hang",
- "prompt": "hello",
- "schedule": "every 5m",
- "enabled": True,
- "next_run_at": "2020-01-01T00:00:00",
- "deliver": "local",
- }
- timeouts: list = []
-
+ (tmp_path / "config.yaml").write_text("cron:\n session_db_timeout_seconds: 0.02\n")
+ entered, release, closed = threading.Event(), threading.Event(), threading.Event()
+ owner.db.close.side_effect = closed.set
+
+ def acquire(_path):
+ entered.set()
+ release.wait(10)
+ return owner.db
+
+ try:
+ with patch("hermes_state_registry.acquire", side_effect=acquire):
+ started = time.monotonic()
+ success, _, response, error = scheduler.run_job(job, execution_id=execution_id)
+ elapsed = time.monotonic() - started
+ assert entered.is_set()
+ assert elapsed < 5
+ assert not success and response == "" and error and "TimeoutError" in error
+ agent_cls.assert_not_called()
+ owner.db.close.assert_not_called()
+ release.set()
+ assert closed.wait(5), "late borrowed reference was leaked"
+ owner.db.close.assert_called_once()
+ finally:
+ release.set()
+ assert closed.wait(5)
+
+
[email protected]("failure", ["wrong-store", "acquire-error"])
+def test_owner_store_failure_never_runs_unpersisted_agent(owner_run, failure):
+ owner, job, execution_id, agent_cls = owner_run
+ wrong_db = MagicMock()
+ with patch("hermes_state_registry.acquire", return_value=wrong_db,
+ side_effect=OSError("store unavailable") if failure == "acquire-error" else None):
+ success, _, response, error = scheduler.run_job(job, execution_id=execution_id)
+ assert not success and response == ""
+ assert error and ("canonical owner store" if failure == "wrong-store" else "store unavailable") in error
+ agent_cls.assert_not_called()
+ owner.db.close.assert_not_called()
+ assert wrong_db.close.call_count == (1 if failure == "wrong-store" else 0)
+
+
- def test_invalid_timeout_env_falls_back_to_default(owner_run, monkeypatch, caplog):
- owner, job, _, _ = owner_run
- monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "not-a-number")
- future = concurrent.futures.Future()
- future.set_result(owner.db)
- with patch("cron.scheduler.concurrent.futures.ThreadPoolExecutor") as pool:
- pool.return_value.submit.return_value = future
- with patch.object(future, "result", wraps=future.result) as result:
- assert scheduler._open_cron_session_db(job) is owner.db
- assert result.call_args.kwargs["timeout"] == 10.0
- assert any("HERMES_CRON_SESSION_DB_TIMEOUT" in r.message and "not-a-number" in r.message
- for r in caplog.records)
-
-
+def test_guard_is_released_and_job_refires_after_sessiondb_hang(owner_run, monkeypatch):
+ owner, job, _, agent_cls = owner_run
+ monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.02")
+ from cron import jobs
+
+ release = threading.Event()
+ closed = threading.Event()
+ owner.db.close.side_effect = closed.set
+ calls = []
+
+ def acquire(_path):
+ calls.append(True)
+ if len(calls) == 1:
+ release.wait(10)
+ return owner.db
+
+ # The scheduler dispatches through the authority; emulate only transport and
+ # execution admission, retaining the real guard and run_job lifecycle.
+ def admitted(fired, **kwargs):
+ token = session_cron._execution.set((owner, "owner-session", fired["id"], kwargs["execution_id"]))
try:
- with patch("cron.scheduler._hermes_home", tmp_path), \
- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \
- patch("hermes_cli.env_loader.load_hermes_dotenv"), \
- patch("hermes_cli.env_loader.reset_secret_source_cache"), \
- patch("hermes_state_registry.acquire"), \
- patch(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- return_value=_RUNTIME,
- ), \
- patch("run_agent.AIAgent") as mock_agent_cls, \
- patch(
- "cron.scheduler.concurrent.futures.ThreadPoolExecutor",
- side_effect=_session_db_executor(timeouts),
- ), \
- patch.object(sched, "get_due_jobs", return_value=[job]), \
- patch.object(sched, "claim_job_for_fire", return_value=True), \
- patch.object(sched, "save_job_output", return_value="/tmp/out"), \
- patch.object(sched, "mark_job_run"), \
- patch.object(sched, "_deliver_result", return_value=None):
- mock_agent = MagicMock()
- mock_agent.run_conversation.return_value = {"final_response": "ok"}
- mock_agent_cls.return_value = mock_agent
-
- n = sched.tick(verbose=False) # sync=True by default: waits for the job
- assert n == 1
- assert timeouts == [0.2]
-
- # Without the fix this would still contain the job ID forever.
- assert "guard-sessiondb-hang" not in sched.get_running_job_ids()
-
- # A second tick can dispatch the same job again — before the
- # fix this would log "already running — skipping" and
- # return 0.
- n2 = sched.tick(verbose=False)
- assert n2 == 1
+ return scheduler.run_job(fired, **kwargs)
finally:
- sched._running_job_ids.discard(sched._inflight_key("guard-sessiondb-hang"))
- sched._shutdown_parallel_pool()
-
-
-# ===========================================================================
-# Bug #72782: late SessionDB result leaks FDs after timeout abandonment
-# ===========================================================================
-
-
-
-class TestLateSessionDbClosedAfterTimeout:
- """End-to-end: when SessionDB init times out but later completes inside the
- abandoned worker, the orphaned result must be closed (#72782)."""
-
- def test_late_session_db_result_is_closed(self, tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.2")
- never_set = threading.Event()
- late_db_holder = [] # captures the SessionDB returned by the late init
-
- def _hanging_then_capture():
- never_set.wait(timeout=30)
- db = MagicMock()
- late_db_holder.append(db)
- return db
-
- job = {"id": "late-close-test", "name": "test", "prompt": "hello"}
+ session_cron._execution.reset(token)
+ with jobs.use_cron_store(owner.db.db_path.parent):
+ saved = jobs.create_job(prompt="hello", schedule="every 5m", deliver="local")
try:
- with patch("cron.scheduler._hermes_home", tmp_path), \
- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \
- patch("hermes_cli.env_loader.load_hermes_dotenv"), \
- patch("hermes_cli.env_loader.reset_secret_source_cache"), \
- patch("hermes_state_registry.acquire", side_effect=_hanging_then_capture), \
- patch(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- return_value={
- "api_key": "test-key",
- "base_url": "https://example.invalid/v1",
- "provider": "openrouter",
- "api_mode": "chat_completions",
- },
- ), \
- patch("run_agent.AIAgent") as mock_agent_cls:
- mock_agent = MagicMock()
- mock_agent.run_conversation.return_value = {"final_response": "ok"}
- mock_agent_cls.return_value = mock_agent
-
- success, output, final_response, error = run_job(job)
- # run_job returned promptly after the timeout; session_db is None
- assert success is True
-
- # Release the hanging init so the abandoned worker completes.
- never_set.set()
- # Wait for the done-callback to fire and close the late result.
- for _ in range(50):
- if late_db_holder and late_db_holder[0].close.called:
- break
- time.sleep(0.1)
+ with patch("hermes_state_registry.acquire", side_effect=acquire), \
+ patch("cron.scheduler_authority.run_canonical_job", side_effect=admitted), \
+ patch("cron.scheduler_authority.reconcile_pending"), \
+ patch.object(scheduler, "get_due_jobs", return_value=[saved]):
+ assert scheduler.tick() == 1
+ assert saved["id"] not in scheduler.get_running_job_ids()
+ agent_cls.assert_not_called()
+ release.set()
+ assert closed.wait(5)
+ assert scheduler.tick() == 1
+ assert len(calls) == 2
+ assert agent_cls.call_count == 1
+ final_job = jobs.get_job(saved["id"])
+ assert final_job and final_job["last_status"] == "ok"
finally:
- never_set.set()
-
- assert len(late_db_holder) == 1, "SessionDB() should have completed once"
- late_db_holder[0].close.assert_called_once(), (
- "The SessionDB that completed after the timeout must be closed by "
- "the done-callback — otherwise its SQLite FDs leak until process exit (#72782)"
- )
-
-
-# ===========================================================================
-# #96290: gated runs must not open the session store at all
-# ===========================================================================
-
-class TestSessionDbInitAfterEarlyReturns:
- """SessionDB init moved AFTER the wake-gate / prompt-validation early
- returns (#96290): a run that never reaches the agent must never open
- state.db, so there is no handle for a gated return path to abandon."""
-
- def test_wake_gate_false_never_opens_session_db(self, tmp_path, monkeypatch):
- monkeypatch.delenv("HERMES_CRON_SESSION_DB_TIMEOUT", raising=False)
- job = {
- "id": "gated-no-db",
- "name": "gated-no-db",
- "prompt": "hello",
- "script": "gate.py",
- }
-
- with patch("cron.scheduler._hermes_home", tmp_path), \
- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \
- patch("hermes_cli.env_loader.load_hermes_dotenv"), \
- patch("hermes_cli.env_loader.reset_secret_source_cache"), \
- patch("hermes_state_registry.acquire") as mock_db_cls, \
- patch(
- "cron.scheduler._run_job_script_with_claim_heartbeat",
- return_value=(True, '{"wakeAgent": false}'),
- ), \
- patch("run_agent.AIAgent") as mock_agent_cls:
- success, output, final_response, error = run_job(job)
-
- assert success is True
- mock_db_cls.assert_not_called()
- mock_agent_cls.assert_not_called()
+ release.set()
+ scheduler._shutdown_parallel_pool()
+
+
- @pytest.mark.parametrize("result", ["db", None, RuntimeError("connect failed")])
- def test_close_late_session_db_result(result):
- db = MagicMock()
- future = concurrent.futures.Future()
- if isinstance(result, Exception):
- future.set_exception(result)
- else:
- future.set_result(db if result == "db" else result)
- scheduler._close_late_session_db_result(future)
- assert db.close.call_count == (1 if result == "db" else 0)
-
-
+def test_wake_gate_false_never_opens_session_db(owner_run):
+ _, job, execution_id, agent_cls = owner_run
+ job["script"] = "gate.py"
+ with patch("hermes_state_registry.acquire") as acquire, \
+ patch("cron.scheduler._run_job_script_with_claim_heartbeat", return_value=(True, '{"wakeAgent": false}')):
+ success, _, _, error = scheduler.run_job(job, execution_id=execution_id)
+ assert success and error is None
+ acquire.assert_not_called()
+ agent_cls.assert_not_called()
diff --cc tests/gateway/test_approval_prompt_redaction.py
index d91f643051b,6426def4e5b..b861712458c
--- a/tests/gateway/test_approval_prompt_redaction.py
+++ b/tests/gateway/test_approval_prompt_redaction.py
@@@ -60,99 -60,6 +60,45 @@@ class TestRedactApprovalCommand
assert _FAKE_GHP not in out
+class TestApprovalCommandWiring:
- """Guard the production wiring on BOTH approval-notify transports:
- 1. the chat-platform path (_approval_notify_sync in gateway/run.py), and
- 2. the SSE/API path (_approval_notify in
- gateway/platforms/api_server_runs.py),
- each of which must route the command through _redact_approval_command and
- REASSIGN the redacted value before any send/enqueue (so the raw command
- cannot reach a client). Uses AST (not char-offset string slicing) so a
- benign refactor doesn't cause a false failure, and so a discarded-result
- call (`_redact(cmd); send(cmd)`) does NOT pass."""
-
- def _assert_redacts_then_uses(self, module, func_name: str, sink_substr: str):
- """Parse `module`'s full AST, locate the (possibly nested) function
- `func_name`, and assert it contains an assignment
- `<x> = _redact_approval_command(...)` whose result is then used by a
- statement matching `sink_substr` on a LATER line. Walking the real AST
- (not a source slice) is refactor-robust and rejects discarded-result
- calls (the call must be an assignment, not a bare expression)."""
- import ast
- import inspect
-
- source = inspect.getsource(module)
- tree = ast.parse(source)
- target_fn = None
- for node in ast.walk(tree):
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == func_name:
- target_fn = node
- break
- assert target_fn is not None, f"function {func_name} not found in {module.__name__}"
-
- redact_line = None
- for node in ast.walk(target_fn):
- if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call):
- fn = node.value.func
- if isinstance(fn, ast.Name) and fn.id == "_redact_approval_command":
- redact_line = node.lineno
- assert redact_line is not None, (
- f"{func_name} must assign the result of _redact_approval_command(...) "
- "(a discarded-result call would still leak the raw command)"
- )
-
- sink_line = None
- for node in ast.walk(target_fn):
- seg = ast.get_source_segment(source, node)
- if seg and sink_substr in seg and getattr(node, "lineno", 0) > redact_line:
- sink_line = node.lineno
- break
- assert sink_line is not None, (
- f"`{sink_substr}` sink not found after the redaction in {func_name}"
- )
++ """The chat-platform approval notify (TurnRunner._approval_notify_sync) must send the REDACTED
++ command on both the card and the text fallback, without mutating the approval payload."""
+
+ def test_chat_platform_path_redacts_before_send(self):
+ import asyncio
+ from types import SimpleNamespace
+ from gateway.run_turn_runner import TurnRunner
+
+ async def exercise():
+ for card_success in (True, False):
+ sent = []
+
+ class Adapter:
+ def pause_typing_for_chat(self, chat_id):
+ pass
+
+ async def send_exec_approval(self, **kwargs):
+ sent.append(kwargs['command'])
+ return SimpleNamespace(success=card_success, error=None)
+
+ async def send(self, chat_id, text, **kwargs):
+ sent.append(text)
+ return SimpleNamespace(success=True)
+
+ ctx = SimpleNamespace(_status_adapter=Adapter(), _status_chat_id='fixture',
+ _status_thread_metadata=None, session_key='redaction-fixture',
+ _loop_for_step=asyncio.get_running_loop(), stream_consumer_holder=[None])
+ turn = TurnRunner(SimpleNamespace(), ctx)
+ raw = 'curl -H "Authorization: token ' + _FAKE_GHP + '" https://example.test'
+ approval = {'command': raw, 'description': 'fixture'}
+ await asyncio.to_thread(turn._approval_notify_sync, approval)
+ assert len(sent) == (1 if card_success else 2)
+ assert all(_FAKE_GHP not in text and 'curl' in text for text in sent)
+ assert approval['command'] == raw
+
+ asyncio.run(exercise())
+
- def test_sse_api_path_redacts_before_enqueue(self):
- from gateway.platforms import api_server_runs
-
- self._assert_redacts_then_uses(
- api_server_runs, "_approval_notify", "put_nowait"
- )
-
+
class TestApprovalTextFallbackContract:
def test_smart_deny_only_advertises_one_operation(self):
from gateway.run import _format_exec_approval_fallback
diff --cc tests/hermes_cli/test_cli_partial_update_hint.py
index e25ccee3090,492ad0f7d74..8395d283514
--- a/tests/hermes_cli/test_cli_partial_update_hint.py
+++ b/tests/hermes_cli/test_cli_partial_update_hint.py
@@@ -115,11 -110,9 +108,10 @@@ def test_cmd_chat_prints_update_hint_wh
err = capsys.readouterr().err
assert name in err
assert "hermes update" in err
- assert "partially-updated" in err
-def test_cmd_chat_still_reraises_unrelated_import_errors(main_mod, monkeypatch):
[email protected]("entry", ["cmd_chat", "_run_oneshot_from_args"])
+def test_cmd_chat_still_reraises_unrelated_import_errors(main_mod, monkeypatch, entry):
exc = ImportError("cannot import name 'dumps' from 'requests'")
exc.name = "requests"
diff --cc tests/hermes_cli/test_cli_preloaded_skills.py
index 33d233ae3a9,264c18bca36..00000000000
deleted file mode 100644,100644
--- a/tests/hermes_cli/test_cli_preloaded_skills.py
+++ /dev/null
@@@ -1,69 -1,91 +1,0 @@@
--from __future__ import annotations
-
- import importlib
- import os
- import sys
- from unittest.mock import MagicMock, patch
--
--import pytest
--
--
- def _make_real_cli(**kwargs):
- clean_config = {
- "model": {
- "default": "anthropic/claude-opus-4.6",
- "base_url": "https://openrouter.ai/api/v1",
- "provider": "auto",
- },
- "display": {"compact": False, "tool_progress": "all"},
- "agent": {},
- "terminal": {"env_type": "local"},
- }
- clean_env = {"LLM_MODEL": "", "HERMES_MAX_ITERATIONS": ""}
- prompt_toolkit_stubs = {
- "prompt_toolkit": MagicMock(),
- "prompt_toolkit.history": MagicMock(),
- "prompt_toolkit.styles": MagicMock(),
- "prompt_toolkit.patch_stdout": MagicMock(),
- "prompt_toolkit.application": MagicMock(),
- "prompt_toolkit.layout": MagicMock(),
- "prompt_toolkit.layout.processors": MagicMock(),
- "prompt_toolkit.filters": MagicMock(),
- "prompt_toolkit.layout.dimension": MagicMock(),
- "prompt_toolkit.layout.menus": MagicMock(),
- "prompt_toolkit.widgets": MagicMock(),
- "prompt_toolkit.key_binding": MagicMock(),
- "prompt_toolkit.completion": MagicMock(),
- "prompt_toolkit.formatted_text": MagicMock(),
- }
- with patch.dict(sys.modules, prompt_toolkit_stubs), patch.dict(
- "os.environ", clean_env, clear=False
- ):
- import cli as cli_mod
-class _DummyCLI:
- def __init__(self, **kwargs):
- self.kwargs = kwargs
- self.session_id = "session-123"
- self.system_prompt = "base prompt"
- self.preloaded_skills = []
--
- cli_mod = importlib.reload(cli_mod)
- with patch.object(cli_mod, "get_tool_definitions", return_value=[]), patch.dict(
- cli_mod.__dict__, {"CLI_CONFIG": clean_config}
- ):
- return cli_mod.HermesCLI(**kwargs)
- def show_banner(self):
- return None
--
- def show_tools(self):
- return None
--
- def test_show_banner_does_not_print_skills():
- """show_banner() no longer prints the activated skills line — it moved to run()."""
- cli_obj = _make_real_cli(compact=False)
- cli_obj.preloaded_skills = ["hermes-agent-dev", "github-auth"]
- cli_obj.console = MagicMock()
- def show_toolsets(self):
- return None
--
- with patch("hermes_cli.banner.build_welcome_banner") as mock_banner, patch(
- "shutil.get_terminal_size", return_value=os.terminal_size((120, 40))
- ):
- cli_obj.show_banner()
- def run(self):
- return None
--
- print_calls = [
- call.args[0]
- for call in cli_obj.console.print.call_args_list
- if call.args and isinstance(call.args[0], str)
- ]
- startup_lines = [line for line in print_calls if "Activated skills:" in line]
- assert len(startup_lines) == 0
- assert mock_banner.call_count == 1
-
-def _real_finalize(cli_obj):
- """Call the real HermesCLI.finalize_preloaded_skills on a dummy object."""
- return _REAL_FINALIZE(cli_obj)
-
-
-def _capture_real_finalize():
- import cli as cli_mod
- return cli_mod.HermesCLI.__dict__["finalize_preloaded_skills"]
-
-
-_REAL_FINALIZE = _capture_real_finalize()
-
-
-def test_main_applies_preloaded_skills_to_system_prompt(monkeypatch):
- import cli as cli_mod
-
- created = {}
-
- def fake_cli(**kwargs):
- created["cli"] = _DummyCLI(**kwargs)
- return created["cli"]
-
- monkeypatch.setattr(cli_mod, "HermesCLI", fake_cli)
- monkeypatch.setattr(
- cli_mod,
- "build_preloaded_skills_prompt",
- lambda skills, task_id=None, excluded_loaded_names=None: ("skill prompt", ["hermes-agent-dev", "github-auth"], []),
- )
-
- with pytest.raises(SystemExit):
- cli_mod.main(skills="hermes-agent-dev,github-auth", list_tools=True)
-
- cli_obj = created["cli"]
- # The preload now runs in a background thread and is folded in at agent
- # init via finalize_preloaded_skills() (startup-latency change). Drive
- # the finalize explicitly — the same call _init_agent makes.
- _real_finalize(cli_obj)
- assert cli_obj.system_prompt == "base prompt\n\nskill prompt"
- assert cli_obj.preloaded_skills == ["hermes-agent-dev", "github-auth"]
-
-
-def test_main_raises_for_unknown_preloaded_skill(monkeypatch):
- import cli as cli_mod
-
- created = {}
-
- def fake_cli(**kwargs):
- created["cli"] = _DummyCLI(**kwargs)
- return created["cli"]
-
- monkeypatch.setattr(cli_mod, "HermesCLI", fake_cli)
- monkeypatch.setattr(
- cli_mod,
- "build_preloaded_skills_prompt",
- lambda skills, task_id=None, excluded_loaded_names=None: ("", [], ["missing-skill"]),
- )
-
- with pytest.raises(SystemExit):
- cli_mod.main(skills="missing-skill", list_tools=True)
-
- # The all-skills-unknown hard failure now surfaces when the preload is
- # finalized (agent init), preserving the fail-loud contract.
- with pytest.raises(ValueError, match=r"Unknown skill\(s\): missing-skill"):
- _real_finalize(created["cli"])
-
-
diff --cc tests/hermes_cli/test_cron.py
index 6b0a4ba0d22,8148bc82f99..61711067061
--- a/tests/hermes_cli/test_cron.py
+++ b/tests/hermes_cli/test_cron.py
@@@ -386,41 -386,8 +386,18 @@@ class TestExternalCronProviderStatus
assert "Scheduler is not ready" not in out
- def test_cron_list_warns_when_gateway_not_running(monkeypatch, capsys):
- monkeypatch.setattr(
- "cron.jobs.list_jobs",
- lambda include_disabled=False: [
- {
- "id": "job-1",
- "name": "Nightly docs",
- "schedule_display": "every day",
- "state": "scheduled",
- "enabled": True,
- "next_run_at": "2026-06-01T00:00:00Z",
- "deliver": ["local"],
- }
- ],
- )
- monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda: [])
- monkeypatch.setattr(cron_cli, "_active_cron_provider_name", lambda: "builtin")
-
- cron_cli.cron_list()
-
- out = capsys.readouterr().out
- assert "Scheduler is not ready" in out
- assert "Nightly docs" in out
+def test_cron_tick_invokes_scheduler_tick_verbose_and_headless(monkeypatch):
+ """The CLI tick runs outside any gateway: it must declare itself headless so agent jobs are
+ refused, never spawned for."""
+ calls = []
+ monkeypatch.setattr("cron.scheduler.tick",
+ lambda verbose=False, headless=False: calls.append((verbose, headless)))
+
+ cron_cli.cron_tick()
+
+ assert calls == [(True, True)]
def test_cron_create_failure_returns_nonzero(monkeypatch, capsys):
diff --cc tests/hermes_cli/test_kanban_gateway_restart_handoff.py
index 1c8bbc4d342,5bc28c5e0cc..7981b97a2e1
--- a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py
+++ b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py
@@@ -214,53 -206,22 +215,53 @@@ def test_real_user_systemd_scope_preser
"'pid': os.getpid(), 'cwd': os.getcwd(), "
"'task': os.environ.get('HERMES_KANBAN_TASK'), "
"'run': os.environ.get('HERMES_KANBAN_RUN_ID'), "
+ "'claim': os.environ.get('HERMES_KANBAN_CLAIM_LOCK'), "
+ "'board': os.environ.get('HERMES_KANBAN_BOARD'), "
+ "'home': os.environ.get('HERMES_HOME'), "
+ "'profile': os.environ.get('HERMES_PROFILE'), "
+ "'source': os.environ.get('HERMES_SESSION_SOURCE'), "
+ "'terminal_cwd': os.environ.get('TERMINAL_CWD'), "
- "'cgroup': pathlib.Path('/proc/self/cgroup').read_text()})); time.sleep(0.5)"
+ "'cgroup': pathlib.Path('/proc/self/cgroup').read_text()})); os.replace(t, p); time.sleep(0.5)"
)
- monkeypatch.setattr(kbd, "_resolve_hermes_argv", lambda: [sys.executable, "-c", script, str(receipt)])
+ # Replace only the worker payload; keep real scope creation and env handoff.
+ monkeypatch.setattr(
+ kbd, "_worker_argv",
+ lambda task, profile_arg, hermes_home: [sys.executable, "-c", script, str(receipt)],
+ )
monkeypatch.setenv("INVOCATION_ID", "managed-gateway-test")
monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: True)
pid = kbd._default_spawn(task, str(workspace))
- deadline = time.monotonic() + 15
- while not receipt.exists() and time.monotonic() < deadline:
- time.sleep(0.05)
-
- assert receipt.exists()
- payload = json.loads(receipt.read_text(encoding="utf-8"))
- assert payload["pid"] == pid
- assert payload["cwd"] == str(workspace)
- assert payload["task"] == task.id
- assert payload["run"] == "23"
- assert ".scope" in payload["cgroup"]
- assert "hermes-gateway.service" not in payload["cgroup"]
+ try:
- deadline = time.monotonic() + 5
++ deadline = time.monotonic() + 15
+ while not receipt.exists() and time.monotonic() < deadline:
+ time.sleep(0.05)
+
+ log_path = kb.worker_logs_dir() / f"{task.id}.log"
+ assert receipt.exists(), log_path.read_text(encoding="utf-8", errors="replace")
+ payload = json.loads(receipt.read_text(encoding="utf-8"))
+ assert payload["pid"] == pid
+ assert payload["cwd"] == str(workspace)
+ assert payload["task"] == task.id
+ assert payload["run"] == "23"
+ assert payload["claim"] == task.claim_lock
+ assert payload["board"] == kb.get_current_board()
+ assert payload["home"] == str(workspace.parent / '.hermes' / 'profiles' / task.assignee)
+ assert payload["profile"] == task.assignee
+ assert payload["source"] == 'kanban'
+ assert payload["terminal_cwd"] == str(workspace)
+ assert unit in payload["cgroup"]
+ assert "hermes-gateway.service" not in payload["cgroup"]
+ import psutil
+ assert psutil.Process(pid).wait(timeout=5) == 0
+ finally:
+ # Stop only this test's freshly named scope, never the historical fixed
+ # name or another producer's unit. The live-system guard stays enabled.
+ subprocess.run(["systemctl", "--user", "stop", unit], stdin=subprocess.DEVNULL,
+ capture_output=True, timeout=10, check=False,
+ env=process_registry.systemd_user_bus_env())
+ state = subprocess.run(["systemctl", "--user", "show", unit, "--property=ActiveState", "--value"],
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10,
+ env=process_registry.systemd_user_bus_env())
+ assert state.stdout.strip() in ('inactive', 'failed'), state.stdout + state.stderr
+ print(json.dumps({'worker': payload, 'scope_after_cleanup': state.stdout.strip()}))
diff --cc tests/hermes_cli/test_web_server.py
index 9134e398d2c,6cd0f848b9e..f783f769075
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@@ -374,41 -336,8 +356,9 @@@ class TestWebServerEndpoints
monkeypatch.setattr(_web_server_sessions, "_open_session_db_for_profile", boom)
assert self.client.get("/api/sessions?limit=1&offset=0").status_code == 500
- def test_get_status_loads_gateway_config_off_event_loop(self, monkeypatch):
- """Cold gateway config loading must not block the WebSocket loop.
-
- On Windows the first ``load_gateway_config()`` call imports and
- discovers platform adapters and can take longer than Desktop's 15s
- WebSocket timeout. Running it inline makes a concurrent /api/ws
- handshake time out before ``gateway.ready`` can be sent.
- """
- import gateway.config as gateway_config
- import hermes_cli.web_server as web_server
-
- seen = {}
-
- class _Config:
- @staticmethod
- def get_connected_platforms():
- return []
-
- def _load():
- seen["thread"] = threading.get_ident()
- return _Config()
-
- monkeypatch.setattr(gateway_config, "load_gateway_config", _load)
-
- async def _run():
- event_loop_thread = threading.get_ident()
- await _rt_status.get_status()
- return event_loop_thread
-
- event_loop_thread = asyncio.run(_run())
-
- assert seen["thread"] != event_loop_thread
- def test_get_sessions_auto_archive_uses_maintenance_writer(self):
+ def test_get_sessions_leaves_auto_archive_to_owner(self):
+ from hermes_cli import web_server
from hermes_cli.config import load_config, save_config
from hermes_constants import get_hermes_home
from hermes_state import SessionDB
@@@ -731,12 -692,11 +678,9 @@@
with ThreadPoolExecutor(max_workers=8) as pool:
responses = list(pool.map(self.client.get, paths))
- assert [response.status_code for response in responses] == [
- 200
- ] * len(paths)
+ assert [response.status_code for response in responses] == [503] * len(paths)
-
-
-
def test_messaging_platforms_profile_scopes_gateway_reads(self, monkeypatch):
"""?profile=<name> must resolve liveness from the profile's own home.
@@@ -1189,31 -1113,7 +1097,7 @@@ CONFIG_SCHEMA = ProviderConfigSchema
# ── Dashboard font override ─────────────────────────────────────────
-
-
- def _create_session_with_heavy_fields(self, session_id: str) -> None:
- from hermes_state import SessionDB
-
- db = SessionDB()
- try:
- db.create_session(
- session_id=session_id,
- source="cli",
- system_prompt="# SOUL.md\n" + ("prompt body " * 500),
- model_config={"temperature": 0.7, "notes": "x" * 200},
- )
- finally:
- db.close()
-
-
-
-
-
-
- def test_import_sessions_endpoint_imports_exported_json(self):
+ def test_import_sessions_endpoint_imports_exported_json(self, mutation_owner):
from hermes_state import SessionDB
payload = {
diff --cc tests/hermes_cli/test_web_server_sessiondb_eventloop.py
index 6ea2c774f21,af83baeb5e4..63e90b6df0f
--- a/tests/hermes_cli/test_web_server_sessiondb_eventloop.py
+++ b/tests/hermes_cli/test_web_server_sessiondb_eventloop.py
@@@ -1,197 -1,76 +1,35 @@@
--import ast
import asyncio
--import threading
--from pathlib import Path
--import pytest
--
--from hermes_cli import web_server
import hermes_cli.web_models as _web_models
import hermes_cli.web_routers.sessions as _rt_sessions
import hermes_cli.web_server_sessions as _web_server_sessions
--from hermes_cli import web_server_sessions
--from hermes_cli.web_routers import analytics as web_analytics
--from hermes_cli.web_routers import sessions as web_sessions
--
--
--TARGET_HANDLERS = {
-- "bulk_delete_sessions_endpoint",
-- "count_empty_sessions_endpoint",
-- "delete_empty_sessions_endpoint",
-- "get_session_latest_descendant",
-- "get_session_messages",
- # delete_session_endpoint admits through the session authority and opens no SessionDB.
- "delete_session_endpoint",
-- "export_session_endpoint",
-- "prune_sessions_endpoint",
-- "get_usage_analytics",
-- "get_models_analytics",
-- "search_sessions",
-- "get_session_stats",
-- "get_session_detail",
--}
--
--
--def _call_name(call: ast.Call) -> str | None:
-- if isinstance(call.func, ast.Name):
-- return call.func.id
-- if isinstance(call.func, ast.Attribute):
-- return call.func.attr
-- return None
-
-
- def test_sessiondb_handlers_open_connections_inside_executor_helpers():
- # The session and analytics route handlers were extracted to
- # web_routers/{sessions,analytics}.py; the executor helpers live in
- # web_server_sessions.py (and any left in web_server.py) — scan all
- # four modules' top-level bodies.
- handlers: dict[str, ast.AsyncFunctionDef] = {}
- top_level_helpers: dict[str, ast.FunctionDef] = {}
- for mod in (web_server, web_server_sessions, web_sessions, web_analytics):
- tree = ast.parse(Path(mod.__file__).read_text(encoding="utf-8"))
- for node in tree.body:
- if isinstance(node, ast.AsyncFunctionDef) and node.name in TARGET_HANDLERS:
- handlers[node.name] = node
- elif isinstance(node, ast.FunctionDef):
- top_level_helpers[node.name] = node
- assert handlers.keys() == TARGET_HANDLERS
-
- for name, handler in handlers.items():
- helpers = {
- **top_level_helpers,
- **{
- node.name: node
- for node in handler.body
- if isinstance(node, ast.FunctionDef)
- },
- }
- offloaded = {
- arg.id
- for node in ast.walk(handler)
- if isinstance(node, ast.Call)
- and _call_name(node) == "to_thread"
- for arg in node.args[:1]
- if isinstance(arg, ast.Name)
- }
- db_open_owners = {
- helper_name
- for helper_name, helper in helpers.items()
- if helper_name in offloaded
- and any(
- isinstance(node, ast.Call)
- and _call_name(node) == "_open_session_db_for_profile"
- for node in ast.walk(helper)
- )
- }
- assert db_open_owners, f"{name} does not offload SessionDB open + work"
-
-
- def test_sessiondb_opens_declare_access_mode():
- for mod in (web_server_sessions, web_sessions):
- tree = ast.parse(Path(mod.__file__).read_text(encoding="utf-8"))
- calls = [
- node
- for node in ast.walk(tree)
- if isinstance(node, ast.Call)
- and _call_name(node) == "_open_session_db_for_profile"
- ]
- assert calls
- for call in calls:
- assert any(keyword.arg == "read_only" for keyword in call.keywords)
--
--
- def test_bulk_delete_sessiondb_work_runs_off_event_loop(monkeypatch):
-def test_session_rename_runs_writer_open_and_update_off_event_loop(monkeypatch):
-- loop_thread = threading.get_ident()
-- db_threads: list[int] = []
- db_modes: list[bool] = []
-
- class _DB:
- def delete_sessions(self, ids):
- db_threads.append(threading.get_ident())
- assert ids == ["one", "two"]
- return 2
-
- def close(self):
- db_threads.append(threading.get_ident())
-
- def _open_db(profile=None, *, read_only):
- assert profile is None
- db_modes.append(read_only)
- return _DB()
-
- monkeypatch.setattr(_web_server_sessions, "_open_session_db_for_profile", _open_db)
-
- result = asyncio.run(
- _rt_sessions.bulk_delete_sessions_endpoint(
- _web_models.BulkDeleteSessions(ids=["one", "two"])
- )
- )
-
- assert result == {"ok": True, "deleted": 2}
- assert db_modes == [False]
- assert db_threads
- assert all(thread_id != loop_thread for thread_id in db_threads)
-
-
- class _ReadDB:
- """Read-only stand-in that records which thread every SessionDB call runs on."""
-
- def __init__(self, threads: list[int]):
- self._threads = threads
-
- def _hit(self, value=None):
- self._threads.append(threading.get_ident())
- return value
-
- def session_count(self, **_kw):
- return self._hit(3)
-
- def message_count(self):
- return self._hit(7)
-
- def session_count_by_source(self, **_kw):
- return self._hit({"cli": 3})
-
- def get_session(self, sid):
- return self._hit({"id": sid, "title": "t"})
-
- def get_session_rich_row(self, sid):
- return self._hit(None)
-
- def get_compression_tip(self, root_id):
- return self._hit(None)
-
- def search_sessions_by_id(self, q, **_kw):
- return self._hit([{"id": "sess-1", "preview": "hello", "started_at": 1.0}])
-
- def search_messages(self, **_kw):
- return self._hit([])
- def close(self):
- self._hit()
- class _DB:
- def set_session_title(self, sid, title):
- db_threads.append(threading.get_ident())
- assert (sid, title) == ("sess-1", "renamed")
- def get_session_title(self, sid):
- db_threads.append(threading.get_ident())
- assert sid == "sess-1"
- return "renamed"
++def test_session_rename_routes_through_authority_without_second_writer(monkeypatch):
++ """Main's rename fix offloaded the ad-hoc ``_with_db`` writer; on the unified runtime the
++ PATCH route never opens a SessionDB at all — the owning session authority applies the
++ ``sidebar`` mutation, so a second writer (on or off the loop) would be the regression."""
++ seen = {}
- @pytest.mark.parametrize(
- "call",
- [
- pytest.param(lambda: _rt_sessions.search_sessions(q="hello"), id="search"),
- pytest.param(lambda: _rt_sessions.get_session_stats(), id="stats"),
- pytest.param(lambda: _rt_sessions.get_session_detail("sess-1"), id="detail"),
- ],
- )
- def test_session_read_handlers_run_sessiondb_work_off_event_loop(monkeypatch, call):
- """Regression for #60747: /search, /stats and /{id} ran FTS + SQLite inline on the
- loop thread, so a large state.db froze every other dashboard request."""
- loop_thread = threading.get_ident()
- db_threads: list[int] = []
- def close(self):
- db_threads.append(threading.get_ident())
++ def _open_db(*_args, **_kwargs):
++ raise AssertionError("rename must not open its own SessionDB writer")
-- def _open_db(profile=None, *, read_only):
- assert read_only is True
- return _ReadDB(db_threads)
- db_threads.append(threading.get_ident())
- assert profile is None
- assert read_only is False
- return _DB()
++ async def _mutate(request, profile, session_id, *, request_id, expected_revision, operation,
++ payload, expected_generation=None):
++ seen.update(profile=profile, session_id=session_id, request_id=request_id,
++ expected_revision=expected_revision, operation=operation, payload=payload,
++ expected_generation=expected_generation)
++ return {"ok": True, "title": payload.get("title")}
monkeypatch.setattr(_web_server_sessions, "_open_session_db_for_profile", _open_db)
-- monkeypatch.setattr(_rt_sessions, "_resolve_session_id", lambda db, sid: sid)
++ monkeypatch.setattr(_web_server_sessions, "_mutate_session_request", _mutate)
- asyncio.run(call())
- result = asyncio.run(
- _rt_sessions.rename_session_endpoint(
- "sess-1", _web_models.SessionRename(title="renamed")
- )
- )
++ body = _web_models.SessionRename(title="renamed", pinned=True, request_id="req-1",
++ expected_revision=3, expected_generation=1)
++ result = asyncio.run(_rt_sessions.rename_session_endpoint("sess-1", body, request=object()))
- assert db_threads, "handler never touched the SessionDB"
- assert all(thread_id != loop_thread for thread_id in db_threads)
+ assert result == {"ok": True, "title": "renamed"}
- assert db_threads
- assert all(thread_id != loop_thread for thread_id in db_threads)
++ assert seen == {
++ "profile": None, "session_id": "sess-1", "request_id": "req-1", "expected_revision": 3,
++ "expected_generation": 1, "operation": "sidebar", "payload": {"title": "renamed", "pinned": True},
++ }
diff --cc tests/plugins/test_kanban_model_override.py
index b1ff270cb54,61768c6606f..ff76633899c
--- a/tests/plugins/test_kanban_model_override.py
+++ b/tests/plugins/test_kanban_model_override.py
@@@ -293,14 -241,34 +289,8 @@@ def test_reasoning_effort_survives_clea
assert t.reasoning_effort == "ultra"
- def test_reasoning_effort_without_a_model_override(conn):
- """A task may run the profile's OWN model at a different depth."""
- tid = kb.create_task(conn, title="t", assignee="worker", reasoning_effort="low")
- t = kb.get_task(conn, tid)
- assert t.model_override is None
- assert t.reasoning_effort == "low"
-def test_spawn_passes_reasoning_without_a_model(monkeypatch, tmp_path, conn):
- tid = kb.create_task(conn, title="t", assignee="elias", reasoning_effort="high")
- task = kb.get_task(conn, tid)
- cmd = _spawn_and_capture(monkeypatch, tmp_path, task)
- assert "-m" not in cmd
- i = cmd.index("--reasoning")
- assert cmd[i + 1] == "high"
-
-
-def test_spawn_omits_reasoning_when_unset(monkeypatch, tmp_path, conn):
- tid = kb.create_task(conn, title="t", assignee="elias")
- task = kb.get_task(conn, tid)
- cmd = _spawn_and_capture(monkeypatch, tmp_path, task)
- assert "--reasoning" not in cmd
-
-
-def test_worker_cli_accepts_the_reasoning_flag():
- """The dispatcher's --reasoning must be a real flag on the worker's CLI —
- a spawn arg no parser accepts fails every dispatch."""
- from hermes_cli._parser import build_top_level_parser
-
- parser = build_top_level_parser()[0]
- args = parser.parse_args(["--cli", "chat", "-q", "hi", "--reasoning", "high"])
- assert args.reasoning == "high"
-
-
def test_patch_sets_and_clears_reasoning_effort(client):
task = _create(client)
r = client.patch(
diff --cc tests/tools/test_bot_live_owner_delivery.py
index df1e120fffe,5455385fa15..e6d07779b9a
--- a/tests/tools/test_bot_live_owner_delivery.py
+++ b/tests/tools/test_bot_live_owner_delivery.py
@@@ -159,17 -173,54 +159,3 @@@ def test_non_dict_ticket_fails_exact_id
with pytest.raises(ValueError):
mailbox.read_delivery_result(tmp_path, "e" * 32)
assert bad.read_text(encoding="utf-8") == '"oops"'
--
--
- def test_existing_mailbox_lock_does_not_fsync_parent_dirs(tmp_path, monkeypatch):
- """The lock is re-entered on every receipt read; only a freshly created mailbox links its parents."""
-def test_schema_damaged_ticket_does_not_wedge_bulk_scans(tmp_path, caplog):
- """Valid JSON that lost a field must degrade like corrupt JSON: skipped, warned once, never raised."""
- import logging
-
-- from tools import bot_live_delivery as mailbox
--
- calls = []
- monkeypatch.setattr(mailbox, "fsync_directory", lambda path: calls.append(path))
- with mailbox._locked(tmp_path):
- pass
- assert len(calls) == 2
- with mailbox._locked(tmp_path):
- pass
- assert len(calls) == 2
- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",
- lease_id="lease", live_session_id="live")
- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "healthy", delivery_id="d" * 32)
- root = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME
- damaged = {
- root / f"{'a' * 32}.json": "{}",
- root / f"{'b' * 32}.json": json.dumps(dict(
- delivery_id="b" * 32, id="b" * 32, status="queued", created_at=1,
- sequence=1, owner=None, message="owner lost")),
- root / f"{'c' * 32}.json": json.dumps(dict(
- delivery_id="c" * 32, id="c" * 32, status="queued", created_at=2,
- sequence="old", owner=owner, message="sequence lost", **owner)),
- root / f"{'e' * 32}.json": json.dumps(dict(
- delivery_id="../wrong", id="../wrong", status="queued", created_at=3,
- sequence=3, owner=owner, message="id lost", **owner)),
- root / f"{'1' * 32}.json": json.dumps(dict(
- delivery_id="1" * 32, id="1" * 32, status=[], created_at=4,
- sequence=4, owner=owner, message="status lost", **owner)),
- }
- for path, contents in damaged.items():
- path.write_text(contents, encoding="utf-8")
- with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):
- admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "also healthy", delivery_id="f" * 32)
- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == queued["delivery_id"]
- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == admitted["delivery_id"]
- for _ in range(3):
- assert mailbox.claim_pending_delivery(tmp_path, owner) is None
- assert admitted["sequence"] == queued["sequence"] + 1
- assert {path: path.read_text(encoding="utf-8") for path in damaged} == damaged
- skipped = [r.message for r in caplog.records if r.message.startswith("bot_live_delivery: skipping unreadable ticket")]
- assert len(skipped) == len(damaged), "each damaged ticket warns once per process, not per scan"
-
-
diff --cc tests/tools/test_bot_mode_dm.py
index 6fdf6a18852,d068c4f12e8..ebbac4b729f
--- a/tests/tools/test_bot_mode_dm.py
+++ b/tests/tools/test_bot_mode_dm.py
@@@ -326,27 -277,30 +326,26 @@@ def test_local_delivery_admits_canonica
assert result["status"] == "queued"
assert result["to"] == "@researcher"
assert result["process_id"] == "proc_test1234"
- assert "Do NOT wait" in result["detail"]
+ # Exactly one canonical admission, on the target profile's own authority.
+ assert [h for h, _p in authority.calls] == [target.resolve()]
+ _home, params = authority.calls[0]
+ assert params["id"] == result["delivery_id"] and params["profile"] == "researcher"
+
+ # The background process only waits for the receipt: no model turn argv.
assert len(calls) == 1
call = calls[0]
assert call["background"] is True
assert call["notify_on_complete"] is True
assert call["_host_local"] is True
# The completion notification IS the reply: sized like a message, not a build log's 2000-char tail.
- assert call["_completion_output_chars"] == bot_mode_dm.REPLY_COMPLETION_CHARS == bot_mode_dm.MESSAGE_MAX_CHARS + 2000
+ assert call["_completion_output_chars"] > bot_mode_dm.MESSAGE_MAX_CHARS
assert Path(call["workdir"]) == Path(bot_mode_dm.__file__).resolve().parent.parent
command = call["command"]
- mode, dm_file, transport_argv = _runner_parts(command)
+ mode, dm_file, transport_argv, profile_home = _runner_parts(command)
assert mode == "query-file"
- assert transport_argv == [
- "hermes",
- "-p",
- "researcher",
- "chat",
- "--in",
- "~",
- "-c",
- "Bot Chat",
- "--create-if-missing",
- "-Q",
- ]
+ assert Path(profile_home) == target.resolve()
+ assert transport_argv[:3] == ["hermes", "-p", "researcher"]
# message body rides the temp file, never the command line
assert "PAYLOAD_SENTINEL_7A91" not in command
assert "$(" not in command
@@@ -357,25 -311,8 +356,9 @@@
content = Path(dm_file).read_text(encoding="utf-8")
assert content.startswith("Message from 🤖 hermes (@hermes): ")
assert '$(and this is not shell)' in content
+ assert params["message"] == content
- def test_cli_runner_ack_is_a_dispatch_ack_that_names_the_completion_notification(tmp_path, monkeypatch):
- """``status: queued`` is returned before the background runner has delivered anything; the
- detail (and the schema text the model reads) must say the completion notification carries
- the outcome, so a runner that dies at exec is never read as a delivered message."""
- _capture_spawn(monkeypatch)
- home = _managed_home(tmp_path, teammates=("researcher",))
- _canonical_target(monkeypatch, home / "profiles" / "researcher")
- result = json.loads(bot_mode_dm.message_agent_tool(
- target="researcher", message="hi", agent=_FakeAgent(home, title="Bot Chat")))
-
- assert result["status"] == "queued"
- assert "Do NOT wait or resend" in result["detail"]
- assert "delivered" not in result["detail"].lower()
- description = bot_mode_dm.message_agent_tool_schema()["function"]["description"]
- assert "dispatch acknowledgement" in description and "not a delivery receipt" in description
- assert "completion notification" in description and "delivery failure" in description
def test_cli_runner_ack_is_queued_with_the_runner_delivery_id(tmp_path, monkeypatch):
@@@ -620,76 -548,8 +603,50 @@@ def test_named_profile_sender_prefix(tm
assert _runner_author(calls[0]["command"]) == {"id": "bot:coder", "name": "coder", "is_bot": True}
- def test_delivery_command_author_json_survives_quoting(tmp_path):
- """The optional author JSON survives shell quoting before the delivery mode."""
- author = {"id": "bot:default", "name": "hermes", "is_bot": True}
- command = bot_mode_dm._delivery_command(["hermes", "-p", "x"], str(tmp_path / "dm.txt"),
- stdin_file=False, author=author)
- parts = shlex.split(command)
- assert parts[2:4] == ["--run-delivery", "--author"]
- assert json.loads(parts[4]) == author
- assert parts[5] == "query-file"
- assert _runner_parts(command) == ("query-file", str(tmp_path / "dm.txt"), ["hermes", "-p", "x"], None)
-
- # Without an author the optional argv pair is absent.
- command = bot_mode_dm._delivery_command(["hermes"], "dm.txt", stdin_file=True)
- assert shlex.split(command)[2:4] == ["--run-delivery", "stdin"]
- assert _runner_author(command) is None
-
-
- @pytest.mark.windows_only
- def test_delivery_command_preserves_author_during_windows_slash_rewrite():
- command = bot_mode_dm._delivery_command(["hermes", "-p", "x"], "C:\\Users\\me\\dm.txt",
- stdin_file=False, author={"id": "bot:default", "name": 'q"q', "is_bot": True})
- parts = shlex.split(command)
- assert json.loads(parts[4]) == {"id": "bot:default", "name": 'q"q', "is_bot": True}
- assert parts[6] == "C:/Users/me/dm.txt"
-
-
+def test_unavailable_authority_is_reported_never_worked_around(tmp_path, monkeypatch):
+ """No canonical target: the sender learns the outcome is unknown and nothing
+ else (no CLI, no background runner) is started."""
+ home = _managed_home(tmp_path)
+ agent = _FakeAgent(home, title="Bot Chat")
+ from tools import bot_live_delivery as live
+
+ def unavailable(home):
+ raise ValueError("profile authority is not ready")
+ monkeypatch.setattr(live, "find_canonical_live_owner", unavailable)
+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)
+ import tools.terminal_tool as terminal_tool_module
+ monkeypatch.setattr(terminal_tool_module, "terminal_tool",
+ lambda *a, **k: pytest.fail("no runner may start without admission"))
+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("no CLI turn may start"))
+ result = json.loads(
+ bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent)
+ )
+ assert result["status"] == "ambiguous"
+ assert "not ready" in result["error"] and "Do not resend" in result["error"]
+ assert Path(result["evidence_file"]).read_text(encoding="utf-8").endswith("hi")
+
+
+def test_notification_spawn_failure_is_reported_after_admission(tmp_path, monkeypatch):
+ """The receipt waiter failing to start is a notification problem, surfaced
+ beside the (already committed) admission — never a reason to re-admit."""
+ home = _managed_home(tmp_path)
+ target = home / "profiles" / "researcher"
+ authority = _canonical_target(monkeypatch, target)
+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)
+ import tools.terminal_tool as terminal_tool_module
+
+ def boom(command, **kwargs):
+ raise RuntimeError("spawn failed")
+
+ monkeypatch.setattr(terminal_tool_module, "terminal_tool", boom)
+ result = json.loads(
+ bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=_FakeAgent(home))
+ )
+ assert result["status"] == "queued"
+ assert "could not be started" in result["notification_error"]
+ assert len(authority.records) == 1
def test_live_dm_admitted_before_waiter_failure(tmp_path, monkeypatch):
@@@ -740,49 -601,14 +697,14 @@@ def test_live_dm_runner_retry_never_ree
assert dm_file.read_text(encoding="utf-8") == "hello"
-# ── plaintext tempfile lifecycle ─────────────────────────────────────────────
+# ── plaintext tempfile lifecycle (peer stdin transport) ─────────────────────
- def test_peer_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path):
- dm_file = tmp_path / "message with spaces.txt"
- dm_file.write_text("secret $(not shell)", encoding="utf-8")
- observed = tmp_path / "observed.txt"
- child = tmp_path / "child.py"
- child.write_text(
- textwrap.dedent(
- """\
- import pathlib
- import sys
-
- pathlib.Path(sys.argv[1]).write_text(sys.stdin.read(), encoding="utf-8")
- """
- ),
- encoding="utf-8",
- )
-
- returncode = bot_mode_dm._run_delivery(
- [sys.executable, str(child), str(observed)], str(dm_file), stdin_file=True
- )
-
- assert returncode == 0
- assert observed.read_text(encoding="utf-8") == "secret $(not shell)"
- assert not dm_file.exists()
-
-
- def test_peer_delivery_runner_unlinks_when_child_launch_raises(tmp_path, monkeypatch):
- dm_file = tmp_path / "message.txt"
- dm_file.write_text("secret", encoding="utf-8")
- def boom(*args, **kwargs):
- raise RuntimeError("child launch failed")
- monkeypatch.setattr(subprocess, "run", boom)
- with pytest.raises(RuntimeError, match="child launch failed"):
- bot_mode_dm._run_delivery(["hermes"], str(dm_file), stdin_file=True)
- assert not dm_file.exists()
-def test_delivery_runner_preserves_child_failure_and_unlinks(tmp_path):
+def test_peer_delivery_runner_preserves_child_failure_and_unlinks(tmp_path):
dm_file = tmp_path / "message.txt"
dm_file.write_text("secret", encoding="utf-8")
child = tmp_path / "fail.py"
diff --cc tests/tools/test_bot_retry_policy.py
index f66fade925e,0a43ae61583..2fb7ea2ade3
--- a/tests/tools/test_bot_retry_policy.py
+++ b/tests/tools/test_bot_retry_policy.py
@@@ -51,22 -49,9 +51,14 @@@ def test_non_retryable_reasons_stop(rea
assert bfr.retry_action(reason) == bfr.RETRY_NONE
- def test_every_reason_has_a_defined_action():
- """Invariant: the policy is total over the closed reason vocabulary."""
- for reason in bfr.ALL_REASONS:
- assert bfr.retry_action(reason) in {
- bfr.RETRY_RESUME,
- bfr.RETRY_COMPRESS_THEN_RESUME,
- bfr.RETRY_NONE,
- }
-# ── relay deliver handler consumes the policy ────────────────────────────────
+# ── delivery surfaces never run their own retry loop ─────────────────────────
+#
+# Retired: the relay handler and local runner used to re-run a `hermes -p ...`
+# CLI turn on transient failure. Execution now belongs to the profile
+# authority's canonical admission; retry policy applies inside that turn.
+# These surfaces must only forward/refuse with a typed reason, never spawn.
@pytest.fixture
diff --cc tests/tools/test_bot_turn_lock.py
index f9508b20f8e,347380ad258..e68a275d1d7
--- a/tests/tools/test_bot_turn_lock.py
+++ b/tests/tools/test_bot_turn_lock.py
@@@ -11,7 -11,7 +11,6 @@@ from __future__ import annotation
import json
import os
- import re
-import subprocess
import sys
import threading
import time
diff --cc tui_gateway/agent_factory.py
index cca985c013f,00000000000..7fb49ef72c7
mode 100644,000000..100644
--- a/tui_gateway/agent_factory.py
+++ b/tui_gateway/agent_factory.py
@@@ -1,628 -1,0 +1,632 @@@
+"""TUI agent_factory seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
+from .method_ctx import bind_module
+
+def _env_model_seed() -> str:
+ """The launch-scoped model seed (``hermes --tui -m``, hosted provisioning); "" when unset."""
+ return (os.environ.get("HERMES_MODEL", "") or os.environ.get("HERMES_INFERENCE_MODEL", "")).strip()
+
+
+def _resolve_model() -> str:
+ if env := _env_model_seed():
+ return env
+ m = _load_cfg().get("model", "")
+ if isinstance(m, dict):
+ return str(m.get("default", "") or "").strip()
+ if isinstance(m, str) and m:
+ return m.strip()
+ # No env seed / config preference: the cost-safe silent default (cache-only read), never an unpicked flagship.
+ with contextlib.suppress(Exception):
+ from hermes_cli.models import get_preferred_silent_default_model
+ return get_preferred_silent_default_model()
+ return "z-ai/glm-5.2"
+
+
+def _resolve_session_platform() -> str:
+ """``HERMES_DESKTOP=1`` without ``HERMES_DESKTOP_TERMINAL`` → "desktop" (chat panel; the agent then
+ suggests TUI-only slash commands), else "tui" (embedded terminal pane or standalone ``hermes --tui``)."""
+ desktop = is_truthy_value(os.environ.get("HERMES_DESKTOP"))
+ return "desktop" if desktop and not is_truthy_value(os.environ.get("HERMES_DESKTOP_TERMINAL")) else "tui"
+
+
+def _resolve_session_source(explicit: str | None) -> str:
+ """Session DB ``source``: an explicit caller value (plugin session tagged ``"telegram"``) is never
+ rewritten; only empty/None falls back to the env-resolved platform."""
+ return explicit or _resolve_session_platform()
+
+
+def _resolve_agent_platform(source: str | None) -> str:
+ return _resolve_session_source(source)
+
+
+def _config_model_target() -> tuple[str, str]:
+ """(model, provider) selected by config.yaml — and ONLY config: the HERMES_MODEL launch seed fed into
+ the per-turn sync would be replayed as a /model switch and persisted globally, or pin the session so
+ dashboard/CLI model changes never reach an open chat. Empty model = "no preference" → no-op sync."""
+ cfg_model = _load_cfg().get("model")
+ if isinstance(cfg_model, dict):
+ provider = str(cfg_model.get("provider") or "").strip()
+ return str(cfg_model.get("default", "") or "").strip(), "" if provider.lower() == "auto" else provider
+ return (cfg_model.strip() if isinstance(cfg_model, str) else ""), ""
+
+
+def _resolve_startup_runtime() -> tuple[str, str | None]:
+ model = _resolve_model()
+ if explicit_provider := os.environ.get("HERMES_TUI_PROVIDER", "").strip():
+ return model, explicit_provider
+ if not (explicit_model := _env_model_seed()):
+ return model, None
+ with contextlib.suppress(Exception):
+ from hermes_cli.model_switch import resolve_startup_model_route
+ from hermes_cli.models import detect_static_provider_for_model
+ full_cfg = _load_cfg()
+ cfg = full_cfg.get("model") or {}
+ current_provider = ((str(cfg.get("provider") or "").strip().lower() if isinstance(cfg, dict) else "")
+ or os.environ.get("HERMES_INFERENCE_PROVIDER", "").strip().lower() or "auto")
+ # Same owner as HermesCLI/oneshot: ``custom:<name>:<model>`` selects that provider (#73943).
+ if route := resolve_startup_model_route(
+ explicit_model, current_provider=current_provider,
+ user_providers=full_cfg.get("providers"), custom_providers=full_cfg.get("custom_providers")):
+ return route.model, route.provider
+ if detected := detect_static_provider_for_model(explicit_model, current_provider):
+ provider, detected_model = detected
+ return detected_model, provider
+ return model, None
+
+
+# Bare billing buckets are not routable provider identities; restoring one as a session provider override
+# breaks resume. ``openrouter`` is deliberately NOT in this set (fully routable; agent_init's gate is a different set).
+# (agent_init's fail-fast gate is a DIFFERENT set that also skips "openrouter" — there it means "default
+# route, don't fail fast", not "unroutable".) ``openrouter`` is deliberately excluded here — it is a fully
+# routable provider with its own API key and base_url. Sessions that used OpenRouter store
+# ``billing_provider="openrouter"``; dropping it forces resume to the current global model (e.g. a custom
+# endpoint), which is the wrong provider for the stored model. See #57588.
+
+
+def _is_routable_provider(provider: str) -> bool:
+ with contextlib.suppress(Exception):
+ from hermes_cli.runtime_provider import is_routable_provider
+ return is_routable_provider(provider)
+ return False
+
+
+def _overrides_have_routable_provider(overrides: dict) -> bool:
+ """Whether persisted runtime overrides still name a routable provider (renamed/removed → "Unknown
+ provider" at agent init). Empty = NOT routable, so the caller falls back to the session's picked model."""
+ provider = str(overrides.get("provider_override") or "").strip()
+ if not provider:
+ provider = str((overrides.get("model_override") or {}).get("provider") or "").strip()
+ return bool(provider) and _is_routable_provider(provider)
+
+
+def _parse_model_config(raw, *, quiet: bool = False) -> dict:
+ """A row's ``model_config`` (dict or JSON text) as a dict; ``{}`` when absent/invalid."""
+ if isinstance(raw, dict):
+ return raw
+ if isinstance(raw, str) and raw.strip():
+ try:
+ parsed = json.loads(raw)
+ return parsed if isinstance(parsed, dict) else {}
+ except Exception:
+ if not quiet:
+ raise
+ logger.debug("failed to parse stored session model_config", exc_info=True)
+ return {}
+
+
+def _row_follows_profile(row: dict | None) -> bool:
+ """Whether a stored row is a canonical Bot Chat whose runtime follows the member profile's config.
+ Identity is the persisted ``follow_profile_config`` marker; the bare title compare stays ONLY here as
+ the legacy fallback for rows written before the marker existed."""
+ if not row:
+ return False
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ return bool(model_config.get("follow_profile_config") or str(row.get("title") or "").strip() == "Bot Chat")
+
+
+def _stored_session_runtime_overrides(row: dict | None) -> dict:
+ """Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``):
+ resume restores the model/provider/reasoning THAT chat used, not the global pick. Plugin-owned Bot-Mode
+ sessions normally rebuild from the member profile's CURRENT config (a stale provider pin left room bots
+ "out of Nous credits" after a profile switch). A canonical Bot Chat may instead restore an explicit
+ composer pick while the profile model it diverged from remains unchanged."""
+ if not row:
+ return {}
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ _row_title = str(row.get("title") or "").strip()
+ room_plumbing = model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))
+ composer_profile = model_config.get("composer_override_profile")
+ composer_profile_matches = isinstance(composer_profile, dict) and (
+ str(composer_profile.get("model") or "").strip(),
+ str(composer_profile.get("provider") or "").strip(),
+ ) == _config_model_target()
+ if room_plumbing or (_row_follows_profile(row) and not composer_profile_matches):
+ return {}
+ overrides: dict = {}
+ field = lambda k: str(model_config.get(k) or "").strip()
+ model = str(row.get("model") or model_config.get("model") or "").strip()
+ # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class "custom", which
+ # agent_init treats as non-routable. Only restore an explicit provider; else resume uses the configured default.
+ provider = field("provider")
+ billing_provider = str(model_config.get("billing_provider") or row.get("billing_provider") or "").strip()
+ if not provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:
+ provider = billing_provider
+ base_url, api_mode, service_tier = field("base_url"), field("api_mode"), field("service_tier")
+ reasoning_config = model_config.get("reasoning_config")
++ from hermes_cli.runtime_provider import is_foreign_provider_endpoint
++ if is_foreign_provider_endpoint(provider, base_url):
++ # The endpoint and its wire belong to the provider this chat left; resolve the stored one's own.
++ base_url = api_mode = ""
+ # Heal a stale provider persisted by an older build (renamed/removed custom provider → "Unknown provider"):
+ # recover ``custom:<name>`` from the stored base_url, then from the entry serving the model; else drop it.
+ if provider and not _is_routable_provider(provider):
+ healed = None
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ healed = canonical_custom_identity(base_url=base_url or None, model=model or None)
+ except Exception:
+ logger.debug("custom provider identity recovery failed", exc_info=True)
+ if healed:
+ logger.info("healed stale session provider %r to %r", provider, healed)
+ provider = healed
+ base_url = "" # the healed identity owns a registered endpoint; the snapshot URL must not override it
+ else:
+ provider = ""
+ if model:
+ # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom endpoint
+ # metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.
+ overrides["model_override"] = {
+ "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None}
+ if provider:
+ overrides["provider_override"] = provider
+ if isinstance(reasoning_config, dict):
+ overrides["reasoning_config_override"] = reasoning_config
+ if service_tier: # None = "inherit the profile" at _make_agent; "" = real override "no priority tier"
+ overrides["service_tier_override"] = "" if service_tier.lower() == "normal" else service_tier
+ return overrides
+
+
+def _runtime_model_config(agent, existing: dict | None = None) -> dict:
+ """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``. Falsy agent
+ attributes DELETE the key rather than skip the write: resume reads provider/endpoint from this JSON
+ (model column written separately), so a stale provider would route the resumed chat to the wrong endpoint."""
+ config = dict(existing or {})
+ attr = lambda k: str(getattr(agent, k, "") or "").strip()
+ model, provider, base_url = attr("model"), attr("provider"), attr("base_url")
+ if provider.lower() == "custom":
+ # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the entry
+ # identity (api_key is never persisted): recover ``custom:<name>`` from the endpoint URL.
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ provider = canonical_custom_identity(base_url=base_url, model=model or None) or provider
+ except Exception:
+ logger.debug("custom provider identity lookup failed", exc_info=True)
+ reasoning_config = getattr(agent, "reasoning_config", None)
+ live = {
+ "model": model, "provider": provider, "base_url": base_url, "api_mode": attr("api_mode"),
+ # An empty dict is still a real (present) reasoning config.
+ "reasoning_config": reasoning_config if isinstance(reasoning_config, dict) else None,
+ "service_tier": getattr(agent, "service_tier", None),
+ }
+ for key, value in live.items():
+ if value or isinstance(value, dict):
+ config[key] = value
+ else:
+ config.pop(key, None)
+ return config
+
+
+def _persist_live_session_runtime(session: dict | None) -> None:
+ """Persist active session runtime so future resumes restore the same footer."""
+ live = _live_session_agent_db(session)
+ if live is None:
+ return
+ agent, session_key, db = live
+ try:
+ row = db.get_session(session_key) or {}
+ model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))
+ if isinstance(composer_profile := session.get("composer_override_profile"), dict):
+ model_config["composer_override_profile"] = composer_profile
+ elif "composer_override_profile" in session:
+ model_config.pop("composer_override_profile", None)
+ if (tier_override := session.get("create_service_tier_override")) is not None:
+ # agent.service_tier is None for explicit normal; without this the distinction is erased on every persist.
+ model_config["service_tier"] = tier_override or "normal"
+ model = str(getattr(agent, "model", "") or "").strip()
+ if hasattr(db, "update_session_meta"):
+ db.update_session_meta(session_key, json.dumps(model_config), model or None)
+ elif model and hasattr(db, "update_session_model"):
+ db.update_session_model(session_key, model)
+ except Exception:
+ logger.debug("failed to persist live session runtime", exc_info=True)
+
+def _load_approval_mode() -> str:
+ """Effective ``approvals.mode`` via the gate's own ``_get_approval_mode`` (a raw re-read missed the
+ managed overlay and ``${VAR}`` expansion)."""
+ from tools.approval_context import _get_approval_mode
+ mode = _get_approval_mode()
+ return mode if mode in _APPROVAL_MODES else "manual"
+
+
+def _coerce_statusbar(raw) -> str:
+ if raw is False:
+ return "off"
+ return s if isinstance(raw, str) and (s := raw.strip().lower()) in _STATUSBAR_MODES else "top"
+
+
+_MOUSE_TRACKING_ALIASES = {
+ "0": "off", "1": "all", "all": "all", "any": "all", "button": "buttons", "buttons": "buttons",
+ "click": "buttons", "false": "off", "full": "all", "no": "off", "off": "off", "on": "all",
+ "scroll": "wheel", "true": "all", "wheel": "wheel", "yes": "all",
+}
+
+
+def _display_mouse_tracking(display: dict) -> str:
+ """display.mouse_tracking → ``off|wheel|buttons|all`` (bools: True → all, False → off); ``wheel`` (DEC
+ 1000+1006) is the tmux-friendly subset without hover events. Legacy ``tui_mouse`` only when ``mouse_tracking`` is absent."""
+ if not isinstance(display, dict):
+ return "all"
+ raw = display.get("mouse_tracking") if "mouse_tracking" in display else display.get("tui_mouse", True)
+ if isinstance(raw, str):
+ return _MOUSE_TRACKING_ALIASES.get(raw.strip().lower(), "all")
+ return "off" if raw is False or raw == 0 else "all"
+
+
+def _load_reasoning_config(model: str = "") -> dict | None:
+ """Via the shared chokepoint :func:`hermes_constants.resolve_reasoning_config` (per-model override >
+ global ``agent.reasoning_effort``; YAML False = disabled).
+
+ Closes #21256.
+ """
+ from hermes_constants import resolve_reasoning_config
+ return resolve_reasoning_config(_load_cfg(), model)
+
+
+_SERVICE_TIER_ALIASES = {"fast": "priority", "priority": "priority", "on": "priority", "auto": "auto", "cold": "cold"}
+
+
+def _load_service_tier() -> str | None:
+ raw = str((_load_cfg().get("agent") or {}).get("service_tier", "") or "").strip().lower()
+ return _SERVICE_TIER_ALIASES.get(raw)
+
+
+def _load_provider_routing() -> dict:
+ """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an effectively random provider)."""
+ with contextlib.suppress(Exception):
+ return _load_cfg().get("provider_routing", {}) or {}
+ return {}
+
+
+def _load_show_reasoning() -> bool:
+ # Fallback True — keep in sync with DEFAULT_CONFIG display.show_reasoning (no DEFAULT_CONFIG merge here).
+ return bool(_display_cfg().get("show_reasoning", True))
+
+
+def _load_memory_notifications() -> str:
+ """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates the
+ "💾 Self-improvement review" summary (gateway/CLI parity)."""
+ raw = _display_cfg().get("memory_notifications")
+ if isinstance(raw, bool):
+ return "on" if raw else "off"
+ return str(raw).lower() if raw else "on"
+
+
+_TOOL_PROGRESS_MODES = frozenset({"off", "new", "all", "verbose"})
+
+
+def _load_tool_progress_mode() -> str:
+ env = os.environ.get("HERMES_TUI_TOOL_PROGRESS", "").strip().lower()
+ if env in _TOOL_PROGRESS_MODES:
+ return env
+ raw = _display_cfg().get("tool_progress", "all")
+ if isinstance(raw, bool):
+ return "all" if raw else "off"
+ mode = str(raw or "all").strip().lower()
+ return mode if mode in _TOOL_PROGRESS_MODES else "all"
+
+
+def _gui_surface_toolsets(platform: str) -> set[str]:
+ """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).
+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud
+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""
+ return {"project", "desktop_ui"} if platform == "desktop" else {"project"}
+
+
+def _with_session_toolsets(selection, platform: str | None) -> list[str]:
+ """*selection* plus what the session carries whatever its config says (the client surface's
+ toolsets when *platform* is given; the ones its PROFILE's role reserves, from the backend-written
+ profile.yaml under the session's home override), minus toolsets reserved for another role."""
+ from toolsets import profile_role_toolsets
+ granted, denied = profile_role_toolsets()
+ surface = _gui_surface_toolsets(platform) if platform is not None else set()
+ kept = [name for name in selection if name not in denied]
+ return [*kept, *sorted((surface | granted) - set(kept))]
+
+
+def _tui_notice(text: str) -> None:
+ print(text, file=sys.stderr, flush=True)
+
+
+def _resolve_explicit_toolsets(explicit: list[str], validate_toolset) -> list[str] | None | bool:
+ """Resolve a HERMES_TUI_TOOLSETS pin: list, None for "all", False when nothing was valid."""
+ built_in = [name for name in explicit if validate_toolset(name)]
+ unresolved = [name for name in explicit if name not in built_in]
+ if unresolved:
+ try:
+ from hermes_cli.plugins import discover_plugins
+ discover_plugins()
+ plugin_valid = [name for name in unresolved if validate_toolset(name)]
+ except Exception:
+ plugin_valid = []
+ built_in.extend(plugin_valid)
+ unresolved = [name for name in unresolved if name not in plugin_valid]
+ if any(name in {"all", "*"} for name in built_in):
+ if ignored := [name for name in explicit if name not in {"all", "*"}]:
+ _tui_notice(f"[tui] HERMES_TUI_TOOLSETS=all enables every toolset; ignoring additional entries: {', '.join(ignored)}")
+ return None
+ if not unresolved:
+ return built_in
+ try: # (enabled, disabled) MCP server names from raw config; both empty on any failure
+ from hermes_cli.config import read_raw_config
+ from tools.mcp_tool_common import mcp_server_enabled
+ raw_cfg = read_raw_config()
+ mcp_servers = raw_cfg.get("mcp_servers") if isinstance(raw_cfg.get("mcp_servers"), dict) else {}
+ mcp_names, mcp_disabled = set(), set()
+ for name, server_cfg in mcp_servers.items():
+ if isinstance(server_cfg, dict):
+ on = mcp_server_enabled(server_cfg)
+ (mcp_names if on else mcp_disabled).add(str(name))
+ except Exception:
+ mcp_names, mcp_disabled = set(), set()
+ mcp_valid = [name for name in unresolved if name in mcp_names]
+ disabled = [name for name in unresolved if name in mcp_disabled]
+ unknown = [name for name in unresolved if name not in mcp_names and name not in mcp_disabled]
+ if unknown:
+ _tui_notice(f"[tui] ignoring unknown HERMES_TUI_TOOLSETS entries: {', '.join(unknown)}")
+ if disabled:
+ _tui_notice("[tui] ignoring disabled MCP servers in HERMES_TUI_TOOLSETS "
+ f"(set enabled: true in config.yaml to use): {', '.join(disabled)}")
+ return (built_in + mcp_valid) or False
+
+
+def _load_enabled_toolsets(platform: str | None = None) -> list[str] | None:
+ """The agent's toolsets for this session (None = all): an explicit HERMES_TUI_TOOLSETS pin; else the
+ coding posture (coding_context collapses to coding toolset + enabled MCP servers in a code workspace);
+ else the configured CLI toolsets. Client-surface toolsets fold in here — only this surface can answer them."""
+ session_platform = platform or _resolve_session_platform()
+ explicit = [item.strip() for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",") if item.strip()]
+ fallback_notice = None
+ if not explicit:
+ with contextlib.suppress(Exception):
+ from agent.coding_context import coding_selection
+ selection = coding_selection(platform=session_platform)
+ if selection is not None:
+ return sorted(_with_session_toolsets(selection, session_platform))
+ try:
+ from toolsets import validate_toolset
+ except Exception:
+ validate_toolset = None
+ if explicit and validate_toolset is not None:
+ resolved = _resolve_explicit_toolsets(explicit, validate_toolset)
+ if resolved is not False:
+ # An operator pin replaces the surface fold-in but never strips the profile's own role toolsets.
+ return resolved if resolved is None else _with_session_toolsets(resolved, None)
+ fallback_notice = "[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsets"
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.tools_config import _get_platform_tools
+ cfg = load_config()
+ # include_default_mcp_servers=True is the runtime variant (the agent must be able to call
+ # default MCP servers); the config-editing variant would silently drop MCP tools from the TUI.
+ # Passing ``False`` here is the config-editing variant — used when we need to persist a toolset list
+ # without baking in implicit MCP defaults. Using the wrong variant at agent creation time makes MCP
+ # tools silently missing from the TUI. See PR #3252 for the original design split.
+ enabled = _get_platform_tools(cfg, "cli", include_default_mcp_servers=True)
+ if fallback_notice is not None:
+ _tui_notice(fallback_notice)
+ return sorted(_with_session_toolsets(enabled, session_platform)) if enabled else None
+ except Exception:
+ if fallback_notice is not None:
+ _tui_notice("[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets")
+ return None
+
+
+def _session_tool_progress_mode(sid: str) -> str:
+ return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all")
+
+
+def _session_verbose(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) == "verbose"
+
+
+def _tool_progress_enabled(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) != "off"
+
+
+def _tool_lifecycle_required_for_ui(name: str) -> bool:
+ """Interactive UI, not optional chrome: Desktop renders clarify / connection cards from the tool-call part."""
+ return name in ("clarify", "manage_connections", "setup_mcp")
+
+def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _RuntimeFallbackResolution:
+ """Resolve the primary runtime or one complete provider/model fallback. Provider-only fallback entries
+ are skipped so the unavailable primary model can never leak into a different runtime."""
+ from hermes_cli.auth import AuthError
+ from hermes_cli.runtime_provider import resolve_runtime_provider
+ try:
+ return _RuntimeFallbackResolution(resolve_runtime_provider(**(resolve_kwargs or {})), None, False)
+ except AuthError as primary_exc:
+ for entry in _load_fallback_model() or []:
+ fb_provider = str(entry.get("provider") or "").strip() if isinstance(entry, dict) else ""
+ fb_model = str(entry.get("model") or "").strip() if isinstance(entry, dict) else ""
+ if not fb_provider or not fb_model:
+ continue
+ try:
+ from hermes_cli.fallback_config import effective_runtime_provider, resolve_entry_api_key
+ fb_kwargs: dict = {"requested": fb_provider, "target_model": fb_model,
+ **({"explicit_base_url": entry["base_url"]} if entry.get("base_url") else {})}
+ if fb_api_key := resolve_entry_api_key(entry):
+ fb_kwargs["explicit_api_key"] = fb_api_key
+ runtime = resolve_runtime_provider(**fb_kwargs)
+ # Named custom entries resolve to the bare "custom" billing class; keep the configured
+ # identity so the session/UI shows the provider name, matching the manual-switch path (#98739).
+ runtime["provider"] = effective_runtime_provider(entry, runtime)
+ from hermes_cli.auth import primary_failure_wording
+ logging.getLogger(__name__).warning(
+ "Primary %s (%s), falling back to %s model %s",
+ primary_failure_wording(primary_exc)[0], primary_exc, fb_provider, fb_model)
+ return _RuntimeFallbackResolution(runtime, fb_model, True)
+ except Exception:
+ continue
+ raise
+
+
+def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[str, dict]:
+ """(model, runtime) for a new agent; a per-session override (/model switch or a resumed row's persisted
+ runtime) wins over global config/env. Older rows stored the resolved provider "custom" (no named entry
+ matches) — recover the identity from the persisted base_url or the rebuild fails "No LLM provider
+ configured". Persisted base_url/api_key/api_mode are honored only for the original runtime, never a fallback."""
+ if isinstance(model_override, dict) and model_override.get("model"):
+ model = str(model_override.get("model") or "")
+ requested_provider = model_override.get("provider") or provider_override or None
+ override_base_url = model_override.get("base_url")
+ resolve_kwargs = {}
+ if str(requested_provider or "").strip().lower() == "custom":
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ if recovered := canonical_custom_identity(base_url=override_base_url or None, model=model or None):
+ requested_provider = recovered
+ if override_base_url:
+ # Failing identity recovery, still hand base_url to the direct-alias branch so pool/env credentials resolve.
+ resolve_kwargs["explicit_base_url"] = override_base_url
+ resolve_kwargs.update(requested=requested_provider, target_model=model or None)
+ overrides = {k: model_override.get(k) for k in ("base_url", "api_key", "api_mode")}
+ else:
+ model, requested_provider = _resolve_startup_runtime()
+ if isinstance(model_override, str) and model_override:
+ model = model_override
+ if provider_override:
+ requested_provider = provider_override
+ resolve_kwargs = {"requested": requested_provider, "target_model": model or None}
+ overrides = {}
+ resolution = _resolve_runtime_with_fallback(resolve_kwargs)
+ if resolution.used_fallback:
+ if not resolution.selected_model:
+ raise RuntimeError("Auth fallback resolved without a model")
+ # Same pre-agent switch the messaging gateway surfaces (#74349); _make_agent pops it onto the
+ # agent's one-shot notice so the TUI/Desktop user sees which provider actually answered.
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ # requested_provider=None means resolve_runtime_provider read the persisted config provider.
+ primary_provider = requested_provider or (_load_cfg().get("model") or {}).get("provider")
+ resolution.runtime["_fallback_notice"] = pre_agent_fallback_notice(
+ primary_provider, model, resolution.runtime.get("provider"), resolution.selected_model)
+ return resolution.selected_model, resolution.runtime
+ if resolution.runtime.get("source") == "local-runtime":
+ # Live supervisor beat any persisted loopback URL for this identity.
+ overrides.pop("base_url", None)
+ resolution.runtime.update({k: v for k, v in overrides.items() if v})
+ if any(overrides.values()):
+ _rederive_per_model_route(model, resolution.runtime)
+ return model, resolution.runtime
+
+
+def _rederive_per_model_route(model: str, runtime: dict) -> None:
+ """A row's persisted api_mode/base_url were written for whichever model the session last ran. Providers
+ that pick the wire per model (OpenCode Zen/Go, Copilot, Nous) must re-derive both from the target model,
+ or a resumed opencode-go session keeps a MiniMax-era anthropic_messages route (and its /v1-stripped or
+ other-family relay URL) for a chat_completions model like deepseek-v4-flash-vision-exp (#96066)."""
+ from hermes_cli.model_switch import model_derived_api_mode
+ from hermes_cli.models import normalize_opencode_base_url
+ provider = str(runtime.get("requested_provider") or runtime.get("provider") or "")
+ api_mode = model_derived_api_mode(provider, model)
+ if api_mode is None:
+ return
+ runtime["api_mode"] = api_mode
+ runtime["base_url"] = normalize_opencode_base_url(provider, api_mode, runtime.get("base_url"))
+
+
+def _startup_system_prompt(cfg: dict, task_id: str) -> str:
+ """Config ephemeral system prompt + HERMES_TUI_SKILLS preload block. Hard-fails only when EVERY requested
+ skill is missing (cli.py parity): a typo'd name must not auto-block the Kanban task."""
+ from hermes_cli.config import resolve_ephemeral_system_prompt_from_config
+ system_prompt = resolve_ephemeral_system_prompt_from_config(cfg)
+ startup_skills = _parse_tui_skills_env()
+ if not startup_skills:
+ return system_prompt
+ from agent.skill_commands import build_preloaded_skills_prompt
+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)
+ if missing_skills:
+ missing_display = ", ".join(missing_skills)
+ if not loaded_skills:
+ raise ValueError(f"Unknown skill(s): {missing_display}")
+ logger.warning("Unknown skill(s) requested, skipping: %s. Continuing with: %s. "
+ "List available skills with `hermes skills list`.", missing_display, ", ".join(loaded_skills))
+ if skills_prompt:
+ system_prompt = "\n\n".join(part for part in (system_prompt, skills_prompt) if part).strip()
+ return system_prompt
+
+
+def _make_agent(
+ sid: str, key: str, session_id: str | None = None, session_db=None,
+ model_override: dict | str | None = None, provider_override: str | None = None,
+ reasoning_config_override: dict | None = None, service_tier_override: str | None = None,
+ platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None,
+ cwd_override: str | None = None, auth_user_id: str | None = None):
+ # AC-4 test seam: dead unless armed by the isolated certify harness.
+ from tui_gateway.synthetic_turn import maybe_build_synthetic_agent
+ synthetic = maybe_build_synthetic_agent(session_id or key, model_override)
+ if synthetic is not None:
+ return synthetic
+ from run_agent import AIAgent
+ # MCP discovery runs in a daemon thread (a dead server can't freeze the shell); the agent snapshots its tool
+ # list once, so briefly wait for in-flight discovery. Dashboard /api/ws uses mcp_startup; TUI stdio uses entry.
+ for _mod in ("hermes_cli.mcp_startup", "tui_gateway.entry"):
+ with contextlib.suppress(Exception):
+ importlib.import_module(_mod).wait_for_mcp_discovery()
+ cfg = _load_cfg()
+ # Load hooks alongside the same profile config used to construct this agent.
+ from agent.shell_hooks import register_from_config
+ register_from_config(cfg)
+ system_prompt = _startup_system_prompt(cfg, session_id or key)
+ model, runtime = _resolve_agent_model_runtime(model_override, provider_override)
+ fallback_notice = runtime.pop("_fallback_notice", None)
+ _pr = _load_provider_routing()
+ platform = _resolve_agent_platform(platform_override)
+ ignore_rules = is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))
+ with _sessions_lock:
+ session = _sessions.get(sid)
+ agent = AIAgent(
+ model=model, max_iterations=_cfg_max_turns(cfg, 500), provider=runtime.get("provider"),
+ requested_provider=runtime.get("requested_provider"),
+ base_url=runtime.get("base_url"), api_key=runtime.get("api_key"), api_mode=runtime.get("api_mode"),
+ acp_command=runtime.get("command"), acp_args=runtime.get("args"),
+ credential_pool=runtime.get("credential_pool"), quiet_mode=True,
+ verbose_logging=False, # DEBUG agent logging; independent of tool_progress_mode
+ reasoning_config=(
+ reasoning_config_override if reasoning_config_override is not None else _load_reasoning_config(str(model or ""))),
+ service_tier=service_tier_override if service_tier_override is not None else _load_service_tier(),
+ enabled_toolsets=_load_enabled_toolsets(platform),
+ # OpenRouter provider_routing prefs (gateway + CLI parity).
+ providers_allowed=_pr.get("only"), providers_ignored=_pr.get("ignore"), providers_order=_pr.get("order"),
+ provider_sort=_pr.get("sort"), provider_require_parameters=_pr.get("require_parameters", False),
+ provider_data_collection=_pr.get("data_collection"), platform=platform, session_id=session_id or key,
+ cwd=cwd_override,
+ # The dashboard login identity reaches memory providers as the runtime user, like a gateway user id.
+ # Builds that run before the record exists (branch, eager resume, compute host) pass it explicitly.
+ user_id=auth_user_id if auth_user_id is not None else _session_auth_user_id(session),
+ session_db=session_db if session_db is not None else _get_db(), ephemeral_system_prompt=system_prompt or None,
+ checkpoints_enabled=is_truthy_value(os.environ.get("HERMES_TUI_CHECKPOINTS")),
+ pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),
+ skip_context_files=ignore_rules, skip_memory=ignore_rules, fallback_model=_load_fallback_model(),
+ **_agent_cbs(sid))
+ if context_cwd_is_launch_artifact is None:
+ context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(session)
+ agent._context_cwd_is_launch_artifact = bool(context_cwd_is_launch_artifact)
+ if fallback_notice:
+ # Emitted once on the first successful reply via _emit_pending_fallback_notice -> status_callback.
+ agent._pending_fallback_notice = fallback_notice
+ return agent
+
+
+def register(server):
+ bind_module(globals(), server)
diff --cc ui-tui/src/__tests__/createSlashHandler.test.ts
index 5a299a597aa,804753b9a02..8240f1acf30
--- a/ui-tui/src/__tests__/createSlashHandler.test.ts
+++ b/ui-tui/src/__tests__/createSlashHandler.test.ts
@@@ -527,27 -467,7 +479,7 @@@ describe('createSlashHandler', () =>
expect(ctx.gateway.gw.request).not.toHaveBeenCalled()
})
- it('skips the confirmation for the /reset alias when config disables it', () => {
- patchUiState({ destructiveSlashConfirm: false })
-
- const ctx = buildCtx({
- local: {
- catalog: {
- canon: {
- '/new': '/new',
- '/reset': '/new'
- }
- }
- }
- })
-
- expect(createSlashHandler(ctx)('/reset')).toBe(true)
-
- expect(getOverlayState().confirm).toBeNull()
- expect(ctx.session.newSession).toHaveBeenCalledWith('new session started', undefined)
- })
-
- it('keeps visible scrollback when branching a TUI session', async () => {
+ it('hydrates a branch through session resume without prematurely replacing source state', async () => {
patchUiState({ sid: 'sid-parent' })
const rpc = vi.fn(() => Promise.resolve({ session_id: 'sid-branch', title: 'branch title' }))
const ctx = buildCtx({ gateway: { ...buildGateway(), rpc } })
diff --cc ui-tui/src/__tests__/submissionCore.test.ts
index e3011a5d499,19e33e3bb9c..87ae31967d8
--- a/ui-tui/src/__tests__/submissionCore.test.ts
+++ b/ui-tui/src/__tests__/submissionCore.test.ts
@@@ -1,7 -1,6 +1,7 @@@
import { beforeEach, describe, expect, it, vi } from 'vitest'
- import { isSessionBusyError, markSubmitting, submitPrompt, type SubmitPromptDeps } from '../app/submissionCore.js'
+ import { isSessionBusyError, submitPrompt, type SubmitPromptDeps } from '../app/submissionCore.js'
+import { captureDestination } from '../app/submissionDestination.js'
import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'
import type { GatewayClient } from '../gatewayClient.js'
@@@ -151,106 -132,6 +133,96 @@@ describe('submissionCore.submitPrompt �
})
})
+it('keeps the submit destination across preprocessing and never mutates the newly focused session', async () => {
+ resetUiState()
+ patchUiState({ sid: 'original' })
+ const { gw, resolveDrop } = makeDeferredGateway()
+ const deps = makeDeps(gw)
+ submitPrompt('private', deps)
+ patchUiState({ sid: 'other', busy: false, status: 'other ready' })
+ resolveDrop()
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(gw.request).toHaveBeenCalledWith(
+ 'prompt.submit',
+ expect.objectContaining({ session_id: 'original', text: 'private' })
+ )
+ expect(deps.appendMessage).not.toHaveBeenCalled()
+ expect(getUiState()).toMatchObject({ sid: 'other', busy: false, status: 'other ready' })
+})
+
+it('retains a queued submission on ambiguous response and retries the exact identity until durable acknowledgement', async () => {
+ resetUiState()
+ patchUiState({ sid: 'owner', info: { model: 'test', tools: {}, skills: {}, stored_session_id: 'stored-owner' } })
+ const settle = vi.fn()
+ const item = { text: 'private', display: 'private', submissionId: 'stable-id', settle }
+
+ const request = vi.fn().mockResolvedValueOnce({ status: 'streaming' }).mockResolvedValueOnce({
+ admission_id: 'stable-id',
+ target_session_id: 'stored-owner',
+ target_profile_home: captureDestination().profileHome,
+ status: 'queued'
+ })
+
+ const deps = makeDeps({ request } as unknown as GatewayClient)
+ submitPrompt(item.text, deps, true, undefined, { skipDetectDrop: true, queueItem: item })
+ await Promise.resolve()
+ expect(settle).toHaveBeenLastCalledWith(false)
+ submitPrompt(item.text, deps, true, undefined, { skipDetectDrop: true, queueItem: item })
+ await Promise.resolve()
+ expect(request.mock.calls.map(call => call[1])).toEqual([
+ { session_id: 'owner', text: 'private', submission_id: 'stable-id', queued: true },
+ { session_id: 'owner', text: 'private', submission_id: 'stable-id', queued: true }
+ ])
+ expect(settle).toHaveBeenLastCalledWith(true)
+
+ for (const stored_session_id of [undefined, 'wrong-target']) {
+ patchUiState({ info: { model: 'test', tools: {}, skills: {}, stored_session_id } })
+ request.mockResolvedValueOnce({ admission_id: 'stable-id', target_session_id: 'owner',
+ target_profile_home: captureDestination().profileHome, status: 'queued' })
+ submitPrompt(item.text, deps, true, undefined, { skipDetectDrop: true, queueItem: item })
+ await Promise.resolve()
+ expect(settle).toHaveBeenLastCalledWith(false)
+ }
+})
+
+it('preserves legacy isolated submission after explicit unsupported admission without repeating preprocessing', async () => {
+ resetUiState()
+ patchUiState({ sid: 'owner' })
+ const settle = vi.fn()
+ const item = { text: 'private', display: 'private', submissionId: 'unsupported-id', queued: true, settle }
+ let reject!: (error: unknown) => void
+
+ const request = vi.fn().mockReturnValueOnce(new Promise((_, fail) => { reject = fail }))
+ .mockResolvedValueOnce({ status: 'queued' })
+
+ const deps = makeDeps({ request } as unknown as GatewayClient)
+ submitPrompt(item.text, deps, true, undefined, { skipDetectDrop: true, queueItem: item })
+ patchUiState({ sid: 'other', busy: false, status: 'other ready' })
+ reject(Object.assign(new Error('unsupported'), { code: 4094 }))
+ await vi.waitFor(() => expect(settle).toHaveBeenLastCalledWith(true))
+ expect(request.mock.calls.map(call => call[1])).toEqual([
+ { session_id: 'owner', text: 'private', submission_id: 'unsupported-id', queued: true },
+ { session_id: 'owner', text: 'private', queued: true }
+ ])
+ expect(deps.appendMessage).toHaveBeenCalledTimes(1)
+ expect(getUiState()).toMatchObject({ sid: 'other', busy: false, status: 'other ready' })
+})
+
+it('never downgrades ambiguous or conflicting durable submissions to legacy delivery', async () => {
+ for (const code of [undefined, 4093, 5071]) {
+ resetUiState()
+ patchUiState({ sid: 'owner' })
+ const settle = vi.fn()
+ const item = { text: 'private', display: 'private', submissionId: 'retained-id', settle }
+ const request = vi.fn().mockRejectedValue(Object.assign(new Error('not admitted'), { code }))
+ submitPrompt(item.text, makeDeps({ request } as unknown as GatewayClient), true, undefined,
+ { skipDetectDrop: true, queueItem: item })
+ await vi.waitFor(() => expect(settle).toHaveBeenLastCalledWith(false))
+ expect(request).toHaveBeenCalledTimes(1)
+ }
+})
+
- describe('submissionCore.markSubmitting', () => {
- beforeEach(() => resetUiState())
-
- it('sets busy + running status', () => {
- markSubmitting()
- expect(getUiState().busy).toBe(true)
- expect(getUiState().status).toBe('running…')
- })
- })
-
describe('submissionCore.isSessionBusyError', () => {
it('matches the legacy busy rejections but not arbitrary errors', () => {
expect(isSessionBusyError(new Error('session busy'))).toBe(true)
diff --cc ui-tui/src/app/useSessionLifecycle.ts
index 67be0999918,09314d14e9c..0a8ae0ab964
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@@ -6,7 -5,7 +6,8 @@@ import { evictInkCaches } from '@hermes
import type { InflightTurn, SessionResumeResult, Usage } from '@hermes/shared/gateway-events'
import { type RefObject, useCallback, useEffect, useMemo, useRef } from 'react'
+import { localCreationOptions } from '../canonicalGateway.js'
+ import { STARTUP_WORKSPACE_CWD } from '../config/env.js'
import { buildSetupRequiredSections, SETUP_REQUIRED_TITLE } from '../content/setup.js'
import { introMsg, toTranscriptMessages } from '../domain/messages.js'
import { ZERO } from '../domain/usage.js'
@@@ -278,113 -196,96 +279,118 @@@ export function useSessionLifecycle(opt
const startNewSession = useCallback(
async (msg?: string, title?: string, keepCurrent = false) => {
- const setup = await rpc<SetupStatusResponse>('setup.status', {})
+ const flight = ++attachmentFlight.current
+ const previousSid = getUiState().sid
+ const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
+ pendingAttachments.current.add(flight)
- if (setup?.provider_configured === false) {
- panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())
- patchUiState({ status: 'setup required' })
+ try {
+ const setup = gw.isCanonical ? null : await rpc<SetupStatusResponse>('setup.status', {})
- return null
- }
+ if (flight !== attachmentFlight.current) {return null}
- const previousSid = getUiState().sid
+ if (setup?.provider_configured === false) {
+ panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())
+ patchUiState({ status: 'setup required' })
- if (!keepCurrent) {
- await closeSession(previousSid)
- }
+ return null
+ }
- const r = await rpc<SessionCreateResponse>('session.create', {
- cols: colsRef.current,
- ...(STARTUP_WORKSPACE_CWD ? { cwd: STARTUP_WORKSPACE_CWD } : {})
- })
+ if (!keepCurrent) {
+ await closeSession(previousSid)
- if (!r) {
- patchUiState({ status: 'ready' })
+ if (flight !== attachmentFlight.current) {return null}
+ }
- return null
- }
++ // HERMES_TUI_CWD is the dashboard-picked workspace: an explicit cwd on
++ // session.create on both transports, so /new stays in that workspace.
++ const workspaceCwd = STARTUP_WORKSPACE_CWD ? { cwd: STARTUP_WORKSPACE_CWD } : {}
+
- // The durable id lives on the create result; the lazy-create `info` does
- // not carry it, and session.resume / the exit epilogue need the stored id.
- const storedSid = r.stored_session_id || r.session_id
- const info = r.info ? { ...r.info, stored_session_id: storedSid } : null
- const requestedTitle = title?.trim() ?? ''
-
- resetSession()
- setSessionStartedAt(Date.now())
-
- writeActiveSessionFile(storedSid)
- patchUiState({
- info,
- sid: r.session_id,
- status: info?.version ? 'ready' : 'starting agent…',
- storedSid,
- usage: usageFrom(info)
- })
+ const r = await rpc<SessionCreateResponse>('session.create', gw.isCanonical
- ? { request_id: randomUUID(), ...localCreationOptions() } : { cols: colsRef.current })
++ ? { request_id: randomUUID(), ...localCreationOptions(), ...workspaceCwd }
++ : { cols: colsRef.current, ...workspaceCwd })
- if (info) {
- setHistoryItems([introMsg(info)])
- }
+ if (flight !== attachmentFlight.current) {
+ discardStaleAttachment(r)
- if (info?.credential_warning) {
- sys(`warning: ${describeCredentialWarning(info.credential_warning)}`)
- }
+ return null
+ }
- if (info?.config_warning) {
- sys(`warning: ${info.config_warning}`)
- }
+ if (!r) {
+ patchUiState({ status: 'ready' })
- if (msg) {
- sys(msg)
- }
+ return null
+ }
- if (requestedTitle) {
- rpc<SessionTitleResponse>('session.title', {
- session_id: r.session_id,
- title: requestedTitle
+ // The durable id lives on the create result; the lazy-create `info` does
+ // not carry it, and session.resume / the exit epilogue need the stored id.
+ const storedSid = r.stored_session_id || r.info?.stored_session_id || r.session_id
+ const info = r.info ? { ...r.info, stored_session_id: storedSid } : null
+ const requestedTitle = title?.trim() ?? ''
+
+ resetSession()
+ setSessionStartedAt(Date.now())
+
+ writeActiveSessionFile(storedSid)
+ patchUiState({
+ info,
+ sid: r.session_id,
+ status: gw.isCanonical || info?.version ? 'ready' : 'starting agent…',
+ storedSid,
+ usage: usageFrom(info)
})
- .then(result => {
- if (!result || getUiState().sid !== r.session_id) {
- return
- }
- const nextTitle = (result.title ?? requestedTitle).trim()
- const suffix = result.pending ? ' (queued while session initializes)' : ''
- patchUiState({ sessionTitle: nextTitle })
- sys(`session title set: ${nextTitle}${suffix}`)
- })
- .catch((err: unknown) => {
- if (getUiState().sid !== r.session_id) {
- return
- }
+ if (info) {
+ setHistoryItems([introMsg(info)])
+ }
- const message = err instanceof Error ? err.message : String(err)
- sys(`warning: failed to set session title: ${message}`)
+ if (info?.credential_warning) {
+ sys(`warning: ${describeCredentialWarning(info.credential_warning)}`)
+ }
+
+ if (info?.config_warning) {
+ sys(`warning: ${info.config_warning}`)
+ }
+
+ if (msg) {
+ sys(msg)
+ }
+
+ if (requestedTitle) {
+ rpc<SessionTitleResponse>('session.title', {
+ session_id: r.session_id,
+ title: requestedTitle
})
- }
+ .then(result => {
+ if (!result || getUiState().sid !== r.session_id) {
+ return
+ }
+
+ const nextTitle = (result.title ?? requestedTitle).trim()
+ const suffix = result.pending ? ' (queued while session initializes)' : ''
+ patchUiState({ sessionTitle: nextTitle })
+ sys(`session title set: ${nextTitle}${suffix}`)
+ })
+ .catch((err: unknown) => {
+ if (getUiState().sid !== r.session_id) {
+ return
+ }
+
+ const message = err instanceof Error ? err.message : String(err)
+ sys(`warning: failed to set session title: ${message}`)
+ })
+ }
- signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)
+ signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)
+ adoptAttachment(r, previousSid, previousSubscription)
- return r.session_id
+ return r.session_id
+ } finally {
+ finishAttachment(flight)
+ }
},
- [closeSession, colsRef, onFreshSessionStarted, panel, resetSession, rpc, setHistoryItems, setSessionStartedAt, sys]
+ [adoptAttachment, closeSession, colsRef, discardStaleAttachment, finishAttachment, gw.isCanonical, onFreshSessionStarted, panel,
+ resetSession, rpc, setHistoryItems, setSessionStartedAt, sys]
)
const newSession = useCallback(