Skip to content

The agent that grows with you

Merge origin/main (#16: 4,465 commits to 9dcab1e440c) into feat/unified-gateway-runtime

Teknium1e500ebce2a9
diff --cc .github/workflows/ci.yaml
index aec32e5870a,9e801a5284c..9eff2ed6706
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@@ -76,17 -76,13 +76,18 @@@ jobs
desktop_updater: ${{ steps.gate-lanes.outputs.desktop_updater }}
rust: ${{ steps.gate-lanes.outputs.rust }}
docker_meta: ${{ steps.gate-lanes.outputs.docker_meta }}
- mcp_catalog: ${{ steps.gate-lanes.outputs.mcp_catalog }}
- ci_review: ${{ steps.classify.outputs.ci_review }}
- ci_review_files: ${{ steps.classify.outputs.ci_review_files }}
+ e2e: ${{ steps.gate-lanes.outputs.e2e }}
+ e2e_upgrade: ${{ steps.gate-lanes.outputs.e2e_upgrade }}
+ e2e_desktop_core: ${{ steps.gate-lanes.outputs.e2e_desktop_core }}
+ e2e_desktop_update: ${{ steps.gate-lanes.outputs.e2e_desktop_update }}
event_name: ${{ github.event_name }}
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7.0.1
+ with:
+ sparse-checkout: |
+ .github/actions/detect-changes
+ scripts/ci/classify_changes.py
+ sparse-checkout-cone-mode: false
- name: Detect affected areas
id: classify
uses: ./.github/actions/detect-changes
diff --cc agent/conversation_compression.py
index a7bb49cade0,a8b6da0a8a8..1bb717c03d2
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@@ -3280,8 -3259,21 +3259,12 @@@ def _carry_session_state_to_child(agent
is carried unchanged (renumbering per rotation made one session look like many); its provenance is read BEFORE the
transfer clears the ancestor's row, then restored so an inherited auto-title stays upgradeable.
"""
- with _swallow('Could not migrate goal on compression: %s'):
- # Carry a persistent /goal onto the continuation session. Compression mints a fresh child id;
- # load_goal does a flat per-session lookup with no parent walk, so without this an active goal
- # silently dies at the boundary (#33618).
- from hermes_cli.goals import migrate_goal_to_session
- migrate_goal_to_session(old_session_id, agent.session_id, reason="compression")
- with _swallow('Could not migrate heartbeat on compression: %s'):
- from hermes_cli.heartbeat import migrate_heartbeat_to_session
- migrate_heartbeat_to_session(old_session_id, agent.session_id)
- with _swallow('Could not migrate loop on compression: %s'):
- from hermes_cli.loops import migrate_loop_to_session
- migrate_loop_to_session(old_session_id, agent.session_id, reason="compression")
++ # /goal, /heartbeat, /loop: carried locally, or atomically by the owner on a RuntimeSessionStore.
+ from agent.compression_automation import carry_compression_automation
+ carry_compression_automation(agent, old_session_id)
+ with _swallow('Could not carry rejected thinking on compression: %s'):
+ from agent.anthropic_thinking_replay import carry_rejected_thinking_to_session
+ carry_rejected_thinking_to_session(agent, old_session_id)
if not old_title:
return
_src = None
diff --cc agent/runtime_session_store.py
index 1392ff1056f,00000000000..a1dce5db706
mode 100644,000000..100644
--- a/agent/runtime_session_store.py
+++ b/agent/runtime_session_store.py
@@@ -1,331 -1,0 +1,334 @@@
+"""Explicit worker persistence facade; never opens the canonical SQLite store.
+
+This first operation family is deliberately NOT a complete SessionDB substitute.
+No existing cron/child/compute consumer is switched until its inventory is covered.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+from pathlib import Path
+import tempfile
+import threading
+
+
+_worker_process = False
+
+
+def is_worker_process():
+ """A successful self-registration makes this interpreter compute-only.
+
+ Process-scoped (not ContextVar): import-time recovery and fresh helper threads
+ must not regain owner-ledger access. This is cooperative runtime ownership,
+ not OS confinement or an authorization credential.
+ """
+ return _worker_process
+
+
+
+def apply_row_annotations(messages, annotations):
+ """Mirror the owner's in-place row stamps onto the worker's dicts (None = the owner popped it)."""
+ for message, annotation in zip(messages, annotations, strict=True):
+ for key, value in annotation.items():
+ if value is None:
+ message.pop(key, None)
+ else:
+ message[key] = value
+
+class WorkerPersistenceError(RuntimeError):
+ pass
+
+
+class WorkerRPC:
+ """Bounded authenticated calls to an existing owner; never starts a daemon.
+
+ websockets.sync owns a dedicated frame receiver, independent of the caller.
+ No owner-loop synchronous self-RPC or SQLite fallback is permitted.
+ """
+ def __init__(self, home):
+ self.home = Path(home).resolve()
+ self.lock = threading.Lock()
+
+ def __call__(self, method, **params):
+ from hermes_cli.gateway_client import _session_ticket
+ from hermes_cli.gateway_runtime_discovery import query_identify
+ from websockets.sync.client import connect
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ pass
+ else:
+ raise WorkerPersistenceError('synchronous_rpc_on_event_loop')
+ with self.lock:
+ # A served secondary has no socket; its multiplexer's descriptor names it.
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint
+ discovery = discover_gateway_endpoint(self.home, timeout=5)
+ if discovery.state != 'ready' or discovery.endpoint is None:
+ raise WorkerPersistenceError('owner_unavailable')
+ from hermes_cli.gateway_runtime import control_home_for
+ descriptor = query_identify(control_home_for(self.home, discovery.endpoint), timeout=5)
+ if descriptor.get('pid') == os.getpid():
+ raise WorkerPersistenceError('synchronous_self_rpc')
+ endpoint = discovery.endpoint
+ ticket = _session_ticket(self.home, endpoint,
+ purpose='interactive' if method == 'worker.register' else 'worker-adoption')
+ url = endpoint.api_origin.replace('https:', 'wss:').replace('http:', 'ws:') + '/api/ws'
+ with connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket],
+ open_timeout=5, close_timeout=1, max_size=8 * 1024 * 1024) as ws:
+ ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}))
+ import time
+ deadline = time.monotonic() + 20
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise TimeoutError('worker_receipt_timeout')
+ response = json.loads(ws.recv(timeout=remaining))
+ if response.get('id') == 1:
+ break
+ if 'error' in response:
+ raise WorkerPersistenceError(response['error'].get('message', 'persistence_failed'))
+ if method in ('worker.register', 'worker.adopt') and params.get('pid') == os.getpid():
+ global _worker_process
+ _worker_process = True
+ return response['result']
+
+
+from agent.runtime_session_compression import RuntimeSessionCompressionMixin
+
+
+from agent.runtime_session_lifecycle import RuntimeSessionLifecycleMixin
+
+
+class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecycleMixin):
+ """Synchronous durable results with a private byte-bounded retry journal.
+
+ A failed write remains pending, and failure is sticky until explicit retry or
+ adoption. Local queue acceptance is never returned as canonical commit.
+ Pending journals live outside age-pruned cache trees.
+ """
+ def __init__(self, rpc, scope, outbox_dir, *, max_bytes=4 * 1024 * 1024):
+ self.rpc = rpc
+ self.scope = dict(scope)
+ self.max_bytes = max_bytes
+ self.lock = threading.RLock()
+ self.failure = None
+ self.path = Path(outbox_dir) / 'pending.json'
+ self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ if self.path.parent.is_symlink() or self.path.is_symlink():
+ raise WorkerPersistenceError('unsafe_outbox')
+ os.chmod(self.path.parent, 0o700)
+ from gateway.status import _try_acquire_file_lock
+ lock_path = self.path.parent / 'owner.lock'
+ if lock_path.is_symlink():
+ raise WorkerPersistenceError('unsafe_outbox')
+ self._outbox_owner = lock_path.open('a+', encoding='utf-8')
+ os.chmod(lock_path, 0o600)
+ if not _try_acquire_file_lock(self._outbox_owner):
+ self._outbox_owner.close()
+ raise WorkerPersistenceError('outbox_in_use')
+ try:
+ if self.path.exists():
+ if self.path.stat().st_size > max_bytes:
+ raise WorkerPersistenceError('outbox_full')
+ self.journal = json.loads(self.path.read_text(encoding="utf-8-sig"))
+ if self.journal['scope'] != self.scope:
+ raise WorkerPersistenceError('outbox_scope_mismatch')
+ else:
+ self.journal = {'scope': self.scope, 'next_sequence': 1, 'pending': []}
+ self._save(self.journal)
+ if is_worker_process():
+ from tools.async_delegation_worker import bind_worker_delegation_store
+ bind_worker_delegation_store(self)
+ except Exception:
+ self._outbox_owner.close()
+ raise
+
+ def _save(self, journal):
+ if self._outbox_owner.closed:
+ raise WorkerPersistenceError('outbox_closed')
+ encoded = json.dumps(journal, ensure_ascii=True, allow_nan=False, separators=(',', ':')).encode()
+ if len(encoded) > self.max_bytes:
+ self.failure = 'outbox_full'
+ raise WorkerPersistenceError(self.failure)
+ fd, temporary = tempfile.mkstemp(prefix='.pending-', dir=self.path.parent)
+ try:
+ with os.fdopen(fd, 'wb') as stream:
+ stream.write(encoded)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, self.path)
+ if os.name != 'nt':
+ directory = os.open(self.path.parent, os.O_RDONLY)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+ def _session(self, session_id):
+ if session_id != self.scope['session_id']:
+ raise WorkerPersistenceError('permission_denied')
+
+ def _apply(self, operation, payload):
+ with self.lock:
+ if self.failure:
+ raise WorkerPersistenceError(self.failure)
+ if self.journal['pending']:
+ raise WorkerPersistenceError('pending_receipt')
+ entry = {'sequence': self.journal['next_sequence'], 'operation': operation, 'payload': payload}
+ candidate = json.loads(json.dumps(self.journal))
+ candidate['pending'].append(json.loads(json.dumps(entry, allow_nan=False)))
+ candidate['next_sequence'] += 1
+ try:
+ self._save(candidate)
+ except Exception as exc:
+ self.failure = str(exc)
+ raise
+ self.journal = candidate
+ return self.retry_pending()[0]
+
+ def retry_pending(self):
+ with self.lock:
+ results = []
+ try:
+ while self.journal['pending']:
+ entry = self.journal['pending'][0]
+ result = self.rpc('worker.persist', **self.scope, **entry)
+ candidate = dict(self.journal, pending=self.journal['pending'][1:])
+ candidate = self._compression_receipt_journal(candidate, result)
+ self._save(candidate)
+ self.scope = candidate['scope']
+ self.journal = candidate
+ results.append(result)
+ except Exception as exc:
+ self.failure = str(exc)
+ raise
+ self.failure = None
+ return results
+
+ def adopt(self, epoch):
+ """Install only a separately verified worker.adopt result; never self-adopt."""
+ with self.lock:
+ candidate = dict(self.journal, scope=dict(self.scope, epoch=epoch))
+ self._save(candidate)
+ self.scope = candidate['scope']
+ self.journal = candidate
+ self.failure = None
+
+ def append_messages_batch(self, session_id, messages, compression_lock_holder=None,
+ turn_lease_holder=None, chunk_rows=None, turn_lease_ttl_seconds=300.0):
+ self._session(session_id)
+ if chunk_rows is not None:
+ raise WorkerPersistenceError('unsupported_operation')
+ if compression_lock_holder is not None or turn_lease_ttl_seconds != 300.0:
+ return self._append_compression_messages(session_id, messages, compression_lock_holder,
+ turn_lease_holder, turn_lease_ttl_seconds)
+ result = self._apply('transcript.append', {'messages': messages, 'turn_lease_holder': turn_lease_holder})
+ apply_row_annotations(messages, result['annotations'])
+ return result['count']
+
+ def try_acquire_session_turn_lease(self, session_id, holder, *, ttl_seconds=300.0, patience_s=None):
+ self._session(session_id)
+ return self._apply('turn.acquire', {'holder': holder, 'ttl_seconds': ttl_seconds})['value']
+
+ def acquire_session_turn_lease(self, session_id, holder, *, ttl_seconds=300.0,
+ wait_seconds=1800.0, poll_interval_seconds=1.0, on_wait=None,
- wait_notice_interval_seconds=15.0, should_abort=None, acquire_patience_s=0.5):
- # Reuse only the local polling orchestrator, not the SQLite mixin surface.
++ wait_notice_interval_seconds=15.0, should_abort=None, acquire_patience_s=0.5,
++ on_contended=None):
++ # Reuse only the local polling orchestrator, not the SQLite mixin surface. Same signature
++ # as the owner's (``on_contended``: a busy-database notice; the RPC try never raises it).
+ from hermes_state_compression import SessionCompressionMixin
+ return SessionCompressionMixin.acquire_session_turn_lease(self, session_id, holder,
+ ttl_seconds=ttl_seconds, wait_seconds=wait_seconds,
+ poll_interval_seconds=poll_interval_seconds, on_wait=on_wait,
+ wait_notice_interval_seconds=wait_notice_interval_seconds,
- should_abort=should_abort, acquire_patience_s=acquire_patience_s)
++ should_abort=should_abort, acquire_patience_s=acquire_patience_s,
++ on_contended=on_contended)
+
+ def refresh_session_turn_lease(self, session_id, holder, *, ttl_seconds=300.0):
+ self._session(session_id)
+ return self._apply('turn.renew', {'holder': holder, 'ttl_seconds': ttl_seconds})['value']
+
+ def release_session_turn_lease(self, session_id, holder):
+ # DurableTurnLease retains its admission target across physical rotation.
+ self._apply('turn.cleanup', {'target': session_id, 'holder': holder})
+
+ def queue_token_counts(self, session_id, **usage):
+ self._session(session_id)
+ self._apply('usage.main', usage)
+
+ def record_auxiliary_usage(self, session_id, task, **usage):
+ self._session(session_id)
+ self._apply('usage.auxiliary', dict(usage, task=task))
+
+ def flush_token_counts(self, timeout=5.0):
+ with self.lock:
+ if self.failure:
+ raise WorkerPersistenceError(self.failure)
+ if self.journal['pending']:
+ raise WorkerPersistenceError('pending_receipt')
+ return True
+
+ def get_session_title(self, session_id):
+ return self.get_session(session_id).get('title')
+
+ def get_compression_failure_cooldown_row(self, session_id):
+ row = self.get_session(session_id)
+ return {'session_exists': True, 'cooldown_until': row.get('compression_failure_cooldown_until'),
+ 'error': row.get('compression_failure_error')}
+
+ def get_compression_failure_cooldown(self, session_id):
+ import time
+ now = time.time()
+ row = self.get_compression_failure_cooldown_row(session_id)
+ deadline = row['cooldown_until']
+ if deadline is None or float(deadline) <= now:
+ return None
+ return {'cooldown_until': float(deadline), 'remaining_seconds': float(deadline) - now,
+ 'error': row['error']}
+
+ def _session_number(self, session_id, column, cast, zero):
+ row = self.get_session(session_id)
+ try:
+ return max(zero, cast(row.get(column) or zero))
+ except (TypeError, ValueError):
+ return zero
+
+ def get_compression_fallback_streak(self, session_id):
+ return self._session_number(session_id, 'compression_fallback_streak', int, 0)
+
+ def get_compression_ineffective_count(self, session_id):
+ return self._session_number(session_id, 'compression_ineffective_count', int, 0)
+
+ def get_compression_recovery_deadline(self, session_id):
+ return self._session_number(session_id, 'compression_recovery_deadline', float, 0.0)
+
+ def get_session_model_config_value(self, session_id, key, default=None):
+ from hermes_state_sessions import _parse_model_config
+ return _parse_model_config(self.get_session(session_id).get('model_config')).get(key, default)
+
+ def update_system_prompt(self, session_id, system_prompt):
+ self._session(session_id)
+ self._apply('session.prompt', {'system_prompt': system_prompt})
+
+ def patch_session_model_config(self, session_id, patch):
+ self._session(session_id)
+ self._apply('session.sidecars', {'patch': patch})
+
+ def update_session_tool_names(self, session_id, pin):
+ # The tools[] freeze pin ({"version", "tools"}; None clears): without it every fresh worker
+ # re-probes check_fns and a config flip between turns silently forks the cached prefix.
+ self._session(session_id)
+ self._apply('session.tools', {'tool_names': pin})
+
+ def finish(self):
+ return self._apply('execution.finish', {})
+
+ def close(self):
+ with self.lock:
+ try:
+ self.flush_token_counts()
+ finally:
+ self._outbox_owner.close()
diff --cc agent/skill_commands.py
index 09ccae53386,164a369a40e..91ddb9c6bfa
--- a/agent/skill_commands.py
+++ b/agent/skill_commands.py
@@@ -399,14 -480,7 +484,11 @@@ def scan_skill_commands() -> Dict[str,
Builds a local map and publishes once at the end: writing straight into the
global exposed partial results to overlapping scans, which then logged
bogus "already claimed" collisions against their own incumbents."""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return {}
- global _skill_commands, _skill_commands_platform, _skill_commands_home, _skill_commands_project
- platform = _resolve_skill_commands_platform()
- home = _resolve_skill_commands_home()
- project = _resolve_skill_commands_project()
+ key = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
# Build into a local map and publish once, at the end. Writing straight into the global made a scan's
# partial results visible to everything else in the process: a second, overlapping scan deduped against
# its own (empty) ``seen_names`` but collided against the first scan's already- published slugs, logging
@@@ -458,19 -519,124 +527,128 @@@ def get_skill_commands() -> Dict[str, D
active profile's home (Desktop profile switch) or the session's project root (two sessions in two
repos) changes, so each sees its own ``platform_disabled`` / ``external_dirs`` / project-skill view.
- See #14536, #88023, #114359.
+ See #14536, #88023, #114359, #104849.
"""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return {}
- current = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
+ key = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
with _publish_lock:
- commands = _skill_commands
- is_fresh = bool(commands) and (_skill_commands_platform, _skill_commands_home, _skill_commands_project) == current
+ cached = _skill_commands_by_key.get(key)
+ if cached is not None:
+ return cached
# Scan outside the lock — file I/O and deferred imports; concurrent scans
# are safe since each builds its own map.
- return commands if is_fresh else scan_skill_commands()
+ return scan_skill_commands()
+
+
+ # Plugin projection cache. The projection re-parses every plugin SKILL.md and sits on the
+ # per-keystroke completion path (94 ms per Tab measured with 60 plugin skills), so it is reused
+ # while its tag holds: the resolved Hermes home (plugin managers are home-keyed, so profiles never
+ # share a registry) plus the registered qualified names (a plugin enable/disable/install changes
+ # them). ``reload_skills()`` drops it explicitly to pick up edited SKILL.md files.
+ _plugin_skill_commands: Dict[str, Dict[str, Any]] = {}
+ _plugin_skill_commands_tag: Optional[tuple] = None
+
+
+ def invalidate_plugin_skill_commands() -> None:
+ """Drop the cached plugin skill projection."""
+ global _plugin_skill_commands, _plugin_skill_commands_tag
+ with _publish_lock:
+ _plugin_skill_commands = {}
+ _plugin_skill_commands_tag = None
+
+
+ def get_plugin_skill_commands() -> Dict[str, Dict[str, Any]]:
+ """Project enabled plugin skills into the interactive-only slash namespace (``/plugin:skill``).
+
+ Config disable lists (``skills.disabled``, ``plugins.disabled``) are applied on EVERY call, so a
+ config-only disable takes effect without a rescan.
+ """
+ from agent.skill_utils import get_disabled_skill_names
+ from hermes_cli.plugins import discover_plugins, get_plugin_manager
+ from hermes_cli.plugins_discovery import _get_disabled_plugins
+ from hermes_constants import get_hermes_home
+
+ discover_plugins() # no-op once this home is discovered
+ manager = get_plugin_manager()
+ metadata = manager.list_plugin_skill_metadata()
+ tag = (str(get_hermes_home()), tuple(str(m.get("name") or "") for m in metadata))
+ with _publish_lock:
+ cached, is_fresh = _plugin_skill_commands, _plugin_skill_commands_tag == tag
+ if not is_fresh:
+ cached = _scan_plugin_skill_commands(manager, metadata, tag)
+ disabled = get_disabled_skill_names()
+ disabled_plugins = _get_disabled_plugins()
+ if not disabled and not disabled_plugins:
+ return cached
+ return {
+ key: info for key, info in cached.items()
+ if not (info["name"] in disabled or info["name"].split(":", 1)[1] in disabled
+ or info["name"].split(":", 1)[0] in disabled_plugins)
+ }
+
+
+ def _scan_plugin_skill_commands(manager, metadata: list, tag: tuple) -> Dict[str, Dict[str, Any]]:
+ """Build the plugin skill projection and publish it with its tag atomically."""
+ global _plugin_skill_commands, _plugin_skill_commands_tag
+ from tools.skills_tool import (
+ _parse_frontmatter, skill_matches_apps, skill_matches_environment,
+ skill_matches_platform,
+ )
+
+ commands: Dict[str, Dict[str, Any]] = {}
+ for entry in metadata:
+ qualified = str(entry.get("name") or "").strip()
+ if ":" not in qualified:
+ continue
+ skill_md = manager.find_plugin_skill(qualified)
+ if skill_md is None or not skill_md.is_file():
+ continue
+ try:
+ parsed, _ = _parse_frontmatter(skill_md.read_text(encoding="utf-8-sig", errors="replace"))
+ except OSError:
+ continue
+ # Offer from the file we will actually load, not registration-time hints.
+ if not (skill_matches_platform(parsed) and skill_matches_environment(parsed) and skill_matches_apps(parsed)):
+ continue
+ key = f"/{qualified.lower()}"
+ if skill_command_collision_note(qualified) is not None or key in commands:
+ logger.warning("Plugin skill %r collides with an existing slash command; skipping", qualified)
+ continue
+ commands[key] = {
+ "name": qualified, "description": str(parsed.get("description") or entry.get("description")
+ or f"Invoke the {qualified} plugin skill").strip(),
+ "skill_identifier": qualified, "skill_md_path": str(skill_md),
+ "skill_dir": str(skill_md.parent), "source": "plugin",
+ }
+ with _publish_lock:
+ _plugin_skill_commands, _plugin_skill_commands_tag = commands, tag
+ return commands
+
+
+ def _merge_interactive_skill_commands(
+ filesystem_commands: Dict[str, Dict[str, Any]], plugin_commands: Dict[str, Dict[str, Any]],
+ ) -> Dict[str, Dict[str, Any]]:
+ """Merge interactive sources with filesystem commands winning collisions."""
+ commands = dict(filesystem_commands)
+ for command, info in plugin_commands.items():
+ if command in commands:
+ logger.warning("Plugin skill %r collides with %r; keeping the first", command, commands[command]["name"])
+ else:
+ commands[command] = info
+ return commands
+
+
+ def get_interactive_skill_commands() -> Dict[str, Dict[str, Any]]:
+ """Filesystem skills plus profile-scoped plugin skills; never use for
+ messaging/native command menus (plugin skills are CLI/TUI/desktop only)."""
+ identity = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
+ commands = _merge_interactive_skill_commands(get_skill_commands(), get_plugin_skill_commands())
+ with _publish_lock:
+ _last_interactive_skill_commands_by_key[identity] = dict(commands)
+ return commands
def diff_command_snapshots(before: Dict[str, str], after: Dict[str, str]) -> Dict[str, Any]:
diff --cc agent/subdirectory_hints.py
index 01601c29dbb,c5b495a6e90..20791e1fc7c
--- a/agent/subdirectory_hints.py
+++ b/agent/subdirectory_hints.py
@@@ -137,12 -159,33 +163,35 @@@ class SubdirectoryHintTracker
if found and found[1]:
self._loaded_digests.add(_digest(found[1]))
+ def rebind_working_dir(self, working_dir: str) -> None:
+ """Re-anchor hint discovery to *working_dir* (a session workspace adoption)."""
+ try:
+ new_dir = Path(working_dir).expanduser().resolve()
+ if not new_dir.is_dir() or _is_home_like_working_dir(new_dir):
+ return
+ except (OSError, ValueError, RuntimeError):
+ return
+ if new_dir == self.working_dir:
+ self._home_is_working_dir = False
+ return
+ self.working_dir = new_dir
+ self._home_is_working_dir = False
+ # Fresh anchor, fresh bookkeeping: the new project's directories get their
+ # own first-visit hints (startup never loaded context files for it).
+ self._loaded_dirs = {self.working_dir}
+ self._loaded_digests = set()
+ found = _first_hint_file(self.working_dir)
+ if found and found[1]:
+ self._loaded_digests.add(_digest(found[1]))
+
def check_tool_call(self, tool_name: str, tool_args: Dict[str, Any]) -> Optional[str]:
"""Return formatted hint text for newly visited directories, or None."""
- if not self.enabled:
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if not self.enabled or safe_worker_enabled():
return None
+ if self._home_is_working_dir:
+ return None
all_hints = [h for d in self._extract_directories(tool_name, tool_args) if (h := self._load_hints_for_directory(d))]
return "\n\n" + "\n\n".join(all_hints) if all_hints else None
diff --cc agent/transports/chat_completions.py
index fab5bd98b89,52ba191bf03..d67afa80fbd
--- a/agent/transports/chat_completions.py
+++ b/agent/transports/chat_completions.py
@@@ -35,9 -36,7 +36,10 @@@ _XAI_TOOL_SEARCH_ALIAS = "hermes_tool_s
# providers reject with HTTP 400 ("Extra inputs are not permitted").
_STRIP_MSG_KEYS = (
"codex_reasoning_items", "codex_message_items", "tool_name", "effect_disposition", "timestamp",
- "platform_message_id", "api_content", "anthropic_content_blocks", "bedrock_content_blocks", MESSAGE_UID,
+ # ``platform_message_id`` is persisted as-is and comes back from replay as ``message_id``
+ # (JSONL transcript compat); both are delivery bookkeeping, never model input.
+ "platform_message_id", "message_id", "api_content", "anthropic_content_blocks", "bedrock_content_blocks",
++ MESSAGE_UID,
)
_STRIP_TC_KEYS = ("call_id", "response_item_id")
_HIGH_EFFORTS = {"high", "xhigh", "max", "ultra"}
diff --cc apps/desktop/electron/main.ts
index fc90e66d197,8d65d7e4104..c32be49fe93
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -210,10 -215,15 +224,10 @@@ import type { RegistryConnection } fro
import type { RosterProfileMetadata } from './connection-registry'
import { liveWindowState, overlayWindowState } from './connection-window-state'
import { describeCrashReason, installCrashForensics } from './crash-forensics'
-import {
- adoptServedDashboardToken,
- isAttachedBackendTokenDrifted,
- resolveServedDashboardToken
-} from './dashboard-token'
-import { resolveDashboardWebDist } from './dashboard-web-dist'
+import { adoptServedDashboardToken } from './dashboard-token'
import { resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths'
import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'
- import { formatDesktopLogLine } from './desktop-log-line'
+ import { formatDesktopLogLine, formatLogStamp } from './desktop-log-line'
import {
createDesktopProfilePreferences,
DESKTOP_PROFILE_NAME_RE,
@@@ -275,11 -284,10 +290,10 @@@ import
import { downloadViaOauthSessionToFile, downloadViaTokenToFile } from './gateway-file-download-transport'
import { stopGatewayBeforeUpdate } from './gateway-stop-before-update'
import { resolveGatewayVersion } from './gateway-version'
-import { probeGatewayWebSocket, spawnedBackendProbeOptions } from './gateway-ws-probe'
+import { probeGatewayWebSocket } from './gateway-ws-probe'
import { windowsGitCandidates } from './git-binary-candidates'
import { registerGitIpc } from './git-ipc'
- import { desktopBackendSpawnEnv, guestOnboardingEnabled, skipIntroEnabled } from './guest-onboarding'
- import { readAndConsumeHandoffResult } from './handoff-result'
+ import { desktopBackendSpawnEnv, guestOnboardingEnabled } from './guest-onboarding'
import {
assertExistingPathForOpen,
ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,
@@@ -301,7 -311,18 +317,8 @@@
tightenSecretFileMode,
writeSecretFileAtomic
} from './hardening'
-import {
- type AttachedBackend,
- attachOrReserveSpawn,
- checkoutHeadIdentity,
- HOST_SPAWN_GATE_STALE_MS,
- spawnLedgerPath,
- type SpawnReservation
-} from './host-backend-attach'
-import { assertNoSecondLocalBackend, assertNotPassiveSpawn } from './host-backend-singleton'
-import { lookupPublishedSessionToken } from './host-published-token'
-import { claimHostSpawnGate } from './host-spawn-gate'
+import { assertNotPassiveSpawn } from './host-backend-singleton'
+ import { HERMES_HUB_FALLBACK_ORIGIN, HERMES_HUB_ORIGIN, isHermesHubClipboardWrite } from './hub-iframe-policy'
import { requestHudClose } from './hud-close'
import { cursorPointInWindow } from './hud-cursor'
import { startHudGameOverlayWatch } from './hud-game-overlay'
@@@ -379,27 -423,48 +419,32 @@@ import
} from './oauth-rest-request'
import { wireOauthSessionResponse } from './oauth-session-response'
import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'
-import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'
+import { createParentStartMarkerResolver } from './parent-process-identity'
- import { bundledPayload, installIdForRoot, type PayloadInfo } from './payload-backend'
- import { petOverlayClickThrough } from './pet-overlay'
+ import { bundledPayload, installIdForRoot, type PayloadInfo, payloadPythonPath } from './payload-backend'
+ import { petOverlayClickThrough, shouldPopInOnOverlayClosed } from './pet-overlay'
import { placePetOverlay, registerPetOverlayIpc } from './pet-overlay-ipc'
- import {
- pendingNotice as pendingPluginCompatNotice,
- recordDismissed as recordPluginCompatDismissed
- } from './plugin-compat-notice'
import {
buildRegistryProfileRoutes,
isLocalEnumerationFailure,
localRouteFallbackProfiles,
undialedSshRouteSeeds
} from './plugin-profile-routes'
- import { createPortalSession } from './portal-session'
- import { createKeepAwake } from './power-save'
-import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS, POOL_LIMITS_MIN } from './pool-limits'
-import { createPoolRetirer } from './pool-retire'
-import { createPoolRetirementClient } from './pool-retire-http'
-import {
- assertPoolEntryStillOwned,
- BackgroundSlotRetryBackoff,
- BackgroundSlotRetryDeferredError,
- isBackgroundSlotRetryDeferred,
- isBackgroundSlotWaitTimeout,
- LocalBackendSpawnCoordinator,
- type LocalBackendSpawnPriority,
- registerLocalBackendExitFinalizer,
- releaseLocalBackendSlot,
- releaseLocalBackendSlotAfterExit
-} from './pool-spawn-coordinator'
-import { createPoolStopper } from './pool-stop'
-import { poolTouchKeys } from './pool-touch-scope'
+ import { createPortalSession, resolvePortalBaseUrl } from './portal-session'
+ import {
+ createKeepAwake,
+ type KeepAwakeMode,
+ keepAwakeWanted,
+ parseKeepAwakeMode,
+ readKeepAwakeMode
+ } from './power-save'
import { readPreUpdateBackupEnabled } from './pre-update-backup-config'
+import { registerPreparedSubmissions } from './prepared-submissions'
import { capturePreviewContents } from './preview-capture'
import { onPreviewWatchOwnerDestroyed, sendPreviewFileChangedToOwner } from './preview-file-watch'
+ import { hasClosePreviewFlag, previewGuestInputAction } from './preview-guest-escape'
+ import { commandFocusedGuest, notePreviewGuestHidden } from './preview-guest-offscreen'
import { PreviewReachRegistry } from './preview-reach'
+ import { previewHttpUrlTarget } from './preview-url-target'
import {
createPrimaryRemoteConnection,
FirstRunSetupResetError,
@@@ -454,13 -535,13 +515,15 @@@ import
revalidateSuspectPooledRemoteBackends
} from './remote-liveness'
import { resolveRemoteOauthTicket, rosterSourceEnumerationTimeoutMs } from './remote-oauth-ticket'
+ import { createRemoteOwnerCache } from './remote-owner-cache'
import { remoteSessionCookies } from './remote-session-cookies'
import {
+ applyRemoteRequestHeaders,
attachRemoteRequestHeaderListener,
collectRemoteHeaderSources,
createRegistryGatewayWsUrlHandler,
createRemoteWsHeaderStore,
++ type InjectedHeadersByRequest,
oauthLoginLoadUrlOptions,
resolveRemoteRequestHeaders
} from './remote-ws-headers'
@@@ -8638,25 -8742,6 +8537,38 @@@ function installRemoteHeaderRulesOnSess
}
remoteHeaderSessions.add(sess)
+
+ if (sess === session.defaultSession) {
+ // Native one-use gateway dials (renderer WebSocket) drop Origin and ride
- // the minted ticket; every other request keeps the remote-header path.
++ // the minted ticket; every other request keeps the remote-header path,
++ // including its per-request redirect-hop strip (same bookkeeping as
++ // attachRemoteRequestHeaderListener).
++ const injectedByRequest: InjectedHeadersByRequest = new Map()
++
+ sess.webRequest.onBeforeSendHeaders((details, callback) => {
+ const nativeHeaders = localGatewayDials.headers(details)
+
+ if (nativeHeaders) {
+ callback({ requestHeaders: nativeHeaders })
+
+ return
+ }
+
- applyRemoteRequestHeaders(details, callback, headersForRemoteRequest)
++ applyRemoteRequestHeaders(details, callback, headersForRemoteRequest, injectedByRequest)
+ })
+
++ const forgetInjected = (details: { id?: number }) => {
++ if (details?.id !== undefined) {
++ injectedByRequest.delete(details.id)
++ }
++ }
++
++ sess.webRequest.onCompleted(forgetInjected)
++ sess.webRequest.onErrorOccurred(forgetInjected)
++
+ return
+ }
+
attachRemoteRequestHeaderListener(sess, headersForRemoteRequest)
}
@@@ -11756,54 -12132,368 +11758,81 @@@ async function dialPoolBackend(profile
}
}
- // Everything below starts a LOCAL `hermes serve` child. Multiplex-only says
- // the host has exactly one, and routing (resolveProfileBackendRoute case 6)
- // keeps local profiles off this path — this is the backstop that makes the
- // pool spawn path genuinely unreachable rather than merely unused.
- // Same options object the router reads, so the guard cannot drift from it
- // (profileRouteOptions folds the per-profile SSH override into
- // profileRemoteOverride; a hand-rolled term here missed that).
- const guardRoute = profileRouteOptions(profile)
-
- assertNoSecondLocalBackend(poolKey, {
- isolated: guardRoute.isolatedBackend,
- primaryRemoteActive: guardRoute.primaryRemoteActive,
- profileRemoteOverride: opts.forceLocal ? false : guardRoute.profileRemoteOverride,
- unscopableRequest: opts.unscopableRequest
- })
+ assertLocalProfileCanStart(profile, profileDeletionGate, key =>
+ directoryExists(path.join(HERMES_HOME, 'profiles', key))
+ )
- // Bound the slot wait BELOW the renderer's backend-boot budget (45s): once
- // the renderer has given up on this spawn, a ticket still queued for the
- // pool-idle window (10 min) would hold the pool key hostage and every
- // later click on the profile would join that stale wait. Failing here
- // surfaces the "all N slots busy" reason instead of a generic boot timeout.
- // The caller stamped entry.spawnPriority from its own request; a foreground
- // dial that joined the claim before this entry existed left a mark instead.
- if (takeForegroundSpawn(poolKey, profile)) {
- entry.spawnPriority = 'foreground'
- }
+ const connection = await ensureLocalGateway(async () => {
+ const backend = await ensureRuntime(
+ await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),
+ () => assertPoolEntryStillOwned(poolKey, entry)
+ )
- const spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)
+ profileDeletionGate.assertCanStart(profile)
+ assertPoolEntryStillOwned(poolKey, entry)
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
+ // Never another profile's dotenv credentials from the Desktop env (#68367).
+ return runGatewayEnsure(
+ { ...backend, env: desktopBackendSpawnEnv(backend.env || {}, GUEST_ONBOARDING) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile })
+ )
+ }, async () => {
- await waitForUpdateClearance(updateGateDeps(), { pollMs: UPDATE_WAIT_POLL_MS, timeoutMs: UPDATE_WAIT_TIMEOUT_MS })
++ // Same update mutual exclusion as the primary's waitForLocalStart (#73822);
++ // a held update shows the window's blocked screen for this profile too.
++ await waitForPoolUpdateClearance({
++ profile,
++ poolKey,
++ gateDeps: updateGateDeps,
++ signal: localBackendLifecycle.signal,
++ isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
++ log: rememberLog,
++ showHold: showUpdateHold,
++ clearHold: clearUpdateHold,
++ pollMs: UPDATE_WAIT_POLL_MS,
++ timeoutMs: UPDATE_WAIT_TIMEOUT_MS
++ })
+ // Update waits yield: retirement or profile deletion may win in that gap.
+ assertPoolEntryStillOwned(poolKey, entry)
+ assertLocalProfileCanStart(profile, profileDeletionGate, key => directoryExists(path.join(HERMES_HOME, 'profiles', key)))
+ })
- if (spawnPriority === 'background' && !backgroundSlotRetryBackoff.canAttempt(poolKey)) {
- throw new BackgroundSlotRetryDeferredError(profile)
- }
+ assertPoolEntryStillOwned(poolKey, entry)
- // The arbiter subscribes to the actual coordinator queue, so a later
- // foreground promotion receives reclamation too, not just fresh starts.
- const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {
- timeoutMs: POOL_SLOT_WAIT_MS,
- priority: spawnPriority
- })
+ return { ...connection, profile, logs: hermesLog.slice(-80), ...getWindowState() }
+}
- entry.localBackendSlotKey = poolKey
- entry.localBackendSpawnRequest = spawnRequest
+// Forget a cached descriptor. Nothing is killed: the gateway behind it owns its
+// own lifetime (`hermes gateway ensure` attach semantics), so the next
+// ensure*() for this key simply re-dials. Every retire path — dispatch probe
+// failure, resume revalidation, registry removal, profile delete/rename, quit —
+// funnels through here so the verb stays in one place.
+async function stopPoolBackend(profile: string) {
+ backendPool.delete(profile)
+}
- if (spawnRequest.queued) {
- rememberLog(
- `Profile backend "${profile}" waiting for a free local slot (${localBackendSpawnCoordinator.activeCount}/${poolMaxBackends()} busy, ${localBackendSpawnCoordinator.queuedCount} queued)`
- )
- }
++// Profile delete/rename also drops a per-profile SSH remote's tunnel/server
++// (main's pool-stop fence ran this for every key, #106935). Teardown runs inside
++// the bootstrap drain barrier; a failure is logged, never thrown, so it cannot
++// block the delete/rename it belongs to.
+async function teardownPoolBackendAndWait(profile) {
- await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))
++ await Promise.all(
++ localProfilePoolKeys(profile).map(async key => {
++ await stopPoolBackend(key)
+
- const cancelRequest = (): void => {
- spawnRequest.cancel()
- }
++ try {
++ await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))
++ } catch (err) {
++ sshRememberLog(`[ssh-teardown] ${key}: ${String(err)}`)
++ }
++ })
++ )
+}
- localBackendLifecycle.signal.addEventListener('abort', cancelRequest, { once: true })
-
- try {
- entry.releaseLocalBackendSlot = await spawnRequest.acquired
- backgroundSlotRetryBackoff.clear(poolKey)
- } catch (error) {
- if (isBackgroundSlotWaitTimeout(error)) {
- backgroundSlotRetryBackoff.recordFailure(poolKey)
- }
-
- throw error
- } finally {
- localBackendLifecycle.signal.removeEventListener('abort', cancelRequest)
- }
-
- if (entry.localBackendSpawnRequest === spawnRequest) {
- entry.localBackendSpawnRequest = null
- }
-
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- const token = crypto.randomBytes(32).toString('base64url')
-
- // Same update mutual exclusion as the primary window's waitForLocalStart
- // (#73822): pool backends spawn from the same venv, so an ungated respawn
- // during applyUpdates' critical section starts a backend on the runtime
- // being replaced. No boot-progress UI here — pool backends boot
- // silently for background profiles — so we only log while parked.
- await waitForPoolUpdateClearance({
- profile,
- poolKey,
- gateDeps: updateGateDeps,
- signal: localBackendLifecycle.signal,
- isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
- log: rememberLog,
- showHold: showUpdateHold,
- clearHold: clearUpdateHold,
- pollMs: UPDATE_WAIT_POLL_MS,
- timeoutMs: UPDATE_WAIT_TIMEOUT_MS
- })
-
- profileDeletionGate.assertCanStart(profile)
-
- // --profile wins over the inherited HERMES_HOME env (see _apply_profile_override
- // step 3 in hermes_cli/main.py), so the child re-homes to this profile.
- // --port 0: the OS assigns an ephemeral port; the child announces it on stdout.
- const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0']
-
- const backend = await ensureRuntime(await resolveHermesBackend(backendArgs), () =>
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
- )
-
- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.
- backend.args = await getBackendArgsForRuntime(backend)
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
- const hermesCwd = resolveHermesCwd()
-
- const webDist = resolveDashboardWebDist({
- activeHermesRoot: ACTIVE_HERMES_ROOT,
- appRoot: APP_ROOT,
- env: process.env
- })
-
- const readyFile = backend.readyFile ? makeDashboardReadyFile() : null
-
- // Guard BEFORE the "Starting" line: a profile that only exists on a remote
- // backend (remote-primary desktop asked for a forced-local child) rejects
- // here, and logging "Starting" first left an orphaned line with no READY
- // and no exit — the exact undiagnosable burst signature in remote-gateway
- // user bundles (Aug 2026, Dash's report).
- assertLocalProfileCanStart(profile, profileDeletionGate, key =>
- directoryExists(path.join(HERMES_HOME, 'profiles', key))
- )
- rememberLog(`Starting Hermes backend for profile "${profile}" via ${backend.label}`)
-
- const parentStartMarker = await desktopParentStartMarker()
- const backendNonce = crypto.randomBytes(16).toString('hex')
- const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- const child = spawnOwnedBackend(
- windowsShellCommand(backend.command, Boolean(backend.shell)),
- backend.args,
- hiddenWindowsChildOptions({
- cwd: hermesCwd,
- env: desktopBackendSpawnEnv(
- {
- // Never another profile's dotenv credentials from the Desktop env (#68367), and never
- // the launch profile's TERMINAL_CWD: a pooled backend serves THIS --profile, whose
- // placeholder/unset terminal.cwd sessions must resolve their own workspace, not the
- // app-global one (#87584). The child re-resolves from its profile config like a
- // standalone `hermes -p X serve`.
- ...pooledProfileBackendEnv({ hermesHome: HERMES_HOME, profile, backendEnv: backend.env }),
- HERMES_DASHBOARD_SESSION_TOKEN: token,
- // Marks this dashboard backend as desktop-spawned so it runs the cron
- // scheduler tick loop (the gateway isn't running under the app).
- HERMES_DESKTOP: '1',
- // Exact parent identity lets the backend self-exit after an unclean
- // Desktop death without mistaking a reused PID for its owner. If the
- // optional marker probe fails, retain legacy PID-only tracking.
- ...parentIdentityEnv,
- HERMES_WEB_DIST: webDist,
- ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
- },
- GUEST_ONBOARDING
- ),
- shell: backend.shell,
- stdio: ['ignore', 'pipe', 'pipe']
- })
- )
-
- entry.process = child
- entry.token = token
- registerLocalBackendExitFinalizer(backendPool, poolKey, entry, () => releaseLocalBackendSlot(entry))
- // Buffer stdout+stderr from the instant of spawn (#93608): an early crash's
- // traceback must survive into the claim error and the before-ready exit
- // message instead of a bare exit code. rememberLog attaches later, after
- // the claim, and would miss anything printed before it.
- const outputTail = createBackendOutputTail()
- outputTail.attach(child)
-
- let ready = false
- let rejectStart = null
-
- const startFailed = new Promise((_resolve, reject) => {
- rejectStart = reject
- })
-
- // Exit/error can now arrive while the ownership claim is still pending.
- startFailed.catch(() => {})
-
- child.once('error', error => {
- rememberLog(`Hermes backend for profile "${profile}" failed to start: ${error.message}`)
- void teardownFailedLocalBackend(poolKey, entry).catch(cleanupError => {
- rememberLog(
- `Hermes backend for profile "${profile}" cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`
- )
- })
- rejectStart?.(error)
- })
- child.once('exit', (code, signal) => {
- rememberLog(formatBackendExitLine(`Hermes backend for profile "${profile}" exited`, code, signal, outputTail))
- releaseBackendChild(child)
-
- if (!ready) {
- rejectStart?.(
- new Error(
- `Hermes backend for profile "${profile}" exited before it became ready (${signal || code}).${outputTail.describe()}`
- )
- )
- }
- })
-
- // Start watching for the READY announcement BEFORE any await (#60323):
- // stdout is already flowing into the tail, and Node streams never replay
- // consumed chunks to late listeners — a sentinel printed while
- // claimBackendChild runs would otherwise be lost forever, timing out a
- // healthy backend. The tail-buffer accessor covers any residual gap.
- const portAnnouncement = waitForDashboardPortAnnouncement(child, {
- bufferedOutput: () => outputTail.text(),
- describeOutputTail: () => outputTail.describe(),
- readyFile
- })
-
- portAnnouncement.catch(() => {})
- await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- child.stdout.on('data', rememberLog)
- child.stderr.on('data', rememberLog)
-
- const port = await Promise.race([portAnnouncement, startFailed])
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- if (readyFile) {
- fs.unlink(readyFile, () => {})
- }
-
- entry.port = port
-
- const baseUrl = `http://127.0.0.1:${port}`
- await Promise.race([waitForHermes(baseUrl, token), startFailed])
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
- ready = true
-
- const childAlive = () => child.exitCode === null && !child.killed
-
- const authToken = await adoptServedDashboardToken(baseUrl, token, {
- childAlive,
- label: `Hermes backend for profile "${profile}"`,
- rememberLog
- })
-
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- entry.token = authToken
-
- // Verify the WebSocket session token before declaring backend ready.
- // HTTP /api/status can pass while WS auth fails (separate transport, separate guards).
- const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`
-
- // Our own child: a cold start can stall its loop past the base budget (#96177).
- const wsProbe = await probeGatewayWebSocket(wsUrl, {
- WebSocketImpl: globalThis.WebSocket,
- ...spawnedBackendProbeOptions(childAlive)
- })
-
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- if (!wsProbe.ok) {
- throw new Error(
- `Hermes backend for profile "${profile}" is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`
- )
- }
-
- return {
- baseUrl,
- mode: 'local',
- source: 'local',
- authMode: 'token',
- token: authToken,
- profile,
- wsUrl,
- logs: hermesLog.slice(-80),
- ...getWindowState()
- }
-}
-
-// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —
-// idle reaper, LRU eviction, profile delete/rename, quit — shares one
-// in-flight stop per key and retains the process handle until the bounded
-// physical shutdown promise resolves. Previously
-// SIGTERM + immediate entry delete dropped the handle and a slow child
-// survived detached under PID 1.
-const poolStopper = createPoolStopper({
- pool: backendPool,
- // localBackendLifecycle is the single owner of local child stop semantics:
- // stopChild triggers its stop (stop + bounded exit wait + slot release);
- // waitForExit resolves when that same stop promise settles. Remote /
- // SSH-isolated pool entries keep `process: null` — child exit is immediate
- // there, so the same in-flight fence carries only the bootstrap drain +
- // SSH teardown below (#106935).
- stopChild: child => {
- void localBackendLifecycle.stop(child as ChildProcess | null | undefined)
- },
- waitForExit: child => localBackendLifecycle.stop(child as ChildProcess | null | undefined),
- afterStop: async key => {
- try {
- await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))
- } catch (err) {
- // The idle reaper calls stopPoolBackend un-awaited; a failed SSH teardown
- // must not surface as an unhandled rejection or block the pool fence.
- sshRememberLog(`[ssh-teardown] ${key}: ${String(err)}`)
- }
- }
-})
-
-function stopPoolBackend(profile: string): Promise<void> {
- const entry = backendPool.get(profile)
-
- const stopping = releaseLocalBackendSlotAfterExit(
- () => releaseLocalBackendSlot(entry),
- () => poolStopper.stop(profile)
- )
-
- // Fire-and-forget callers still need diagnostics; awaiters receive the
- // rejection, while physical ownership and the exit finalizer remain live.
- void stopping.catch(error => {
- rememberLog(`Profile backend "${profile}" stop failed: ${error instanceof Error ? error.message : String(error)}`)
- })
-
- return stopping
-}
-
-// Tell every window the pooled backend under `poolKey` is being retired so the
-// renderer parks that scope (wantOpen=false) instead of redialing into the
-// slot it just vacated. Fired BEFORE the SIGTERM (pool-retire.ts contract).
-function broadcastPoolBackendRetiring(poolKey: string) {
- for (const win of BrowserWindow.getAllWindows()) {
- const { webContents } = win
-
- if (webContents && !webContents.isDestroyed()) {
- webContents.send('hermes:pool:retiring', { poolKey })
- }
- }
-}
-
-const poolRetirer = createPoolRetirer({
- pool: backendPool,
- coordinator: localBackendSpawnCoordinator,
- ...createPoolRetirementClient(fetchJson),
- stopBackend: stopPoolBackend,
- onRetiring: broadcastPoolBackendRetiring,
- log: rememberLog
-})
-
-localBackendLifecycle.signal.addEventListener('abort', poolRetirer.dispose, { once: true })
-
-async function teardownPoolBackendAndWait(profile) {
- await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))
-}
-
-async function stopAllPoolBackends() {
- const entries = [...backendPool.values()]
- await poolStopper.stopAll()
- entries.forEach(releaseLocalBackendSlot)
-}
+async function stopAllPoolBackends() {
+ backendPool.clear()
+}
/**
* Last teardown act on Windows: kill orphaned tools still running out of
@@@ -12029,15 -12998,18 +12060,19 @@@ async function startHermes(requestedPro
const connectionAttempt = backendConnectionState.startAttempt()
- // ONE launch-profile decision for this attempt (#108417): routing pin,
- // --profile argv, and the child env all derive from the same read, so a
+ // ONE launch-profile decision for this attempt (#108417): routing identity,
+ // the --profile argv and the child env all derive from the same read, so a
// hermes:profile:remember landing mid-startup becomes the NEXT boot's
// preference instead of splitting routing identity from the launch
- // argument. (The pin below still honors a live primary — but a primary
- // being live means startHermes never got here.)
- const { argvProfile: activeProfile, routingProfile: primaryProfile } = resolveLaunchProfile(readActiveDesktopProfile)
+ // argument. An explicit profile-scoped caller names both.
+ const { argvProfile: activeProfile, routingProfile: primaryProfile } = requestedProfile
+ ? { argvProfile: requestedProfile, routingProfile: requestedProfile }
+ : resolveLaunchProfile(readActiveDesktopProfile)
+ // Pin the routing table to the profile this primary actually boots as; a
+ // later hermes:profile:remember must not retarget requests mid-life.
+ primaryProfilePin.pin(primaryProfile)
+
// Legacy path callers without an explicit profile belong to the primary
// window backend. Profile-scoped callers still pass their key directly.
setActiveGatewayProfile(primaryProfile)
@@@ -12160,27 -13155,277 +12195,25 @@@
// Local WSL backend — paths are bridgeable.
setWslBridgeProfileState(primaryProfile, true)
- stopAttachedBackendMonitor()
-
- const backend = setup.backend
- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.
- backend.args = await getBackendArgsForRuntime(backend)
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
- const hermesCwd = resolveHermesCwd()
-
- const webDist = resolveDashboardWebDist({
- activeHermesRoot: ACTIVE_HERMES_ROOT,
- appRoot: APP_ROOT,
- env: process.env
- })
-
- const readyFile = backend.readyFile ? makeDashboardReadyFile() : null
-
- await advanceBootProgress('backend.spawn', `Starting Hermes backend via ${backend.label}`, 84)
- rememberLog(`Starting Hermes backend via ${backend.label}`)
-
- const profile = primaryProfile
- const parentStartMarker = await desktopParentStartMarker()
- const backendNonce = crypto.randomBytes(16).toString('hex')
- const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
-
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
-
- const hermesProcess = spawnOwnedBackend(
- windowsShellCommand(backend.command, Boolean(backend.shell)),
- backend.args,
- hiddenWindowsChildOptions({
- cwd: hermesCwd,
- env: desktopBackendSpawnEnv(
- {
- // Never another profile's dotenv credentials from the Desktop env (#68367).
- ...profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: activeProfile }),
- // Explicitly pin HERMES_HOME for the child so Python's get_hermes_home()
- // resolves to the SAME location our resolveHermesHome() picked. Without
- // this pin, Python falls back to ~/.hermes on every platform — fine on
- // mac/linux (where our default matches), but on Windows our default is
- // %LOCALAPPDATA%\hermes, which differs from C:\Users\<u>\.hermes.
- // Mismatch would split config / sessions / .env / logs across two
- // directories. install.ps1 sets HERMES_HOME via setx; the desktop
- // can't reliably do that, so we set it inline for every spawn.
- HERMES_HOME,
- ...backend.env,
- TERMINAL_CWD: hermesCwd,
- HERMES_DASHBOARD_SESSION_TOKEN: token,
- // Marks this dashboard backend as desktop-spawned so it runs the cron
- // scheduler tick loop (the gateway isn't running under the app).
- HERMES_DESKTOP: '1',
- // Exact parent identity lets the backend self-exit after an unclean
- // Desktop death without mistaking a reused PID for its owner. If the
- // optional marker probe fails, retain legacy PID-only tracking.
- ...parentIdentityEnv,
- HERMES_WEB_DIST: webDist,
- ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
- },
- GUEST_ONBOARDING
- ),
- shell: backend.shell,
- stdio: ['ignore', 'pipe', 'pipe']
- })
- )
-
- // Buffer stdout+stderr from the instant of spawn (#93608): an early
- // crash's traceback must survive into the claim error and the
- // before-ready exit message shown by the boot UI. rememberLog attaches
- // later, after the claim, and would miss anything printed before it.
- const primaryOutputTail = createBackendOutputTail()
- primaryOutputTail.attach(hermesProcess)
-
- // Start watching for the READY announcement BEFORE any await (#60323):
- // claimBackendChild can take seconds (its Windows Get-Process probe cold
- // start alone runs 2-8s) and advanceBootProgress awaits renderer IPC.
- // stdout is already flowing into the tail, and Node streams never replay
- // consumed chunks to late listeners, so a sentinel printed during that
- // window was lost forever — the wait then hit its 90s timeout and a
- // healthy backend was killed (deterministic on Windows, racy on
- // macOS/Linux). The tail-buffer accessor covers any residual gap.
- const portAnnouncement = waitForDashboardPortAnnouncement(hermesProcess, {
- bufferedOutput: () => primaryOutputTail.text(),
- describeOutputTail: () => primaryOutputTail.describe(),
- readyFile
- })
-
- // Mark handled so an early rejection (child dies during the claim) can't
- // surface as an unhandled rejection before the Promise.race below attaches.
- portAnnouncement.catch(() => {})
-
- const processOwner = await backendConnectionState.claimProcess(
- connectionAttempt,
- hermesProcess,
- (child: ChildProcess): ReturnType<typeof claimBackendChild> =>
- claimBackendChild(
- child,
- `${backend.command} ${backend.args.join(' ')}`,
- profile,
- backendNonce,
- primaryOutputTail
- )
- )
-
- if (!processOwner) {
- await localBackendLifecycle.stop(hermesProcess)
- releaseBackendChild(hermesProcess)
- throw new Error('Hermes backend start was superseded by a newer connection attempt.')
- }
-
- hermesProcess.stdout.on('data', rememberLog)
- hermesProcess.stderr.on('data', rememberLog)
- let backendReady = false
- let rejectBackendStart = null
-
- const backendStartFailed = new Promise((_resolve, reject) => {
- rejectBackendStart = reject
- })
-
- hermesProcess.once('error', error => {
- releaseBackendChild(hermesProcess)
-
- if (!backendConnectionState.clearForCurrentProcess(processOwner)) {
- rememberLog(`Ignoring stale Hermes backend error: ${error.message}`)
- scheduleUnexpectedPrimaryRecovery({ error: error.message, ready: backendReady })
- rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))
-
- return
- }
-
- // The CURRENT owner failed to start: its routing identity must not
- // outlive it. A newer attempt already re-pins on its own decision
- // (#108417), and the stale branch above never reaches this clear.
- primaryProfilePin.clear()
-
- rememberLog(`Hermes backend failed to start: ${error.message}`)
- updateBootProgress(
- {
- error: error.message,
- message: `Hermes backend failed to start: ${error.message}`,
- phase: 'backend.error',
- running: false
- },
- { allowDecrease: true }
- )
- sendBackendExit({ code: null, signal: null, error: error.message })
- rejectBackendStart?.(error)
- })
- hermesProcess.once('exit', (code, signal) => {
- releaseBackendChild(hermesProcess)
-
- if (!backendConnectionState.clearForCurrentProcess(processOwner)) {
- rememberLog(formatBackendExitLine('Ignoring stale Hermes backend exit', code, signal, primaryOutputTail))
-
- scheduleUnexpectedPrimaryRecovery({ code, signal, ready: backendReady })
-
- if (!backendReady) {
- rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))
- }
-
- return
- }
-
- rememberLog(formatBackendExitLine('Hermes backend exited', code, signal, primaryOutputTail))
-
- // The current primary child is gone; release its routing pin so the
- // next startHermes() re-reads active-profile.json instead of re-pinning
- // the dead child's profile (#108417). Supervisor respawns go through
- // startHermes, which makes a fresh decision — a respawn cannot inherit
- // a pin from a process that no longer exists.
- primaryProfilePin.clear()
-
- if (!scheduleUnexpectedPrimaryRecovery({ code, signal, ready: backendReady })) {
- sendBackendExit({ code, signal })
- }
-
- if (!backendReady) {
- const message = `Hermes backend exited before it became ready (${signal || code}).${primaryOutputTail.describe()}`
- updateBootProgress(
- {
- error: message,
- message,
- phase: 'backend.error',
- running: false
- },
- { allowDecrease: true }
- )
- rejectBackendStart?.(
- new Error(
- `Hermes backend exited before it became ready (${signal || code}). Log: ${DESKTOP_LOG_PATH}\n${recentHermesLog()}`
- )
- )
- }
- })
-
- await advanceBootProgress('backend.port', 'Waiting for Hermes backend to launch', 86)
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
+ const connection = await ensureLocalGateway(() => runGatewayEnsure(
+ { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}, GUEST_ONBOARDING) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: primaryProfile })
+ ))
- void showPluginCompatNoticeOnce()
-
- // Discover the ephemeral port the child bound to
- const port = await Promise.race([portAnnouncement, backendStartFailed])
backendConnectionState.assertCurrentAttempt(connectionAttempt)
- if (readyFile) {
- fs.unlink(readyFile, () => {})
- }
-
- const baseUrl = `http://127.0.0.1:${port}`
- await advanceBootProgress('backend.wait', 'Waiting for Hermes backend to become ready', 90)
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
- await Promise.race([waitForHermes(baseUrl, token), backendStartFailed])
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
- backendReady = true
- // The host now has a bound, registered backend: the next launcher will
- // discover and attach to it, so the spawn gate is done.
- releaseHostSpawnReservation()
- primaryExitRecovery.reset()
backendStartFailure = null
-
- const childAlive = () => hermesProcess.exitCode === null && !hermesProcess.killed
-
- const authToken = await adoptServedDashboardToken(baseUrl, token, {
- childAlive,
- rememberLog
- })
-
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
-
- // Verify the WebSocket session token before declaring backend ready.
- const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`
-
- // Same policy as the pool path: our own child may still be cold-starting (#96177).
- const wsProbe = await probeGatewayWebSocket(wsUrl, {
- WebSocketImpl: globalThis.WebSocket,
- ...spawnedBackendProbeOptions(childAlive)
- })
-
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
-
- if (!wsProbe.ok) {
- throw new Error(
- `Local Hermes backend is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`
- )
- }
-
- updateBootProgress({
- phase: 'backend.ready',
- message: 'Hermes backend is ready. Finalizing desktop startup',
- progress: 94,
- running: true,
- error: null
- })
-
- // A successful boot (including a soft restart that the repair-guard
- // chose over a hard reinstall, see #74874) means any in-flight repair
- // attempt counter has been honoured — reset it so the next genuine
- // failure starts fresh from attempt 1 instead of inheriting the
- // accumulated count of the resolved episode.
+ rememberLog('[backend] Hermes gateway is ready')
+ updateBootProgress({ phase: 'backend.ready', message: 'Hermes gateway is ready', progress: 94, running: true, error: null })
bootstrapRepairAttempt = 0
- return {
- baseUrl,
- mode: 'local',
- source: 'local',
- authMode: 'token',
- token: authToken,
- profile,
- wsUrl,
- logs: hermesLog.slice(-80),
- ...getWindowState()
- }
+ // The primary descriptor names its own profile: a profile-less descriptor
+ // reads as "default" downstream and breaks per-source profile memory when
+ // the primary actually booted as another profile (#825324fd).
+ return { ...connection, profile: primaryProfile, logs: hermesLog.slice(-80), ...getWindowState() }
})().catch(async error => {
- releaseHostSpawnReservation()
-
if (!backendConnectionState.clearPromiseForAttempt(connectionAttempt)) {
throw error
}
@@@ -16078,68 -17638,17 +16405,34 @@@ async function handleHermesApiRequest(r
try {
connection = await ensureBackend(routeProfile, {
passive: request?.passive,
- request: { method: request?.method, path: request?.path },
- spawnPriority
+ request: { method: request?.method, path: request?.path }
})
+
const timeoutMs = resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
- const url = `${connection.baseUrl}${apiRoute.requestPath}`
-
- // OAuth gateways authenticate REST via EITHER a native bearer token
- // (cookieless RFC 8252 flow) OR the HttpOnly session cookie held in the OAuth
- // partition. Prefer the native bearer when present (mirroring
- // mintGatewayWsTicket): the native flow never sets a cookie, so routing an
- // oauth-mode REST call through the cookie-only path returns 401 no_cookie even
- // though a valid bearer is held. Cookie mode rides Electron's net stack bound
- // to the OAuth partition so the cookie attaches automatically. Token/local
- // modes keep using the static session-token header.
- if (connection.authMode === 'oauth') {
- // The OAuth path rides electron.net with JSON headers; multipart isn't
- // wired there. Fail loudly rather than corrupting the upload.
- if (request?.upload) {
- throw new Error('File uploads are not supported against OAuth-gated remote backends yet.')
- }
-
- // Native bearer first (cookieless). ensureNativeAccessToken transparently
- // refreshes a near-expiry AT via /auth/native/refresh; a null return means
- // no native session (resolveOauthRestAuth then selects the cookie path).
- const nativeAt = await ensureNativeAccessToken(connection.baseUrl).catch(() => null)
- const restAuth = resolveOauthRestAuth(nativeAt)
-
- if (restAuth.kind === 'bearer') {
- response = await fetchJson(url, null, {
- method: request?.method,
- body: request?.body,
- timeoutMs,
- bearer: restAuth.token
- })
- } else {
- response = await fetchJsonViaOauthSession(url, {
- method: request?.method,
- body: request?.body,
- timeoutMs
- })
- }
- } else if (connection.gatewayEndpoint) {
- response = await fetchJsonForBackend(connection, apiRoute.requestPath, {
- method: request?.method,
- body: request?.body,
- upload: request?.upload,
- timeoutMs
- })
++ if (connection.gatewayEndpoint) {
+ response = await redialLocalGateway({
+ ensure: () => ensureBackend(routeProfile),
+ forget: () => forgetLocalGatewayDescriptor(routeProfile),
+ use: current => fetchJson(`${current.baseUrl}${apiRoute.requestPath}`, current.token, {
+ method: request?.method,
+ body: request?.body,
+ upload: request?.upload,
+ timeoutMs,
+ gatewayDescriptor: current
+ })
+ })
+ } else {
- response = await fetchJson(url, connection.token, {
++ // Remote URL / cloud / SSH: main's shared transport — configured remote
++ // headers, and the OAuth bearer→cookie fallback that survives refresh
++ // failures and login races (requestWithOauthFallback).
++ response = await fetchJsonForBackend(connection, apiRoute.requestPath, {
+ method: request?.method,
+ body: request?.body,
+ upload: request?.upload,
+ timeoutMs
+ })
+ }
} catch (error) {
// A failed rename PATCH must not strand the app on the temporary primary:
// restore the original active profile and restart its backend.
diff --cc apps/desktop/src/api/canonical-clarify-prompt.test.ts
index 00000000000,00000000000..31a38f48159
new file mode 100644
--- /dev/null
+++ b/apps/desktop/src/api/canonical-clarify-prompt.test.ts
@@@ -1,0 -1,0 +1,50 @@@
++// @vitest-environment node
++import { expect, test } from 'vitest'
++
++import { HermesGateway } from './client'
++
++// A canonical shared clarify prompt reaches the question card in its one `questions[]` shape,
++// and the card's `clarify.lock` lands as the generation-fenced `clarify.respond`.
++test('a canonical clarify prompt drives the question card and its lock answers on the fenced wire', async () => {
++ const wsPackage = 'ws'
++ const { WebSocketServer } = await import(wsPackage)
++ const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
++ await new Promise<void>(resolve => server.once('listening', resolve))
++ const sent: any[] = []
++ server.on('connection', (socket: any) => {
++ socket.on('message', (bytes: Buffer) => {
++ const frame = JSON.parse(bytes.toString())
++ sent.push(frame)
++ socket.send(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { status: 'resolved' } }))
++ })
++ socket.send(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'clarify.request', session_id: 's', payload: {
++ kind: 'clarify', prompt_id: 'c1', execution_generation: 7, question: 'Which target?', choices: ['staging', 'prod'], multi_select: false
++ } } }))
++ })
++ const client = new HermesGateway()
++ let delivered: any
++ let received!: () => void
++ const ready = new Promise<void>(resolve => { received = resolve })
++ client.onRequest(request => { delivered = request; received() })
++
++ try {
++ const address = server.address() as { port: number }
++ await client.connect(`ws://127.0.0.1:${address.port}/api/ws?native_dial=fixture&ticket=one-use`)
++ await ready
++ expect(delivered.method).toBe('clarify')
++ expect(delivered.params.questions).toEqual([{ qid: 'c1', question: 'Which target?', choices: ['staging', 'prod'], multi_select: false }])
++
++ // Skips arrive as a null lock: the fenced respond records them as the empty answer.
++ sent.length = 0
++ await client.request('clarify.lock', { request_id: 'c1', question_id: 'c1', answer: null })
++ expect(sent.map(frame => [frame.method, frame.params])).toEqual([
++ ['session.resume', { session_id: 's', defer_history: true, omit_messages: true }],
++ ['clarify.respond', { session_id: 's', execution_generation: 7, prompt_id: 'c1', answer: '' }]
++ ])
++ } finally {
++ client.close()
++
++ for (const socket of server.clients) { socket.terminate() }
++ await new Promise<void>(resolve => server.close(() => resolve()))
++ }
++})
diff --cc apps/desktop/src/api/client.ts
index b6ef46d635b,c6a727599b8..4eecf325988
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@@ -36,147 -28,7 +36,166 @@@ export const PROMPT_SUBMIT_REQUEST_TIME
export const GATEWAY_NOT_CONNECTED_MESSAGE = 'Hermes gateway is not connected'
+// Canonical shared prompts (`gateway/session_pending_controls.py`) travel as
+// `approval.request` / `clarify.request` EVENTS keyed by `prompt_id` and are
+// answered through `approval.respond` / `clarify.respond`. The renderer only
+// knows server→client REQUESTS (#110521), so each prompt event is delivered to
+// the same `onRequest` registry as a request whose `respond` issues the RPC.
+const CANONICAL_PROMPT_EVENTS: Record<string, 'approval' | 'clarify'> = { 'approval.request': 'approval', 'clarify.request': 'clarify' }
+
+const ATTACH_REQUIRED = new Set(['prompt.submit', 'approval.respond', 'clarify.respond', 'session.interrupt', 'prompt.cancel'])
+// A branch is a CAS mutation on the PARENT: an un-attached parent (right-click on a sidebar row
+// that was never opened) has no cached revision, so attach it first to learn one.
+const PARENT_ATTACH_REQUIRED = new Set(['session.branch_stored', 'session.branch_whole'])
+
+// Canonical-only identity keys. The legacy `hermes serve` contract refuses an unknown key as
+// version skew (4000), so they are stripped on a non-canonical dial. `prompt.submit` keeps its
+// `submission_id` on purpose: the submit path retries identityless on that exact refusal and
+// records the send as legacy-attempted, which a silent strip here would hide.
+const LEGACY_STRIP: Record<string, string[]> = { 'session.create': ['request_id'], 'session.branch_stored': ['request_id'] }
+
+function legacyParams(method: string, params: Record<string, unknown>): Record<string, unknown> {
+ const strip = LEGACY_STRIP[method]
+
+ if (!strip || !strip.some(key => key in params)) { return params }
+
+ return Object.fromEntries(Object.entries(params).filter(([key]) => !strip.includes(key)))
+}
+
export class HermesGateway extends JsonRpcGatewayClient {
+ private canonical = false
+ private readonly protocol = new CanonicalDesktopProtocol()
+ private readonly promptHandlers = new Set<ServerRequestHandler>()
- private readonly deliveredPrompts = new Set<string>()
++ // Delivered canonical prompt id → its session (the fenced respond needs both).
++ private readonly deliveredPrompts = new Map<string, string>()
+
+ override onRequest(handler: ServerRequestHandler): () => void {
+ this.promptHandlers.add(handler)
+ const off = super.onRequest(handler)
+
+ return () => {
+ this.promptHandlers.delete(handler)
+ off()
+ }
+ }
+
+ private deliverCanonicalPrompt(event: { type: string; session_id?: string; payload?: unknown }, replayed: boolean) {
+ const kind = CANONICAL_PROMPT_EVENTS[event.type]
+ const p = event.payload as Record<string, unknown> | undefined
+ const sid = event.session_id
+
+ if (!kind || !p || !sid || typeof p.prompt_id !== 'string') { return }
+ const id = p.prompt_id
+
+ if (this.deliveredPrompts.has(id)) { return }
- this.deliveredPrompts.add(id)
++ this.deliveredPrompts.set(id, sid)
+ const choices = Array.isArray(p.choices) ? p.choices : []
+
++ // The question card reads one `questions[]` shape. A canonical clarify prompt is one
++ // question (the shared gateway asks a batch one card at a time), so its prompt id doubles
++ // as the qid that `clarify.lock` answers with (see `request` below).
+ const params: Record<string, unknown> = kind === 'clarify'
- ? { session_id: sid, question: p.question, choices, multi_select: p.multi_select, questions: p.questions, answers: p.answers }
++ ? { session_id: sid, answers: p.answers,
++ questions: Array.isArray(p.questions) ? p.questions : [{ qid: id, question: p.question, choices, multi_select: p.multi_select }] }
+ : { session_id: sid, request_id: id, command: p.command, description: p.description, choices,
+ allow_permanent: choices.includes('always'), edit: p.edit }
+
+ let settled = false
+
+ const request: ServerRequest = {
+ id,
+ method: kind,
+ params,
+ replayed,
+ respond: result => {
+ if (settled) { return }
+ settled = true
- const answer = kind === 'clarify' ? { answer: result.answer } : { choice: result.choice }
++ // A clarify reply without an answer (skip, Stop, cancel) is the empty answer the
++ // authority records as skipped; `clarify.respond` refuses a missing field.
++ const answer = kind === 'clarify'
++ ? { answer: typeof result.answer === 'string' ? result.answer : '' }
++ : { choice: result.choice }
+ void this.request(`${kind}.respond`, { session_id: sid, request_id: id, ...answer }).catch(() => undefined)
+ },
+ fail: () => { settled = true }
+ }
+
+ for (const handler of this.promptHandlers) {
+ if (handler(request) !== false) { return }
+ }
+ }
+
+ override on<K extends GatewayEventName>(type: K, handler: (event: GatewayEvent<K>) => void): () => void {
+ return super.on<K>(type, event => {
+ // Named listeners run before wildcard listeners in the shared client.
+ // Normalize before either kind sees the prompt, including replay delivery.
+ if (this.canonical) { this.protocol.event(event) }
+ handler(event)
+ })
+ }
+
+ override async connect(wsUrl: string): Promise<void> {
+ this.canonical = new URL(wsUrl).searchParams.has('native_dial')
+ this.attached.clear()
+
+ return super.connect(wsUrl)
+ }
+
+ // Sessions attached over THIS socket. An authority subscription is per
+ // transport: when routing moves a session to another socket (a profile split,
+ // a redial) the new socket must resume before it may submit or respond.
+ private attached = new Set<string>()
+
+ override async request<T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number, signal?: AbortSignal): Promise<T> {
+ if (!this.canonical) { return super.request<T>(method, legacyParams(method, params), timeoutMs, signal) }
++
++ // The card locks each question with `clarify.lock`; a canonical prompt is a single
++ // question, so its one lock is the generation-fenced `clarify.respond` (null = skipped).
++ const promptSession = method === 'clarify.lock' ? this.deliveredPrompts.get(String(params.request_id ?? '')) : undefined
++
++ if (promptSession) {
++ const answer = typeof params.answer === 'string' ? params.answer : ''
++
++ return this.request<T>('clarify.respond', { session_id: promptSession, request_id: params.request_id, answer }, timeoutMs, signal)
++ }
+ const sid = typeof params.session_id === 'string' ? params.session_id : null
+
+ if (sid && ATTACH_REQUIRED.has(method) && !this.attached.has(sid)) {
+ await this.request('session.resume', { session_id: sid, defer_history: true, omit_messages: true, ...(params.profile ? { profile: params.profile } : {}) })
+ }
+
+ const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id : null
+
+ if (typeof parent === 'string' && parent && !this.attached.has(parent)) {
+ await this.request('session.resume', { session_id: parent, defer_history: true, omit_messages: true, ...(params.profile ? { profile: params.profile } : {}) })
+ }
+
+ const prepared = this.protocol.prepare(method, params)
+ const wireMethod = this.protocol.wire(method, prepared)
+
+ try {
+ const result = await super.request<T>(wireMethod, prepared, timeoutMs, signal)
+
+ const settled = this.protocol.settle(method, prepared, this.protocol.result(method, prepared, result), (m, p) => this.request(m, p)) as T
+
+ if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') {
+ // Prompts still open on the authority re-deliver like `open_requests` after a reconnect.
+ const sid = (settled as { session_id?: string }).session_id
+
+ if (sid) { this.attached.add(sid) }
+
+ for (const prompt of ((settled as { prompts?: Array<Record<string, unknown>> }).prompts ?? [])) {
+ this.deliverCanonicalPrompt({ type: `${prompt.kind}.request`, session_id: sid, payload: prompt }, true)
+ }
+ }
+
+ return settled
+ } catch (error) {
+ this.protocol.failure(prepared, error)
+ throw error
+ }
+ }
+
constructor() {
super({
closedErrorMessage: 'Hermes gateway connection closed',
diff --cc apps/desktop/src/api/sessions.test.ts
index e702229652d,424ac0558f3..8f2dcfef6e2
--- a/apps/desktop/src/api/sessions.test.ts
+++ b/apps/desktop/src/api/sessions.test.ts
@@@ -213,6 -204,36 +219,36 @@@ describe('setSessionPinnedRemote / setS
})
})
+ describe('renameSession profile scoping', () => {
+ it('carries the owning profile in the PATCH body and request', async () => {
- hermesApi.mockResolvedValue({ ok: true, title: 'Prep Butler' } as never)
++ hermesApi.mockResolvedValue({ ok: true, title: 'Prep Butler', exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
+
+ await renameSession('sess-r', 'Prep Butler', 'personal')
+
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
++ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
+ method: 'PATCH',
+ path: '/api/sessions/sess-r',
+ profile: 'personal',
+ body: { title: 'Prep Butler', profile: 'personal' }
+ })
+ })
+
+ it('falls back to the active request profile when the argument is omitted', async () => {
- hermesApi.mockResolvedValue({ ok: true, title: 'Prep Butler' } as never)
++ hermesApi.mockResolvedValue({ ok: true, title: 'Prep Butler', exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
+ vi.mocked(client.getApiRequestProfile).mockReturnValue('personal')
+
+ await renameSession('sess-r2', 'Prep Butler')
+
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
++ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
+ method: 'PATCH',
+ path: '/api/sessions/sess-r2',
+ profile: 'personal',
+ body: { title: 'Prep Butler', profile: 'personal' }
+ })
+ vi.mocked(client.getApiRequestProfile).mockReturnValue(null)
+ })
+ })
+
describe('listSidebarSessions remote ownership', () => {
it('stamps active remote rows so a later resume stays on their gateway', async () => {
hermesApi.mockResolvedValue({
diff --cc apps/desktop/src/api/sessions.ts
index 8b5be82294f,8b759e957b3..69c93cb70d8
--- a/apps/desktop/src/api/sessions.ts
+++ b/apps/desktop/src/api/sessions.ts
@@@ -370,48 -370,73 +372,56 @@@ export async function listSidebarSessio
}
}
-// Mutations take the owning `profile` so Electron can route them to the correct
-// remote backend or local profile scope. Omit for the current/default profile.
+const runSessionMutation = createSessionMutationClient()
+
+function mutateSessionHttp<T>(id: string, method: 'PATCH' | 'DELETE', payload: Record<string, unknown>, profile?: ProfileScope): Promise<T> {
+ // Null is the window's v1 route (its primary, local or remote); defaulting it to
+ // the registry's 'local' source would pin a remote primary's edits to this machine.
+ const scope = { connectionId: getApiRequestConnection(), ...sessionScoped(profile) }
+ const path = `/api/sessions/${encodeURIComponent(id)}`
+ const query = new URLSearchParams(scope.profile ? { profile: scope.profile } : {})
+ const suffix = query.size ? `?${query}` : ''
+ const key = JSON.stringify([scope, id, method, payload])
+
+ return runSessionMutation(key,
+ () => hermesApi<SessionMutationSnapshot>({ ...scope, path: `${path}/mutation-snapshot${suffix}` }),
+ identity => {
+ if (method === 'DELETE') {
+ const params = new URLSearchParams(query)
+
+ for (const [name, value] of Object.entries(identity)) { params.set(name, String(value)) }
+
+ return hermesApi<T>({ ...scope, path: `${path}?${params}`, method })
+ }
+
+ return hermesApi<T>({ ...scope, path, method,
+ body: { ...payload, ...identity, ...(scope.profile ? { profile: scope.profile } : {}) } })
+ })
+}
+
export function setSessionArchived(id: string, archived: boolean, profile?: string | null): Promise<{ ok: boolean }> {
- // Carry the owning profile IN THE PATCH BODY, mirroring renameSession — the
- // backend reads its target DB from body.profile (_open_session_db_for_profile).
- // Passing it only as request.profile (Electron routing) is not enough on a
- // remote gateway with no remoteProfile alias: the archive lands on the wrong
- // (default) state.db, no-ops on a missing row, and the archived/unarchived
- // state silently fails to stick — the same class as the unscoped DELETE.
- const owner = sessionWriteProfile(profile)
-
- return hermesApi<{ ok: boolean }>({
- ...(owner ? { profile: owner } : {}),
- path: `/api/sessions/${encodeURIComponent(id)}`,
- method: 'PATCH',
- body: { archived, ...(owner ? { profile: owner } : {}) }
- })
+ return mutateSessionHttp(id, 'PATCH', { archived }, sessionWriteProfile(profile))
}
-// Mirror a sidebar pin to the backend "keep" flag so the sessions.auto_archive
-// sweep (which runs backend-side, blind to Desktop localStorage) never hides a
-// pinned chat. Best-effort: the sidebar stays localStorage-driven for its own
-// display; this only feeds the backend policy.
export function setSessionPinnedRemote(id: string, pinned: boolean, profile?: string | null): Promise<{ ok: boolean }> {
- // Owning profile in the PATCH body (see setSessionArchived / renameSession):
- // the handler reads its target DB from body.profile, so a remote/foreign
- // profile's pin must travel in the body or it no-ops on the wrong state.db.
- const owner = sessionWriteProfile(profile)
-
- return hermesApi<{ ok: boolean }>({
- ...(owner ? { profile: owner } : {}),
- path: `/api/sessions/${encodeURIComponent(id)}`,
- method: 'PATCH',
- body: { pinned, ...(owner ? { profile: owner } : {}) }
- })
+ return mutateSessionHttp(id, 'PATCH', { pinned }, sessionWriteProfile(profile))
}
-// Mirror a sidebar unread toggle to the backend read-state watermark
-// (sessions.last_read_at via SessionDB.set_session_read). Same profile
-// routing as the other session mutations: a remote session's row lives only
-// on its remote host, so the owning profile must travel with the request.
export function setSessionUnreadRemote(id: string, unread: boolean, profile?: string | null): Promise<{ ok: boolean }> {
- // Owning profile in the PATCH body (see setSessionArchived / renameSession):
- // the handler reads its target DB from body.profile, so a remote/foreign
- // profile's unread toggle must travel in the body or it no-ops on the wrong
- // state.db.
- const owner = sessionWriteProfile(profile)
-
- return hermesApi<{ ok: boolean }>({
- ...(owner ? { profile: owner } : {}),
- path: `/api/sessions/${encodeURIComponent(id)}`,
- method: 'PATCH',
- body: { unread, ...(owner ? { profile: owner } : {}) }
- })
+ return mutateSessionHttp(id, 'PATCH', { unread }, sessionWriteProfile(profile))
}
- export function searchSessions(query: string): Promise<SessionSearchResponse> {
+ // Full-text search over one profile's sessions. Pass the profile the caller is
+ // showing: an unscoped request lands on the primary backend, which searches
+ // its launch profile's state.db whatever profile the sidebar is on. `null`
+ // asks the primary on purpose; omitted follows the ambient request profile.
+ export function searchSessions(query: string, profile?: null | string): Promise<SessionSearchResponse> {
+ const scope = profileScoped(profile)
+ const suffix = scope.profile ? `&profile=${encodeURIComponent(scope.profile)}` : ''
+
return hermesApi<SessionSearchResponse>({
- path: `/api/sessions/search?q=${encodeURIComponent(query)}`
+ ...scope,
+ path: `/api/sessions/search?q=${encodeURIComponent(query)}${suffix}`
})
}
diff --cc apps/desktop/src/app/chat/composer/controls.tsx
index cfa4da45d3d,dc278982791..93a02d30177
--- a/apps/desktop/src/app/chat/composer/controls.tsx
+++ b/apps/desktop/src/app/chat/composer/controls.tsx
@@@ -176,9 -155,10 +177,10 @@@ export function ComposerControls(
placement="control"
>
<Button
- aria-label={showStop ? c.stop : c.send}
+ aria-label={showStop ? c.stop : sendLabel}
className={PRIMARY_ICON_BTN}
disabled={disabled || !canSubmit}
+ onClick={() => recordAction(showStop ? 'composer.cancel' : 'composer.send', 'click')}
type="submit"
>
{showStop ? (
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
index 1b4396fc166,c9bd16f0039..e665b154529
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
@@@ -1,7 -1,7 +1,8 @@@
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { HermesConnection } from '@/global'
+ import { clearComposerTerminalSelections, setComposerTerminalSelection } from '@/store/composer'
import {
$parkedQueueSessions,
$queuedPromptsBySession,
@@@ -9,9 -10,12 +11,12 @@@
getQueuedPrompts,
isQueueParked,
MAX_AUTO_DRAIN_ATTEMPTS,
- parkQueuedPrompts
+ parkQueuedPrompts,
+ resetFrozenQueuedTransportsForTests,
+ simulateComposerQueueReloadForTests
} from '@/store/composer-queue'
+ import { $notifications, clearNotifications } from '@/store/notifications'
-import { setSessionsLoading } from '@/store/session'
+import { $connection, setSessionsLoading } from '@/store/session'
import type { QueueEditState } from '../composer-utils'
import type { ChatBarProps } from '../types'
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
index 75e10a743fc,d580a5a8f8b..3b3d19d985b
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
@@@ -18,10 -19,11 +19,12 @@@ import
promoteQueuedPrompt,
type QueuedPromptEntry,
removeQueuedPrompt,
+ resolveQueuedPromptTransport,
+ serverOwnsComposerQueue,
shouldAutoDrain,
unparkQueuedPrompts,
- updateQueuedPrompt
+ updateQueuedPrompt,
+ withQueueDrainClaim
} from '@/store/composer-queue'
import { notify } from '@/store/notifications'
import { $sessionsLoading } from '@/store/session'
@@@ -192,23 -264,36 +267,64 @@@ export function useComposerQueue(
return false
}
- if (serverOwnsComposerQueue(sessionId ?? activeQueueSessionKey)) {
- return Promise.resolve(onSubmit(text, {
- attachments: cloneAttachments(attachments), fromQueue: true,
- sessionId: sessionId ?? null, storedSessionId: activeQueueSessionKey
- })).then(accepted => {
- if (accepted !== true) { return false }
-
- if (currentQueueKeyRef.current === activeQueueSessionKey && draftRef.current === text) {
- clearDraft()
- scope.attachments.removeOccurrences(attachments)
- }
+ // Slash commands cannot ride alongside attachments — the drain path would
+ // reject the entry on every attempt (submitText warns + returns false) and
+ // the queue would livelock. Refuse to enqueue it in the first place.
+ if (isSlashCommandText(text) && attachments.length) {
+ notify({
+ kind: 'warning',
+ title: t.desktop.slashCommandIgnoredTitle,
+ message: t.desktop.slashCommandIgnoredBody
+ })
- return true
- }).catch(() => false)
+ return false
}
- if (!enqueueQueuedPrompt(activeQueueSessionKey, { text, attachments })) {
+ // Freeze `@terminal:` chips at enqueue. Persist the chip form; keep the
+ // fenced selection in the runtime map so drain never re-resolves the live
+ // label map and localStorage never stores terminal CONTENTS (#77078).
+ const frozen = text.trim() ? freezeQueuedDraftText(text, t.composer) : { text }
+
+ if (!frozen) {
+ return false
+ }
+
++ // Canonical (gateway-owned) sessions admit busy input straight into the
++ // durable gateway FIFO; the row comes back as a server-owned queue entry.
++ // `fromQueue` submits skip the transport freeze, so send the frozen text.
++ if (serverOwnsComposerQueue(sessionId ?? activeQueueSessionKey)) {
++ return Promise.resolve(
++ onSubmit(frozen.frozenTransport ?? frozen.text, {
++ attachments: cloneAttachments(attachments),
++ ...(frozen.displayText ? { displayText: frozen.displayText } : {}),
++ fromQueue: true,
++ sessionId: sessionId ?? null,
++ storedSessionId: activeQueueSessionKey
++ })
++ )
++ .then(accepted => {
++ if (accepted !== true) {
++ return false
++ }
++
++ if (currentQueueKeyRef.current === activeQueueSessionKey && draftRef.current === text) {
++ clearDraft()
++ scope.attachments.removeOccurrences(attachments)
++ }
++
++ return true
++ })
++ .catch(() => false)
++ }
++
+ if (
+ !enqueueQueuedPrompt(activeQueueSessionKey, {
+ text: frozen.text,
+ attachments,
+ ...(frozen.displayText ? { displayText: frozen.displayText } : {}),
+ ...(frozen.frozenTransport ? { frozenTransport: frozen.frozenTransport } : {})
+ })
+ ) {
return false
}
@@@ -219,12 -304,14 +335,14 @@@
triggerHaptic('selection')
return true
- }, [activeQueueSessionKey, attachments, clearDraft, draftRef, scope.attachments, onSubmit, sessionId])
- }, [activeQueueSessionKey, attachments, clearDraft, draftRef, scope.attachments, t.composer])
++ }, [activeQueueSessionKey, attachments, clearDraft, draftRef, scope.attachments, onSubmit, sessionId, t.composer])
// All queue drain paths share one lock + send-then-remove sequence.
- // `pickEntry` lets each caller choose head, by-id, or skip-edited.
+ // `pickEntry` lets each caller choose head, by-id, or skip-edited, from the
+ // queue as it stands inside the cross-window claim. Resolves null when there
+ // is nothing to send: another window already sent the picked entry.
const runDrain = useCallback(
- async (pickEntry: (entries: QueuedPromptEntry[]) => QueuedPromptEntry | undefined): Promise<boolean> => {
+ async (pickEntry: (entries: QueuedPromptEntry[]) => QueuedPromptEntry | undefined): Promise<boolean | null> => {
if (drainingQueueRef.current || !activeQueueSessionKey) {
return false
}
@@@ -240,33 -322,53 +353,55 @@@
drainingQueueRef.current = true
try {
- const accepted = await Promise.resolve(
- onSubmit(entry.text, {
- attachments: entry.attachments,
- ...(entry.displayText ? { displayText: entry.displayText } : {}),
- ...(entry.displayKind ? { displayKind: entry.displayKind } : {}),
- fromQueue: true,
- submission_id: entry.id,
- sessionId: drainRuntimeSessionId,
- storedSessionId: drainQueueSessionKey
- })
- )
-
- if (accepted !== true) {
- return false
- }
-
- drainFailuresRef.current.delete(entry.id)
- // Submit now owns the blob: previews (optimistic bubble); do not revoke.
- removeQueuedPrompt(drainQueueSessionKey, entry.id, { retainPreviewUrls: true })
- resetBrowseState(drainRuntimeSessionId)
- // A successful drain means the queue is flowing again — lift any park
- // so the remaining entries follow. Manual drains (Enter on an empty
- // composer, the per-row send arrow) are exactly the resume gestures a
- // parked queue waits for; the auto path only reaches here unparked.
- unparkQueuedPrompts(drainQueueSessionKey)
-
- return true
+ return await withQueueDrainClaim(drainQueueSessionKey, async queue => {
- const entry = pickEntry(queue)
++ // Server-owned rows already sit in the gateway FIFO; never re-send them.
++ const entry = pickEntry(queue.filter(candidate => !candidate.serverStatus))
+
+ if (!entry) {
+ return null
+ }
+
+ const resolved = resolveQueuedPromptTransport(entry)
+
+ if (!resolved.ok) {
+ notify({
+ kind: 'warning',
+ title: t.composer.terminalSelectionMissingTitle,
+ message: t.composer.queuedTerminalSelectionExpiredBody
+ })
+ drainFailuresRef.current.set(entry.id, MAX_AUTO_DRAIN_ATTEMPTS)
+
+ return false
+ }
+
+ const accepted = await Promise.resolve(
+ onSubmit(resolved.transportText, {
+ attachments: entry.attachments,
+ ...(resolved.displayText ? { displayText: resolved.displayText } : {}),
+ ...(entry.displayKind ? { displayKind: entry.displayKind } : {}),
+ fromQueue: true,
++ submission_id: entry.id,
+ sessionId: drainRuntimeSessionId,
+ storedSessionId: drainQueueSessionKey
+ })
+ )
+
- if (accepted === false) {
++ if (accepted !== true) {
+ return false
+ }
+
+ drainFailuresRef.current.delete(entry.id)
+ // Submit now owns the blob: previews (optimistic bubble); do not revoke.
+ removeQueuedPrompt(drainQueueSessionKey, entry.id, { retainPreviewUrls: true })
+ resetBrowseState(drainRuntimeSessionId)
+ // A successful drain means the queue is flowing again — lift any park
+ // so the remaining entries follow. Manual drains (Enter on an empty
+ // composer, the per-row send arrow) are exactly the resume gestures a
+ // parked queue waits for; the auto path only reaches here unparked.
+ unparkQueuedPrompts(drainQueueSessionKey)
+
+ return true
+ })
} finally {
drainingQueueRef.current = false
}
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
index 6f69eda8231,7d9a84c86eb..df6ea7a7b53
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
@@@ -2,10 -2,17 +2,17 @@@ import { act, cleanup, renderHook, wait
import { type Dispatch, type PropsWithChildren, type SetStateAction, useLayoutEffect, useState } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
+ import * as sessionOwnerUtils from '@/app/session/hooks/use-session-actions/utils'
import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'
import { $clarifyRequests } from '@/store/clarify'
- import type { ComposerAttachment } from '@/store/composer'
+ import {
+ clearComposerTerminalSelections,
+ type ComposerAttachment,
+ setComposerTerminalSelection
+ } from '@/store/composer'
-import { clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
+import { $queuedPromptsBySession, clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
+ import { $connectionRequests, type ConnectionRequest } from '@/store/connection-request'
+ import { $gateway } from '@/store/gateway'
import {
clearAllPrompts,
hasBlockingPromptRequest,
@@@ -24,8 -30,6 +31,7 @@@ import { useComposerSubmit } from './us
interface SubmitHarnessOptions {
attachments?: ComposerAttachment[]
busy?: boolean
+ busyInputMode?: 'interrupt' | 'queue' | 'steer' | null
- compacting?: boolean
inputDisabled?: boolean
scopeTarget?: ComposerTarget
sessionKey?: string | null
@@@ -40,8 -44,6 +46,7 @@@ let surfaceSequence =
function renderSubmitHook({
attachments = [],
busy = false,
+ busyInputMode = 'interrupt',
- compacting = false,
inputDisabled = false,
scopeTarget = 'main',
sessionKey = 'stored-session',
@@@ -104,10 -107,9 +110,10 @@@
activeQueueSessionKeyRef: { current: sessionKey },
attachments,
busy,
+ busyInputMode,
- compacting,
clearDraft,
disabled: false,
+ draftScopeRef,
draftRef,
drainNextQueued: vi.fn(async () => false),
editorRef,
@@@ -525,6 -458,71 +515,71 @@@ describe('useComposerSubmit busy-turn r
expect(queueCurrentDraft).not.toHaveBeenCalled()
expect(onCancel).not.toHaveBeenCalled()
})
+
+ it('threads the loaded composer scope through onSubmit for the #59305 submit-time guard', async () => {
+ const { hook, onSubmit } = renderSubmitHook({ text: 'hello' })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
+ await waitFor(() =>
+ expect(onSubmit).toHaveBeenCalledWith('hello', expect.objectContaining({ composerScope: 'stored-session' }))
+ )
+ })
+
+ it('leaves idle @terminal chips for the submit transport freeze (does not expand here)', async () => {
+ setComposerTerminalSelection('zsh:23-58', 'selected terminal lines')
+
+ const { hook, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({
+ text: 'look at @terminal:`zsh:23-58`'
+ })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
+ await waitFor(() =>
+ expect(onSubmit).toHaveBeenCalledWith('look at @terminal:`zsh:23-58`', {
+ attachments: [],
+ composerScope: 'stored-session'
+ })
+ )
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(queueCurrentDraft).not.toHaveBeenCalled()
+ })
+
+ it('expands @terminal selection chips before steering a busy turn', async () => {
+ setComposerTerminalSelection('zsh:23-58', 'selected terminal lines')
+
+ const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({
+ busy: true,
+ text: 'look at @terminal:`zsh:23-58`'
+ })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
- await waitFor(() => expect(onSteer).toHaveBeenCalledWith('```terminal\nselected terminal lines\n```\n\nlook at'))
++ await waitFor(() => expect(onSteer).toHaveBeenCalledWith('```terminal\nselected terminal lines\n```\n\nlook at', 'interrupt'))
+ expect(queueCurrentDraft).not.toHaveBeenCalled()
+ })
+
+ it('refuses to steer when a restored @terminal chip has no selection payload', () => {
+ clearComposerTerminalSelections()
+
+ const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({
+ busy: true,
+ text: 'look at @terminal:`zsh:23-58`'
+ })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(queueCurrentDraft).not.toHaveBeenCalled()
+ })
})
describe('useComposerSubmit with a clarify parked on the session', () => {
@@@ -579,8 -609,8 +666,8 @@@
hook.result.current.submitDraft()
})
- await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course'))
+ await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course', 'interrupt'))
- expect(respond).toHaveBeenCalledWith({ answer: '' })
+ expect(respond).toHaveBeenCalledWith({})
})
it('leaves the question alone for an empty Enter (Stop, not an answer)', () => {
@@@ -612,6 -642,90 +699,90 @@@
})
})
+ describe('useComposerSubmit with a connection card parked on the session', () => {
+ afterEach(() => {
+ cleanup()
+ $connectionRequests.set({})
+ $gateway.set(null)
+ vi.restoreAllMocks()
+ })
+
+ const parkConnection = () => {
+ const connection: ConnectionRequest = {
+ toolCallId: 'call-connection',
+ opId: 'op-connection',
+ seq: 1,
+ deadlineAt: 1_800_000_000,
+ sessionId: 'runtime-session',
+ targets: [
+ {
+ name: 'gmail',
+ kind: 'connector',
+ action: 'connect',
+ state: 'pending',
+ detail: '',
+ connectUrl: null,
+ connectionId: '',
+ tools: [],
+ requiredEnv: [],
+ instructions: null,
+ discoveryError: null
+ }
+ ],
+ settled: false,
+ settledBy: null
+ }
+
+ $connectionRequests.set({ 'runtime-session': connection })
+ }
+
+ it.each([
+ '/btw what is the task?',
+ '/BTW what is the task?',
+ '/btw',
+ '/bg summarize the logs',
+ '/background run the tests'
+ ])('keeps the connection card answerable while dispatching %s', async text => {
+ parkConnection()
+ vi.spyOn(sessionOwnerUtils, 'resolveSessionOwner').mockRejectedValue(new Error('test no owner'))
+ const gatewayRequest = vi.fn(async () => ({}))
+ $gateway.set({ request: gatewayRequest } as unknown as NonNullable<ReturnType<typeof $gateway.get>>)
+ const { hook, onSubmit, onSteer } = renderSubmitHook({ busy: true, text })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(text, expect.anything()))
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(gatewayRequest).not.toHaveBeenCalledWith('connection.respond', expect.anything())
+ expect($connectionRequests.get()['runtime-session']?.settled).toBe(false)
+ })
+
+ it('still continues the connection request for an ordinary reply', async () => {
+ parkConnection()
+ vi.spyOn(sessionOwnerUtils, 'resolveSessionOwner').mockRejectedValue(new Error('test no owner'))
+ const gatewayRequest = vi.fn(async () => ({}))
+ $gateway.set({ request: gatewayRequest } as unknown as NonNullable<ReturnType<typeof $gateway.get>>)
+ const { hook, onSteer } = renderSubmitHook({ busy: true, text: 'continue without connecting' })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
- await waitFor(() => expect(onSteer).toHaveBeenCalledWith('continue without connecting'))
++ await waitFor(() => expect(onSteer).toHaveBeenCalledWith('continue without connecting', 'interrupt'))
+ await waitFor(() =>
+ expect(gatewayRequest).toHaveBeenCalledWith(
+ 'connection.respond',
+ expect.objectContaining({
+ op_id: 'op-connection',
+ result: { settled_by: 'continue' }
+ })
+ )
+ )
+ })
+ })
+
describe('useComposerSubmit with a blocking prompt parked on the session', () => {
// Typing cannot answer approval/sudo/secret prompts, so the busy submit must
// route text to the QUEUE — a steer would sit undelivered behind the blocked
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index a6560f69a33,47b42ee14fa..b589186a1de
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@@ -2,13 -2,21 +2,22 @@@ import { SLASH_COMMAND_RE } from '@herm
import { type RefObject, useLayoutEffect, useRef } from 'react'
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
+ import { translateNow, useI18n } from '@/i18n'
+ import { isSlashCommandText } from '@/lib/chat-runtime'
+ import { isSideTaskSlashCommand } from '@/lib/desktop-slash-commands'
import { triggerHaptic } from '@/lib/haptics'
+import type { BusyInputMode } from '@/store/busy-input-mode'
import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
- import { clearSessionDraft, type ComposerAttachment } from '@/store/composer'
+ import {
+ clearSessionDraft,
+ type ComposerAttachment,
+ freezeComposerTransportPayload,
+ isFreshDraftScope
+ } from '@/store/composer'
import { resetBrowseState } from '@/store/composer-input-history'
-import { enqueueQueuedPrompt, type QueuedPromptEntry } from '@/store/composer-queue'
+import { enqueueQueuedPrompt, type QueuedPromptEntry, serverOwnsComposerQueue } from '@/store/composer-queue'
import { hasConnectionRequest, skipConnectionRequest } from '@/store/connection-request'
+ import { notify } from '@/store/notifications'
import { hasBlockingPromptRequest } from '@/store/prompts'
import { cloneAttachments, type QueueEditState } from '../composer-utils'
@@@ -23,10 -31,9 +32,10 @@@ interface UseComposerSubmitArgs
activeQueueSessionKeyRef: RefObject<string | null>
attachments: ComposerAttachment[]
busy: boolean
+ busyInputMode?: BusyInputMode | null
- compacting: boolean
clearDraft: () => void
disabled: boolean
+ draftScopeRef: RefObject<string | null>
draftRef: RefObject<string>
drainNextQueued: () => Promise<boolean>
editorRef: RefObject<HTMLDivElement | null>
@@@ -60,10 -67,9 +69,10 @@@ export function useComposerSubmit(
activeQueueSessionKeyRef,
attachments,
busy,
+ busyInputMode = 'interrupt',
- compacting,
clearDraft,
disabled,
+ draftScopeRef,
draftRef,
drainNextQueued,
editorRef,
@@@ -85,20 -91,39 +94,47 @@@
const paneVisible = usePaneVisible()
const scope = useComposerScope()
const surfaceId = useComposerSurfaceId()
+ const { t } = useI18n()
+ const copy = t.desktop
// Shared send primitive: fire onSubmit, and if the gateway rejects (accepted
- // === false) or throws, re-load + re-stash the draft so the words survive.
- const dispatchSubmit = (text: string, attachments?: ComposerAttachment[], displayKind?: 'hidden', target?: Parameters<ChatBarProps['onSubmit']>[1]) => {
- const submittedScope = target?.storedSessionId ?? activeQueueSessionKeyRef.current
+ // === false) or throws, re-stash the draft so the words survive. Repaint it
+ // only while the same session still owns the visible composer; a late reject
+ // must not publish an old session's text into the newly focused one.
- const dispatchSubmit = (text: string, attachments?: ComposerAttachment[], displayKind?: 'hidden') => {
++ // `target` carries an explicit destination (a canonical queue admission).
++ const dispatchSubmit = (
++ text: string,
++ attachments?: ComposerAttachment[],
++ displayKind?: 'hidden',
++ target?: Parameters<ChatBarProps['onSubmit']>[1]
++ ) => {
+ // A fresh chat's composer is keyed by its per-lifecycle fresh-draft key
+ // (`__new__:<uuid>`), but the submit contract spells "no session yet" as
+ // null: the create handoff below and the composer drift prong both key off
+ // it, and draftKey(null) resolves to that same fresh bucket.
- const submittedScope = isFreshDraftScope(draftScopeRef.current) ? null : draftScopeRef.current
++ const submittedScope =
++ target?.storedSessionId ?? (isFreshDraftScope(draftScopeRef.current) ? null : draftScopeRef.current)
++
+ let restoreScope = submittedScope
const submittedAttachments = attachments ?? []
+ // Only this operation's explicit session.create handoff may re-home a
+ // pre-session submit. A null → stored render can also be user navigation.
+ const assignment =
+ submittedScope === null
+ ? {
+ onComposerScopeAssigned: (scope: string) => {
+ restoreScope = scope
+ }
+ }
+ : {}
+
const restore = () => {
- loadIntoComposer(text, submittedAttachments)
- // Use the scope captured at dispatch, not whatever session is focused
- // now — the gateway can reject well after the user has switched away,
- // and re-stashing into the currently-focused session would overwrite
- // its draft with the rejected text from a different session (#54527).
- stashAt(submittedScope, text, submittedAttachments)
+ stashAt(restoreScope, text, submittedAttachments)
+
+ if ((isFreshDraftScope(draftScopeRef.current) ? null : draftScopeRef.current) === restoreScope) {
+ loadIntoComposer(text, submittedAttachments)
+ }
}
// A hidden submit is machine text (a setup note, never something the user
@@@ -106,7 -131,14 +142,13 @@@
const rejected = displayKind ? () => {} : restore
void Promise.resolve(
- onSubmit(text, { ...target, ...(attachments ? { attachments } : {}), composerScope: submittedScope, ...(displayKind ? { displayKind } : {}) })
- attachments
- ? onSubmit(text, {
- attachments,
- composerScope: submittedScope,
- ...assignment,
- ...(displayKind ? { displayKind } : {})
- })
- : onSubmit(text, { composerScope: submittedScope, ...assignment, ...(displayKind ? { displayKind } : {}) })
++ onSubmit(text, {
++ ...target,
++ ...(attachments ? { attachments } : {}),
++ composerScope: submittedScope,
++ ...assignment,
++ ...(displayKind ? { displayKind } : {})
++ })
)
.then(accepted => void (accepted === false ? rejected() : clearSessionDraft(submittedScope)))
.catch(rejected)
@@@ -263,13 -313,13 +323,18 @@@
triggerHaptic('submit')
clearDraft()
dispatchSubmit(text)
- } else if (!compacting && !blockingPrompt && !attachments.length && text.trim()) {
- // Unloaded policy must not turn an intended queue into an interrupt.
+ } else if (!blockingPrompt && !attachments.length && text.trim()) {
- // Cursor-style stop-and-correct: interrupt the live turn and redirect
- // it with this text. redirect() preserves the shown reasoning/work; if
- // the turn already ended, steerDraft re-queues so nothing is lost.
- // Compaction is the gateway's call: it answers `queued` under the
- // compression lock. The client flag can outlive an aborted compaction.
- steerDraft()
++ // Busy Send follows the backend busy-input policy: interrupt redirects
++ // the live turn (Cursor-style stop-and-correct), steer injects at the
++ // next tool boundary, queue admits it as the next turn. If the turn
++ // already ended, steerDraft re-queues so nothing is lost. Compaction is
++ // the gateway's call: it answers `queued` under the compression lock.
++ // Unloaded policy (null) must not turn an intended queue into an interrupt.
+ if (busyInputMode === 'queue') {
+ queueCurrentDraft()
+ } else if (busyInputMode !== null) {
+ steerDraft(busyInputMode)
+ }
} else if (payloadPresent) {
// Attachments can't ride a redirect (no tool-result image carriage) —
// queue the whole payload for the next turn. Same for a turn parked on
@@@ -313,29 -377,32 +392,46 @@@
triggerHaptic('submit')
clearDraft()
+ const submittedScope = activeQueueSessionKeyRef.current
+
- // The draft is already cleared, so a refused or failed redirect must keep the only copy
- // (#68927): the canonical queue when the server owns it, the local queue otherwise, or the
- // composer itself when there is no queue yet (a new chat busy before its first session).
+ // The draft is already cleared, so a refused or failed redirect must keep
- // the only copy: queue it for the next turn, or restore it when there is no
++ // the only copy (#68927): the canonical gateway queue when the server owns
++ // it, the local queue otherwise, or the composer itself when there is no
+ // queue yet (a new chat is busy before its first session exists). Keep the
+ // frozen transport for the queue; restoring to the composer keeps the chip
+ // form so the user can re-send it as-is.
+ const hasTerminalTransport = frozen.displayText !== frozen.transportText
+ const canonical = serverOwnsComposerQueue(sessionId ?? activeQueueSessionKey)
+
const keep = () => {
- if (activeQueueSessionKey) {
+ if (!activeQueueSessionKey) {
- loadIntoComposer(text, [])
- stashAt(submittedScope, text, [])
++ loadIntoComposer(frozen.displayText, [])
++ stashAt(submittedScope, frozen.displayText, [])
+ } else if (canonical) {
- dispatchSubmit(text, [], undefined, { fromQueue: true, sessionId: sessionId ?? null, storedSessionId: activeQueueSessionKey })
++ // `fromQueue` skips the submit-side freeze, so hand it the frozen transport.
++ dispatchSubmit(frozen.transportText, [], undefined, {
++ ...(hasTerminalTransport ? { displayText: frozen.displayText } : {}),
++ fromQueue: true,
++ sessionId: sessionId ?? null,
++ storedSessionId: activeQueueSessionKey
++ })
+ } else {
- enqueueQueuedPrompt(activeQueueSessionKey, { text, attachments: [] })
+ enqueueQueuedPrompt(activeQueueSessionKey, {
+ text: frozen.displayText,
+ attachments: [],
+ ...(hasTerminalTransport ? { displayText: frozen.displayText, frozenTransport: frozen.transportText } : {})
+ })
- } else {
- loadIntoComposer(frozen.displayText, [])
}
}
- void Promise.resolve().then(() => onSteer(text, mode)).then(accepted => {
- if (!accepted) {
- keep()
- }
- }).catch(keep)
-
- void Promise.resolve(onSteer(frozen.transportText))
++ void Promise.resolve()
++ .then(() => onSteer(frozen.transportText, mode))
+ .then(accepted => {
+ if (!accepted) {
+ keep()
+ }
+ })
+ .catch(keep)
}
const queueDraft = () => {
diff --cc apps/desktop/src/app/chat/composer/index.tsx
index 5ec6e56c40f,0c4f1d6e8f4..b6cb4d7ef98
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@@ -437,11 -421,13 +440,12 @@@ export function ChatBar(
// into a tool result) and never for a slash command (those execute inline).
// A blocking prompt (approval/sudo/secret) also rules it out: the tool batch
// is parked on the user, so a steer can't reach the model — text queues.
- const canSteer = busy && !compacting && !blockingPrompt && !!onSteer && attachments.length === 0 && isSteerableText
+ // Compaction does not: the gateway holds the correction until it finishes.
+ const canSteer = busy && !blockingPrompt && !!onSteer && attachments.length === 0 && isSteerableText
- // While busy: text redirects the live turn (Cursor-style stop-and-correct),
- // attachments queue for the next turn, an empty composer stops.
- const busyAction: 'steer' | 'queue' | 'stop' = canSteer
- ? 'steer'
+ // Ordinary busy Send follows backend policy; attachments queue and empty stops.
+ const busyAction: 'interrupt' | 'steer' | 'queue' | 'stop' = canSteer
+ ? (busyInputMode ?? 'interrupt')
: compacting || hasComposerPayload
? 'queue'
: 'stop'
diff --cc apps/desktop/src/app/chat/composer/queue-panel.tsx
index 938028d32b1,fdd2e8341b1..0b2bcff708b
--- a/apps/desktop/src/app/chat/composer/queue-panel.tsx
+++ b/apps/desktop/src/app/chat/composer/queue-panel.tsx
@@@ -77,9 -94,9 +98,12 @@@ export function QueuePanel(
// Steer only surfaces where it can actually deliver: a live turn to
// redirect and an entry the redirect can carry (text-only, no slash).
const canSteer = busy && Boolean(onSteerNow) && isSteerableEntry(entry)
+ // The owner died mid-turn and recovered this row as `unknown`: the
+ // FIFO behind it is paused until someone acknowledges the loss.
+ const lost = entry.serverStatus === 'unknown'
+ const preview = entryPreview(entry, c)
+ const canExpand = shouldOfferExpandedPreview(preview)
+ const isExpanded = expandedIds.has(entry.id)
return (
<StatusRow
@@@ -91,21 -108,26 +115,43 @@@
key={entry.id}
leading={<Codicon className="text-muted-foreground/70" name="comment" size="0.8rem" />}
trailing={
- lost && onDiscardLost ? (
- <Tip label={c.queueLostDiscardTip}>
- <Button
- aria-label={c.queueLostDiscard}
- className="h-5 rounded-md px-1.5 text-[0.66rem]"
- data-slot="queue-lost-discard"
- onClick={() => onDiscardLost(entry.id)}
- size="micro"
- type="button"
- variant="text"
- >
- {c.queueLostDiscard}
- </Button>
- </Tip>
- ) : !entry.serverStatus && <>
+ <>
+ {canExpand && (
+ <Tip label={isExpanded ? c.queueCollapse : c.queueExpand}>
+ <Button
+ aria-expanded={isExpanded}
+ aria-label={isExpanded ? c.queueCollapse : c.queueExpand}
+ className="size-5 rounded-md"
+ onClick={() => toggleExpanded(entry.id)}
+ size="icon-xs"
+ type="button"
+ variant="ghost"
+ >
+ <Codicon
+ className={cn('transition-transform', isExpanded && 'rotate-180')}
+ name="chevron-down"
+ size={iconSize.xs}
+ />
+ </Button>
+ </Tip>
+ )}
++ {lost && onDiscardLost ? (
++ <Tip label={c.queueLostDiscardTip}>
++ <Button
++ aria-label={c.queueLostDiscard}
++ className="h-5 rounded-md px-1.5 text-[0.66rem]"
++ data-slot="queue-lost-discard"
++ onClick={() => onDiscardLost(entry.id)}
++ size="micro"
++ type="button"
++ variant="text"
++ >
++ {c.queueLostDiscard}
++ </Button>
++ </Tip>
++ ) : (
++ !entry.serverStatus && (
++ <>
<Tip label={c.queueEdit}>
<Button
aria-label={c.queueEdit}
@@@ -147,15 -169,21 +193,25 @@@
<CornerDownLeft className={iconSize.xs} />
</Button>
</Tip>
++ </>
++ )
++ )}
</>
}
- trailingVisible={isEditing}
+ trailingVisible={isEditing || lost}
>
<div className="min-w-0 flex-1">
- <p className="truncate text-[0.73rem] leading-4 text-foreground/92">{entryPreview(entry, c)}</p>
+ <p
+ className={cn(
+ 'text-[0.73rem] leading-4 text-foreground/92',
+ isExpanded ? 'max-h-40 overflow-y-auto whitespace-pre-wrap pr-1' : 'line-clamp-2 break-words'
+ )}
+ >
+ {preview}
+ </p>
- {(attachmentsCount > 0 || isEditing) && (
+ {(attachmentsCount > 0 || isEditing || lost) && (
<div className="mt-0.5 flex items-center gap-1.5 text-[0.64rem] text-muted-foreground/75">
+ {lost && <span data-slot="queue-lost-note">{c.queueLostNote}</span>}
{attachmentsCount > 0 && <span>{c.attachments(attachmentsCount)}</span>}
{isEditing && (
<span className="text-[color-mix(in_srgb,var(--dt-composer-ring)_78%,var(--muted-foreground))]">
diff --cc apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
index 97be14fde1f,6a417f14bb3..a5ce8adddb1
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
@@@ -6,9 -6,9 +6,10 @@@ import type { ClientSessionState } fro
import type * as HermesModule from '@/hermes'
import { textPart } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
+import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'
import { $notifications } from '@/store/notifications'
+ import { $cronRunReadOnlyVerdicts, recordCronRunVerdict } from '@/store/read-only-transcript'
-import { setSessionOwnerHint, setSessions } from '@/store/session'
+import { $activeSessionId, setSessionOwnerHint, setSessions } from '@/store/session'
import { $sessionTiles, sessionTileDelegate } from '@/store/session-states'
import type { SessionInfo } from '@/types/hermes'
diff --cc apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
index c57ed34e099,c25709c6726..06029fdcbb1
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
@@@ -34,12 -41,11 +41,13 @@@ import { refreshCronRunWriteGate } fro
import type { usePromptActions } from '../../session/hooks/use-prompt-actions'
import { singleFlightSessionResume } from '../../session/hooks/use-prompt-actions/single-flight-resume'
import { markSessionRecentlyInterrupted, withSessionNotFoundResume } from '../../session/hooks/use-prompt-actions/utils'
+ import type { useSessionActions } from '../../session/hooks/use-session-actions'
import {
chatMessageArraysEquivalent,
+ overlayConcurrentMessageChanges,
preserveLocalPendingTurnMessages,
reconcileResumeMessages,
+ resolveResumedBusy,
resolveSessionOwner
} from '../../session/hooks/use-session-actions/utils'
import type { useSessionStateCache } from '../../session/hooks/use-session-state-cache'
diff --cc apps/desktop/src/app/contrib/wiring.tsx
index f60730d7ce4,7c1818988ab..205313fdb2e
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@@ -230,11 -211,23 +209,21 @@@ function useRouteRequestNavigation(navi
routeRequestSeenRef.current = routeRequest.seq
navigate(routeRequest.path)
}, [navigate, routeRequest])
+ }
+
-// Recovery actions raised by toast buttons (Restart Hermes, Open Billing, pool
-// caps, cron review) fire from stores with no router context. Each counter is
++// Recovery actions raised by toast buttons (Restart Hermes, Open Billing, cron
++// review) fire from stores with no router context. Each counter is
+ // consumed here: the ref skips the initial mount value, and only a fresh
+ // request navigates or recycles the backend.
+ function useRecoveryRequestToasts(): void {
+ const navigate = useNavigate()
+ const billingSettingsRequest = useStore($billingSettingsRequest)
- const poolLimitsSettingsRequest = useStore($poolLimitsSettingsRequest)
+ const backendRestartRequest = useStore($backendRestartRequest)
+ const cronReviewRequest = useStore($cronReviewRequest)
+ const billingSettingsSeenRef = useRef(0)
- const poolLimitsSettingsSeenRef = useRef(0)
+ const backendRestartSeenRef = useRef(0)
+ const cronReviewSeenRef = useRef(0)
- // "Restart Hermes" from a toast: recycle the local backend the user is
- // looking at (same IPC the Models page uses), then let the boot hook re-dial.
- // A remote/cloud connection has no local process to recycle — there the
- // only meaningful "restart" is re-dialing the connection.
// eslint-disable-next-line no-restricted-syntax -- one-shot request-seen sentinel, not an atom mirror
useEffect(() => {
if (backendRestartRequest === backendRestartSeenRef.current) {
diff --cc apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index b2f9d640017,89a3534ea28..c5ff8082bac
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@@ -51,9 -54,10 +54,9 @@@ import
reportPrimaryGatewayState,
type ScopedServerRequest,
setPrimaryGateway,
- setPrimaryGatewayConnection,
- touchSecondaryGateways
+ setPrimaryGatewayConnection
} from '@/store/gateway'
- import { reconnectGateway, registerGatewayReconnect } from '@/store/gateway-reconnect'
+ import { type GatewayReconnectOptions, reconnectGateway, registerGatewayReconnect } from '@/store/gateway-reconnect'
import {
$gatewaySwitching,
beginGatewaySwitch,
@@@ -1273,6 -1395,6 +1377,12 @@@ export function useGatewayBoot(
pruneSecondaryGateways(keep)
}
++ // The pruner is otherwise event-driven: a socket spared by the
++ // min-lifetime grace with no store change afterwards would stay open
++ // forever. Pool keepalive touches are gone (the canonical gateway outlives
++ // its viewers); only this recompute tick remains.
++ const pruneTimer = setInterval(() => recomputeKeptGateways(), 60_000)
++
const offWorking = $workingSessionIds.subscribe(() => recomputeKeptGateways())
const offAttention = $attentionSessionIds.subscribe(() => recomputeKeptGateways())
const offActiveSession = $activeSessionId.subscribe(() => recomputeKeptGateways())
@@@ -1561,6 -1687,7 +1675,7 @@@
clearReconnectTimer()
clearBootRetryTimer()
clearLivenessReprobeTimer()
- clearInterval(keepaliveTimer)
++ clearInterval(pruneTimer)
offWorking()
offAttention()
offActiveSession()
diff --cc apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
index 290507c82de,f6faa268ce2..7759e7e88d3
--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
@@@ -115,6 -117,76 +118,77 @@@ describe('useBackgroundQueueDrain', ()
await waitFor(() => expect(getQueuedPrompts('stored-session-a')).toHaveLength(0))
})
+ it('submits a queued entry once when two idle windows both drain it', async () => {
+ // Web Locks are arbitrated across windows by the browser; jsdom has none.
+ // A FIFO mutex per lock name stands in for it.
+ const tails = new Map<string, Promise<unknown>>()
+
+ const request = (name: string, callback: () => Promise<unknown>) => {
+ const granted = (tails.get(name) ?? Promise.resolve()).then(callback)
+ tails.set(
+ name,
+ granted.catch(() => {})
+ )
+
+ return granted
+ }
+
+ Object.defineProperty(window.navigator, 'locks', { configurable: true, value: { request } })
+
+ try {
+ const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
+ let accept!: (accepted: boolean) => void
+ const submitText = vi.fn(() => new Promise<boolean>(resolve => (accept = resolve)))
+
+ enqueueQueuedPrompt('stored-session-a', { text: 'send me once', attachments: [] })
+ clearAllSessionStates()
+
+ // Two windows, each viewing another chat, share session A's queue.
+ render(<Harness runtimeMap={runtimeMap} selectedStoredSessionId="stored-session-b" submitText={submitText} />)
+ render(<Harness runtimeMap={runtimeMap} selectedStoredSessionId="stored-session-c" submitText={submitText} />)
+
+ await waitFor(() => expect(submitText).toHaveBeenCalled())
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+ await act(async () => accept(true))
+
+ await waitFor(() => expect(getQueuedPrompts('stored-session-a')).toHaveLength(0))
+ // Let the window that waited on the claim finish its turn at the queue.
+ await act(async () => {
+ await Promise.all(tails.values())
+ })
+
+ expect(submitText).toHaveBeenCalledTimes(1)
+ } finally {
+ delete (window.navigator as { locks?: unknown }).locks
+ }
+ })
+
+ it('forwards queued displayText so frozen @terminal chips render in the bubble', async () => {
+ const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
+ const submitText = vi.fn(async () => true)
+
+ enqueueQueuedPrompt('stored-session-a', {
+ text: 'look at @terminal:`zsh:23-58`',
+ displayText: 'look at @terminal:`zsh:23-58`',
+ attachments: [],
+ frozenTransport: '```terminal\nselection A\n```\n\nlook at'
+ })
+ clearAllSessionStates()
+
+ render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)
+
+ await waitFor(() => {
+ expect(submitText).toHaveBeenCalledWith('```terminal\nselection A\n```\n\nlook at', {
+ attachments: [],
+ displayText: 'look at @terminal:`zsh:23-58`',
+ fromQueue: true,
++ submission_id: expect.any(String),
+ sessionId: 'rt-session-a',
+ storedSessionId: 'stored-session-a'
+ })
+ })
+ })
+
it('leaves the selected session queue to the mounted ChatBar drainer', async () => {
const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
const submitText = vi.fn(async () => true)
diff --cc apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
index e40b4da45d7,d1e998ce25f..223e73299f6
--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
@@@ -164,38 -165,49 +165,51 @@@ export function useBackgroundQueueDrain
scheduleRetry()
}
- void Promise.resolve()
- .then(async () => {
- const liveEntry = getQueuedPrompts(sessionKey).find(candidate => candidate.id === entry.id)
+ void withQueueDrainClaim(sessionKey, async queue => {
+ const liveEntry = queue.find(candidate => candidate.id === entry.id)
- if (!liveEntry || liveEntry.serverStatus) {
- return true
- }
- if (!liveEntry) {
++ // Server-owned rows are already admitted to the gateway FIFO.
++ if (!liveEntry || liveEntry.serverStatus) {
+ return true
+ }
- const runtimeSessionId = runtimeIdByStoredSessionIdRef.current.get(sessionKey) ?? null
+ const resolved = resolveQueuedPromptTransport(liveEntry)
- const accepted = await Promise.resolve(
- submitTextRef.current(liveEntry.text, {
- attachments: liveEntry.attachments,
- fromQueue: true,
- submission_id: liveEntry.id,
- ...(liveEntry.displayText ? { displayText: liveEntry.displayText } : {}),
- sessionId: runtimeSessionId,
- storedSessionId: sessionKey
- })
- )
+ if (!resolved.ok) {
+ notify({
+ kind: 'warning',
+ title: t.composer.terminalSelectionMissingTitle,
+ message: t.composer.queuedTerminalSelectionExpiredBody
+ })
+ drainFailuresRef.current.set(liveEntry.id, MAX_AUTO_DRAIN_ATTEMPTS)
- if (accepted !== true) {
- return false
- }
+ return true
+ }
- drainFailuresRef.current.delete(liveEntry.id)
- // Submit owns blob: previews after a successful drain handoff.
- removeQueuedPrompt(sessionKey, liveEntry.id, { retainPreviewUrls: true })
- resetBrowseState(runtimeSessionId)
+ const runtimeSessionId = runtimeIdByStoredSessionIdRef.current.get(sessionKey) ?? null
- return true
- })
+ const accepted = await Promise.resolve(
+ submitTextRef.current(resolved.transportText, {
+ attachments: liveEntry.attachments,
+ ...(resolved.displayText ? { displayText: resolved.displayText } : {}),
+ fromQueue: true,
++ submission_id: liveEntry.id,
+ sessionId: runtimeSessionId,
+ storedSessionId: sessionKey
+ })
+ )
+
- if (accepted === false) {
++ if (accepted !== true) {
+ return false
+ }
+
+ drainFailuresRef.current.delete(liveEntry.id)
+ // Submit owns blob: previews after a successful drain handoff.
+ removeQueuedPrompt(sessionKey, liveEntry.id, { retainPreviewUrls: true })
+ resetBrowseState(runtimeSessionId)
+
+ return true
+ })
.then(accepted => {
if (!accepted) {
onFail()
diff --cc apps/desktop/src/app/session/hooks/use-hermes-config.ts
index d8fc469dd0e,6ecc132aa8f..d1f6c7d6f88
--- a/apps/desktop/src/app/session/hooks/use-hermes-config.ts
+++ b/apps/desktop/src/app/session/hooks/use-hermes-config.ts
@@@ -3,12 -3,10 +3,13 @@@ import { type MutableRefObject, useCall
import { setTerminalFontFamilyFromConfig } from '@/app/right-sidebar/terminal/terminal-font'
import { getHermesConfig, getHermesConfigDefaults } from '@/hermes'
import { BUILTIN_PERSONALITIES, normalizePersonalityValue, personalityNamesFromConfig } from '@/lib/chat-runtime'
+ import { composerServiceTier } from '@/lib/model-status-label'
import { normalize } from '@/lib/text'
+import { $busyInputConfig, busyInputOwnerKey, normalizeBusyInputMode } from '@/store/busy-input-mode'
import { setDisplayTimestampsFromConfig } from '@/store/display-timestamps'
+import { $activeGatewayProfile } from '@/store/profile'
import { setShowReasoningFromConfig } from '@/store/reasoning-disclosure'
+import { $connection } from '@/store/session'
import {
getComposerSelectionGeneration,
getCurrentModelSource,
@@@ -147,16 -143,9 +148,17 @@@ export function useHermesConfig({ activ
return
}
+ if ($connection.get() === connection && $activeGatewayProfile.get() === profile) {
+ $busyInputConfig.set({
+ owner: busyInputOwnerKey(connection?.connectionId, profile),
+ connection,
+ mode: normalizeBusyInputMode(config.display?.busy_input_mode)
+ })
+ }
+
setDisplayTimestampsFromConfig(config.display?.timestamps)
setShowReasoningFromConfig(config.display?.show_reasoning)
+ setShowToolActivityFromConfig(config.display?.tool_progress)
setTerminalFontFamilyFromConfig(config.terminal?.font_family)
setChatFontFamilyFromConfig(config.desktop?.font_family)
diff --cc apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
index 8e1686f120c,06641ecb48f..bb2d9f9452f
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
@@@ -1,7 -1,7 +1,8 @@@
import type { GatewayEvent } from '@hermes/shared'
import type { HermesSkin } from '@hermes/shared/skin'
+ import { invalidateContextBreakdown } from '@/app/shell/hooks/use-context-breakdown'
+import { eventSourceMatchesOwner, gatewayEventSource } from '@/lib/replay-gap-owner'
import { clearClarifyRequest } from '@/store/clarify'
import {
notifyCronChanged,
@@@ -14,16 -14,9 +15,16 @@@
type PetChangeMeta,
setChangeEventsAvailable
} from '@/store/live-sync'
- import { clearAllPrompts } from '@/store/prompts'
+ import { clearAllPrompts, clearApprovalRequest } from '@/store/prompts'
import { markRuntimeGone } from '@/store/runtime-gone'
-import { dropSessionState, unbindTileRuntime } from '@/store/session-states'
+import { getSessionOwnerHint, knownSessionOwner, ownerLookupSessionRows, requestSessionResume } from '@/store/session'
+import type { SessionOwnerScope } from '@/store/session-request-router'
+import {
+ $sessionTiles,
+ dropSessionState,
+ sessionTileDelegate,
+ unbindTileRuntime
+} from '@/store/session-states'
// Leaf import (not the `@/themes` barrel) to avoid pulling the ThemeProvider
// module graph into the gateway event hot path.
import { ingestBackendSkin } from '@/themes/backend-sync'
diff --cc apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
index 9b11acfb7d8,610a5740483..6998e5bb9c3
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
@@@ -1,10 -2,9 +2,10 @@@ import { finalizeInterruptedMessages }
import { normalizePersonalityValue } from '@/lib/chat-runtime'
import { modelOptionsQueryKey } from '@/lib/model-options'
import { reconcileApprovalModeForProfile } from '@/store/approval-mode'
- import { clearClarifyRequest } from '@/store/clarify'
+ import { clearSettledClarifyRequest } from '@/store/clarify'
import { reconcileSessionCompacting } from '@/store/compaction'
import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'
+import { reconcilePendingSubmissions } from '@/store/pending-submissions'
import { followActiveSessionCwd } from '@/store/projects'
import { clearAllPrompts } from '@/store/prompts'
import {
diff --cc apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
index 676c121d2ba,64dc17ac744..cbb46e25841
--- a/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
@@@ -20,13 -20,12 +20,15 @@@ import { act, cleanup, render, renderHo
import { useEffect, useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { MAIN_COMPOSER_SCOPE } from '@/app/chat/composer/scope'
+ import { useRuntimeMessageRepository } from '@/app/chat/runtime-repository'
+import { useSessionTileActions } from '@/app/chat/session-tile-actions'
import { usePromptActions } from '@/app/session/hooks/use-prompt-actions'
import type { ClientSessionState } from '@/app/types'
- import { chatMessageText } from '@/lib/chat-messages'
+ import { type ChatMessage, chatMessageText } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
+ import { IncrementalExternalStoreRuntimeCore } from '@/lib/incremental-external-store-runtime'
+import { setSessionTileDelegate } from '@/store/session-states'
import { STREAM_DELTA_FLUSH_MS } from './utils'
@@@ -96,28 -95,11 +98,29 @@@ function Harness({ tile = false }: { ti
updateSessionState
})
+ const tileActions = useSessionTileActions({
+ requestGateway,
+ runtimeId: SID,
+ storedSessionId: SID,
+ scope: MAIN_COMPOSER_SCOPE
+ })
+
useEffect(() => {
+ setSessionTileDelegate({
+ archiveSession: async () => undefined,
+ branchSession: async () => undefined,
++ branchSessionAtMessage: async () => false,
+ deleteSession: async () => undefined,
+ executeSlash: async () => undefined,
+ interruptSession: async () => undefined,
+ resumeTile: async () => SID,
- submitToSession: async () => undefined,
++ submitToSession: async () => ({ runtimeSessionId: SID, storedSessionId: SID }),
+ updateSession: updateSessionState
+ })
handleEvent = stream.handleGatewayEvent
- redirect = actions.redirectPrompt
+ redirect = tile ? tileActions.steerPrompt : actions.redirectPrompt
states = sessionStateByRuntimeIdRef.current
- }, [stream.handleGatewayEvent, actions.redirectPrompt])
+ }, [stream.handleGatewayEvent, actions.redirectPrompt, tileActions.steerPrompt, tile])
return null
}
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
index 57b03ae703d,d7a35054ba5..99046136d0a
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
@@@ -6,9 -4,9 +6,10 @@@ import type { MutableRefObject } from '
import { useEffect, useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ClientSessionState } from '@/app/types'
import { getLatestSessionMessages, getSession } from '@/hermes'
- import { textPart, toChatMessages } from '@/lib/chat-messages'
+ import { en } from '@/i18n/en'
+ import { textPart } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
import { $compactingSessions, setSessionCompacting } from '@/store/compaction'
import { $composerAttachments, $composerDraft, type ComposerAttachment, setComposerDraft } from '@/store/composer'
@@@ -47,7 -44,9 +49,10 @@@ import { uploadComposerAttachment, useP
// never-settling in-flight promise from one test into the next.
beforeEach(() => {
clearSingleFlightSessionResumeState()
+ window.localStorage.removeItem('hermes.desktop.preparedSubmissions.v1')
+ // Queue mutations build on the persisted map, not the atom — a queue an
+ // earlier test left in storage would otherwise sit ahead of this test's send.
+ window.localStorage.removeItem('hermes.desktop.composerQueue.v1')
vi.mocked(getLatestSessionMessages).mockReset()
vi.mocked(getLatestSessionMessages).mockImplementation(async () => ({ messages: [], session_id: 'session' }))
})
@@@ -2996,7 -2867,41 +3196,41 @@@ describe('usePromptActions redirectProm
expect(await handle!.redirectPrompt('too late')).toBe(false)
})
+ it('refuses to steer a session with no live turn — no echo, no RPC (#105176)', async () => {
+ // The composer's busy belief lags the slice by an effect tick on the
+ // busy→false settle edge, so a steer can reach redirectPrompt for a session
+ // whose turn already settled: not busy, no stream, not awaiting a response.
+ // There is nothing to redirect, so it must NOT echo a bubble into this chat
+ // nor RPC an idle session — returning false lets the caller queue the text
+ // for the conversation whose run is actually live.
+ publishSessionState(RUNTIME_SESSION_ID, createClientSessionState(RUNTIME_SESSION_ID))
+
+ try {
+ const requestGateway = vi.fn(async () => ({ status: 'redirected' }) as never)
+ // The stale belief: busy was true when the steer was fired.
+ const staleBusyRef = { current: true }
+
+ let handle: HarnessHandle | null = null
+ const capturedStates: Record<string, unknown>[] = []
+ await actRender(
+ <Harness
+ busyRef={staleBusyRef}
+ onReady={h => (handle = h)}
+ onSeedState={state => capturedStates.push(state)}
+ refreshSessions={async () => undefined}
+ requestGateway={requestGateway}
+ />
+ )
+
+ expect(await handle!.redirectPrompt('stale steer')).toBe(false)
+ expect(requestGateway).not.toHaveBeenCalled()
+ expect(capturedStates).toEqual([])
+ } finally {
+ dropSessionState(RUNTIME_SESSION_ID)
+ }
+ })
+
- it('reports rejection without throwing when the redirect RPC errors', async () => {
+ it('surfaces redirect RPC errors instead of converting rejection to queue admission', async () => {
const requestGateway = vi.fn(async () => {
throw new Error('agent does not support redirect')
})
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index a358ed5e38b,6877698f13c..59d7ba1d03b
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@@ -5,8 -4,7 +4,8 @@@ import { stripAnsi } from '@hermes/shar
import { useStore } from '@nanostores/react'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
+import { hermesApi } from '@/api/client'
- import { transcribeAudio } from '@/hermes'
+ import { type ResolvedOwner, transcribeAudio } from '@/hermes'
import { useI18n } from '@/i18n'
import { attachmentPathNeedsUpload } from '@/lib/attachment-upload-policy'
import { type ChatMessage, textPart } from '@/lib/chat-messages'
@@@ -129,32 -120,12 +129,33 @@@ export async function uploadComposerAtt
const label = attachment.label || pathLabel(path)
const uploadBytes = remote || attachmentPathNeedsUpload(path, backendCwd, terminalBackend)
+ if (attachment.kind === 'image' && serverOwnsComposerQueue(storedSessionId ?? opts.sessionId)) {
+ // Pin HTTP to the same owner before the native byte read yields. Images
+ // are immutable admission payloads, never legacy agent.pending_images.
+ const owner = destination.owner
+ const connectionId = typeof owner === 'object' && owner ? owner.connectionId : $connection.get()?.connectionId
+ const profile = typeof owner === 'object' && owner ? owner.targetProfile || owner.profile : owner || $activeGatewayProfile.get()
+
+ const dataUrl = attachment.previewUrl?.includes(';base64,')
+ ? attachment.previewUrl
+ : await window.hermesDesktop?.readFileDataUrl(path)
+
+ if (!dataUrl) { throw new Error(`Could not read ${label}`) }
+
+ const result = await hermesApi<{ path: string; mime_type: string }>({
+ method: 'POST', path: '/api/chat/image-upload', connectionId: connectionId ?? 'local', profile,
+ body: { data_url: dataUrl, filename: label }
+ })
+
+ return { ...attachment, path: result.path, mime: result.mime_type, attachedSessionId: opts.sessionId, uploadState: undefined }
+ }
+
// Read bytes/paths ONCE, outside the retry. Only the session-scoped RPC is
// replayed on recovery — re-reading a multi-MB file to retry a dead session
- // id would double the disk/IPC cost of every recovered attach. For images,
- // the chip's previewUrl already holds the full file as a base64 data URL,
- // so passing it avoids re-reading the same bytes off disk at submit.
+ // id would double the disk/IPC cost of every recovered attach. Images are
+ // always read fresh from disk here: the chip's cached `previewUrl` is
+ // dropped once a thumbnail exists, so it cannot be trusted to hold the
+ // full-resolution bytes the model needs.
let imagePayload: Awaited<ReturnType<typeof readImageForRemoteAttach>> | null = null
let fileDataUrl: null | string = null
@@@ -670,12 -631,23 +676,22 @@@ export function usePromptActions(
const visibleText = sanitizeComposerInput(rawText).trim()
const attachments = options?.attachments ?? $composerAttachments.get()
- if (!attachments.length && SLASH_COMMAND_RE.test(visibleText)) {
+ if (isSlashCommandText(visibleText)) {
+ if (attachments.length) {
+ notify({
+ kind: 'warning',
+ title: copy.slashCommandIgnoredTitle,
+ message: copy.slashCommandIgnoredBody
+ })
+
+ return false
+ }
+
triggerHaptic('selection')
+
// Forward the explicit target (background queue drain, tile) — dropping
// it ran the command against whatever chat happened to be in front.
- await executeSlashCommand(visibleText, options?.sessionId ? { sessionId: options.sessionId } : undefined)
-
- return true
+ return await executeSlashCommand(visibleText, options)
}
return await submitPromptText(rawText, options)
@@@ -908,7 -885,7 +943,8 @@@
[
activeSessionIdRef,
appendSessionTextMessage,
+ busyRef,
+ copy.promptFailed,
getRoutedStoredSessionId,
requestGateway,
runtimeIdByStoredSessionIdRef,
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index 211b9cf6322,70b9228f5ef..db2a2a64695
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
@@@ -193,46 -193,7 +196,46 @@@ export function useSlashCommand(deps: S
const compressInFlightRef = useRef(new Set<string>())
return useCallback(
- async (rawCommand: string, options?: SubmitTextOptions & { recordInput?: boolean }) => {
- async (rawCommand: string, options?: { sessionId?: string; recordInput?: boolean; typed?: boolean }) => {
++ async (rawCommand: string, options?: SubmitTextOptions & { recordInput?: boolean; typed?: boolean }) => {
+ const initialRuntimeId = options?.sessionId ?? activeSessionIdRef.current
+ const initialSelectedId = selectedStoredSessionIdRef.current
+ const initialRoutedId = getRoutedStoredSessionId()
+
+ let submitted = true
+
+ const initialStoredId =
+ options?.storedSessionId ??
+ (options?.sessionId
+ ? ($sessionStates.get()[options.sessionId]?.storedSessionId ?? null)
+ : (initialRoutedId ?? initialSelectedId))
+
+ const destination =
+ options?.destination ?? captureSubmissionDestination(initialStoredId ?? initialRuntimeId, ambientRequestGateway)
+
+ const requestGateway = destination.requestGateway
+ const retryOptions = { ...options, retryText: rawCommand }
+
+ try {
+ const prepared = await readPreparedSubmission(preparedSubmissionKey(
+ resolveComposerSessionKey(initialStoredId ?? initialRuntimeId, $sessions.get()),
+ destination, rawCommand, options?.attachments ?? $composerAttachments.get(), retryOptions
+ ))
+
+ if (prepared) {
+ return await submitPromptText(prepared.text, {
+ ...retryOptions, sessionId: initialRuntimeId ?? undefined,
+ storedSessionId: initialStoredId, displayText: prepared.displayText,
+ submission_id: prepared.id, destination
+ })
+ }
+ } catch (err) {
+ notifyError(err, copy.promptFailed)
+
+ return false
+ }
+
+ const submissionId = options?.submission_id ?? crypto.randomUUID()
+
// Resolve the session this command targets through the SHARED ladder that
// submit.ts uses. A slash command runs backend commands against a runtime
// session, and per-session state (`/goal`, `/usage`, `/status`) is keyed by
@@@ -1348,6 -1351,18 +1404,19 @@@
return
}
+ // Shared metrics count each command the user typed exactly once, here, whether the desktop
+ // handles it locally or on the gateway (which no longer counts slash.exec itself). An alias
+ // re-dispatch (recordInput=false) and programmatic calls (typed=false) are not user input.
+ if (recordInput && options?.typed !== false) {
- const metricsSessionId = sessionHint || activeSessionIdRef.current
++ // The entry-time runtime: the metric rides the same pinned destination.
++ const metricsSessionId = sessionHint || initialRuntimeId
+
+ void requestGateway('shared_metrics.slash_command', {
+ command: name,
+ ...(metricsSessionId ? { session_id: metricsSessionId } : {})
+ }).catch(() => undefined)
+ }
+
const ctx: SlashActionCtx = { arg, command, name, recordInput, sessionHint }
const surface = resolveDesktopCommand(`/${name}`)?.surface
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
index c33833d8aba,3a579344e58..121282d6959
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
@@@ -17,16 -16,15 +16,17 @@@ import
import {
$composerAttachments,
type ComposerAttachment,
+ freezeComposerTransportPayload,
mainComposerScope,
- revokeDiscardedAttachmentPreviews,
- terminalContextBlocksFromDraft
+ revokeDiscardedAttachmentPreviews
} from '@/store/composer'
+import { serverOwnsComposerQueue } from '@/store/composer-queue'
+ import { noteMessageSent } from '@/store/desktop-metrics'
import { $hudMode } from '@/store/hud'
import { clearNotifications, notify, notifyError } from '@/store/notifications'
import { consumePendingCredentialWarning, requestDesktopOnboarding } from '@/store/onboarding'
+import { trackPendingSubmission } from '@/store/pending-submissions'
- import { isStoredTranscriptReadOnly } from '@/store/read-only-transcript'
+ import { isCronRunReadOnly, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'
import {
$activeSessionId,
$sessions,
@@@ -37,26 -35,17 +37,24 @@@
setMessages,
touchSessionActivity
} from '@/store/session'
- import { $sessionStates, knownOwnerForSession } from '@/store/session-states'
+ import { profileScopeForSessionOwner } from '@/store/session-request-router'
-import { $sessionStates, $sessionTiles } from '@/store/session-states'
++import { $sessionStates, $sessionTiles, knownOwnerForSession } from '@/store/session-states'
import type { SessionInfo } from '@/types/hermes'
- import {
- profileScopeForTranscriptSession,
- resolveActiveTranscriptSession
- } from '../../../contrib/hooks/use-background-sync'
+ import { isCronRunSessionId, refreshCronRunWriteGate } from '../../../cron/open-cron-run'
import type { ClientSessionState } from '../../../types'
- import { sessionContextDrift } from '../session-context-drift'
- import { resolveSessionProfile } from '../use-session-actions/utils'
+ import { routeTargetFromToken, sessionContextDrift } from '../session-context-drift'
+ import type { CreateBackendSessionForSend } from '../use-session-actions/create-overrides'
+ import { resolveSessionOwner, resolveSessionProfile } from '../use-session-actions/utils'
+import {
+ preparedSubmissionKey,
+ readPreparedSubmission,
+ removePreparedSubmission,
+ writePreparedSubmission
+} from './prepared-submissions'
- import { finalizeInterruptedMessages } from './rewind'
import { registerRecoveredRuntime, singleFlightSessionResume, takeRecoveredRuntime } from './single-flight-resume'
+import { captureSubmissionDestination } from './submission-destination'
import {
acquireSubmitInFlight,
type GatewayRequest,
@@@ -242,11 -242,9 +267,11 @@@ export function useSubmitPrompt(deps: S
// not the foreground flag: an explicit target (tile, queue drain) is
// frequently not the session on screen, so the foreground flag would gate
// one session's send on another session's turn.
- const hasSendable = Boolean(visibleText || terminalContextBlocks || attachments.length || hasImage)
+ const hasSendable = Boolean(visibleText || attachments.length || hasImage)
const guardSessionId = options?.sessionId ?? activeSessionIdRef.current
+ const serverQueue = serverOwnsComposerQueue(options?.storedSessionId ?? guardSessionId)
+ const queueAdmission = serverQueue && Boolean(options?.fromQueue || isTargetSessionBusy($sessionStates.get(), guardSessionId, busyRef.current))
if (
!hasSendable ||
@@@ -888,63 -883,7 +946,20 @@@
// Images keep their inline bounded thumbnail — see optimisticAttachmentRef.
attachmentRefs = syncedAttachments.map(optimisticAttachmentRef).filter((r): r is string => Boolean(r))
rewriteOptimistic(liveSessionId, syncedAttachments)
- const text = buildContextText(syncedAttachments)
+ const text = retained?.text ?? buildContextText(syncedAttachments)
+
- // Another Desktop window may own a newer transcript while this one
- // still shows an open-time snapshot. Refuse the send and refresh
- // rather than forking the session (#65047). A server-owned
- // (canonical gateway) route has one writer and one FIFO, so a send
- // from a stale view only queues behind the peer's turn — no fork.
- const guardStoredId = targetStoredSessionId ?? selectedStoredSessionIdRef.current
-
- if (!serverQueue && guardStoredId && liveSessionId) {
- const localSnapshot = updateSessionState(liveSessionId, state => state, targetStoredSessionId)
-
- const refreshed = await refreshIfTranscriptStale(guardStoredId, localSnapshot.messages, {
- excludeMessageId: optimisticId,
- profile: profileScopeForTranscriptSession(resolveActiveTranscriptSession(guardStoredId, liveSessionId))
- })
-
- if (sessionDriftReason()) {
- return abortForSessionSwitch(liveSessionId)
- }
-
- if (refreshed) {
- updateSessionState(
- liveSessionId,
- state => ({
- ...state,
- awaitingResponse: false,
- busy: false,
- messages: refreshed,
- pendingBranchGroup: null
- }),
- targetStoredSessionId
- )
-
- if (targetIsCurrentView()) {
- scope.setMessages(() => refreshed)
- notify({
- kind: 'warning',
- message: copy.staleSessionBody,
- title: copy.staleSessionTitle
- })
- }
-
- releaseBusy()
-
- return false
- }
- }
-
++ // No pre-send stale-transcript guard (removed on main, fcfc5c66ede):
++ // windows on one backend share the live session and turns are
++ // serialized, so a send from a window behind its chat cannot fork it.
+ trackPendingSubmission(targetStoredSessionId ?? liveSessionId, {
+ id: submissionId,
+ text,
+ displayText: options?.displayText
+ })
+
- const imageAttachments = syncedAttachments.filter(attachment => attachment.kind === 'image' && attachment.mime)
++ const imageAttachments = syncedAttachments
++ .filter(attachment => attachment.kind === 'image' && attachment.mime)
+ .map(attachment => ({ path: attachment.path!, mime: attachment.mime! }))
const submitParams = (targetId: string) => ({
session_id: targetId,
@@@ -999,12 -915,18 +1014,20 @@@
// other session-scoped RPC (attach, /compress, rewind, interrupt) goes
// through the same helper so one policy covers the whole bug class.
let submitErr: unknown = null
+ let legacyAccepted = false
+ // The identity the backend actually accepted: the live runtime id,
+ // replaced below when a stale binding was recovered.
+ let acceptedRuntimeSessionId = liveSessionId
+ // Hoisted out of the recovery call so the acceptance report can name
- // the durable session even when no recovery was needed.
- const recoverStoredSessionId = targetStoredSessionId ?? selectedStoredSessionIdRef.current
++ // the durable session even when no recovery was needed. The explicit
++ // target only: a drain must never recover into the chat on screen.
++ const recoverStoredSessionId = targetStoredSessionId
try {
- const recoverStoredSessionId = targetStoredSessionId
+ // A bot's chat is a tile scoped to the `bots` workspace; the primary chat is Sessions mode.
+ noteMessageSent($sessionTiles.get().find(tile => tile.runtimeId === sessionId)?.workspaceMode ?? 'sessions')
- const submitted = await withSessionNotFoundResume(
+ const { result, sessionId: receiptSessionId } = await withSessionNotFoundResume<SubmitReceipt>(
sessionId,
recoverStoredSessionId,
liveId =>
@@@ -1133,6 -984,8 +1156,8 @@@
}
})
}
+
- acceptedRuntimeSessionId = submitted.sessionId
++ acceptedRuntimeSessionId = receiptSessionId
} catch (firstErr) {
if (firstErr instanceof SessionRecoveryAborted) {
console.warn('[submit-drift-abort]', firstErr.reason, { phase: 'post-resume-retry' })
@@@ -1147,8 -1000,16 +1172,18 @@@
throw submitErr
}
+ await removePreparedSubmission(retryKey)
+
+ // The prompt is now accepted. Report the EXACT identity it landed on
+ // (recovered id included) so a caller that must prove delivery — the
+ // Quick Entry bridge — never guesses the foreground session. Fires
+ // before the local cleanup below: acceptance is already true even if a
+ // later local step throws.
+ options?.onAccepted?.({
+ runtimeSessionId: acceptedRuntimeSessionId,
+ storedSessionId: recoverStoredSessionId ?? null
+ })
+
if (usingComposerAttachments) {
// A submit owns only the occurrences that actually reached the
// gateway. Tokenized chips match across staging clones; legacy chips
diff --cc apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index 4b8189fce20,d3d57a98303..1e045b1fe06
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@@ -879,30 -1152,214 +1152,237 @@@ describe('startFreshSessionDraft', () =
})
})
+ describe('submitTextToNewSession pin release', () => {
+ beforeEach(() => {
+ releaseStoredSessionPins('corr-1')
+ releaseStoredSessionPins('owner-a')
+ releaseStoredSessionPins('owner-b')
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ it('releases the pin at the terminal transition instead of on ticks', async () => {
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.create') {
+ return { session_id: RUNTIME_SESSION_ID, stored_session_id: 'stored-quick-entry' } as never
+ }
+
+ return {} as never
+ })
+
+ let handle: HarnessHandle | null = null
+
+ render(
+ <Harness
+ getRoutedStoredSessionId={() => 'stored-other'}
+ onReady={value => (handle = value)}
+ requestGateway={requestGateway}
+ />
+ )
+ await waitFor(() => expect(handle).not.toBeNull())
+
+ await act(async () => {
+ await handle!.submitTextToNewSession('quick entry', 'corr-1')
+ })
+
+ expect(pinnedStoredSessionIdsForOwner('corr-1').size).toBe(0)
+ })
+
+ it('concurrent new-session submissions keep distinct owner pins', async () => {
+ const observations: Array<{ promptOwner: 'owner-a' | 'owner-b'; ownerA: string[]; ownerB: string[] }> = []
+ const runtimeOwner = new Map<string, 'owner-a' | 'owner-b'>()
+
+ const storedByOwner = {
+ 'owner-a': 'stored-owner-a',
+ 'owner-b': 'stored-owner-b'
+ } as const
+
+ let createCount = 0
+ const releaseCreates = deferred<void>()
+
+ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {
+ if (method === 'session.create') {
+ createCount += 1
+
+ const owner = params?.model === 'model-owner-a' ? 'owner-a' : 'owner-b'
+ const runtimeSessionId = `runtime-${owner}`
+ runtimeOwner.set(runtimeSessionId, owner)
+
+ if (createCount < 2) {
+ await releaseCreates.promise
+ }
+
+ return {
+ session_id: runtimeSessionId,
+ stored_session_id: storedByOwner[owner]
+ } as never
+ }
+
+ if (method === 'prompt.submit') {
+ const promptOwner = runtimeOwner.get(String(params?.session_id)) ?? 'owner-a'
+ observations.push({
+ promptOwner,
+ ownerA: [...pinnedStoredSessionIdsForOwner('owner-a')],
+ ownerB: [...pinnedStoredSessionIdsForOwner('owner-b')]
+ })
+ }
+
+ return {} as never
+ })
+
+ let handle: HarnessHandle | null = null
+
+ render(
+ <Harness
+ getRoutedStoredSessionId={() => 'stored-other'}
+ onReady={value => (handle = value)}
+ requestGateway={requestGateway}
+ />
+ )
+ await waitFor(() => expect(handle).not.toBeNull())
+
+ let first!: Promise<{ runtimeSessionId: string; sessionId: string }>
+ let second!: Promise<{ runtimeSessionId: string; sessionId: string }>
+ act(() => {
+ setCurrentModel('model-owner-a')
+ setCurrentModelSource('manual')
+ first = handle!.submitTextToNewSession('a', 'owner-a')
+ setCurrentModel('model-owner-b')
+ setCurrentModelSource('manual')
+ second = handle!.submitTextToNewSession('b', 'owner-b')
+ setCurrentModel('')
+ setCurrentModelSource('')
+ })
+
+ await waitFor(() => expect(createCount).toBe(2))
+
+ await act(async () => {
+ releaseCreates.resolve()
+ await Promise.all([first, second])
+ })
+
+ expect(observations).toHaveLength(2)
+ expect(observations.map(({ promptOwner }) => promptOwner).sort()).toEqual(['owner-a', 'owner-b'])
+
+ for (const observation of observations) {
+ const ownPins = observation.promptOwner === 'owner-a' ? observation.ownerA : observation.ownerB
+ const otherPins = observation[observation.promptOwner === 'owner-a' ? 'ownerB' : 'ownerA']
+
+ expect(ownPins).toContain(storedByOwner[observation.promptOwner])
+ expect(ownPins).not.toContain(storedByOwner[observation.promptOwner === 'owner-a' ? 'owner-b' : 'owner-a'])
+ expect(otherPins).not.toContain(storedByOwner[observation.promptOwner])
+ }
+
+ expect(pinnedOwnerCount()).toBe(0)
+ })
+
+ it('submits to the exact created runtime even when the route/selection never moved (#85590/#107773 race)', async () => {
+ // The Quick Entry new-session path is route-neutral: it never navigates
+ // before the submit, so the drift guard must see identical tokens across
+ // the seconds-long session.create round-trip and never abort its own
+ // first send.
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.create') {
+ return { session_id: 'runtime-quick', stored_session_id: 'stored-quick' } as never
+ }
+
+ return {} as never
+ })
+
+ let handle: HarnessHandle | null = null
+
+ render(
+ <Harness
+ getRoutedStoredSessionId={() => 'stored-other'}
+ onReady={value => (handle = value)}
+ requestGateway={requestGateway}
+ />
+ )
+ await waitFor(() => expect(handle).not.toBeNull())
+
+ const created = await handle!.submitTextToNewSession('quick entry text')
+
+ expect(created).toEqual({ runtimeSessionId: 'runtime-quick', sessionId: 'stored-quick' })
+ expect(requestGateway).toHaveBeenCalledWith('prompt.submit', {
+ session_id: 'runtime-quick',
+ text: 'quick entry text'
+ })
+ })
+
+ it('aborts the new-session submit when a genuine user switch lands mid-create', async () => {
+ // A real navigation to another chat between the create's start and its
+ // settle is drift: the minted session must not receive the prompt and the
+ // caller gets a retryable failure, not a silent misroute.
+ const createPending = deferred<Record<string, string>>()
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.create') {
+ return (await createPending.promise) as never
+ }
+
+ return {} as never
+ })
+
+ const selectedRef = { current: 'stored-original' as string | null }
+ let routeToken = 'route:a'
+ let handle: HarnessHandle | null = null
+
+ render(
+ <Harness
+ getRoutedStoredSessionId={() => 'stored-original'}
+ getRouteToken={() => routeToken}
+ onReady={value => (handle = value)}
+ requestGateway={requestGateway}
+ selectedStoredSessionIdRef={selectedRef}
+ />
+ )
+ await waitFor(() => expect(handle).not.toBeNull())
+
+ let submit!: Promise<{ runtimeSessionId: string; sessionId: string }>
+ act(() => {
+ submit = handle!.submitTextToNewSession('misroute me')
+ })
+
+ // The user switches to a different chat while session.create is in flight.
+ routeToken = 'route:b'
+ selectedRef.current = 'stored-elsewhere'
+ createPending.resolve({ session_id: 'runtime-orphan', stored_session_id: 'stored-orphan' })
+
+ await expect(submit).rejects.toThrow(/destination changed mid-create/)
+
+ // The orphaned runtime never received the prompt.
+ const promptCalls = requestGateway.mock.calls.filter(([method]) => method === 'prompt.submit')
+ expect(promptCalls).toEqual([])
+ })
+ })
+
describe('createBackendSessionForSend profile routing', () => {
+ it('reuses the create intent after ACK loss but not after New chat', async () => {
+ $newChatRoute.set(null)
+ $activeGatewayProfile.set('default')
+ const calls: Record<string, unknown>[] = []
+
+ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {
+ if (method === 'session.create') { calls.push(params!); throw new Error('lost create ACK') }
+
+ return {} as never
+ })
+
+ let handle: HarnessHandle | null = null
+ render(<Harness onReady={value => { handle = value }} requestGateway={requestGateway} />)
+ await waitFor(() => expect(handle).not.toBeNull())
+ await act(async () => { await expect(handle!.createBackendSessionForSend()).rejects.toThrow('lost create ACK') })
+ await act(async () => { await expect(handle!.createBackendSessionForSend()).rejects.toThrow('lost create ACK') })
+ expect(calls[0].request_id).toEqual(expect.any(String))
+ expect(calls[1].request_id).toBe(calls[0].request_id)
+ act(() => handle!.startFreshSessionDraft())
+ await act(async () => { await expect(handle!.createBackendSessionForSend()).rejects.toThrow('lost create ACK') })
+ expect(calls[2].request_id).not.toBe(calls[0].request_id)
+ })
+
afterEach(() => {
cleanup()
$newChatProfile.set(null)
diff --cc apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 5fa51b3f6d2,d60e31454d0..6971b71e599
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@@ -941,17 -1172,27 +1178,30 @@@ export function useSessionActions(
// flag) into the bot's chat; omitting them lets the selected profile
// supply its configured defaults. Ordinary Sessions tiles keep the
// sticky composer override.
+ //
+ // No `hidden` here, in either mode. Only Bot Mode's PLUMBING sessions
+ // are born hidden, and each mints its own row: the canonical Bot Chat
+ // (`hermes-bots/canonical-chat.ts`) and group member sessions
+ // (`hermes-bots/group-turns.ts`). Every session this path creates is a
+ // side chat the user asked for by hand — "New chat with this bot" and
+ // the Bot Mode tab-strip "+" / ⌘T — so it is an ordinary conversation
+ // in the bot's profile and stays listed, exactly as
+ // `apps/desktop/src/AGENTS.md` and the hide sweep's title allow-list
+ // (`hermes-bots/session-sweep.ts`) already promise. Blanket-hiding the
+ // mode stranded them: unlisted in the Sessions sidebar, skipped by
+ // `/resume`, and reachable only while their tab stayed open, since the
+ // bot row opens the canonical chat and "Open recent session" reads
+ // `last_session`, which never reports a hidden row.
- const params = await desktopSessionCreateParams(
- cwd,
- capturedRoute,
- requestedProfile,
- options?.route === null || defaultTarget?.route === null,
- workspaceScope.workspaceMode !== 'bots'
- )
+ const params = {
+ ...(await desktopSessionCreateParams(
+ cwd,
+ capturedRoute,
+ requestedProfile,
+ options?.route === null || defaultTarget?.route === null,
+ workspaceScope.workspaceMode !== 'bots'
+ )),
- request_id: crypto.randomUUID(),
- ...(workspaceScope.workspaceMode === 'bots' ? { hidden: true } : {})
++ request_id: crypto.randomUUID()
+ }
// Same lease chain as createBackendSessionForSend: owner socket held
// across the create, then the foreground hold carries it until the
diff --cc apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
index fa0ce3e5be7,f8495ef2506..446a842e6f2
--- a/apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/clarify-tool.test.tsx
@@@ -187,30 -190,8 +190,33 @@@ describe('ClarifyTool live card stays m
expect(screen.getByText('Which deployment target?')).toBeTruthy()
expect(screen.queryByRole('status', { name: /loading question/i })).toBeNull()
- expect(screen.getByRole('button', { name: /Continue/ }).hasAttribute('disabled')).toBe(true)
+ expect(screen.getByRole('button', { name: /Confirm and continue/ }).hasAttribute('disabled')).toBe(true)
})
+
+ it('a batch tool call answered one card at a time by the shared gateway gets a live single card', () => {
+ // `gateway/run_turn_runner.py::_clarify_batch_sync` sends one single-question request per
+ // entry; the batch preview built from the tool args must not shadow it as a disabled form.
+ $activeSessionId.set('session-1')
+ $gateway.set({ request: vi.fn().mockResolvedValue({ ok: true }) } as never)
+ setClarifyRequest({
- choices: ['staging', 'production'],
- multiSelect: false,
- question: 'Which deployment target?',
++ questions: [{ choices: ['staging', 'production'], multiSelect: false, qid: 'request-1', question: 'Which deployment target?' }],
+ requestId: 'request-1',
+ sessionId: 'session-1'
+ })
+ const props = liveClarifyProps()
- const args = { questions: [{ question: 'Which deployment target?', choices: ['staging', 'production'] }] }
- renderClarify(<ClarifyTool {...props} args={args} argsText={JSON.stringify(args)} />)
+
- const staging = screen.getByRole('button', { name: /staging/ })
++ const args = {
++ questions: [
++ { question: 'Which deployment target?', choices: ['staging', 'production'] },
++ { question: 'Which region?', choices: ['us', 'eu'] }
++ ]
++ }
+
- expect(staging.hasAttribute('disabled')).toBe(false)
- expect(screen.queryByRole('button', { name: /Confirm and continue/ })).toBeNull()
++ renderClarify(<ClarifyTool {...props} args={args} argsText={JSON.stringify(args)} />)
++
++ expect(screen.getByRole('button', { name: /staging/ }).hasAttribute('disabled')).toBe(false)
++ expect(screen.queryByText('Which region?')).toBeNull()
+ })
})
describe('ClarifyTool choice selection', () => {
diff --cc apps/desktop/src/global.d.ts
index 5a33f759199,007eb281d35..68902d6c32a
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@@ -6,6 -7,10 +7,9 @@@ import type { ScreenshotApi } from '../
import type { HudModifierApi } from '../electron/hud-modifier-types'
import type { MachineProfile } from '../electron/machine-profile'
import type { HermesNotification } from '../electron/notification-types'
-import type { PoolLimits } from '../electron/pool-limits'
+ import type { KeepAwakeMode } from '../electron/power-save'
+ import type { UpdateHoldWire } from '../electron/update-hold-types'
+ import type { UpdateRunReport } from '../electron/updater/update-metrics'
import type { GrowRequest } from '../electron/window-growth'
import type { WakeIndicatorState } from './lib/wake-indicator'
diff --cc apps/desktop/src/i18n/ar.ts
index 6f3fa15e9f8,a6cf824bc54..64d8b3996a7
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@@ -1,3705 -12,49 +12,56 @@@ import { arSettings } from './ar_settin
import { defineLocale } from './define-locale'
export const ar = defineLocale({
- externalOpenFailed: {
- title: 'تعذّر فتح هذا الرابط',
- message: 'لا يوجد متصفح مسجل لفتح هذا العنوان. انسخ الرابط وافتحه يدويًا.',
- copyUrl: 'نسخ الرابط',
- close: 'إغلاق'
- },
-
- catalog: {
- add: 'إضافة',
- added: 'تمت الإضافة',
- discover: 'اكتشف',
- featured: 'مميزة',
- explorePlugins: 'استكشف الإضافات',
- exploreSkills: 'استكشف المهارات',
- mostStarred: 'الأكثر حصولًا على نجوم',
- newest: 'الأحدث',
- recentlyUpdated: 'المحدثة مؤخرًا',
- alphabetical: 'الاسم',
- sortBy: 'ترتيب حسب',
- seeAll: 'عرض الكل',
- related: 'عناصر مشابهة',
- tags: 'الوسوم',
- screenshots: 'لقطات الشاشة',
- listView: 'عرض القائمة',
- cardView: 'عرض البطاقات',
- installTitle: (name: string) => `تثبيت «${name}»؟`,
- installDescription: 'ستتوفر هذه المهارة في الجلسات الجديدة. ثبّت من المصادر التي تثق بها فقط.',
- installTo: 'التثبيت في',
- thisComputer: 'هذا الكمبيوتر',
- installing: 'جارٍ التثبيت…',
- installComplete: (name: string) => `تم تثبيت «${name}»`,
- destinationChanged: 'تغيرت وجهة التثبيت. أغلق هذا الحوار وافتح رابط التثبيت مجددًا.',
- installed: 'المثبتة',
- searchSkills: 'البحث في المهارات',
- searchPlugins: 'البحث في الإضافات',
- allSources: 'كل المصادر',
- allCategories: 'كل الفئات',
- about: 'نبذة',
- author: 'المؤلف',
- source: 'المصدر',
- category: 'الفئة',
- version: 'الإصدار',
- platforms: 'المنصات',
- requires: 'المتطلبات',
- tools: 'الأدوات',
- hooks: 'الخطافات',
- middleware: 'البرمجيات الوسيطة',
- commands: 'الأوامر',
- license: 'الترخيص',
- addedDate: 'تاريخ الإضافة',
- updatedDate: 'تاريخ التحديث',
- repository: 'المستودع',
- documentation: 'التوثيق',
- noResults: 'لا توجد نتائج مطابقة',
- tryAnother: 'جرّب بحثًا آخر أو امسح عوامل التصفية.',
- clearFilters: 'مسح عوامل التصفية',
- filters: 'عوامل التصفية',
- loadFailed: 'تعذر تحميل الكتالوج',
- retry: 'حاول مرة أخرى',
- more: 'عرض المزيد',
- pinned: 'التزام تمت مراجعته',
- snapshotHint: 'من كتالوج Hermes. لا يتصل التصفح بمستودعات المصدر مطلقًا.',
- installHint: 'راجع المصدر قبل التثبيت. تسري التغييرات على الجلسات الجديدة.',
- results: (count: number) => `النتائج: ${count.toLocaleString('ar')}`,
- back: 'العودة إلى النتائج'
- },
- sessionImport: {
- title: 'المتابعة من تطبيق آخر',
- subtitle: 'انقل محادثة إلى Hermes وتابع من حيث توقفت.',
- action: 'استيراد جلسة',
- readingFrom: 'القراءة من',
- connectedComputer: 'الكمبيوتر المتصل',
- destination: 'الاستيراد إلى',
- all: 'الكل',
- search: 'البحث في الجلسات المحملة',
- scanning: 'جارٍ البحث عن المحادثات',
- scanError: 'تعذر العثور على الجلسات',
- scanHelp: 'تحقق من اتصال الخادم ثم أعد المحاولة. قد تحتاج الخوادم القديمة إلى تحديث.',
- empty: 'لا توجد محادثات',
- emptyHelp: 'ستظهر هنا جلسات Claude Code وCodex الموجودة على هذا الخادم.',
- noMatches: 'لا توجد محادثات مطابقة',
- searchHelp: 'جرّب عنوانًا أو مجلدًا آخر، أو حمّل المزيد من الجلسات.',
- skipped: 'تم تجاوز بعض السجلات الفارغة أو غير المقروءة أو الكبيرة جدًا.',
- more: 'تحميل المزيد من الجلسات',
- messages: 'رسائل',
- choose: 'محادثة تستحق المتابعة',
- chooseHelp: 'اختر جلسة لقراءة سجلها قبل نقلها إلى Hermes.',
- previewLoading: 'جارٍ فتح المعاينة',
- previewError: 'المعاينة غير متاحة',
- previewHelp: 'ربما تم نقل الملف الأصلي أو تغييره. حدّث القائمة وحاول مرة أخرى.',
- previewLimit: 'تم اختصار المعاينة لتسهيل القراءة. يتم استيراد المحادثة كاملة.',
- you: 'أنت',
- snapshot: 'هذه المحادثة موجودة بالفعل في Hermes. افتح نسختك الحالية للمتابعة.',
- copyNotice: 'ينسخ نص المحادثة دون تغيير الملفات الأصلية. لا يشمل مخرجات الأدوات أو الاستدلال.',
- importing: 'جارٍ الاستيراد…',
- open: 'فتح في Hermes',
- continue: 'المتابعة في Hermes',
- importError: 'تعذر استيراد هذه المحادثة.'
- },
- sendDiagnostics: {
- title: 'إرسال التشخيصات إلى Nous',
- privacyNotice:
- 'سيؤدي هذا إلى رفع حزمة تصحيح إلى التخزين الداخلي لدى Nous (ليست لصيقة عامة). تتضمن معلومات النظام (نظام التشغيل، الإصدارات، المزوّد، وأنواع مفاتيح API المُهيأة — وليس المفاتيح نفسها أبداً) والسجلات الكاملة للوكيل والبوابة وسطح المكتب (حتى 512 كيلوبايت لكل منها، ومن المرجح أن تحتوي على محتوى المحادثات ومخرجات الأدوات ومسارات الملفات). تُحجب الأسرار قبل الرفع. لا يمكن الاطلاع عليها إلا لموظفي Nous ومشرفي Discord المعتمدين، وتُحذف تلقائياً بعد 14 يوماً.',
- upload: 'رفع',
- uploading: 'جارٍ الرفع…',
- cancel: 'إلغاء',
- close: 'إغلاق',
- copyLink: 'نسخ الرابط',
- uploadIdFallback: id => `لم يتم إرجاع رابط عرض — اذكر معرّف الرفع ${id} للدعم`,
- doneTitle: 'تم إرسال التشخيصات',
- doneDescription: 'تم رفع الحزمة بشكل خاص. شارك الرابط أدناه في محادثة الدعم لكي يتمكن الفريق من رؤية سجلاتك.',
- failedTitle: 'فشل الرفع',
- failedHint:
- 'يمكنك أيضاً تشغيل `hermes debug share --nous` من الطرفية، أو `hermes debug share --local` لعرض التقرير دون رفعه.',
- handoffLead: 'تابع النقاش في:',
- links: {
- github: 'GitHub Issues',
- portal: 'دعم بوابة Nous',
- discord: 'Discord'
- }
- },
- common: {
- apply: 'تطبيق',
- back: 'رجوع',
- save: 'حفظ',
- saving: 'جار الحفظ...',
- cancel: 'إلغاء',
- change: 'تغيير',
- choose: 'اختيار',
- clear: 'مسح',
- close: 'إغلاق',
- collapse: 'طي',
- confirm: 'تأكيد',
- connect: 'اتصال',
- connecting: 'جار الاتصال',
- continue: 'متابعة',
- bots: 'الروبوتات',
- copied: 'تم النسخ',
- copy: 'نسخ',
- copyFailed: 'فشل النسخ',
- delete: 'حذف',
- docs: 'الوثائق',
- done: 'تم',
- error: 'خطأ',
- failed: 'فشل',
- free: 'مجاني',
- loading: 'جار التحميل...',
- notSet: 'غير مضبوط',
- refresh: 'تحديث',
- remove: 'إزالة',
- replace: 'استبدال',
- retry: 'إعادة المحاولة',
- run: 'تشغيل',
- send: 'إرسال',
- set: 'ضبط',
- skip: 'تخطي',
- update: 'تحديث',
- on: 'مفعل',
- off: 'معطل'
- },
- fileMenu: {
- revealFinder: 'إظهار في Finder',
- revealExplorer: 'إظهار في File Explorer',
- revealFileManager: 'فتح المجلد الحاوي',
- revealInSidebar: 'إظهار في شجرة الملفات',
- copyPath: 'نسخ المسار',
- copyRelativePath: 'نسخ المسار النسبي',
- download: 'تنزيل',
- downloadSaved: 'تم الحفظ',
- downloadFailed: 'فشل التنزيل',
- rename: 'إعادة تسمية...',
- delete: 'حذف',
- renameTitle: 'إعادة تسمية',
- renameLabel: 'الاسم الجديد',
- deleteTitle: name => `حذف ${name}؟`,
- deleteBody: 'سيتم نقله إلى سلة المهملات — يمكنك استعادته من هناك.',
- pathCopied: 'تم نسخ المسار',
- revealMissing: 'هذا المجلد ليس على هذا الحاسوب'
- },
- boot: {
- ready: 'Hermes Desktop جاهز',
- desktopBootFailedWithMessage: message => `فشل تشغيل سطح المكتب: ${message}`,
- steps: {
- connectingGateway: 'جار الاتصال ببوابة سطح المكتب',
- loadingSettings: 'جار تحميل إعدادات Hermes',
- loadingSessions: 'جار تحميل الجلسات الأخيرة',
- retryingRemoteBackend: 'جارٍ إعادة الاتصال بخادم Hermes البعيد…',
- startingDesktopConnection: 'جار بدء اتصال سطح المكتب',
- startingHermesDesktop: 'جار تشغيل Hermes Desktop...'
- },
- errors: {
- backgroundExited: 'خرجت عملية Hermes الخلفية.',
- backgroundExitedDuringStartup: 'خرجت عملية Hermes الخلفية أثناء بدء التشغيل.',
- backendStopped: 'توقف الخلفية',
- desktopBootFailed: 'فشل تشغيل سطح المكتب',
- gatewayConnectionLost: 'انقطع الاتصال بالبوابة',
- gatewayConnectionLostDetail:
- 'Still retrying in the background. You can keep reading and drafting — open Gateway settings if this persists.',
- gatewaySignInRequired: 'تسجيل الدخول للبوابة مطلوب',
- ipcBridgeUnavailable: 'جسر IPC لسطح المكتب غير متاح.'
- },
- failure: {
- title: 'تعذر تشغيل Hermes',
- description: 'لم تعمل البوابة الخلفية. جرب إحدى خطوات الاسترداد أدناه. لن يحذف ذلك محادثاتك أو إعداداتك.',
- remoteTitle: 'تسجيل الدخول للبوابة البعيدة مطلوب',
- remoteDescription: 'انتهت جلسة البوابة البعيدة. سجل الدخول مرة أخرى لإعادة الاتصال.',
- retry: 'إعادة المحاولة',
- repairInstall: 'إصلاح التثبيت',
- useLocalGateway: 'استخدام البوابة المحلية',
- cloudDownTitle: 'عامل Nous Cloud معطّل',
- cloudDownDescription:
- 'يعيد عامل السحابة المُدار من Nous الذي يتصل به هذا البوابة خطأً من الخادم. لا يمكن إعادة تشغيله من هنا — تحقق من حالته، أو بدّل إلى البوابة المحلية، أو احصل على الدعم.',
- cloudDownHint: 'تفتح الأزرار أدناه بوابة Nous (حالة المثيل وعناصر التحكم) أو Discord للحصول على الدعم.',
- cloudDownCheckPortal: 'التحقق من حالة البوابة',
- cloudDownDiscord: 'الحصول على مساعدة عبر Discord',
- openLogs: 'فتح السجلات',
- repairHint: 'يعيد الإصلاح تشغيل المثبت وقد يستغرق بضع دقائق على جهاز جديد.',
- remoteSignInHint: signInLabel =>
- `يسجّل الخروج من جلسة المتصفح البعيدة المحفوظة، ثم يفتح ${signInLabel}. استخدم البوابة المحلية للتبديل إلى الخلفية المضمنة.`,
- signOutAndSignIn: 'تسجيل الخروج وإعادة تسجيل الدخول',
- hideRecentLogs: 'إخفاء السجلات الأخيرة',
- showRecentLogs: 'إظهار السجلات الأخيرة',
- signedInTitle: 'تم تسجيل الدخول',
- signedInMessage: 'جار إعادة الاتصال بالبوابة البعيدة...',
- signInIncompleteTitle: 'تسجيل الدخول غير مكتمل',
- signInIncompleteMessage: 'أغلقت نافذة تسجيل الدخول قبل اكتمال المصادقة.',
- signInFailed: 'فشل تسجيل الدخول',
- signInToRemoteGateway: 'تسجيل الدخول للبوابة البعيدة',
- signInWithProvider: provider => `تسجيل الدخول عبر ${provider}`,
- identityProvider: 'مزود الهوية'
- }
- },
- notifications: {
- sharedProfileWarning:
- 'تستخدم نسخة أخرى من Hermes هذا الملف الشخصي. تتشارك النسختان إعداداته وبياناته، لذا قد تتعارض التغييرات. يمكنك المتابعة أو إغلاق النسخة الأخرى قبل إجراء تغييرات.',
- region: 'الإشعارات',
- hide: 'إخفاء',
- show: 'إظهار',
- more: count => `${count} إشعار إضافي`,
- clearAll: 'مسح الكل',
- dismiss: 'إغلاق الإشعار',
- details: 'التفاصيل',
- copyDetail: 'نسخ التفاصيل',
- copyDetailFailed: 'تعذر نسخ تفاصيل الإشعار',
- backendOutOfDateTitle: 'الخلفية قديمة',
- backendOutOfDateMessage: 'خلفية Hermes أقدم من إصدار سطح المكتب الحالي وقد لا تعمل كما يجب. حدثهما ليتوافقا.',
- desktopOutOfDateTitle: 'التطبيق قديم',
- desktopOutOfDateMessage: 'تطبيق Hermes أقدم من الخلفية المتصل بها وقد لا يعمل كما يجب. حدّث التطبيق ليتوافقا.',
- updateDesktopApp: 'تحديث التطبيق',
- updateHermes: 'تحديث Hermes',
- updateReadyTitle: 'التحديث جاهز',
- updateReadyMessage: count => `${count} تغيير جديد متاح.`,
- updateReadyMessageUnknown: 'يتوفر تحديث جديد.',
- seeWhatsNew: 'عرض الجديد',
- mcp: {
- needsAuthTitle: 'خادم MCP يحتاج إلى إعادة المصادقة',
- needsAuthMessage: name => `يحتاج ${name} MCP إلى إعادة المصادقة.`,
- errorTitle: 'تعذر الوصول إلى خادم MCP',
- errorMessage: name => `فشل فحص سلامة ${name} MCP.`,
- signIn: 'تسجيل الدخول',
- view: 'عرض',
- disable: 'تعطيل',
- disabledMessage: name => `تم تعطيل ${name} MCP. يمكنك إعادة تفعيله في أي وقت من الإمكانات → MCP.`,
- disableFailed: name => `تعذّر تعطيل ${name} MCP.`
- },
- errors: {
- elevenLabsNeedsKey: 'يتطلب ElevenLabs STT المفتاح ELEVENLABS_API_KEY.',
- elevenLabsRejectedKey: 'رفض ElevenLabs مفتاح API (401).',
- diskFull: 'القرص ممتلئ — حرّر مساحة ثم أعد المحاولة.',
- methodNotAllowed: 'رفضت خلفية سطح المكتب هذا الطلب (405 Method Not Allowed). جرب إعادة تشغيل Hermes Desktop.',
- microphonePermission: 'تم رفض إذن الميكروفون.',
- openaiRejectedApiKey: 'رفض OpenAI مفتاح API.',
- openaiTtsNeedsKey: 'يتطلب OpenAI TTS المفتاح VOICE_TOOLS_OPENAI_KEY أو OPENAI_API_KEY.',
- codeSkewRestartRequired: 'بعد التحديث ما زال هذا الخلفية يشغّل كودا قديما. أعد تشغيله لتحميل الكود الجديد.'
- },
- voice: {
- configureSpeechToText: 'اضبط تحويل الكلام إلى نص لاستخدام وضع الصوت.',
- couldNotStartSession: 'تعذر بدء جلسة الصوت',
- microphoneAccessDenied: 'تم رفض الوصول إلى الميكروفون.',
- microphoneConstraintsUnsupported: 'قيود الميكروفون غير مدعومة على هذا الجهاز.',
- microphoneFailed: 'فشل الميكروفون',
- microphoneInUse: 'الميكروفون مستخدم من تطبيق آخر.',
- microphonePermissionDenied: 'تم رفض إذن الميكروفون.',
- microphoneStartFailed: 'تعذر بدء تسجيل الميكروفون.',
- microphoneUnsupported: 'هذا المتصفح لا يدعم تسجيل الميكروفون.',
- noMicrophone: 'لم يتم العثور على ميكروفون.',
- noSpeechDetected: 'لم يتم اكتشاف كلام',
- playbackFailed: 'فشل تشغيل الصوت',
- recordingFailed: 'فشل التسجيل',
- sayStopToEnd: phrase => `قل "${phrase}" لإنهاء المحادثة الصوتية.`,
- transcriptionFailed: 'فشل التفريغ النصي',
- transcriptionUnavailable: 'التفريغ النصي غير متاح.',
- tryRecordingAgain: 'حاول التسجيل مرة أخرى.',
- unavailable: 'الصوت غير متاح'
- },
- native: {
- approvalTitle: 'مطلوب موافقة',
- approvalTitleNamed: session => `مطلوب موافقة — ${session}`,
- approveAction: 'موافقة',
- rejectAction: 'رفض',
- inputTitle: 'مطلوب إدخال',
- inputTitleNamed: session => `مطلوب إدخال — ${session}`,
- inputBody: 'ينتظر Hermes ردّك.',
- turnDoneTitle: 'أنهى Hermes',
- turnDoneBody: '',
- turnErrorTitle: 'فشلت الجولة',
- backgroundDoneTitle: 'انتهت المهمة في الخلفية',
- backgroundFailedTitle: 'فشلت المهمة في الخلفية'
- }
- },
- remoteDisplayBanner: {
- message: reason => `العرض البرمجي نشط — تم اكتشاف شاشة بعيدة (${reason}). تم تعطيل تسريع GPU لمنع الوميض.`
- },
- titlebar: {
- hideSidebar: 'إخفاء الشريط الجانبي',
- showSidebar: 'إظهار الشريط الجانبي',
- search: 'بحث',
- searchTitle: 'البحث في الجلسات والعروض والإجراءات',
- swapSidebarSides: 'تبديل جانبي الأشرطة',
- hideRightSidebar: 'إخفاء الشريط الأيمن',
- showRightSidebar: 'إظهار الشريط الأيمن',
- unreadSessions: count => (count === 1 ? 'جلسة واحدة غير مقروءة' : `${count} جلسات غير مقروءة`),
- muteHaptics: 'كتم الاهتزازات',
- unmuteHaptics: 'تفعيل الاهتزازات',
- openSettings: 'فتح الإعدادات',
- openStarmap: 'فتح خريطة الذاكرة',
- enterHud: 'وضع HUD',
- exitHud: 'إنهاء وضع HUD',
- resetHudLayout: 'إعادة تعيين حجم HUD وموضعه',
- layoutEditor: 'محرر التخطيط',
- layoutEditorTitle: modifier => `محرر التخطيط — انقر مع ${modifier} لإعادة ضبط التخطيط`
- },
- keybinds: {
- title: 'اختصارات لوحة المفاتيح',
- subtitle: open => `انقر على اختصار لإعادة تعيينه · ${open} يعيد فتح هذه اللوحة.`,
- search: 'ابحث في الاختصارات...',
- rebind: 'إعادة تعيين',
- reset: 'إعادة إلى الافتراضي',
- resetAll: 'إعادة تعيين الكل',
- pressKey: 'اضغط مفتاحا...',
- set: 'مضبوط',
- conflictWith: label => `مرتبط أيضا بـ “${label}”`,
- categories: {
- composer: 'المحرّر',
- profiles: 'الملفات الشخصية',
- session: 'الجلسة',
- navigation: 'التنقل',
- view: 'العرض'
- },
- actions: {
- 'keybinds.openPanel': 'فتح اختصارات لوحة المفاتيح',
- 'nav.commandPalette': 'فتح لوحة الأوامر',
- 'nav.commandCenter': 'فتح مركز الأوامر',
- 'nav.settings': 'فتح الإعدادات',
- 'nav.profiles': 'فتح الملفات الشخصية',
- 'nav.capabilities': 'فتح المهارات',
- 'nav.messaging': 'فتح المراسلة',
- 'nav.artifacts': 'فتح العناصر',
- 'nav.cron': 'فتح المهام المجدولة',
- 'nav.agents': 'فتح الوكلاء',
- 'session.new': 'جلسة جديدة',
- 'session.newTab': 'علامة تبويب جلسة جديدة',
- 'session.newWindow': 'جلسة جديدة في نافذة',
- 'session.next': 'الجلسة التالية',
- 'session.prev': 'الجلسة السابقة',
- 'session.slot.1': 'الانتقال إلى الجلسة الأخيرة 1',
- 'session.slot.2': 'الانتقال إلى الجلسة الأخيرة 2',
- 'session.slot.3': 'الانتقال إلى الجلسة الأخيرة 3',
- 'session.slot.4': 'الانتقال إلى الجلسة الأخيرة 4',
- 'session.slot.5': 'الانتقال إلى الجلسة الأخيرة 5',
- 'session.slot.6': 'الانتقال إلى الجلسة الأخيرة 6',
- 'session.slot.7': 'الانتقال إلى الجلسة الأخيرة 7',
- 'session.slot.8': 'الانتقال إلى الجلسة الأخيرة 8',
- 'session.slot.9': 'الانتقال إلى الجلسة الأخيرة 9',
- 'session.focusSearch': 'البحث في الجلسات',
- 'session.togglePin': 'تثبيت / إلغاء تثبيت الجلسة الحالية',
- 'conversation.scrollPageUp': 'تمرير المحادثة صفحة إلى الأعلى',
- 'conversation.scrollPageDown': 'تمرير المحادثة صفحة إلى الأسفل',
- 'workspace.newWorktree': 'worktree جديد',
- 'workspace.openFolder': 'فتح مجلد كمشروع',
- 'composer.focus': 'التركيز على المحرّر',
- 'composer.modelPicker': 'فتح منتقي النموذج',
- 'composer.voice': 'بدء / إيقاف المحادثة الصوتية',
- 'composer.dictate': 'بدء / إيقاف الإملاء',
- 'composer.reasoningUp': 'رفع مستوى التفكير',
- 'composer.reasoningDown': 'خفض مستوى التفكير',
- 'view.toggleSidebar': 'تبديل الشريط الجانبي للجلسات',
- 'view.toggleRightSidebar': 'تبديل متصفح الملفات',
- 'view.toggleReview': 'تبديل لوحة المراجعة',
- 'view.showFiles': 'إظهار متصفح الملفات',
- 'view.showBrowser': 'فتح المتصفح',
- 'view.showTerminal': 'إظهار الطرفية',
- 'view.closeTab': 'إغلاق علامة التبويب',
- 'view.reopenTab': 'إعادة فتح علامة التبويب المغلقة',
- 'view.selectionToComposer': 'إرسال التحديد إلى المحرّر',
- 'view.terminalCopy': 'نسخ تحديد الطرفية',
- 'view.terminalPaste': 'لصق في الطرفية',
- 'view.flipPanes': 'تبديل جانبي الشريط الجانبي',
- 'appearance.toggleMode': 'تبديل الفاتح / الداكن',
- 'profile.default': 'الانتقال إلى الملف الشخصي الافتراضي',
- 'profile.switch.1': 'الانتقال إلى الملف الشخصي 1',
- 'profile.switch.2': 'الانتقال إلى الملف الشخصي 2',
- 'profile.switch.3': 'الانتقال إلى الملف الشخصي 3',
- 'profile.switch.4': 'الانتقال إلى الملف الشخصي 4',
- 'profile.switch.5': 'الانتقال إلى الملف الشخصي 5',
- 'profile.switch.6': 'الانتقال إلى الملف الشخصي 6',
- 'profile.switch.7': 'الانتقال إلى الملف الشخصي 7',
- 'profile.switch.8': 'الانتقال إلى الملف الشخصي 8',
- 'profile.switch.9': 'الانتقال إلى الملف الشخصي 9',
- 'profile.switch.10': 'الانتقال إلى الملف الشخصي 10',
- 'profile.switch.11': 'الانتقال إلى الملف الشخصي 11',
- 'profile.switch.12': 'الانتقال إلى الملف الشخصي 12',
- 'profile.switch.13': 'الانتقال إلى الملف الشخصي 13',
- 'profile.switch.14': 'الانتقال إلى الملف الشخصي 14',
- 'profile.switch.15': 'الانتقال إلى الملف الشخصي 15',
- 'profile.switch.16': 'الانتقال إلى الملف الشخصي 16',
- 'profile.switch.17': 'الانتقال إلى الملف الشخصي 17',
- 'profile.switch.18': 'الانتقال إلى الملف الشخصي 18',
- 'profile.next': 'الملف الشخصي التالي',
- 'profile.prev': 'الملف الشخصي السابق',
- 'profile.toggleAll': 'تبديل عرض كل الملفات الشخصية',
- 'profile.create': 'إنشاء ملف شخصي',
- 'composer.send': 'إرسال الرسالة',
- 'composer.newline': 'إدراج سطر جديد',
- 'composer.steer': 'توجيه الدور الجاري',
- 'composer.sendQueued': 'إرسال الدور التالي في الطابور',
- 'composer.mention': 'الإشارة إلى الملفات والمجلدات وعناوين URL',
- 'composer.slash': 'لوحة الأوامر المائلة',
- 'composer.help': 'مساعدة سريعة',
- 'composer.history': 'التنقل في النافذة المنبثقة / السجل',
- 'composer.cancel': 'إغلاق النافذة المنبثقة · إلغاء التشغيل'
- }
- },
- language: {
- label: 'اللغة',
- description: 'اختر لغة واجهة سطح المكتب.',
- saving: 'جار حفظ اللغة...',
- saveError: 'تعذر تحديث اللغة',
- switchTo: 'تغيير اللغة',
- searchPlaceholder: 'ابحث عن لغة...',
- noResults: 'لا توجد لغة مطابقة'
- },
- settings: {
- subpages: {
- appearanceTheme: 'السمة',
- appearanceTypography: 'الخطوط والتحجيم',
- appearanceWindowLayout: 'النافذة والتخطيط',
- appearanceChatDisplay: 'عرض المحادثة',
- appearancePet: 'الحيوان الأليف',
- appearanceGeneral: 'عام',
- modelMain: 'النموذج الرئيسي',
- modelAuxiliary: 'النماذج المساعدة',
- modelMoa: 'مزيج الوكلاء',
- modelFallbacks: 'النماذج البديلة',
- chatBehavior: 'السلوك',
- chatAttachments: 'المرفقات',
- workspaceProjects: 'المشاريع والاكتشاف',
- workspaceShell: 'بيئة الصدفة',
- workspaceFiles: 'الملفات والتنفيذ',
- safetyApprovals: 'الموافقات',
- safetyPrivacy: 'الخصوصية والشبكة',
- safetyCheckpoints: 'نقاط الاستعادة',
- browserProfile: 'ملف المتصفح',
- browserNetwork: 'العناوين المحلية والخاصة',
- memoryPersistent: 'الذاكرة الدائمة',
- memoryContext: 'السياق والضغط',
- voiceConversation: 'المحادثة الصوتية',
- voiceTranscription: 'تحويل الكلام إلى نص',
- voiceSpeech: 'تحويل النص إلى كلام',
- advancedRuntime: 'حدود الوكيل',
- advancedTools: 'الوصول إلى الأدوات',
- advancedTerminal: 'خلفية الطرفية',
- advancedOutput: 'حدود المخرجات',
- advancedDelegation: 'الوكلاء الفرعيون',
- advancedDesktop: 'سطح المكتب وبدء التشغيل',
- gatewayConnection: 'هذه النافذة',
- gatewayDevices: 'الاتصالات المحفوظة',
- gatewayManagedUpdates: 'التحديثات البعيدة',
- gatewayManagedUpdatesUnavailable: 'تتطلب التحديثات البعيدة إصدار سطح مكتب يدعم تحديثات SSH المُدارة.',
- gatewayManagedUpdatesEmpty: 'أضف اتصال SSH في الاتصالات المحفوظة لإدارة تحديثاته هنا.',
- keyboardShortcuts: 'تعيينات المفاتيح',
- hudGesture: 'إيماءة HUD',
- screenCapture: 'التقاط الشاشة',
- notificationAlerts: 'تنبيهات سطح المكتب',
- notificationSounds: 'الأصوات',
- archivedSessions: 'الأرشفة والاحتفاظ',
- defaultDirectory: 'مجلد المشروع الافتراضي',
- vaultCredentials: 'بيانات الاعتماد المحفوظة',
- vaultSources: 'مديرو كلمات المرور',
- appUpdates: 'الإصدار والتحديثات',
- uninstall: 'إلغاء التثبيت',
- billingOverview: 'نظرة عامة',
- billingPlans: 'الخطط'
- },
- closeSettings: 'إغلاق الإعدادات',
- exportConfig: 'تصدير الإعدادات',
- importConfig: 'استيراد الإعدادات',
- resetToDefaults: 'إعادة الافتراضيات',
- resetConfirm: 'هل تريد إعادة كل الإعدادات إلى افتراضيات Hermes؟',
- exportFailed: 'فشل التصدير',
- resetFailed: 'فشلت إعادة الضبط',
- nav: {
- providers: 'المزودون',
- providerAccounts: 'الحسابات',
- providerApiKeys: 'مفاتيح API',
- gateway: 'البوابة',
- apiKeys: 'الأدوات والمفاتيح',
- keysTools: 'الأدوات',
- keysSettings: 'الإعدادات',
- mcp: 'MCP',
- archivedChats: 'المحادثات المؤرشفة',
- sessions: 'الجلسات',
- about: 'حول',
- notifications: 'الإشعارات',
- keybinds: 'اختصارات لوحة المفاتيح',
- vault: 'كلمات المرور وتسجيلات الدخول'
- },
- vault: {
- title: 'كلمات المرور وتسجيلات الدخول',
- blurb:
- 'قل «سجّل الدخول إلى GitHub» وسيقوم الوكيل بذلك نيابةً عنك. في أول مرة يصادف صفحة تسجيل دخول يطلب منك بيانات الدخول في مكانها، وبعدها يعمل تلقائيًا. تُشفَّر كلمات المرور على هذا الجهاز وتُملأ في الصفحة مباشرة — ولا يراها النموذج أبدًا.',
- count: n => `${n} محفوظة`,
- loadFailed: 'تعذّر تحميل عناصر الخزنة',
- empty: 'لا شيء محفوظ بعد',
- emptyDesc:
- 'لا حاجة لإضافة أي شيء هنا. اطلب من الوكيل تسجيل الدخول إلى موقع وسيطلب منك بيانات الدخول مرة واحدة في مكانها. استخدم «إضافة» إذا كنت تفضّل إدخالها مسبقًا.',
- add: 'إضافة',
- addTitle: 'إضافة بيانات دخول أو بطاقة أو عنوان',
- addDescription: 'تُخزَّن مشفّرة على هذا الجهاز. لا يرى الوكيل كلمة المرور أبداً.',
- added: 'تم الحفظ.',
- adding: 'جارٍ الحفظ…',
- addConfirm: 'حفظ',
- kindField: 'النوع',
- kinds: { login: 'تسجيل دخول', payment: 'بطاقة دفع', address: 'عنوان' },
- labelField: 'التسمية',
- labelPlaceholder: 'مثال: حساب GitHub للعمل',
- labelRequired: 'التسمية مطلوبة.',
- originField: 'أصل الموقع',
- originPlaceholder: 'https://github.com',
- originPlaceholderCheckout: 'https://shop.example.com',
- originInvalid: 'أدخل عنوان URL صالحاً مثل https://example.com.',
- identifierTypeField: 'نوع المعرّف',
- identifierTypes: { email: 'البريد الإلكتروني', phone: 'الهاتف', username: 'اسم المستخدم' },
- identifierField: 'المعرّف',
- identifierShown: identifier => identifier,
- passwordField: 'كلمة المرور',
- loginFieldsRequired: 'المعرّف وكلمة المرور مطلوبان.',
- cardNumberField: 'رقم البطاقة',
- cardNameField: 'الاسم على البطاقة',
- expMonthField: 'شهر الانتهاء',
- expYearField: 'سنة الانتهاء',
- cvcField: 'CVC',
- postalField: 'الرمز البريدي',
- addressLine1Field: 'سطر العنوان 1',
- addressLine2Field: 'سطر العنوان 2',
- cityField: 'المدينة',
- stateField: 'الولاية / المنطقة',
- countryField: 'الدولة',
- optional: '(اختياري)',
- createdOn: date => `أُضيفت ${date}`,
- deleteAction: 'إزالة العنصر المحفوظ',
- otpField: 'مفتاح المصادقة',
- otpPlaceholder: 'سر Base32 أو رابط otpauth://',
- otpHint: '«مفتاح الإعداد» الذي يعرضه الموقع عند تفعيل المصادقة الثنائية. بحفظه يولّد Hermes الرموز بنفسه.',
- twoFactorBadge: '2FA تلقائي',
- deleteTitle: 'حذف هذا العنصر؟',
- deleteDescription: label => `سيُزال "${label}" من الخزنة المشفّرة. لا يمكن التراجع عن هذا.`,
- deleteConfirm: 'حذف',
- sources: {
- title: 'مديرو كلمات المرور',
- blurb:
- 'تُكتشف مديري كلمات المرور المثبّتة تلقائيًا. يطلب منك الوكيل فتح أحدها في أول مرة يحتاج فيها إلى بيانات دخول منه (مرة واحدة لكل جلسة)؛ يبقى في الذاكرة رمز الجلسة فقط، ولا يرى الوكيل كلمة المرور الرئيسية أو أي بيانات دخول.',
- toggleFailed: 'تعذر تحديث مدير كلمات المرور',
- notInstalled: name => `غير مكتشف. ثبّت أداة سطر الأوامر ${name} وسجّل الدخول إليها؛ سيكتشفها Hermes تلقائيًا.`,
- disabledDesc: 'مكتشف لكنه معطّل لـ Hermes.',
- lockedDesc: 'مكتشف. سيطلب منك الوكيل فتحه عند الحاجة إلى بيانات دخول، أو افتحه الآن.',
- unlockedDesc: 'مفتوح لهذه الجلسة. يُقفل تلقائيًا بعد 30 دقيقة من الخمول أو عند إغلاق Hermes.',
- statusLocked: 'مقفل',
- statusNotDetected: 'غير مكتشف',
- statusOff: 'متوقف',
- statusUnlocked: 'مفتوح',
- unlock: 'فتح القفل',
- unlocking: 'جارٍ فتح القفل…',
- lock: 'قفل',
- unlocked: name => `تم فتح قفل ${name} لهذه الجلسة.`,
- unlockTitle: name => `فتح قفل ${name}`,
- unlockDescription:
- 'أدخل كلمة المرور الرئيسية. تُسلَّم إلى مدير كلمات المرور على هذا الجهاز ثم تُهمل — لا تُخزَّن ولا تُسجَّل ولا تُعرض على الوكيل أبدًا.',
- masterPasswordPlaceholder: 'كلمة المرور الرئيسية'
- }
- },
- plugins: {
- title: 'إضافات سطح المكتب',
- blurb:
- 'امتدادات واجهة تُحمّل داخل هذا التطبيق — إما مضمّنة مع البناء، أو موضوعة في مجلد desktop-plugins (بما فيها التي يكتبها Hermes). تعطيل الإضافة يفرغها مباشرة ويبقى بعد إعادة التشغيل.',
- count: n => `${n} مثبتة`,
- openFolder: 'فتح مجلد إضافات سطح المكتب',
- rescan: 'إعادة الفحص',
- reveal: 'إظهار في مدير الملفات',
- enable: 'تفعيل',
- disable: 'تعطيل',
- failed: 'فشل',
- empty: 'لا توجد إضافات سطح مكتب مثبتة بعد.',
- kinds: { bundled: 'مضمّنة', disk: 'على القرص', runtime: 'وقت التشغيل' },
- installModal: {
- installUncertain:
- 'توقف Hermes عن انتظار نتيجة التثبيت، لكن قد يستمر تثبيت المكوّن الإضافي. أغلق هذه النافذة وأعد فحص قائمة المكوّنات الإضافية قبل محاولة التثبيت مرة أخرى.',
- toolsConnected: n => `تم توصيل ${n} من الأدوات`,
- skillsReady: names => (names.length === 1 ? `المهارة ${names[0]} جاهزة` : `${names.length} من المهارات جاهزة`),
- nextChat: 'أدوات أخرى متاحة في دردشتك التالية',
- serverNotConnected: (server, reason) => `خادم MCP ${server} غير متصل${reason ? `: ${reason}` : '.'}`
- }
- },
- notifications: {
- title: 'الإشعارات',
- intro:
- 'إشعارات سطح المكتب الأصلية، منفصلة عن التنبيهات داخل التطبيق. هذه محلية على الجهاز — كل حاسوب يحتفظ بإعداداته الخاصة.',
- enableAll: 'تفعيل الإشعارات',
- enableAllDesc: 'إيقافه يصمت كل الإشعارات أدناه.',
- focusedHint: 'تنبيهات الاكتمال تظهر فقط عندما يكون Hermes في الخلفية.',
- kinds: {
- approval: {
- label: 'يلزم الموافقة',
- description: 'هناك أمر ينتظر موافقتك أو رفضك له.'
- },
- input: {
- label: 'يلزم إدخال',
- description: 'طرح Hermes سؤالا أو يحتاج إلى كلمة مرور أو سر.'
- },
- turnDone: {
- label: 'الرد جاهز',
- description: 'انتهى دور بينما كان Hermes في الخلفية.'
- },
- turnError: {
- label: 'فشل الدور',
- description: 'أخطاء الأدوار في الخلفية.'
- },
- backgroundDone: {
- label: 'اكتملت مهمة الخلفية',
- description: 'اكتمل أمر طرفية يعمل في الخلفية.'
- }
- },
- test: 'إرسال إشعار تجريبي',
- testTitle: 'Hermes',
- testBody: 'الإشعارات تعمل.',
- testSent: 'تم إرسال التجربة. إذا لم يظهر شيء، تحقق من أذونات الإشعارات في نظام التشغيل ووضع التركيز/عدم الإزعاج.',
- testUnsupported: 'هذا النظام لا يدعم الإشعارات الأصلية.',
- completionSoundTitle: 'صوت الاكتمال',
- completionSoundDesc: 'يُشغّل عند انتهاء دور الوكيل. اختر إعدادا مسبقا وعاينه هنا.',
- completionSoundPreview: 'معاينة'
- },
- sections: {
- model: 'النموذج',
- chat: 'المحادثة',
- appearance: 'المظهر',
- workspace: 'مساحة العمل',
- safety: 'الأمان',
- memory: 'الذاكرة والسياق',
- voice: 'الصوت',
- advanced: 'متقدم'
- },
- searchPlaceholder: {
- about: 'حول Hermes Desktop',
- config: 'ابحث في الإعدادات...',
- gateway: 'اتصال البوابة...',
- keys: 'ابحث في مفاتيح API...',
- mcp: 'ابحث في خوادم MCP...',
- sessions: 'ابحث في المحادثات المؤرشفة...'
- },
- modeOptions: {
- light: {
- label: 'فاتح',
- description: 'أسطح سطح مكتب ساطعة'
- },
- dark: {
- label: 'داكن',
- description: 'مساحة عمل منخفضة الوهج'
- },
- system: {
- label: 'النظام',
- description: 'اتباع مظهر نظام التشغيل'
- }
- },
- appearance: {
- title: 'المظهر',
- intro: 'خصص مظهر Hermes Desktop.',
- colorMode: 'نمط الألوان',
- colorModeDesc: 'اختر الوضع الفاتح أو الداكن أو اتبع النظام.',
- toolViewTitle: 'عرض الأدوات',
- toolViewDesc: 'تحكم في كيفية عرض نشاط الأدوات داخل المحادثة.',
- hideCodeDiffsTitle: 'إخفاء فروق الكود',
- hideCodeDiffsDesc: 'عرض تعديلات الملفات كسطور أدوات مضمّنة مع عدد الأسطر المضافة والمحذوفة، دون عرض الكود.',
- hideThreadTimelineTitle: 'إخفاء أشرطة المخطط الزمني للمحادثة',
- hideThreadTimelineDesc: 'إخفاء أشرطة التنقل على الحافة اليمنى لكل محادثة.',
- reasoningCollapsedTitle: 'طي التفكير افتراضيًا',
- reasoningCollapsedDesc: 'أبقِ التفكير المتدفق متاحًا دون توسيعه حتى تفتحه.',
- translucencyTitle: 'شفافية النافذة',
- translucencyDesc: 'إظهار سطح المكتب من خلال النافذة بالكامل، بما في ذلك النص.',
- translucencyGlassDesc: 'زجاج غير لامع: يظهر سطح المكتب كضبابية ناعمة بينما يبقى النص واضحًا.',
- translucencyModeClear: 'شفاف',
- translucencyModeGlass: 'زجاج',
- translucencyTintTitle: 'التلوين',
- translucencyFadeTitle: 'التلاشي',
- translucencyFrostTitle: 'نوع الضبابية',
- translucencyFrost: {
- 'under-window': 'عميق',
- popover: 'ناعم',
- titlebar: 'ساطع',
- header: 'متوهج'
- },
- translucencyScopeTitle: 'النطاق',
- translucencyScope: {
- window: 'النافذة كاملة',
- sidebar: 'الشريط الجانبي فقط'
- },
- backdropTitle: 'خلفية النافذة',
- backdropDesc: 'اختيار مقدار مزج خلفية سطح المكتب مع سطح Hermes.',
- userBubbleTitle: 'فقاعة الرسالة',
- userBubbleDesc: 'مدى شفافية رسائلك. معتمة عند 0؛ يبقى الإطار فقط عند 100.',
- textDirectionTitle: 'اتجاه النص',
- textDirectionDesc:
- 'كيف تحدد رسائل المحادثة وحقل الكتابة اتجاهها. «تلقائي» يتبع أول حرف في كل فقرة؛ اختر اتجاهًا عندما يظهر النص المختلط بترتيب خاطئ. تبقى الشيفرة دائمًا من اليسار إلى اليمين.',
- textDirection: { auto: 'تلقائي', rtl: 'من اليمين إلى اليسار', ltr: 'من اليسار إلى اليمين' },
- introSplashTitle: 'شاشة المقدمة',
- introSplashDesc: 'الشعار النصي والعبارة التمهيدية في محادثة فارغة.',
- reactionsTitle: 'تفاعلات الرسائل',
- reactionsDesc: 'تفاعلات إيموجي بأسلوب iMessage — تفاعل مع الرسائل، ويمكن لـ Hermes التفاعل مع رسائلك.',
- tipsTitle: 'نصائح داخل التطبيق',
- tipsDesc:
- 'نصائح تظهر أحيانًا من التطبيق وHermes. تظهر كل نصيحة مرة واحدة. تُعطّل تلقائيًا بعد أول 30 يومًا من الاستخدام، ويمكنك تفعيلها مجددًا.',
- tipsReset: count => `إظهار ${count} نصيحة مرة أخرى`,
- toursTitle: 'جولات إرشادية',
- toursDesc:
- 'دع Hermes يرشدك في التطبيق مع إبراز كل خطوة. تُعطّل الجولات تلقائيًا بعد أول 30 يومًا من الاستخدام، ويمكنك تفعيلها مجددًا.',
- composerPopoutTitle: 'محرر عائم',
- composerPopoutDesc: 'السماح بسحب محرر الرسائل خارج موضعه. عند إيقاف الخيار، يبقى مثبتًا في الأسفل.',
- fileBrowserTitle: 'مستعرض الملفات',
- fileBrowserDesc: 'عرض مستعرض الملفات بجانب المحادثة عند فتح مساحة عمل. يغيّر زر شريط العنوان هذا الخيار أيضًا.',
- vibeHeartsTitle: 'قلوب المزاج',
- vibeHeartsDesc: 'قلوب عائمة عند قول شكراً أو أحبك أو good bot أو إرسال قلب. منفصلة عن تفاعلات الرسائل أعلاه.',
- embedsTitle: 'التضمينات المضمّنة',
- embedsDesc:
- 'تُحمّل المعاينات الغنية من مواقع طرف ثالث (YouTube، X، …). "اسأل" يعرض عنصرا نائبا حتى تسمح لكل واحد؛ "دائما" يحمّلها تلقائيا؛ "إيقاف" يبقي الروابط عادية.',
- embedsAsk: 'اسأل',
- embedsAlways: 'دائما',
- embedsOff: 'إيقاف',
- embedsReset: count => `إعادة تعيين ${count} ${count === 1 ? 'خدمة مسموح بها' : 'خدمة مسموح بها'}`,
- resumeLastSessionTitle: 'إعادة فتح آخر محادثة عند التشغيل',
- resumeLastSessionDesc: 'متابعة من حيث توقفت عند بدء التطبيق. أوقفه للبدء دائمًا بمحادثة جديدة.',
- product: 'مبسط',
- productDesc: 'عرض أنظف يركز على النتيجة.',
- technical: 'تقني',
- technicalDesc: 'يعرض تفاصيل أكثر عن الأدوات والتنفيذ.',
- themeTitle: 'الثيم',
- themeDesc: 'اختر ثيم سطح المكتب.',
- themeProfileNote: profile => `سيطبق هذا الثيم على الملف الشخصي ${profile}.`,
- installTitle: 'تثبيت ثيم',
- installDesc: 'ألصق رابط ثيم أو اسمه لتثبيته.',
- installPlaceholder: 'رابط أو اسم الثيم',
- installButton: 'تثبيت',
- installing: 'جار التثبيت...',
- installError: 'فشل تثبيت الثيم',
- installed: name => `تم تثبيت ${name}`,
- removeTheme: 'إزالة الثيم',
- importedBadge: 'مستورد',
- pet: {
- title: 'حيوان أليف',
- intro:
- 'تبنَّ تعويذة petdex متحركة تطفو فوق التطبيق وتتفاعل مع ما يفعله Hermes — تجري أثناء تنفيذ الأدوات، وتحتفل عند النجاح، وتعبس عند الأخطاء.',
- restartHint:
- 'تحتاج الحيوانات الأليفة إلى إعادة تشغيل سريعة — بدأ التطبيق العامل قبل إضافة هذه الميزة. أغلق Hermes وأعد فتحه، ثم ارجع إلى هنا.',
- scaleTitle: 'الحجم',
- scaleDesc: 'غيّر حجم التعويذة الطافية. يُطبّق في كل مكان فورا.',
- chooseTitle: 'اختر حيوانا أليفا',
- chooseDesc: 'اختياره يثبّته (إن لزم) ويجعله نشطا.',
- searchPlaceholder: 'البحث عن حيوانات أليفة...',
- unreachable: 'تعذّر الوصول إلى معرض petdex. تحقق من اتصالك وأعد فتح هذه الصفحة.',
- noMatch: query => `لا توجد حيوانات أليفة تطابق "${query}".`,
- installedTag: 'مثبّت',
- generatedTag: 'مُولّد',
- countCapped: (cap, total) => `عرض ${cap} من ${total} — اكتب لتضييق النتائج.`,
- count: n => `${n} ${n === 1 ? 'حيوان أليف' : 'حيوان أليف'}.`,
- uninstall: name => `إلغاء تثبيت ${name}`,
- delete: name => `حذف ${name}`,
- deleteTitle: name => `حذف ${name}؟`,
- deleteBody: 'هذا يحذف الحيوان الأليف نهائيا — لا يمكن إعادة تثبيته.',
- deleteConfirm: 'حذف',
- rename: name => `إعادة تسمية ${name}`,
- renameTitle: 'إعادة تسمية الحيوان الأليف',
- renamePlaceholder: 'سمِّ حيوانك الأليف',
- renameSave: 'حفظ',
- exportPet: name => `تصدير ${name}`,
- adoptFailed: slug => `تعذّر تبني ${slug}`,
- uninstallFailed: slug => `تعذّر إلغاء تثبيت ${slug}`,
- renameFailed: slug => `تعذّرت إعادة تسمية ${slug}`,
- exportFailed: slug => `تعذّر تصدير ${slug}`,
- noneAvailable: 'لا توجد حيوانات أليفة متاحة للتشغيل الآن.',
- turnOnFailed: 'تعذّر تشغيل الحيوان الأليف.',
- turnOffFailed: 'تعذّر إيقاف الحيوان الأليف.'
- }
- },
- fieldLabels: {
- model: 'النموذج الافتراضي',
- modelContextLength:
- 'يتجاوز نافذة السياق المكتشفة لنموذج المحادثة الرئيسي فقط (بالرموز). اتركه 0 لاستخدام القيمة المكتشفة للنموذج المحدد. لا يؤثر على النماذج المساعدة أو نماذج MoA.',
- fallbackProviders: 'النماذج الاحتياطية',
- toolsets: 'مجموعات الأدوات المفعلة',
- timezone: 'المنطقة الزمنية',
- 'display.personality': 'أسلوب المساعد',
- 'display.showReasoning': 'إظهار التفكير',
- 'agent.maxTurns': 'الحد الأقصى لخطوات الوكيل',
- 'agent.imageInputMode': 'مرفقات الصور',
- 'agent.apiMaxRetries': 'محاولات API',
- 'agent.serviceTier': 'مستوى الخدمة',
- 'agent.toolUseEnforcement': 'فرض استخدام الأدوات',
- 'terminal.cwd': 'مجلد العمل',
- 'terminal.backend': 'خلفية التنفيذ',
- 'terminal.timeout': 'مهلة الأوامر',
- 'terminal.persistentShell': 'صدفة مستمرة',
- 'terminal.envPassthrough': 'تمرير متغيرات البيئة',
- 'terminal.dockerImage': 'صورة Docker',
- 'terminal.singularityImage': 'صورة Singularity',
- 'terminal.modalImage': 'صورة Modal',
- 'terminal.daytonaImage': 'صورة Daytona',
- fileReadMaxChars: 'حد قراءة الملفات',
- 'toolOutput.maxBytes': 'حد مخرجات الطرفية',
- 'toolOutput.maxLines': 'حد صفحات الملفات',
- 'toolOutput.maxLineLength': 'حد طول السطر',
- 'codeExecution.mode': 'نمط تنفيذ الكود',
- 'approvals.mode': 'نمط الموافقات',
- 'approvals.timeout': 'مهلة الموافقة',
- 'approvals.mcpReloadConfirm': 'تأكيد إعادة تحميل MCP',
- commandAllowlist: 'قائمة الأوامر المسموحة',
- 'security.redactSecrets': 'إخفاء الأسرار',
- 'security.allowPrivateUrls': 'السماح بالروابط الخاصة',
- 'browser.allowPrivateUrls': 'روابط المتصفح الخاصة',
- 'browser.autoLocalForPrivateUrls': 'متصفح محلي للروابط الخاصة',
- 'checkpoints.enabled': 'نقاط حفظ الملفات',
- 'checkpoints.maxSnapshots': 'حد نقاط الحفظ',
- 'voice.maxRecordingSeconds': 'أقصى مدة للتسجيل',
- 'voice.autoTts': 'قراءة الردود صوتياً',
- 'stt.enabled': 'تحويل الكلام إلى نص',
- 'stt.provider': 'مزود تحويل الكلام إلى نص',
- 'stt.local.model': 'نموذج التفريغ المحلي',
- 'stt.local.language': 'لغة التفريغ',
- 'stt.openai.model': 'نموذج OpenAI STT',
- 'stt.groq.model': 'نموذج Groq STT',
- 'stt.mistral.model': 'نموذج Mistral STT',
- 'stt.elevenlabs.modelId': 'نموذج ElevenLabs STT',
- 'stt.elevenlabs.languageCode': 'لغة ElevenLabs',
- 'stt.elevenlabs.tagAudioEvents': 'وسم أحداث الصوت',
- 'stt.elevenlabs.diarize': 'تمييز المتحدثين',
- 'tts.provider': 'مزود تحويل النص إلى كلام',
- 'tts.edge.voice': 'صوت Edge',
- 'tts.openai.model': 'نموذج OpenAI TTS',
- 'tts.openai.voice': 'صوت OpenAI',
- 'tts.elevenlabs.voiceId': 'صوت ElevenLabs',
- 'tts.elevenlabs.modelId': 'نموذج ElevenLabs',
- 'tts.xai.voiceId': 'صوت xAI (Grok)',
- 'tts.xai.language': 'لغة xAI',
- 'tts.minimax.model': 'نموذج MiniMax TTS',
- 'tts.minimax.voiceId': 'صوت MiniMax',
- 'tts.mistral.model': 'نموذج Mistral TTS',
- 'tts.mistral.voiceId': 'صوت Mistral',
- 'tts.gemini.model': 'نموذج Gemini TTS',
- 'tts.gemini.voice': 'صوت Gemini',
- 'tts.neutts.model': 'نموذج NeuTTS',
- 'tts.neutts.device': 'جهاز NeuTTS',
- 'tts.kittentts.model': 'نموذج KittenTTS',
- 'tts.kittentts.voice': 'صوت KittenTTS',
- 'tts.piper.voice': 'صوت Piper',
- 'memory.memoryEnabled': 'الذاكرة المستمرة',
- 'memory.userProfileEnabled': 'ملف المستخدم',
- 'memory.memoryCharLimit': 'ميزانية الذاكرة',
- 'memory.userCharLimit': 'ميزانية الملف الشخصي',
- 'memory.provider': 'مزود الذاكرة',
- 'context.engine': 'محرك السياق',
- 'compression.enabled': 'الضغط التلقائي',
- 'compression.threshold': 'عتبة الضغط',
- 'compression.codexGpt55Autoraise': 'الرفع التلقائي لضغط Codex',
- 'compression.targetRatio': 'هدف الضغط',
- 'compression.protectLastN': 'الرسائل الأخيرة المحمية',
- 'auxiliary.compression.timeout': 'مهلة نموذج الضغط (ثانية)',
- 'delegation.model': 'نموذج الوكيل الفرعي',
- 'delegation.provider': 'مزود الوكيل الفرعي',
- 'delegation.maxIterations': 'حد دورات الوكيل الفرعي',
- 'delegation.maxConcurrentChildren': 'الوكلاء الفرعيون المتوازيون',
- 'delegation.childTimeoutSeconds': 'مهلة الوكيل الفرعي',
- 'delegation.reasoningEffort': 'جهد تفكير الوكيل الفرعي',
- 'updates.nonInteractiveLocalChanges': 'تغييرات التحديث داخل التطبيق'
- },
- fieldDescriptions: {
- model: 'يستخدم في المحادثات الجديدة ما لم تختر نموذجاً مختلفاً من محرر الرسائل.',
- modelContextLength: 'اتركه 0 لاستخدام نافذة السياق المكتشفة للنموذج المحدد.',
- fallbackProviders: 'إدخالات احتياطية بصيغة provider:model لتجربتها إذا فشل النموذج الافتراضي.',
- 'display.personality': 'أسلوب المساعد الافتراضي للجلسات الجديدة.',
- 'display.showReasoning': 'يعرض أقسام التفكير عندما توفرها الخلفية.',
- timezone: 'تستخدم عندما يحتاج Hermes إلى سياق الوقت المحلي. اتركها فارغة لاستخدام منطقة النظام.',
- 'agent.imageInputMode': 'يتحكم في طريقة إرسال مرفقات الصور إلى النموذج.',
- 'agent.maxTurns': 'الحد الأعلى لدورات استدعاء الأدوات قبل أن يوقف Hermes التشغيل.',
- 'terminal.cwd': 'مجلد المشروع الافتراضي لعمل الأدوات والطرفية.',
- 'terminal.persistentShell': 'يحافظ على حالة الصدفة بين الأوامر عندما تدعمها الخلفية.',
- 'terminal.envPassthrough': 'متغيرات البيئة التي تمرر إلى تنفيذ الأدوات.',
- 'terminal.dockerImage': 'صورة الحاوية المستخدمة عند اختيار Docker كخلفية تنفيذ.',
- 'terminal.singularityImage': 'الصورة المستخدمة عند اختيار Singularity.',
- 'terminal.modalImage': 'الصورة المستخدمة عند اختيار Modal.',
- 'terminal.daytonaImage': 'الصورة المستخدمة عند اختيار Daytona.',
- 'codeExecution.mode': 'مدى تقييد تنفيذ الكود بالمشروع الحالي.',
- fileReadMaxChars: 'أقصى عدد أحرف يستطيع Hermes قراءته من ملف واحد في الطلب.',
- 'approvals.mode': 'كيف يتعامل Hermes مع الأوامر التي تحتاج موافقة صريحة.',
- 'approvals.timeout': 'مدة انتظار طلبات الموافقة قبل انتهاء المهلة.',
- 'security.redactSecrets': 'يخفي الأسرار المكتشفة من المحتوى المرئي للنموذج قدر الإمكان.',
- 'checkpoints.enabled': 'ينشئ لقطات رجوع قبل تعديلات الملفات.',
- 'memory.memoryEnabled': 'يحفظ ذكريات دائمة يمكن أن تساعد الجلسات القادمة.',
- 'memory.userProfileEnabled': 'يحافظ على ملف مختصر لتفضيلات المستخدم.',
- 'context.engine': 'استراتيجية إدارة المحادثات الطويلة قرب حد السياق.',
- 'compression.enabled': 'يلخص السياق الأقدم عندما تكبر المحادثات.',
- 'compression.codexGpt55Autoraise': 'يرفع عتبة الضغط إلى 85٪ لنماذج ChatGPT Codex OAuth المدعومة.',
- 'auxiliary.compression.timeout':
- 'عدد الثواني لانتظار نموذج الضغط المساعد في كل استدعاء (الافتراضي 120). ارفعه للنماذج المحلية البطيئة.',
- 'voice.autoTts': 'ينطق ردود المساعد تلقائياً.',
- 'tts.xai.voiceId': 'معرف صوت xAI مثل eve أو معرف صوت مخصص.',
- 'tts.xai.language': 'رمز لغة النطق، مثل en.',
- 'tts.neutts.device': 'جهاز الاستدلال المحلي لـ NeuTTS.',
- 'stt.enabled': 'يفعل التفريغ الصوتي المحلي أو عبر مزود.',
- 'stt.elevenlabs.languageCode': 'رمز لغة ISO-639-3 اختياري. اتركه فارغاً للاكتشاف التلقائي.',
- 'updates.nonInteractiveLocalChanges':
- 'عندما يحدّث Hermes نفسه من التطبيق دون موجه طرفية، احتفظ بتعديلات المصدر المحلية أو تجاهلها.'
- },
- about: {
- updates: 'التحديثات'
- },
-
- config: {
- minimizeToTrayTitle: 'التصغير إلى علبة النظام',
- minimizeToTrayDesc:
- 'تصغير النوافذ أو إغلاق النافذة الرئيسية يخفيها في علبة النظام (شريط القوائم على macOS) مع استمرار Hermes في العمل. استخدم إنهاء Hermes من قائمة العلبة أو Cmd+Q للخروج. معطّل افتراضيًا ويُطبّق على هذا الجهاز فقط.',
- minimizeToTrayUnavailable:
- 'علبة النظام غير متاحة. ستُصغّر النوافذ وتُغلق كالمعتاد. أوقف هذا الخيار ثم فعّله لإعادة المحاولة.',
- none: 'لا شيء',
- noneParen: '(لا شيء)',
- notSet: 'غير مضبوط',
- commaSeparated: 'قيم مفصولة بفواصل',
- searchPlaceholder: 'بحث…',
- noResults: 'لا توجد نتائج',
- systemDefault: 'إعداد النظام الافتراضي',
- loading: 'جار تحميل إعدادات Hermes...',
- emptyTitle: 'لا توجد إعدادات',
- emptyDesc: 'لا يحتوي هذا القسم على إعدادات قابلة للتعديل.',
- failedLoad: 'فشل تحميل الإعدادات',
- autosaveFailed: 'فشل الحفظ التلقائي',
- imported: 'تم استيراد الإعدادات',
- invalidJson: 'JSON غير صالح',
- voiceShortcutHintTitle: 'اختصار تسجيل الصوت',
- voiceShortcutHintDesc:
- 'اضبط اختصار تسجيل الصوت من الإعدادات ← اختصارات لوحة المفاتيح («بدء / إيقاف المحادثة الصوتية»). قيمة voice.record_key مخصصة لـ CLI وTUI فقط.'
- },
- hudModifier: {
- title: 'استدعاء HUD بضغطة',
- description:
- 'اضغط ثم حرّر ⌘ + Option على Mac، أو Ctrl + Alt على Windows/Linux، لإظهار HUD من أي تطبيق. معطّل افتراضيًا ويُطبّق على هذا الجهاز فقط.',
- permission:
- 'اسمح لـ Hermes في إعدادات النظام ← الخصوصية والأمان ← مراقبة الإدخال، ثم أعد المحاولة. لا تسجّل هذه الإيماءة ضغطات المفاتيح ولا تلتقط الشاشة.',
- unavailable:
- 'تعذّر تشغيل مساعد إيماءة HUD أو توقف بشكل غير متوقع. أعد المحاولة أو أعد تشغيل Hermes. يظل اختصار HUD الحالي يعمل داخل Hermes.',
- missingHelper: 'مساعد إيماءة HUD غير موجود في تثبيت Hermes هذا. حدّث Hermes أو أعد تثبيته، ثم أعد المحاولة.',
- unsupportedSession:
- 'جلسة سطح المكتب هذه لا تدعم ضغطات مفاتيح التعديل على مستوى النظام. يتطلب Linux جلسة X11؛ Wayland غير مدعوم.'
- },
- screenshot: {
- enabledTitle: 'اختصار لقطة الشاشة',
- enabledDesc:
- 'اضغط مفتاحَي Command معًا من أي تطبيق لالتقاط النافذة الأمامية وإرفاقها بمسودة Hermes الحالية. لا يُرسل أي شيء تلقائيًا. معطّل افتراضيًا ويُطبَّق على جهاز Mac هذا فقط. قد تتضمن النافذة محتوى حساسًا، لذا راجع المرفق قبل الإرسال.',
- statusTitle: 'حالة اختصار لقطة الشاشة',
- checking: 'جارٍ التحقق من اختصار لقطة الشاشة…',
- disabled: 'اختصار لقطة الشاشة معطّل.',
- starting: 'جارٍ بدء رصد الاختصار. لم يصبح جاهزًا بعد.',
- ready: 'الاختصار جاهز. تُرفق اللقطات بالمسودة الحالية دون إرسالها.',
- inputPermission:
- 'يتيح إذن مراقبة الإدخال لـ Hermes رصد مفتاحَي Command أثناء استخدام تطبيق آخر. اسمح لـ Hermes في إعدادات النظام ← الخصوصية والأمان ← مراقبة الإدخال، ثم عُد إلى هنا وأعد المحاولة.',
- screenPermission:
- 'يتيح إذن تسجيل الشاشة لـ Hermes التقاط نافذة التطبيق الأمامية عند استخدام هذا الاختصار. اسمح لـ Hermes في إعدادات النظام ← الخصوصية والأمان ← تسجيل الشاشة، ثم عُد إلى هنا وأعد المحاولة. أعد تشغيل Hermes إذا طلب macOS ذلك.',
- openSettings: 'فتح إعدادات النظام',
- retry: 'إعادة المحاولة',
- unavailable: 'اختصار لقطة الشاشة غير متاح. أعد المحاولة أو عطّله.',
- errorTitle: 'خطأ في اختصار لقطة الشاشة',
- loadFailed: 'تعذّرت قراءة حالة الاختصار. أعد المحاولة للتحقق من إعداده الحالي.',
- saveFailed: 'تعذّر تأكيد تغيير الاختصار. أعد المحاولة للتحقق من إعداده الحالي.',
- permissionFailed: 'تعذّر فتح إعدادات النظام. افتح الخصوصية والأمان يدويًا، ثم أعد المحاولة.',
- captureFailed: 'تعذّر التقاط النافذة الأمامية. لم يُرفق أو يُرسل أي شيء.',
- contextChanged: 'تغيّرت المسودة الحالية أثناء الالتقاط. لم تُرفق اللقطة أو تُرسل.'
- },
- quickEntry: {
- enabledTitle: 'الإدخال السريع',
- enabledDesc: 'استدعِ محرّرا صغيرا من أي مكان باختصار عام وأرسل طلبا دون فتح Hermes.',
- shortcutTitle: 'اختصار الإدخال السريع',
- shortcutDesc: 'يحتاج إلى مفتاح تعديل واحد على الأقل، مثل CommandOrControl+Shift+Space.',
- active: 'الاختصار مفعّل.',
- takenBy: 'يستخدم تطبيق آخر هذا الاختصار — اختر اختصارا مختلفا.',
- invalidShortcut: 'ليس اختصارا صالحا. أضف مفتاح تعديل واحدا على الأقل.'
- },
- credentials: {
- pasteKey: 'لصق المفتاح',
- pasteLabelKey: label => `لصق مفتاح ${label}`,
- optional: 'اختياري',
- enterValueFirst: 'أدخل قيمة أولا.',
- couldNotSave: 'تعذّر حفظ بيانات الاعتماد.',
- remove: 'إزالة',
- getKey: 'احصل على مفتاح',
- saving: 'جار الحفظ'
- },
- envActions: {
- actions: 'إجراءات',
- docs: 'الوثائق',
- hideValue: 'إخفاء القيمة',
- revealValue: 'إظهار القيمة',
- replace: 'استبدال',
- set: 'ضبط',
- clear: 'مسح'
- },
- gateway: {
- loading: 'جار تحميل إعدادات البوابة...',
- unavailableTitle: 'إعدادات البوابة غير متاحة',
- unavailableDesc: 'جسر IPC في سطح المكتب لا يوفّر إعدادات البوابة.',
- title: 'اتصال البوابة',
- envOverride: 'تجاوز من البيئة',
- intro:
- 'يشغّل Hermes Desktop بوابة محلية خاصة افتراضياً. استخدم بوابة بعيدة عندما تريد أن يتحكم هذا التطبيق بخلفية Hermes تعمل مسبقاً على جهاز آخر أو خلف وكيل موثوق. اتصالات البوابة إعداد على مستوى الجهاز؛ ويتم اكتشاف الملفات الشخصية من البوابات المتصلة.',
- envOverrideTitle: 'متغيرات البيئة تتحكم في جلسة سطح المكتب هذه.',
- envOverrideDesc: 'أزل HERMES_DESKTOP_REMOTE_URL و HERMES_DESKTOP_REMOTE_TOKEN لاستخدام الإعداد المحفوظ أدناه.',
- localTitle: 'بوابة محلية',
- localDesc: 'تشغيل خلفية Hermes خاصة على localhost. هذا هو الافتراضي ويعمل دون اتصال.',
- remoteTitle: 'بوابة بعيدة',
- remoteDesc:
- 'صل واجهة سطح المكتب هذه بخلفية Hermes بعيدة. البوابات المستضافة تستخدم OAuth أو اسم مستخدم وكلمة مرور، والبوابات الذاتية قد تستخدم رمز جلسة.',
- remoteUrlTitle: 'رابط البوابة البعيدة',
- remoteUrlDesc: 'الرابط الأساسي لخلفية لوحة التحكم البعيدة. يمكن استخدام بادئات مسار مثل /hermes.',
- probing: 'جار فحص طريقة مصادقة هذه البوابة...',
- probeError: 'تعذر الوصول إلى هذه البوابة الآن. تحقق من الرابط وستظهر طريقة المصادقة عند الاستجابة.',
- signedIn: 'تم تسجيل الدخول',
- signIn: 'تسجيل الدخول',
- signOut: 'تسجيل الخروج',
- signInWith: provider => `تسجيل الدخول عبر ${provider}`,
- authTitle: 'المصادقة',
- authSignedInPassword: 'هذه البوابة تستخدم اسم مستخدم وكلمة مرور. أنت مسجل الدخول والجلسة تتجدد تلقائياً.',
- authSignedInOauth: 'هذه البوابة تستخدم OAuth. أنت مسجل الدخول والجلسة تتجدد تلقائياً.',
- authNeedsPassword: 'هذه البوابة تستخدم اسم مستخدم وكلمة مرور. سجل الدخول لتفويض تطبيق سطح المكتب.',
- authNeedsOauth: provider => `هذه البوابة تستخدم OAuth. سجل الدخول عبر ${provider} لتفويض تطبيق سطح المكتب.`,
- tokenTitle: 'رمز الجلسة',
- tokenDesc: 'رمز جلسة لوحة التحكم المستخدم لطلبات REST و WebSocket. اتركه فارغاً للإبقاء على الرمز المحفوظ.',
- existingToken: value => `رمز موجود ${value}`,
- savedToken: 'محفوظ',
- pasteSessionToken: 'ألصق رمز الجلسة',
- keychainEncryptionTitle: 'تشفير الأسرار المحفوظة باستخدام سلسلة مفاتيح النظام',
- keychainEncryptionDesc:
- 'معطّل افتراضياً. عند التفعيل، تُشفَّر رموز البوابة وبيانات تسجيل الدخول باستخدام سلسلة مفاتيح النظام (Keychain Access أو GNOME Keyring أو Windows DPAPI) — وقد يطلب النظام إذناً أو كلمة مرور. عند التعطيل، تُخزَّن كملفات عادية لا يقرؤها سوى حساب المستخدم الحالي.',
- keychainEncryptionFailed: 'تعذّر تغيير إعداد تشفير الأسرار',
- testRemote: 'اختبار البعيد',
- saveForRestart: 'حفظ للتشغيل القادم',
- saveAndReconnect: 'حفظ وإعادة الاتصال',
- diagnostics: 'التشخيصات',
- diagnosticsDesc: 'اعرض desktop.log في مدير الملفات، وهذا مفيد عند فشل تشغيل البوابة.',
- openLogs: 'فتح السجلات',
- incompleteTitle: 'إعداد البوابة البعيدة غير مكتمل',
- incompleteSignIn: 'أدخل رابط البوابة البعيدة وسجل الدخول قبل التبديل إلى البعيد.',
- incompleteToken: 'أدخل رابط البوابة البعيدة ورمز الجلسة قبل التبديل إلى البعيد.',
- incompleteSignInTest: 'أدخل رابط البوابة البعيدة وسجل الدخول قبل الاختبار.',
- incompleteTokenTest: 'أدخل رابط البوابة البعيدة ورمز الجلسة قبل الاختبار.',
- enterUrlFirst: 'أدخل رابط البوابة البعيدة أولاً.',
- restartingTitle: 'جار إعادة تشغيل اتصال البوابة',
- savedTitle: 'تم حفظ إعدادات البوابة',
- restartingMessage: 'سيعيد Hermes Desktop الاتصال باستخدام الإعدادات المحفوظة.',
- savedMessage: 'تم الحفظ للتشغيل القادم.',
- connectedTo: (baseUrl, version) => `متصل بـ ${baseUrl}${version ? ` · Hermes ${version}` : ''}`,
- reachableTitle: 'البوابة البعيدة قابلة للوصول',
- signedOutTitle: 'تم تسجيل الخروج',
- signedOutMessage: 'تم مسح جلسة البوابة البعيدة.',
- failedLoad: 'فشل تحميل إعدادات البوابة',
- signInFailed: 'فشل تسجيل الدخول',
- signOutFailed: 'فشل تسجيل الخروج',
- testFailed: 'فشل اختبار البوابة البعيدة',
- applyFailed: 'تعذر تطبيق إعدادات البوابة',
- saveFailed: 'تعذر حفظ إعدادات البوابة'
- },
- keys: {
- loading: 'جار تحميل مفاتيح API وبيانات الاعتماد...',
- failedLoad: 'فشل تحميل مفاتيح API',
- empty: 'لا يوجد شيء مضبوط في هذه الفئة بعد.'
- },
- profileScope: {
- appliesTo: 'ينطبق على',
- editsProfile: profile => `تنطبق التغييرات في هذه الصفحة على الملف الشخصي «${profile}».`
- },
- mcp: {
- loading: 'جار تحميل خوادم MCP...',
- invalidJson: 'JSON الخاص بـ MCP غير صالح',
- saveFailed: 'فشل الحفظ',
- removeFailed: 'فشلت الإزالة',
- reloadFailed: 'فشلت إعادة تحميل MCP',
- savedTitle: 'تم حفظ خادم MCP',
- savedMessage: name => `سيطبق ${name} بعد إعادة تحميل MCP.`,
- disabled: 'معطل',
- name: 'الاسم',
- serverJson: 'JSON الخادم',
- remove: 'إزالة',
- deepLinkTitle: 'إضافة خادم MCP؟',
- deepLinkDescription:
- 'طلب رابط إضافة خادم MCP هذا إلى Hermes. راجع الإعدادات الكاملة أدناه — فهي قادمة من الرابط وليست من Hermes.',
- deepLinkStdioWarning:
- 'سيشغّل هذا الخادم عملية محلية على جهازك بالأمر الموضح أدناه. لا تتابع إلا إذا كنت تثق بمصدره.',
- deepLinkConfirm: 'إضافة الخادم',
- deepLinkNameInvalid: 'الأسماء من 1-64 حرفا أو رقما أو نقطة أو شرطة أو شرطة سفلية.',
- deepLinkNameConflict: name => `يوجد خادم باسم ${name} بالفعل — اختر اسما مختلفا أو ألغِ العملية.`,
- deepLinkErrorTitle: 'رُفض رابط تثبيت MCP',
- deepLinkErrorName: 'اسم الخادم في الرابط مفقود أو غير صالح.',
- deepLinkErrorConfig: 'إعدادات الرابط ليست JSON صالحا مرمّزا بـ base64.',
- deepLinkErrorShape: 'يجب أن تكون الإعدادات كائن JSON يحتوي على حقل `url` أو `command` نصي.',
- deepLinkErrorUrl: 'يسمح فقط بعناوين http:// و https:// للخادم.',
- deepLinkErrorTooLarge: 'حجم الإعدادات يتجاوز الحد الأقصى 32KB.'
- },
- model: {
- moaTitle: 'مزيج الوكلاء (Mixture of Agents)',
- moaPreset: 'إعداد مسبق',
- moaDescription:
- 'اضبط إعدادات مسبقة مسماة تظهر كنماذج ضمن موفّر Mixture of Agents. نموذج التجميع هو المنفّذ؛ ينفّذ كل خطوة في حلقة الأدوات وتُحتسب غالبية تكلفة التشغيل على موفّره. تقدّم النماذج المرجعية المشورة مرة واحدة لكل رسالة مستخدم افتراضياً.',
- moaAggregator: 'نموذج التجميع',
- moaAggregatorBilled: 'النموذج المنفّذ · تُحتسب عليه تكلفة التشغيل',
- moaReferenceHint: 'يقدّم المشورة مرة واحدة لكل رسالة افتراضياً',
- setupProviderFallback: 'الموفّر',
- setUpProvider: name => `إعداد ${name}`,
- staleAuxBefore: (count, names) => `المهام المساعدة (${count}: ${names}) ما زالت تعمل لدى `,
- staleAuxAfter: '، وليس على النموذج الرئيسي.',
- staleAuxOtherProviders: 'موفّرين آخرين',
- moaEnabled: 'مُفعّل',
- moaSetDefault: 'تعيين الافتراضي',
- moaNewPresetPlaceholder: 'إعداد جديد',
- moaAddPreset: 'إضافة إعداد',
- customModel: 'نموذج مخصص…',
- customModelPlaceholder: 'معرّف النموذج',
- chooseFromList: 'اختر من القائمة',
- moaDefault: 'الافتراضي:',
- moaReferenceToggle: (enabled, index) => `${enabled ? 'تعطيل' : 'تفعيل'} المرجع ${index}`,
- moaReferenceTitle: index => `المرجع ${index}`,
- moaAddReference: 'إضافة نموذج مرجعي',
- loading: 'جار تحميل إعدادات النموذج...',
- appliesDesc: 'ينطبق على الجلسات الجديدة. استخدم منتقي النموذج في صندوق الإنشاء لتبديل المحادثة النشطة فورا.',
- provider: 'المزوّد',
- model: 'النموذج',
- applying: 'جار التطبيق...',
- defaultsLabel: 'الافتراضيات',
- reasoning: 'الاستدلال',
- reasoningOff: 'إيقاف',
- defaultsFailed: 'فشل حفظ افتراضيات النموذج',
- loadFailed: 'تعذر تحميل النماذج',
- restartRequired: 'بعد التحديث ما زال هذا الخلفية يشغّل كودا قديما. أعد تشغيله لتحميل الكود الجديد.',
- restartBackend: 'إعادة تشغيل الخلفية',
- restartingBackend: 'جار إعادة تشغيل الخلفية...',
- restartFailed: 'تعذر إعادة تشغيل الخلفية',
- auxiliaryTitle: 'النماذج المساعدة',
- resetAllToMain: 'إعادة تعيين الكل إلى النموذج الرئيسي',
- auxiliaryDesc: 'تعمل المهام المساعدة على النموذج الرئيسي افتراضيا. عيّن نموذجا مخصصا لأي مهمة لتجاوز ذلك.',
- setToMain: 'ضبط على الرئيسي',
- change: 'تغيير',
- autoUseMain: 'تلقائي · استخدام النموذج الرئيسي',
- inheritMainEffort: 'وراثة · جهد النموذج الرئيسي',
- providerDefault: '(افتراضي المزوّد)',
- tasks: {
- vision: {
- label: 'الرؤية',
- hint: 'تحليل الصور'
- },
- compression: {
- label: 'الضغط',
- hint: 'ضغط السياق'
- },
- skills_hub: {
- label: 'مركز المهارات',
- hint: 'بحث المهارات'
- },
- approval: {
- label: 'الموافقة',
- hint: 'موافقة تلقائية ذكية'
- },
- mcp: {
- label: 'MCP',
- hint: 'توجيه أدوات MCP'
- },
- title_generation: {
- label: 'توليد العناوين',
- hint: 'عناوين الجلسات'
- },
- review: {
- label: 'المراجعة',
- hint: 'وكيل المراجعة الفرعي /review'
- },
- triage_specifier: {
- label: 'محدد الفرز',
- hint: 'توضيح مواصفات كانبان'
- },
- kanban_decomposer: {
- label: 'مفكك كانبان',
- hint: 'تفكيك المهام'
- },
- profile_describer: {
- label: 'واصف الملف الشخصي',
- hint: 'أوصاف ملفات شخصية تلقائية'
- },
- curator: {
- label: 'المنسّق',
- hint: 'مراجعة استخدام المهارات'
- }
- }
- },
- providers: {
- connectAccount: 'ربط حساب',
- haveApiKey: 'لديك مفتاح API بدلاً من ذلك؟',
- intro: 'سجل الدخول باشتراكك دون نسخ مفتاح API. يشغّل Hermes تسجيل الدخول من المتصفح لك داخل التطبيق.',
- connected: 'متصل',
- collapse: 'طي',
- connectAnother: 'ربط مزود آخر',
- otherProviders: 'مزودون آخرون',
- disconnect: 'قطع الاتصال',
- disconnectInTerminal: 'قطع الاتصال (يشغّل أمر الإزالة في الطرفية)',
- removeConfirm: provider => `إزالة ${provider}؟`,
- removeExternalGeneric: provider => `${provider} يُدار عبر CLI خاص به — أزله من هناك.`,
- removeKeyManaged: provider => `${provider} مُعدّ من مفتاح API. أزله من مفاتيح API.`,
- removeTerminalConfirm: (provider, command) =>
- `قطع اتصال ${provider}؟ هذا يشغّل "${command}" في الطرفية لمسح بيانات الاعتماد.`,
- removeTerminalRunning: provider => `جار تشغيل قطع اتصال ${provider} في الطرفية…`,
- removedTitle: 'تمت إزالة الحساب',
- removedMessage: provider => `تمت إزالة ${provider}.`,
- failedRemove: provider => `تعذّرت إزالة ${provider}`,
- noProviderKeys: 'لا توجد مفاتيح API متاحة للمزودين.',
- searchKeys: 'البحث عن مزوّدين...',
- noKeysMatch: 'لا يوجد مزوّدون يطابقون بحثك.',
- localEndpoint: {
- title: 'نقطة نهاية محلية',
- description: 'استخدم خادما محليا أو نقطة نهاية متوافقة مع OpenAI لهذا المزود.'
- },
- loading: 'جار تحميل المزودين...'
- },
- sessions: {
- loading: 'جار تحميل الجلسات المؤرشفة...',
- archivedTitle: 'الجلسات المؤرشفة',
- archivedIntro:
- 'تُخفى المحادثات المؤرشفة من الشريط الجانبي مع الاحتفاظ بكل رسائلها. اضغط Alt/⌥+Shift مع النقر على محادثة في الشريط الجانبي لأرشفتها.',
- emptyArchivedTitle: 'لا توجد محادثات مؤرشفة',
- emptyArchivedDesc: 'أرشف محادثة لإخفائها هنا.',
- unarchive: 'إلغاء الأرشفة',
- deletePermanently: 'حذف نهائي',
- messages: count => `${count} ${count === 1 ? 'رسالة' : 'رسائل'}`,
- restored: 'تمت الاستعادة',
- deleteConfirm: title => `حذف "${title}" نهائياً؟ لا يمكن التراجع عن هذا.`,
- defaultDirTitle: 'مجلد المشروع الافتراضي',
- defaultDirDesc: 'تبدأ الجلسات الجديدة في هذا المجلد ما لم تختر غيره. اتركه غير مضبوط لاستخدام مجلدك الرئيسي.',
- defaultDirUpdated: 'تم تحديث مجلد المشروع الافتراضي، ابدأ محادثة جديدة (Ctrl/⌘+N) ليطبق التغيير',
- defaultsTo: label => `الافتراضي هو ${label}.`,
- change: 'تغيير',
- choose: 'اختيار',
- clear: 'مسح',
- notSet: 'غير مضبوط',
- failedLoad: 'تعذر تحميل الجلسات المؤرشفة',
- unarchiveFailed: 'فشل إلغاء الأرشفة',
- deleteFailed: 'فشل الحذف',
- updateDirFailed: 'تعذر تحديث المجلد الافتراضي',
- clearDirFailed: 'تعذر مسح المجلد الافتراضي'
- },
- toolsets: {
- loadingConfig: 'جار تحميل الإعدادات',
- savedTitle: 'تم حفظ بيانات الاعتماد',
- savedMessage: key => `تم تحديث ${key}.`,
- removedTitle: 'تمت إزالة بيانات الاعتماد',
- removedMessage: key => `تمت إزالة ${key}.`,
- failedSave: key => `فشل حفظ ${key}`,
- failedRemove: key => `فشل إزالة ${key}`,
- failedReveal: key => `فشل إظهار ${key}`,
- removeConfirm: key => `إزالة ${key} من .env؟`,
- set: 'ضبط',
- notSet: 'غير مضبوط',
- selectedTitle: 'تم اختيار المزوّد',
- selectedMessage: provider => `${provider} نشط الآن.`,
- failedSelect: provider => `فشل اختيار ${provider}`,
- failedLoad: 'فشل تحميل إعدادات الأدوات',
- noProviderOptions: 'لا تحتوي مجموعة الأدوات هذه على خيارات مزوّد — فعّلها لتعمل مع إعدادك الحالي.',
- noProviders: 'لا يوجد مزوّدون متاحون لمجموعة الأدوات هذه الآن.',
- ready: 'جاهز',
- nousIncluded: 'مُضمّن مع اشتراك Nous — سجّل الدخول إلى Nous Portal للتفعيل.',
- noApiKeyRequired: 'لا يلزم مفتاح API.',
- postSetupHint: step =>
- `تحتاج هذه الخلفية إلى تثبيت لمرة واحدة (${step}). يعمل على هذا الجهاز — قد يستغرق بضع دقائق.`,
- postSetupRun: 'تشغيل الإعداد',
- postSetupRunning: 'جار التثبيت…',
- postSetupStarting: 'جار البدء…',
- postSetupCompleteTitle: 'اكتمل الإعداد',
- postSetupCompleteMessage: step => `تم تثبيت ${step}.`,
- postSetupErrorTitle: 'انتهى الإعداد بأخطاء',
- postSetupErrorMessage: step => `تحقق من سجل ${step}.`,
- postSetupFailed: step => `فشل تشغيل إعداد ${step}`
- }
- },
- skills: {
- plugins: {
- pageBlurb: 'يمكن للإضافة توسيع هذا التطبيق أو الوكيل أو كليهما — ولكل جزء مفتاح تشغيل مستقل.'
- },
- tabSkills: 'المهارات',
- tabToolsets: 'مجموعات الأدوات',
- all: 'الكل',
- searchSkills: 'البحث في المهارات',
- searchToolsets: 'البحث في مجموعات الأدوات',
- refresh: 'تحديث',
- refreshing: 'جار التحديث...',
- loading: 'جار التحميل...',
- noSkillsTitle: 'لا توجد مهارات',
- noSkillsDesc: 'ستظهر المهارات المثبتة هنا.',
- noToolsetsTitle: 'لا توجد مجموعات أدوات',
- noToolsetsDesc: 'ستظهر مجموعات الأدوات المتاحة هنا.',
- noDescription: 'لا يوجد وصف',
- configured: 'مضبوط',
- needsKeys: 'يحتاج مفاتيح',
- toolsetsEnabled: (enabled, total) => `${enabled} من ${total} مفعلة`,
- configureToolset: label => `ضبط ${label}`,
- toggleToolset: (label, enabled) => `${enabled ? 'تشغيل' : 'إيقاف'} ${label}`,
- skillsLoadFailed: 'فشل تحميل المهارات',
- toolsetsRefreshFailed: 'فشل تحديث مجموعات الأدوات',
- skillEnabled: 'تم تفعيل المهارة',
- skillDisabled: 'تم تعطيل المهارة',
- toolsetEnabled: 'تم تفعيل مجموعة الأدوات',
- toolsetDisabled: 'تم تعطيل مجموعة الأدوات',
- appliesToNewSessions: name => `ينطبق على الجلسات الجديدة في ${name}`,
- failedToUpdate: name => `فشل تحديث ${name}`
- },
- agents: {
- extendedTranscript: 'سجل موسّع',
- transcriptTruncated: 'عرض أحدث 16 KiB',
- transcriptUnavailable: 'السجل المباشر غير متاح',
-
- close: 'إغلاق الوكلاء',
- title: 'شجرة التوليد',
- subtitle: 'نشاط الوكلاء الفرعيين المباشر للدور الحالي.',
- emptyTitle: 'لا يوجد وكلاء فرعيون مباشرون',
- emptyDesc: 'عندما يفوّض دور ما عملا، يبث الوكلاء الأبناء تقدّمهم هنا.',
- running: 'قيد التشغيل',
- failed: 'فشل',
- done: 'تم',
- streaming: 'جار البث',
- files: 'الملفات',
- moreFiles: count => `+${count} ملفات إضافية`,
- moreAgents: count => `${count} وكلاء إضافيون`,
- queued: 'في قائمة الانتظار',
- waitingActivity: 'بانتظار النشاط',
- steer: 'توجيه',
- steerPlaceholder: 'تعليمات لهذا الوكيل الفرعي',
- steerQueued: 'في انتظار نقطة التحقق التالية',
- stopRequested: 'تم طلب الإيقاف',
- requestRejected: 'لم يقبل الوكيل الفرعي الطلب',
- delegation: index => `التفويض ${index}`,
- workers: count => `${count} عامل`,
- workersActive: count => `${count} نشط`,
- agentsCount: count => `${count} ${count === 1 ? 'وكيل' : 'وكلاء'}`,
- activeCount: count => `${count} نشط`,
- failedCount: count => `${count} فشل`,
- toolsCount: count => `${count} أداة`,
- filesCount: count => `${count} ملف`,
- updatedAgo: age => `تم التحديث ${age}`,
- ageNow: 'الآن',
- ageSeconds: seconds => `قبل ${seconds} ث`,
- ageMinutes: minutes => `قبل ${minutes} د`,
- ageHours: hours => `قبل ${hours} س`,
- durationSeconds: seconds => `${seconds} ث`,
- durationMinutes: (minutes, seconds) => `${minutes} د ${seconds} ث`,
- tokens: value => `${value} رمز`
- },
- commandCenter: {
- close: 'إغلاق',
- paletteTitle: 'لوحة الأوامر',
- back: 'رجوع',
- searchPlaceholder: 'ابحث عن أمر أو إعداد...',
- goTo: 'انتقال إلى',
- goToSession: 'الانتقال إلى الجلسة',
- branches: 'الفروع',
- startInBranch: branch => `محادثة جديدة في ${branch}`,
- commandCenter: 'مركز الأوامر',
- appearance: 'المظهر',
- settings: 'الإعدادات',
- changeTheme: 'تغيير الثيم',
- changeColorMode: 'تغيير نمط الألوان',
- pets: {
- title: 'الحيوانات الأليفة',
- placeholder: 'البحث في الحيوانات الأليفة...',
- loading: 'جار تحميل معرض petdex...',
- error: 'تعذّر الوصول إلى معرض petdex.',
- staleBackend: 'أعد تشغيل Hermes لاستخدام الحيوانات الأليفة — الخادم الخلفي أقدم من هذه الميزة.',
- empty: 'لا توجد حيوانات أليفة مطابقة.',
- turnOff: 'إيقاف التشغيل',
- turnOn: 'تشغيل',
- installed: 'مثبّت',
- generatedTag: 'مُولّد',
- adoptFailed: 'تعذّر تبنّي ذلك الحيوان الأليف.',
- toggleFailed: enabled => `تعذّر ${enabled ? 'تشغيل' : 'إيقاف'} الحيوان الأليف.`,
- noneAvailable: 'لا توجد حيوانات أليفة متاحة — اختر واحدا أدناه لتثبيته.'
- },
- generatePet: {
- title: 'توليد حيوان أليف',
- placeholder: 'صف حيوانا أليفا لتوليده...',
- promptHint: 'اكتب وصفا، ثم اضغط Enter لرسم أربعة مظاهر.',
- readyHint: 'اضغط Enter لرسم أربعة مظاهر من وصفك.',
- generate: 'توليد',
- generating: 'جار التوليد...',
- retry: 'إعادة المحاولة',
- hatch: 'تفقيس',
- spawning: 'جار الإنشاء...',
- hatching: 'جار تفقيس حيوانك الأليف...',
- hatchingSub: 'جار بثّ الحياة فيه...',
- hatched: 'تم التفقيس!',
- hatchRow: (_state, done, total) => `جار رسم الإطار ${done} من ${total}...`,
- hatchComposing: 'جار تجميع الأجزاء...',
- hatchSaving: 'أوشكنا على الانتهاء...',
- namePlaceholder: 'سمِّ حيوانك الأليف',
- staleBackend: 'حدّث Hermes لتوليد الحيوانات الأليفة.',
- backgroundHint: 'يمكنك إغلاق هذا — سيُعلِمك Hermes عند الانتهاء.',
- slowProviderHint: 'قد يستغرق هذا عدة دقائق',
- remix: 'إعادة مزج',
- remixConfirmTitle: 'إعادة مزج هذا المظهر؟',
- remixConfirmBody: 'يولّد هذا مجموعة جديدة من المسوّدات باستخدام هذا كنقطة بداية. قد يستغرق عدة دقائق.',
- genericError: 'فشل التوليد — حاول مجددا أو اختر اقتراحا.',
- referenceImageTooLarge: 'صورة المرجع كبيرة جدا. استخدم واحدة أقل من 16 MB.',
- referenceImageInvalid: 'تعذّرت قراءة صورة المرجع تلك. جرّب PNG أو JPG أو WebP أو GIF.',
- adopt: 'تبنّي',
- startOver: 'البدء من جديد'
- },
- installTheme: {
- title: 'تثبيت سمة...',
- placeholder: 'البحث في VS Code Marketplace...',
- loading: 'جار البحث في Marketplace...',
- error: 'تعذّر الوصول إلى Marketplace.',
- empty: 'لا توجد سمات مطابقة.',
- install: 'تثبيت',
- installing: 'جار التثبيت...',
- installed: 'مثبّت',
- installs: count => `${count} عملية تثبيت`
- },
- settingsFields: 'حقول الإعدادات',
- mcpServers: 'خوادم MCP',
- archivedChats: 'المحادثات المؤرشفة',
- commands: 'الأوامر',
- sections: {
- sessions: 'الجلسات',
- system: 'النظام',
- usage: 'الاستخدام'
- },
- sectionDescriptions: {
- sessions: 'البحث في الجلسات وإدارتها',
- system: 'الحالة والسجلات وإجراءات النظام',
- usage: 'نشاط الرموز والتكلفة والمهارات عبر الزمن'
- },
- nav: {
- newChat: {
- title: 'جلسة جديدة',
- detail: 'بدء جلسة جديدة'
- },
- settings: {
- title: 'الإعدادات',
- detail: 'تكوين Hermes desktop'
- },
- capabilities: {
- title: 'المهارات والأدوات',
- detail: 'تفعيل المهارات ومجموعات الأدوات والمزوّدين'
- },
- messaging: {
- title: 'المراسلة',
- detail: 'إعداد Telegram وSlack وDiscord والمزيد'
- },
- artifacts: {
- title: 'العناصر',
- detail: 'استعراض المخرجات المولّدة'
- }
- },
- sectionEntries: {
- sessions: {
- title: 'لوحة الجلسات',
- detail: 'البحث في الجلسات وتثبيتها وإدارتها'
- },
- system: {
- title: 'لوحة النظام',
- detail: 'حالة البوابة والسجلات وإعادة التشغيل/التحديث'
- },
- usage: {
- title: 'لوحة الاستخدام',
- detail: 'نشاط الرموز والتكلفة والمهارات'
- }
- },
- providerNavigate: 'فتح المزود',
- providerSessions: 'جلسات المزود',
- refresh: 'تحديث',
- refreshing: 'جار التحديث...',
- noResults: 'لا توجد نتائج',
- pinSession: 'تثبيت الجلسة',
- unpinSession: 'إلغاء تثبيت الجلسة',
- exportSession: 'تصدير الجلسة',
- deleteSession: 'حذف الجلسة',
- noSessions: 'لا توجد جلسات',
- gatewayRunning: 'البوابة تعمل',
- gatewayStopped: 'البوابة متوقفة',
- hermesActiveSessions: (version, count) => `Hermes ${version} لديه ${count} جلسة نشطة`,
- restartGateway: 'إعادة تشغيل البوابة',
- openBrowser: 'فتح المتصفح',
- gatewayRestartFailed: 'فشل إعادة تشغيل البوابة.',
- sharedGatewayRestartTitle: 'إعادة تشغيل البوابة المشتركة؟',
- sharedGatewayRestartDescription: bots => `تتم إعادة اتصال جميع البوتات على هذا الجهاز: ${bots}`,
- sharedGatewayRestartConfirm: 'إعادة تشغيل الكل',
- sharedGatewayRestarted: count => `تمت إعادة تشغيل البوابة المشتركة (${count} بوت)`,
- updateHermes: 'تحديث Hermes',
- reloadWindow: 'إعادة تحميل النافذة',
- actionRunning: 'الإجراء قيد التشغيل',
- actionDone: 'اكتمل الإجراء',
- actionFailed: 'فشل الإجراء',
- actionStartedWaiting: 'بدأ الإجراء، جار الانتظار...',
- loadingStatus: 'جار تحميل الحالة',
- recentLogs: 'السجلات الأخيرة',
- noLogs: 'لا توجد سجلات',
- days: count => `${count} يوم`,
- statSessions: 'الجلسات',
- statApiCalls: 'نداءات API',
- statTokens: 'الرموز',
- statCost: 'التكلفة',
- actualCost: cost => `التكلفة الفعلية ${cost}`,
- loadingUsage: 'جار تحميل الاستخدام',
- noUsage: period => `لا يوجد استخدام خلال ${period} يوم`,
- retry: 'إعادة المحاولة',
- dailyTokens: 'الرموز اليومية',
- input: 'إدخال',
- output: 'إخراج',
- noDailyActivity: 'لا يوجد نشاط يومي',
- topModels: 'أكثر النماذج استخداما',
- noModelUsage: 'لا يوجد استخدام نماذج',
- topSkills: 'أكثر المهارات استخداما',
- noSkillActivity: 'لا يوجد نشاط مهارات',
- actions: count => `${count} إجراء`
- },
- messaging: {
- search: 'بحث',
- loading: 'جار التحميل...',
- loadFailed: 'فشل التحميل',
- states: {
- connected: 'متصل',
- connecting: 'جار الاتصال',
- disabled: 'معطّل',
- fatal: 'خطأ',
- gateway_stopped: 'تم إيقاف بوابة المراسلة',
- not_configured: 'يحتاج إعدادا',
- pending_restart: 'يلزم إعادة التشغيل',
- retrying: 'جار إعادة المحاولة',
- startup_failed: 'فشل بدء التشغيل'
- },
- unknown: 'غير معروف',
- hintPendingRestart: 'تحتاج إعادة تشغيل لتطبيق التغييرات.',
- sharedListenerUrl: 'يُخدم عبر مستمع البوابة المشتركة على',
- hintGatewayStopped: 'البوابة متوقفة.',
- restartNeeded: 'تم الحفظ. أعد تشغيل بوابة المراسلة لتطبيق الإعدادات الجديدة.',
- restartNow: 'إعادة التشغيل الآن',
- restarting: 'جارٍ إعادة التشغيل…',
- restartFailedManual: 'فشلت إعادة تشغيل البوابة — أعد تشغيلها يدويًا وتحقق من سجلات البوابة.',
- telegramQr: {
- title: 'اختر طريقة ربط بوت Telegram',
- subtitle: 'كلا الخيارين يربط بوتًا تتحكم به ويحفظ بياناته في هذا التثبيت من Hermes فقط.',
- quickSetup: 'إعداد سريع',
- recommended: 'موصى به',
- quickHelp: 'امسح رمز QR وأكّد في Telegram. سينشئ Hermes البوت ويكتشف معرّف مستخدم Telegram الخاص بك تلقائيًا.',
- createWithQr: 'إنشاء عبر QR',
- starting: 'جارٍ البدء…',
- replaceWarning: 'بيانات Telegram مُعدّة بالفعل. سيحل إعداد QR الجديد أو رمز البوت محل البوت الحالي عند الحفظ.',
- scanHint: 'امسح بتطبيق Telegram على هاتفك، أو افتح الرابط على هذا الجهاز.',
- waiting: 'في انتظار Telegram…',
- expiresIn: remaining => `ينتهي خلال ${remaining}`,
- expired: 'منتهي',
- openTelegram: 'افتح Telegram',
- ready: 'تم إنشاء البوت',
- allowedUsers: 'المستخدمون المسموح لهم',
- ownerDetected: 'تم اكتشاف المالك',
- addAtLeastOne: 'أضف معرّف مستخدم Telegram واحدًا على الأقل.',
- userIdPlaceholder: 'معرّف مستخدم Telegram',
- add: 'إضافة',
- numericOnly: 'يجب أن تكون معرّفات مستخدمي Telegram أرقامًا.',
- saveAndRestart: 'حفظ وإعادة التشغيل',
- applying: 'جارٍ الحفظ…',
- pairingExpired: 'انتهت صلاحية اقتران Telegram. ابدأ إعداد QR جديدًا.',
- stillWaiting: detail => `ما زلنا ننتظر Telegram. إعادة المحاولة بعد: ${detail}`,
- savedRestarting: 'تم حفظ Telegram؛ تجري إعادة تشغيل البوابة…',
- savedRestartFailed: detail => `تم حفظ Telegram؛ فشلت إعادة تشغيل البوابة${detail}`
- },
- credentialsSet: 'بيانات الاعتماد مضبوطة',
- needsSetup: 'يحتاج إعدادا',
- gatewayStopped: 'البوابة متوقفة',
- getCredentials: 'الحصول على بيانات الاعتماد',
- openSetupGuide: 'فتح دليل الإعداد',
- required: 'مطلوب',
- recommended: 'موصى به',
- advanced: count => `${count} إعدادات متقدمة`,
- noTokenNeeded: 'لا يحتاج رمز',
- enabled: 'مفعل',
- disabled: 'معطل',
- unsavedChanges: 'تغييرات غير محفوظة',
- saving: 'جار الحفظ...',
- saveChanges: 'حفظ التغييرات',
- saved: 'تم الحفظ',
- replaceValue: 'استبدال القيمة',
- openDocs: 'فتح الوثائق',
- clearField: key => `مسح ${key}`,
- enableAria: name => `تفعيل ${name}`,
- disableAria: name => `تعطيل ${name}`,
- platformEnabled: name => `تم تفعيل ${name}`,
- platformDisabled: name => `تم تعطيل ${name}`,
- restartToApply: 'أعد التشغيل لتطبيق التغييرات.',
- setupSaved: name => `تم حفظ إعداد ${name}`,
- restartToReconnect: 'أعد التشغيل لإعادة الاتصال.',
- appliedLive: 'تم التطبيق على البوابة قيد التشغيل.',
- connectingLive: 'البوابة قيد التشغيل تتصل باستخدام بيانات الاعتماد الجديدة.',
- keyCleared: key => `تم مسح ${key}`,
- setupUpdated: name => `تم تحديث إعداد ${name}`,
- failedUpdate: name => `فشل تحديث ${name}`,
- failedSave: name => `فشل حفظ ${name}`,
- failedClear: key => `فشل مسح ${key}`,
- fieldCopy: {
- TELEGRAM_BOT_TOKEN: {
- label: 'رمز البوت (token)',
- help: 'أنشئ بوتا عبر @BotFather، ثم الصق الرمز الذي يمنحك إياه.',
- placeholder: 'الصق رمز بوت Telegram'
- },
- TELEGRAM_ALLOWED_USERS: {
- label: 'معرّفات مستخدمي Telegram المسموح بهم',
- help: 'موصى به. معرّفات رقمية مفصولة بفواصل من @userinfobot. بدون ذلك، يمكن لأي شخص مراسلة بوتك مباشرة.'
- },
- TELEGRAM_PROXY: {
- label: 'رابط الـ Proxy',
- help: 'مطلوب فقط على الشبكات التي يكون فيها Telegram محجوبا.'
- },
- DISCORD_BOT_TOKEN: {
- label: 'رمز البوت (token)',
- help: 'أنشئ تطبيقا في Discord Developer Portal، وأضف بوتا، ثم الصق رمزه.'
- },
- DISCORD_ALLOWED_USERS: {
- label: 'معرّفات مستخدمي Discord المسموح بهم',
- help: 'موصى به. معرّفات مستخدمي Discord مفصولة بفواصل.'
- },
- DISCORD_REPLY_TO_MODE: {
- label: 'نمط الرد',
- help: 'first أو all أو off.'
- },
- DISCORD_ALLOW_ALL_USERS: {
- label: 'السماح لكل مستخدمي Discord',
- help: 'للتطوير فقط. عند التفعيل، يمكن لأي شخص مراسلة البوت مباشرة دون قائمة سماح.'
- },
- DISCORD_HOME_CHANNEL: {
- label: 'معرّف القناة الرئيسية',
- help: 'القناة التي يرسل فيها البوت الرسائل الاستباقية (مخرجات cron، التذكيرات).'
- },
- DISCORD_HOME_CHANNEL_NAME: {
- label: 'اسم القناة الرئيسية',
- help: 'الاسم المعروض للقناة الرئيسية في السجلات ومخرجات الحالة.'
- },
- BLUEBUBBLES_ALLOW_ALL_USERS: {
- label: 'السماح لكل مستخدمي iMessage',
- help: 'عند التفعيل، يتم تخطي قائمة سماح BlueBubbles.'
- },
- MATTERMOST_ALLOW_ALL_USERS: {
- label: 'السماح لكل مستخدمي Mattermost'
- },
- MATTERMOST_HOME_CHANNEL: {
- label: 'القناة الرئيسية'
- },
- QQ_ALLOW_ALL_USERS: {
- label: 'السماح لكل مستخدمي QQ'
- },
- QQBOT_HOME_CHANNEL: {
- label: 'قناة QQ الرئيسية',
- help: 'القناة أو المجموعة الافتراضية لتسليم cron.'
- },
- QQBOT_HOME_CHANNEL_NAME: {
- label: 'اسم قناة QQ الرئيسية'
- },
- SLACK_BOT_TOKEN: {
- label: 'رمز بوت Slack',
- help: 'استخدم رمز البوت من OAuth & Permissions بعد تثبيت تطبيق Slack الخاص بك.',
- placeholder: 'الصق رمز بوت Slack'
- },
- SLACK_APP_TOKEN: {
- label: 'رمز تطبيق Slack',
- help: 'استخدم الرمز على مستوى التطبيق المطلوب لـ Socket Mode.',
- placeholder: 'الصق رمز تطبيق Slack'
- },
- SLACK_ALLOWED_USERS: {
- label: 'معرّفات مستخدمي Slack المسموح بهم',
- help: 'موصى به. معرّفات مستخدمي Slack مفصولة بفواصل.'
- },
- MATTERMOST_URL: {
- label: 'رابط الخادم',
- placeholder: 'https://mattermost.example.com'
- },
- MATTERMOST_TOKEN: {
- label: 'رمز البوت (token)'
- },
- MATTERMOST_ALLOWED_USERS: {
- label: 'معرّفات المستخدمين المسموح بهم',
- help: 'موصى به. معرّفات مستخدمي Mattermost مفصولة بفواصل.'
- },
- MATRIX_HOMESERVER: {
- label: 'رابط Homeserver',
- placeholder: 'https://matrix.org'
- },
- MATRIX_ACCESS_TOKEN: {
- label: 'رمز الوصول'
- },
- MATRIX_USER_ID: {
- label: 'معرّف مستخدم البوت',
- placeholder: '@hermes:example.org'
- },
- MATRIX_ALLOWED_USERS: {
- label: 'معرّفات مستخدمي Matrix المسموح بهم',
- help: 'موصى به. معرّفات مستخدمين مفصولة بفواصل بصيغة @user:server.'
- },
- SIGNAL_HTTP_URL: {
- label: 'رابط جسر Signal',
- placeholder: 'http://127.0.0.1:8080',
- help: 'رابط جسر signal-cli REST قيد التشغيل.'
- },
- SIGNAL_ACCOUNT: {
- label: 'رقم الهاتف',
- help: 'الرقم المسجّل مع جسر signal-cli الخاص بك.'
- },
- SIGNAL_ALLOWED_USERS: {
- label: 'مستخدمو Signal المسموح بهم',
- help: 'موصى به. معرّفات Signal مفصولة بفواصل.'
- },
- WHATSAPP_ENABLED: {
- label: 'تفعيل جسر WhatsApp',
- help: 'يُضبط تلقائيا عبر المفتاح أدناه. اتركه دون تغيير ما لم تكن متأكدا من حاجتك إليه.'
- },
- WHATSAPP_MODE: {
- label: 'وضع الجسر'
- },
- WHATSAPP_ALLOWED_USERS: {
- label: 'مستخدمو WhatsApp المسموح بهم',
- help: 'موصى به. أرقام هواتف أو معرّفات WhatsApp مفصولة بفواصل.'
- }
- },
- platformIntro: {}
- },
- profiles: {
- close: 'إغلاق',
- nameHint: 'اسم الملف الشخصي',
- title: 'الملفات الشخصية',
- count: count => `${count} ملف شخصي`,
- loading: 'جار التحميل...',
- newProfile: 'ملف شخصي جديد',
- importProfile: 'استيراد ملف شخصي…',
- exportProfile: 'تصدير ملف شخصي…',
- exportMenu: 'تصدير…',
- imported: 'تم استيراد الملف الشخصي',
- exported: 'تم تصدير الملف الشخصي',
- failedImport: 'فشل استيراد الملف الشخصي',
- failedExport: 'فشل تصدير الملف الشخصي',
- allProfiles: 'كل الملفات الشخصية',
- showAllProfiles: 'إظهار كل الملفات الشخصية',
- switchToProfile: name => `التبديل إلى ${name}`,
- switchToConnection: name => `التبديل إلى ${name}`,
- switchConnectionFailed: name => `تعذّر الاتصال بـ ${name}`,
- manageProfiles: 'إدارة الملفات الشخصية',
- fleet: {
- localDevice: 'هذا الجهاز (خلفية محلية — تثبّت Hermes إن كان مفقودًا، وإلا تفتح جلسة جديدة)',
- switchDeviceTitle: 'التبديل إلى هذا الجهاز؟',
- switchDeviceDesc: 'يفتح هذا جلسة جديدة على هذا الحاسوب. تبقى المحادثة الحالية على البوابة الأخرى.',
- switchDeviceConfirm: 'تبديل',
- installDeviceTitle: 'التبديل إلى هذا الجهاز؟',
- installDeviceDesc: 'سيُثبَّت Hermes محليًا ثم تُفتح جلسة جديدة على هذا الحاسوب. لا يبدأ التثبيت قبل التأكيد.',
- installDeviceConfirm: 'تثبيت محليًا',
- connectExistingInstead: 'الاتصال بموجود بدلًا من ذلك'
- },
- remoteOverride: {
- menuItem: 'الاتصال بمضيف بعيد…',
- badge: (host: string) => `يعمل على ${host}`,
- title: (profile: string) => `ربط ${profile} بمضيف بعيد`,
- description: 'ستعمل جلسات هذا الملف الشخصي على خادم Hermes البعيد الذي تحدده، بدلاً من هذا الجهاز.',
- urlLabel: 'العنوان البعيد',
- urlPlaceholder: 'https://hermes.example.com',
- urlInvalid: 'أدخل عنواناً كاملاً يبدأ بـ http:// أو https://',
- tokenLabel: 'رمز الوصول',
- tokenPlaceholder: 'الصق رمز الجلسة البعيد',
- tokenSavedHint: 'يوجد رمز محفوظ بالفعل. اتركه فارغاً للاحتفاظ به.',
- plainTextOptIn:
- 'لا يتوفر تخزين مفاتيح آمن على هذا الجهاز، لذا سيُحفظ الرمز على القرص دون تشفير. احفظه على أي حال.',
- collisionWarning: (label: string) =>
- `توجد بوابة باسم «${label}» في الإعدادات بالفعل. اتصال هذا الملف الشخصي منفصل ولن يغيّرها.`,
- confirmTitle: 'ربط هذا الملف الشخصي بمضيف بعيد؟',
- confirmNote: (profile: string, host: string) =>
- `ستعمل المحادثات الجديدة في ${profile} على ${host}. سيقوم ذلك الجهاز بتنفيذ الأوامر وقراءة الملفات هناك، وليس هنا. اتصل فقط بمضيف تثق به.`,
- confirmBack: 'رجوع',
- connect: 'اتصال',
- connecting: 'جارٍ الاتصال…',
- disconnect: 'إزالة الاتصال البعيد',
- savedTitle: 'تم ربط الملف الشخصي',
- savedMessage: (profile: string, host: string) => `${profile} يعمل الآن على ${host}`,
- removedTitle: 'تمت إزالة الاتصال البعيد',
- removedMessage: (profile: string) => `${profile} يعمل الآن على هذا الجهاز`,
- removeFailed: 'تعذّرت إزالة الاتصال البعيد',
- authFailedTitle: 'رفض المضيف البعيد الرمز المحفوظ',
- authFailedMessage: (profile: string, host: string) =>
- `رفض ${host} الرمز المحفوظ لـ ${profile}. ربما تم تغييره على الجانب البعيد.`,
- updateToken: 'أدخل رمزاً جديداً…'
- },
- actions: 'إجراءات',
- color: 'اللون',
- colorFor: 'اللون',
- openInNewWindow: 'فتح في نافذة جديدة',
- setAsDefault: 'تعيين كافتراضي',
- defaultProfile: 'الملف الشخصي الافتراضي',
- defaultSet: name => `أصبح ${name} الملف الافتراضي`,
- defaultDescription: 'يُستخدم عند فتح Hermes وللمحادثات الجديدة. تبقى الجلسات الحالية في ملفاتها الشخصية.',
- failedSetDefault: 'تعذّر تعيين الملف الشخصي الافتراضي',
- setColor: color => `ضبط اللون ${color}`,
- autoColor: 'لون تلقائي',
- noProfiles: 'لا توجد ملفات شخصية',
- selectPrompt: 'اختر ملفا شخصيا',
- refresh: 'تحديث',
- refreshing: 'جار التحديث...',
- default: 'الافتراضي',
- skills: count => `${count} مهارة`,
- env: 'البيئة',
- defaultBadge: 'افتراضي',
- rename: 'إعادة تسمية',
- copySetup: 'نسخ الإعداد',
- copying: 'جار النسخ...',
- modelLabel: 'النموذج',
- skillsLabel: 'المهارات',
- notSet: 'غير مضبوط',
- soulDesc: 'الموجّه (prompt) النظامي وتعليمات الشخصية المضمّنة في هذا الملف الشخصي.',
- soulMissing:
- 'لا يوجد ملف SOUL.md لهذا الملف الشخصي بعد. أضف التعليمات أدناه واحفظ لإنشائه. تُدار إعدادات الشخصية في config.yaml بشكل منفصل.',
- soulOptional: 'اختياري',
- soulPlaceholder: mode =>
- `الموجّه (prompt) النظامي / الشخصية لهذا الملف الشخصي.\nاتركه فارغا للإبقاء على افتراضي ${mode}.`,
- soulPlaceholderCloned: 'مستنسخ',
- soulPlaceholderEmpty: 'فارغ',
- unsavedChanges: 'تغييرات غير محفوظة',
- loadingSoul: 'جار تحميل SOUL.md...',
- emptySoul: 'SOUL.md فارغ — ابدأ بكتابة الشخصية...',
- saving: 'جار الحفظ...',
- saveSoul: 'حفظ التعليمات',
- deleteTitle: 'حذف الملف الشخصي',
- deleteDescPrefix: 'سيؤدي هذا إلى حذف ',
- deleteDescMid: ' وإزالة ',
- deleteDescSuffix: ' الخاص به. لا يمكن التراجع عن هذا.',
- deleting: 'جار الحذف...',
- createDesc: 'أنشئ ملفا شخصيا بإعدادات منفصلة.',
- nameLabel: 'الاسم',
- cloneFrom: 'استنساخ من',
- cloneFromNone: 'لا شيء (فارغ)',
- cloneFromDesc: 'ينسخ الإعدادات والمهارات وSOUL.md من الملف الشخصي المصدر المحدد.',
- cloneFromDefault: 'نسخ إعداد الافتراضي',
- cloneFromDefaultDesc: 'ابدأ من إعدادات الملف الافتراضي.',
- invalidName: hint => `اسم غير صالح: ${hint}`,
- nameRequired: 'الاسم مطلوب',
- creating: 'جار الإنشاء...',
- createAction: 'إنشاء ملف شخصي',
- renameTitle: 'إعادة تسمية الملف الشخصي',
- renameDescPrefix: 'تؤدي إعادة التسمية إلى تحديث دليل الملف الشخصي وأي سكربتات تغليف في ',
- renameDescSuffix: '.',
- newNameLabel: 'الاسم الجديد',
- renaming: 'جار إعادة التسمية...',
- created: 'تم إنشاء الملف الشخصي',
- renamed: 'تمت إعادة التسمية',
- deleted: 'تم الحذف',
- setupCopied: 'تم نسخ الإعداد',
- soulSaved: 'تم حفظ التعليمات',
- failedLoad: 'فشل تحميل الملفات الشخصية',
- failedDelete: 'فشل الحذف',
- failedCopy: 'فشل النسخ',
- failedLoadSoul: 'فشل تحميل التعليمات',
- failedSaveSoul: 'فشل حفظ التعليمات',
- failedCreate: 'فشل الإنشاء',
- failedRename: 'فشل إعادة التسمية'
- },
- modelAssignment: {
- saveFailed: 'لم يحفظ Hermes تغيير النموذج هذا.',
- confirmTitle: 'تحذير اختيار النموذج',
- confirmDetail: 'أكّد فقط إذا كنت تقبل هذه المقايضة.',
- confirmAction: 'تأكيد',
- declined: 'أُلغي تغيير النموذج — رفضت تحذير طبقة تدريب البيانات.'
- },
-
- cron: {
- close: 'إغلاق',
- search: 'بحث',
- loading: 'جار التحميل...',
- states: {
- enabled: 'مُفعّل',
- scheduled: 'مجدول',
- running: 'قيد التشغيل',
- paused: 'متوقف مؤقتا',
- disabled: 'معطّل',
- error: 'خطأ',
- completed: 'مكتمل'
- },
- deliveryLabels: {
- local: 'سطح المكتب هذا',
- telegram: 'Telegram',
- discord: 'Discord',
- slack: 'Slack',
- email: 'البريد الإلكتروني'
- },
- scheduleLabels: {
- daily: 'يوميا',
- weekdays: 'أيام الأسبوع',
- weekly: 'أسبوعيا',
- monthly: 'شهريا',
- hourly: 'كل ساعة',
- 'every-15-minutes': 'كل 15 دقيقة',
- custom: 'مخصص'
- },
- scheduleHints: {
- daily: 'كل يوم في الساعة 9:00 صباحا',
- weekdays: 'من الاثنين إلى الجمعة في الساعة 9:00 صباحا',
- weekly: 'كل اثنين في الساعة 9:00 صباحا',
- monthly: 'أول يوم من كل شهر في الساعة 9:00 صباحا',
- hourly: 'في بداية كل ساعة',
- 'every-15-minutes': 'كل 15 دقيقة',
- custom: 'صياغة cron أو لغة طبيعية'
- },
- days: {
- '0': 'الأحد',
- '1': 'الاثنين',
- '2': 'الثلاثاء',
- '3': 'الأربعاء',
- '4': 'الخميس',
- '5': 'الجمعة',
- '6': 'السبت',
- '7': 'الأحد'
- },
- dayFallback: value => `اليوم ${value}`,
- everyDayAt: time => `كل يوم في ${time}`,
- weekdaysAt: time => `أيام الأسبوع في ${time}`,
- everyDayOfWeekAt: (day, time) => `كل ${day} في ${time}`,
- monthlyOnDayAt: (dayOfMonth, time) => `شهريا في اليوم ${dayOfMonth} في ${time}`,
- topOfHour: 'في بداية كل ساعة',
- everyHourAt: minute => `كل ساعة عند :${minute}`,
- newCron: 'مهمة مجدولة جديدة',
- emptyDescNew: 'أنشئ مهمة مجدولة لتشغيل Hermes تلقائيا.',
- emptyDescSearch: 'لا توجد مهام تطابق البحث.',
- emptyTitleNew: 'لا توجد مهام مجدولة',
- emptyTitleSearch: 'لا توجد نتائج',
- last: 'آخر تشغيل',
- next: 'التالي',
- noRuns: 'لا توجد تشغيلات',
- manage: 'إدارة',
- showRuns: 'إظهار التشغيلات',
- hideRuns: 'إخفاء التشغيلات',
- runHistory: 'سجل التشغيل',
-
- actionsTitle: 'الإجراءات',
- resume: 'استئناف',
- pause: 'إيقاف مؤقت',
- resumeTitle: 'استئناف المهمة',
- pauseTitle: 'إيقاف المهمة مؤقتا',
- triggerNow: 'تشغيل الآن',
- edit: 'تحرير',
- deleteTitle: 'حذف المهمة',
- deleteDescPrefix: 'سيؤدي هذا إلى إزالة ',
- deleteDescSuffix: ' نهائيا. سيتوقف عن العمل فورا.',
- deleting: 'جار الحذف...',
- resumed: 'تم الاستئناف',
- paused: 'تم الإيقاف مؤقتا',
- triggered: 'تم التشغيل',
- deleted: 'تم الحذف',
- created: 'تم الإنشاء',
- updated: 'تم التحديث',
- failedLoad: 'فشل تحميل المهام',
- failedUpdate: 'فشل التحديث',
- failedTrigger: 'فشل التشغيل',
- failedDelete: 'فشل الحذف',
- failedSave: 'فشل الحفظ',
- editTitle: 'تحرير المهمة المجدولة',
- createTitle: 'إنشاء مهمة مجدولة',
- editDesc: 'عدل الجدول والرسالة.',
- createDesc: 'اضبط مهمة يشغلها Hermes تلقائيا.',
- nameLabel: 'الاسم',
- namePlaceholder: 'مثال: الملخص الصباحي',
- promptLabel: 'الرسالة',
- scriptLabel: 'البرنامج النصي',
- scriptBadge: 'برنامج نصي',
- promptPlaceholder: 'ماذا تريد من Hermes أن يفعل؟',
- frequencyLabel: 'التكرار',
- deliverLabel: 'التسليم',
- customScheduleLabel: 'جدول مخصص',
- customPlaceholder: 'تعبير cron',
- customHint: 'استخدم صيغة cron القياسية.',
- optional: 'اختياري',
- promptScheduleRequired: 'الرسالة والجدول مطلوبان',
- saveChanges: 'حفظ التغييرات',
- createAction: 'إنشاء'
- },
- artifacts: {
- search: 'بحث',
- refresh: 'تحديث',
- refreshing: 'جار التحديث...',
- indexing: 'جار الفهرسة...',
- tabAll: 'الكل',
- tabImages: 'الصور',
- tabFiles: 'الملفات',
- tabLinks: 'الروابط',
- noArtifactsTitle: 'لا توجد عناصر',
- noArtifactsDesc: 'ستظهر الصور والملفات والروابط من محادثاتك هنا.',
- failedLoad: 'فشل تحميل العناصر',
- openFailed: 'فشل الفتح',
- itemsImage: 'صور',
- itemsLink: 'روابط',
- itemsFile: 'ملفات',
- itemsGeneric: 'عناصر',
- zero: 'صفر',
- rangeOf: (start, end, total) => `${start}-${end} من ${total}`,
- goToPage: (itemLabel, page) => `الانتقال إلى صفحة ${page} من ${itemLabel}`,
- colTitleLink: 'الرابط',
- colTitleFile: 'الملف',
- colTitleDefault: 'العنوان',
- colLocationLink: 'الموقع',
- colLocationFile: 'الموقع',
- colLocationDefault: 'الموقع',
- colSession: 'الجلسة',
- kindImage: 'صورة',
- kindFile: 'ملف',
- kindLink: 'رابط',
- chat: 'المحادثة',
- copyUrl: 'نسخ الرابط',
- copyPath: 'نسخ المسار'
- },
-
- artifactCard: {
- kind: { code: 'كود', html: 'صفحة تفاعلية', svg: 'رسم' },
- generating: lines => `جارٍ الإنشاء… ${lines} سطرًا`,
- versionBadge: count => `${count} إصدارات`,
- open: 'فتح'
- },
-
- artifactPreview: {
- versionOf: (current, total) => `الإصدار ${current} من ${total}`,
- olderVersion: 'إصدار أقدم',
- newerVersion: 'إصدار أحدث',
- latest: 'الأحدث',
- copyContent: 'نسخ المحتوى',
- download: 'تنزيل',
- openInBrowser: 'فتح في المتصفح',
- openInBrowserFailed: 'تعذّر الفتح في المتصفح',
- missingTitle: 'الناتج غير متاح',
- missingBody: 'لم يعد هذا الناتج موجودًا في السجل المحلي.'
- },
- sidebar: {
- profileRail: 'شريط الملفات الشخصية',
- markAllRead: 'وضع علامة مقروء على الكل',
- filter: {
- grouping: 'تجميع',
- ordering: 'ترتيب',
- show: 'إظهار',
- filters: 'تصفية',
- status: 'الحالة',
- pullRequest: 'طلب سحب',
- profile: 'الملف الشخصي',
- project: 'المشروع',
- archived: 'مؤرشف',
- resetToDefaults: 'إعادة تعيين إلى الافتراضي',
- expandAll: 'توسيع الكل',
- collapseAll: 'طي الكل',
- inboxStyle: 'نمط البريد الوارد',
- updated: 'محدّث',
- created: 'أُنشئ',
- tokens: 'الرموز',
- cost: 'التكلفة',
- manual: 'يدوي',
- preview: 'معاينة',
- pr: 'PR',
- needsInput: 'يحتاج إدخالاً',
- working: 'يعمل',
- unread: 'غير مقروء',
- draft: 'مسودة',
- idle: 'خامل',
- open: 'مفتوح',
- merged: 'مدمج',
- closed: 'مغلق',
- noPR: 'لا يوجد PR'
- },
- gatewayGroups: {
- grouping: 'البوابة والملف الشخصي',
- rename: 'إعادة تسمية المجموعة',
- aliasLabel: 'اسم العرض',
- aliasHint: 'يتغير اسم العرض فقط؛ تبقى أسماء البوابة والملف الشخصي دون تغيير.',
- resetName: 'إعادة تعيين الاسم',
- moveUp: 'نقل لأعلى',
- moveDown: 'نقل لأسفل',
- reorder: 'إعادة ترتيب المجموعة',
- actions: 'إجراءات المجموعة'
- },
- nav: {
- 'new-session': 'جلسة جديدة',
- capabilities: 'المهارات',
- messaging: 'المراسلة',
- artifacts: 'العناصر',
- cron: 'المهام المجدولة'
- },
- searchAria: 'البحث في الجلسات',
- searchPlaceholder: 'البحث في الجلسات...',
- clearSearch: 'مسح البحث',
- noMatch: query => `لا توجد جلسات تطابق "${query}"`,
- results: 'النتائج',
- pinned: 'المثبتة',
- sessions: 'الجلسات',
- terminal: 'الطرفية',
- files: 'الملفات',
- review: 'المراجعة',
- logs: 'السجلات',
- cronJobs: 'المهام المجدولة',
- groupAriaGrouped: 'الجلسات مجمعة حسب مساحة العمل',
- groupAriaUngrouped: 'الجلسات غير مجمعة',
- showProjects: 'عرض المشاريع',
- showSessions: 'عرض الجلسات',
- groupTitleGrouped: 'مجمعة حسب مساحة العمل',
- groupTitleUngrouped: 'كل الجلسات',
- allPinned: 'كل الجلسات مثبتة',
- shiftClickHint: 'استخدم Shift للتحديد المتعدد',
- noWorkspace: 'بدون مساحة عمل',
- projectEmpty: 'لا توجد جلسات بعد',
- projectLoadFailed: 'تعذر تحميل الجلسات',
- noSessions: 'لا توجد جلسات بعد',
- noFilterMatches: 'لا توجد جلسات تطابق عوامل التصفية هذه',
- projects: {
- showAllSessions: 'عرض جميع الجلسات',
- sectionLabel: 'المشاريع',
- home: 'الرئيسية',
- autoDiscovered: 'مكتشف تلقائيًا',
- newButton: 'مشروع جديد',
- createTitle: 'مشروع جديد',
- createDesc: 'سمِّ مساحة العمل وأضف مجلدا أو أكثر.',
- renameTitle: 'إعادة تسمية المشروع',
- addFolderTitle: 'إضافة مجلد',
- namePlaceholder: 'مثال: Skunkworks',
- foldersLabel: 'المجلدات',
- ideaLabel: 'الفكرة',
- ideaPlaceholder: 'ما موضوع هذا المشروع؟ (يُحفظ في IDEA.md)',
- ideaGenerate: 'توليد فكرة',
- ideaGenerating: 'جار التوليد...',
- ideaShuffle: 'خلط القوالب',
- noFolders: 'لم تتم إضافة أي مجلدات بعد.',
- addFolder: 'إضافة مجلد',
- primaryBadge: 'أساسي',
- removeFolder: 'إزالة',
- create: 'إنشاء',
- menu: 'إجراءات',
- menuRename: 'إعادة تسمية…',
- menuAppearance: 'المظهر',
- noColor: 'بلا لون',
- menuAddFolder: 'إضافة مجلد',
- menuSetActive: 'تعيين كنشط',
- menuDelete: 'حذف',
- reveal: 'إظهار في المجلد',
- copyPath: 'نسخ المسار',
- removeFromSidebar: 'إخفاء من الشريط الجانبي',
- createFailed: 'تعذّر إنشاء المشروع',
- deleteConfirm: 'هذا يزيل المشروع المحفوظ من Hermes. تبقى الملفات ومستودعات git وأشجار العمل دون تغيير.',
- startWork: 'شجرة عمل جديدة',
- newWorktreeTitle: 'شجرة عمل جديدة',
- newWorktreeDesc: 'سمِّ الفرع لشجرة العمل هذه.',
- branchPlaceholder: 'مثال: my-feature',
- startWorkFailed: 'تعذّر إنشاء شجرة العمل',
- worktreeStaleBackend:
- 'حدِّث خادم Hermes لإنشاء أشجار العمل عبر هذا الاتصال البعيد — فهو أقدم من واجهة git worktree.',
- worktreeProjectLabel: 'المشروع',
- worktreeProjectPlaceholder: 'ابحث في المشاريع…',
- worktreeProjectNone: 'لا توجد مشاريع بمجلد',
- convertBranch: 'تحويل فرع...',
- convertBranchTitle: 'تحويل فرع',
- convertBranchDesc: 'افتح الفروع المسحوبة، أو أنشئ شجرة عمل لفرع حر.',
- convertBranchPlaceholder: 'البحث في الفروع...',
- convertBranchInstead: 'تحويل فرع موجود',
- branchOpenExisting: 'فتح',
- branchSwitchHome: 'تبديل الموطن',
- branchCreateWorktree: 'شجرة عمل جديدة',
- branchTrackRemote: 'تتبع البعيد',
- branchesLoading: 'جار تحميل الفروع...',
- noBranches: 'لم يتم العثور على فروع',
- removeWorktree: 'إزالة شجرة العمل',
- removeWorktreeFailed: 'تعذّر إزالة شجرة العمل (تغييرات غير مُودعة؟)',
- removeWorktreeConfirm:
- 'أزِلها من git (يحذف مجلد شجرة العمل؛ يبقى الفرع)، أو فقط أخفِ المسار من الشريط الجانبي واترك شجرة العمل على القرص.',
- removeWorktreeDirty:
- 'تحتوي شجرة العمل هذه على تغييرات غير مُودعة. أزِلها بالقوة (يتجاهل تلك التغييرات)، أو فقط أخفِ المسار واحتفظ بها على القرص.',
- forceRemove: 'إزالة بالقوة',
- enter: label => `فتح ${label}`,
- reorder: label => `إعادة ترتيب ${label}`,
- toggle: (label, open) => `${open ? 'إظهار' : 'إخفاء'} جلسات ${label}`,
- showAllCount: count => `إظهار كل الجلسات (${count})`,
- back: 'كل المشاريع'
- },
- newSessionIn: label => `جلسة جديدة في ${label}`,
- showMoreIn: (count, label) => `إظهار ${count} أخرى في ${label}`,
- loading: 'جار التحميل...',
- loadMore: 'تحميل المزيد',
- loadCount: step => `تحميل ${step} أخرى`,
- row: {
- pin: 'تثبيت',
- unpin: 'إلغاء التثبيت',
- markUnread: 'وضع علامة كغير مقروء',
- markRead: 'وضع علامة كمقروء',
- unreadFailed: 'تعذر تحديث حالة القراءة',
- copyId: 'نسخ المعرف',
- export: 'تصدير',
- branchFrom: 'فرع',
- rename: 'إعادة تسمية…',
- archive: 'أرشفة',
- unarchive: 'إلغاء الأرشفة',
- newWindow: 'فتح في نافذة جديدة',
- openInTerminal: 'فتح في الطرفية',
- copyIdFailed: 'فشل نسخ المعرف',
-
- sessionActions: 'إجراءات الجلسة',
- sessionRunning: 'الجلسة تعمل',
- needsInput: 'تحتاج إدخالا',
- waitingForAnswer: 'بانتظار إجابة',
- backgroundRunning: 'تعمل في الخلفية',
- draftSession: 'مسودة — لم تُرسل بعد',
- finishedUnread: 'اكتملت وفيها جديد',
- hideTabBar: 'إخفاء شريط التبويبات',
- openInNewTab: 'فتح في تبويب جديد',
- openInSplit: 'فتح في تقسيم',
- ownedByProfile: profile => `مملوكة للملف الشخصي ${profile}`,
- untitledChat: id => `محادثة ${id}`,
- handoffOrigin: platform => `قادمة من ${platform}`,
- continuationOrigin: 'متابعة تلقائية — تم ضغط هذه المحادثة ومتابعتها',
- renamed: 'تمت إعادة التسمية',
- renameFailed: 'فشلت إعادة التسمية',
- renameTitle: 'إعادة تسمية الجلسة',
- renameDesc: '',
- untitledPlaceholder: 'جلسة بلا عنوان',
- deleteTitle: 'حذف الجلسة؟',
- deleteDesc: title => `سيتم حذف «${title}» نهائيًا. لا يمكن التراجع عن هذا الإجراء.`,
- deleting: 'جارٍ الحذف…',
- deleted: 'تم حذف الجلسة',
- ageNow: 'الآن',
- ageDay: 'يوم',
- ageHour: 'ساعة',
- ageMin: 'دقيقة'
- }
- },
+ sharedMetrics: arCommon.sharedMetrics,
+ externalOpenFailed: arChrome.externalOpenFailed,
+ sessionImport: arConnectors.sessionImport,
+ sendDiagnostics: arDiagnostics.sendDiagnostics,
+ common: arCommon.common,
+ fileMenu: arChrome.fileMenu,
+ boot: arBoot.boot,
+ notifications: arDiagnostics.notifications,
+ remoteDisplayBanner: arBoot.remoteDisplayBanner,
+ butterbar: arBoot.butterbar,
+ titlebar: arChrome.titlebar,
+ keybinds: arChrome.keybinds,
+ language: arSettings.language,
+ settings: arSettings.settings,
+ skills: arCapabilities.skills,
+ agents: arCapabilities.agents,
+ commandCenter: arCommandCenter.commandCenter,
+ messaging: arCommandCenter.messaging,
+ profiles: arCommandCenter.profiles,
+ modelAssignment: arSettings.modelAssignment,
+ cron: arCommandCenter.cron,
+ artifacts: arArtifacts.artifacts,
+ artifactCard: arArtifacts.artifactCard,
+ artifactPreview: arArtifacts.artifactPreview,
+ sidebar: arChrome.sidebar,
- composer: arChat.composer,
+ composer: {
- message: 'الرسالة',
- wakingProfile: profile => `جار إيقاظ ${profile}`,
- placeholderStarting: 'جار بدء Hermes...',
- placeholderReconnecting: 'جار إعادة الاتصال...',
- placeholderFollowUp: 'اكتب متابعة...',
- newSessionPlaceholders: ['اسأل Hermes عن شيء...', 'اطلب من Hermes تنفيذ مهمة...', 'ابدأ محادثة جديدة...'],
- followUpPlaceholders: ['اكتب متابعة...', 'أضف توجيها...', 'اسأل سؤالا آخر...'],
- startVoice: 'بدء الصوت',
- openDirective: 'فتح',
- queueMessage: 'إضافة الرسالة للطابور',
- steer: 'توجيه',
++ ...arChat.composer,
+ redirect: 'إعادة توجيه التشغيل الحالي',
- stop: 'إيقاف',
- send: 'إرسال',
- speaking: 'يتحدث',
- transcribing: 'جار التفريغ',
- thinking: 'يفكر',
- muted: 'مكتوم',
- listening: 'يستمع',
- muteMic: 'كتم الميكروفون',
- unmuteMic: 'إلغاء كتم الميكروفون',
- stopListening: 'إيقاف الاستماع',
- stopShort: 'إيقاف',
- endConversation: 'إنهاء المحادثة',
- endShort: 'إنهاء',
- stopDictation: 'إيقاف الإملاء',
- transcribingDictation: 'جار تفريغ الإملاء',
- voiceControls: 'صوت',
- voiceDictation: 'إملاء صوتي',
- lookupLoading: 'جار البحث...',
- lookupNoMatches: 'لا توجد نتائج',
- lookupTry: 'جرب',
- lookupOr: 'أو',
- commonCommands: 'الأوامر الشائعة',
- hotkeys: 'الاختصارات',
- helpFooter: 'استخدم الأسهم للتنقل و Enter للاختيار.',
- commandDescs: {
- '/help': 'عرض أوامر الشرطة المائلة لسطح المكتب',
- '/clear': 'بدء جلسة جديدة',
- '/resume': 'استئناف جلسة محفوظة',
- '/details': 'التحكم في مستوى تفاصيل النص',
- '/copy': 'نسخ التحديد أو آخر رسالة من المساعد',
- '/quit': 'الخروج من hermes',
- '/start': 'تأكيد طلب بدء المنصة دون إرسال رد',
- '/new': 'بدء محادثة جديدة في تطبيق سطح المكتب',
- '/topic': 'تفعيل مواضيع الرسائل الخاصة في Telegram أو عرضها',
- '/save': 'حفظ المحادثة الحالية بصيغة JSON',
- '/retry': 'إعادة إرسال آخر رسالة إلى الوكيل',
- '/prompt': 'كتابة الطلب التالي بتنسيق Markdown في $EDITOR ثم إرساله',
- '/undo': 'الرجوع بعدد محدد من أدوار المستخدم وإعادة الطلب (الافتراضي 1)',
- '/title': 'إعادة تسمية الجلسة الحالية',
- '/handoff': 'نقل هذه الجلسة إلى منصة مراسلة',
- '/branch': 'إنشاء فرع من آخر رسالة في محادثة جديدة',
- '/worktree': 'عرض أشجار عمل Git المعزولة أو سردها أو إنشاؤها أو تنظيفها',
- '/compress': 'ضغط سياق المحادثة الحالية',
- '/rollback': 'عرض نقاط استعادة الملفات أو استعادتها مع الحفاظ على تعديلاتك اليدوية',
- '/export': 'تصدير الملف الشخصي بإعداداته ومهاراته وسمته إلى أرشيف قابل للمشاركة',
- '/import': 'استيراد أرشيف مشترك كملف شخصي جديد',
- '/stop': 'إيقاف الدور الجاري والعمليات الخلفية',
- '/pause': 'إيقاف العمل الجديد مؤقتًا للجميع؛ الاستئناف باستخدام /pause off',
- '/bg': 'تشغيل طلب في جلسة خلفية منفصلة',
- '/btw': 'طرح سؤال جانبي عن المحادثة دون مقاطعتها',
- '/agents': 'عرض الوكلاء النشطين والمهام الجارية',
- '/journey': 'فتح رسم الذاكرة لعرض المهارات والذكريات عبر الزمن',
- '/queue': 'إضافة طلبات للدور التالي أو عرضها أو تعديلها أو حذفها أو نقلها أو مسحها',
- '/steer': 'إدراج رسالة بعد استدعاء الأداة التالي دون مقاطعة العمل',
- '/goal': 'تحديد هدف مستمر يعمل عليه Hermes حتى إنجازه',
- '/heartbeat': 'تحديد طلب متكرر يعود إلى هذه الجلسة عندما تكون خاملة',
- '/refine': 'مراجعة هذه المحادثة وحفظ الدروس في الذاكرة أو المهارات',
- '/review': 'تشغيل وكيل فرعي مستقل لمراجعة العمل الذي نوقش',
- '/loop': 'تكرار طلب على فترات منتظمة في هذه الجلسة',
- '/plan': 'كتابة خطة تنفيذ بتنسيق Markdown في .hermes/plans/ دون تنفيذها',
- '/moa': 'تشغيل طلب باستخدام Mixture of Agents ثم استعادة النموذج',
- '/subgoal': 'إضافة معايير للهدف النشط أو إدارتها',
- '/status': 'عرض حالة الجلسة الحالية',
- '/egress': 'عرض حالة وكيل الاتصالات الصادرة في Docker',
- '/context': 'عرض استخدام السياق وتفاصيله وإحصاءات الضغط ومعدل المعالجة',
- '/whoami': 'عرض صلاحية الوصول إلى أوامر الشرطة المائلة',
- '/profile': 'تبديل ملف Hermes الشخصي النشط',
- '/codex-runtime': 'تبديل بيئة Codex app-server لنماذج OpenAI/Codex',
- '/personality': 'اختيار شخصية محددة مسبقًا',
- '/battery': 'تبديل عرض مؤشر البطارية الملون في شريط الحالة',
- '/timestamps': 'تبديل الطوابع الزمنية في الرسائل و /history',
- '/diff': 'عرض تغييرات Git في مجلد العمل',
- '/focus': 'تبديل عرض التركيز الذي يعرض الطلب والرد النهائي فقط',
- '/yolo': 'تبديل YOLO — الموافقة التلقائية على الأوامر الخطرة',
- '/approvals': 'عرض وضع الموافقة على الأوامر الخطرة أو ضبطه',
- '/reasoning': 'إدارة مستوى الاستدلال وطريقة عرضه',
- '/skin': 'تبديل سمة سطح المكتب أو الانتقال إلى التالية',
- '/wake': 'التحكم في مستمع كلمة التنبيه [on|off|status]',
- '/tools': 'إدارة الأدوات المتاحة للوكيل',
- '/memory': 'مراجعة عمليات كتابة الذاكرة المعلقة أو تبديل طلب الموافقة',
- '/bundles': 'عرض حزم المهارات',
- '/pet': 'تبديل تميمة petdex أو تبني واحدة',
- '/hatch': 'إنشاء حيوان أليف جديد',
- '/learn': 'تعلم مهارة قابلة لإعادة الاستخدام من المجلدات أو الروابط أو المحادثة أو الملاحظات',
- '/init': 'فحص المستودع لإنشاء تعليمات AGENTS.md أو تحديثها',
- '/suggestions': 'مراجعة عمليات الأتمتة المقترحة وقبولها أو رفضها',
- '/blueprint': 'إعداد أتمتة من قالب مخطط',
- '/browser': 'إدارة اتصال المتصفح عبر CDP [connect|disconnect|status] (بوابة محلية فقط)',
- '/palette': 'فتح لوحة الأوامر',
- '/usage': 'عرض استخدام الرموز وحدود الطلبات؛ reset يسترد إعادة ضبط محفوظة لحدود Codex',
- '/subscription': 'عرض خطة Nous وتغييرها في المتصفح',
- '/topup': 'عرض رصيد Nous وإدارة الفواتير',
- '/platform': 'إيقاف منصة بوابة متعثرة مؤقتًا أو استئنافها أو عرضها',
- '/version': 'عرض إصدار Hermes Agent',
- '/debug': 'رفع تقرير تصحيح يتضمن معلومات النظام والسجلات للحصول على رابط قابل للمشاركة',
- '/model': 'تبديل نموذج هذه الجلسة'
- },
- hotkeyDescs: {
- 'composer.mention': 'الإشارة إلى الملفات والمجلدات والروابط وgit',
- 'composer.slash': 'لوحة أوامر الشرطة المائلة',
- 'composer.help': 'هذه المساعدة السريعة (احذف للإخفاء)',
- 'composer.sendNewline': 'إرسال · Shift+Enter لسطر جديد',
- 'composer.sendQueued': 'إرسال الدور التالي في قائمة الانتظار',
- 'keybinds.openPanel': 'كل اختصارات لوحة المفاتيح',
- 'composer.cancel': 'إغلاق النافذة المنبثقة · إلغاء التشغيل',
- 'composer.history': 'التنقل في النافذة المنبثقة / السجل'
- },
- attachUrlTitle: 'إرفاق رابط',
- attachUrlDesc: 'أضف رابطا إلى الرسالة.',
- urlPlaceholder: 'https://example.com',
- urlHintPre: 'سيقرأ Hermes الرابط ضمن السياق.',
- attach: 'إرفاق',
- queued: count => `${count} في الطابور`,
- attachmentOnly: 'إرفاق فقط',
- emptyTurn: 'اكتب رسالة أو أرفق ملفا.',
- attachments: count => `${count} مرفق`,
- editingInComposer: 'جار التحرير في صندوق الكتابة',
- editingQueuedInComposer: 'جار تحرير رسالة في الطابور',
- restoredDraftNotice: 'تمت استعادة رسالتك غير المُرسلة',
- restoredDraftUndo: 'تراجع',
- queueEdit: 'تحرير الرسالة المجدولة',
- queueSendNext: 'إرسالها تاليا',
- queueSteer: 'توجيه — تصحيح الدور الجاري فورا',
- queueSend: 'إرسالها الآن',
- queueDelete: 'حذف من الطابور',
+ queueLostNote: 'فُقد الدور أثناء إعادة التشغيل',
+ restoreImageDraft: 'استعادة مسودة الصورة',
+ queueLostDiscard: 'تجاهل',
- queueLostDiscardTip: 'أعادت البوابة التشغيل أثناء هذا الدور ولا يمكن إكماله. تجاهله لتستمر الأدوار المنتظرة خلفه.',
- queueStuckTitle: 'لم تُرسل الرسالة في قائمة الانتظار',
- queueStuckBody: 'ظل دور في قائمة الانتظار يفشل في الإرسال. ما زال في قائمة الانتظار — حاول إرساله مرة أخرى.',
- queueDroppedTitle: 'تم إسقاط عنصر قائمة الانتظار',
- queueDroppedBody:
- 'أُسقط هذا العنصر في الخلفية لأن جلسته تعذّر استئنافها بعد محاولات متكررة. بقية قائمة الانتظار لم تتأثر.',
- previewUnavailable: 'المعاينة غير متاحة',
- previewLabel: label => `معاينة ${label}`,
- couldNotPreview: label => `تعذرت معاينة ${label}`,
- removeAttachment: label => `إزالة ${label}`,
- dictating: 'جار الإملاء',
- preparingAudio: 'جار تجهيز الصوت',
- speakingResponse: 'جار قراءة الرد',
- readingAloud: 'جار القراءة بصوت عال',
- themeSuggestions: 'اقتراحات سمات سطح المكتب',
- noMatchingThemes: 'لا توجد سمات مطابقة.',
- themeTryPre: 'جرّب ',
- themeTryPost: '.',
- attachLabel: 'إرفاق',
- files: 'ملفات',
- folder: 'مجلد',
- images: 'صور',
- pasteImage: 'لصق صورة',
- url: 'رابط',
- promptSnippets: 'مقتطفات جاهزة',
- tipPre: 'نصيحة: اكتب ',
- tipPost: ' للإشارة إلى الملفات ضمن النص.',
- snippetsTitle: 'مقتطفات الموجّهات',
- snippetsDesc: 'اختر موجّهًا أوليًا لإدراجه في المحرّر.',
- dropFiles: 'أفلت الملفات للإرفاق',
- dropSession: 'أفلت الجلسة للفتح',
- snippets: {
- codeReview: {
- label: 'مراجعة الكود',
- description: 'دقّق التغيير الحالي بحثًا عن الانحدارات والحالات الطرفية المُسقطة والاختبارات المفقودة.',
- text: 'يرجى مراجعة هذا بحثًا عن الأخطاء والانحدارات والاختبارات المفقودة.'
- },
- implementationPlan: {
- label: 'خطة التنفيذ',
- description: 'حدّد نهجًا قبل لمس الكود حتى يبقى الفرق مركّزًا.',
- text: 'يرجى وضع خطة تنفيذ موجزة قبل تغيير الكود.'
- },
- explainThis: {
- label: 'اشرح هذا',
- description: 'اشرح كيفية عمل الكود المحدد واربطه بالملفات الرئيسية.',
- text: 'يرجى شرح كيفية عمل هذا وإرشادي إلى الملفات الرئيسية.'
- }
- }
- },
- statusStack: {
- hideStack: 'إخفاء لوحة الحالة',
- showStack: 'إظهار لوحة الحالة',
- agents: 'الوكلاء',
- background: count => `${count} في الخلفية`,
- goalActive: 'الهدف نشط',
- goalBlocked: 'الهدف متعذر',
- goalDone: 'اكتمل الهدف',
- goalPaused: 'الهدف متوقف مؤقتًا',
- goalWaiting: 'الهدف قيد الانتظار',
- subagents: count => `${count} ${count === 1 ? 'وكيل فرعي' : 'وكيل فرعي'}`,
- todos: (done, total) => `المهام ${done}/${total}`,
- previousTodos: (done, total) => `المهام السابقة ${done}/${total}`,
- running: 'قيد التشغيل',
- stop: 'إيقاف',
- dismiss: 'تجاهل',
- exit: code => `خروج ${code}`,
- control: {
- goalActiveTurns: (turn, maxTurns) => `الجولة ${turn}/${maxTurns}`,
- goalDoneTurns: turns => `${turns} جولات`,
- goalTurn: turn => `الجولة ${turn}`,
- goalActions: 'إجراءات الهدف',
- viewDetails: 'عرض التفاصيل',
- addCriterion: 'إضافة معيار',
- addCriterionDialogTitle: 'إضافة معيار',
- addCriterionPlaceholder: 'أدخل نص المعيار...',
- criterionLabel: 'المعيار',
- pauseGoal: 'إيقاف الهدف مؤقتاً',
- resumeGoal: 'استئناف الهدف',
- resumeNow: 'استئناف الآن',
- clearGoal: 'مسح الهدف',
- clearGoalConfirmTitle: 'مسح الهدف؟',
- clearGoalConfirmBody: 'هل أنت متأكد من مسح الهدف النشط؟ لا يمكن التراجع عن هذا الإجراء.',
- copyCriterion: index => `نسخ المعيار ${index}`,
- removeCriterion: index => `إزالة المعيار ${index}`,
- removeCriterionConfirmTitle: index => `إزالة المعيار ${index}؟`,
- removeCriterionConfirmBody: index => `هل أنت متأكد من إزالة المعيار ${index}؟`,
- clearCriteria: 'مسح جميع المعايير',
- clearCriteriaConfirmTitle: 'مسح جميع المعايير؟',
- clearCriteriaConfirmBody: 'هل أنت متأكد من رغبتك في إزالة جميع المعايير من هذا الهدف؟',
- criteriaHeader: count => `المعايير · ${count}`,
- noCriteria: 'لا توجد معايير',
- goalDetailsTitle: 'تفاصيل الهدف',
- objectiveLabel: 'الهدف',
- contractOutcome: 'النتيجة',
- contractVerification: 'التحقق',
- contractConstraints: 'القيود',
- contractBoundaries: 'الحدود',
- contractStopWhen: 'التوقف عند',
- waitBarrierTitle: 'شرط الانتظار',
- waitUntil: target => `في الانتظار حتى ${target}`,
- waitSession: target => `في انتظار الجلسة ${target}`,
- waitPid: pid => `في انتظار العملية ${pid}`,
- qualityGatesTitle: 'بوابات الجودة',
- gateCommand: 'الأمر',
- gateAttempts: (attempts, max) => `${attempts}/${max} محاولات`,
- gateTimeout: seconds => `مهلة ${seconds} ثانية`,
- gateLastExit: code => (code === null ? 'قيد الانتظار' : `رمز الخروج: ${code}`),
- loopActive: 'التكرار نشط',
- loopPaused: 'التكرار متوقف مؤقتاً',
- loopDeferred: 'التكرار مؤجل',
- loopFinished: 'التكرار منتهي',
- loopRuns: runs => `${runs} مرات تشغيل`,
- loopRunCount: (current, total) => `تشغيل ${current}/${total}`,
- loopNext: time => `التالي ${time}`,
- loopEverySeconds: seconds => `كل ${seconds} ث`,
- loopEveryMinutes: minutes => `كل ${minutes} د`,
- loopEveryHours: hours => `كل ${hours} س`,
- loopSelfPaced: 'ذاتي الإيقاع',
- loopActions: 'إجراءات التكرار',
- pauseLoop: 'إيقاف التكرار مؤقتاً',
- resumeLoop: 'استئناف التكرار',
- stopLoop: 'إيقاف التكرار',
- stopLoopConfirmTitle: 'إيقاف التكرار؟',
- stopLoopConfirmBody: 'هل أنت متأكد من رغبتك في إيقاف هذا التكرار؟',
- dismissLoop: 'تجاهل التكرار',
- loopPromptLabel: 'الموجه',
- loopCadenceLabel: 'الإيقاع',
- loopUntilLabel: 'شرط الانتهاء',
- loopDeferredNotice: 'الهدف النشط يتحكم بالجلسة حالياً.',
- loopAwaitingResponse: 'في انتظار الاستجابة',
- heartbeatActive: 'النبض نشط',
- heartbeatPaused: 'النبض متوقف مؤقتاً',
- heartbeatEveryMinutes: minutes => `كل ${minutes} د`,
- heartbeatEveryHours: hours => `كل ${hours} س`,
- heartbeatEverySeconds: seconds => `كل ${seconds} ث`,
- heartbeatNext: time => `التالي ${time}`,
- heartbeatActions: 'إجراءات النبض',
- pauseHeartbeat: 'إيقاف النبض مؤقتاً',
- resumeHeartbeat: 'استئناف النبض',
- clearHeartbeat: 'مسح النبض',
- clearHeartbeatConfirmTitle: 'مسح النبض؟',
- clearHeartbeatConfirmBody: 'هل أنت متأكد من رغبتك في مسح هذا النبض؟',
- heartbeatFiredCount: count => `انطلق ${count} مرة`,
- actionFailed: msg => `فشل الإجراء: ${msg}`,
- actionSucceeded: 'تم الإجراء بنجاح',
- copySuccess: 'تم نسخ المعيار إلى الحافظة',
- copyFailure: 'فشل نسخ المعيار إلى الحافظة',
- continuationFailed: 'فشل إرسال متابعة الهدف',
- continuationQueued: 'تم استئناف الهدف — المتابعة في قائمة الانتظار حتى انتهاء الدور الحالي',
- continuationBusy: 'تم استئناف الهدف — الجلسة مشغولة، أوقف الرد الحالي أولاً (زر الإيقاف أو Esc) للمتابعة',
- controlUnavailable: msg => `عناصر تحكم الجلسة غير متاحة: ${msg}`,
- dismissError: 'تجاهل الخطأ',
- add: 'إضافة'
- },
- coding: {
- title: 'شجرة العمل',
- noBranch: 'لا يوجد فرع',
- detached: 'منفصل',
- clean: 'نظيف',
- changed: count => `${count} مُغيَّر`,
- ahead: count => `${count} متقدم`,
- behind: count => `${count} متأخر`,
- review: 'مراجعة',
- close: 'إغلاق',
- openChanges: 'فتح التغييرات',
- openFile: 'فتح الملف',
- stage: 'إدراج',
- unstage: 'إلغاء الإدراج',
- stageAll: 'إدراج الكل',
- viewAsTree: 'عرض كشجرة',
- viewAsList: 'عرض كقائمة',
- revert: 'تراجع',
- revertAll: 'التراجع عن الكل',
- revertConfirm: 'هل تريد تجاهل التغييرات على هذا الملف واستعادته إلى الحالة المُودعة؟ لا يمكن التراجع عن هذا.',
- revertAllConfirm: 'هل تريد تجاهل كل التغييرات واستعادة الملفات إلى الحالة المُودعة؟ لا يمكن التراجع عن هذا.',
- staged: 'مُدرَج',
- noChanges: 'لا توجد تغييرات',
- notRepo: 'ليس مستودع git',
- noDiff: 'لا يوجد فرق لعرضه',
- scopeUncommitted: 'غير مُودَع',
- scopeBranch: 'فرع',
- scopeLastTurn: 'آخر دور',
- commit: 'إيداع',
- commitAndPush: 'إيداع ودفع',
- commitPlaceholder: shortcut => `رسالة (${shortcut} للإيداع)`,
- generateCommitMessage: 'توليد رسالة الإيداع',
- stopGenerating: 'إيقاف التوليد',
- createPr: 'إنشاء PR',
- openPr: 'فتح PR',
- ghMissing: 'ثبّت GitHub CLI (gh) وسجّل الدخول لفتح طلبات السحب',
- agentShip: 'اطلب من Hermes فتح PR',
- agentShipUnavailable: 'المحادثة التي تملك هذه التغييرات ليست على الشاشة.',
- agentShipPrompt: 'راجع التغييرات الحالية، وأودعها برسالة إيداع تقليدية واضحة، وادفع الفرع، وافتح طلب سحب.',
- newBranch: 'فرع جديد',
- branchOffFrom: base => `فرع جديد من ${base}`,
- switchTo: branch => `التبديل إلى ${branch}`,
- switchFailed: branch => `تعذّر التبديل إلى ${branch}`,
- worktrees: 'أشجار العمل'
- }
- },
- updates: {
- discontinuedTitle: 'لم يعد إصدار Hermes هذا مدعومًا',
- discontinuedBody: 'لم يعد إصدار Hermes هذا مدعومًا وقد يتوقف عن العمل — ألغِ تثبيته. ستبقى بياناتك على القرص.',
- channels: { stable: 'مستقر', canary: 'تجريبي' },
- bundleSwapPending: 'أعد التشغيل لإكمال التحديث',
- bundleSwapPendingDesc:
- 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',
- bundleSwapPendingAction: 'إعادة تشغيل Hermes',
- stages: {
- idle: 'جار التحضير...',
- prepare: 'جار التحضير...',
- fetch: 'جار التنزيل...',
- pull: 'أوشكنا على الانتهاء...',
- pydeps: 'جار الإنهاء...',
- update: 'جار تحديث Hermes...',
- rebuild: 'جار إعادة بناء تطبيق سطح المكتب...',
- restart: 'جار إعادة تشغيل Hermes...',
- done: 'اكتمل التحديث',
- manual: 'التحديث من الطرفية',
- guiSkew: 'تحديث تطبيق سطح المكتب',
- error: 'تم إيقاف التحديث مؤقتا'
- },
- checking: 'جار البحث عن تحديثات...',
- checkFailedTitle: 'تعذّر التحقق من التحديثات',
- tryAgain: 'إعادة المحاولة',
- notAvailableTitle: 'التحديث غير متاح',
- unsupportedMessage: 'لا يمكن لهذا الإصدار من Hermes تحديث نفسه من داخل التطبيق.',
- appName: 'Hermes Desktop',
- version: value => `الإصدار ${value}`,
- versionUnavailable: 'الإصدار غير متاح',
- bundleOutOfSync: 'إصدار التطبيق قديم',
- bundleOutOfSyncDesc:
- 'تم تحديث وقت تشغيل Hermes، لكن تطبيق سطح المكتب نفسه لا يزال إصدارًا قديمًا — لن تظهر ميزات الواجهة الجديدة (مثل Bot Mode) حتى يتم تحديث التطبيق. شغّل التحديث أدناه لإعادة بناء التطبيق. إذا لم يختفِ هذا التحذير، فأعد التثبيت من أحدث مثبّت لسطح المكتب.',
- bundleOutOfSyncAction: 'الحصول على المثبّت',
- checkNow: 'التحقق الآن',
- checkingShort: 'جار التحقق...',
- seeWhatsNew: 'عرض الجديد',
- releaseNotes: 'ملاحظات الإصدار',
- onLatest: 'أنت على أحدث إصدار',
- installing: 'جار التثبيت...',
- cantReach: 'تعذر الوصول لخدمة التحديث',
- tapCheck: 'اضغط للتحقق من التحديثات.',
- updateReady: count => `${count} تحديث متاح`,
- updateReadyUnknown: 'تحديث جديد جاهز.',
- lastChecked: age => `آخر تحقق ${age}`,
- justNowSuffix: 'الآن',
- never: 'أبدا',
- justNow: 'الآن',
- minAgo: count => `قبل ${count} دقيقة`,
- hoursAgo: count => `قبل ${count} ساعة`,
- daysAgo: count => `قبل ${count} يوم`,
- versionDetailsTitle: 'تفاصيل الإصدار',
- versionDetailsBody: 'هذا التثبيت مُدار خارج التطبيق. حدّثه بالطريقة نفسها التي استخدمتها لتثبيته.',
- versionDetailsVersion: 'الإصدار',
- versionDetailsCommit: 'الالتزام',
- versionDetailsBuildOrigin: 'مصدر البناء',
- versionDetailsDistribution: 'التوزيع',
- versionDetailsDistributionDesktop: 'تطبيق سطح المكتب',
- versionDetailsDistributionDesktopMsix: 'تطبيق سطح المكتب (MSIX)',
- versionDetailsDistributionDesktopInstaller: 'تطبيق سطح المكتب (المُثبِّت)',
- versionDetailsDistributionSourceInstaller: 'المصدر (سكربت التثبيت)',
- versionDetailsDistributionSourceInstallerDesktop: 'المصدر (سكربت التثبيت) + hermes desktop',
- versionDetailsDistributionSource: 'المصدر',
- versionDetailsDistributionSourceDesktop: 'المصدر + hermes desktop',
- versionDetailsDistributionStore: 'Microsoft Store',
- versionDetailsRuntimeEmbedded: 'وقت تشغيل مضمّن',
- versionDetailsRuntimeExternal: 'خارجي (يستخدم وقت تشغيل الجهاز)',
- versionDetailsRuntime: 'وقت التشغيل',
- versionDetailsInstallId: 'معرّف التثبيت',
- versionDetailsUncommittedChanges: '(+ تغييرات غير ملتزمة)',
- connectionRetry: 'تحقق من اتصالك وأعد المحاولة.',
- gitUnusable: 'لم يتمكن Hermes من تشغيل Git على هذا الجهاز، لذا لم يتمكن من التحقق من التحديثات.',
- latestBody: 'أنت تستخدم أحدث إصدار.',
- latestBodyBackend: 'الواجهة الخلفية تعمل بأحدث إصدار.',
- allSetTitle: 'كل شيء جاهز',
- availableTitle: 'يتوفر تحديث جديد',
- availableBody: 'إصدار جديد من Hermes جاهز للتثبيت.',
- availableTitleBackend: 'يتوفر تحديث للواجهة الخلفية',
- availableBodyBackend: 'إصدار أحدث من واجهة Hermes الخلفية المتصلة جاهز للتثبيت.',
- availableBodyNoChangelog: 'إصدار أحدث جاهز. ملاحظات الإصدار غير متاحة لنوع التثبيت هذا.',
- availableBodyRelease: (tag: string) => `Hermes ${tag} جاهز للتثبيت.`,
- updateNow: 'التحديث الآن',
- maybeLater: 'ربما لاحقا',
- moreChanges: count => `+ ${count} تغيير${count === 1 ? '' : 'ات'} إضافي مُضمَّن.`,
- manualTitle: 'التحديث من الطرفية',
- manualUnavailableTitle: 'لا يمكن التحديث من هنا',
- manualBody: 'لقد ثبّتت Hermes من سطر الأوامر، لذا تُجرى التحديثات من هناك أيضا. الصق هذا في طرفيتك:',
- manualBodyBackend: 'تتم إدارة خادم Hermes خارج هذا التطبيق. نفّذ هذا الأمر على الخادم الذي يستضيفه:',
- manualPickedUp: 'سيلتقط Hermes الإصدار الجديد في المرة التالية التي تشغّله فيها.',
- manualPickedUpBackend: 'سيحمّل الخادم الإصدار الجديد بعد اكتمال التحديث.',
- guiSkewTitle: 'تحديث تطبيق سطح المكتب',
- guiSkewBody:
- 'تم تحديث الواجهة الخلفية، لكن حزمة تطبيق سطح المكتب هذه لم تتغير. حدّث أو أعد تثبيت تطبيق Hermes لسطح المكتب (ملف AppImage / ‎.deb / ‎.rpm) لمطابقته.',
- copy: 'نسخ',
- copied: 'تم النسخ',
- done: 'تم',
- applyingBody:
- 'يتولّى مُحدِّث Hermes المهمة في نافذته الخاصة ويعيد فتح Hermes تلقائيا عند الانتهاء. الرجاء عدم إعادة فتح Hermes بنفسك أثناء التحديث.',
- applyingBodyBackend:
- 'تطبّق الواجهة الخلفية البعيدة التحديث وستعيد التشغيل. يعيد Hermes الاتصال تلقائيا عند عودتها.',
- applyingClose: 'ستُغلق هذه النافذة أثناء تشغيل التحديث، ثم يعيد Hermes فتح نفسه تلقائيا.',
- errorTitle: 'لم يكتمل التحديث',
- errorBody: 'لا داعي للقلق — لم يُفقد شيء. يمكنك إعادة المحاولة الآن.',
- blockerTitle: 'إغلاق المعاينات المحلية لتحديث Hermes؟',
- blockerBody: 'يحتاج Hermes إلى إيقاف هذه المعاينات المحلية قبل التحديث. لن يؤدي ذلك إلى تعديل ملفاتك أو حذفها.',
- foreignBlockerTitle: 'أغلق العمليات الأخرى لتحديث Hermes',
- foreignBlockerBody:
- 'لا يمكن لـ Hermes إغلاق هذه العمليات تلقائيًا بأمان. أغلق التطبيق أو الطرفية أو الخدمة التي تشغّل كل عملية، ثم حاول التحديث مرة أخرى.',
- mixedBlockerBody:
- 'يمكن لـ Hermes إغلاق المعاينات المحلية المدرجة أدناه. يجب إغلاق العمليات الأخرى يدويًا قبل متابعة التحديث.',
- closePreviewsAndUpdate: 'إغلاق المعاينات والتحديث',
- closePreviewsAndCheckAgain: 'إغلاق المعاينات والتحقق مجددًا',
- localPreview: 'معاينة محلية',
- portLabel: port => `المنفذ ${port}`,
- pidLabel: pid => `معرّف العملية ${pid}`,
- technicalDetails: 'التفاصيل التقنية',
- notNow: 'ليس الآن',
- clientAlsoBehindTitle: 'تطبيق سطح المكتب متأخر',
- clientAlsoBehindMessage:
- 'الخادم الخلفي محدث، لكن تطبيق سطح المكتب هذا لا يزال على إصدار أقدم. حدّثه للحصول على أحدث الإصلاحات.',
- clientAlsoBehindAction: 'تحديث تطبيق سطح المكتب',
- everythingDispatched: 'تم إرسال التحديث',
- everythingSkipped: 'تم التخطي',
- everythingRowFailed: 'فشل التحديث',
- everythingFanoutFailedTitle: 'تعذر تحديث المثيلات الأخرى',
- changeLogNew: 'جديد',
- changeLogFixed: 'إصلاحات',
- changeLogFaster: 'أسرع',
- changeLogImproved: 'تحسينات',
- changeLogOther: 'تحسينات أخرى',
- changeLogFallbackLabel: 'في هذا التحديث',
- changeLogFallbackItem: 'تحسينات وإصلاحات',
- applyStatus: {
- preparing: 'جار تحديث الواجهة الخلفية...',
- pulling: 'جار تحديث الواجهة الخلفية...',
- restarting: 'تعيد الواجهة الخلفية التشغيل لتحميل التحديث...',
- notAvailable: 'التحديث غير متاح لهذه الواجهة الخلفية.',
- failed: 'فشل تحديث الواجهة الخلفية.',
- noReturn: 'لم تعد الواجهة الخلفية إلى الاتصال. قد لا يكون التحديث قد اكتمل — تحقق من مضيف الواجهة الخلفية.'
- }
- },
- guidedGreeting: {
- line: 'أهلا، تفضل بالدخول. أنا Hermes. امنحني دقيقتين لأرتب المكان حولك، ثم نبدأ بشيء تريد إنجازه فعلا.\n\nبداية، بماذا أناديك؟',
- nameSuggestion: (name: string) => `(يمكنني أن أناديك ${name} إن كنت تفضل ذلك.)`
- },
- install: {
- stageStates: {
- pending: 'قيد الانتظار',
- running: 'جار التثبيت',
- succeeded: 'تم',
- skipped: 'تم التخطي',
- failed: 'فشل'
- },
- oneTimeTitle: 'يحتاج Hermes إلى تثبيت لمرة واحدة',
- unsupportedDesc: platform =>
- `التثبيت التلقائي عند أول تشغيل غير متاح على ${platform} بعد. افتح الطرفية وشغّل الأمر أدناه، ثم أعد تشغيل هذا التطبيق. ستتخطى عمليات التشغيل اللاحقة هذه الخطوة.`,
- installCommand: 'أمر التثبيت',
- copyCommand: 'نسخ الأمر',
- viewDocs: 'عرض مستندات التثبيت',
- installTo: 'سيتم التثبيت في',
- retryAfterRun: 'لقد شغّلته -- إعادة المحاولة',
- failedTitle: 'فشل التثبيت',
- settingUpTitle: 'جار إعداد وكيل Hermes',
- finishingTitle: 'جار الإنهاء',
- failedDesc:
- 'فشلت إحدى خطوات التثبيت. على Windows، قد يحدث هذا إذا كان هناك نسخة أخرى من Hermes CLI أو تطبيق سطح المكتب قيد التشغيل. أوقف أي نسخ Hermes قيد التشغيل، ثم أعد المحاولة. تحقق من التفاصيل أدناه أو من سجل سطح المكتب للحصول على النص الكامل.',
- activeDesc:
- 'هذا إعداد لمرة واحدة. يقوم مثبّت Hermes بتنزيل التبعيات وتهيئة جهازك. ستتخطى عمليات التشغيل اللاحقة هذه الخطوة.',
- progress: (completed, total) => `اكتملت ${completed} من ${total} خطوة`,
- currentStage: stage => ` -- الآن: ${stage}`,
- fetchingManifest: 'جار جلب بيان المثبّت...',
- error: 'خطأ',
- hideOutput: 'إخفاء مخرجات المثبّت',
- showOutput: 'إظهار مخرجات المثبّت',
- lines: count => `${count} سطر`,
- noOutput: 'لا توجد مخرجات بعد.',
- cancelling: 'جار الإلغاء...',
- cancelInstall: 'إلغاء التثبيت',
- transcriptSaved: 'تم حفظ النص الكامل في',
- copiedOutput: 'تم النسخ!',
- copyOutput: 'نسخ المخرجات',
- reloadRetry: 'إعادة التحميل وإعادة المحاولة'
- },
- onboarding: {
- headerTitle: 'لنُعِدّ لك Hermes Agent',
- headerDesc: 'اربط مزوّد نماذج لبدء المحادثة. معظم الخيارات تتطلب نقرة واحدة.',
- preparingInstall: 'يُكمل Hermes التثبيت. عادة ما يستغرق ذلك أقل من دقيقة في أول تشغيل.',
- starting: 'جار بدء Hermes...',
- lookingUpProviders: 'جار البحث عن المزوّدين...',
- collapse: 'طي',
- otherProviders: 'مزودون آخرون',
- haveApiKey: 'لديك مفتاح API',
- chooseLater: 'سأختار مزوّدا لاحقا',
- recommended: 'موصى به',
- connected: 'متصل',
- featuredPitch: 'اشتراك واحد، أكثر من 300 نموذج متقدم — الطريقة الموصى بها لتشغيل Hermes',
- fireworksPitch: 'نماذج مفتوحة سريعة مع استضافة Fireworks.',
- openRouterPitch: 'مفتاح واحد لمئات النماذج — خيار افتراضي جيد',
- apiKeyOptions: {
- openrouter: {
- short: 'مفتاح واحد، نماذج كثيرة',
- description: 'يستضيف مئات النماذج خلف مفتاح واحد. خيار افتراضي جيد للتثبيتات الجديدة.'
- },
- openai: {
- short: 'نماذج من فئة GPT',
- description: 'وصول مباشر إلى نماذج OpenAI.'
- },
- gemini: {
- short: 'نماذج Gemini',
- description: 'وصول مباشر إلى نماذج Google Gemini.'
- },
- xai: {
- short: 'نماذج Grok',
- description: 'وصول مباشر إلى نماذج xAI Grok.'
- },
- local: {
- short: 'مستضاف ذاتيا',
- description:
- 'وجّه Hermes إلى نقطة نهاية محلية أو مستضافة ذاتيا متوافقة مع OpenAI (vLLM، llama.cpp، Ollama، إلخ).'
- }
- },
- backToSignIn: 'العودة إلى تسجيل الدخول',
- getKey: 'الحصول على مفتاح',
- replaceCurrent: 'استبدال القيمة الحالية',
- pasteApiKey: 'ألصق مفتاح API',
- localApiKeyPlaceholder: 'مفتاح API (اختياري — فقط إذا كانت نقطة النهاية تتطلبه)',
- couldNotSave: 'تعذر حفظ بيانات الاعتماد.',
- connecting: 'جار الاتصال',
- update: 'تحديث',
- flowSubtitles: {
- pkce: 'يفتح المتصفح لتسجيل الدخول ثم يتابع هنا',
- device_code: 'يفتح صفحة تحقق في المتصفح — يتصل Hermes تلقائياً',
- external: 'سجل الدخول مرة واحدة في الطرفية ثم عد إلى المحادثة'
- },
- startingSignIn: provider => `جار بدء تسجيل الدخول لـ ${provider}...`,
- verifyingCode: provider => `جار التحقق من الرمز عبر ${provider}...`,
- connectedProvider: provider => `تم ربط ${provider}`,
- connectedPicking: provider => `تم ربط ${provider}. جار اختيار نموذج افتراضي...`,
- signInFailed: 'فشل تسجيل الدخول. حاول مرة أخرى.',
- signInExpired:
- 'انتهت مهلة انتظار التفويض. السبب الأكثر شيوعًا هو تعطّل صفحة تسجيل الدخول في تبويب المتصفح (مشكلة من جهة الخادم) — أكمل تسجيل الدخول هناك ثم أعد المحاولة. إذا استمر الفشل، استخدم مفتاح API أو واجهة سطر الأوامر بدلاً من ذلك.',
- pickDifferentProvider: 'اختر مزوداً آخر',
- signInWith: provider => `تسجيل الدخول عبر ${provider}`,
- openedBrowser: provider => `فتحنا ${provider} في المتصفح.`,
- authorizeThere: 'صرّح لـ Hermes هناك.',
- copyAuthCode: 'انسخ رمز التفويض وألصقه أدناه.',
- pasteAuthCode: 'ألصق رمز التفويض',
- reopenAuthPage: 'إعادة فتح صفحة التفويض',
- autoBrowser: provider => `فتحنا ${provider} في المتصفح. صرّح لـ Hermes هناك وسيتم الاتصال تلقائياً دون نسخ أو لصق.`,
- reopenSignInPage: 'إعادة فتح صفحة تسجيل الدخول',
- waitingAuthorize: 'بانتظار التفويض...',
- externalPending: provider =>
- `${provider} يسجل الدخول عبر أداة سطر الأوامر الخاصة به. شغّل هذا الأمر في الطرفية، ثم عد واختر "سجلت الدخول":`,
- signedIn: 'سجلت الدخول',
- deviceCodeOpened: provider => `فتحنا ${provider} في المتصفح. أدخل هذا الرمز هناك:`,
- reopenVerification: 'إعادة فتح صفحة التحقق',
- copy: 'نسخ',
- defaultModel: 'النموذج الافتراضي',
- freeTier: 'الطبقة المجانية',
- pro: 'مدفوع',
- free: 'مجاني',
- price: (input, output) => `${input} إدخال / ${output} إخراج لكل مليون رمز`,
- change: 'تغيير',
- startChatting: 'ابدأ',
- docs: provider => `وثائق ${provider}`
- },
- modelPicker: {
- title: 'اختيار النموذج',
- current: 'الحالي',
- unknown: 'غير معروف',
- search: 'البحث عن نموذج...',
- noModels: 'لا توجد نماذج',
- addProvider: 'إضافة مزود',
- loadFailed: 'فشل تحميل النماذج',
- noAuthenticatedProviders: 'لا توجد مزودات مصادق عليها',
- pro: 'Pro',
- proNeedsSubscription: 'يتطلب اشتراكا',
- free: 'مجاني',
- freeTier: 'طبقة مجانية',
- priceTitle: 'السعر',
- customModel: 'نموذج مخصص',
- addCustomModelAction: 'إضافة نموذج مخصص…',
- customModelPlaceholder: 'اكتب معرّف النموذج، مثل openai/gpt-5'
- },
- modelVisibility: {
- title: 'النماذج',
- search: 'بحث في النماذج',
- noAuthenticatedProviders: 'لا يوجد مزوّدون مصادق عليهم.',
- addProvider: 'إضافة مزوّد…',
- addCustomModel: 'إضافة نموذج مخصص',
- removeCustomModel: 'إزالة النموذج المخصص'
- },
- shell: {
- windowControls: 'تحكم النافذة',
- paneControls: 'تحكم اللوحات',
- appControls: 'تحكم التطبيق',
- modelMenu: {
- search: 'البحث عن نموذج...',
- noModels: 'لا توجد نماذج',
- editModels: 'تحرير النماذج',
- followDefault: 'استخدام الافتراضي من الإعدادات',
- refreshModels: 'تحديث النماذج',
- fast: 'سريع'
- },
- modelOptions: {
- noOptions: 'لا توجد خيارات لهذا النموذج',
- options: 'الخيارات',
- thinking: 'التفكير',
- fast: 'سريع',
- effort: 'الجهد',
- minimal: 'أدنى',
- low: 'منخفض',
- medium: 'متوسط',
- high: 'عالٍ',
- max: 'أقصى',
- sendsOnRoute: (level: string) => `يُرسل ${level} على هذا المسار`,
- updateFailed: 'فشل تحديث خيار النموذج',
- fastFailed: 'فشل تحديث الوضع السريع'
- },
- gatewayMenu: {
- gateway: 'البوابة',
- connected: 'متصل',
- connecting: 'جار الاتصال',
- offline: 'غير متصل',
- inferenceReady: 'الاستدلال جاهز',
- inferenceNotReady: 'الاستدلال غير جاهز',
- checkingInference: 'جار فحص الاستدلال',
- disconnected: 'منقطع',
- reconnectGateway: 'إعادة الاتصال بالبوابة',
- openSystem: 'فتح النظام',
- connection: label => `الاتصال: ${label}`,
- recentActivity: 'النشاط الأخير',
- viewAllLogs: 'عرض كل السجلات',
- messagingPlatforms: 'منصات المراسلة'
- },
- statusbar: {
- unknown: 'غير معروف',
- restart: 'إعادة تشغيل',
- update: 'تحديث',
- updateInProgress: 'التحديث جار',
- commitsBehind: (count, branch) => `${count} commits خلف ${branch}`,
- releaseAvailable: tag => `الإصدار ${tag} متاح`,
- desktopVersion: version => `سطح المكتب ${version}`,
- backendVersion: version => `الخلفية ${version}`,
- clientLabel: version => `العميل ${version}`,
- backendLabel: version => `الخلفية ${version}`,
- commit: sha => `commit ${sha}`,
- branch: branch => `الفرع ${branch}`,
- closeCommandCenter: 'إغلاق مركز الأوامر',
- openCommandCenter: 'فتح مركز الأوامر',
- showTerminal: 'إظهار الطرفية',
- hideTerminal: 'إخفاء الطرفية',
- gateway: 'البوابة',
- gatewayReady: 'البوابة جاهزة',
- gatewayNeedsSetup: 'البوابة تحتاج إعدادا',
- gatewayUnavailable: 'الاستدلال غير متاح',
- gatewayChecking: 'جار فحص البوابة',
- gatewayConnecting: 'جار اتصال البوابة',
- gatewayOffline: 'البوابة غير متصلة',
- gatewayRestarting: 'جار إعادة التشغيل...',
- gatewayTitle: 'البوابة',
- agents: 'الوكلاء',
- closeAgents: 'إغلاق الوكلاء',
- openAgents: 'فتح الوكلاء',
- subagents: count => `${count} وكيل فرعي`,
- failed: count => `${count} فشل`,
- running: count => `${count} يعمل`,
- cron: 'المهام',
- openCron: 'فتح المهام المجدولة',
- turnRunning: 'الدور يعمل',
- contextUsage: 'استخدام السياق',
- focusedSince: 'منذ التركيز',
- focusedSinceTitle: 'الوقت منذ تركيز هذه المحادثة — وليس مدة الدور',
- yoloOn: 'YOLO مفعل',
- yoloOff: 'YOLO معطل',
- modelNone: 'لا نموذج',
- noModel: 'لا يوجد نموذج',
- switchModel: 'تبديل النموذج',
- openModelPicker: 'فتح اختيار النموذج',
- modelPinned: 'النموذج مثبت',
- modelTitle: (provider, model) => `${provider}: ${model}`,
- providerModelTitle: (provider, model) => `${provider}: ${model}`
- }
- },
- rightSidebar: {
- aria: 'الشريط الجانبي الأيمن',
- panelsAria: 'لوحات الشريط الأيمن',
- files: 'الملفات',
- terminal: 'الطرفية',
- noFolderSelected: 'لم يتم اختيار مجلد',
- changeCwdTitle: 'تغيير مجلد العمل',
- remotePickerTitle: 'اختر مجلدا بعيدا',
- remotePickerDescription: 'استعرض المجلدات على الخادم الخلفي المتصل.',
- remotePickerSelect: 'تحديد المجلد',
- remotePickerNewFolder: 'مجلد جديد',
- remotePickerFolderName: 'اسم المجلد',
- remotePickerCreateFolder: 'إنشاء المجلد',
- remotePickerInvalidFolderName: 'أدخل اسم مجلد واحد بدون شرطات مائلة.',
- remotePickerCreateFolderFailed: error => `تعذر إنشاء المجلد: ${error}`,
- folderTip: cwd => cwd,
- openFolder: 'فتح مجلد',
- refreshTree: 'تحديث الشجرة',
- collapseAll: 'طي الكل',
- showIgnored: 'إظهار الملفات المتجاهلة في git',
- hideIgnored: 'إخفاء الملفات المتجاهلة في git',
- previewUnavailable: 'المعاينة غير متاحة',
- couldNotPreview: path => `تعذرت معاينة ${path}`,
- noProjectTitle: 'لا يوجد مشروع',
- noProjectBody: 'اختر مجلد عمل لعرض الملفات.',
- noProjectOpen: 'لا يوجد مشروع مفتوح',
- noDiffs: 'لا توجد فروقات',
- unreadableTitle: 'تعذر قراءة المجلد',
- unreadableBody: error => `السبب: ${error}`,
- emptyTitle: 'المجلد فارغ',
- emptyBody: 'لا توجد ملفات للعرض.',
- treeErrorTitle: 'فشل تحميل شجرة الملفات',
- treeErrorBody: 'حاول التحديث أو اختر مجلدا آخر.',
- tryAgain: 'حاول مرة أخرى',
- loadingTree: 'جار تحميل الشجرة...',
- loadingFiles: 'جار تحميل الملفات...',
- terminalHide: 'إخفاء الطرفية',
- addToChat: 'إضافة للمحادثة'
- },
- preview: {
- tab: 'معاينة',
- closePane: 'إغلاق جزء المعاينة',
- loading: 'جار تحميل المعاينة',
- unavailable: 'المعاينة غير متاحة',
- opening: 'جار الفتح...',
- hide: 'إخفاء',
- openPreview: 'فتح المعاينة',
- openInBrowser: 'فتح في المتصفح',
- openInExternal: 'فتح في الخارج',
- popIn: 'إدخال',
- popOut: 'إخراج',
- linkHint: '⌘/Ctrl-نقر لجزء المعاينة',
- sourceLineTitle: 'انقر للتحديد · shift-نقر للتوسيع · اسحب إلى المُنشئ',
- source: 'المصدر',
- renderedPreview: 'المعاينة',
- diff: 'الفرق',
- unknownSize: 'حجم غير معروف',
- binaryTitle: 'يبدو هذا ملفا ثنائيا',
- binaryBody: label => `قد تعرض معاينة ${label} نصا غير قابل للقراءة.`,
- largeTitle: 'هذا الملف كبير',
- largeBody: (label, size) => `حجم ${label} هو ${size}. سيعرض Hermes أول 512 KB فقط.`,
- previewAnyway: 'معاينة على أي حال',
- truncated: 'عرض أول 512 KB.',
- noInlineTitle: 'لا توجد معاينة مضمّنة',
- noInlineBody: mimeType => `${mimeType || 'هذا النوع من الملفات'} لا يزال بالإمكان إرفاقه كسياق.`,
- edit: 'تحرير',
- editing: 'جار التحرير',
- unsavedChanges: 'تغييرات غير محفوظة',
- saveFailed: message => `تعذّر الحفظ: ${message}`,
- diskChangedTitle: 'تغيّر الملف على القرص',
- diskChangedBody: 'تغيّر هذا الملف منذ أن فتحته. هل تريد الكتابة فوقه بنسختك، أم تجاهل تعديلاتك وإعادة التحميل؟',
- overwrite: 'الكتابة فوقه',
- discardReload: 'تجاهل وإعادة التحميل',
- console: {
- deselect: 'إلغاء تحديد الإدخال',
- select: 'تحديد الإدخال',
- copyFailed: 'تعذّر نسخ مخرجات الكونسول',
- copyEntry: 'نسخ هذا الإدخال',
- sendEntry: 'إرسال هذا الإدخال إلى المحادثة',
- messages: count => `${count} رسائل كونسول`,
- resize: 'تغيير حجم كونسول المعاينة',
- title: 'كونسول المعاينة',
- selected: count => `${count} محدد`,
- sendToChat: 'إرسال إلى المحادثة',
- copySelected: 'نسخ المحدد إلى الحافظة',
- copyAll: 'نسخ الكل إلى الحافظة',
- copy: 'نسخ',
- clear: 'مسح',
- empty: 'لا توجد رسائل كونسول بعد.',
- promptHeader: 'كونسول المعاينة:',
- sentTitle: 'تم الإرسال إلى المحادثة',
- sentMessage: count => `أُضيف ${count} ${count === 1 ? 'إدخال سجل' : 'إدخالات سجل'} إلى المُنشئ`
- },
- web: {
- appFailedToBoot: 'فشل إقلاع تطبيق المعاينة',
- serverNotFound: 'الخادم غير موجود',
- remoteLoopback:
- 'يشير هذا العنوان إلى الجهاز الذي يشغّل الوكيل، وليس هذا الجهاز. تحمّل لوحة المتصفح الصفحات محليًا، لذا يحتاج خادم التطوير البعيد إلى إعادة توجيه منفذ أو اسم مضيف يمكن الوصول إليه.',
- failedToLoad: 'فشل تحميل المعاينة',
- tryAgain: 'إعادة المحاولة',
- restarting: 'جار إعادة تشغيل Hermes...',
- askRestart: 'اطلب من Hermes إعادة تشغيل الخادم',
- lookingRestart: taskId => `يبحث Hermes عن خادم معاينة لإعادة تشغيله (${taskId})`,
- restartingTitle: 'جار إعادة تشغيل خادم المعاينة',
- restartingMessage: 'يعمل Hermes في الخلفية. راقب كونسول المعاينة لمتابعة التقدم.',
- startRestartFailed: message => `تعذّر بدء إعادة تشغيل الخادم: ${message}`,
- restartFailed: 'فشلت إعادة تشغيل الخادم',
- hideConsole: 'إخفاء كونسول المعاينة',
- showConsole: 'إظهار كونسول المعاينة',
- hideDevTools: 'إخفاء DevTools المعاينة',
- openDevTools: 'فتح DevTools المعاينة',
- goBack: 'رجوع',
- goForward: 'تقدم',
- reload: 'إعادة تحميل الصفحة',
- address: 'العنوان',
- addressPlaceholder: 'أدخل العنوان',
- blankPageBody: 'اكتب عنوانًا في الأعلى للتصفح، أو اطلب من Hermes فتح صفحة.',
- finishedRestarting: message => `أنهى Hermes إعادة تشغيل خادم المعاينة${message ? `: ${message}` : ''}`,
- failedRestarting: message => `فشلت إعادة تشغيل الخادم: ${message}`,
- unknownError: 'خطأ غير معروف',
- restartedTitle: 'تمت إعادة تشغيل خادم المعاينة',
- reloadingNow: 'جار إعادة تحميل المعاينة الآن.',
- restartFailedTitle: 'فشلت إعادة تشغيل المعاينة',
- restartFailedMessage: 'تعذّر على Hermes إعادة تشغيل الخادم.',
- stillWorking:
- 'لا يزال Hermes يعمل، لكن لم تصل نتيجة إعادة التشغيل بعد. قد يكون أمر الخادم قيد التشغيل في المقدمة.',
- workspaceReloading: 'تغيّرت مساحة العمل، جار إعادة تحميل المعاينة',
- fileChanged: url => `تغيّر الملف، جار إعادة تحميل المعاينة: ${url}`,
- filesChanged: (count, url) => `${count} تغييرات ملفات، جار إعادة تحميل المعاينة: ${url}`,
- watchFailed: message => `تعذّر مراقبة ملف المعاينة: ${message}`,
- moduleMimeDescription:
- 'يتم تقديم نصوص الوحدات بنوع MIME خاطئ. عادة ما يعني هذا أن خادم ملفات ثابتة يقدّم تطبيق Vite/React بدلا من خادم تطوير المشروع.',
- loadFailedConsole: (code, message) => `فشل التحميل${code ? ` (${code})` : ''}: ${message}`,
- unreachableDescription: 'تعذّر الوصول إلى صفحة المعاينة.',
- openTarget: url => `فتح ${url}`,
- fallbackTitle: 'معاينة'
- }
- },
- interfaceMode: {
- title: 'وضع الواجهة',
- hint: 'يغيّر ما يظهر، وليس ما يستطيع Hermes فعله.',
- sessionNote: 'يحدده الوضع البسيط. التغيير هنا يستمر لهذه الجلسة فقط؛ بدّل إلى المتقدم لجعله خيارك.',
- simple: {
- label: 'بسيط',
- description: 'للتحدث مع Hermes. الشريط الجانبي والدردشة؛ بلا طرفية أو لوحات ملفات أو فروقات.'
- },
- advanced: {
- label: 'متقدم',
- description: 'للمطورين. الطرفية والملفات والفروقات وشريط الحالة والتخطيطات، كما أعددتها.'
- }
- },
- zones: {
- showTabStrip: 'إظهار علامات التبويب',
- hideTabStrip: 'إخفاء علامات التبويب',
- showStripTab: title => `إظهار ${title}`,
- hideStripTab: title => `إخفاء ${title}`,
- lastTabKeptTitle: 'يبقى آخر تبويب',
- lastTabKeptBody:
- 'تحتاج هذه المنطقة إلى تبويب مرئي واحد على الأقل. أظهر تبويبا آخر أولا، أو اطو الشريط الجانبي بأكمله.',
- toggleStripTab: title => `تبديل تبويب ${title}`,
- minimize: 'تصغير',
- restore: 'استعادة',
- closeRunningTitle: 'إغلاق تبويب يعمل؟',
- closeRunningBody:
- 'هذه المحادثة ما زالت تعمل (أو تنتظر إدخالك). إغلاق التبويب يخفيها فقط — ستحتفظ الجلسة بتقدمها ويمكن إعادة فتحها من الشريط الجانبي.',
- closeRunningConfirm: 'إغلاق التبويب',
- reload: 'إعادة التحميل',
- closeOthers: 'إغلاق الأخرى',
- closeToRight: 'إغلاق ما على اليمين',
- closeAll: 'إغلاق الكل',
- pluginDisabled: pluginId => `الإضافة "${pluginId}" معطلة`,
- pluginDisabledBody: 'أعد تفعيلها من القدرات ← الإضافات لإرجاع اللوحة.',
- missingPane: paneId => `لوحة مفقودة: ${paneId}`,
- editTitle: 'التخطيطات',
- editHint: 'اختر تخطيطا، أو اسحب اللوحات بين المناطق.',
- reset: 'إعادة ضبط',
- templates: 'القوالب',
- custom: 'مخصص',
- newGridLayout: 'تخطيط شبكة جديد',
- saveCurrentAs: 'حفظ الترتيب الحالي كقالب',
- nameLayoutPlaceholder: 'سم هذا التخطيط...',
- deletePreset: name => `حذف ${name}`,
- zoneEditorTitle: 'محرر المناطق',
- editorHintPre: 'انقر للتقسيم · ',
- editorHintPost: ' يعكس الخط · اسحب عبر المناطق للدمج · اسحب الحواف المشتركة لتغيير الحجم',
- templateColumns: 'أعمدة',
- templateRows: 'صفوف',
- templateGrid: 'شبكة',
- templatePriority: 'أولوية',
- zoneTag: index => `منطقة ${index}`,
- mergeZones: count => `دمج ${count} مناطق`,
- customZoneName: count => `مخصص من ${count} مناطق`,
- layoutNamePlaceholder: fallback => `اسم التخطيط (${fallback})`,
- saveApply: 'حفظ وتطبيق',
- notExpressible: 'هذا الترتيب متشابك — لا يمكن تمثيله كتقسيمات متداخلة بعد',
- zoneCount: count => `${count} مناطق`,
- tabCount: count => `${count} تبويبات`
- },
- contextMenu: {
- link: {
- openInApp: 'فتح في متصفح التطبيق',
- openExternal: 'فتح في المتصفح الخارجي',
- copyUrl: 'نسخ الرابط',
- copyResolvedUrl: 'نسخ الرابط المُحلَّل'
- },
- image: {
- copyImage: 'نسخ الصورة',
- copyImageAddress: 'نسخ عنوان الصورة',
- saveImageAs: 'حفظ الصورة باسم…'
- },
- edit: {
- cut: 'قص',
- paste: 'لصق',
- selectAll: 'تحديد الكل',
- addToDictionary: 'إضافة إلى القاموس'
- },
- page: {
- copyPageUrl: 'نسخ رابط الصفحة',
- inspectElement: 'فحص العنصر'
- }
- },
- assistant: {
- catalogInstall: {
- preparing: 'جارٍ تجهيز التثبيت…',
- install: 'تثبيت',
- advanced: 'خيارات متقدمة',
- skip: 'تخطٍّ',
- installing: 'جارٍ التثبيت…',
- installed: 'مثبّت',
- notInstalled: 'غير مثبّت',
- failed: 'فشل',
- showNames: 'إظهار الأسماء',
- hideNames: 'إخفاء الأسماء',
- skill: name => `المهارة ${name}`,
- kind: { plugin: 'إضافة', skill: 'مهارة' },
- tier: { official: 'رسمي', community: 'مجتمعي' },
- targetProfile: profile => `يُثبَّت في ملفك الشخصي ${profile}`,
- sendFailed: 'تعذّر إرسال ردك. حاول مرة أخرى.',
- commitLabel: 'الإيداع',
- subdirLabel: 'المجلد',
- securityHeading: 'الأمان',
- scan: { passed: 'نجح الفحص', warnings: 'وجد الفحص تحذيرات', failed: 'فشل الفحص' },
- requirementsLabel: 'المتطلبات',
- credentialsHeading: 'بيانات الاعتماد'
- },
- thread: {
- loadingSession: 'جار تحميل الجلسة...',
- showEarlier: 'عرض الرسائل الأقدم',
- loadingResponse: 'جار تحميل الرد...',
- resumeWhenBackgroundDone: count =>
- count === 1 ? 'سيُستأنف عند انتهاء المهمة الخلفية' : `سيُستأنف عند انتهاء ${count} مهام خلفية`,
- thinking: 'يفكر...',
- thought: 'فكّر',
- thoughtBriefly: 'فكّر قليلاً',
- thoughtFor: duration => `فكّر لمدة ${duration}`,
- turnDuration: duration => `استغرقت هذه الجولة ${duration}`,
- today: time => `اليوم ${time}`,
- yesterday: time => `أمس ${time}`,
- copy: 'نسخ',
- refresh: 'تحديث',
- moreActions: 'إجراءات إضافية',
- branchNewChat: 'تفريع إلى محادثة جديدة',
- react: 'تفاعل',
- dismissError: 'تجاهل الخطأ',
- errorLayers: {
- auth: 'خطأ في المصادقة',
- billing: 'نفاد الرصيد',
- disk: 'القرص ممتلئ',
- endpoint: 'خطأ في نقطة النهاية المخصصة',
- gateway: 'خطأ في البوابة',
- generic: 'فشلت الجولة',
- provider: 'خطأ من المزوّد',
- runtime: 'خطأ في بيئة التشغيل المحلية',
- streaming: 'خطأ في اتصال البث'
- },
- errorRetry: 'إعادة المحاولة',
- errorLimitResets: time => `يُعاد ضبط الحد عند ${time}`,
- errorRetryAtReset: time => `إعادة المحاولة عند إعادة ضبط الحد (${time})`,
- errorRetryScheduled: (time, wait) => `ستتم إعادة المحاولة عند ${time} — بعد ${wait}`,
- errorRetryScheduledCancel: 'إلغاء',
- errorStartNewSession: 'بدء جلسة جديدة',
- errorSwitchProvider: 'تبديل المزوّد',
- errorSignInAgain: provider => `تسجيل الدخول إلى ${provider} مجدداً`,
- errorOauthExpired: provider =>
- `انتهت صلاحية تسجيل دخولك إلى ${provider} أو تم إلغاؤه. سجّل الدخول مجدداً لمتابعة المحادثة.`,
- errorOpenLogs: 'فتح السجلات',
- errorOpenLogsFailed: 'تعذّر فتح مجلد السجلات',
- errorOpenDesktopLogs: 'فتح سجلات سطح المكتب',
- errorCopyDiagnostics: 'نسخ تفاصيل الخطأ',
- errorSendDiagnostics: 'إرسال التشخيصات',
- filesChanged: count => `${count} ملفات تم تغييرها`,
- reviewChanges: 'مراجعة',
- readAloudFailed: 'فشلت القراءة بصوت عال',
- preparingAudio: 'جار تجهيز الصوت',
- stopReading: 'إيقاف القراءة',
- readAloud: 'قراءة بصوت عال',
- copyFullResponse: 'نسخ الرد الكامل',
- readAloudFullResponseHint: 'انقر مع الضغط على Shift: قراءة الرد الكامل بصوت عال',
- editMessage: 'تحرير الرسالة',
- scrollToBottom: 'التمرير إلى الأسفل',
- stop: 'إيقاف',
- restorePrevious: 'استعادة السابق',
- restoreCheckpoint: 'استعادة النقطة',
- restoreFromHere: 'استعادة نقطة التحقق — إعادة التشغيل من هذا الموجّه',
- restoreTitle: 'الاستعادة إلى نقطة التحقق هذه؟',
- restoreBody: 'يُزال كل ما يلي هذا الموجّه من المحادثة، ويُعاد تشغيل الموجّه من هنا.',
- restoreConfirm: 'استعادة وإعادة تشغيل',
- restoreNext: 'استعادة التالي',
- goForward: 'تقدم',
- sendEdited: 'إرسال التعديل',
- attachingFile: 'جار إرفاق الملف'
- },
- approval: {
- gatewayDisconnected: 'البوابة غير متصلة',
- sendFailed: 'فشل الإرسال',
- run: 'تشغيل',
- command: 'الأمر',
- moreOptions: 'خيارات إضافية',
- allowSession: 'السماح لهذه الجلسة',
- alwaysAllowMenu: 'السماح دائما',
- jumpToApproval: 'الموافقة مطلوبة',
- reject: 'رفض',
- alwaysTitle: 'السماح دائما',
- alwaysDescription: pattern => `السماح دائما بالأوامر المطابقة لـ ${pattern}`,
- alwaysAllow: 'السماح دائما'
- },
- clarify: {
- notReady: 'غير جاهز',
- gatewayDisconnected: 'البوابة غير متصلة',
- sendFailed: 'فشل الإرسال',
- loadingQuestion: 'جار تحميل السؤال...',
- other: 'غير ذلك',
- placeholder: 'اكتب إجابتك...',
- skip: 'تخطي',
- continueLabel: 'متابعة',
- confirmAndContinueLabel: 'تأكيد ومتابعة',
- answeredBadge: 'تمت الإجابة',
- questionProgress: (answered, total) => `تمت الإجابة على ${answered} من ${total}`
- },
- tool: {
- copyCode: 'نسخ الكود',
- renderingImage: 'جار عرض الصورة...',
- copyOutput: 'نسخ الإخراج',
- copyCommand: 'نسخ الأمر',
- copyContent: 'نسخ المحتوى',
- copyUrl: 'نسخ الرابط',
- copyResults: 'نسخ النتائج',
- copyQuery: 'نسخ الاستعلام',
- copyFile: 'نسخ الملف',
- copyPath: 'نسخ المسار',
- failedCalls: (count: number) => `عدد استدعاءات الأدوات الفاشلة: ${count}`,
- skillActivity: {
- loading: 'جارٍ تحميل المهارة',
- loaded: 'تم تحميل المهارة',
- loadFailed: 'تعذر تحميل المهارة',
- readingResource: 'جارٍ قراءة مورد المهارة',
- readResource: 'تمت قراءة مورد المهارة',
- resourceFailed: 'تعذرت قراءة مورد المهارة',
- listing: 'جارٍ عرض المهارات',
- listed: 'تم عرض المهارات',
- listFailed: 'تعذر عرض المهارات',
- unavailable: 'نتيجة المهارة غير متاحة'
- },
- outputAlt: 'إخراج الأداة',
- rawResponse: 'الرد الخام',
- copyActivity: 'نسخ النشاط',
- recoveredOne: 'تم الاسترداد',
- recoveredMany: count => `تم استرداد ${count}`,
- failedOne: 'فشل',
- failedMany: count => `فشل ${count}`,
- statusRunning: 'يعمل',
- statusError: 'خطأ',
- statusRecovered: 'تم الاسترداد',
- statusDone: 'تم',
- resultUnavailable: 'النتيجة غير متاحة',
- resultInterrupted: 'تمت المقاطعة',
- memoryWriteNoted: 'تم تسجيل كتابة الذاكرة',
- actions: {
- read: 'قراءة',
- reading: 'جار القراءة',
- opened: 'تم الفتح',
- opening: 'جار الفتح',
- searched: 'تم البحث',
- searching: 'جار البحث',
- ran: 'تم التشغيل',
- running: 'جار التشغيل',
- ranCode: 'تم تشغيل الكود',
- runningCode: 'جار البرمجة'
- },
- prefixes: {
- browser: 'المتصفح',
- web: 'الويب'
- },
- titleTemplates: {
- actionCommand: (action, command) => `${action} ${command}`,
- actionQuoted: (action, value) => `${action} “${value}”`,
- actionTarget: (action, target) => `${action} ${target}`,
- prefixedDone: (prefix, action) => `${prefix} ${action}`,
- runningPrefixedTool: (prefix, action) => `جار تشغيل ${prefix.toLowerCase()} ${action.toLowerCase()}`,
- runningTool: action => `جار تشغيل ${action.toLowerCase()}`
- },
- titles: {
- browser_click: {
- done: 'تم النقر على عنصر الصفحة',
- pending: 'جار النقر على عنصر الصفحة',
- pendingAction: 'جار النقر'
- },
- browser_fill: {
- done: 'تم ملء حقل النموذج',
- pending: 'جار ملء حقل النموذج',
- pendingAction: 'جار الملء'
- },
- browser_navigate: {
- done: 'تم فتح الصفحة',
- pending: 'جار فتح الصفحة',
- pendingAction: 'جار الفتح'
- },
- browser_snapshot: {
- done: 'تم التقاط لقطة الصفحة',
- pending: 'جار التقاط لقطة الصفحة',
- pendingAction: 'جار الالتقاط'
- },
- browser_take_screenshot: {
- done: 'تم التقاط لقطة الشاشة',
- pending: 'جار التقاط لقطة الشاشة',
- pendingAction: 'جار الالتقاط'
- },
- browser_type: {
- done: 'تمت الكتابة على الصفحة',
- pending: 'جار الكتابة على الصفحة',
- pendingAction: 'جار الكتابة'
- },
- clarify: {
- done: 'تم طرح سؤال',
- pending: 'جار طرح سؤال',
- pendingAction: 'جار السؤال'
- },
- cronjob: {
- done: 'مهمة مجدولة',
- pending: 'جار جدولة المهمة',
- pendingAction: 'جار الجدولة'
- },
- edit_file: {
- done: 'تم تحرير الملف',
- pending: 'جار تحرير الملف',
- pendingAction: 'جار التحرير'
- },
- execute_code: {
- done: 'تم تشغيل الكود',
- pending: 'جار البرمجة',
- pendingAction: 'جار البرمجة'
- },
- image_generate: {
- done: 'تم إنشاء الصورة',
- pending: 'جار إنشاء الصورة',
- pendingAction: 'جار الإنشاء'
- },
- list_files: {
- done: 'تم سرد الملفات',
- pending: 'جار سرد الملفات',
- pendingAction: 'جار السرد'
- },
- memory: {
- done: 'تم الحفظ في الذاكرة',
- pending: 'جار الحفظ في الذاكرة',
- pendingAction: 'جار الحفظ'
- },
- patch: {
- done: 'تم تصحيح الملف',
- pending: 'جار تصحيح الملف',
- pendingAction: 'جار التصحيح'
- },
- read_file: {
- done: 'تمت قراءة الملف',
- pending: 'جار قراءة الملف',
- pendingAction: 'جار القراءة'
- },
- search_files: {
- done: 'تم البحث في الملفات',
- pending: 'جار البحث في الملفات',
- pendingAction: 'جار البحث'
- },
- session_search_recall: {
- done: 'تم البحث في سجل الجلسة',
- pending: 'جار البحث في سجل الجلسة',
- pendingAction: 'جار البحث'
- },
- terminal: {
- done: 'تم تشغيل الأمر',
- pending: 'جار تشغيل الأمر',
- pendingAction: 'جار التشغيل'
- },
- todo: {
- done: 'تم تحديث المهام',
- pending: 'جار تحديث المهام',
- pendingAction: 'جار التحديث'
- },
- vision_analyze: {
- done: 'تم تحليل الصورة',
- pending: 'جار تحليل الصورة',
- pendingAction: 'جار التحليل'
- },
- web_extract: {
- done: 'تمت قراءة صفحة الويب',
- pending: 'جار قراءة صفحة الويب',
- pendingAction: 'جار القراءة'
- },
- web_search: {
- done: 'تم البحث في الويب',
- pending: 'جار البحث في الويب',
- pendingAction: 'جار البحث'
- },
- write_file: {
- done: 'تم تحرير الملف',
- pending: 'جار تحرير الملف',
- pendingAction: 'جار التحرير'
- }
- }
- }
- },
- prompts: {
- gatewayDisconnected: 'البوابة غير متصلة',
- sudoSendFailed: 'فشل إرسال كلمة مرور sudo',
- secretSendFailed: 'فشل إرسال السر',
- sudoTitle: 'مطلوب sudo',
- sudoDesc:
- 'راجع الأمر قبل إدخال كلمة مرور sudo. تُرسل كلمة المرور إلى الوكيل الذي ينفّذه وتُحفظ مؤقتًا لهذه الجلسة.',
- sudoCommandUnavailable: 'لم يقدّم هذا الوكيل الأمر. ألغِ الطلب إذا لم تتمكن من التحقق منه في المحادثة.',
- sudoInstallDesc:
- 'يحتاج Hermes إلى كلمة مرور sudo لتثبيت حزم Bot Screen (TigerVNC + Xfce) على مضيف البوابة. تُرسل إلى ذلك المضيف فقط.',
- sudoPlaceholder: 'كلمة المرور',
- secretTitle: 'مطلوب سر',
- secretDesc: 'أدخل القيمة المطلوبة لمتابعة المهمة.',
- secretPlaceholder: 'القيمة السرية',
- vaultUnlockSendFailed: 'تعذر إرسال كلمة المرور الرئيسية',
- vaultUnlockTitle: name => `فتح قفل ${name}`,
- vaultUnlockDesc: name =>
- `يريد الوكيل تسجيل الدخول إلى موقع ببيانات دخول محفوظة في ${name}. أدخل كلمة المرور الرئيسية لفتح القفل لهذه الجلسة — تُسلَّم مباشرة إلى ${name} على هذا الجهاز ولا تُخزَّن ولا تُعرض على الوكيل.`,
- vaultUnlockPlaceholder: 'كلمة المرور الرئيسية',
- vaultUnlockKeepLocked: 'إبقاؤه مقفلًا',
- vaultUnlockConfirm: 'فتح القفل',
- vaultSaveSendFailed: 'تعذر حفظ بيانات الدخول',
- vaultSaveTitle: site => `حفظ بيانات الدخول إلى ${site}؟`,
- vaultSaveDesc: origin =>
- `وصل Hermes إلى صفحة تسجيل الدخول في ${origin} ولا توجد بيانات دخول محفوظة لها. أدخلها هنا مرة واحدة؛ تُشفَّر على هذا الجهاز وتُملأ في الصفحة مباشرة، ولا يرى النموذج كلمة المرور أبدًا.`,
- vaultSaveIdentifierLabel: 'البريد الإلكتروني أو اسم المستخدم',
- vaultSaveIdentifierPlaceholder: '[email protected]',
- vaultSavePasswordPlaceholder: 'كلمة المرور',
- vaultSaveFootnote: 'أدِر بيانات الدخول المحفوظة من الإعدادات ← كلمات المرور وتسجيلات الدخول.',
- vaultSaveDecline: 'عدم الحفظ',
- vaultSaveConfirm: 'حفظ وتسجيل الدخول',
- vaultCodeSendFailed: 'تعذر إرسال الرمز',
- vaultCodeTitle: site => `رمز التحقق لـ ${site}`,
- vaultCodeDesc: site =>
- `يطلب ${site} رمزًا لمرة واحدة (رسالة نصية أو بريد إلكتروني أو تطبيق مصادقة). أدخله هنا وسيكتبه Hermes في الصفحة؛ لا يراه النموذج أبدًا.`,
- vaultCodeLabel: 'الرمز',
- vaultCodeFootnote:
- 'تلميح: احفظ مفتاح المصادقة مع بيانات الدخول هذه في الإعدادات ← كلمات المرور وتسجيلات الدخول وسيُدخل Hermes الرموز نيابةً عنك.',
- vaultCodeSkip: 'تخطٍ',
- vaultCodeConfirm: 'إدخال الرمز'
- },
- desktop: {
- audioReadFailed: 'فشلت قراءة الصوت',
- sessionUnavailable: 'الجلسة غير متاحة',
- createSessionFailed: 'فشل إنشاء الجلسة',
- promptFailed: 'فشل إرسال الرسالة',
- staleSessionTitle: 'المحادثة غير محدّثة',
- staleSessionBody:
- 'كانت هذه النافذة متأخرة عن عرض آخر لنفس المحادثة. تم تحميل أحدث الرسائل. أعد الإرسال إذا كنت لا تزال تريد ذلك.',
- providerCredentialRequired: 'مطلوب اعتماد المزود',
- emptySlashCommand: 'أمر slash فارغ',
- desktopCommands: 'أوامر سطح المكتب',
- skillCommandsAvailable: count => `${count} أمر مهارة متاح`,
- warningLine: message => `تحذير: ${message}`,
- yoloArmed: 'YOLO مفعل',
- yoloOff: 'YOLO معطل',
- yoloSystem: active => (active ? 'YOLO مفعل للنظام' : 'YOLO معطل للنظام'),
- yoloTitle: 'وضع YOLO',
- yoloToggleFailed: 'فشل تبديل YOLO',
- profileStatus: current => `الملف الحالي: ${current}`,
- unknownProfile: 'ملف شخصي غير معروف',
- noProfileNamed: (target, available) => `لا يوجد ملف باسم ${target}. المتاح: ${available}`,
- newChatsProfile: name => `المحادثات الجديدة تستخدم ${name}`,
- setProfileFailed: 'فشل ضبط الملف الشخصي',
- sttDisabled: 'تحويل الكلام إلى نص معطل',
- stopFailed: 'فشل الإيقاف',
- regenerateFailed: 'فشلت إعادة التوليد',
- editFailed: 'فشل التحرير',
- editTurnUnavailable: 'هذه الجولة لم تعد في سجل الخادم (ربما أزيلت بالضغط).',
- resumeFailed: 'فشل الاستئناف',
- readOnlyTranscriptTitle: 'فُتحت للقراءة فقط',
- readOnlyTranscriptBody:
- 'لا يوجد بعد خادم متصل يملك هذه المحادثة القديمة، لذا فُتحت كنصّ محفوظ للقراءة فقط. السجل سليم؛ الإرسال معطّل حتى يتبنّاها خادم.',
- readOnlyTranscriptSendBlocked: 'هذه المحادثة مفتوحة كنصّ محفوظ للقراءة فقط — الإرسال معطّل.',
- resumeStrandedTitle: 'تعذّر تحميل هذه الجلسة',
- resumeStrandedBody:
- 'فشل الاتصال بهذه الجلسة وتوقفت إعادة المحاولة التلقائية. تأكد من تشغيل البوابة، ثم حاول مجددا.',
- poolSlotTimeoutBody:
- 'جميع خانات الواجهات الخلفية المحلية للملفات الشخصية مشغولة. زد عدد Warm Bot Backends من الإعدادات ← متقدم، أو أعد المحاولة بعد إزالة واجهة خلفية خاملة.',
- poolSlotTimeoutOpenSettings: 'فتح الإعدادات المتقدمة',
- resumeRetry: 'إعادة المحاولة',
- nothingToBranch: 'لا يوجد ما يمكن تفريعه',
- branchNeedsChat: 'يحتاج التفريع إلى محادثة',
- sessionBusy: 'الجلسة مشغولة',
- branchStopCurrent: 'أوقف الدور الحالي قبل التفريع',
- branchNoText: 'لا يوجد نص للتفريع',
- branchTitle: n => `مسودة: تفريع #${n}`,
- branchFailed: 'فشل التفريع',
- deleteFailed: 'فشل الحذف',
- archived: 'تمت الأرشفة',
- archiveFailed: 'فشلت الأرشفة',
- restored: 'تمت الاستعادة',
- unarchiveFailed: 'فشل إلغاء الأرشفة',
- cwdChangeFailed: 'فشل تغيير مجلد العمل',
- cwdStagedTitle: 'تم تجهيز مجلد العمل',
- cwdStagedMessage: 'سيطبق مجلد العمل على الرسالة التالية.',
- modelSwitchConfirmBody: 'يتطلب تبديل النموذج هذا تأكيدًا.',
- modelSwitchConfirmLabel: 'التبديل على أي حال',
- modelSwitchConfirmTitle: (model: string) => `التبديل إلى ${model}؟`,
- modelSwitchConfirmTitleFallback: 'تبديل النموذج؟',
- modelSwitchFailed: 'فشل تبديل النموذج',
- modelSwitchKeepLabel: 'الاحتفاظ بالنموذج الحالي',
- modelSwitchStaleNotice: 'تغيّر الاختيار — لم يتم تطبيق تبديل النموذج.',
- hydrationSyncing: (profile: string) => `جارٍ مزامنة ${profile}\u2026`,
- sessionExported: 'تم تصدير الجلسة',
- sessionExportFailed: 'فشل تصدير الجلسة',
- imageSaved: 'تم حفظ الصورة',
- downloadStarted: 'بدأ التنزيل',
- restartToUseSaveImage: 'أعد التشغيل لاستخدام حفظ الصور',
- restartToSaveImages: 'أعد التشغيل لحفظ الصور',
- imageDownloadFailed: 'فشل تنزيل الصورة',
- openImage: 'فتح الصورة',
- downloadImage: 'تنزيل الصورة',
- savingImage: 'جار حفظ الصورة',
- imagePreviewFailed: 'فشلت معاينة الصورة',
- imageAttach: 'إرفاق الصورة',
- imageWriteFailed: 'فشل كتابة الصورة',
- imageAttachFailed: 'فشل إرفاق الصورة',
- pastedContent: 'محتوى ملصق',
- pasteAttachFailed: 'تعذر إرفاق النص الملصق',
- attachImages: 'إرفاق الصور',
- clipboard: 'الحافظة',
- noClipboardImage: 'لا توجد صورة في الحافظة',
- clipboardPasteFailed: 'فشل اللصق من الحافظة',
- dropFiles: 'أفلت الملفات هنا',
- handoff: {
- pickPlatform: 'اختر وجهة',
- success: platform => `تم التسليم إلى ${platform}. استأنف هنا في أي وقت.`,
- systemNote: platform => `↻ تم التسليم إلى ${platform} — استأنف هنا في أي وقت.`,
- failed: error => `فشل التسليم: ${error}`,
- timedOut: 'انتهت المهلة في انتظار البوابة. هل `hermes gateway` قيد التشغيل؟'
- }
- },
- errors: {
- genericFailure: 'حدث خطأ',
- boundaryTitle: 'تعطل جزء من الواجهة',
- boundaryDesc: 'يمكنك إعادة تحميل النافذة أو فتح السجلات لمعرفة التفاصيل.',
- reloadWindow: 'إعادة تحميل النافذة',
- openLogs: 'فتح السجلات'
- },
- tips: {
- close: 'لا تعرض هذه النصيحة مرة أخرى',
- items: {
- 'new-session': {
- title: 'ابدأ من جديد',
- text: 'كل محادثة جديدة لها سياقها وطرفيتها ومجلد عملها الخاص.'
- },
- skills: {
- title: 'علّمه مرة واحدة',
- text: 'المهارات مجلدات من التعليمات يحمّلها Hermes عندما يقتضي العمل ذلك.'
- },
- messaging: {
- title: 'Hermes بعيدًا عن مكتبك',
- text: 'اربطه بـ Telegram وDiscord وSlack وغيرها — الوكيل نفسه والذاكرة نفسها.'
- },
- artifacts: {
- title: 'كل ما صنعه Hermes',
- text: 'الصور والملفات والروابط من كل الجلسات، مفهرسة في مكان واحد.'
- },
- cron: {
- title: 'عمل يجري من تلقاء نفسه',
- text: 'جدوِل موجّهًا كل ساعة أو كل ليلة أو وفق تعبير cron.'
- },
- 'command-palette': {
- title: 'صندوق واحد لكل شيء',
- text: 'الجلسات والإعدادات والمهارات والأوامر كلها تستجيب للوحة الأوامر.'
- },
- profiles: {
- title: 'الملفات الشخصية منفصلة',
- text: 'كل واحد منها Hermes مستقل — مفاتيحه وذاكرته وجلساته الخاصة.'
- },
- 'composer-mentions': {
- title: 'المرفقات والأوامر',
- text: 'اكتب @ لإحضار ملف إلى المحادثة، و / لتشغيل أمر.'
- },
- 'local-runtime-update': {
- title: 'يتوفر تحديث للمحرك المحلي',
- text: 'حدّث المحرك الذي يشغّل نماذجك المحلية. قد تنقطع الطلبات المحلية الجارية.',
- action: 'التحديث الآن'
- },
- 'local-setup': {
- title: 'هذا الجهاز يمكنه تشغيل النماذج محليًا',
- text: 'عتادك قادر على تشغيل نموذج محلي. تبقى محادثاتك على جهازك ولا تكلف شيئًا.',
- action: 'إعداد الآن'
- },
- 'right-pane': {
- title: 'لوحة العمل',
- text: 'الملفات والطرفية والمراجعة والمتصفح المدمج تتشارك اللوحة الجانبية.'
- }
- }
- },
- ui: {
- search: {
- clear: 'مسح البحث'
- },
- pagination: {
- label: 'ترقيم الصفحات',
- previous: 'السابق',
- previousAria: 'الصفحة السابقة',
- next: 'التالي',
- nextAria: 'الصفحة التالية'
- },
- sidebar: {
- title: 'الشريط الجانبي',
- description: 'تنقل التطبيق',
- toggle: open => `${open ? 'إظهار' : 'إخفاء'} الشريط الجانبي`
- }
- }
++ queueLostDiscardTip: 'أعادت البوابة التشغيل أثناء هذا الدور ولا يمكن إكماله. تجاهله لتستمر الأدوار المنتظرة خلفه.'
++ },
+ statusStack: arChat.statusStack,
+ updates: arBoot.updates,
+ guidedGreeting: arBoot.guidedGreeting,
+ install: arBoot.install,
+ onboarding: arBoot.onboarding,
+ modelPicker: arSettings.modelPicker,
+ modelVisibility: arSettings.modelVisibility,
+ shell: arChrome.shell,
+ rightSidebar: arChrome.rightSidebar,
+ preview: arArtifacts.preview,
+ interfaceMode: arSettings.interfaceMode,
+ zones: arChrome.zones,
+ contextMenu: arChrome.contextMenu,
+ assistant: arAssistant.assistant,
+ prompts: arChat.prompts,
+ desktop: arChat.desktop,
+ errors: arDiagnostics.errors,
+ tips: arChat.tips,
+ ui: arCommon.ui
})
diff --cc apps/desktop/src/i18n/zh-hant.ts
index 5d64127ca93,ac21c12e369..186efc4c779
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@@ -2454,1348 -92,22 +92,28 @@@ export const zhHant = defineLocale(
confirmAction: '確認',
declined: '已取消模型變更 — 你拒絕了資料訓練層級警告。'
},
-
- cron: {
- close: '關閉排程',
- title: '排程工作',
- count: count => `${count} 個工作`,
- search: '搜尋排程工作…',
- loading: '正在載入排程工作…',
- states: {
- enabled: '已啟用',
- scheduled: '已排程',
- running: '執行中',
- paused: '已暫停',
- disabled: '已停用',
- error: '錯誤',
- completed: '已完成'
- },
- deliveryLabels: {
- local: '此桌面',
- telegram: 'Telegram',
- discord: 'Discord',
- slack: 'Slack',
- email: '電子郵件'
- },
- scheduleLabels: {
- daily: '每天',
- weekdays: '工作日',
- weekly: '每週',
- monthly: '每月',
- hourly: '每小時',
- 'every-15-minutes': '每 15 分鐘',
- custom: '自訂'
- },
- scheduleHints: {
- daily: '每天上午 9:00',
- weekdays: '週一至週五上午 9:00',
- weekly: '每週一上午 9:00',
- monthly: '每月第一天上午 9:00',
- hourly: '每個整點',
- 'every-15-minutes': '每 15 分鐘',
- custom: 'Cron 語法或自然語言'
- },
- days: {
- '0': '週日',
- '1': '週一',
- '2': '週二',
- '3': '週三',
- '4': '週四',
- '5': '週五',
- '6': '週六',
- '7': '週日'
- },
- dayFallback: value => `第 ${value} 天`,
- everyDayAt: time => `每天 ${time}`,
- weekdaysAt: time => `工作日 ${time}`,
- everyDayOfWeekAt: (day, time) => `每${day} ${time}`,
- monthlyOnDayAt: (dayOfMonth, time) => `每月 ${dayOfMonth} 日 ${time}`,
- topOfHour: '每個整點',
- everyHourAt: minute => `每小時的 :${minute}`,
- newCron: '新排程工作',
- emptyDescNew: '按 cron 表達式排程一個提示詞。Hermes 會執行它,並將結果傳送至您選擇的目的地。',
- emptyDescSearch: '請嘗試更廣泛的搜尋詞。',
- emptyTitleNew: '暫無排程工作',
- emptyTitleSearch: '無相符項目',
- last: '上次:',
- next: '下次:',
- noRuns: '尚無執行',
- manage: '管理',
- showRuns: '顯示執行記錄',
- hideRuns: '隱藏執行記錄',
- runHistory: '執行記錄',
-
- actionsTitle: '排程工作動作',
- resume: '繼續',
- pause: '暫停',
- resumeTitle: '繼續',
- pauseTitle: '暫停',
- triggerNow: '立即觸發',
- edit: '編輯排程工作',
- deleteTitle: '刪除排程工作?',
- deleteDescPrefix: '這將永久移除 ',
- deleteDescSuffix: '。它會立即停止觸發。',
- deleting: '刪除中…',
- resumed: '排程工作已繼續',
- paused: '排程工作已暫停',
- triggered: '排程工作已觸發',
- deleted: '排程工作已刪除',
- created: '排程工作已建立',
- updated: '排程工作已更新',
- failedLoad: '載入排程工作失敗',
- failedUpdate: '更新排程工作失敗',
- failedTrigger: '觸發排程工作失敗',
- failedDelete: '刪除排程工作失敗',
- failedSave: '儲存排程工作失敗',
- editTitle: '編輯排程工作',
- createTitle: '新排程工作',
- editDesc: '更新排程、提示詞或傳遞目標。變更將在下次執行時生效。',
- createDesc: '排程一個提示詞以自動執行。使用 cron 語法或類似「每 15 分鐘」的自然語言。',
- nameLabel: '名稱',
- namePlaceholder: '例如:每日摘要',
- promptLabel: '提示詞',
- scriptLabel: '指令碼',
- scriptBadge: '指令碼',
- promptPlaceholder: '代理每次執行時應做什麼?',
- frequencyLabel: '頻率',
- deliverLabel: '傳遞至',
- deliverNeedsHomeChannel: '請先設定主頻道',
- modelLabel: '模型',
- modelDefault: '預設(全域模型)',
- customScheduleLabel: '自訂排程',
- customPlaceholder: '0 9 * * * 或 weekdays at 9am',
- customHint: 'Cron 表達式,或類似「每小時」「工作日上午 9 點」的短語。',
- optional: '選填',
- promptRequired: '提示詞為必填項目。',
- promptScheduleRequired: '提示詞和排程為必填項目。',
- scheduleRequired: '排程為必填項目。',
- scriptOnlyEditHint: '僅腳本任務(無 AI 提示詞)。任務 ID:',
- saveChanges: '儲存變更',
- createAction: '建立排程工作',
- tabs: {
- jobs: '工作',
- blueprints: '藍圖'
- },
- blueprints: {
- tab: '藍圖',
- startFrom: '從此開始',
- custom: '自訂',
- subtitle: '現成的自動化',
- dialogDesc: '填寫詳細資訊並進行排程。',
- scheduleIt: '安排工作',
- scheduling: '安排中...',
- scheduled: '藍圖已安排',
- loading: '正在載入藍圖...',
- failedLoad: '載入藍圖失敗',
- emptyTitle: '沒有可用的藍圖',
- emptyDesc: '此後端上沒有可用的自動化藍圖。'
- }
- },
-
- artifacts: {
- search: '搜尋成品…',
- refresh: '重新整理成品',
- refreshing: '正在重新整理成品',
- indexing: '正在索引最近工作階段的成品',
- tabAll: '全部',
- tabImages: '圖片',
- tabFiles: '檔案',
- tabLinks: '連結',
- noArtifactsTitle: '找不到成品',
- noArtifactsDesc: '當工作階段產生圖片和檔案輸出時,它們會顯示在這裡。',
- failedLoad: '成品載入失敗',
- openFailed: '開啟失敗',
- itemsImage: '張圖片',
- itemsLink: '個連結',
- itemsFile: '個檔案',
- itemsGeneric: '項',
- zero: '0',
- rangeOf: (start, end, total) => `${start}-${end},共 ${total}`,
- goToPage: (itemLabel, page) => `前往${itemLabel}第 ${page} 頁`,
- colTitleLink: '連結標題',
- colTitleFile: '名稱',
- colTitleDefault: '標題 / 名稱',
- colLocationLink: 'URL',
- colLocationFile: '路徑',
- colLocationDefault: '位置',
- colSession: '工作階段',
- kindImage: '圖片',
- kindFile: '檔案',
- kindLink: '連結',
- chat: '聊天',
- copyUrl: '複製 URL',
- copyPath: '複製路徑'
- },
-
- artifactCard: {
- kind: { code: '程式碼', html: '互動頁面', svg: '圖形' },
- generating: lines => `產生中… ${lines} 行`,
- versionBadge: count => `${count} 個版本`,
- open: '開啟'
- },
-
- artifactPreview: {
- versionOf: (current, total) => `第 ${current}/${total} 版`,
- olderVersion: '較舊版本',
- newerVersion: '較新版本',
- latest: '最新',
- copyContent: '複製內容',
- download: '下載',
- openInBrowser: '在瀏覽器中開啟',
- openInBrowserFailed: '無法在瀏覽器中開啟',
- missingTitle: '產物無法使用',
- missingBody: '此產物已不在本機註冊表中。'
- },
-
- sidebar: {
- profileRail: '設定檔列',
- markAllRead: '全部標示為已讀',
- filter: {
- grouping: '分組',
- ordering: '排序',
- show: '顯示',
- filters: '篩選',
- status: '狀態',
- pullRequest: '提取請求',
- profile: '設定檔',
- project: '專案',
- archived: '已封存',
- resetToDefaults: '重設為預設值',
- expandAll: '全部展開',
- collapseAll: '全部收合',
- inboxStyle: '收件匣樣式',
- updated: '已更新',
- created: '已建立',
- tokens: '詞元數',
- cost: '費用',
- manual: '手動',
- preview: '預覽',
- pr: 'PR',
- needsInput: '需要輸入',
- working: '運作中',
- unread: '未讀',
- draft: '草稿',
- idle: '閒置',
- open: '開啟',
- merged: '已合併',
- closed: '已關閉',
- noPR: '無 PR'
- },
- gatewayGroups: {
- grouping: '閘道與設定檔',
- rename: '重新命名群組',
- aliasLabel: '顯示名稱',
- aliasHint: '僅變更顯示名稱;閘道和設定檔名稱維持不變。',
- resetName: '重設名稱',
- moveUp: '上移',
- moveDown: '下移',
- reorder: '調整群組順序',
- actions: '群組動作'
- },
- nav: {
- 'new-session': '新工作階段',
- capabilities: '技能與工具',
- messaging: '訊息平台',
- artifacts: '成品',
- cron: '排程工作'
- },
- searchAria: '搜尋工作階段',
- searchPlaceholder: '搜尋工作階段…',
- clearSearch: '清除搜尋',
- noMatch: query => `沒有工作階段符合「${query}」。`,
- results: '結果',
- pinned: '已釘選',
- sessions: '工作階段',
- terminal: '終端機',
- files: '檔案',
- review: '審查',
- logs: '記錄',
- cronJobs: '排程任務',
- groupAriaGrouped: '以單一清單顯示工作階段',
- groupAriaUngrouped: '依工作區分組工作階段',
- showProjects: '顯示專案',
- showSessions: '顯示工作階段',
- groupTitleGrouped: '取消分組',
- groupTitleUngrouped: '依工作區分組',
- allPinned: '這裡的全部已釘選。取消釘選某個聊天即可在最近中顯示。',
- shiftClickHint: 'Shift + 點擊聊天以釘選 · 拖曳以重新排序',
- noWorkspace: '無工作區',
- projectEmpty: '尚無工作階段',
- projectLoadFailed: '會話載入失敗',
- noSessions: '尚無工作階段',
- noFilterMatches: '沒有工作階段符合這些篩選條件',
- projects: {
- showAllSessions: '顯示所有工作階段',
- sectionLabel: '專案',
- home: '主頁',
- autoDiscovered: '自動探索',
- showAllCount: count => `顯示全部 ${count} 個工作階段`,
- newButton: '新增專案',
- createTitle: '新增專案',
- createDesc: '為工作區命名並新增一個或多個資料夾。',
- renameTitle: '重新命名專案',
- addFolderTitle: '新增資料夾',
- namePlaceholder: '例如 Skunkworks',
- foldersLabel: '資料夾',
- ideaLabel: '想法',
- ideaPlaceholder: '這個專案是關於什麼的?(儲存到 IDEA.md)',
- ideaGenerate: '產生想法',
- ideaGenerating: '產生中…',
- ideaShuffle: '隨機範本',
- noFolders: '尚未新增資料夾。',
- addFolder: '新增資料夾',
- primaryBadge: '主要',
- removeFolder: '移除',
- create: '建立',
- menu: '動作',
- menuRename: '重新命名…',
- menuAppearance: '外觀',
- noColor: '無顏色',
- menuAddFolder: '新增資料夾',
- menuSetActive: '設為使用中',
- menuDelete: '刪除',
- reveal: '在資料夾中顯示',
- copyPath: '複製路徑',
- removeFromSidebar: '從側邊欄移除',
- createFailed: '無法建立專案',
- staleBackend: '請更新 Hermes 後端以建立專案——目前後端比桌面應用舊(設定 → 更新 → 後端)。',
- deleteConfirm: '這會從 Hermes 中移除已儲存的專案。檔案、git 儲存庫和工作樹維持不變。',
- startWork: '新增工作樹',
- newWorktreeTitle: '新增工作樹',
- newWorktreeDesc: '為這個工作樹命名分支。',
- branchPlaceholder: '例如 my-feature',
- branchOff: () => ({ after: ' 分支', before: '從 ' }),
- baseBranchPlaceholder: '搜尋分支…',
- baseBranchNone: '未找到分支',
- startWorkFailed: '無法建立工作樹',
- worktreeStaleBackend: '請更新 Hermes 後端以在此遠端連線上建立工作樹 —— 該後端早於 git 工作樹 API。',
- worktreeProjectLabel: '專案',
- worktreeProjectPlaceholder: '搜尋專案…',
- worktreeProjectNone: '沒有包含資料夾的專案',
- convertBranch: '轉換分支…',
- convertBranchTitle: '轉換分支',
- convertBranchDesc: '開啟已簽出的分支,或為可用分支建立工作樹。',
- convertBranchPlaceholder: '搜尋分支…',
- convertBranchInstead: '轉換現有分支',
- branchOpenExisting: '開啟',
- branchSwitchHome: '切回主簽出',
- branchCreateWorktree: '新增工作樹',
- branchTrackRemote: '追蹤遠端',
- branchesLoading: '正在載入分支…',
- noBranches: '找不到分支',
- removeWorktree: '移除工作樹',
- removeWorktreeFailed: '無法移除工作樹(有未提交的變更?)',
- removeWorktreeConfirm:
- '從 git 中移除(刪除工作樹目錄,但保留分支),或僅從側邊欄隱藏該軌道並將工作樹保留在磁碟上。',
- removeWorktreeDirty: '此工作樹有未提交的變更。強制移除(捨棄這些變更),或僅隱藏軌道並保留在磁碟上。',
- forceRemove: '強制移除',
- enter: label => `開啟 ${label}`
- },
- newSessionIn: label => `在 ${label} 中新建工作階段`,
- showMoreIn: (count, label) => `在 ${label} 中再顯示 ${count} 個`,
- loading: '載入中…',
- loadMore: '載入更多',
- loadCount: step => `再載入 ${step} 個`,
- messageCount: count => `${count} 條訊息`,
- toolCallCount: count => `${count} 次工具調用`,
- row: {
- pin: '釘選',
- unpin: '取消釘選',
- markUnread: '標記為未讀',
- markRead: '標記為已讀',
- unreadFailed: '無法更新未讀狀態',
- copyId: '複製 ID',
- export: '匯出',
- branchFrom: '分支',
- rename: '重新命名…',
- archive: '封存',
- unarchive: '取消封存',
- newWindow: '新視窗',
- openInTerminal: '在終端機中開啟',
- copyIdFailed: '無法複製工作階段 ID',
-
- sessionActions: '工作階段動作',
- sessionRunning: '工作階段執行中',
- needsInput: '需要您的輸入',
- waitingForAnswer: '等待您的回答',
- finishedUnread: '已完成 — 未讀',
- backgroundRunning: '背景任務執行中',
- draftSession: '草稿 — 尚未傳送',
- handoffOrigin: platform => `從 ${platform} 轉接`,
- ownedByProfile: profile => `設定檔:${profile}`,
- renamed: '已重新命名',
- renameFailed: '重新命名失敗',
- renameTitle: '重新命名工作階段',
- renameDesc: '留空則清除。',
- untitledPlaceholder: '未命名工作階段',
- deleteTitle: '刪除會話?',
- deleteDesc: title => `這將永久刪除「${title}」,且無法復原。`,
- deleting: '正在刪除…',
- deleted: '會話已刪除',
- untitledChat: id => `工作階段 ${id}`,
- ageNow: '剛才',
- ageDay: '天',
- ageHour: '時',
- ageMin: '分'
- },
- dateDivider: {
- today: '今天稍早',
- yesterday: '昨天',
- thisWeek: '本週',
- lastWeek: '上週',
- thisMonth: '本月'
- },
- statusDivider: {
- working: '進行中',
- done: '已完成'
- }
- },
-
+ cron: zhHantCommandCenter.cron,
+ artifacts: zhHantArtifacts.artifacts,
+ artifactCard: zhHantArtifacts.artifactCard,
+ artifactPreview: zhHantArtifacts.artifactPreview,
+ sidebar: zhHantChrome.sidebar,
- composer: zhHantChat.composer,
+ composer: {
- message: '訊息',
- wakingProfile: profile => `正在喚醒 ${profile}…`,
- placeholderStarting: '正在啟動 Hermes...',
- placeholderReconnecting: '正在重新連線至 Hermes…',
- placeholderFollowUp: '傳送後續訊息',
- newSessionPlaceholders: [
- '我們要建立什麼?',
- '給 Hermes 一個任務',
- '您在想什麼?',
- '描述您需要什麼',
- '我們該處理什麼?',
- '盡管問',
- '從一個目標開始'
- ],
- followUpPlaceholders: [
- '傳送後續訊息',
- '補充更多脈絡',
- '細化此請求',
- '下一步是什麼?',
- '繼續推進',
- '再深入一點',
- '調整或繼續'
- ],
- startVoice: '開始語音對話',
- openDirective: '開啟',
- queueMessage: '排隊訊息',
- stop: '停止',
- send: '傳送',
- speaking: '說話中',
- transcribing: '轉寫中',
- thinking: '思考中',
- muted: '已靜音',
- listening: '聆聽中',
- muteMic: '麥克風靜音',
- unmuteMic: '取消麥克風靜音',
- stopListening: '停止聆聽並傳送',
- stopShort: '停止',
- endConversation: '結束語音對話',
- endShort: '結束',
- stopDictation: '停止聽寫',
- transcribingDictation: '正在轉寫聽寫',
- voiceControls: '語音',
- voiceDictation: '語音聽寫',
- speakReplies: '朗讀回覆',
- stopSpeakingReplies: '停止朗讀回覆',
- wakeWordListening: phrase => `喚醒詞:「${phrase}」— 正在聆聽`,
- wakeWord: phrase => `喚醒詞「${phrase}」`,
- wakeWordOff: phrase => `喚醒詞:「${phrase}」— 已關閉`,
- wakeWordPausedVoice: phrase => `喚醒詞:「${phrase}」— 語音對話期間暫停`,
- lookupLoading: '查詢中…',
- lookupNoMatches: '沒有相符項目。',
- lookupTry: '試試',
- lookupOr: '或',
- commonCommands: '常用指令',
- hotkeys: '快捷鍵',
- helpFooter: '開啟完整面板 · 退格鍵關閉',
- commandDescs: {
- '/help': '顯示桌面端斜線指令',
- '/clear': '開始新工作階段',
- '/resume': '繼續已儲存的工作階段',
- '/details': '控制對話記錄的詳細程度',
- '/copy': '複製所選內容或最後一條助手訊息',
- '/quit': '結束 hermes',
- '/start': '確認平台啟動請求,不傳送回覆',
- '/new': '開始新的桌面聊天',
- '/topic': '啟用或查看 Telegram 私訊話題工作階段',
- '/save': '將目前對話記錄儲存為 JSON',
- '/retry': '重試最後一則訊息(重新傳送給代理)',
- '/prompt': '在 $EDITOR 中用 Markdown 撰寫下一個提示詞,然後傳送',
- '/undo': '退回 N 個使用者回合並重新提示(預設為 1)',
- '/title': '重新命名目前工作階段',
- '/handoff': '將此工作階段交接至訊息平台',
- '/branch': '將最新訊息分支至新的聊天',
- '/worktree': '顯示、列出、建立或清理隔離的 Git worktree',
- '/compress': '壓縮此對話的上下文',
- '/rollback': '列出或還原檔案系統檢查點(還原會保留你的手動編輯;--all 可覆寫此行為)',
- '/export': '將設定檔(設定、技能、主題)匯出為可分享的封存檔',
- '/import': '將共用的設定檔封存檔匯入為新的設定檔',
- '/stop': '停止目前回合與背景程序',
- '/pause': '暫停全域新工作(緊急停止);/pause off 恢復',
- '/bg': '在獨立的背景工作階段中執行提示詞',
- '/btw': '在不中斷目前對話的情況下詢問旁支問題',
- '/agents': '顯示作用中的代理與執行中的任務',
- '/journey': '開啟記憶圖譜 — 查看技能與記憶隨時間的變化',
- '/queue': '排入、檢視、編輯、移除、移動或清空下一回合提示詞',
- '/steer': '在下一次工具呼叫後插入訊息,不會中斷目前工作',
- '/goal': '設定持續目標,讓 Hermes 跨回合工作直到完成',
- '/heartbeat': '設定週期性提示詞,在閒置時重新進入此工作階段',
- '/refine': '立即檢查此對話,並將心得儲存至記憶或技能',
- '/review': '產生獨立子代理,審查剛才討論的工作(PR、程式碼、文件)',
- '/loop': '在此工作階段以固定間隔重新執行提示詞',
- '/plan': '將 Markdown 實作計畫寫入 .hermes/plans/,不執行任何操作',
- '/moa': '使用預設的 Mixture of Agents 組合執行提示詞,完成後還原模型',
- '/subgoal': '新增或管理作用中目標的額外條件',
- '/status': '顯示目前工作階段狀態',
- '/egress': '顯示 Docker 對外連線代理狀態',
- '/context': '顯示詳細的上下文視窗,包括用量、分類明細、壓縮統計與吞吐量',
- '/whoami': '顯示你的斜線指令存取權限(admin / user)',
- '/profile': '切換作用中的 Hermes 設定檔',
- '/codex-runtime': '切換 OpenAI/Codex 模型使用的 Codex app-server runtime',
- '/personality': '設定預先定義的人格',
- '/battery': '切換狀態列中的彩色電池指示器',
- '/timestamps': '切換訊息與 /history 上的 [HH:MM] 時間戳記',
- '/diff': '顯示工作目錄中的 Git 變更',
- '/focus': '切換專注檢視 — 只顯示你的提示詞與最終回覆',
- '/yolo': '切換 YOLO — 自動核准危險指令',
- '/approvals': '顯示或設定持久化的危險指令核准模式',
- '/reasoning': '管理推理強度與顯示方式',
- '/skin': '切換桌面主題,或切換至下一個主題',
- '/wake': '控制桌面的喚醒詞監聽器 [on|off|status]',
- '/tools': '管理工具',
- '/memory': '檢視待處理的記憶寫入,或切換核准閘門',
- '/bundles': '列出技能套件(可用 /<name> 作為多個技能的別名)',
- '/pet': '切換或領養 petdex 吉祥物(/pet、/pet list、/pet boba)',
- '/hatch': '產生新的寵物(開啟寵物產生器)',
- '/learn': '從你描述的任何內容(目錄、URL、此聊天、筆記)學習可重用的技能',
- '/init': '掃描儲存庫並產生或更新 AGENTS.md 專案指引',
- '/suggestions': '檢視建議的自動化項目(接受或略過)',
- '/blueprint': '使用 blueprint 範本設定自動化',
- '/browser': '管理瀏覽器 CDP 連線 [connect|disconnect|status](僅限本機 gateway)',
- '/palette': '開啟模糊搜尋指令面板(也可使用 Ctrl+P)',
- '/usage': '顯示 Token 用量與速率限制;`reset` 可兌換保留的 Codex 限額重設',
- '/subscription': '檢視你的 Nous 方案,並在瀏覽器中變更',
- '/topup': '顯示你的 Nous 餘額,並在 Portal 管理帳務',
- '/platform': '暫停、恢復或列出故障的閘道平台',
- '/version': '顯示 Hermes Agent 版本',
- '/debug': '上傳偵錯報告(系統資訊與記錄),並取得可分享連結',
- '/model': '切換此工作階段的模型'
- },
- hotkeyDescs: {
- 'composer.mention': '參照檔案、資料夾、URL、git',
- 'composer.slash': '斜線指令面板',
- 'composer.help': '此快速說明(刪除以關閉)',
- 'composer.sendNewline': '傳送 · Shift+Enter 換行',
- 'composer.sendQueued': '傳送下一個排隊的回合',
- 'keybinds.openPanel': '所有鍵盤快捷鍵',
- 'composer.cancel': '關閉彈出視窗 · 取消執行',
- 'composer.history': '循環彈出視窗 / 歷史記錄'
- },
- attachUrlTitle: '附加 URL',
- attachUrlDesc: 'Hermes 將擷取該頁面並作為此回合的脈絡。',
- urlPlaceholder: 'https://example.com/post',
- urlHintPre: '請輸入完整 URL,例如 ',
- attach: '附加',
- queued: count => `${count} 個排隊中`,
- queuedPaused: count => `${count} 個排隊中 — 已暫停`,
- attachmentOnly: '僅附件回合',
- emptyTurn: '空回合',
- attachments: count => `${count} 個附件`,
- editingInComposer: '在輸入框中編輯',
- editingQueuedInComposer: '在輸入框中編輯排隊回合',
- restoredDraftNotice: '已還原你未送出的訊息',
- restoredDraftUndo: '復原',
- queueEdit: '編輯',
- queueSendNext: '下一個',
- queueSteer: '引導 — 立即修正目前回合',
- queueSend: '傳送',
- queueDelete: '刪除',
++ ...zhHantChat.composer,
+ queueLostNote: '重新啟動期間該回合已遺失',
+ restoreImageDraft: '還原圖片草稿',
+ queueLostDiscard: '捨棄',
- queueLostDiscardTip: '閘道在該回合進行中重新啟動,無法完成。捨棄後其後的排隊回合將繼續執行。',
- queueResume: '繼續',
- queueResumeTip: '已被停止操作暫停 — 繼續傳送排隊的回合',
- queueStuckTitle: '佇列訊息未送出',
- queueStuckBody: '佇列中的對話多次傳送失敗。它仍在佇列中,請重試傳送。',
- queueDroppedTitle: '已捨棄佇列內容',
- queueDroppedBody: '該背景佇列項目因工作階段多次嘗試後仍無法恢復而遭捨棄。佇列中的其他內容不受影響。',
- previewUnavailable: '預覽不可用',
- previewLabel: label => `預覽 ${label}`,
- couldNotPreview: label => `無法預覽 ${label}`,
- removeAttachment: label => `移除 ${label}`,
- dictating: '聽寫中',
- preparingAudio: '正在準備音訊',
- speakingResponse: '正在朗讀回覆',
- readingAloud: '朗讀中',
- themeSuggestions: '桌面主題建議',
- noMatchingThemes: '沒有相符的主題。',
- themeTryPre: '試試 ',
- themeTryPost: '。',
- attachLabel: '附加',
- files: '檔案…',
- folder: '資料夾…',
- images: '圖片…',
- pasteImage: '貼上圖片',
- url: 'URL…',
- promptSnippets: '提示詞片段…',
- tipPre: '提示:輸入 ',
- tipPost: ' 以行內參照檔案。',
- snippetsTitle: '提示詞片段',
- snippetsDesc: '選擇一個起始提示詞放入輸入框。',
- dropFiles: '拖曳檔案以附加',
- dropSession: '拖曳以連結此聊天',
- snippets: {
- codeReview: {
- label: '程式碼審查',
- description: '審查目前的變更是否有回歸、遺漏的邊緣情況和缺少的測試。',
- text: '請審查這部分是否有錯誤、回歸和缺少的測試。'
- },
- implementationPlan: {
- label: '實作計劃',
- description: '在動程式碼之前先勾勒方案,讓 diff 保持聚焦。',
- text: '請在修改程式碼前制定一個簡潔的實作計劃。'
- },
- explainThis: {
- label: '解釋這段',
- description: '說明所選程式碼的運作方式,並連結到關鍵檔案。',
- text: '請解釋這是如何運作的,並告訴我關鍵檔案在哪裡。'
- }
- }
- },
-
- statusStack: {
- hideStack: '隱藏狀態面板',
- showStack: '顯示狀態面板',
- agents: '代理',
- background: count => `${count} 個背景任務`,
- goalActive: '目標進行中',
- goalBlocked: '目標受阻',
- goalDone: '目標已完成',
- goalPaused: '目標已暫停',
- goalWaiting: '目標等待中',
- subagents: count => `${count} 個子代理`,
- todos: (done, total) => `任務 ${done}/${total}`,
- previousTodos: (done, total) => `先前任務 ${done}/${total}`,
- running: '執行中',
- stop: '停止',
- dismiss: '關閉',
- exit: code => `結束碼 ${code}`,
- control: {
- goalActiveTurns: (turn, maxTurns) => `第 ${turn}/${maxTurns} 輪`,
- goalDoneTurns: turns => `共 ${turns} 輪`,
- goalTurn: turn => `第 ${turn} 輪`,
- goalActions: '目標操作',
- viewDetails: '檢視詳細資訊',
- addCriterion: '新增條件',
- addCriterionDialogTitle: '新增條件',
- addCriterionPlaceholder: '輸入條件內容...',
- criterionLabel: '條件',
- pauseGoal: '暫停目標',
- resumeGoal: '繼續目標',
- resumeNow: '立即繼續',
- clearGoal: '清除目標',
- clearGoalConfirmTitle: '清除目標?',
- clearGoalConfirmBody: '確定要清除目前活躍的目標嗎?此動作無法復原。',
- copyCriterion: index => `複製條件 ${index}`,
- removeCriterion: index => `移除條件 ${index}`,
- removeCriterionConfirmTitle: index => `移除條件 ${index}?`,
- removeCriterionConfirmBody: index => `確定要移除條件 ${index} 嗎?`,
- clearCriteria: '清除全部條件',
- clearCriteriaConfirmTitle: '清除全部條件?',
- clearCriteriaConfirmBody: '確定要移除此目標下的所有條件嗎?',
- criteriaHeader: count => `條件 · ${count}`,
- noCriteria: '無條件',
- goalDetailsTitle: '目標詳細資訊',
- objectiveLabel: '目標內容',
- contractOutcome: '預期成果',
- contractVerification: '驗證方式',
- contractConstraints: '限制條件',
- contractBoundaries: '邊界',
- contractStopWhen: '停止條件',
- waitBarrierTitle: '等待條件',
- waitUntil: target => `等待至 ${target}`,
- waitSession: target => `等待工作階段 ${target}`,
- waitPid: pid => `等待處理程序 ${pid}`,
- qualityGatesTitle: '品質關卡',
- gateCommand: '命令',
- gateAttempts: (attempts, max) => `嘗試 ${attempts}/${max}`,
- gateTimeout: seconds => `逾時 ${seconds} 秒`,
- gateLastExit: code => (code === null ? '擱置中' : `結束代碼: ${code}`),
- loopActive: '循環進行中',
- loopPaused: '循環已暫停',
- loopDeferred: '循環已延後',
- loopFinished: '循環已完成',
- loopRuns: runs => `執行 ${runs} 次`,
- loopRunCount: (current, total) => `執行 ${current}/${total}`,
- loopNext: time => `下次 ${time}`,
- loopEverySeconds: seconds => `每 ${seconds} 秒`,
- loopEveryMinutes: minutes => `每 ${minutes} 分鐘`,
- loopEveryHours: hours => `每 ${hours} 小時`,
- loopSelfPaced: '自訂步調',
- loopActions: '循環操作',
- pauseLoop: '暫停循環',
- resumeLoop: '繼續循環',
- stopLoop: '停止循環',
- stopLoopConfirmTitle: '停止循環?',
- stopLoopConfirmBody: '確定要停止此循環嗎?',
- dismissLoop: '關閉循環',
- loopPromptLabel: '提示詞',
- loopCadenceLabel: '頻率',
- loopUntilLabel: '截止條件',
- loopDeferredNotice: '目前由進行中的目標控制工作階段。',
- loopAwaitingResponse: '等待回應中',
- heartbeatActive: '活動訊號進行中',
- heartbeatPaused: '活動訊號已暫停',
- heartbeatEveryMinutes: minutes => `每 ${minutes} 分鐘`,
- heartbeatEveryHours: hours => `每 ${hours} 小時`,
- heartbeatEverySeconds: seconds => `每 ${seconds} 秒`,
- heartbeatNext: time => `下次 ${time}`,
- heartbeatDueWaitingForIdle: '已到期 — 等待會話閒置',
- heartbeatActions: '活動訊號操作',
- pauseHeartbeat: '暫停活動訊號',
- resumeHeartbeat: '繼續活動訊號',
- clearHeartbeat: '清除活動訊號',
- clearHeartbeatConfirmTitle: '清除活動訊號?',
- clearHeartbeatConfirmBody: '確定要清除此活動訊號嗎?',
- heartbeatFiredCount: count => `已觸發 ${count} 次`,
- actionFailed: msg => `操作失敗: ${msg}`,
- actionSucceeded: '操作成功',
- copySuccess: '已將條件複製到剪貼板',
- copyFailure: '複製條件到剪貼板失敗',
- continuationFailed: '提交目標延續內容失敗',
- continuationQueued: '目標已恢復 — 延續內容已排隊,將在目前回合結束後送出',
- continuationBusy: '目標已恢復 — 會話忙碌中,請先停止目前回覆(Stop 按鈕或 Esc)以繼續',
- controlUnavailable: msg => `會話控制無法使用: ${msg}`,
- dismissError: '關閉錯誤',
- add: '新增'
- },
- coding: {
- title: '工作區',
- noBranch: '無分支',
- detached: '分離 HEAD',
- clean: '乾淨',
- changed: count => `${count} 處變更`,
- ahead: count => `領先 ${count}`,
- behind: count => `落後 ${count}`,
- review: '審查',
- close: '關閉',
- openChanges: '開啟變更',
- openFile: '開啟檔案',
- stage: '暫存',
- unstage: '取消暫存',
- stageAll: '全部暫存',
- viewAsTree: '樹狀檢視',
- viewAsList: '清單檢視',
- revert: '還原',
- revertAll: '全部還原',
- revertConfirm: '捨棄對此檔案的變更並將其還原至已提交狀態?此操作無法復原。',
- revertAllConfirm: '捨棄所有變更並將檔案還原至已提交狀態?此操作無法復原。',
- staged: '已暫存',
- noChanges: '沒有變更',
- notRepo: '不是 Git 儲存庫',
- noDiff: '沒有可顯示的差異',
- scopeUncommitted: '未提交',
- scopeBranch: '分支',
- scopeLastTurn: '上一輪',
- commit: '提交',
- commitAndPush: '提交並推送',
- commitPlaceholder: shortcut => `訊息(${shortcut} 提交)`,
- generateCommitMessage: '產生提交訊息',
- stopGenerating: '停止產生',
- createPr: '建立 PR',
- openPr: '開啟 PR',
- ghMissing: '安裝 GitHub CLI (gh) 並登入後可開啟 PR',
- agentShip: '讓 Hermes 提交並開 PR',
- agentShipUnavailable: '擁有這些變更的對話目前不在畫面上。',
- agentShipPrompt: '檢查目前的變更,使用清晰的約定式提交訊息提交,推送分支,並開啟一個拉取請求。',
- newBranch: '新增分支',
- branchOffFrom: base => `從 ${base} 建立新分支`,
- switchTo: branch => `切換到 ${branch}`,
- switchFailed: branch => `無法切換到 ${branch}`,
- worktrees: '工作樹'
- }
- },
-
- updates: {
- discontinuedTitle: '此版本的 Hermes 已停止支援',
- discontinuedBody: '此版本的 Hermes 已停止支援,可能無法正常運作——請解除安裝。您的資料仍保留在磁碟上。',
- channels: { stable: '穩定版', canary: '預覽版' },
- bundleSwapPending: '重新啟動以完成更新',
- bundleSwapPendingDesc:
- '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',
- bundleSwapPendingAction: '重新啟動 Hermes',
- stages: {
- idle: '準備中…',
- prepare: '準備中…',
- fetch: '下載中…',
- pull: '快完成了…',
- pydeps: '收尾中…',
- update: '正在更新 Hermes…',
- rebuild: '正在重新建置桌面應用程式…',
- restart: '正在重新啟動 Hermes…',
- done: '更新完成',
- manual: '從終端機更新',
- guiSkew: '請更新桌面應用程式',
- error: '更新已暫停'
- },
- checking: '正在檢查更新…',
- checkFailedTitle: '無法檢查更新',
- tryAgain: '重試',
- notAvailableTitle: '更新不可用',
- unsupportedMessage: '此版本的 Hermes 無法在應用程式內自行更新。',
- connectionRetry: '請檢查網路連線後重試。',
- gitUnusable: 'Hermes 無法在這台電腦上執行 Git,因此無法檢查更新。',
- latestBody: '您正在執行最新版本。',
- versionDetailsDistributionStore: 'Microsoft Store',
- latestBodyBackend: '後端正在執行最新版本。',
- allSetTitle: '已是最新版本',
- availableTitle: '有可用更新',
- availableBody: '新版 Hermes 已可安裝。',
- availableTitleBackend: '後端有可用更新',
- availableBodyBackend: '已連接的 Hermes 後端有新版本可安裝。',
- availableBodyNoChangelog: '已有新版本可用。此安裝方式無法顯示更新日誌。',
- updateNow: '立即更新',
- maybeLater: '稍後再說',
- moreChanges: count => `另有 ${count} 項變更。`,
- manualTitle: '從終端機更新',
- manualUnavailableTitle: '無法從這裡更新',
- manualBody: '您是從命令列安裝的 Hermes,因此更新也需要在那裡執行。請將此指令貼到終端機:',
- manualBodyBackend: 'Hermes 後端由本應用程式之外管理。請在託管它的伺服器上執行此指令:',
- manualPickedUp: '下次啟動 Hermes 時會使用新版本。',
- manualPickedUpBackend: '後端會在更新完成後載入新版本。',
- guiSkewTitle: '請更新桌面應用程式',
- guiSkewBody:
- '後端已更新,但此桌面應用程式套件未變更。請更新或重新安裝 Hermes 桌面應用程式(你的 AppImage / .deb / .rpm)以保持一致。',
- copy: '複製',
- copied: '已複製',
- done: '完成',
- applyingBody:
- 'Hermes 更新程式會在自己的視窗中接管,並在完成後自動重新開啟 Hermes。更新期間請勿自行重新開啟 Hermes。',
- applyingBodyBackend: '遠端後端正在套用更新並將重新啟動。恢復後 Hermes 會自動重新連線。',
- applyingClose: '此視窗會在更新期間關閉,隨後 Hermes 會自動重新開啟。',
- errorTitle: '更新未完成',
- errorBody: '沒有資料遺失。您可以現在重試。',
- blockerTitle: '關閉本機預覽以更新 Hermes?',
- blockerBody: 'Hermes 需要在更新前停止這些本機預覽。這不會修改或刪除您的檔案。',
- foreignBlockerTitle: '關閉其他處理程序以更新 Hermes',
- foreignBlockerBody:
- 'Hermes 無法安全地自動關閉這些處理程序。請關閉擁有這些處理程序的應用程式、終端機或服務,然後重試更新。',
- mixedBlockerBody: 'Hermes 可以關閉下方列出的本機預覽。其他處理程序必須手動關閉,更新才能繼續。',
- closePreviewsAndUpdate: '關閉預覽並更新',
- closePreviewsAndCheckAgain: '關閉預覽並重新檢查',
- localPreview: '本機預覽',
- portLabel: port => `連接埠 ${port}`,
- pidLabel: pid => `PID ${pid}`,
- technicalDetails: '技術詳細資料',
- notNow: '暫不',
- clientAlsoBehindTitle: '桌面應用版本落後',
- clientAlsoBehindMessage: '後端已是最新,但此桌面應用仍是舊版本。請更新以取得最新修復。',
- clientAlsoBehindAction: '更新桌面應用',
- everythingDispatched: '更新已派送',
- everythingSkipped: '已略過',
- everythingRowFailed: '更新失敗',
- everythingFanoutFailedTitle: '無法更新其他執行個體',
- changeLogNew: '新增功能',
- changeLogFixed: '修復',
- changeLogFaster: '更快',
- changeLogImproved: '改進',
- changeLogOther: '其他改進',
- changeLogFallbackLabel: '本次更新',
- changeLogFallbackItem: '改進與修復',
- applyStatus: {
- preparing: '正在更新後端…',
- pulling: '後端更新中…',
- restarting: '後端正在重新啟動以載入更新…',
- notAvailable: '此後端無法更新。',
- failed: '後端更新失敗。',
- noReturn: '後端未恢復連線。更新可能未完成——請檢查後端主機。'
- },
- // Restored About-card strings (moved from `settings.about.*` to `updates.*`).
- version: value => `版本 ${value}`,
- versionUnavailable: '版本不可用',
- checkNow: '立即檢查',
- seeWhatsNew: '查看新增內容',
- releaseNotes: '發行說明',
- onLatest: '你已是最新版本。',
- installing: '正在安裝更新。',
- cantReach: '無法連線到更新伺服器。',
- tapCheck: '點選「立即檢查」以尋找更新。',
- updateReady: count => `新更新已就緒(包含 ${count} 項變更)。`,
- updateReadyUnknown: '新更新已就緒。',
- lastChecked: age => `上次檢查:${age}`,
- never: '從未',
- justNow: '剛剛',
- minAgo: count => `${count} 分鐘前`,
- hoursAgo: count => `${count} 小時前`,
- daysAgo: count => `${count} 天前`,
- justNowSuffix: ' · 剛剛',
- bundleOutOfSync: '應用程式建置版本過舊',
- bundleOutOfSyncDesc:
- 'Hermes 執行環境已更新,但桌面應用程式本身仍是舊建置——在應用程式更新之前,新的介面功能(如 Bot Mode)不會顯示。請執行下方的更新以重新建置應用程式。如果此警告仍未消除,請從最新的桌面安裝程式重新安裝。',
- bundleOutOfSyncAction: '取得安裝程式',
- checkingShort: '檢查中…'
- },
-
- guidedGreeting: {
- line: '來了,進來吧。我是 Hermes。給我兩分鐘,把這裡按你的習慣整理一下,然後我們找件你真正想做的事來做。\n\n先說,我該怎麼稱呼你?',
- nameSuggestion: (name: string) => `(如果你願意,我也可以直接叫你 ${name}。)`
- },
- install: {
- stageStates: {
- pending: '等待中',
- running: '安裝中',
- succeeded: '完成',
- skipped: '已略過',
- failed: '失敗'
- },
- oneTimeTitle: 'Hermes 需要一次性安裝',
- unsupportedDesc: platform =>
- `${platform} 暫不支援自動首次啟動安裝。請開啟終端機並執行下面的指令,然後重新啟動此應用程式。之後啟動會略過此步驟。`,
- installCommand: '安裝指令',
- copyCommand: '複製指令',
- viewDocs: '檢視安裝文件',
- installTo: '將安裝至',
- retryAfterRun: '我已執行 -- 重試',
- setupChoiceTitle: '設定 Hermes Desktop',
- setupChoiceDesc: '將此應用程式連線到您已執行的 Hermes 閘道,或在這台電腦上本機安裝 Hermes。',
- connectExistingTitle: '連線到現有 Hermes',
- connectExistingShort: '連線現有環境',
- connectExistingDesc: '使用工作階段權杖或瀏覽器登入連線遠端後端。不會啟動本機安裝。',
- installLocalTitle: '本機安裝 Hermes',
- installLocalDesc: '下載 Hermes、建立 Python 環境,並在這台電腦上執行後端。',
- localStartUnavailable: '無法啟動本機安裝。請重新啟動 Hermes Desktop 後再試一次。',
- remoteSetupTitle: '連線到現有 Hermes',
- remoteSetupDesc: '輸入閘道 URL。Hermes Desktop 會偵測需要權杖還是瀏覽器登入。',
- remoteUrlTitle: '閘道 URL',
- remoteUrlDesc: '使用 Hermes 閘道的基礎 URL;遠端位址請包含 https://。',
- remoteUrlPlaceholder: 'https://gateway.example.com/hermes',
- probing: '正在偵測閘道驗證方式...',
- probeError: '無法連線到該 Hermes 閘道。',
- identityProvider: '您的身分提供者',
- authTitle: '驗證',
- authNeedsOauth: provider => `測試此閘道前請先使用 ${provider} 登入。`,
- authSignedIn: '瀏覽器登入已完成。',
- connected: '已連線',
- signIn: '登入',
- signInWith: provider => `使用 ${provider} 登入`,
- enterUrlFirst: '請先輸入閘道 URL。',
- signInIncomplete: '驗證完成前登入視窗已關閉。',
- tokenTitle: '工作階段權杖',
- tokenDesc: '貼上遠端閘道 .env 檔案中的工作階段權杖。',
- pasteSessionToken: '貼上工作階段權杖',
- incompleteSignInTest: '測試此受 OAuth 保護的閘道前請先登入。',
- incompleteTokenTest: '測試此閘道前請輸入工作階段權杖。',
- testConnection: '測試連線',
- testSucceeded: (baseUrl, version) => `已連線到 ${baseUrl}${version ? ` (${version})` : ''}。`,
- applyRemote: '套用並重新連線',
- backToSetup: '返回',
- failedTitle: '安裝失敗',
- settingUpTitle: '正在設定 Hermes Agent',
- finishingTitle: '正在收尾',
- failedDesc:
- '某個安裝步驟失敗。在 Windows 上,如果另一個 Hermes CLI 或桌面執行個體正在執行,可能會出現這種情況。請停止正在執行的 Hermes 執行個體後重試。可查看下方的詳細資訊或 desktop 記錄中的完整記錄。',
- activeDesc: '這是一次性設定。Hermes 安裝程式正在下載相依套件並設定您的電腦。之後啟動會略過此步驟。',
- progress: (completed, total) => `${completed}/${total} 個步驟已完成`,
- currentStage: stage => ` -- 目前:${stage}`,
- fetchingManifest: '正在取得安裝程式 manifest...',
- error: '錯誤',
- hideOutput: '隱藏安裝程式輸出',
- showOutput: '顯示安裝程式輸出',
- lines: count => `${count} 行`,
- noOutput: '暫無輸出。',
- cancelling: '取消中...',
- cancelInstall: '取消安裝',
- transcriptSaved: '完整記錄已儲存至',
- copiedOutput: '已複製!',
- copyOutput: '複製輸出',
- reloadRetry: '重新載入並重試'
- },
-
- onboarding: {
- headerTitle: '開始設定 Hermes Agent',
- headerDesc: '連線模型提供方即可開始聊天。大多數選項只需一次點擊。',
- preparingInstall: 'Hermes 正在完成安裝。首次執行通常不到一分鐘。',
- starting: '正在啟動 Hermes…',
- lookingUpProviders: '正在查詢提供方...',
- collapse: '收合',
- otherProviders: '其他提供方',
- haveApiKey: '我有 API 金鑰',
- chooseLater: '稍後再選擇提供方',
- recommended: '建議',
- connected: '已連線',
- featuredPitch: '一個訂閱,300+ 前沿模型 — 執行 Hermes 的建議方式',
- fireworksPitch: '直接模型 API — Fireworks 託管的前沿模型',
- localModelsTitle: '本地執行模型',
- localModelsPitch: '無需帳號——下載模型,在本機執行',
- openRouterPitch: '一個金鑰,數百個模型 — 穩定的預設選擇',
- apiKeyOptions: {
- fireworks: { short: '直接模型 API', description: '直接存取 Fireworks AI 託管的模型。' },
- openrouter: { short: '一個金鑰,多個模型', description: '用一個金鑰存取數百個模型。適合新安裝的預設選擇。' },
- openai: { short: 'GPT 等級模型', description: '直接存取 OpenAI 模型。' },
- gemini: { short: 'Gemini 模型', description: '直接存取 Google Gemini 模型。' },
- xai: { short: 'Grok 模型', description: '直接存取 xAI Grok 模型。' },
- local: {
- short: '自託管',
- description: '將 Hermes 指向本機或自託管的 OpenAI 相容端點(vLLM、llama.cpp、Ollama 等)。'
- }
- },
- backToSignIn: '返回登入',
- getKey: '取得金鑰',
- replaceCurrent: '取代目前值',
- pasteApiKey: '貼上 API 金鑰',
- couldNotSave: '無法儲存憑證。',
- connecting: '連線中',
- update: '更新',
- flowSubtitles: {
- pkce: '開啟瀏覽器登入,然後回到這裡繼續',
- device_code: '在瀏覽器中開啟驗證頁面 — Hermes 會自動連線',
- external: '先在終端機登入一次,然後回來繼續聊天'
- },
- startingSignIn: provider => `正在為 ${provider} 啟動登入...`,
- verifyingCode: provider => `正在透過 ${provider} 驗證您的代碼...`,
- connectedProvider: provider => `${provider} 已連線`,
- connectedPicking: provider => `${provider} 已連線。正在選擇預設模型...`,
- signInFailed: '登入失敗,請重試。',
- signInExpired:
- '等待授權逾時。通常是因為登入頁面在開啟的分頁中卡住(伺服器端問題)——請在該頁面完成登入後重試。若仍失敗,請改用 API 金鑰或 CLI 方式。',
- pickDifferentProvider: '選擇其他提供方',
- signInWith: provider => `使用 ${provider} 登入`,
- openedBrowser: provider => `已在瀏覽器中開啟 ${provider}。`,
- authorizeThere: '請在那裡授權 Hermes。',
- copyAuthCode: '複製授權碼並貼到下方。',
- pasteAuthCode: '貼上授權碼',
- reopenAuthPage: '重新開啟授權頁面',
- autoBrowser: provider => `已在瀏覽器中開啟 ${provider}。請在那裡授權 Hermes,連線會自動完成,無需複製或貼上。`,
- reopenSignInPage: '重新開啟登入頁面',
- waitingAuthorize: '等待您授權...',
- externalPending: provider => `${provider} 透過自己的 CLI 登入。請在終端機執行此指令,然後回來選擇「我已登入」:`,
- signedIn: '我已登入',
- deviceCodeOpened: provider => `已在瀏覽器中開啟 ${provider}。請在那裡輸入此代碼:`,
- reopenVerification: '重新開啟驗證頁面',
- copy: '複製',
- defaultModel: '預設模型',
- freeTier: '免費層',
- pro: 'Pro',
- free: '免費',
- price: (input, output) => `${input} 輸入 / ${output} 輸出 每 Mtok`,
- change: '變更',
- startChatting: '開始',
- docs: provider => `${provider} 文件`
- },
-
- modelPicker: {
- title: '切換模型',
- current: '目前:',
- unknown: '(未知)',
- search: '篩選提供方和模型...',
- noModels: '找不到模型。',
- addProvider: '新增提供方',
- loadFailed: '無法載入模型',
- downloading: '下載中',
- localDownloadsHeading: '本地',
- noAuthenticatedProviders: '沒有已驗證的提供方。',
- pro: 'Pro',
- proNeedsSubscription: 'Pro 模型需要付費 Nous 訂閱。',
- free: '免費',
- freeTier: '免費層',
- priceTitle: '每百萬 Token 的輸入/輸出價格',
- wasPrice: '原價',
- customModel: '自訂模型',
- addCustomModelAction: '新增自訂模型…',
- customModelPlaceholder: '輸入模型 ID,例如 openai/gpt-5'
- },
-
- modelVisibility: {
- title: '模型',
- search: '搜尋模型',
- noAuthenticatedProviders: '沒有已驗證的提供方。',
- addProvider: '新增提供方…',
- addCustomModel: '新增自訂模型',
- removeCustomModel: '移除自訂模型'
- },
-
- shell: {
- windowControls: '視窗控制項',
- paneControls: '窗格控制項',
- appControls: '應用程式控制項',
- modelMenu: {
- search: '搜尋模型',
- noModels: '找不到模型',
- editModels: '編輯模型…',
- followDefault: '使用設定中的預設模型',
- refreshModels: '重新整理模型',
- fast: '快速'
- },
- modelOptions: {
- noOptions: '此模型沒有可用選項',
- options: '選項',
- thinking: '思考',
- fast: '快速',
- effort: '推理強度',
- minimal: '最小',
- low: '低',
- medium: '中',
- high: '高',
- xhigh: '極高',
- max: '最高',
- ultra: '超高',
- sendsOnRoute: (level: string) => `此路由實際傳送 ${level}`,
- updateFailed: '模型選項更新失敗',
- fastFailed: '快速模式更新失敗'
- },
- gatewayMenu: {
- gateway: '閘道',
- connected: '已連線',
- connecting: '連線中',
- offline: '離線',
- inferenceReady: '推論已就緒',
- inferenceNotReady: '推論未就緒',
- checkingInference: '正在檢查推論',
- disconnected: '已中斷連線',
- reconnectGateway: '重新連線閘道',
- openSystem: '開啟系統面板',
- connection: label => `連線:${label}`,
- recentActivity: '最近活動',
- viewAllLogs: '查看全部記錄 →',
- messagingPlatforms: '訊息平台'
- },
- approvalMode: {
- title: '核准模式',
- ariaLabel: mode => `核准模式:${mode}`,
- manual: '手動',
- manualDescription: '執行需要核准的操作前詢問',
- smart: '智慧',
- smartDescription: '自動評估操作,並在需要時詢問',
- off: '關閉',
- offDescription: '不顯示核准提示,直接執行'
- },
- statusbar: {
- unknown: '未知',
- restart: '重新啟動',
- update: '更新',
- updateInProgress: '更新中',
- commitsBehind: (count, branch) => `落後 ${branch} ${count} 個提交`,
- desktopVersion: version => `Hermes Desktop v${version}`,
- backendVersion: version => `後端 v${version}`,
- clientLabel: version => `用戶端 v${version}`,
- connectionSsh: host => `SSH: ${host}`,
- connectionRemote: host => `遠端: ${host}`,
- connectionCloud: host => `雲端: ${host}`,
- connectionCloudTooltip: host => `Hermes Cloud · ${host}`,
- connectionSshTooltip: host => `SSH · ${host}`,
- connectionRemoteTooltip: host => `Remote · ${host}`,
- backendLabel: version => `後端 v${version}`,
- commit: sha => `提交 ${sha}`,
- branch: branch => `分支 ${branch}`,
- closeCommandCenter: '關閉命令中心',
- openCommandCenter: '開啟命令中心',
- showTerminal: '顯示終端機',
- hideTerminal: '隱藏終端機',
- gateway: '閘道',
- gatewayReady: '就緒',
- gatewayNeedsSetup: '需要設定',
- gatewayUnavailable: '推論不可用',
- gatewayChecking: '檢查中',
- gatewayConnecting: '連線中',
- gatewayOffline: '離線',
- gatewayRestarting: '重新啟動中…',
- gatewayTitle: '閘道',
- agents: '代理',
- closeAgents: '關閉代理',
- openAgents: '開啟代理',
- subagents: count => `${count} 個子代理`,
- failed: count => `${count} 個失敗`,
- running: count => `${count} 個執行中`,
- cron: '排程',
- openCron: '開啟排程工作',
- starmap: '記憶圖譜',
- openStarmap: '開啟記憶圖譜',
- turnRunning: '執行中',
- contextUsage: '上下文使用量',
- systemResources: {
- title: '系統資源',
- loading: '資源…',
- gpuUtilization: 'GPU 使用率',
- gpuMemory: '顯示記憶體',
- ram: '記憶體',
- unifiedNote: '統一記憶體——GPU 與系統共享此記憶體池。',
- toggle: '系統資源'
- },
- contextUsagePanel: {
- categories: {
- conversation: '對話',
- mcp: 'MCP',
- memory: '記憶',
- rules: '規則',
- skills: '技能',
- subagent_definitions: '子代理定義',
- system_prompt: '系統提示詞',
- tool_definitions: '工具定義'
- },
- empty: '尚無上下文資料',
- loading: '正在載入明細…',
- percentFull: percent => `已用 ${percent}%`,
- title: '上下文使用量',
- tokenSummary: (used, max) => `${used} / ${max} Tokens`
- },
- focusedSince: '聚焦以來',
- focusedSinceTitle: '自本次聚焦此對話以來的時間,不是回合執行時長',
- yoloOn: 'YOLO 已開啟 — 自動核准危險指令。Shift+點擊可全域切換。',
- yoloOff: 'YOLO 已關閉。Shift+點擊可全域切換。',
- modelNone: '無',
- noModel: '無模型',
- switchModel: '切換模型',
- openModelPicker: '開啟模型選擇器',
- modelPinned: '已由你固定;新對話將使用此模型而非「設定」中的預設模型',
- modelTitle: (provider, model) => `模型 · ${provider}:${model}`,
- providerModelTitle: (provider, model) => `${provider} · ${model}`
- }
- },
-
- rightSidebar: {
- aria: '右側邊欄',
- panelsAria: '右側邊欄面板',
- files: '檔案系統',
- terminal: '終端機',
- noFolderSelected: '未選擇資料夾',
- changeCwdTitle: '變更工作目錄',
- remotePickerTitle: '選擇遠端資料夾',
- remotePickerDescription: '瀏覽已連線後端上的資料夾。',
- remotePickerSelect: '選擇資料夾',
- remotePickerNewFolder: '新增資料夾',
- remotePickerFolderName: '資料夾名稱',
- remotePickerCreateFolder: '建立資料夾',
- remotePickerInvalidFolderName: '請輸入單一資料夾名稱,不要包含斜線。',
- remotePickerCreateFolderFailed: error => `無法建立資料夾 (${error})。`,
- folderTip: cwd => cwd,
- openFolder: '開啟資料夾',
- refreshTree: '重新整理檔案樹',
- collapseAll: '收合所有資料夾',
- showIgnored: '顯示 gitignore 的檔案',
- hideIgnored: '隱藏 gitignore 的檔案',
- previewUnavailable: '預覽不可用',
- couldNotPreview: path => `無法預覽 ${path}`,
- noProjectTitle: '沒有專案',
- noProjectBody: '開啟一個專案以瀏覽檔案並檢視變更。',
- noProjectOpen: '未開啟專案',
- noDiffs: '無差異',
- unreadableTitle: '無法讀取',
- unreadableBody: error => `無法讀取此資料夾 (${error})。`,
- emptyTitle: '空資料夾',
- emptyBody: '此資料夾是空的。',
- treeErrorTitle: '檔案樹錯誤',
- treeErrorBody: '檔案樹在渲染此資料夾時發生錯誤。',
- tryAgain: '重試',
- loadingTree: '正在載入檔案樹',
- loadingFiles: '正在載入檔案',
- terminalHide: '隱藏終端機',
- terminalsAria: '終端機',
- terminalNew: '新增終端機',
- terminalCloseOthers: '關閉其他',
- terminalCloseAll: '全部關閉',
- addToChat: '新增至聊天'
- },
-
- preview: {
- tab: '預覽',
- closePane: '關閉預覽窗格',
- loading: '正在載入預覽',
- unavailable: '預覽不可用',
- opening: '開啟中...',
- hide: '隱藏',
- openPreview: '開啟預覽',
- openInBrowser: '在瀏覽器中開啟',
- openInExternal: '在外部開啟',
- popIn: '彈回',
- popOut: '彈出',
- linkHint: '⌘/Ctrl+點擊在預覽窗格開啟',
- sourceLineTitle: '點擊選取 · shift 點擊擴展 · 拖曳至輸入框',
- source: '原始碼',
- renderedPreview: '預覽',
- diff: '差異',
- unknownSize: '大小未知',
- binaryTitle: '這看起來像二進位檔案',
- binaryBody: label => `預覽 ${label} 可能會顯示無法讀取的文字。`,
- largeTitle: '此檔案較大',
- largeBody: (label, size) => `${label} 大小為 ${size}。Hermes 只會顯示前 512 KB。`,
- previewAnyway: '仍然預覽',
- truncated: '顯示前 512 KB。',
- noInlineTitle: '沒有行內預覽',
- noInlineBody: mimeType => `${mimeType || '此檔案類型'} 仍可作為脈絡附件。`,
- edit: '編輯',
- editing: '編輯中',
- unsavedChanges: '未儲存的變更',
- saveFailed: message => `無法儲存:${message}`,
- diskChangedTitle: '檔案已在磁碟上變更',
- diskChangedBody: '此檔案自開啟以來已變更。用你的版本覆寫,還是放棄你的編輯並重新載入?',
- overwrite: '覆寫',
- discardReload: '放棄並重新載入',
- console: {
- deselect: '取消選取項目',
- select: '選取項目',
- copyFailed: '無法複製主控台輸出',
- copyEntry: '複製此項目',
- sendEntry: '將此項目傳送至聊天',
- messages: count => `${count} 則主控台訊息`,
- resize: '調整預覽主控台大小',
- title: '預覽主控台',
- selected: count => `已選取 ${count} 個`,
- sendToChat: '傳送至聊天',
- copySelected: '複製所選至剪貼簿',
- copyAll: '全部複製至剪貼簿',
- copy: '複製',
- clear: '清除',
- empty: '暫無主控台訊息。',
- promptHeader: '預覽主控台:',
- sentTitle: '已傳送至聊天',
- sentMessage: count => `已將 ${count} 條記錄新增至輸入框`
- },
- web: {
- appFailedToBoot: '預覽應用程式啟動失敗',
- serverNotFound: '找不到伺服器',
- remoteLoopback:
- '這個位址指向執行代理的那台機器,而不是本機。瀏覽器窗格會在本機載入頁面,因此遠端開發伺服器需要連接埠轉送或可連線的主機名稱。',
- failedToLoad: '預覽載入失敗',
- tryAgain: '重試',
- restarting: 'Hermes 正在重新啟動...',
- askRestart: '請 Hermes 重新啟動伺服器',
- lookingRestart: taskId => `Hermes 正在尋找要重新啟動的預覽伺服器 (${taskId})`,
- restartingTitle: '正在重新啟動預覽伺服器',
- restartingMessage: 'Hermes 正在背景執行。可在預覽主控台查看進度。',
- startRestartFailed: message => `無法啟動伺服器重新啟動:${message}`,
- restartFailed: '伺服器重新啟動失敗',
- hideConsole: '隱藏預覽主控台',
- showConsole: '顯示預覽主控台',
- hideDevTools: '隱藏預覽 DevTools',
- openDevTools: '開啟預覽 DevTools',
- goBack: '上一頁',
- goForward: '下一頁',
- reload: '重新載入頁面',
- address: '網址',
- addressPlaceholder: '輸入網址',
- blankPageBody: '在上方輸入網址開始瀏覽,或請 Hermes 開啟頁面。',
- finishedRestarting: message => `Hermes 已完成預覽伺服器重新啟動${message ? `:${message}` : ''}`,
- failedRestarting: message => `伺服器重新啟動失敗:${message}`,
- unknownError: '未知錯誤',
- restartedTitle: '預覽伺服器已重新啟動',
- reloadingNow: '正在重新載入預覽。',
- restartFailedTitle: '預覽重新啟動失敗',
- restartFailedMessage: 'Hermes 無法重新啟動伺服器。',
- stillWorking: 'Hermes 仍在執行,但尚未收到重新啟動結果。伺服器指令可能正在前台執行。',
- workspaceReloading: '工作區已變更,正在重新載入預覽',
- fileChanged: url => `檔案已變更,正在重新載入預覽:${url}`,
- filesChanged: (count, url) => `${count} 個檔案變更,正在重新載入預覽:${url}`,
- watchFailed: message => `無法監看預覽檔案:${message}`,
- moduleMimeDescription:
- '模組指令碼使用了錯誤的 MIME 類型。這通常表示靜態檔案伺服器正在服務 Vite/React 應用程式,而不是專案開發伺服器。',
- loadFailedConsole: (code, message) => `載入失敗${code ? ` (${code})` : ''}:${message}`,
- unreachableDescription: '無法連線至預覽頁面。',
- openTarget: url => `開啟 ${url}`,
- fallbackTitle: '預覽'
- }
- },
-
++ queueLostDiscardTip: '閘道在該回合進行中重新啟動,無法完成。捨棄後其後的排隊回合將繼續執行。'
++ },
+ statusStack: zhHantChat.statusStack,
+ updates: zhHantBoot.updates,
+ guidedGreeting: zhHantBoot.guidedGreeting,
+ install: zhHantBoot.install,
+ onboarding: zhHantBoot.onboarding,
+ modelPicker: zhHantSettings.modelPicker,
+ modelVisibility: zhHantSettings.modelVisibility,
+ shell: zhHantChrome.shell,
+ rightSidebar: zhHantChrome.rightSidebar,
+ preview: zhHantArtifacts.preview,
interfaceMode: {
title: '介面模式',
hint: '只改變顯示的內容,不改變 Hermes 的能力。',
diff --cc apps/desktop/src/lib/chat-messages/hydration.ts
index 6447bec775f,f04de45b2af..ad6aa2e1b2e
--- a/apps/desktop/src/lib/chat-messages/hydration.ts
+++ b/apps/desktop/src/lib/chat-messages/hydration.ts
@@@ -1,8 -1,8 +1,9 @@@
import { skillInvocationText } from '@hermes/shared'
+import { formatRefValue } from '@/components/assistant-ui/directive-text'
import { splitLeadingAttachmentRefs } from '@/components/assistant-ui/reference-kinds'
import { extractImageRefs } from '@/lib/embedded-images'
+ import { parseErrorSurface } from '@/lib/error-surface'
import { dedupeGeneratedImageEchoesInParts } from '@/lib/generated-images'
import { isTodoToolName } from '@/lib/todos'
import type { MessageReaction, SessionMessage } from '@/types/hermes'
diff --cc apps/desktop/src/plugins/hermes-bots/relay.test.ts
index 59d83599d12,e91894f09ab..88e05303c6b
--- a/apps/desktop/src/plugins/hermes-bots/relay.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/relay.test.ts
@@@ -644,8 -850,15 +851,15 @@@ describe('the drain loop wires drain �
expect(calls.find(call => call.method === 'bot_relay.deliver')).toMatchObject({
connectionId: 'b',
- params: { message: 'status?', profile: 'ops' }
+ params: { id: envelope.id, message: 'status?', profile: 'ops' }
})
+
+ // #93911: the deliver deadline must outlive the backend's own turn bound.
+ const deliverCall = (hostMock.requestProfile as ReturnType<typeof vi.fn>).mock.calls.find(
+ ([, method]) => method === 'bot_relay.deliver'
+ )
+
+ expect(deliverCall?.[3]).toBe(RELAY_DELIVER_TIMEOUT_MS)
expect(calls.find(call => call.method === 'bot_relay.reply')).toMatchObject({
connectionId: 'a',
params: { id: 'env-1', reply: 'all green' }
diff --cc apps/desktop/src/plugins/hermes-bots/relay.ts
index 124d111d757,c16771434c6..d5a5df8a48f
--- a/apps/desktop/src/plugins/hermes-bots/relay.ts
+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts
@@@ -232,16 -250,15 +261,17 @@@ async function relayConnections(): Prom
}
try {
- const routes = await host.profileRoutes()
+ const rawRoutes = await host.profileRoutes()
+ const routes = relayEligibleRoutes(Array.isArray(rawRoutes) ? rawRoutes : [])
const byConnection = new Map<string, ProfileRoute>()
- for (const route of Array.isArray(routes) ? routes : []) {
+ for (const route of routes) {
const id = String(route?.connectionId || '')
- if (id && !byConnection.has(id)) {
- byConnection.set(id, route)
+ const key = JSON.stringify(route)
+
+ if (id && !byConnection.has(key)) {
+ byConnection.set(key, route)
}
}
diff --cc apps/desktop/src/store/composer-queue.ts
index 59c7c108806,9dd268a9439..3d9123d102a
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@@ -1,23 -1,13 +1,32 @@@
import { SLASH_COMMAND_RE } from '@hermes/shared'
import { atom } from 'nanostores'
+ import {
+ type ComposerAttachment,
+ draftHasTerminalChips,
+ revokeAttachmentPreviewUrls,
+ revokeDiscardedAttachmentPreviews
+ } from './composer'
+import { $connection } from './session'
+import { knownOwnerForSession } from './session-states'
+
+/** Local owner routes use canonical admission; remote legacy queues stay local. */
+export function serverOwnsComposerQueue(sessionId: string | null | undefined): boolean {
+ const owner = knownOwnerForSession(sessionId)
+
- if (owner && typeof owner === 'object' && owner.mode) { return owner.mode === 'local' }
++ if (owner && typeof owner === 'object' && owner.mode) {
++ return owner.mode === 'local'
++ }
++
+ const connection = $connection.get()
+
- if (owner && typeof owner === 'object' && owner.connectionId !== connection?.connectionId) { return false }
++ if (owner && typeof owner === 'object' && owner.connectionId !== connection?.connectionId) {
++ return false
++ }
+
+ return Boolean(connection?.wsUrl && new URL(connection.wsUrl).searchParams.has('native_dial'))
+}
- import { type ComposerAttachment, revokeAttachmentPreviewUrls, revokeDiscardedAttachmentPreviews } from './composer'
-
export interface RemoveQueuedPromptOptions {
/**
* When true, leave blob: preview URLs alive because submit/optimistic now
@@@ -47,6 -38,104 +58,106 @@@ export interface QueuedPromptEntry
queuedAt: number
}
+ export interface EnqueueQueuedPromptPayload {
++ /** Stable id to reuse (a canonical submission id), else one is minted. */
++ id?: string
+ text: string
+ attachments: ComposerAttachment[]
+ displayText?: string
+ displayKind?: 'hidden'
+ /** Fenced `@terminal` transport. Runtime-only; never written to localStorage. */
+ frozenTransport?: string
+ }
+
+ export type ResolvedQueuedPromptTransport =
+ { ok: true; transportText: string; displayText?: string } | { ok: false; reason: 'missing-terminal-payload' }
+
+ /**
+ * Frozen terminal transport for queued entries, keyed by stable `queuedPromptId`.
+ * Memory-only on purpose: persisting selection CONTENTS in
+ * `hermes.desktop.composerQueue.v1` would survive renderer restart as stale
+ * secrets-adjacent terminal output, and label reuse after reload cannot
+ * reconstruct the original pane (#77078).
+ */
+ const frozenQueuedTransportById = new Map<string, string>()
+
+ export const getFrozenQueuedTransport = (id: string): string | undefined => frozenQueuedTransportById.get(id)
+
+ export const setFrozenQueuedTransport = (id: string, transportText: string): void => {
+ const trimmed = transportText.trim()
+
+ if (!trimmed) {
+ frozenQueuedTransportById.delete(id)
+
+ return
+ }
+
+ frozenQueuedTransportById.set(id, trimmed)
+ }
+
+ export const clearFrozenQueuedTransport = (id: string): void => {
+ frozenQueuedTransportById.delete(id)
+ }
+
+ export const resetFrozenQueuedTransportsForTests = (): void => {
+ frozenQueuedTransportById.clear()
+ }
+
+ export const queuedEntryHasTerminalChips = (entry: Pick<QueuedPromptEntry, 'displayText' | 'text'>): boolean =>
+ draftHasTerminalChips(entry.displayText ?? '') || draftHasTerminalChips(entry.text)
+
+ export const resolveQueuedPromptTransport = (entry: QueuedPromptEntry): ResolvedQueuedPromptTransport => {
+ if (!queuedEntryHasTerminalChips(entry)) {
+ return {
+ ok: true,
+ transportText: entry.text,
+ ...(entry.displayText ? { displayText: entry.displayText } : {})
+ }
+ }
+
+ const frozen = frozenQueuedTransportById.get(entry.id)?.trim()
+
+ if (!frozen) {
+ return { ok: false, reason: 'missing-terminal-payload' }
+ }
+
+ const chipText = entry.displayText ?? entry.text
+
+ return { ok: true, transportText: frozen, displayText: chipText }
+ }
+
+ const dropFrozenTransportsRemovedFrom = (previous: QueuedPromptEntry[], next: QueuedPromptEntry[]) => {
+ const nextIds = new Set(next.map(entry => entry.id))
+
+ for (const entry of previous) {
+ if (!nextIds.has(entry.id)) {
+ frozenQueuedTransportById.delete(entry.id)
+ }
+ }
+ }
+
+ const toPersistedEntry = (entry: QueuedPromptEntry): QueuedPromptEntry => {
+ const frozen = frozenQueuedTransportById.get(entry.id)?.trim()
+
+ if (!frozen) {
+ return entry
+ }
+
+ // Never write fenced selection CONTENTS into localStorage. Prefer the chip
+ // form already on the entry; if `text` accidentally holds transport, swap it.
+ const persisted: QueuedPromptEntry = { ...entry }
+
+ if (persisted.text === frozen) {
+ persisted.text = persisted.displayText ?? ''
+ }
+
+ if (persisted.displayText === frozen) {
+ delete persisted.displayText
+ }
+
+ return persisted
+ }
+
/** Whether a queued entry can ride a mid-turn redirect: text-only, non-empty,
* not a slash command — the same gate `steerDraft` applies to the live draft
* (attachments can't ride a redirect; slash commands execute, not steer). */
@@@ -141,8 -265,10 +287,15 @@@ const mutateSession = (sid: string, op
// linger as stale state and silently gate entries queued much later.
setParked(sid, false)
}
+
+ return true
}
++/** Replace one session's queue wholesale (canonical receipt reconciliation),
++ * through the same live-merge path as every other mutation. */
++export const writeSessionQueue = (sid: string, queue: QueuedPromptEntry[]): boolean =>
++ mutateSession(sid, () => queue)
++
if (typeof window !== 'undefined') {
// Cross-window sync (#46732): every desktop window boots the queue atom from
// the same localStorage key. The `storage` event fires in every window EXCEPT
@@@ -241,12 -387,15 +414,17 @@@ export const removeQueuedPrompt =
return false
}
- const queue = queueFor(sid)
- const removed = queue.find(e => e.id === id)
+ let removed: QueuedPromptEntry | undefined
+
+ // Server-owned (admitted) rows retire through the gateway, never locally.
- const next = queue.filter(e => e.id !== id || e.serverStatus)
+
- if (!removed || next.length === queue.length) {
+ mutateSession(sid, queue => {
- removed = queue.find(e => e.id === id)
++ removed = queue.find(e => e.id === id && !e.serverStatus)
+
+ return removed ? queue.filter(e => e.id !== id) : null
+ })
+
+ if (!removed) {
return false
}
diff --cc apps/desktop/src/store/gateway-profile-request.test.ts
index afbd361ab8d,5b0d32f1bd1..563e01f5b6e
--- a/apps/desktop/src/store/gateway-profile-request.test.ts
+++ b/apps/desktop/src/store/gateway-profile-request.test.ts
@@@ -110,7 -111,99 +110,99 @@@ describe('requestGatewayForProfile', (
expect($gateway.get()).toBe(primary)
})
+ it('background polls on a down local profile leave redialing to the ladder; a user action still dials (#121865)', async () => {
+ vi.useFakeTimers()
+
+ try {
+ setPrimaryGateway(makePrimary() as never, 'default')
+
+ // The target profile's backend never comes up.
+ const getConnection = vi.fn(async (profile: null | string) => {
+ if (profile === 'jody') {
+ throw new Error('Failed to connect to Hermes gateway')
+ }
+
+ return { port: 4242, token: 'primary-token' }
+ })
+
+ installDesktop(getConnection)
+ await ensureGatewayForProfile('default')
+
+ const jodyDials = () => getConnection.mock.calls.filter(([profile]) => profile === 'jody').length
+
+ // session.control.read against a cross-profile session, polled 20 times in one second.
+ for (let index = 0; index < 20; index += 1) {
+ await requestGatewayForProfile('jody', 'session.control.read', {}).catch(() => undefined)
+ await vi.advanceTimersByTimeAsync(50)
+ }
+
+ // Every attempt is two dials into main: the shared-primary probe, then the secondary.
+ // Before, all 20 polls attempted (40 dials). Now attempts wait out a window that doubles
+ // from 300ms, so one second holds three of them: t=0, t=300, t=900.
+ const backgroundDials = jodyDials()
+ expect(backgroundDials).toBe(6)
+
+ // Inside the same cooldown, a user action is not held back.
+ await requestGatewayForProfile('jody', 'session.activate', {}, undefined, undefined, {
+ spawnPriority: 'foreground'
+ }).catch(() => undefined)
+ expect(jodyDials()).toBeGreaterThan(backgroundDials)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('a served request clears dial history, so the next outage starts back at the shortest window (#121865)', async () => {
+ vi.useFakeTimers()
+
+ try {
+ setPrimaryGateway(makePrimary() as never, 'default')
+
+ let jodyUp = false
+
+ const getConnection = vi.fn(async (profile: null | string) => {
+ if (profile === 'jody') {
+ if (!jodyUp) {
+ throw new Error('Failed to connect to Hermes gateway')
+ }
+
+ return { port: 5151, profile, token: 'secondary-token' }
+ }
+
+ return { port: 4242, token: 'primary-token' }
+ })
+
+ installDesktop(getConnection)
+ await ensureGatewayForProfile('default')
+
+ const poll = () => requestGatewayForProfile('jody', 'session.control.read', {}).catch(() => undefined)
+ const jodyDials = () => getConnection.mock.calls.filter(([profile]) => profile === 'jody').length
+
+ // Three failed attempts in the first second widen the window to 1200ms.
+ for (let index = 0; index < 20; index += 1) {
+ await poll()
+ await vi.advanceTimersByTimeAsync(50)
+ }
+
+ // The backend recovers and serves a request once the widened window has passed.
+ jodyUp = true
+ await vi.advanceTimersByTimeAsync(2_000)
+ await expect(requestGatewayForProfile('jody', 'session.control.read', {})).resolves.toBeDefined()
+
+ // A fresh outage: one failure opens a 300ms window again, so a poll 300ms later dials.
+ // Had the old streak survived, the window would be 2400ms and that poll would be held.
+ jodyUp = false
+ const before = jodyDials()
+ await poll()
+ await vi.advanceTimersByTimeAsync(300)
+ await poll()
+ expect(jodyDials() - before).toBe(4)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
- it('dials the profile with foreground priority when a Settings-scoped caller asks for it (#111651)', async () => {
+ it('accepts a Settings-scoped foreground dial hint without changing the canonical dial (#111651)', async () => {
setPrimaryGateway(makePrimary() as never, 'default')
const getConnection = vi.fn(async (profile: null | string) =>
diff --cc apps/desktop/src/store/gateway.ts
index ce01ec0f8bc,876a109bab9..dea73e8b416
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@@ -748,8 -806,12 +779,8 @@@ async function openSecondary(entry: Sec
const conn =
entry.connectionId && desktop.getConnectionFor
? await withTimeout(
- desktop.getConnectionFor({
- connectionId: entry.connectionId,
- profile: entry.profile,
- ...dialPriority(spawnPriority)
- }),
+ desktop.getConnectionFor({ connectionId: entry.connectionId, profile: entry.profile }),
- RECONNECT_ATTEMPT_TIMEOUT_MS,
+ SOURCE_SWITCH_DIAL_TIMEOUT_MS,
`Timed out connecting to profile "${entry.profile}"`
)
: await withTimeout(
@@@ -870,6 -940,56 +907,56 @@@ function rearmSecondary(entry: Secondar
entry.retiredByPool = false
}
+ function recordDialFailure(entry: Secondary, error?: unknown): void {
+ // Auth rejection has its own ledger (reauthFailures) that already fails background callers fast.
+ if (error !== undefined && isGatewayReauthRequired(error)) {
+ return
+ }
+
+ const previous = g.dialFailures.get(entry.scope)
+
+ g.dialFailures.set(entry.scope, {
+ at: Date.now(),
+ streak: (previous?.streak ?? 0) + 1,
+ connectionId: entry.connectionId ?? null
+ })
+ }
+
+ /** True while a background caller must leave redialing to the ladder: the scope's last dial
+ * failed (or its socket died before RECONNECT_STABLE_OPEN_MS) inside a window that widens with
+ * the failure streak, on the same ceilings as the reconnect ladder. History clears on proof of
+ * health (a served RPC, or a socket that lived) and on a fresh start (foreground re-arm, connection
+ * removal, full teardown) — never on a bare open, so an accept-then-close backend keeps escalating. */
+ function backgroundDialCoolingDown(scope: string, now = Date.now()): boolean {
+ const failure = g.dialFailures.get(scope)
+
+ return failure !== undefined && now - failure.at < reconnectBackoffDelayMs(failure.streak - 1, { jitter: false })
+ }
+
+ /** Dial a request's secondary if it is down. Both request paths (a plain profile via
+ * gatewayForProfile, a registry route via requestGatewayForAgent) used to dial straight past
+ * the reconnect ladder, and openSecondary only coalesces CONCURRENT dials, so a poller against
+ * a scope whose socket accepts and then dies redialed once per tick (session.control.read on a
+ * cross-profile session, #121865). After a failure, background callers fail fast and leave
+ * redialing to scheduleReconnect; a user action (foreground) still dials at once. */
+ async function openSecondaryForRequest(entry: Secondary, spawnPriority: SpawnPriority): Promise<void> {
+ if (isOpen(entry.gateway)) {
+ return
+ }
+
+ if (spawnPriority !== 'foreground' && backgroundDialCoolingDown(entry.scope)) {
+ scheduleReconnect(entry)
+ throw new Error(`Backend for "${entry.profile}" is reconnecting; retry after it settles.`)
+ }
+
+ try {
- await openSecondary(entry, spawnPriority)
++ await openSecondary(entry)
+ } catch (error) {
+ recordDialFailure(entry, error)
+ throw error
+ }
+ }
+
function scheduleReconnect(entry: Secondary): void {
if (entry.reconnecting || entry.reconnectTimer !== null || !entry.wantOpen) {
return
@@@ -1090,7 -1218,15 +1182,15 @@@ async function gatewayForProfile
return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: false }
}
+ // sharedPrimaryRoute is itself a dial into main (it can start the profile's spawn), so a
+ // cooling-down scope has to be held back before it, not just before openSecondary.
+ const existing = g.secondaries.get(key)
+
+ if (spawnPriority !== 'foreground' && !(existing && isOpen(existing.gateway)) && backgroundDialCoolingDown(key)) {
+ throw new Error(`Backend for "${key}" is reconnecting; retry after it settles.`)
+ }
+
- if (await sharedPrimaryRoute(key, spawnPriority)) {
+ if (await sharedPrimaryRoute(key)) {
return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: true }
}
diff --cc apps/desktop/src/store/notifications.ts
index bc84bcf3983,5fa9388b86f..d205531eb2e
--- a/apps/desktop/src/store/notifications.ts
+++ b/apps/desktop/src/store/notifications.ts
@@@ -2,6 -2,9 +2,8 @@@ import { atom } from 'nanostores
import { translateNow } from '@/i18n'
import { isOutOfSyncRpcParams } from '@/lib/gateway-rpc'
+ import { isTimeoutError } from '@/lib/with-timeout'
+ import { type ErrorToastCategory, recordFriction } from '@/store/desktop-metrics'
-import { isLocalBackendSlotWaitTimeout, requestPoolLimitsSettings } from '@/store/pool-limits'
import { requestBackendRestart, requestRoute } from '@/store/recovery-requests'
export type NotificationKind = 'error' | 'warning' | 'info' | 'success'
@@@ -276,17 -312,32 +311,23 @@@ export function notifyError
options: { action?: NotificationAction; id?: string } = {}
): string {
const readable = readableError(error, fallback)
- const poolSlotTimeout = isLocalBackendSlotWaitTimeout(error)
logErrorToDesktopLog(error, fallback)
- return notify({
- action: options.action ?? readable.action,
- // A caller that can fire again for the same cause names its toast, so the repeat replaces it.
- id: options.id,
- kind: 'error',
- title: fallback,
- message: readable.message,
- detail: readable.detail
- })
- const category: ErrorToastCategory = poolSlotTimeout
- ? 'pool_slot_timeout'
- : readable.category === 'unclassified' && isTimeoutError(error)
- ? 'timeout'
- : readable.category
++ const category: ErrorToastCategory =
++ readable.category === 'unclassified' && isTimeoutError(error) ? 'timeout' : readable.category
+
+ return showNotification(
+ {
- action: poolSlotTimeout
- ? {
- label: translateNow('desktop.poolSlotTimeoutOpenSettings'),
- onClick: requestPoolLimitsSettings
- }
- : (options.action ?? readable.action),
++ action: options.action ?? readable.action,
+ // A caller that can fire again for the same cause names its toast, so the repeat replaces it.
+ id: options.id,
+ kind: 'error',
+ title: fallback,
- message: poolSlotTimeout ? translateNow('desktop.poolSlotTimeoutBody') : readable.message,
- detail: poolSlotTimeout ? readable.message : readable.detail
++ message: readable.message,
++ detail: readable.detail
+ },
+ category
+ )
}
export function dismissNotification(id: string) {
diff --cc apps/desktop/src/store/profile.test.ts
index 013b9afe6d2,0e53d4f4465..104b6b07273
--- a/apps/desktop/src/store/profile.test.ts
+++ b/apps/desktop/src/store/profile.test.ts
@@@ -210,6 -221,58 +212,29 @@@ describe('prewarmProfileBackend (hover-
expect(() => prewarmProfileBackend('warm-failing')).not.toThrow()
})
+
- it('skips pre-warm when the pool is saturated (#91545 evict/respawn cascade)', () => {
- // Every pool slot occupied: a speculative spawn would LRU-evict a warm
- // backend — often the one the user is about to click. Default limit 3,
- // 3 open secondaries → the next spawn would exceed the cap.
- openSecondaryCount.mockReturnValue(3)
-
- prewarmProfileBackend('warm-saturated')
-
- expect(openGatewayForProfile).not.toHaveBeenCalled()
- })
-
- it('follows the live pool-limit atom, not a hard-coded cap', () => {
- // User raises Warm Bot Backends to 8 in Settings: prewarming must keep
- // working well past the old default of 3.
- openSecondaryCount.mockReturnValue(5)
- $poolLimits.set({ idleMs: 600_000, maxBackends: 8 })
-
- prewarmProfileBackend('warm-raised-cap')
-
- expect(openGatewayForProfile).toHaveBeenCalledWith('warm-raised-cap')
-
- // And lowering the cap re-engages the guard at the new boundary.
- $poolLimits.set({ idleMs: 600_000, maxBackends: 2 })
-
- prewarmProfileBackend('warm-lowered-cap')
-
- expect(openGatewayForProfile).not.toHaveBeenCalledWith('warm-lowered-cap')
- })
-
+ // A hover-warm on a current-source pick must dial the pair the click will:
+ // the bare name resolved on the legacy door, so hovering a remote source's
+ // `default` spawned This device's default instead (#100098 review).
+ it('warms the same (connection, profile) a current-source pick activates', async () => {
+ activeGatewayConnectionId.mockReturnValue('gateway')
+ $activeGatewayProfile.set('research')
+ openGatewayForAgent.mockClear()
+ ensureGatewayForAgent.mockClear()
+
+ try {
+ prewarmProfilePick('default')
+ selectProfile('default')
+ await vi.waitFor(() => expect(ensureGatewayForAgent).toHaveBeenCalled())
+
+ expect(openGatewayForProfile).not.toHaveBeenCalled()
+ expect(openGatewayForAgent.mock.calls.map(([connection, name]) => [connection, name])).toEqual(
+ ensureGatewayForAgent.mock.calls.map(([connection, name]) => [connection, name])
+ )
+ } finally {
+ activeGatewayConnectionId.mockReturnValue(null)
+ }
+ })
})
describe('refreshProfiles shared rail list (#49289)', () => {
diff --cc apps/desktop/src/store/session.ts
index 72b0b01aa3e,52ad8842078..71ed97487eb
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@@ -1582,13 -1598,15 +1599,19 @@@ export const markSessionRead = (storedS
export const setMessages = (next: Updater<ChatMessage[]>) => updateAtom($messages, next)
export const setFreshDraftReady = (next: Updater<boolean>) => updateAtom($freshDraftReady, next)
+
+ // The fresh-draft identity lives in store/composer.ts with the draft stash it
+ // keys; re-exported here because session.ts is where new-chat lifecycles rotate
+ // it (startFreshSessionDraft) and where most call sites already import from.
+ export { $freshDraftKey, rotateFreshDraftKey } from './composer'
+
export const setResumeFailedSessionId = (next: Updater<string | null>) => updateAtom($resumeFailedSessionId, next)
-export const requestSessionResume = (sessionId: string, ownerRoute?: SessionOwnerRoute) => {
+export const requestSessionResume = (
+ sessionId: string,
+ ownerRoute?: SessionOwnerRoute,
+ options?: { authoritativeSnapshot?: boolean }
+) => {
const id = sessionId.trim()
if (!id) {
diff --cc apps/desktop/src/store/updates.ts
index 283849a944a,bd6a705487d..3fb8f6e68e6
--- a/apps/desktop/src/store/updates.ts
+++ b/apps/desktop/src/store/updates.ts
@@@ -3,9 -3,9 +3,10 @@@
* surfaces it as an ambient pill, and orchestrates the apply flow.
*/
+ import { updateDebt } from '@hermes/shared'
import { atom } from 'nanostores'
+import { CANONICAL_GATEWAY_PROTOCOL } from '@/api/canonical-protocol'
import { connectionScoped, profileScoped } from '@/api/client'
import type {
DesktopUpdateApplyOptions,
diff --cc apps/desktop/src/types/hermes.ts
index 446aeaebce3,164c806dfcd..e9bc7f4ff1f
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@@ -466,8 -487,8 +487,9 @@@ export interface HermesConfig
personality?: string
skin?: string
interim_assistant_messages?: boolean
+ busy_input_mode?: string
timestamps?: boolean
+ tool_progress?: boolean | string
}
desktop?: {
font_family?: string
diff --cc apps/shared/src/json-rpc-gateway.ts
index 3a1f5f1aff2,945a6d6e7d3..f8d653ddb2c
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@@ -541,14 -537,13 +541,21 @@@ export class JsonRpcGatewayClient
}
try {
+ const sessionEpochBefore = this.replayEpochBySession.get(sid) ?? this.replayEpoch
+
// `open_requests` on the answer are re-delivered by the channel itself.
- const result = await this.request<{ events?: GatewayEvent[]; epoch?: string; replay_epoch?: unknown; truncated?: unknown; snapshot_required?: unknown; latest_seq?: unknown }>(
+ const result = await this.request<{
+ epoch?: string
+ events?: GatewayEvent[]
+ latest_seq?: number
++ replay_epoch?: unknown
++ snapshot_required?: unknown
+ truncated?: boolean
- }>('session.events.since', { session_id: sid, last_seen: lastSeen }, REPLAY_REQUEST_TIMEOUT_MS)
++ }>(
+ 'session.events.since',
+ { session_id: sid, last_seen: lastSeen, ...(sessionEpochBefore ? { replay_epoch: sessionEpochBefore } : {}) },
+ REPLAY_REQUEST_TIMEOUT_MS
+ )
// The socket that owned this replay was dropped while its requests were
// settling. Its results and cleanup must not consume the replacement
@@@ -558,25 -553,8 +565,26 @@@
}
const epoch = result?.epoch
+ const sessionEpoch = result?.replay_epoch
+
- if (result?.snapshot_required === true || result?.truncated === true) {
- // The server could not replay our window (epoch changed, ring
- // truncated, cursor ahead). Keeping the watermark would make the
++ if (result?.snapshot_required === true) {
++ // The canonical authority could not replay our window (epoch changed,
++ // ring truncated, cursor ahead). Keeping the watermark would make the
+ // next reconnect believe nothing was missed; drop it and tell the
- // consumer to re-resume for a snapshot.
++ // consumer to re-resume for a snapshot. A legacy backend reports a
++ // bare `truncated` instead; that skips the window below (#100122).
+ this.adoptSessionReplayEpoch(sid, sessionEpoch)
+ this.lastSeenSeq.delete(sid)
+ this.dispatchEvent({ type: 'session.replay_gap', session_id: sid, payload: { replay_epoch: sessionEpoch, latest_seq: result.latest_seq } })
+
+ return
+ }
- if (typeof epoch === 'string' && epoch && this.replayEpoch && epoch !== this.replayEpoch) {
+ if (typeof sessionEpoch === 'string' && sessionEpoch) {
+ // Canonical responses also include `epoch`, but it is session-local,
+ // not the legacy process identity. Never reset unrelated cursors.
+ if (this.adoptSessionReplayEpoch(sid, sessionEpoch)) { return }
+ } else if (typeof epoch === 'string' && epoch && this.replayEpoch && epoch !== this.replayEpoch) {
// The old cursor no longer describes this process's numbering.
this.adoptReplayEpoch(epoch)
diff --cc cli-config.yaml.example
index 86983356bc9,8d02c25bd41..4505d53bae3
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@@ -7,7 -7,7 +7,7 @@@
# Schema version of this file. The installers copy it to seed config.yaml, and
# `hermes update` uses it to know which one-time migrations the file already
# has. Hermes manages it: do not copy it into another config.
- _config_version: 47
-_config_version: 49
++_config_version: 50
# =============================================================================
# Database Configuration
diff --cc cron/jobs.py
index 4e4172485b7,de66ce7698c..bc4d365cabd
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@@ -2446,8 -2485,8 +2504,9 @@@ def mark_job_run
status: Optional[str] = None,
*,
expected_fire_owner: Optional[str] = None,
+ execution_id: Optional[str] = None,
model_unreachable: bool = False,
+ ladder_rung: bool = False,
quota_hold_seconds: Optional[float] = None,
recover_consumed_fire: bool = False,
) -> bool:
@@@ -2482,9 -2521,7 +2543,9 @@@
return False
now = _hermes_now().isoformat()
_record_run_outcome(job, success, error, delivery_error, status, now)
+ if execution_id is not None:
+ job.setdefault("canonical_completions", []).append(execution_id)
- _advance_after_run(job, now)
+ _advance_after_run(job, now, ladder_rung=ladder_rung)
from cron import quota_hold
from cron.unreachable_retry import clear_state, plan_retry
diff --cc cron/scheduler.py
index afa0f025f69,3268a250f24..6a2018eddd5
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@@ -3217,15 -3360,18 +3414,19 @@@ def _run_one_job_body
if not execution_id:
execution_id = create_execution(
job["id"], source="direct", scheduled_instant=job.get("_scheduled_instant"))["id"]
+ job = dict(job, execution_id=execution_id)
delivery_attempted = False
delivery_error = None
- from agent.secret_scope import (
- build_profile_secret_scope, reset_secret_scope, set_secret_scope)
- _scope_token = None
+ _fire_scope_tokens = None
_terminal_scope_token = None
+ _identity_token = None
try:
+ # get_secret() fails closed outside a scope; the ticker thread has none. Delivery adapters
+ # resolve credentials, so the scope must span delivery too (reset in the outer finally) —
+ # including the crash notice in the except below when claim_dispatch or
+ # mark_execution_running raises, so install it before either.
+ _fire_scope_tokens = _install_fire_secret_scope()
# Commit a finite one-shot's dispatch BEFORE its side effect so a tick dying mid-run cannot
# re-fire it forever on restart. No-op for recurring/infinite jobs (at-most-times).
# This lives here in the shared body so BOTH the built-in ticker and the external provider (Chronos
@@@ -4276,32 -4462,4 +4523,4 @@@ if __name__ == "__main__"
raise SystemExit(
0 if _run_external_worker_payload(args.external_worker_file, args.ack_file) else 1
)
- tick(verbose=True)
+ tick(verbose=True, headless=True)
-
-
- # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
- # Names external plugins imported from this module before the Sep 2026 decomposition.
- # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
- # The whole block is removed by reverting the commit that added it.
- import asyncio # noqa: F401,E402
- import shutil # noqa: F401,E402
- import signal # noqa: F401,E402
-
-
- _PLUGIN_COMPAT_LAZY = {
- 'BOT_CHAT_PLATFORM': ('cron.scheduler_delivery', 'BOT_CHAT_PLATFORM'),
- 'SharedRouteAdapters': ('cron.scheduler_preflight', 'SharedRouteAdapters'),
- 'cron_delivery_targets': ('cron.scheduler_delivery', 'cron_delivery_targets'),
- 'parse_bot_chat_deliver_token': ('cron.scheduler_delivery', 'parse_bot_chat_deliver_token'),
- }
-
-
- def __getattr__(name): # PEP 562 — lazy so no import cycles
- target = _PLUGIN_COMPAT_LAZY.get(name)
- if target is None:
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
- import importlib
- from hermes_cli.plugin_compat import warn_once
- warn_once(__name__, name, *target)
- return getattr(importlib.import_module(target[0]), target[1])
- # ---- END PLUGIN-COMPAT ----
diff --cc cron/scheduler_delivery.py
index 2966f747e56,0d4f4b33f5d..25f23c0e066
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@@ -14,6 -14,10 +14,7 @@@ import contextli
import contextvars
import logging
import os
-import shutil
-import subprocess
-import sys
+ import threading
from dataclasses import dataclass
from typing import Any, List, Optional
@@@ -752,37 -825,177 +753,40 @@@ def _deliver_to_bot_chat(job: dict, con
[str(source_home), job_id, str(run_id), str(home)],
ensure_ascii=False, separators=(",", ":"),
).encode("utf-8")).hexdigest()
- if deferred is not None:
- key = deferred["id"]
# Read BEFORE discovery: the previous owner may have exited after accepting.
- # No receipt state, including ambiguous/failed, authorizes a CLI replay.
receipt = read_delivery_result(home, key)
- if receipt is None and not deferred:
- from cron.bot_chat_delivery import defer, read_pending
- from tools.bot_live_delivery import find_canonical_owner
-
- pending = read_pending(key)
- # Suppression is a durable disposition, not a send: record it under the producer
- # lock even when a live owner exists, so the deferred lane never replays it.
- if (pending is not None or suppress_notification
- or (find_canonical_live_owner(home) is None and find_canonical_owner(home))):
- pending = defer(key, dict(job), content, profile, home,
- for_failure=for_failure, suppressed=suppress_notification)
- if pending is not None:
- status = pending["status"]
- target = f"bot-chat:{profile_label}"
- job.setdefault("_bot_chat_delivery_receipts", {})[target] = {
- "status": status, "delivery_id": key}
- if status == "suppressed":
- job["_notification_all_targets_suppressed"] = True
- return None if status in ("settled", "suppressed") else f"{target} {status} (receipt {key}): completion unverified; do not resend"
+ target = f"bot-chat:{profile_label}"
+ if receipt is None and suppress_notification:
+ # Suppression is a durable disposition, not a send: the failure notice is booked
+ # against the job and never handed to the owner (the target profile hides
+ # warning notifications).
+ job.setdefault("_bot_chat_delivery_receipts", {})[target] = {
+ "status": "suppressed", "delivery_id": key}
+ job["_notification_all_targets_suppressed"] = True
+ return None
if receipt is None:
owner = find_canonical_live_owner(home)
- if owner is not None:
- receipt = deliver_to_live_owner(home, owner, message, delivery_id=key,
- **({"notification_category": "diagnostic"} if for_failure else {}))
- if receipt is not None:
- if (receipt["message"] != message
- or receipt.get("notification_category", "result") != ("diagnostic" if for_failure else "result")):
- raise ValueError("delivery id already belongs to a different payload")
- status = receipt["status"]
- target = f"bot-chat:{profile_label}"
- receipts = job.setdefault("_bot_chat_delivery_receipts", {})
- receipts[target] = {"status": status, "delivery_id": key}
- logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",
- job_id, profile_label, key, status)
- if status == "settled":
- return None
- detail = ("completion unverified; do not resend" if status in ("queued", "claimed")
- else receipt.get("error") or receipt.get("reason") or "not completed")
- return f"{target} {status} (receipt {key}): {detail}"
+ if owner is None:
+ return f"bot-chat delivery to profile '{profile_label}' unverified: no canonical Bot Chat"
- receipt = deliver_to_live_owner(home, owner, message, delivery_id=key)
- if receipt["message"] != message:
++ # A failure notice rides as ``diagnostic`` so the target's reply stays muted.
++ receipt = deliver_to_live_owner(home, owner, message, delivery_id=key,
++ **({"notification_category": "diagnostic"} if for_failure else {}))
++ if (receipt["message"] != message
++ or receipt.get("notification_category", "result") != ("diagnostic" if for_failure else "result")):
+ raise ValueError("delivery id already belongs to a different payload")
+ status = receipt["status"]
+ receipts = job.setdefault("_bot_chat_delivery_receipts", {})
+ receipts[target] = {"status": status, "delivery_id": key}
+ logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",
+ job_id, profile_label, key, status)
+ if status == "settled":
+ return None
+ detail = ("completion unverified; do not resend" if status in ("queued", "claimed")
+ else receipt.get("error") or receipt.get("reason") or "not completed")
+ return f"{target} {status} (receipt {key}): {detail}"
except Exception as exc:
- # Discovery/admission uncertainty must never open a second-writer fallback.
return f"bot-chat delivery to profile '{profile_label}' unverified: {exc}"
- # The running install first (same trust order as gateway.run._resolve_hermes_bin): the
- # scheduler lives in the long-running gateway, so a PATH-first lookup would hand delivery
- # to whatever `hermes` PATH names — another install, or a planted one — instead of this one.
- try:
- import importlib.util as _ilu
- found = _ilu.find_spec("hermes_cli") is not None
- except Exception:
- found = False
- if found:
- argv = [sys.executable, "-m", "hermes_cli.main"]
- else:
- hermes_bin = shutil.which("hermes")
- if not hermes_bin:
- return ("Hermes could not deliver this result to Bot Chat: the `hermes` command was not found. "
- "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening")
- argv = [hermes_bin]
-
- def _fail(msg: str, **log_kwargs) -> str:
- logger.warning("Job '%s': %s", job_id, msg, **log_kwargs)
- return msg
-
- from agent.delegation_context import delegated_child_subprocess_env
- from tools.environments.local import served_profile_child_env
- if not home.is_dir():
- return _fail(f"bot-chat delivery target no longer exists: {home}; do not resend")
- # Built for ``home``, the DELIVERY TARGET — the only cron child that acts for a profile other
- # than the one whose tick spawned it, so the launch residue cannot be resolved from the ambient
- # override the way every other lane resolves it. Discovery (or deferred admission) owns the
- # destination, not HOME or a subsequently changed active_profile: do not resolve it again.
- # ``inherit_credentials``: the child runs a full agent turn as that profile, on its own secrets.
- try:
- env = served_profile_child_env(
- delegated_child_subprocess_env(os.environ), target_home=home, inherit_credentials=True)
- except Exception as exc: # unreadable target home / secret source: refuse, never fall back
- return _fail(f"bot-chat delivery to profile '{profile_label}' could not build the target "
- f"profile's environment ({type(exc).__name__}: {exc}); do not resend")
- if home.parent.name != "profiles":
- argv += ["-p", "default"]
- if argv[1:3] == ["-m", "hermes_cli.main"]:
- # served_profile_child_env strips Hermes-owned PYTHONPATH entries; under a store-python
- # shim the bare interpreter then cannot import the package find_spec just proved (#122487).
- from pathlib import Path
-
- from cron.scheduler_worker_env import pin_hermes_tree_on_pythonpath
- pin_hermes_tree_on_pythonpath(env, Path(__file__).resolve().parents[1])
-
- query_file = None
- try:
- with tempfile.NamedTemporaryFile(
- "w", encoding="utf-8", suffix=".txt", prefix="hermes-cron-botchat-", delete=False,
- ) as fh:
- fh.write(message)
- query_file = fh.name
-
- argv += [
- "chat", "--in", "~", "-c", "Bot Chat", "--create-if-missing",
- "-Q", "--query-file", query_file,
- ]
- from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV
- report_file = f"{query_file}.turn.json"
- env[TURN_REPORT_FILE_ENV] = report_file
- timeout_s = _get_bot_chat_delivery_timeout()
- result = _run_bot_chat_turn(argv, env, report_file, timeout_s)
- if result.returncode != 0:
- tail = _format_failure_streams(result)
- logger.warning(
- "Job '%s': bot-chat delivery to profile '%s' failed at %s: %s",
- job_id, profile_label, home, tail)
- return (
- f"Hermes could not deliver this result to Bot Chat (profile '{profile_label}'). "
- "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening"
- f". Details: {tail}")
- logger.info("Job '%s': delivered to Bot Chat of profile '%s'", job_id, profile_label)
- return None
- except subprocess.TimeoutExpired:
- # Replaying the full payload risks a duplicate (the killed turn may already have
- # persisted it); staying silent loses the alert entirely (2026-09-19 docgen-deadman
- # case). So queue a SHORT marker that points at the saved output, once per execution
- # (stable key); the re-mark guard reads the record's ``degraded`` flag, never the text.
- marker_queued = False
- if not (deferred or {}).get("degraded"):
- marker = (
- f"DELIVERY DEGRADED: this alert's bot-chat turn timed out after "
- f"{timeout_s}s, so the full output could NOT be posted here. Read the "
- f"complete saved output with `hermes cron runs` (job '{job_id}'). "
- f"Excerpt: {content.strip()[:280]}"
- )
- try:
- from cron.bot_chat_delivery import defer as _defer_marker
- # Deferred ids double as live-owner delivery ids, which must be 32-64 hex
- # chars (tools.bot_live_delivery._delivery_id) — so the marker's id is a
- # fresh digest derived from the execution key, not a suffixed one.
- marker_key = hashlib.sha256(f"{key}:degraded".encode("utf-8")).hexdigest()
- _defer_marker(marker_key, dict(job), marker, profile, home,
- for_failure=for_failure, degraded=True)
- marker_queued = True
- except Exception as defer_exc:
- logger.warning(
- "Job '%s': degraded-delivery marker could not be queued: %s",
- job_id, defer_exc)
- hint = (
- "a short degraded-delivery notice was queued to Bot Chat — posted once the "
- f"session frees; full output stays saved, run `hermes cron runs` for job '{job_id}'"
- if marker_queued else
- "the result is saved; run `hermes cron runs` to see it, or `hermes doctor` "
- "if this keeps happening")
- return _fail(
- f"bot-chat delivery to profile '{profile_label}' timed out "
- f"after {timeout_s}s ({hint}; raise "
- "cron.bot_chat_delivery_timeout_seconds if this recurs)")
- except Exception as e:
- logger.warning(
- "Job '%s': bot-chat delivery to profile '%s' failed: %s", job_id, profile_label,
- str(e) or type(e).__name__, exc_info=True)
- return (
- f"Hermes could not deliver this result to Bot Chat (profile '{profile_label}'). "
- "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening")
- finally:
- if query_file:
- for path in (query_file, f"{query_file}.turn.json"):
- with contextlib.suppress(OSError):
- os.unlink(path)
-
def _normalize_deliver_value(deliver) -> str:
"""Normalize ``deliver`` to its canonical comma-separated string; ``"local"`` when falsy.
diff --cc gateway/AGENTS.md
index 2a65556ec93,785a5d8c0d1..dcb1b17dca2
--- a/gateway/AGENTS.md
+++ b/gateway/AGENTS.md
@@@ -58,73 -58,20 +58,24 @@@ MagicMock adapters in older tests auto-
## Background process notifications
- `terminal(background=true, notify_on_complete=true)` starts a gateway watcher that detects
- completion and triggers a new agent turn. Verbosity: `display.background_process_notifications`
- (or `HERMES_BACKGROUND_NOTIFICATIONS`): `concise` (default; one line, failures append an output
- tail), `all` (running updates + final raw output), `result` (final raw output only), `error`
- (final raw output only on non-zero exit), `off`.
-
- The watcher is armed on the gateway loop at registration time (`terminal_tool_background.py::
- _register_completion_watcher` → `run_notifications.py::arm_process_watcher`); `pending_watchers`
- is only the fallback for processes registered before the gateway serves (checkpoint recovery) or
- while it stops, drained at startup and post-turn. Agent-notify watchers send no user-facing
- receipt (the agent's next turn is the report) unless the launching turn is still running at exit
- — then the injection only queues a follow-up, so the concise receipt goes out immediately.
-
- The idle completion watcher also drains `watch_match` / `watch_disabled`; no user follow-up is
- required. Notify-off drains these without waking. Transport failures are retried; unavailable
- durable completion owners/transports do not spend delivery attempts. Profile-namespaced process
- events keep their owning adapter, including raw progress/final notices. Adapter acceptance is
- at-least-once admission, not proof that a model turn or final outbound reply completed. API-server
- async completions remain durable delivery rows, never autonomous new model turns. Require the
- `admit_internal_event` receipt for completion/watch injection: a handler returning None is not
- acceptance. Refused admission refunds every claimed batch sibling without spending an attempt;
- actual delivery errors keep their bounded retry policy. Recognized raw API routes resolve after
- persisted messaging origins and defer quietly when unavailable; malformed routes still warn.
+ `terminal(background=true, notify_on_complete=true)` arms a watcher on the gateway loop
+ (`run_notifications.py::arm_process_watcher`) that starts a new turn on completion; verbosity is
+ `display.background_process_notifications`. Injection requires the `admit_internal_event` receipt
+ (a handler returning None is not acceptance); refused admission refunds every claimed batch sibling
+ without spending an attempt. Long form: `website/docs/developer-guide/gateway-internals.md`
+ § Background process notifications.
+Canonical local CLI/TUI/Desktop sessions admit completion and watch events into the same durable
- FIFO as human input, retaining the private local launch policy and `internal_notification` display
- kind. Observers neither own nor consume those turns. Accepted local automation survives owner
- restart; an interrupted started turn remains unknown and pauses its followers. Watch hits carry
- separate event IDs even for identical text, but their pre-admission process queue is not durable.
-
- Cron execution has its own session. Eligible continuable deliveries may mirror or seed the
- reply-facing conversation: origin, origin-less home fallback, user-written bare-platform home,
- or opted-in explicit targets. `all` expansions do not gain home mirror eligibility. Mirrored
- briefs are labelled user turns appended at a turn boundary, preserving role alternation
- (`cron/AGENTS.md`).
++FIFO as human input (private launch policy, `internal_notification` display kind); observers never
++own or consume those turns, and an interrupted started turn stays unknown and pauses its followers.
+
## `/login` (off-turn, paired DM only)
- `/login` is registered in `hermes_cli/commands.py` with `busy_policy="dispatch"` and
- `desktop="settings"`, listed in `run_busy.py::_PLAIN_COMMANDS`, and handled by
- `GatewayLoginCommandsMixin` (`gateway/slash_commands_login.py`). It refuses outside a paired DM:
- `chat_type in {"dm","private"}`, a truthy `chat_id`, and a platform whose `"dm"` really is a paired
- conversation — ntfy, raft and a2a all report `chat_type="dm"` for a broadcast topic, a channel and
- an agent peer, so posting a consent link there would publish it.
-
- **It binds the whole install.** The sign-in writes the singleton `providers.nous`, so whoever
- approves the code owns this gateway's inference and connectors for every chat it serves. Slash
- gating is opt-in (`gateway/slash_access.py`): with no `allow_admin_from` set, every user allowed to
- DM the bot can run it. Operators of shared gateways must set it.
-
- The handler returns its ack at once and drains `anon_auth.run_sign_in` on a **private single-worker
- executor** (`_login_executor`), never the shared 10-thread gateway pool — a promotion wait can last
- the code's full expiry, and a live worker in the shared pool makes shutdown skip the SessionDB
- close/checkpoint. One attempt per process, stamped with the identity that started it: the same
- identity's second `/login` supersedes (the loser ends with the superseded copy pushed into its own
- chat); a different identity is refused. `task.cancel()` cannot interrupt a blocking poll inside a
- worker thread, so shutdown and supersede both work through `attempt.cancelled`, which
- `wait_for_promotion` now polls on a ≤1 s tick. A shutdown-cancelled attempt pushes nothing — the
- task is dying and its adapters may already be gone — but if the server had already completed the
- transfer it still persists, because that transfer is irreversible.
-
- On completion the handler **evicts** every cached agent still on `nous/welcome` and clears any
- session model override pinned to it. It does not switch agents in place and does not write a model
- override: `settle_after_upgrade` already moved `model.default`/`model.base_url` in the config, every
- turn re-resolves the config and the credentials, and `_agent_config_signature` already forces a
- rebuild when the route changes — so an in-place swap buys no cache warmth and an override would pin
- an expiring access token that nothing refreshes.
+ `GatewayLoginCommandsMixin` refuses outside a real paired DM (ntfy, raft and a2a report `dm` for
+ broadcast surfaces) and binds the WHOLE install's `providers.nous`, so shared gateways must set
+ `allow_admin_from`. It drains `anon_auth.run_sign_in` on its private single-worker `_login_executor`
+ (never the shared pool), allows one attempt per process, and on completion evicts agents still on
+ `nous/welcome` instead of writing a model override. Long form: `gateway-internals.md` § `/login`.
## Gateway lifecycle vs. the Desktop app
diff --cc gateway/authz_mixin.py
index bbeeba44578,ff15f3e21fc..b57e9fb424f
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@@ -628,13 -628,9 +628,14 @@@ class GatewayAuthorizationMixin
def _principal_authorized(self, source: SessionSource, *, allow_adapter_delegation: bool) -> bool:
"""The allowlist verdict alone, before the bot loop guard."""
+ from gateway.session_local import authorize_local_source
+ local_verdict = authorize_local_source(self, source)
+ if local_verdict is not None:
+ return local_verdict
+
- # HA events are system-generated (HASS_TOKEN); webhook events are HMAC-verified.
- if source.platform in {Platform.HOMEASSISTANT, Platform.WEBHOOK}:
+ # Webhook events are HMAC-verified; a ``trusted_inbound`` platform's events come from the
+ # service its adapter authenticated to (no human sender to allowlist).
+ if source.platform == Platform.WEBHOOK or getattr(_registry_entry(source.platform), "trusted_inbound", False) is True:
return True
adapter_profile = self._adapter_profile_for_source(source)
diff --cc gateway/control_socket.py
index 8703b7648cf,544e0df32f3..2eb1b798d46
--- a/gateway/control_socket.py
+++ b/gateway/control_socket.py
@@@ -389,12 -315,36 +389,22 @@@ def _query_unix_socket(home: Path, requ
return None
- def _query_windows_pipe(home: Path, request: bytes, timeout: float) -> Optional[bytes]: # pragma: no cover - wine2e lane
+ def _query_windows_pipe(home: Path, request: bytes, timeout: float) -> Optional[bytes]:
- """A synchronous pipe handle has no ``settimeout``: ``handle.read`` blocks until the peer answers,
- so the ``deadline`` in ``_read_response_line`` is only checked between chunks. Run the exchange on
- an abandoned-at-deadline worker so a peer that never answers costs ``timeout``, never forever —
++ """The native overlapped client checks its deadline per I/O step, but SID verification and the
++ connect/peer handshake are still synchronous calls into the pipe. Run the exchange on an
++ abandoned-at-deadline worker so a peer that never answers costs ``timeout``, never forever —
+ the bound ``_query_unix_socket`` already gets from ``sock.settimeout`` (#132547)."""
+ from agent.deadline import run_bounded_sync
+ outcome = run_bounded_sync(lambda: _windows_pipe_exchange(home, request, timeout), timeout, label="control-pipe")
+ return None if outcome.timed_out else outcome.value
+
+
+ def _windows_pipe_exchange(home: Path, request: bytes, timeout: float) -> Optional[bytes]: # pragma: no cover - wine2e lane
- pipe_name = windows_pipe_name(home)
- deadline = time.monotonic() + timeout
- handle = None
- while handle is None:
- try:
- handle = open(pipe_name, "r+b", buffering=0)
- except FileNotFoundError:
- return None
- except OSError:
- # Pipe busy (another client mid-handshake) — brief retry window.
- if time.monotonic() >= deadline:
- return None
- time.sleep(0.05)
- try:
- handle.write(request)
- return _read_response_line(lambda: handle.read(65536), deadline)
- finally:
- with contextlib.suppress(Exception):
- handle.close()
+ # The server is the native overlapped pipe worker; its client verifies the server's SID and
+ # speaks the same framing (a plain open() got no answer in the live Windows pipe test).
+ from gateway.runtime_bootstrap_windows import query_runtime_control
+
+ return query_runtime_control(Path(home), request, timeout)
def identify_gateway(home: Path, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT) -> Optional[dict[str, Any]]:
diff --cc gateway/hosted_room_driver.py
index 50e73e52da1,fb7268767a4..ddd363d57de
--- a/gateway/hosted_room_driver.py
+++ b/gateway/hosted_room_driver.py
@@@ -892,31 -857,3 +892,20 @@@ def prune_published_terminal_tasks
f"DELETE FROM hosted_room_driver_tasks WHERE room_id=? AND task_id IN ({','.join('?' * len(candidates))})",
(room_id, *candidates))
return max(0, int(deleted.rowcount))
+
+
-
+def get_task_for_turn(
+ db_path: DbPath,
+ identity: TaskIdentity,
+) -> dict[str, Any] | None:
+ """Read the immutable admission for a turn, including older payload versions."""
+ conn = _connect(db_path)
+ try:
+ row = conn.execute(
+ """SELECT * FROM hosted_room_driver_tasks
+ WHERE room_id=? AND thread_id=? AND turn_id=?""",
+ (identity.room_id, identity.thread_id, identity.turn_id),
+ ).fetchone()
+ return _task_from_row(row) if row is not None else None
+ finally:
+ conn.close()
-
- # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
- # Names external plugins imported from this module before the Sep 2026 decomposition.
- # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
- # The whole block is removed by reverting the commit that added it.
- from typing import Iterator # noqa: F401,E402
- from pathlib import Path # noqa: F401,E402
- from contextlib import contextmanager # noqa: F401,E402
- import re # noqa: F401,E402
- # ---- END PLUGIN-COMPAT ----
diff --cc gateway/platforms/webhook.py
index 4dc5796ee9d,a3c72d3c039..69b71e7440f
--- a/gateway/platforms/webhook.py
+++ b/gateway/platforms/webhook.py
@@@ -20,9 -20,10 +20,11 @@@ import o
import re
import subprocess
import time
+ import uuid
from collections import deque
+from datetime import datetime, timezone
from contextlib import nullcontext, suppress
+ from dataclasses import dataclass
from typing import Any, Deque, Dict, List, Optional
try:
@@@ -70,6 -71,29 +72,40 @@@ _REPO_RE = re.compile(r"[A-Za-z0-9._-]+
_GH_TOKEN_VARS = ("GH_TOKEN", "GITHUB_TOKEN")
+ @dataclass(frozen=True)
+ class _WebhookDeliveryIdentity:
+ """Collision-free identity for one provider delivery on one routed webhook route."""
+
+ profile: str
+ route: str
+ delivery_id: str
+
+ @classmethod
+ def from_parts(cls, profile: Optional[str], route: str, delivery_id: str) -> "_WebhookDeliveryIdentity":
+ return cls(profile=profile or "default", route=route, delivery_id=delivery_id)
+
+ @property
+ def session_chat_id(self) -> str:
+ # A versioned canonical JSON tuple avoids delimiter ambiguity while keeping the chat id safe
+ # for session-key persistence even when provider-controlled fields contain ':' or '/'.
+ payload = json.dumps(
+ (self.profile, self.route, self.delivery_id), ensure_ascii=False, separators=(",", ":")
+ ).encode("utf-8")
+ token = base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
+ return f"webhook:v2:{token}"
+
++ @staticmethod
++ def route_from_chat_id(chat_id: str) -> str:
++ """The route a delivery chat id names: decoded from a ``webhook:v2:`` token, else the legacy
++ ``webhook:{route}:{delivery}`` spelling that admissions queued before the upgrade still carry."""
++ prefix = "webhook:v2:"
++ if chat_id.startswith(prefix):
++ token = chat_id[len(prefix):]
++ _profile, route, _delivery = json.loads(base64.urlsafe_b64decode(token + "=" * (-len(token) % 4)))
++ return str(route)
++ return chat_id.split(":", 2)[1]
++
+
def _is_loopback_host(host: Optional[str]) -> bool:
"""True when `host` binds only to the local machine (falsy → non-loopback: usually a public default bind)."""
return bool(host) and host.strip().lower() in _LOOPBACK_HOSTS
@@@ -617,10 -661,11 +673,11 @@@ class WebhookAdapter(BasePlatformAdapte
if (skills := route_config.get("skills", [])) and not route_config.get("cron_job"):
prompt = self._apply_skills(prompt, skills)
delivery_id = headers.get("X-GitHub-Delivery", headers.get("svix-id", headers.get(
- "webhook-id", headers.get("X-Request-ID", str(int(time.time() * 1000))))))
+ "webhook-id", headers.get("X-Request-ID", uuid.uuid4().hex))))
now = time.time() # idempotency: skip duplicate deliveries (webhook retries)
- if route_config.get("deliver_only") and not self._record_delivery_id(delivery_id, now):
- logger.info("[webhook] Skipping duplicate delivery %s", delivery_id)
+ delivery_identity = _WebhookDeliveryIdentity.from_parts(profile, route_name, delivery_id)
- if not self._record_delivery_id(delivery_identity, now):
++ if route_config.get("deliver_only") and not self._record_delivery_id(delivery_identity, now):
+ logger.info("[webhook] Skipping duplicate delivery %s on route %s", delivery_id, route_name)
return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)
if route_config.get("cron_job"):
return self._handle_cron_trigger(prompt, route_config, route_name, event_type, delivery_id, profile)
@@@ -628,11 -673,6 +685,11 @@@
return await self._handle_deliver_only(prompt, payload, route_config, route_name, event_type, delivery_id,
profile)
coalesce = route_config.get("coalesce")
+ # A coalesced event waits in memory before it is durably admitted, so the ledger cannot dedupe
+ # a provider retry inside the window; the in-memory idempotency guard fills that gap here.
- if isinstance(coalesce, dict) and not self._record_delivery_id(delivery_id, now):
- logger.info("[webhook] Skipping duplicate delivery %s", delivery_id)
++ if isinstance(coalesce, dict) and not self._record_delivery_id(delivery_identity, now):
++ logger.info("[webhook] Skipping duplicate delivery %s on route %s", delivery_id, route_name)
+ return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)
if isinstance(coalesce, dict) and self._coalescer.enqueue(
route_name=route_name, coalesce=coalesce, payload=payload, event_type=event_type, prompt=prompt,
delivery_id=delivery_id, now=now, route_config=route_config, profile=profile):
@@@ -657,25 -693,9 +714,26 @@@
def _spawn_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,
route_name: str, profile, event_type: str) -> "asyncio.Task":
- """Record delivery info and fire the agent run (shared by the immediate and coalesced paths)."""
+ """Coalesced-path dispatch (settled timer / disconnect flush): admit the merged event as a task
+ so ``WebhookCoalescer.flush`` can await the hand-off. The HTTP ack for these deliveries was
+ already ``coalesced``; an admission failure is logged, never retried by the producer."""
+ async def _admit_or_log():
+ outcome = await self._admit_agent_run(payload, prompt, delivery_id, now, route_config=route_config,
+ route_name=route_name, profile=profile, event_type=event_type)
+ if outcome is None:
+ logger.error("[webhook] Coalesced delivery %s on route %s was not admitted", delivery_id, route_name)
+ task = asyncio.create_task(_admit_or_log())
+ self._background_tasks.add(task)
+ task.add_done_callback(self._background_tasks.discard)
+ return task
+
+ async def _admit_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,
+ route_name: str, profile, event_type: str) -> Optional[str]:
+ """Record delivery info and admit the run through the durable producer (shared by the immediate
+ and coalesced paths). ``"accepted"`` / ``"duplicate"``, or None when admission failed."""
- # delivery_id in the session key → concurrent webhooks on one route get independent runs.
- session_chat_id = f"webhook:{route_name}:{delivery_id}"
++ # (profile, route, delivery_id) in the session key → concurrent webhooks get independent runs.
+ identity = _WebhookDeliveryIdentity.from_parts(profile, route_name, delivery_id)
+ session_chat_id = identity.session_chat_id
# ``profile`` rides along so the reply leg (``send`` → ``_deliver_cross_platform``) egresses through
# THIS profile's adapter, home channel and secrets — not the first profile that has the platform.
self._delivery_info[session_chat_id] = {
diff --cc gateway/platforms/webhook_delivery.py
index 2b092c37bd7,00000000000..263b086551e
mode 100644,000000..100644
--- a/gateway/platforms/webhook_delivery.py
+++ b/gateway/platforms/webhook_delivery.py
@@@ -1,95 -1,0 +1,99 @@@
+"""Validated webhook destinations live in the owner's admitted input, not a TTL cache."""
+from copy import deepcopy
+import hashlib
+import json
+
+from hermes_state_runtime import RuntimeStoreError
+
+
+def route_digest(adapter, chat_id):
++ from gateway.platforms.webhook import _WebhookDeliveryIdentity
+ adapter._reload_dynamic_routes()
- route_name = chat_id.split(':', 2)[1]
++ try:
++ route_name = _WebhookDeliveryIdentity.route_from_chat_id(chat_id)
++ except (ValueError, TypeError, IndexError):
++ raise RuntimeStoreError('not_found') from None
+ route = adapter._routes.get(route_name)
+ if route is None:
+ raise RuntimeStoreError('not_found')
+ return hashlib.sha256(json.dumps(route, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
+
+
+def validate_destination(delivery):
+ from gateway.platforms.webhook import _is_known_platform, _REPO_RE
+ if (not isinstance(delivery, dict)
+ or not {'deliver', 'deliver_extra'} <= set(delivery)
+ or set(delivery) - {'deliver', 'deliver_extra', 'profile', 'mirror', 'route'}
+ or (delivery.get('profile') is not None and not isinstance(delivery['profile'], str))
+ or not isinstance(delivery.get('mirror', False), bool)
+ or (delivery.get('route') is not None and not isinstance(delivery['route'], str))):
+ raise RuntimeStoreError('invalid_params')
+ target, extra = delivery['deliver'], delivery['deliver_extra']
+ if not isinstance(target, str) or not isinstance(extra, dict):
+ raise RuntimeStoreError('invalid_params')
+ if target == 'github_comment':
+ repo, number = extra.get('repo'), extra.get('pr_number')
+ if not isinstance(repo, str) or not _REPO_RE.fullmatch(repo) or not str(number).isdigit() or int(number) <= 0:
+ raise RuntimeStoreError('invalid_params')
+ elif target != 'log' and not _is_known_platform(target):
+ raise RuntimeStoreError('invalid_params')
+ # Configuration extras may contain credentials or whole rendered payloads.
+ # Persist only fields the selected sender actually consumes.
+ fields = {'log': (), 'github_comment': ('repo', 'pr_number')}.get(
+ target, ('chat_id', 'message_thread_id', 'thread_id'))
+ result = {'deliver': target, 'deliver_extra': deepcopy({key: extra[key] for key in fields if key in extra})}
+ # Omit the unbound defaults to preserve pre-profile receipt fingerprints.
+ if delivery.get('profile'):
+ result['profile'] = delivery['profile']
+ # Route opt-in (``mirror_to_session: true``): the delivered text is mirrored into the target chat's
+ # session; the destination row carries it so a replayed delivery mirrors exactly like the first.
+ if delivery.get('mirror') is True:
+ result['mirror'] = True
+ if delivery.get('route'):
+ result['route'] = delivery['route'] # the mirror's label only
+ return result
+
+
+def snapshot_destination(adapter, delivery):
+ from gateway.config import Platform
+
+ result = validate_destination(delivery)
+ if result['deliver'] not in {'log', 'github_comment'} and not result['deliver_extra'].get('chat_id'):
+ profile = result.get('profile')
+ with adapter._profile_scope(profile):
+ home = adapter._delivery_config(profile).get_home_channel(Platform(result['deliver']))
+ if home is None:
+ raise RuntimeStoreError('not_found')
+ result['deliver_extra']['chat_id'] = home.chat_id
+ return result
+
+
+def retained_destination(adapter, chat_id):
+ """Readback also checks today's connector and authorization; retained data is not a grant."""
+ from gateway.session_envelope import restore_native, _validate_native
+ runner = adapter.gateway_runner or getattr(adapter._message_handler, '__self__', None)
+ from gateway.session_authorities import active_authority, all_authorities
+ if not all_authorities(runner):
+ return validate_destination(adapter._delivery_info.get(chat_id))
+ # The reply leg runs in the routed profile's scope; that ledger holds the destination. A
+ # delivery id is unique per route, so an unscoped caller may search every served ledger.
+ scoped = active_authority(runner)
+ candidates = [scoped] if scoped is not None else all_authorities(runner)
+ # Only the signed ingress admission carries the destination; later automation rows
+ # (process/watch completions) on the same chat share its source but never compete.
+ query = """SELECT payload_json FROM session_admissions
+ WHERE json_extract(payload_json, '$.native_text_v1.source.chat_id')=?
+ AND json_extract(payload_json, '$.native_text_v1.source.platform')='webhook'
+ AND json_extract(payload_json, '$.native_text_v1.automation') IS NULL"""
+ rows = [row for authority in candidates for row in authority.db._read_all(query, (chat_id,))]
+ if len(rows) != 1:
+ raise RuntimeStoreError('not_found')
+ payload = json.loads(rows[0]['payload_json'])
+ envelope = payload['native_text_v1']
+ event = restore_native(payload, runner)
+ _validate_native(runner, event, envelope.get('provenance'))
+ if runner._adapter_for_source(event.source) is not adapter:
+ raise RuntimeStoreError('permission_denied')
+ if envelope.get('webhook_route') != route_digest(adapter, chat_id):
+ raise RuntimeStoreError('admission_conflict')
+ return validate_destination(envelope.get('webhook_delivery'))
diff --cc gateway/run_agent_cache.py
index 3cfaf608ba0,5be523d3fc5..c05049dbec4
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@@ -255,6 -257,38 +257,42 @@@ class GatewayAgentCacheMixin
# ordinary drift and still evicts.
return getattr(agent, "_nous_model_switch", None) == (config_model, agent.model)
- def _fallback_baseline_model(self, session_key: str, source: Optional[SessionSource], agent: Any) -> str:
++ def _fallback_baseline_model(self, session_key: str, source: Optional[SessionSource], agent: Any,
++ *, policy_model: Optional[str] = None) -> str:
+ """The model *agent* was built to run, for the post-turn fallback check: what
- ``_resolve_session_agent_runtime`` chose (session /model, then channel_overrides on the chat,
- thread or parent, then the global model), canonicalized as ``AIAgent.__init__`` did on the
- agent's PRIMARY route. The route a fallback moved it to would make that fallback look primary."""
++ ``_resolve_session_agent_runtime`` chose (session /model, then a LOCAL session's frozen launch
++ policy model, then channel_overrides on the chat, thread or parent, then the global model),
++ canonicalized as ``AIAgent.__init__`` did on the agent's PRIMARY route. The route a fallback
++ moved it to would make that fallback look primary."""
+ from gateway.run import _resolve_gateway_model
+ primary = getattr(agent, "_primary_runtime", None) or {}
+ provider = primary.get("provider", getattr(agent, "provider", "")) or ""
+ # An override whose provider was unavailable this turn ran on the default route instead.
+ override = self._session_model_override(session_key) or {}
+ if override.get("model") and override.get("provider") in (None, "", provider):
+ model = override["model"]
++ elif policy_model:
++ model = policy_model
+ elif source is not None:
+ model = self._resolve_model_for_channel(
+ 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,
+ )
+ else:
+ model = _resolve_gateway_model()
+ # Vendor prefix stripped on native providers, else the cached agent is evicted every turn,
+ # destroying prompt caching.
+ with suppress(Exception):
+ from hermes_cli.model_normalize import _AGGREGATOR_PROVIDERS, normalize_model_for_provider
+ if provider and provider not in _AGGREGATOR_PROVIDERS:
+ model = normalize_model_for_provider(model, provider)
+ # The Nous welcome host runs its one model whatever the chat configured (pin_model_for_route).
+ with suppress(Exception):
+ from hermes_cli.anon_auth import pin_model_for_route
+ model = pin_model_for_route(provider, primary.get("base_url", getattr(agent, "base_url", None)), model)
+ return model
+
def _release_running_agent_state(
self, session_key: str, *, run_generation: Optional[int] = None
) -> bool:
diff --cc gateway/run_bootstrap.py
index 1fa211c259a,00000000000..4d83cdf7729
mode 100644,000000..100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@@ -1,766 -1,0 +1,785 @@@
+"""Process startup phases; diagnostics remain in the gateway facade."""
+from __future__ import annotations
+
+import threading
++from pathlib import Path
+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,
+ unserve_profile_verb, serve_profile_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),
+ "unserve-profile": unserve_profile_verb(runner),
+ "serve-profile": serve_profile_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.cwd_placeholder import CWD_PLACEHOLDERS, resolve_placeholder_terminal_cwd
+ 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,
++ _recover_pending_flushes,
+ _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"
+
++ # Messaging-only defaults belong to startup, not incidental imports by the TUI.
++ configured_cwd = os.environ.get("TERMINAL_CWD", "")
++ if not configured_cwd or configured_cwd in CWD_PLACEHOLDERS:
++ resolved_cwd = resolve_placeholder_terminal_cwd(
++ configured_cwd=configured_cwd,
++ terminal_backend=os.environ.get("TERMINAL_ENV", ""),
++ messaging_cwd=os.getenv("MESSAGING_CWD"),
++ docker_mount_cwd_to_workspace=os.getenv(
++ "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").lower()
++ in {"true", "1", "yes"},
++ home_fallback=str(Path.home()))
++ if resolved_cwd is None:
++ os.environ.pop("TERMINAL_CWD", None)
++ else:
++ os.environ["TERMINAL_CWD"] = resolved_cwd
++
+ 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.
+ # 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)
+
++ from gateway.run_startup import recover_left_core_at_gateway_start
++ await asyncio.to_thread(recover_left_core_at_gateway_start) # before the runner loads platform config
++
+ 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,
- )
++ recovered = _recover_pending_flushes(runner)
+ 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_profile_reconcile.py
index bcdedf44321,29652f31c96..e600b7cd975
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@@ -113,46 -114,52 +118,69 @@@ class GatewayProfileReconcileMixin
from gateway.status import live_gateway_pid_for_home
blocked = set()
+ timed_out = set()
warned = self._profile_own_gateway_warned or set()
+ timeout_warned = self._profile_probe_timeout_warned or set()
- for name in list(current):
+ for name in list(live):
if name == active or name in known:
continue
- if live_gateway_pid_for_home(live[name]) is not None:
+ # The probe can end in a control-socket read that has no timeout of its own
+ # (a Windows named pipe stalls there until its peer answers). Inline on the
+ # loop thread it parked shutdown_watchdog liveness probes and the multiplexer
+ # was hard-killed with exit 75 (#132547). Probe off the loop, bounded: a
+ # stalled probe only wedges one bounded housekeeping worker for this cycle
+ # (wait_for cancels the still-queued await), never the event loop.
+ try:
+ pid = await asyncio.wait_for(
- self._run_housekeeping_in_executor(live_gateway_pid_for_home, current[name]),
++ self._run_housekeeping_in_executor(live_gateway_pid_for_home, live[name]),
+ timeout=_OWN_GATEWAY_PROBE_TIMEOUT_SECS)
+ except asyncio.TimeoutError:
+ # Unprovable is not "own gateway running": skip it this cycle without
+ # warning about (or remembering) a gateway that may not exist. Warn once
+ # per stall; a peer that stays wedged repeats at DEBUG every cycle.
+ timed_out.add(name)
+ log = logger.debug if name in timeout_warned else logger.warning
+ log("[MULTIPLEX] Own-gateway probe for profile '%s' timed out; "
+ "not serving it this cycle", name)
- del current[name]
++ del live[name]
+ continue
+ if pid is not None:
blocked.add(name)
if name not in warned:
logger.warning("[MULTIPLEX] Profile '%s' still runs its own gateway; "
"stop it before the host can serve this profile", name)
- del current[name]
+ del live[name]
self._profile_own_gateway_warned = blocked
+ self._profile_probe_timeout_warned = timed_out
sigs = self._served_profile_signatures or {}
- added = [n for n in current if n not in known and n != active]
- removed = [n for n in known if n not in current and n != active]
- changed = [n for n in current if n in known and n != active and n not in added
- and profile_serve_signature(current[n]) != sigs.get(n)]
- return await self._apply_profile_changes(current, added, removed, changed, reason=reason)
+ from gateway.run_runtime import unpark_profile
+ for name in [n for n in self._parked_profile_names() if n not in live]:
+ unpark_profile(self, name)
+ parked = self._parked_profile_names()
+ # The watcher never re-parks the same profile every cycle; a creator's explicit signal does.
+ retry_parked = reason == "control-socket"
+ added = [n for n in live if n not in known and n != active and (retry_parked or n not in parked)]
+ removed = [n for n in known if n not in live and n != active]
+ changed = [n for n in live if n in known and n != active and n not in added
+ and profile_serve_signature(live[n]) != sigs.get(n)]
+ current = {n: h for n, h in live.items() if n in known or n == active}
+ return await self._apply_profile_changes(
+ current, added, removed, changed, reason=reason, live=live, result=result)
- async def _apply_profile_changes(self, current, added, removed, changed, *, reason):
- """Apply a selected diff under the reconcile lock, shared by the watcher and control verbs."""
- from gateway.run import MultiplexConfigError, _multiplex_profile_homes
+ async def _apply_profile_changes(self, current, added, removed, changed, *, reason,
+ live=None, result=None):
+ """Apply a selected diff under the reconcile lock, shared by the watcher and the
+ serve/unserve control verbs. New profiles first get a runtime (reservation + store); one
+ whose home another gateway owns or whose store is unusable is parked, not served."""
+ from gateway.run import MultiplexConfigError
+ from gateway.run_runtime import park_profile, unpark_profile
+ from hermes_cli.profiles import profiles_to_serve
active = getattr(self, "_primary_profile_name", None) or "default"
- result = {"added": [], "removed": [], "rescanned": [], "reason": reason}
+ result = dict(result or {"added": [], "removed": [], "rescanned": [], "parked": [], "reason": reason})
+ result.setdefault("parked", [])
+ live = live if live is not None else dict(current)
+ known = dict(self._served_profile_homes or {})
+ sigs = self._served_profile_signatures or {}
if not (added or removed or changed):
return {**result, "served_profiles": self.served_profile_names()}
for name in removed:
diff --cc gateway/run_runtime_init.py
index 1fd69d66e52,00000000000..56835ef1e2c
mode 100644,000000..100644
--- a/gateway/run_runtime_init.py
+++ b/gateway/run_runtime_init.py
@@@ -1,266 -1,0 +1,266 @@@
+"""Writable runner initialization, separate from process ownership."""
+from __future__ import annotations
+
+class GatewayRuntimeInitMixin:
+ def _init_runtime_settings(self) -> None:
+ """Load ephemeral per-call config (prefill, reasoning, busy modes, timeouts, routing)."""
+ from gateway.run import (Dict, Optional, _load_gateway_config)
+ self._prefill_messages = self._load_prefill_messages()
+ self._reasoning_config = self._load_reasoning_config()
+ self._service_tier = self._load_service_tier()
+ self._show_reasoning = self._load_show_reasoning()
+ self._busy_input_mode = self._load_busy_input_mode()
+ self._busy_text_mode = self._load_busy_text_mode()
+ # Secondary-profile busy modes snapshotted at multiplex startup; handlers never reread config.
+ self._busy_input_modes_by_profile: Dict[str, str] = {}
+ self._busy_text_modes_by_profile: Dict[str, str] = {}
+ self._busy_text_timing = self._busy_text_timing_from_config(_load_gateway_config())
+ self._busy_text_timing_by_profile: Dict[str, tuple[float, float]] = {}
+ self._human_delay = self._human_delay_from_config(_load_gateway_config())
+ self._human_delay_by_profile: Dict[str, Optional[tuple[int, int]]] = {}
+ self._restart_drain_timeout = self._load_restart_drain_timeout()
+ # Live launchd ``ExitTimeOut`` for this job (None when not launchd-owned). Read once at
+ # boot — launchd fixes it at load — and applied only to signal-driven stops, which are the
+ # only stops launchd times. See _load_launchd_exit_timeout().
+ self._stop_requested_by_signal = False
+ self._launchd_exit_timeout_s = self._load_launchd_exit_timeout(self._restart_drain_timeout)
+ self._restart_after_turn_timeout = self._load_restart_after_turn_timeout()
+ self._cron_drain_timeout = self._load_cron_drain_timeout()
+ self._signal_interrupt_grace_timeout = self._load_signal_interrupt_grace_timeout()
+ self._provider_routing = self._load_provider_routing()
+ self._fallback_model = self._load_fallback_model()
+
+ def _init_session_store(self) -> None:
+ """Build the SessionStore (with process-registry reset guard), its async facade and the router."""
+ from gateway.run import (AsyncSessionStore, DeliveryRouter, SessionStore)
+ from tools.process_registry import process_registry
+ self.session_store = SessionStore(
+ self.config.sessions_dir, self.config,
+ has_active_processes_fn=lambda key: process_registry.has_active_for_session(
+ key))
+ # Loop-side boundary: sync helpers use ``session_store`` directly; async handlers await this facade.
+ self._async_session_store = AsyncSessionStore(self.session_store)
+ self.delivery_router = DeliveryRouter(self.config)
+
+ def _init_lifecycle_state(self) -> None:
+ """Initialise run/exit/restart flags, per-session state, and completion-delivery bookkeeping."""
+ from gateway.run import (Dict, List, MessageEvent, Optional, OrderedDict, Platform, SessionSource, SessionState, SessionTurnLeaseRegistry, asyncio, concurrent, threading, time)
+ self._running = self._exit_cleanly = self._exit_with_failure = self._draining = False
+ self._gateway_loop: Optional[asyncio.AbstractEventLoop] = None
+ self._shutdown_event = asyncio.Event()
+ self._exit_reason: Optional[str] = None
+ self._exit_code: Optional[int] = None
+ self._profile_failed_platforms: Dict[str, Dict[Platform, asyncio.Task]] = {}
+ self._systemd_watchdog = None
+ # External (NAS-driven) drain, distinct from one-way ``_draining``: set while ``.drain_request.json``
+ # exists — NEW turns refused, process stays up, removing the marker reverts to ``running``.
+ self._external_drain_active = False
+ # ``_signal_initiated_shutdown``: SIGTERM/SIGINT with no planned-stop/takeover marker (container,
+ # OOM, bare kill); _stop_impl must NOT persist gateway_state=stopped or container_boot won't restart.
+ self._restart_requested = self._signal_initiated_shutdown = self._restart_task_started = False
+ self._restart_detached = self._restart_via_service = self._detached_restart_helper_started = False
+ self._restart_command_source: Optional[SessionSource] = None
+ # Construction clock: bounds the /restart redelivery guard's window (missing dedup marker = stale).
+ self._startup_time: float = time.time()
+ # True when booted from a chat /restart (.restart_notify.json existed). One-shot signal so the
+ # marker-missing fallback suppresses a /restart only when we KNOW we just restarted.
+ self._booted_from_restart: bool = False
+ self._stop_task: Optional[asyncio.Task] = None
+ self._restart_task: Optional[asyncio.Task] = None
+ self._executor_lock = threading.Lock()
+ self._executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
+ # Best-effort session housekeeping runs on its OWN pool; see _run_housekeeping_in_executor.
+ self._housekeeping_executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
+ # Set on gateway stop so the recreate-on-shutdown path can't resurrect the pool.
+ self._executor_closing = False
+ # ALL per-session state lives here (gateway/session_state.py); use _session_state / _peek_session_state.
+ self._sessions: Dict[str, SessionState] = {}
+ # Per-SESSION_ID turn lease: serializes [load history → run → flush] when two ROUTING KEYS resolve
+ # to one session_id (switch_session's many-to-one mapping), which routing-key guards cannot see.
+ self._turn_leases = SessionTurnLeaseRegistry()
+ # Stall-notified keys clear when pending clears / activity resumes / conversation boundary.
+ # Held turn-lease tokens live on SessionState.turn.lease_tokens keyed by run generation, so a
+ # stale unwind can never free a newer turn's lease (#28686). Runner-level queued interrupt text lives on
+ # SessionState.persistent.pending_command_text (NOTE: distinct from the adapter-level
+ # _pending_messages Dict[str, MessageEvent] in gateway/platforms/base.py, which shares the legacy
+ # name). Last successfully-resolved (non-empty) model, keyed by session. Used as a fallback when a
+ # fresh config read transiently returns an empty model (e.g. an mtime-keyed config-cache miss during
+ # a post-interrupt recovery turn). Without this, the agent is built with model="" and every API call
+ # fails HTTP 400 "No models provided" — the session goes silent until the user manually re-sends.
+ # See #35314. The ``"*"`` session entry holds a process-wide last-known-good for sessions seen for
+ # the first time. Lives on SessionState.conversation.last_resolved_model. Overflow buffer for
+ # explicit /queue commands. The adapter-level _pending_messages dict is a single slot per session
+ # (designed for "next-turn" follow-ups where repeated sends collapse into one event). /queue has
+ # different semantics: each invocation must produce its own full agent turn, in FIFO order, with no
+ # merging. When the slot is occupied, additional /queue items land here and are promoted
+ # one-at-a-time after each run's drain. Cleared on /new and /reset. /model and other mid-session
+ # operations preserve the queue. Lives on SessionState.conversation.queued_events; native image
+ # paths, busy-ack debounce timestamps and the monotonic run-generation counter (#28686, NEVER reset)
+ # live on SessionState too. See gateway.session_stall.
+ self._session_stall_notified: Dict[str, bool] = {}
+ # Consecutive "persisted transcript lagged live cached history" turns per session key; see
+ # run_turn_runner._load_turn_history (#114266). Cleared on /new.
+ self._transcript_lag_streaks: Dict[str, int] = {}
+ # Startup restore gate: while restart-interrupted sessions auto-resume, real inbound messages
+ # queue instead of competing with the synthetic resume turns; drained after all resume tasks end.
+ self._startup_restore_in_progress = False
+ self._startup_restore_queue: List[MessageEvent] = []
+ self._startup_restore_tasks: List[asyncio.Task] = []
+ # Set by start_gateway() only for an explicit ``--replace`` launch; scoped to each adapter's
+ # cold-start connect and removed before any reconnect can run.
+ self._platform_lock_takeover_on_start = False
+ # Capped LRU of live SessionSources for fallback routing (shutdown notices, synthetic events) when
+ # the persisted origin is missing and _parse_session_key can't recover thread_id.
+ self._session_sources: "OrderedDict[str, SessionSource]" = OrderedDict()
+ self._session_sources_max = 512
+ # Lifecycle-scoped completion dedup: closes queue/watcher races inside one gateway without claiming
+ # exactly-once across a crash; durable replay state stays owned by tools.async_delegation.
+ self._completion_delivery_lock = threading.Lock()
+ self._completion_deliveries_inflight: set[tuple[str, str, object]] = set()
+ self._completion_deliveries_delivered: "OrderedDict[tuple[str, str, object], None]" = OrderedDict()
+ self._completion_delivery_retention = 2048
+ # Agent-triggered terminal completions from one conversation often land in the same scheduler
+ # tick; hold them briefly so the agent gets one synthetic turn instead of one per process.
+ # See #70300.
+ self._completion_notification_batches: dict[tuple[str, ...], list[tuple[str, dict, asyncio.Future]]] = {}
+ self._completion_notification_batch_tasks: dict[tuple[str, ...], asyncio.Task] = {}
+ self._completion_notification_batch_flush_tasks: set[asyncio.Task] = set()
+ self._completion_notification_batch_window = 0.1
+ self._completion_notification_batches_stopping = False
+
+ def _init_runtime_caches(self) -> None:
+ """Agent cache, profile identity, Teams runtime, failed-platform tracking, slash-confirm counter."""
+ from gateway.run import (Any, Dict, Optional, OrderedDict, Platform, threading)
+ # AIAgent per session preserves prompt caching (fresh agent per message ~10x cost on Anthropic).
+ # Value: (AIAgent, config_signature); LRU cap in _enforce_agent_cache_cap, TTL in expiry watcher.
+ self._agent_cache: "OrderedDict[str, tuple]" = OrderedDict()
+ self._agent_cache_lock = threading.Lock()
+ # Launch-time identity of the profile that owns ``self.adapters``; ``_authorization_adapter``
+ # compares against this rather than the per-turn ``_active_profile_name()``. A multiplex
+ # host's primary map is always the default profile, even when a named profile launched
+ # the process (that launcher is a secondary adapter owner).
+ launch = self._active_profile_name()
+ self._kanban_notifier_profile = launch
+ self._primary_profile_name = (
+ "default" if getattr(self.config, "multiplex_profiles", False) else launch
+ )
+ # Teams meeting pipeline runtime (bound later when msgraph_webhook adapter exists).
+ self._teams_pipeline_runtime = None
+ self._teams_pipeline_runtime_error: Optional[str] = None
+ # Failed-to-connect platforms for background reconnection: Platform -> {config, attempts, next_retry}
+ self._failed_platforms: Dict[Platform, Dict[str, Any]] = {}
+ # Strong refs to detached fatal-error handler tasks so the loop can't GC them mid-run.
+ self._fatal_handler_tasks: set = set()
+ # Slash-confirm state lives in tools.slash_confirm (module-level) so adapters resolve callbacks
+ # without a runner backref; local counter keeps confirm_ids compact (64-byte callback_data caps).
+ import itertools
+ self._slash_confirm_counter = itertools.count(1)
+
+ def _init_startup_checks(self) -> None:
+ """Ensure tirith is installed and warn when manual approvals have no automated assessor."""
+ from gateway.run import (_best_effort, cfg_get, logger)
+ def _ensure_tirith() -> None:
+ from tools.tirith_security import ensure_installed
+ ensure_installed(log_failures=False) # downloads if needed; fail-open at scan time
+
+ _best_effort(_ensure_tirith)
+
+ # Manual approvals with no automated assessor (tirith off AND no auxiliary.approval) fail closed
+ # on unattended gateways — surface it so operators knowingly enable one.
+ try:
+ from hermes_cli.config import load_config as _load_full_config
+ # Startup heads-up (#30882): a gateway in manual approval mode with no automated risk assessor
+ # (tirith disabled AND no auxiliary.approval model) can only gate dangerous commands /
+ # execute_code scripts via live in-chat approval.
+ _appr_cfg = _load_full_config()
+ _appr_mode = str(
+ cfg_get(_appr_cfg, "approvals", "mode", default="manual") or "manual"
+ ).strip().lower()
+ _tirith_on = bool(cfg_get(_appr_cfg, "security", "tirith_enabled", default=True))
+ _aux_approval = cfg_get(_appr_cfg, "auxiliary", "approval", default=None)
+ if _appr_mode == "manual" and not _tirith_on and not _aux_approval:
+ logger.warning(
+ "Gateway approvals.mode=manual with no automated risk "
+ "assessor (security.tirith_enabled is false and "
+ "auxiliary.approval is unset): dangerous commands and "
+ "execute_code scripts will BLOCK until a human approves "
+ "them in chat. Enable security.tirith_enabled or configure "
+ "auxiliary.approval for unattended operation.")
+ except Exception:
+ logger.debug("approvals.mode startup check skipped", exc_info=True)
+
+ def _init_session_db(self) -> None:
+ """Open the session DB for the active scope and run opportunistic state.db / checkpoint maintenance."""
+ from gateway.run import (Any, Dict, Path, _SESSION_DB_UNPINNED, _housekeeping_chore, _housekeeping_state_db_maintenance, _launch_sessions_dir, logger, threading)
+ # Session DB is a property caching one AsyncSessionDB per path (a handle bound here would pin the
+ # root home under multiplex); priming here keeps startup diagnostics at init.
+ # Initialize session database for session_search tool support. Same frozen-handle class of bug as
+ # SessionStore._db (#88532): a handle bound here is pinned to the process's root home, but /resume,
+ # /title, /history and session search all run inside _profile_runtime_scope on a multiplexed gateway
+ # and must see that profile's own state.db.
+ self._session_db_pinned: Any = _SESSION_DB_UNPINNED
+ self._session_db_handles: Dict[Path, Any] = {}
+ self._session_db_handles_lock = threading.Lock()
+ from gateway.session_db_recovery import RecoverableHandleCache
+ self._session_db_handle_cache = RecoverableHandleCache(
+ handles=self._session_db_handles, lock=self._session_db_handles_lock)
+ try:
+ self._open_session_db_for_active_scope(raise_on_error=True)
+ except Exception as e:
+ # WARNING (not DEBUG) so it lands in errors.log; else an NFS HERMES_HOME silently loses /resume etc.
+ logger.warning("SQLite session store not available: %s", e)
+ self._session_db_init_error = str(e) # surfaced on the home channel(s) once connected
+
+ # Opportunistic state.db maintenance (prune + optional VACUUM), at most once per min_interval_hours.
+ # A few blocking seconds per day is fine for a long-lived gateway; failures log, never raise.
+ # Surface the failure to the user via their home channel(s) once the gateway connects. Without this,
+ # state.db corruption or NFS/SMB lock failures silently degrade the entire gateway — messages may
+ # flow but nothing is persisted, and the user has no indication until they try /resume and find
+ # nothing (#88235).
+ # Once per SERVED profile, each under its own scope: both the store and the ``sessions:``
+ # config that governs it must be the profile's own. Bound to ``self._session_db`` this ran
+ # against the construction-time launch home only, so a multiplexed secondary profile's
+ # state.db was never pruned or vacuumed by anybody, and the launch profile's
+ # retention_days/auto_prune decided whether it happened at all.
+ from gateway.run_profile_reconcile import _for_each_served_profile
+ _launch_sessions = _launch_sessions_dir(self.config) # resolved OUTSIDE any profile scope
+ _housekeeping_chore(
+ "state.db startup maintenance",
+ lambda: _for_each_served_profile(
+ self, lambda _label: _housekeeping_state_db_maintenance(_launch_sessions)))
+ # Checkpoint store pruning is a housekeeping chore (``_housekeeping_checkpoint_prune``), not a
+ # constructor step: its ``git gc`` repacks the whole store (tens of seconds on a GB store) and
+ # here it ran before the control socket, adapters and the code_sha stamp — so the first
+ # restart of the day (the ``hermes update`` one) looked hung and failed fleet verification.
+
+ def _init_registries_and_clocks(self) -> None:
+ """Pairing stores, hook registry, voice modes, background-task set, liveness and idle clocks."""
+ from gateway.run import (Dict, List, Optional, asyncio, time)
+ # ``pairing_store``: global/default store (CLI, callers without profile context); ``pairing_stores``:
+ # per-profile map ``authz_mixin._is_user_authorized`` routes through (one whitelist per profile).
+ from gateway.pairing import PairingStore
+ from gateway.hooks import ProfileHookRegistries
+ self.pairing_store = PairingStore()
+ self.pairing_stores: Dict[str, "PairingStore"] = {}
+ # One HookRegistry per served profile home, resolved from the active scope at emit time.
+ self.hooks = ProfileHookRegistries()
+ # Per-chat voice reply mode: "off" | "voice_only" | "all"
+ self._voice_mode: Dict[str, str] = self._load_voice_modes()
- # Per-(guild,user) transcript dedup: the voice/STT pipeline can emit one utterance twice.
- self._recent_voice_transcripts: Dict[tuple[int, int], List[tuple[float, str]]] = {}
++ # Per-(bot, guild, text channel, user) transcript dedup: voice/STT can emit one utterance twice.
++ self._recent_voice_transcripts: Dict[tuple, List[tuple[float, str]]] = {}
+ # Background tasks kept referenced so they are not garbage-collected mid-execution.
+ self._background_tasks: set = set()
+ # Event-loop liveness heartbeat: rewritten every 30s while the loop dispatches; supervisors use
+ # the file mtime / updated_at to tell "process alive" from "loop frozen".
+ # See #66892.
+ self._gateway_started_at: float = time.time()
+ self._loop_heartbeat_task: Optional[asyncio.Task] = None
+ self._loop_floor_timer_handle = self._loop_liveness_watchdog = None
+ # scale-to-zero: gateway-scoped "last inbound seen" clock, stamped in _handle_message (the single
+ # inbound chokepoint) and seeded to "now" so a fresh gateway isn't idle from epoch.
+ self._last_inbound_at: float = time.time()
+ # Re-arm cooldown after a wake so we don't go dormant again before the drained backlog updates
+ # the clock; and a one-shot latch so the "platform owns the suspend" notice logs once.
+ self._scale_to_zero_cooldown_until: float = 0.0
+ self._scale_to_zero_no_suspend_logged: bool = False
+ self._scale_to_zero_direct_platform_logged: bool = False
diff --cc gateway/run_startup.py
index 5778109e6d5,a20ba923f33..f0a1dc241fc
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@@ -582,18 -607,12 +607,19 @@@ class GatewayStartupMixin
candidates = self._resume_pending_candidates(platform)
if candidates is None:
return 0
- now = datetime.now()
scheduled = 0
for entry in candidates:
+ # Canonical admissions own restart decisions, including unknown pauses.
+ # Legacy synthetic resume must not race their restored FIFO.
+ from gateway.session_authorities import all_authorities
+ if any(authority.db._read_one(
+ 'SELECT 1 FROM session_admissions WHERE target_session_id=? LIMIT 1',
+ (entry.session_id,)) for authority in all_authorities(self)):
+ continue
+ # Epoch math: the marker was stamped naive-local by the previous process, possibly
+ # on the other side of a DST change; wall-clock subtraction is off by the shift.
marker = entry.last_resume_marked_at or entry.updated_at
- if marker is not None and (now - marker).total_seconds() > window:
+ if not _is_fresh_gateway_interruption(marker, window_secs=window):
continue
# Already being resumed (e.g. scheduled at startup, still in-flight) — no second turn.
if self._is_session_running(entry.session_key):
diff --cc gateway/run_turn.py
index 9c821973c7c,ad82ba2cf69..09d3ea19f07
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@@ -1687,16 -3597,11 +1676,15 @@@ class GatewayTurnMixin(GatewayTurnPrepa
_result_for_fb = turn_ctx.result_holder[0]
if _agent is None or not hasattr(_agent, 'model') or (_result_for_fb and _result_for_fb.get("failed")):
return
+ # A provider fallback is drift even when it serves the configured model name on another endpoint.
+ if getattr(_agent, "_provider_fallback_active", False) is True:
+ self._evict_cached_agent(session_key)
+ return
- _cfg_model = self._fallback_baseline_model(session_key, turn_ctx.source, _agent)
++ # A LOCAL session runs its frozen launch policy's model, not the gateway's configured one.
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(self, turn_ctx.source)
- _cfg_model = policy.model if policy and policy.model else _resolve_gateway_model()
- # Normalize as AIAgent.__init__ does (vendor prefix stripped on native providers), else the
- # cached agent is evicted every turn, destroying prompt caching.
- with suppress(Exception):
- from hermes_cli.model_normalize import _AGGREGATOR_PROVIDERS, normalize_model_for_provider
- _agent_provider = getattr(_agent, 'provider', '') or ''
- if _agent_provider and _agent_provider not in _AGGREGATOR_PROVIDERS:
- _cfg_model = normalize_model_for_provider(_cfg_model, _agent_provider)
++ _cfg_model = self._fallback_baseline_model(
++ session_key, turn_ctx.source, _agent, policy_model=policy.model if policy and policy.model else None)
if _agent.model != _cfg_model and not self._is_intentional_model_switch(session_key, _agent, _cfg_model):
self._evict_cached_agent(session_key)
diff --cc gateway/run_turn_hygiene.py
index 0f15161f952,00000000000..22794f67249
mode 100644,000000..100644
--- a/gateway/run_turn_hygiene.py
+++ b/gateway/run_turn_hygiene.py
@@@ -1,833 -1,0 +1,829 @@@
+"""Gateway turn hygiene 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 GatewayTurnHygieneMixin:
+ @dataclasses.dataclass
+ class _HygienePlan:
+ """Hygiene pre-check outcome for one turn."""
+
+ needs_compress: bool
+ approx_tokens: int
+ msg_count: int
+ warn_token_threshold: int
+
+ @staticmethod
+ def _hmwa_hygiene_read_config(hs, data):
+ """Apply model / compression knobs from the gateway config onto ``hs`` (invalid values keep the defaults)."""
+ # Resolve model name (same logic as run_sync)
+ _model_cfg = data.get("model", {})
+ if isinstance(_model_cfg, str):
+ hs.model = _model_cfg
+ elif isinstance(_model_cfg, dict):
+ hs.model = _model_cfg.get("default") or _model_cfg.get("model") or hs.model
+ _raw_ctx = _model_cfg.get("context_length")
+ if _raw_ctx is not None:
+ with suppress(TypeError, ValueError):
+ hs.config_context_length = int(_raw_ctx)
+ hs.provider = _model_cfg.get("provider") or None
+ hs.base_url = _model_cfg.get("base_url") or None
+
+ # Only the enabled flag is shared with the agent's compression config (hygiene runs higher).
+ _comp_cfg = data.get("compression", {})
+ if not isinstance(_comp_cfg, dict):
+ return
+ hs.compression_enabled = str(_comp_cfg.get("enabled", True)).lower() in {"true", "1", "yes"}
+
+ def _knob(key, current, cast, allow_zero=False):
+ raw = _comp_cfg.get(key)
+ if raw is None:
+ return current
+ try:
+ parsed = cast(raw)
+ except (TypeError, ValueError):
+ return current
+ return parsed if (parsed >= 0 if allow_zero else parsed > 0) else current
+
+ hs.hard_msg_limit = _knob("hygiene_hard_message_limit", hs.hard_msg_limit, int)
+ hs.timeout_seconds = _knob("hygiene_timeout_seconds", hs.timeout_seconds, float)
+ hs.total_ceiling_seconds = _knob("hygiene_total_ceiling_seconds", hs.total_ceiling_seconds, float)
+ # The ceiling can never be tighter than one idle window, or the extension loop would be dead code.
+ hs.total_ceiling_seconds = max(hs.total_ceiling_seconds, hs.timeout_seconds)
+ hs.max_turn_hold_seconds = _knob("hygiene_max_turn_hold_seconds", hs.max_turn_hold_seconds, float)
+ hs.failure_cooldown_seconds = _knob(
+ "hygiene_failure_cooldown_seconds", hs.failure_cooldown_seconds, float, allow_zero=True,
+ )
+
+ async def _hmwa_hygiene_settings(self, source, session_key):
+ """Resolve model/provider/context-length + hygiene knobs (fail-soft: errors keep defaults).
+
+ The 0.85 threshold is deliberately HIGHER than the agent's compressor (0.50): a safety net
+ for sessions that grew between turns. ``max_turn_hold_seconds`` bounds the TURN wait
+ (compressor keeps running detached, commit fenced); kept below transport idle-timeouts."""
+ from gateway.run import _load_gateway_config
+ hs = self._HygieneSettings(
+ model="anthropic/claude-sonnet-4.6", threshold_pct=0.85, compression_enabled=True,
+ hard_msg_limit=5000, timeout_seconds=30.0, total_ceiling_seconds=600.0,
+ max_turn_hold_seconds=10.0, failure_cooldown_seconds=300.0, config_context_length=None,
+ provider=None, base_url=None, api_key=None, data={},
+ )
+ try:
+ hs.data = _load_gateway_config()
+ if hs.data:
+ self._hmwa_hygiene_read_config(hs, hs.data)
+ configured_model, configured_provider, configured_base_url = hs.model, hs.provider, hs.base_url
+
+ with suppress(Exception):
+ hs.model, _hyg_runtime = self._resolve_session_agent_runtime(
+ source=source, session_key=session_key,
+ user_config=hs.data if isinstance(hs.data, dict) else None,
+ )
+ hs.provider = _hyg_runtime.get("provider") or hs.provider
+ hs.base_url = _hyg_runtime.get("base_url") or hs.base_url
+ hs.api_key = _hyg_runtime.get("api_key") or hs.api_key
+
+ if hs.config_context_length is not None:
+ try:
+ from hermes_cli.route_identity import should_clear_context_pin_async
+
+ if await should_clear_context_pin_async(
+ configured_model, hs.model, configured_base_url, hs.base_url,
+ configured_provider, hs.provider,
+ ):
+ hs.config_context_length = None
+ except Exception:
+ hs.config_context_length = None
+
+ # custom_providers per-model context_length fallback (as in run_agent.py); needs base_url.
+ if hs.config_context_length is None and hs.base_url:
+ with suppress(TypeError, ValueError):
+ try:
+ from hermes_cli.config import (
+ get_compatible_custom_providers as _gw_gcp,
+ get_custom_provider_context_length as _gw_gccl,
+ )
+ _hyg_custom_providers = _gw_gcp(hs.data)
+ except Exception:
+ _hyg_custom_providers = hs.data.get("custom_providers")
+ if not isinstance(_hyg_custom_providers, list):
+ _hyg_custom_providers = []
+ _hyg_custom_ctx = _gw_gccl(
+ model=hs.model, base_url=hs.base_url, custom_providers=_hyg_custom_providers,
+ )
+ if _hyg_custom_ctx:
+ hs.config_context_length = int(_hyg_custom_ctx)
+ except Exception:
+ pass
+ return hs
+
+ async def _hmwa_hygiene_plan(self, hs, history, session_entry, session_key):
+ """Decide whether hygiene compression fires this turn (token/message thresholds, DB-backed
+ failure cooldown, in-flight compression)."""
+ from agent.model_metadata import estimate_messages_tokens_rough, get_model_context_length_async
+ _hyg_context_length = await get_model_context_length_async(
+ hs.model, base_url=hs.base_url or "", api_key=hs.api_key or "",
+ config_context_length=hs.config_context_length, provider=hs.provider or "",
+ )
+ _compress_token_threshold = int(_hyg_context_length * hs.threshold_pct)
+ _warn_token_threshold = int(_hyg_context_length * 0.95)
+ _msg_count = len(history)
+
+ # Real usage decides: the API-reported prompt count, else the anchor persisted on the session
+ # row (real count + delta of what was appended since, survives gateway restarts), else the
+ # rough estimate (runs 30-50% high, which only fires hygiene early — safe). Do NOT compensate
+ # with a threshold multiplier.
+ from agent.image_token_cost import image_cost_context, learned_image_token_cost
+ _anchored = None
+ # Images in any local delta/estimate are priced at the cost learned from this model's usage.
+ with image_cost_context(learned_image_token_cost(hs.model, hs.base_url)):
+ if session_entry.last_prompt_tokens <= 0:
+ from agent.usage_anchor import persisted_anchor_tokens
+ _session_db = getattr(self, "_session_db", None)
+ _anchored = persisted_anchor_tokens(
+ getattr(_session_db, "_db", _session_db), session_entry.session_id, history,
+ )
+ if session_entry.last_prompt_tokens > 0:
+ _approx_tokens, _token_source = session_entry.last_prompt_tokens, "actual"
+ elif _anchored is not None:
+ _approx_tokens, _token_source = _anchored, "anchored"
+ else:
+ _approx_tokens, _token_source = estimate_messages_tokens_rough(history), "estimated"
+
+ # Hard safety valve: force compression at an extreme message count regardless of tokens,
+ # breaking the disconnect → no token data → no compression spiral. 5000 clears 1M+ sessions.
+ _needs_compress = _approx_tokens >= _compress_token_threshold or _msg_count >= hs.hard_msg_limit
+
+ if _needs_compress:
+ # DB-backed cooldown (shared with context_compressor.py): survives gateway restarts, so a
+ # failing compression is not re-triggered on every restart.
+ # The in-memory dict was reset on every restart, re-triggering the same failing compression and
+ # wedging session storage (#74136).
+ _session_db = getattr(self, "_session_db", None)
+ _getter = getattr(getattr(_session_db, "_db", _session_db), "get_compression_failure_cooldown", None)
+ if _getter is not None:
+ _cooldown_state = None
+ with suppress(Exception):
+ _cooldown_state = _getter(session_entry.session_id)
+ if _cooldown_state and _cooldown_state.get("remaining_seconds", 0) > 0:
+ logger.info(
+ "Session hygiene: skipping compression for %s; "
+ "previous failure cooldown active for %.1fs",
+ session_entry.session_id, _cooldown_state["remaining_seconds"],
+ )
+ _needs_compress = False
+
+ if _needs_compress and await self._session_has_compression_in_flight(session_key):
+ # A prior compression still holds the durable lock (e.g. a shielded worker left by /stop):
+ # another attempt would wait up to 600s behind a commit the fence will refuse.
+ logger.info(
+ "Session hygiene: skipping compression for %s; "
+ "another compression is already in flight", session_entry.session_id,
+ )
+ _needs_compress = False
+
+ if _needs_compress:
+ logger.info(
+ "Session hygiene: %s messages, ~%s tokens (%s) — auto-compressing "
+ "(threshold: %s%% of %s = %s tokens)",
+ _msg_count, f"{_approx_tokens:,}", _token_source,
+ int(hs.threshold_pct * 100), f"{_hyg_context_length:,}", f"{_compress_token_threshold:,}",
+ )
+ return self._HygienePlan(_needs_compress, _approx_tokens, _msg_count, _warn_token_threshold)
+
+ async def _hmwa_hygiene_wait_for_summary(self, attempt, hs, session_entry):
+ """Progress-aware inline wait for the detached hygiene compressor. Returns the compressed
+ transcript; raises ``HygieneTurnHoldExceeded`` (turn-hold budget) or
+ ``asyncio.TimeoutError`` (idle/ceiling/fence cancel) for the caller's handlers.
+
+ Idle timeout (fence ticks per streamed token) + hard ceiling + turn-hold cap."""
+ from gateway.run import HygieneTurnHoldExceeded, hygiene_wait_should_extend
+ fence = attempt.commit_fence
+ while True:
+ if fence.is_cancelled:
+ raise asyncio.TimeoutError
+ # Charge the idle budget from the LAST PROGRESS event, else silence can approach 2x timeout.
+ _hyg_waited = time.monotonic() - attempt.wait_started
+ _slice = min(
+ max(hs.timeout_seconds - fence.seconds_since_progress(), 0.005),
+ max(hs.total_ceiling_seconds - _hyg_waited, 0.005),
+ )
+ # Cap the slice at the remaining turn-hold budget so a continuously-streaming worker can't
+ # hold the turn until the ceiling. Budget exhausted → immediate timeout → abandonment.
+ _turn_hold_remaining = hs.max_turn_hold_seconds - (time.monotonic() - attempt.wait_started)
+ _slice = 0.005 if _turn_hold_remaining <= 0 else min(_slice, max(_turn_hold_remaining, 0.005))
+ # Short poll so a /stop or /restart cancel is not stuck behind a full idle window.
+ _idle_left = max(hs.timeout_seconds - fence.seconds_since_progress(), 0.005)
+ _slice = min(_slice, 0.25)
+ try:
+ _compressed, _ = await asyncio.wait_for(asyncio.shield(attempt.future), timeout=_slice)
+ return _compressed
+ except asyncio.TimeoutError:
+ if fence.is_cancelled:
+ raise
+ _hyg_waited = time.monotonic() - attempt.wait_started
+ _idle = fence.seconds_since_progress()
+ # Never hold the TURN past the budget even while the summary streams: proceed on the
+ # uncompressed transcript so the wire never trips a transport idle-timeout.
+ if _hyg_waited >= hs.max_turn_hold_seconds:
+ logger.info(
+ "Session hygiene compression for session %s exceeded the turn-hold "
+ "budget (%.1fs >= %.1fs) — abandoning inline wait, proceeding "
+ "without compression this turn",
+ session_entry.session_id, _hyg_waited, hs.max_turn_hold_seconds,
+ )
+ raise HygieneTurnHoldExceeded(
+ f"turn-hold budget {hs.max_turn_hold_seconds:.1f}s "
+ f"elapsed after {_hyg_waited:.1f}s"
+ )
+ if hygiene_wait_should_extend(
+ idle=_idle, timeout=hs.timeout_seconds, waited=_hyg_waited,
+ ceiling=hs.total_ceiling_seconds, fence_cancelled=fence.is_cancelled,
+ ):
+ if _slice >= _idle_left - 1e-9:
+ logger.info(
+ "Session hygiene compression for session %s still streaming after "
+ "%.0fs (last progress %.1fs ago) — extending wait (ceiling %.0fs)",
+ session_entry.session_id, _hyg_waited, _idle, hs.total_ceiling_seconds,
+ )
+ continue
+ raise
+
+ async def _hmwa_hygiene_cancel_or_adopt(self, attempt, context):
+ """Cancel the worker at the commit fence; on success release its lease and defer agent
+ cleanup, returning ``None``. When the worker already crossed into its commit, consume and
+ return the compressed transcript instead (a successful compaction is never a timeout; the
+ turn may be held past the budget by up to the commit duration — by design). The lock-free
+ ``commit_in_flight`` marker keeps the poll from spinning on a hung commit."""
+ fence = attempt.commit_fence
+ while not fence.commit_in_flight:
+ cancelled = fence.try_cancel_before_commit()
+ if cancelled is None:
+ await asyncio.sleep(0.025)
+ elif cancelled:
+ fence.release_cancelled_compression_lock()
+ self._hmwa_hygiene_defer_cleanup(attempt, context)
+ return None
+ else:
+ break
+ _compressed, _ = await attempt.future
+ return _compressed
+
+ def _hmwa_hygiene_defer_cleanup(self, attempt, context):
+ """Hand the agent's cleanup to the still-running worker future and mark it deferred."""
+ self._defer_agent_cleanup_until_future_done(attempt.future, attempt.agent, context=context)
+ attempt.cleanup_deferred = True
+
+ @staticmethod
+ def _hmwa_hygiene_stamp(agent, desc, provenance_name, debug_label):
+ from agent.session_activity import ActivityProvenance
+ from gateway.run import _stamp_hygiene_compression_provenance
+ _stamp_hygiene_compression_provenance(agent, desc, getattr(ActivityProvenance, provenance_name), debug_label)
+
+ async def _hmwa_hygiene_notify(self, source, meta, message, what):
+ """Best-effort user notice on the hygiene thread; failure is logged, never raised."""
+ try:
+ _adapter = self._delivery_adapter_for(source)
+ if _adapter and source.chat_id:
+ await _adapter.emit_warning(source.chat_id, message, metadata=meta,
+ logical_platform=source.platform)
+ except Exception as _werr:
+ logger.warning("Failed to deliver %s to user: %s", what, _werr)
+
+ async def _hmwa_hygiene_record_failure_cooldown(self, hs, session_key, session_id, reason):
+ """Escalate the failure streak (off-loop) and persist the cooldown, when enabled."""
+ from gateway.run import _hygiene_cooldown_for_failure, _record_hygiene_cooldown
+ if hs.failure_cooldown_seconds < 0:
+ return
+ _hyg_cooldown = await asyncio.to_thread(
+ _hygiene_cooldown_for_failure, self, session_key, hs.failure_cooldown_seconds,
+ )
+ _record_hygiene_cooldown(self, session_id, _hyg_cooldown, reason)
+
+ async def _hmwa_hygiene_on_turn_hold(self, attempt, hs, session_entry, session_key, source):
+ """``except HygieneTurnHoldExceeded`` body: keep or cancel the worker's commit admission,
+ notify the user, and re-raise; returns the compressed transcript only when the worker
+ was already committing.
+
+ Turn-hold expiry is an availability boundary, not a failure: the streak must NOT advance,
+ only flat retry spacing is recorded. A watermark-fenced commit (rows appended after
+ compression start survive as cloned tail) KEEPS admission: the turn proceeds uncompressed
+ now and the summary is adopted at the worker's fenced commit — always cancelling burned
+ every attempt for thinking summary models. Without the fence a late commit could clobber
+ newer turns, so cancel."""
+ from gateway.run import (
+ _HYGIENE_TURNHOLD_RETRY_SECONDS, _record_hygiene_cooldown, _reset_hygiene_failure_streak
+ )
+ fence = attempt.commit_fence
+ _hyg_keep_admission = bool(getattr(fence, "commit_watermark_fenced", False)) and not fence.is_cancelled
+ if _hyg_keep_admission:
+ self._hmwa_hygiene_defer_cleanup(attempt, "session hygiene turn-hold")
+ # NO retry-after here (it would also block the agent-side preflight compressor); spacing
+ # comes from the durable compression lock. The done-callback records the flat retry-after
+ # ONLY if the worker ends without committing anything.
+ _sid, _skey, _agent = session_entry.session_id, session_key, attempt.agent
+
+ def _hyg_adopt_or_space_retry(_fut, _gw=self, _sid=_sid, _skey=_skey, _agent=_agent):
+ try:
+ _exc = _fut.exception()
+ except (asyncio.CancelledError, Exception):
+ _committed = False
+ else:
+ _committed = _exc is None and (
+ bool(getattr(_agent, "_last_compaction_in_place", False))
+ or getattr(_agent, "session_id", _sid) != _sid
+ )
+ if _committed:
+ logger.info(
+ "Session hygiene compression for session %s finished after the "
+ "turn-hold was released — summary adopted at the watermark-fenced "
+ "commit boundary (#97963)", _sid,
+ )
+ try:
+ _reset_hygiene_failure_streak(_gw, _skey)
+ except Exception as _rs_err:
+ logger.debug("hygiene streak reset after deferred adoption failed: %s", _rs_err)
+ else:
+ # Nothing to adopt (summary failed / fence refused / superseded): flat spacing so
+ # sustained traffic doesn't spawn and abandon a compressor every turn.
+ _record_hygiene_cooldown(
+ _gw, _sid, _HYGIENE_TURNHOLD_RETRY_SECONDS,
+ "hygiene compression deferred: turn-hold budget expired and the "
+ "detached attempt did not commit",
+ )
+
+ attempt.future.add_done_callback(_hyg_adopt_or_space_retry)
+ _log_suffix = (
+ " — the watermark-fenced worker keeps its commit admission and the summary "
+ "will be adopted when it finishes"
+ )
+ else:
+ _adopted = await self._hmwa_hygiene_cancel_or_adopt(attempt, "session hygiene turn-hold")
+ if _adopted is not None:
+ return _adopted
+ # Short flat retry-after, else every turn re-spawns, holds and cancels a compressor.
+ _record_hygiene_cooldown(
+ self, session_entry.session_id, _HYGIENE_TURNHOLD_RETRY_SECONDS,
+ "hygiene compression deferred: turn-hold budget expired while the "
+ "summary was still streaming",
+ )
+ _log_suffix = ""
+ self._hmwa_hygiene_stamp(
+ attempt.agent, "session hygiene compression turn-hold",
+ "AGENT_COMPRESSION_TURNHOLD", "hygiene compression turn-hold activity stamp failed",
+ )
+ logger.info(
+ "Session hygiene compression for session %s exceeded turn-hold budget (%.1fs); "
+ "proceeding without compression this turn%s",
+ session_entry.session_id, time.monotonic() - attempt.wait_started, _log_suffix,
+ )
+ await self._hmwa_hygiene_notify(
+ source, attempt.meta, t("gateway.compress.turnhold_deferred"), "compression-turnhold notice",
+ )
+ raise
+
+ async def _hmwa_hygiene_on_timeout(self, attempt, hs, session_entry, session_key, source):
+ """``except asyncio.TimeoutError`` body: cancel at the commit fence, record the failure
+ cooldown, warn the user, and re-raise; returns the compressed transcript only when the
+ worker crossed the commit boundary first."""
+ from gateway.run import _hygiene_compression_timeout_message
+ fence = attempt.commit_fence
+ _hyg_waited = time.monotonic() - attempt.wait_started
+ _hyg_total_exhausted = _hyg_waited >= hs.total_ceiling_seconds or fence.deadline_exceeded
+ if _hyg_total_exhausted:
+ # The worker checks this deadline between digest calls; keep its lease until it exits so
+ # an unchanged session cannot overlap a retry (the release below is then a no-op).
+ fence.retain_compression_lock_until_worker_done()
+ # Capture fence state BEFORE try_cancel (which itself sets is_cancelled).
+ _hyg_fence_cancelled = fence.is_cancelled
+ _adopted = await self._hmwa_hygiene_cancel_or_adopt(attempt, "session hygiene timeout")
+ if _adopted is not None:
+ return _adopted
+ await self._hmwa_hygiene_record_failure_cooldown(
+ hs, session_key, session_entry.session_id,
+ "session hygiene compression " + (
+ "cancelled at commit fence" if _hyg_fence_cancelled
+ else "total ceiling exhausted" if _hyg_total_exhausted
+ else "timed out with no output from the summary model"
+ ),
+ )
+ self._hmwa_hygiene_stamp(
+ attempt.agent,
+ "session hygiene compression cancelled at commit fence" if _hyg_fence_cancelled
+ else "session hygiene compression timed out",
+ "AGENT_COMPRESSION_TIMEOUT", "hygiene compression timeout activity stamp failed",
+ )
+ if _hyg_fence_cancelled:
+ logger.warning(
+ "Session hygiene compression for session %s was cancelled at the "
+ "commit fence; continuing without compression", session_entry.session_id,
+ )
+ raise
+ _hyg_elapsed = time.monotonic() - attempt.wait_started
+ if _hyg_total_exhausted:
+ logger.warning(
+ "Session hygiene compression for session %s reached its total ceiling after "
+ "%.1fs (progress observed=%s); continuing without compression",
+ session_entry.session_id, _hyg_elapsed, fence.progress_observed,
+ )
+ else:
+ logger.warning(
+ "Session hygiene compression for session %s made no progress for %.1fs "
+ "(total wait %.1fs, ceiling %.1fs); continuing without compression",
+ session_entry.session_id, fence.seconds_since_progress(), _hyg_elapsed, hs.total_ceiling_seconds,
+ )
+ await self._hmwa_hygiene_notify(
+ source, attempt.meta,
+ _hygiene_compression_timeout_message(
+ total_exhausted=_hyg_total_exhausted, elapsed=_hyg_elapsed,
+ idle_timeout=hs.timeout_seconds, progress_observed=fence.progress_observed,
+ ),
+ "compression-timeout warning",
+ )
+ raise
+
+ def _hmwa_hygiene_on_unwind(self, attempt, hs, session_entry, session_key):
+ """``except BaseException`` body (caller re-raises): revoke commit admission BEFORE the host
+ unwinds so the detached worker can never commit later, and record a cooldown — otherwise
+ the next turn re-arms hygiene and waits up to 600s behind a fence that refuses again."""
+ from gateway.run import _hygiene_cooldown_for_failure, _record_hygiene_cooldown
+ attempt.commit_fence.revoke_commit_admission()
+ if not attempt.cleanup_deferred:
+ self._hmwa_hygiene_defer_cleanup(attempt, "session hygiene unwind")
+ if hs.failure_cooldown_seconds >= 0:
+ try:
+ _record_hygiene_cooldown(
+ self, session_entry.session_id,
+ _hygiene_cooldown_for_failure(self, session_key, hs.failure_cooldown_seconds),
+ "session hygiene compression cancelled at commit fence",
+ )
+ except Exception as _cd_err:
+ logger.debug("hygiene unwind cooldown record failed: %s", _cd_err)
+
+ async def _hmwa_hygiene_adopt_transcript(
+ self, attempt, _compressed, history, plan, *, session_entry, source, _quick_key, run_generation,
+ ):
+ """Adopt a finished compression (rotation / in-place / refused); publishes the transcript to
+ continue with on ``attempt.history``. Returns ``(rotated, in_place, new_count, new_tokens)``.
+
+ Rewrite only on rotation (NEW session id): in-place compaction already soft-archived the
+ old rows and rewrite_transcript() would DELETE them; neither rotation nor in-place signals
+ FAILURE and an unconditional rewrite would leave only the summary. Write-before-repoint:
+ a repoint-then-failed-rewrite would point the live entry at an empty session."""
+ from gateway.run_turn import hygiene_no_commit_reason
+ from agent.model_metadata import estimate_messages_tokens_rough
+ _hyg_agent = attempt.agent
+ # _compress_context rotates to a NEW session_id so the old transcript stays intact/searchable.
+ _hyg_new_sid = _hyg_agent.session_id
+ _hyg_rotated = _hyg_new_sid != session_entry.session_id
+ _hyg_in_place = bool(getattr(_hyg_agent, "_last_compaction_in_place", False))
+ # Anti-growth guard: refuse a compression that did not shrink the transcript (seen 427K→598K).
+ _hyg_in_toks = estimate_messages_tokens_rough(history)
+ _hyg_out_toks = estimate_messages_tokens_rough(_compressed)
+ if _hyg_rotated and _hyg_out_toks > _hyg_in_toks:
+ logger.warning(
+ "Gateway hygiene compression for session %s would grow transcript (~%s -> ~%s "
+ "tokens); keeping the original transcript unchanged",
+ session_entry.session_id, f"{_hyg_in_toks:,}", f"{_hyg_out_toks:,}",
+ )
+ _hyg_rotated = False
+ _compressed = history
- # Only rewrite the transcript when rotation produced a NEW session id. In-place compaction does NOT
++ # Only persist a child transcript when rotation produced a NEW session id. In-place compaction does NOT
+ # need a rewrite: archive_and_compact() has already soft-archived the previous active rows and
+ # inserted the compacted messages as the new active set inside _compress_context(). Calling
+ # rewrite_transcript() after in-place compaction would invoke replace_messages(active_only=False)
+ # which DELETEs ALL rows — including the archived turns that archive_and_compact() deliberately
+ # preserved (silent data loss, #61145). The danger this guards against (mirrors the /compress fix
+ # #44794/#39704): if _compress_context returns a summary but neither rotates nor completes
+ # archive_and_compact(), the session_id is unchanged for a FAILURE reason, and an unconditional
+ # rewrite_transcript() would DELETE the original messages and replace them with only the compressed
+ # summary (permanent data loss, #21301). Write-before-repoint (mirrors manual /compress): if we
+ # repointed session_entry onto the child SID and rewrite_transcript then failed (lock/ENOSPC), the
+ # live entry would already reference a brand-new empty session while the turn continues — the
+ # conversation silently vanishes. Persist the child transcript first; only then rebind the live
+ # entry.
+ if _hyg_rotated:
- if not await self.async_session_store.rewrite_transcript(_hyg_new_sid, _compressed):
++ # Published child is already durable; a rewrite would drop rows cloned at publish.
++ if not await self.async_session_store.persist_rotated_compression_child(
++ session_entry.session_id, _hyg_new_sid, _compressed):
+ logger.error(
+ "Session hygiene: failed to persist compressed transcript for rotated session "
+ "%s → %s; keeping the live entry on the original session so the "
+ "conversation is not dropped", session_entry.session_id, _hyg_new_sid,
+ )
+ # Fail closed: treat like no rotation.
+ _hyg_rotated = False
+ _hyg_in_place = False
+ else:
+ session_entry.session_id = _hyg_new_sid
+ # The held turn lease follows the rotation (alias keys still serialize on this turn).
+ self._rebind_turn_lease(_quick_key, run_generation, _hyg_new_sid)
+ await self.async_session_store._save()
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="hygiene-compression",
+ )
+
+ if _hyg_rotated or _hyg_in_place:
- # Rewritten (rotation) or persisted by archive_and_compact() (in-place): reset token count.
++ # Persisted (rotation) or persisted by archive_and_compact() (in-place): reset token count.
+ session_entry.last_prompt_tokens = 0
+ attempt.history = _compressed
+ _new_count = len(_compressed)
+ _new_tokens = estimate_messages_tokens_rough(_compressed)
+ else:
+ # No rewrite happened — post-compression counts equal the pre-compression ones.
+ _new_count = plan.msg_count
+ _new_tokens = plan.approx_tokens
+ logger.warning(
+ "Gateway hygiene compression for session %s did not rotate or compact in place (%s) — "
+ "preserving the original transcript instead of overwriting it with the summary (#21301).",
+ session_entry.session_id, hygiene_no_commit_reason(_hyg_agent),
+ )
+
+ logger.info(
+ "Session hygiene: compressed %s → %s msgs, ~%s → ~%s tokens",
+ plan.msg_count, _new_count, f"{plan.approx_tokens:,}", f"{_new_tokens:,}",
+ )
+ if _new_tokens >= plan.warn_token_threshold:
+ logger.warning("Session hygiene: still ~%s tokens after compression", f"{_new_tokens:,}")
+ return _hyg_rotated, _hyg_in_place, _new_count, _new_tokens
+
+ async def _hmwa_hygiene_apply_result(
+ self, attempt, hs, _compressed, history, plan, *,
+ session_entry, session_key, source, _quick_key, run_generation,
+ ):
+ """Adopt a finished hygiene compression, rebind the session + turn lease, record
+ streak/cooldown, and warn the user on abort."""
+ from gateway.run import _reset_hygiene_failure_streak, hygiene_compaction_recovered
+ _hyg_rotated, _hyg_in_place, _new_count, _new_tokens = await self._hmwa_hygiene_adopt_transcript(
+ attempt, _compressed, history, plan, session_entry=session_entry, source=source,
+ _quick_key=_quick_key, run_generation=run_generation,
+ )
+ # Summary failure aborts the compressor (nothing dropped). Warn the user visibly — agent.log
+ # is invisible on TG/Discord — so they know the chat is "frozen" and can /compress or /reset.
+ _comp = getattr(attempt.agent, "context_compressor", None)
+ _hyg_aborted = _comp is not None and getattr(_comp, "_last_compress_aborted", False)
+ # A fence-cancelled _compress_context returns the original transcript with
+ # _last_compress_aborted False: treat that no-op as an abort so hygiene records a cooldown
+ # instead of retrying into the 600s wait. A committed rotate/in-place is never an abort.
+ _hyg_fence_cancelled = bool(attempt.commit_fence.is_cancelled and not _hyg_rotated and not _hyg_in_place)
+ if _hyg_fence_cancelled:
+ _hyg_aborted = True
+ # Recovery decision lives in the unit-tested predicate: the "neither rotated nor in place"
+ # path reuses pre-compression counts, so a numbers-only check would read a no-op as success.
+ if not _hyg_aborted and hygiene_compaction_recovered(
+ aborted=_hyg_aborted, rotated=_hyg_rotated, in_place=_hyg_in_place,
+ msg_count=plan.msg_count, new_count=_new_count, approx_tokens=plan.approx_tokens,
+ new_tokens=_new_tokens,
+ ):
+ await asyncio.to_thread(_reset_hygiene_failure_streak, self, session_key)
+ if _hyg_aborted:
+ await self._hmwa_hygiene_record_failure_cooldown(
+ hs, session_key, session_entry.session_id,
+ "session hygiene compression cancelled at commit fence" if _hyg_fence_cancelled
+ else getattr(_comp, "_last_summary_error", None),
+ )
+ self._hmwa_hygiene_stamp(
+ attempt.agent, "session hygiene compression aborted",
+ "AGENT_COMPRESSION_COOLDOWN", "hygiene compression abort activity stamp failed",
+ )
+ if not _hyg_fence_cancelled:
+ # Force-redact: provider exception text may contain credentials; this reaches users.
+ from agent.redact import redact_sensitive_text
- _err = redact_sensitive_text(getattr(_comp, "_last_summary_error", None) or "unknown error", force=True)
++ _err = redact_sensitive_text(
++ getattr(_comp, "_last_summary_error", None) or t("gateway.shared.unknown_error"), force=True)
+ logger.warning("Session hygiene compression aborted: %s", _err)
+ await self._hmwa_hygiene_notify(
- source, attempt.meta,
- "⚠️ Shortening the conversation history failed, so I kept everything as-is. "
- "Run /compress to try again or /new to start fresh. If this keeps happening, "
- "run `hermes doctor` on the host.",
- "compression-failure warning",
++ source, attempt.meta, t("gateway.compress.hygiene_failed"), "compression-failure warning",
+ )
+ # Configured aux model failed, recovered on the main model: only the user can fix that config.
+ elif _comp is not None and getattr(_comp, "_last_aux_model_failure_model", None):
+ _aux_model = getattr(_comp, "_last_aux_model_failure_model", "")
- _aux_err = getattr(_comp, "_last_aux_model_failure_error", None) or "unknown error"
++ _aux_err = getattr(_comp, "_last_aux_model_failure_error", None) or t("gateway.shared.unknown_error")
+ await self._hmwa_hygiene_notify(
- source, attempt.meta, f"ℹ️ Configured compression model `{_aux_model}` "
- f"failed ({_aux_err}). Recovered using your main "
- "model — context is intact — but you may want to "
- "check `auxiliary.compression.model` in config.yaml.",
++ source, attempt.meta, t("gateway.compress.aux_failed", model=_aux_model, error=_aux_err),
+ "aux-model-fallback notice",
+ )
+
+ async def _hmwa_hygiene_codex_compaction(self, hs, plan, history, session_entry, session_key, _hyg_runtime):
+ """codex app-server runtime: the real context is the server-side thread, not the transcript
+ mirror. The detached-agent path would only rewrite the mirror and its finally-eviction
+ would destroy the live thread (next turn starts blank), so use the cached agent's
+ thread/compact/start and KEEP it cached."""
+ from gateway.run import run_codex_hygiene_compaction
+ # codex app-server runtime: the model's real context is the app-server's server-side thread, not the
+ # transcript mirror. See #73503.
+ _hyg_codex_auto = "native"
+ _hyg_comp_cfg = hs.data.get("compression") if isinstance(hs.data, dict) else None
+ if isinstance(_hyg_comp_cfg, dict):
+ _hyg_codex_auto = str(_hyg_comp_cfg.get("codex_app_server_auto", "native") or "native")
+ _hyg_codex_outcome = await run_codex_hygiene_compaction(
+ self, session_key, session_entry.session_id, auto_mode=_hyg_codex_auto, history=history,
+ approx_tokens=plan.approx_tokens, timeout_seconds=hs.total_ceiling_seconds,
+ failure_cooldown_seconds=hs.failure_cooldown_seconds,
+ )
+ logger.info(
+ "Session hygiene (codex app-server): %s (session=%s, mode=%s, ~%s tokens)",
+ _hyg_codex_outcome, session_entry.session_id, _hyg_codex_auto, f"{plan.approx_tokens:,}",
+ )
+
+ async def _hmwa_hygiene_build_agent(self, _hyg_model, _hyg_runtime, session_entry):
+ """Build the detached hygiene ``AIAgent`` with the live session's system prompt. Returns
+ ``(agent, sync_session_db)``."""
+ from gateway.run import _GATEWAY_HYGIENE_PLATFORM, _seed_hygiene_system_prompt
+ from run_agent import AIAgent
+ try:
+ _hyg_session_row = await self._session_db.get_session(session_entry.session_id)
+ except Exception as exc:
+ _hyg_session_row = None
+ logger.warning(
+ "Session hygiene could not restore the system prompt for session %s: %s. "
+ "Preserving an empty prompt so the live turn rebuilds it with its "
+ "configured providers.", session_entry.session_id, exc, exc_info=True,
+ )
+ _hyg_session_db = getattr(self._session_db, "_db", self._session_db)
+ # With compression.checkpoint_required on, load the memory provider so the checkpoint exists
+ # before any mutation; otherwise keep the fast path (no provider init).
+ from hermes_cli.config import load_config as _load_cfg
+ from utils import is_truthy_value as _is_truthy
+
+ _hyg_checkpoint_required = _is_truthy(
+ ((_load_cfg() or {}).get("compression") or {}).get("checkpoint_required"), default=False,
+ )
+ _hyg_agent = AIAgent(
+ **_hyg_runtime, model=_hyg_model, max_iterations=4, quiet_mode=True,
+ skip_memory=not _hyg_checkpoint_required, enabled_toolsets=["memory"],
+ session_id=session_entry.session_id, session_db=_hyg_session_db,
+ )
+ _seed_hygiene_system_prompt(_hyg_agent, _hyg_session_row)
+ # The stamp only marks this agent as no real surface. Since #104414 Platform is not a
+ # restore-identity field, so it no longer forces the next live turn to rebuild; the seed's
+ # retain flag is what keeps the reduced-toolset build out of the session row (#122822).
+ _hyg_agent.platform = _GATEWAY_HYGIENE_PLATFORM
+ return _hyg_agent, _hyg_session_db
+
+ async def _hmwa_hygiene_detached_attempt(
+ self, attempt, hs, plan, history, _hyg_msgs, _hyg_model, _hyg_runtime,
+ source, session_entry, session_key, _quick_key, run_generation,
+ ):
+ """Run one detached hygiene compression attempt end to end; publishes the transcript to
+ continue with (compressed or original) on ``attempt.history``."""
+ from gateway.run import HygieneTurnHoldExceeded
+ from agent.conversation_compression import CompressionCommitFence
+ _hyg_agent, _hyg_session_db = await self._hmwa_hygiene_build_agent(_hyg_model, _hyg_runtime, session_entry)
+ attempt.agent = _hyg_agent
+ try:
+ # Hygiene owns the session binding, so prefer in-place compaction over minting a
+ # continuation child. Without a SessionDB this stays False.
+ _hyg_agent.compression_in_place = True
+ _bind_hyg_state = getattr(getattr(_hyg_agent, "context_compressor", None), "bind_session_state", None)
+ if callable(_bind_hyg_state):
+ _bind_hyg_state(_hyg_session_db, session_entry.session_id)
+ # Never finalize on close() — that would end the live gateway session row.
+ _hyg_agent._end_session_on_close = False
+ _hyg_agent._print_fn = lambda *a, **kw: None
+
+ loop = asyncio.get_running_loop()
+ _hyg_commit_fence = CompressionCommitFence(total_ceiling_seconds=hs.total_ceiling_seconds)
+ # Default executor (NOT self._get_executor): a hung summary must never occupy an
+ # agent-work slot. MUST run in the caller's contextvars (multiplex secret scope).
+ attempt.commit_fence = _hyg_commit_fence
+ attempt.future = loop.run_in_executor(
+ None,
+ # But it MUST run inside the caller's contextvars: under multiplex_profiles the profile
+ # secret scope / HERMES_HOME override live in ContextVars, and a bare run_in_executor worker
+ # starts with an empty Context — the summary model's get_secret(<PROVIDER>_API_KEY) then
+ # fails closed (UnscopedSecretError) and every hygiene compaction silently degrades to a
+ # lossy truncation (#100849 bundle).
+ copy_context().run,
+ # task_id = the live turn's dedup bucket (session row id), never "" (= reset every task).
+ lambda: _hyg_agent._compress_context(
+ _hyg_msgs, "", approx_tokens=plan.approx_tokens, commit_fence=_hyg_commit_fence,
+ task_id=session_entry.session_id or "default",
+ ),
+ )
+ # Register the live worker with shutdown NOW, not only once it is deferred: the default
+ # executor is outside self._executor's quiesce, so an untracked in-flight summary would let
+ # stop() close/checkpoint state.db under its late write (mirrors run_codex_hygiene_compaction).
+ self._track_deferred_agent_worker(attempt.future, _hyg_agent)
+ attempt.wait_started = time.monotonic()
+ try:
+ _compressed = await self._hmwa_hygiene_wait_for_summary(attempt, hs, session_entry)
+ except HygieneTurnHoldExceeded:
+ _compressed = await self._hmwa_hygiene_on_turn_hold(attempt, hs, session_entry, session_key, source)
+ except asyncio.TimeoutError:
+ _compressed = await self._hmwa_hygiene_on_timeout(attempt, hs, session_entry, session_key, source)
+ except BaseException:
+ self._hmwa_hygiene_on_unwind(attempt, hs, session_entry, session_key)
+ raise
+
+ await self._hmwa_hygiene_apply_result(
+ attempt, hs, _compressed, history, plan, session_entry=session_entry,
+ session_key=session_key, source=source, _quick_key=_quick_key,
+ run_generation=run_generation,
+ )
+ finally:
+ # Evict the cached agent so the next turn rebuilds its system prompt.
+ self._evict_cached_agent(session_key)
+ if not attempt.cleanup_deferred:
+ await self._cleanup_agent_resources_off_loop(_hyg_agent, context="session hygiene")
+
+ async def _hmwa_run_session_hygiene(
+ self, event, source, session_entry, session_key, history, _quick_key, run_generation,
+ ):
+ """Auto-compress pathologically large transcripts before the agent starts so oversized
+ histories don't cause repeated truncation/context failures. Token source: the API's
+ prompt_tokens from the last turn, else a char/4 estimate."""
+ from gateway.run import HygieneTurnHoldExceeded
+ if not history or len(history) < 4:
+ return history
+
+ hs = await self._hmwa_hygiene_settings(source, session_key)
+ # Hygiene can never land with compression disabled; a sub-limit transcript is the identity (#111988).
+ if not hs.compression_enabled:
+ return self._bound_hygiene_payload(history, hs, session_entry)
+ plan = await self._hmwa_hygiene_plan(hs, history, session_entry, session_key)
+ # No compression this turn (under both thresholds, cooldown, or one already in flight): without
+ # the bound the model would get the full uncompressed transcript.
+ if not plan.needs_compress:
+ return self._bound_hygiene_payload(history, hs, session_entry)
+
+ attempt = self._HygieneAttempt(agent=None, meta=self._event_thread_metadata(event, source), history=history)
+ try:
+ _hyg_model, _hyg_runtime = self._resolve_session_agent_runtime(
+ source=source, session_key=session_key,
+ user_config=hs.data if isinstance(hs.data, dict) else None,
+ )
+ if str(_hyg_runtime.get("api_mode") or "").lower() == "codex_app_server":
+ await self._hmwa_hygiene_codex_compaction(hs, plan, history, session_entry, session_key, _hyg_runtime)
+ elif _hyg_runtime.get("api_key"):
+ # Pass the FULL transcript (tool results included) as the agent loop does: filtering
+ # to user/assistant starved the compressor (tool results are the bulk of context).
+ _hyg_msgs = [m for m in history if m.get("role") in {"user", "assistant", "tool"}]
+ if len(_hyg_msgs) >= 4:
+ await self._hmwa_hygiene_detached_attempt(
+ attempt, hs, plan, history, _hyg_msgs, _hyg_model, _hyg_runtime,
+ source, session_entry, session_key, _quick_key, run_generation,
+ )
+ except HygieneTurnHoldExceeded:
+ # Availability boundary, not a failure — already logged at INFO by the turn-hold handler.
+ # Must not hit the generic "auto-compress failed" warning below: that log is how thinking-model
+ # deployments read as permanently broken (#97963; surfaced by @686f6c61 in PR #99657).
+ pass
+ except Exception as e:
+ logger.warning("Session hygiene auto-compress failed: %s", e)
+ # A landed compression published a NEW transcript on attempt.history: leave it byte-identical.
+ # Anything else (turn-hold, timeout, unwind, codex path) left the FULL uncompressed transcript
+ # there — that is the fail-closed case (#111988).
+ if attempt.history is history:
+ return self._bound_hygiene_payload(history, hs, session_entry)
+ return attempt.history
+
+ @staticmethod
+ def _bound_hygiene_payload(history, hs, session_entry):
+ """``bound_model_input_without_hygiene`` over ``hs.hard_msg_limit``, with one INFO line when the
+ cut is real. Below the limit this is the identity — no allocation, no behaviour change."""
+ from gateway.run_turn import bound_model_input_without_hygiene
+ bounded = bound_model_input_without_hygiene(history, hs.hard_msg_limit)
+ if bounded is not history:
+ logger.info(
+ "Session hygiene did not land for %s: bounding the model payload to %s of %s "
+ "messages (hard limit %s) — the stored transcript is unchanged",
+ session_entry.session_id, len(bounded), len(history), hs.hard_msg_limit,
+ )
+ return bounded
diff --cc gateway/run_turn_persistence.py
index 7ead8ff3608,00000000000..256265d357b
mode 100644,000000..100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@@ -1,583 -1,0 +1,579 @@@
+"""Gateway turn persistence 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.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE
+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.warning_notifications import diagnostic_wake_muted
+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 GatewayTurnPersistenceMixin:
+ async def _hmwa_shape_agent_response(
+ self, agent_result, source, history, session_entry, session_key,
+ _quick_key, run_generation, _run_start_session_id, _platform_name, _msg_start_time,
+ persist_user_display_kind: Optional[str] = None,
+ reply_expected: Optional[bool] = None,
+ ):
+ """Turn the raw agent result into the outbound text: sentinel/silence handling, response
+ logging, resume-pending clear, empty-response normalization, and identity-guarded
+ post-compression session_id propagation. Returns
+ ``(response, _intentional_silence, agent_messages)``."""
+ from gateway.run import (
+ _is_gateway_hidden_reasoning_incomplete_turn, _normalize_empty_agent_response,
+ _sanitize_gateway_final_response, _should_clear_resume_pending_after_turn,
+ )
+ response = agent_result.get("final_response") or ""
+ # Hidden-reasoning-only retry exhaustion: the loop's sentinel text doubles as final_response
+ # and would be delivered verbatim (peer agents would ingest it as a completed turn).
+ if _is_gateway_hidden_reasoning_incomplete_turn(agent_result):
+ response = ""
+ _intentional_silence = self._is_intentional_silence(agent_result, response)
+ # A queued (/queue) chain's TERMINAL turn owns the silence verdict, not the event that
+ # opened the chain: an internal follow-up, or a message not addressed to the bot, may go
+ # silent; any other human one must not.
+ from gateway.response_filters import is_machinery_display_kind, silence_allowed
- from gateway.run_turn import _UNEXPECTED_SILENCE_REPLY
++ from gateway.run_turn import _unexpected_silence_reply
+ _silence_kind = agent_result.get("queued_terminal_display_kind", persist_user_display_kind)
+ _silence_reply_expected = agent_result.get("queued_terminal_reply_expected", reply_expected)
+ if _intentional_silence and not silence_allowed(_silence_kind, _silence_reply_expected):
+ logger.warning(
+ "silence marker rejected on a user turn: platform=%s chat=%s",
+ _platform_name, source.chat_id or "unknown",
+ )
+ _intentional_silence = False
- response = _UNEXPECTED_SILENCE_REPLY
++ response = _unexpected_silence_reply()
+ elif _intentional_silence and not is_machinery_display_kind(_silence_kind):
+ logger.debug(
+ "silence marker suppressed on an unaddressed turn: platform=%s chat=%s",
+ _platform_name, source.chat_id or "unknown",
+ )
+
+ # "(empty)" = the model produced no visible content after exhausting all retries. One
+ # text with the CLI explainer and the desktop (agent/turn_explainers.py) so the user
+ # reads the same words on every surface.
+ if response == "(empty)" and not _intentional_silence:
+ from agent.turn_explainers import EMPTY_RESPONSE_EXPLANATION
+
- _model = str(agent_result.get("model") or "").strip() or "The model"
- response = "⚠️ " + EMPTY_RESPONSE_EXPLANATION.format(model=_model)
++ _model = str(agent_result.get("model") or "").strip() or t("gateway.errors.empty_response_model_label")
++ response = t("gateway.shared.warn_passthrough", error=EMPTY_RESPONSE_EXPLANATION.format(model=_model))
+ agent_messages = agent_result.get("messages", [])
+ logger.info(
+ "response ready: platform=%s chat=%s session=%s time=%.1fs api_calls=%d response=%d chars",
+ _platform_name, source.chat_id or "unknown", session_key or "unknown",
+ time.time() - _msg_start_time, agent_result.get("api_calls", 0), len(response),
+ )
+
+ # Successful turn: clear the consecutive-restart stuck-loop counter and resume_pending (set
+ # by drain-timeout shutdown) so later messages don't get the restart-interruption note.
+ if session_key and _should_clear_resume_pending_after_turn(agent_result):
+ await self._clear_restart_failure_count(session_key)
+ try:
+ await self.async_session_store.clear_resume_pending(session_key)
+ except Exception as _e:
+ logger.debug("clear_resume_pending failed for %s: %s", session_key, _e)
+
+ # Normalize empty responses: surface errors, partial failures, and work-without-text.
+ # Fix for #18765.
+ if not _intentional_silence:
+ response = _normalize_empty_agent_response(agent_result, response, history_len=len(history))
+ response = _sanitize_gateway_final_response(source.platform, response)
+
+ # The agent thread already updated the contextvar; propagate to SessionEntry + _save() only
+ # if the binding still points at the session this run was launched against.
+ if agent_result.get("session_id") and agent_result["session_id"] != session_entry.session_id:
+ if session_entry.session_id == _run_start_session_id:
+ session_entry.session_id = agent_result["session_id"]
+ # The held turn lease follows the rotation (persistence writes to the NEW id).
+ self._rebind_turn_lease(_quick_key, run_generation, session_entry.session_id)
+ await self.async_session_store._save()
+ await self.async_session_store._record_gateway_session_peer(
+ session_entry.session_id, session_key, source,
+ )
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="agent-result-compression",
+ )
+ else:
+ logger.info(
+ "Skipping agent-result session split sync for %s because the session binding "
+ "moved from %s to %s before compression finished",
+ session_key or "?", _run_start_session_id, session_entry.session_id,
+ )
+ return response, _intentional_silence, agent_messages
+
- # reasoning_style → (header line, per-line quote prefix for blank / non-blank lines)
++ # reasoning_style → (header catalog key, per-line quote prefix for blank / non-blank lines)
+ _REASONING_QUOTE_STYLES = {
- "subtext": ("-# 💭 Reasoning", "-# ", "-#"), "blockquote": ("> 💭 **Reasoning:**", "> ", ">")
++ "subtext": ("gateway.reasoning.quote_label_discord", "-# ", "-#"),
++ "blockquote": ("gateway.reasoning.quote_label_md", "> ", ">"),
+ }
+
+ def _hmwa_prepend_reasoning(self, agent_result, response, source, _intentional_silence):
+ """Prepend the last reasoning block when show_reasoning is on for this platform. Mattermost
+ requires an explicit per-platform opt-in (scratch text, not final-answer content)."""
+ from gateway.run import _load_gateway_config, _platform_config_key, _resolve_gateway_display_bool
+ try:
+ _show_reasoning_effective = _resolve_gateway_display_bool(
+ _load_gateway_config(), _platform_config_key(source.platform), "show_reasoning",
+ default=bool(getattr(self, "_show_reasoning", False)), platform=source.platform,
+ require_platform_override_for={Platform.MATTERMOST},
+ )
+ except Exception:
+ _show_reasoning_effective = (
+ False if source.platform == Platform.MATTERMOST else getattr(self, "_show_reasoning", False)
+ )
+ last_reasoning = agent_result.get("last_reasoning")
+ if not (_show_reasoning_effective and response and not _intentional_silence and last_reasoning):
+ return response
+ from gateway.stream_consumer_fences import escape_code_fences_for_display
+ # Collapse long reasoning to keep messages readable
+ lines = last_reasoning.strip().splitlines()
+ if len(lines) > 15:
- display_reasoning = "\n".join(lines[:15]) + f"\n_... ({len(lines) - 15} more lines)_"
++ display_reasoning = "\n".join(lines[:15]) + t("gateway.reasoning.more_lines", count=len(lines) - 15)
+ else:
+ display_reasoning = last_reasoning.strip()
+ # Per-platform render style: Discord defaults to "-# " subtext, others keep the code block.
+ try:
+ from gateway.display_config import resolve_display_setting
+ _reasoning_style = resolve_display_setting(
+ _load_gateway_config(), _platform_config_key(source.platform), "reasoning_style", "code",
+ )
+ except Exception:
+ _reasoning_style = "code"
+ _quote = self._REASONING_QUOTE_STYLES.get(_reasoning_style)
+ if _quote:
- header, prefix, empty = _quote
++ header_key, prefix, empty = _quote
+ _quoted = "\n".join(f"{prefix}{ln}" if ln else empty for ln in display_reasoning.splitlines())
- return f"{header}\n{_quoted}\n\n{response}"
++ return f"{t(header_key)}\n{_quoted}\n\n{response}"
+ # Escape ``` inside reasoning so inner fences don't break the outer code block.
+ display_reasoning = escape_code_fences_for_display(display_reasoning)
- return f"💭 **Reasoning:**\n```\n{display_reasoning}\n```\n\n{response}"
++ return t("gateway.reasoning.block", reasoning=display_reasoning, response=response)
+
+ def _hmwa_runtime_footer_line(self, agent_result, source, _turn_seconds):
+ """Runtime-metadata footer for the FINAL message of the turn; off by default
+ (display.runtime_footer.enabled=false)."""
+ from gateway.run import _load_gateway_config, _platform_config_key, _terminal_scope_cwd
+ try:
+ from gateway.runtime_footer import build_footer_line as _bfl
+ return _bfl(
+ user_config=_load_gateway_config(),
+ platform_key=_platform_config_key(source.platform), model=agent_result.get("model"),
+ context_tokens=agent_result.get("last_prompt_tokens", 0) or 0,
+ context_length=agent_result.get("context_length") or None,
+ cwd=_terminal_scope_cwd(""), turn_seconds=_turn_seconds,
+ requested_model=agent_result.get("requested_model"),
+ served_model=agent_result.get("served_model"),
+ )
+ except Exception as _footer_err:
+ logger.debug("runtime_footer build failed: %s", _footer_err)
+ return ""
+
+ async def _hmwa_post_turn_hooks(self, hook_ctx, agent_result, response):
+ """agent:end hook, process-watcher scheduling, and watch-notification drain."""
+ await self.hooks.emit("agent:end", {
+ **hook_ctx, "response": (response or "")[:500], "model": agent_result.get("model", ""),
+ "provider": agent_result.get("provider", ""),
+ })
+
+ # Pending process watchers (check_interval on background processes)
+ try:
+ from tools.process_registry import process_registry
+ # Detach the batch atomically (reassign, not clear()) so concurrent appends aren't dropped.
+ watchers = process_registry.pending_watchers
+ process_registry.pending_watchers = []
+ for i, watcher in enumerate(watchers):
+ asyncio.create_task(self._run_process_watcher(watcher))
+ if i % 100 == 99:
+ await asyncio.sleep(0)
+ except Exception as e:
+ logger.error("Process watcher setup error: %s", e)
+
+ # Drain watch notifications that arrived during the run; the queue also carries process /
+ # async-delegation completions owned elsewhere — inject only watch-type events.
+ try:
+ from tools.process_registry import process_registry as _pr
+ await self._drain_watch_notifications(_pr.completion_queue)
+ except Exception as e:
+ logger.debug("Watch queue drain error: %s", e)
+
+ # One owner for the boundary copy (agent/turn_failure_copy.py): the core closer in
+ # agent/conversation_loop.py writes the same row on the paths that never reach this layer.
+
+ def _hmwa_add_failed_turn_notice(self, response, notice):
+ """Make failed-turn delivery explicit without replacing the provider-specific guidance."""
+ response = str(response or "").strip()
+ return f"{response}\n\n{notice}" if response else notice
+
+ def _hmwa_failed_turn_notice(self, agent_result):
+ """Choose retry guidance without assuming completed tool effects can be repeated safely."""
+ from gateway.media_repair import _current_turn_messages
+ # Compression during the failed turn can move the slice boundary; the shared helper falls
+ # back to the last user row so tool evidence is not silently dropped.
+ turn_messages = _current_turn_messages(
+ agent_result.get("messages", []) or [], agent_result.get("history_offset", 0),
+ )
+ if any(
+ message.get("role") == "tool"
+ or (message.get("role") == "assistant" and message.get("tool_calls"))
+ for message in turn_messages
+ ):
+ return PARTIAL_FAILED_TURN_NOTICE
+ return FAILED_TURN_NOTICE
+
+ async def _hmwa_close_failed_turn(self, session_id, notice):
+ """Append the gateway-owned assistant boundary iff the durable tail is an open user row.
+
+ The tail, not "did the gateway write the user row", is the key: on the primary path the
+ agent's turn-start flush already persisted the row (so the platform-id dedupe skips the
+ gateway write), and a platform redelivery of an already-closed turn must not stack a
+ second assistant row."""
+ if await self.async_session_store.transcript_tail_role(session_id) != "user":
+ return
+ await self.async_session_store.append_to_transcript(session_id, {
+ "role": "assistant", "content": notice, "timestamp": time.time(), "display_kind": FAILED_TURN_DISPLAY_KIND,
+ })
+
+ def _hmwa_classify_turn_failure(self, agent_result, history, session_entry):
+ """Classify a finished turn for transcript persistence. Returns
+ ``(agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure)``.
+
+ Context-overflow failures must NOT persist the user message (session would grow and
+ reproduce the failure forever); transient failures (429/timeout/5xx) DO."""
+ from gateway.run import _is_gateway_hidden_reasoning_incomplete_turn
+ # Save the full conversation to the transcript, including tool calls. This preserves the complete
+ # agent loop (tool_calls, tool results, intermediate reasoning) so sessions can be resumed with full
+ # context and transcripts are useful for debugging and training data. IMPORTANT: For
+ # context-overflow failures (compression exhausted, generic 400 on large sessions) we must NOT
+ # persist the user's message — doing so would grow the session further and cause the same failure on
+ # the next attempt, an infinite loop. (#1630, #9893) Transient failures (429, timeout, connection
+ # error, provider 5xx) are different: the session is not oversized, and silently dropping the user
+ # message causes severe context loss on retry — the agent forgets what was just asked. Persist the
+ # user turn so the conversation is preserved. (#7100)
+ agent_failed_early = bool(agent_result.get("failed"))
+ hidden_reasoning_incomplete = _is_gateway_hidden_reasoning_incomplete_turn(agent_result)
+ from gateway.run_turn import is_context_overflow_failure_result
+ is_context_overflow_failure = is_context_overflow_failure_result(agent_result, len(history))
+ if is_context_overflow_failure:
+ logger.info(
+ "Skipping transcript persistence for context-overflow "
+ "failure in session %s to prevent session growth loop.", session_entry.session_id,
+ )
+ elif agent_failed_early:
+ logger.info(
+ "Transient agent failure in session %s — persisting user "
+ "message so conversation context is preserved on retry.", session_entry.session_id,
+ )
+ elif hidden_reasoning_incomplete:
+ logger.warning(
+ "Suppressing hidden-reasoning-only incomplete gateway turn for session %s: %s",
+ session_entry.session_id, agent_result.get("error", "processing incomplete"),
+ )
+ return agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure
+
+ async def _hmwa_compression_exhaustion_reset(
+ self, agent_result, response, session_entry, session_key, source,
+ ):
+ """Auto-reset a permanently oversized session so the next message starts fresh instead of
+ replaying the oversized context forever. Never on a lock-contended defer — that is the
+ OPPOSITE case (a concurrent path holds the lock and is shrinking it). Returns
+ ``(response, session_entry)``."""
+ # When compression is exhausted, the session is permanently too large to process. (#9893) Never wipe
+ # the session for that — retry-next-message semantics apply (#69870 lock-skip consumer; salvaged
+ # from #49874).
+ if agent_result.get("compression_deferred"):
+ logger.info(
+ "Compression deferred for session %s — the compression "
+ "lock is held by a concurrent compressor. Keeping the "
+ "session intact; the next message retries normally.",
+ session_entry.session_id if session_entry else "?",
+ )
+ elif agent_result.get("compression_exhausted") and session_entry and session_key:
+ logger.info("Auto-resetting session %s after compression exhaustion.", session_entry.session_id)
+ new_entry = await self.async_session_store.reset_session(session_key)
+ self._evict_cached_agent(session_key)
+ # Conversation boundary: the funnel clears every conversation-scoped per-session dict.
+ self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")
+ if new_entry is not None:
+ # Re-point the Telegram topic binding at the fresh session, or the binding-heal walk
+ # switches the next message back onto the bloated child and re-triggers exhaustion
+ # forever. No-op on non-topic lanes.
+ # Compression rotated session_entry.session_id to the oversized compressed child earlier
+ # this turn (the agent-result sync above), and that _sync also rewrote the (chat_id,
+ # thread_id) -> bloated-child binding. reset_session swaps in a clean, parentless session,
+ # but without re-syncing the binding the next inbound message in this topic gets
+ # switch_session'd back onto the bloated child by the binding-heal walk, reloads the
+ # oversized transcript, and re-triggers compression exhaustion forever (#35809 — regression
+ # of the #9893/#10063 auto-reset).
+ session_entry = new_entry
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-exhausted-reset",
+ )
- response = (response or "") + (
- "\n\n🔄 Session auto-reset — the conversation exceeded the maximum context size and "
- "could not be compressed further. Your next message will start a fresh session."
- )
++ response = (response or "") + t("gateway.session.auto_reset_context_exhausted")
+ return response, session_entry
+
+ @staticmethod
+ def _hmwa_user_transcript_entry(event, prepared, ts):
+ """Transcript row for the inbound user turn (clean text + event time when captured)."""
+ # Transient failure (429/timeout/5xx): persist only the user message so the next message can load a
+ # transcript that reflects what was said. Skip the assistant error text since it's a
+ # gateway-generated hint, not model output. Hidden- reasoning-only incomplete turns follow the same
+ # persistence rule so peer-agent channels don't ingest them as completed assistant turns. (#7100,
+ # #51628)
+ _user_entry = {
+ "role": "user",
+ "content": (
+ prepared.persist_user_message if prepared.persist_user_message is not None
+ else prepared.message_text
+ ),
+ "timestamp": prepared.persist_user_timestamp if prepared.persist_user_timestamp is not None else ts,
+ }
+ if prepared.persist_user_display_kind:
+ _user_entry["display_kind"] = prepared.persist_user_display_kind
+ if prepared.persistence_owner:
+ _user_entry["display_metadata"] = {"gateway_input_owner": prepared.persistence_owner}
+ if getattr(event, "message_id", None):
+ _user_entry["message_id"] = str(event.message_id)
+ return _user_entry
+
+ async def _hmwa_persist_turn_transcript(
+ self, *, event, source, session_entry, session_key, agent_result, agent_messages,
+ prepared, response, agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure,
+ ):
+ """Persist this turn to the transcript (session_meta on first turn, user-only on transient
+ failure, nothing on context overflow), update last_prompt_tokens, and re-baseline the
+ cached agent's message count."""
+ from gateway.run import _resolve_gateway_model
+ ts = time.time() # Unix epoch float — consistent with DB storage
+ store = self.async_session_store
+ sid = session_entry.session_id
+ history = prepared.history
+ # The agent already persisted this turn's rows (codex app-server reports agent_persisted=True
+ # too); skip the DB write. Default = a session DB exists; non-persisting runtimes pass False.
+ # The agent already persisted these messages to SQLite via _flush_messages_to_session_db(), so skip
+ # the DB write here to prevent the duplicate-write bug (#860 / #42039). This holds for the codex
+ # app-server runtime too: although it early-returns and bypasses conversation_loop's per-step
+ # flushes, it flushes its own projected assistant/tool messages before returning and reports
+ # agent_persisted=True (see agent/codex_runtime.py). Reading the flag (default = self._session_db is
+ # not None) keeps the persistence contract explicit and lets any future non-persisting runtime opt
+ # into a gateway-side write by returning False.
+ agent_persisted = agent_result.get("agent_persisted", self._session_db is not None)
+ _user_row = self._hmwa_user_transcript_entry(event, prepared, ts)
+
+ if is_context_overflow_failure:
+ pass # Skip all transcript writes — don't grow a broken session
+ else:
+ if not history and source.platform != Platform.LOCAL:
+ # Fresh session: the tool definitions (as sent in the API request) make the transcript
+ # self-describing. A LOCAL route (one-shot, chat -q, ACP, TUI attach) keeps the classic
+ # in-process CLI's transcript shape: the marker is gateway bookkeeping every local
+ # reader filters out, and the session row already carries model/model_config.
+ await store.append_to_transcript(sid, {
+ "role": "session_meta",
+ "tools": agent_result.get("tools", []) or [],
+ "model": _resolve_gateway_model(),
+ "platform": source.platform.value if source.platform else "",
+ "timestamp": ts,
+ })
+ if agent_failed_early or hidden_reasoning_incomplete:
+ # Transient failure / hidden-reasoning incomplete: persist only the user message (the
+ # assistant error text is a gateway hint, not model output). Dedupe on platform
+ # message_id (Telegram retries after transient failures).
+ if event.message_id and await store.has_platform_message_id(sid, str(event.message_id)):
+ logger.info(
+ "Skipping duplicate user turn (message_id=%s) in session %s",
+ event.message_id, sid,
+ )
+ else:
+ await store.append_to_transcript(sid, _user_row, skip_db=agent_persisted)
+ # Close the failed turn: a user-only tail lets alternation repair merge this request
+ # into an unrelated future message and replay stale side effects (#107070).
+ await self._hmwa_close_failed_turn(sid, self._hmwa_failed_turn_notice(agent_result))
+ else:
+ # Only the NEW messages: history_offset (what the agent saw), not len(history), which
+ # counts session_meta entries stripped before the agent saw them.
+ history_len = agent_result.get("history_offset", len(history))
+ new_messages = agent_messages[history_len:] if len(agent_messages) > history_len else []
+ if not new_messages:
+ # Edge case: fall back to simple user/assistant rows.
+ await store.append_to_transcript(sid, _user_row, skip_db=agent_persisted)
+ if response:
+ await store.append_to_transcript(
+ sid, {"role": "assistant", "content": response, "timestamp": ts},
+ skip_db=agent_persisted,
+ )
+ else:
+ # Attach the inbound platform message_id to the first user entry so platform-level
+ # quote-resolution (e.g. Yuanbao) can find earlier @bot messages by original id.
+ _user_msg_id_attached = False
+ for msg in new_messages:
+ if msg.get("role") == "system":
+ continue # rebuilt each run
+ entry = {**msg, "timestamp": ts}
+ if (
+ not _user_msg_id_attached
+ and msg.get("role") == "user"
+ and event.message_id
+ and "message_id" not in entry
+ ):
+ entry["message_id"] = str(event.message_id)
+ _user_msg_id_attached = True
+ await store.append_to_transcript(sid, entry, skip_db=agent_persisted)
+
+ # The agent persists token counts/model itself; keep only last_prompt_tokens for hygiene.
+ await store.update_session(
+ session_entry.session_key, last_prompt_tokens=agent_result.get("last_prompt_tokens", 0),
+ touch_activity=not bool(getattr(event, "internal", False)),
+ )
+
+ # Re-baseline the cached agent's message_count now that ALL of this turn's writes are done:
+ # the coherence guard snapshots at agent-BUILD time, so our own writes would otherwise
+ # trigger a rebuild next turn (destroying prompt caching).
+ await self._refresh_agent_cache_message_count(session_key, sid)
+
+ async def _hmwa_deliver_turn_response(
+ self, event, source, session_entry, session_key, run_generation,
+ agent_result, agent_messages, response, _footer_line, _intentional_silence,
+ ):
+ """Final delivery decisions: intentional silence, voice reply, streamed-turn media/footer.
+ Returns the text for the adapter to send, or ``None`` when already delivered."""
+ if diagnostic_wake_muted(event):
+ return None
+ # Intentional silence is a delivery decision: the [SILENT] turn stays persisted (alternation).
+ if _intentional_silence:
+ logger.info("Suppressing intentional silence marker for session %s", session_entry.session_id)
+ response = ""
+
+ adapter = self._delivery_adapter_for(source)
+ # Auto voice reply (TTS audio before the text) unless streaming TTS already delivered audio.
+ _streaming_tts_done = adapter is not None and bool(
+ getattr(adapter, "_streaming_tts_turn_completed", lambda *_a, **_k: False)(session_key, run_generation)
+ )
+ if not _streaming_tts_done and self._should_send_voice_reply(
+ event, response, agent_messages, already_sent=bool(agent_result.get("already_sent")),
+ ):
+ await self._send_voice_reply(event, response)
+
+ # Streamed responses still need MEDIA: files delivered (chunks carry the tags verbatim). Never
+ # skip when the agent failed: the error text is new content streaming didn't show.
+ if agent_result.get("already_sent") and not agent_result.get("failed"):
+ # The queued-follow-up lane uploads this response's attachments itself; re-scanning here
+ # would upload every file a second time.
+ if response and adapter and not agent_result.get("media_already_delivered"):
+ await self._deliver_media_from_response(response, event, adapter)
+ # Streaming delivered the body, but the footer was held back (`not already_sent` gate).
+ if _footer_line and adapter:
+ try:
+ await adapter.send(source.chat_id, _footer_line, metadata=self._event_thread_metadata(event, source))
+ except Exception as _e:
+ logger.debug("trailing footer send failed: %s", _e)
+ # Return None so the body isn't sent twice; stash the delivered text on the event for the
+ # /loop and /goal hooks that read the return value.
+ with suppress(Exception):
+ event._streamed_final_response = str(response or "")
+ return None
+
+ return response
+
+ # Chat-side next steps keyed by HTTP status; Hermes commands only (/login is the gateway's own
+ # sign-in, `{relogin}` the profile-aware host equivalent, filled from the turn's agent provider).
++ # Values are catalog keys (``gateway.errors.hint_*``); 401 carries a ``{relogin}`` placeholder.
+ _STATUS_HINTS = {
- 401: (" Your sign-in to the AI model service has expired or the API key is wrong. "
- "Use /login here, or run `{relogin}` on the host."),
- 402: " Your AI model service balance or quota is used up. Top it up on the service's website, or use /model to switch models.",
- 529: " The AI model service is temporarily overloaded. Wait a moment, then use /retry.",
++ 401: "gateway.errors.hint_auth",
++ 402: "gateway.errors.hint_quota",
++ 529: "gateway.errors.hint_overloaded",
+ }
+
+ async def _hmwa_agent_error_reply(self, e, event, source, session_entry, session_key, prepared):
+ """``except Exception`` body of the agent turn: stop typing, log, persist the inbound user
+ turn once, and build the sanitized user-facing error reply."""
+ # Retain Slack thread/workspace routing so a failed turn cannot leave its status visible.
+ await self._hmwa_stop_typing_for_turn(event, source)
+ logger.exception("Agent error in session %s", session_key)
+ status_code = getattr(e, "status_code", None)
+ if status_code in {400, 500} and len(prepared.history) > 50:
+ # Context overflow / payload too large: a deterministic rejection (#107567), and the same
+ # no-grow rule as the persist path (#1630) — nothing is written into an oversized session.
- from gateway.run import _CONTEXT_OVERFLOW_REPLY
- return _CONTEXT_OVERFLOW_REPLY
++ from gateway.run import _context_overflow_reply
++ return _context_overflow_reply()
+ # Replay can coalesce inputs; only this input's durable marker establishes ownership.
+ try:
+ if prepared.message_text is not None and session_entry is not None:
+ _owned = await self.async_session_store.has_input_owner(
+ prepared.persistence_session_id, prepared.persistence_owner,
+ )
+ if not _owned:
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id, self._hmwa_user_transcript_entry(event, prepared, time.time()),
+ )
+ # Tool effects are unknown after an exception.
+ await self._hmwa_close_failed_turn(session_entry.session_id, PARTIAL_FAILED_TURN_NOTICE)
+ except Exception:
+ logger.debug("Failed to persist inbound user message after agent exception", exc_info=True)
+ # Never expose raw exception types/messages to end users (info-leakage risk).
- status_hint = self._STATUS_HINTS.get(status_code, "")
++ _hint_key = self._STATUS_HINTS.get(status_code)
++ status_hint = t(_hint_key) if _hint_key and status_code != 401 else ""
+ if status_code == 401:
+ from agent.turn_failure_copy import relogin_command_hint
+
+ _turn_agent = getattr(self._session_state(session_key).turn, "agent", None)
- status_hint = status_hint.format(relogin=relogin_command_hint(getattr(_turn_agent, "provider", None)))
++ status_hint = t(_hint_key, relogin=relogin_command_hint(getattr(_turn_agent, "provider", None)))
+ elif status_code == 429:
+ # Plan usage limit (resets on a schedule) vs a transient rate limit
+ _err_json = {}
+ with suppress(Exception):
+ _err_json = e.response.json().get("error", {})
+ if not isinstance(_err_json, dict):
+ _err_json = {}
+ _resets_in = _err_json.get("resets_in_seconds")
+ if _err_json.get("type") != "usage_limit_reached":
- status_hint = " You are being rate-limited. Please wait a moment and try again."
++ status_hint = t("gateway.errors.hint_rate_limited")
+ elif _resets_in and _resets_in > 0:
+ import math
- status_hint = f" Your plan's usage limit has been reached. It resets in ~{math.ceil(_resets_in / 3600)}h."
++ status_hint = t("gateway.errors.hint_usage_limit_resets", hours=math.ceil(_resets_in / 3600))
+ else:
- status_hint = " Your plan's usage limit has been reached. Please wait until it resets."
++ status_hint = t("gateway.errors.hint_usage_limit")
+ elif status_code == 400:
- status_hint = " The AI model service rejected the request."
++ status_hint = t("gateway.errors.hint_rejected")
+ return self._hmwa_add_failed_turn_notice(
- f"⚠️ Something went wrong and I couldn't finish this reply.{status_hint}\n"
- "Use /retry to try again, or /new to start a fresh conversation. "
- "Technical details are in the gateway log (`hermes logs`).",
- PARTIAL_FAILED_TURN_NOTICE,
++ t("gateway.errors.generic_failed_with_hint", hint=status_hint), PARTIAL_FAILED_TURN_NOTICE,
+ )
+
+ def _hmwa_discard_stale_result(self, source, _quick_key, run_generation):
+ """A newer run generation superseded this turn: drop its deferred post-delivery callback."""
+ logger.info(
+ "Discarding stale agent result for %s — generation %d is no longer current",
+ _quick_key or "?", run_generation,
+ )
+ self._pop_post_delivery_callback(self._delivery_adapter_for(source), _quick_key, run_generation)
diff --cc gateway/run_turn_prepare.py
index 5fc6402dd28,00000000000..ea59c6da75d
mode 100644,000000..100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@@ -1,714 -1,0 +1,712 @@@
+"""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
+ # Every exit path starts clean: a stale notice must never attach to another session's next
+ # turn (#74349). Set again below only when THIS resolution fell back.
+ self._pre_agent_fallback_notice = None
+ policy = policy_for_source(self, source) if source is not None else None
+ if policy is not None:
+ 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')
+ # Same resolution-time walker the in-process one-shot used (#81209): an AuthError from
+ # the frozen primary (expired token, Portal down, exhausted pool) tries the route's own
+ # ``fallback_providers`` before the turn is refused.
+ from hermes_cli.runtime_provider import resolve_runtime_with_fallback
+ # Only a launch-supplied URL is explicit (classic one-shot parity): config's own
+ # ``model.base_url`` is resolved by the provider chain, which keeps the credential pool
+ # an explicit URL would drop (no pool = no refresh/rotation on a 401).
+ runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=policy.provider,
+ explicit_api_key=key, explicit_base_url=json.loads(policy.request_json).get('base_url'),
+ target_model=policy.model)
+ if fallback_entry is not None:
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ self._pre_agent_fallback_notice = pre_agent_fallback_notice(
+ policy.provider or '', policy.model or '',
+ runtime.get('provider') or fallback_entry.get('provider') or 'unknown',
+ fallback_entry.get('model') or 'default')
+ return fallback_entry['model'], _runtime_agent_kwargs(runtime)
+ return policy.model, _runtime_agent_kwargs(runtime)
+ skey = self._resolve_session_key_or_none(source, session_key)
+ 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 (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,
+ )
+ elif logger.isEnabledFor(logging.DEBUG):
+ # The override_keys scan walks every session; only pay for it when DEBUG is on.
+ 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, 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 agent.fast_mode import STATIC_TIERS
+ 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":
++ tier = getattr(self, "_service_tier", None)
++ if tier not in STATIC_TIERS:
+ # 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"],
++ route["model"], provider=runtime["provider"], base_url=runtime["base_url"], tier=tier,
+ )
+ 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"
- )
++ notice = t("gateway.session.auto_reset_notice")
+ 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):
++ async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes, internal=False):
+ """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:
++ from gateway.run import _gateway_config_home, _home_target_env_var, _load_gateway_config
++ if history or internal: # internal = plugin/system turn: no human made first contact
+ return
+ # LOCAL sessions (one-shot, chat -q, ACP, TUI attach) are the classic in-process CLI's
+ # surfaces: it never appended this note, and mark_seen would rewrite config.yaml under
+ # an ordinary launch that promises to leave the profile's files untouched.
- if source.platform == Platform.LOCAL:
- return
- if not await self.async_session_store.has_any_sessions():
++ human_platform = bool(source.platform) and source.platform not in (Platform.LOCAL, Platform.WEBHOOK)
++ if human_platform and source.chat_type == "dm" and not await self.async_session_store.has_any_sessions():
+ # Same branch logic as the TUI (profile-build offer once when "ask", else plain intro);
+ # first_contact_turn_note already falls back to the plain intro on error.
+ from agent.onboarding import first_contact_turn_note
+ note = first_contact_turn_note(
- _load_gateway_config(), _hermes_home / "config.yaml",
++ _load_gateway_config(), _gateway_config_home() / "config.yaml",
+ session_history_empty=True, install_has_prior_sessions=False,
+ )
+ if note:
+ turn_sidecar_notes.append(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):
++ if not human_platform:
+ 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.",
++ source, t("gateway.notify.no_home_channel", platform=platform_name.title(), sethome_cmd=sethome_cmd),
+ )
+
+ 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
++ title_user_message: 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.
+ # A LOCAL session (CLI one-shot, ACP, cron run-now, TUI attach) is the operator's own machine:
+ # the messaging block ("Source: Local", connected platforms, cron delivery targets) was never
+ # part of the classic in-process prompt, and the TUI gateway still builds that prompt in-process.
+ # Rendering it here would make every surface hop of one durable session a system-prompt
+ # (and prompt-cache) break.
++ if source.platform != Platform.LOCAL and event.internal and session_key:
++ await self._rehydrate_prompt_pins(session_key, session_entry.session_id)
+ context_prompt = "" if source.platform == Platform.LOCAL else \
+ self._pinned_session_context_prompt(context, _redact_pii, session_key, internal=event.internal)
+
+ # 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)
+
++ # Keep human text separate from skills, sender metadata, and other model context.
++ # With no text (e.g. voice-only), retain the existing enriched-message title fallback.
++ title_user_message = event.text or None
++
+ # 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
++ return t("gateway.errors.history_unavailable"), _session_env_tokens
+
- await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes)
++ await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes, internal=event.internal)
+
+ # 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,
++ title_user_message=title_user_message,
+ ), _session_env_tokens
diff --cc gateway/run_turn_progress.py
index a4ef6682ae2,00000000000..cd49cbc7f57
mode 100644,000000..100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@@ -1,892 -1,0 +1,897 @@@
+"""Extracted gateway run_turn_progress responsibility; consumed by TurnRunner."""
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import json
+import logging
+import queue
+import re
+import threading
+import time
+from contextlib import suppress
+from datetime import datetime
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
+
++from agent.i18n import t
+from agent.interrupt_compat import _accepts_keyword
+from agent.replay_cleanup import strip_stale_dangerous_confirmations
+from gateway.config import Platform
+from gateway.media_repair import repair_explicit_computer_use_media_paths
+from gateway.platforms.base import BasePlatformAdapter
+from gateway.turn_context import TurnContext
+from hermes_cli.config import cfg_get
+from utils import is_truthy_value
+
+if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
+ from gateway.run import GatewayRunner # noqa: F401
+
+# Log-record parity with the origin module.
+logger = logging.getLogger("gateway.run")
+
+
+def _tool_lifecycle_payload(call_id, tool_name, args) -> dict:
+ """The ``ToolStartPayload`` contract every client reads (``tool_id``/``name``/``context``),
+ plus the ``tool_call_id``/``tool_name`` the gateway's own consumers were built on."""
+ from agent.display import build_tool_preview, tool_labels_for_call
+ name = str(tool_name or "tool")
+ args = args if isinstance(args, dict) else {}
+ payload = {"tool_id": str(call_id or ""), "name": name, "context": build_tool_preview(name, args, max_len=80) or "",
+ "tool_call_id": str(call_id or ""), "tool_name": name, "args": args}
+ if labels := [label.as_payload() for label in tool_labels_for_call(name, args)]:
+ payload["labels"] = labels
+ return payload
+
+
+class GatewayTurnProgressMixin:
+ # ── shared thread→loop plumbing ─────────────────────────────────────────────────────────
+
+ def _schedule(self, coro, log_message: str, loop=None):
+ """Hop a coroutine from the agent's sync worker thread onto the gateway loop."""
+ from gateway.run import safe_schedule_threadsafe
+ return safe_schedule_threadsafe(
+ coro, self._ctx._loop_for_step if loop is None else loop, logger=logger, log_message=log_message,
+ )
+
+ def _agent_interrupted(self) -> bool:
+ """True once the user sent `stop` (agent_holder[0] is the shared agent handle)."""
+ try:
+ agent = self._ctx.agent_holder[0] if self._ctx.agent_holder else None
+ return bool(agent is not None and getattr(agent, "is_interrupted", False))
+ except Exception:
+ return False
+
+ def _stream_consumer(self):
+ holder = self._ctx.stream_consumer_holder
+ return holder[0] if holder else None
+
+ def _drain_progress_queue(self) -> None:
+ q = self._ctx.progress_queue
+ with suppress(Exception):
+ while not q.empty():
+ q.get_nowait()
+
+ def _track_progress_result(self, result) -> None:
+ """Remember a delivered progress/status message id for end-of-turn cleanup."""
+ ctx = self._ctx
+ if ctx._cleanup_progress and getattr(result, "success", False) and getattr(result, "message_id", None):
+ ctx._cleanup_msg_ids.append(str(result.message_id))
+
+ def _track_future_cleanup_id(self, fut) -> None:
+ try:
+ res = fut.result()
+ except Exception:
+ return
+ self._track_progress_result(res)
+
+ # ── progress_callback (agent thread → progress queue) ───────────────────────────────────
+
+ def progress_callback(self, event_type: str, tool_name: str = None, preview: str = None, args: dict = None, **kwargs):
+ """Callback invoked by agent on tool lifecycle events."""
+ ctx = self._ctx
+ # Failed subagent → one clean user-facing notice, handled FIRST, before every progress-queue
+ # gate: platforms with tool_progress off must still hear about a dead delegation.
+ if event_type == "subagent.complete":
+ self._progress_subagent_notice(preview, kwargs)
+ return
+ self._progress_live_status(event_type, tool_name, args)
+ # "log" mode: append tool.started lines to the log queue, silent in chat. Handled before
+ # the progress_queue guard because log mode runs without a chat progress queue.
+ if ctx.log_queue is not None and event_type == "tool.started" and tool_name and tool_name != "_thinking":
+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ preview_str = f' "{preview}"' if preview else ""
+ ctx.log_queue.put(f"{ts} {tool_name}:{preview_str}".rstrip())
+ if not ctx.progress_queue or not ctx._run_still_current():
+ return
+ if event_type == "tool.completed" and not ctx.long_tool_hint_fired[0]:
+ self._progress_onboarding_hint(kwargs)
+ return
+ # "_thinking" is assistant scratch text between tool calls, never ordinary tool progress:
+ # only relayed when the platform explicitly opted into thinking_progress.
+ if event_type == "_thinking" or tool_name == "_thinking":
+ thinking_text = (preview if tool_name == "_thinking" else tool_name) if ctx._thinking_enabled else None
+ if thinking_text:
- ctx.progress_queue.put(f"💬 {thinking_text}")
++ ctx.progress_queue.put(t("gateway.progress.thinking_prefix", text=thinking_text))
+ return
+ # Native task cards consume the ID-bearing tool_start/tool_complete callbacks instead;
+ # name-correlated text events would duplicate cards and mispair concurrent same-tool calls.
+ if ctx._native_slack_task_cards and event_type in {"tool.started", "tool.completed"}:
+ return
+ # tool_progress off → only _thinking passes (above). Only tool.started renders. clarify:
+ # send_clarify IS the user-facing rendering (a bubble would duplicate it, and verbose mode
+ # would dump the raw args JSON right under the prompt). Post-`stop`: N parallel tool calls
+ # fire N tool.started events before the interrupt check, so a late stop must not render them.
+ if (
+ not ctx.tool_progress_enabled
+ or event_type != "tool.started"
+ # The adapter's send_clarify IS the user-facing rendering (interactive buttons or the
+ # numbered-text fallback), so a progress bubble is pure duplication — and in verbose mode it
- # dumps the raw tool-call args JSON ({"question": ..., "choices": [...]}) into the chat. Because
++ # dumps the raw tool-call args JSON into the chat. Because
+ # the progress queue drains on a background task, that raw JSON typically lands right underneath
+ # the rendered prompt (#52374).
+ or tool_name == "clarify"
+ or self._agent_interrupted()
+ ):
+ return
+ # "new" mode: only report when tool changes
+ if ctx.progress_mode == "new" and tool_name == ctx.last_tool[0]:
+ return
+ ctx.last_tool[0] = tool_name
+ msg = self._progress_build_message(tool_name, preview, args)
+ if msg is not None:
+ self._progress_emit(msg)
+
+ def _progress_subagent_notice(self, preview, kwargs: dict) -> None:
+ """Only terminal failure statuses render (same notice rail as credit warnings)."""
+ ctx = self._ctx
+ from gateway.warning_notifications import render_notification
+ status = kwargs.get("status")
+ try:
+ from tools.delegate_tool import SUBAGENT_FAILURE_STATUSES, format_subagent_failure_line
+ if status in SUBAGENT_FAILURE_STATUSES and ctx._run_still_current():
+ line = format_subagent_failure_line(
+ kwargs.get("goal"), status, error=kwargs.get("summary") or preview,
+ duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),
+ )
+ render_notification(
+ lambda: self._schedule(self._runner._deliver_platform_notice(ctx.source, line), "subagent failure notice scheduling error"),
+ platform=ctx.source.platform, user_config=ctx.user_config)
+ except Exception:
+ logger.debug("subagent failure notice failed", exc_info=True)
+
+ def _progress_live_status(self, event_type: str, tool_name, args) -> None:
+ """Live status line (Slack assistant status): stash the tool phrase on the adapter; the
+ _keep_typing refresh renders it. Plain dict write, safe from the sync worker thread."""
+ ctx = self._ctx
+ adapter = ctx._live_status_adapter
+ if adapter is None or ctx._live_status_mode == "off" or tool_name == "_thinking":
+ return
+ try:
+ if event_type == "tool.started" and tool_name and ctx._run_still_current():
+ from agent.display import build_status_phrase
+ adapter.set_status_text(ctx.source.chat_id, build_status_phrase(tool_name, args if ctx._live_status_mode == "full" else None))
+ elif event_type == "tool.completed":
+ # Between tools the model is genuinely "thinking" again — revert to the static default.
+ adapter.set_status_text(ctx.source.chat_id, None)
+ except Exception as err:
+ logger.debug("live status update failed: %s", err)
+
+ def _progress_onboarding_hint(self, kwargs: dict) -> None:
+ """First-touch onboarding: the first time a tool exceeds _LONG_TOOL_THRESHOLD_S while
+ streaming every tool (progress_mode == "all"), append a one-time /verbose hint."""
+ from gateway.run import _hermes_home, _load_gateway_config
+ ctx = self._ctx
+ try:
+ if (kwargs.get("duration") or 0) >= ctx._LONG_TOOL_THRESHOLD_S and ctx.progress_mode == "all":
+ from agent.onboarding import TOOL_PROGRESS_FLAG, is_seen, mark_seen, tool_progress_hint_gateway
+ cfg = _load_gateway_config()
+ gate_on = is_truthy_value(cfg_get(cfg, "display", "tool_progress_command"), default=False)
+ if gate_on and not is_seen(cfg, TOOL_PROGRESS_FLAG):
+ ctx.long_tool_hint_fired[0] = True
+ ctx.progress_queue.put(tool_progress_hint_gateway())
+ mark_seen(_hermes_home / "config.yaml", TOOL_PROGRESS_FLAG)
+ except Exception as err:
+ logger.debug("tool-progress onboarding hint failed: %s", err)
+
+ @staticmethod
+ def _preview_cap() -> int:
+ """tool_preview_length (default 40): the one-line preview budget for "all"/"new" modes."""
+ from agent.display import get_tool_preview_max_len
+ pl = get_tool_preview_max_len()
+ return pl if pl > 0 else 40
+
+ def _progress_terminal_blocks(self, adapter, tool_name, args, emoji):
+ """(full, short) fenced blocks for a terminal command on markdown platforms, else (None, None).
+
+ No language tag: Slack mrkdwn renders it as a literal first code line. Verbose shows the FULL
+ command; "all"/"new" truncate to one line capped at ``tool_preview_length``. Consecutive
+ terminal calls drop the repeated header so back-to-back commands render as adjacent blocks.
+ """
+ if not (
+ getattr(adapter, "supports_code_blocks", False) and tool_name == "terminal" and isinstance(args, dict)
+ and isinstance(args.get("command"), str) and args["command"].strip()
+ ):
+ return None, None
+ cmd_full = args["command"].rstrip()
- header = "" if self._ctx.last_was_terminal_block[0] else f"{emoji} {tool_name}\n"
++ header = "" if self._ctx.last_was_terminal_block[0] else t("gateway.progress.tool_head", emoji=emoji, tool=tool_name) + "\n"
+ cap = self._preview_cap()
+ lines = cmd_full.splitlines()
+ cmd_short = lines[0] if lines else cmd_full
+ if len(cmd_short) > cap:
+ cmd_short = cmd_short[:cap - 3] + "..."
+ elif len(lines) > 1:
+ cmd_short += " ..."
+ return f"{header}```\n{cmd_full}\n```", f"{header}```\n{cmd_short}\n```"
+
+ def _progress_build_message(self, tool_name, preview, args) -> Optional[str]:
+ """Render the progress line. Verbose mode queues directly (no dedup) and returns None."""
+ ctx = self._ctx
+ from agent.display import get_tool_emoji
+ emoji = get_tool_emoji(tool_name, default="⚙️")
+ try:
+ adapter = self._runner._delivery_adapter_for(ctx.source)
+ except Exception:
+ adapter = None
+ code_full, code_short = self._progress_terminal_blocks(adapter, tool_name, args, emoji)
+ verbose = ctx.progress_mode == "verbose"
+ code = code_full if verbose else code_short
+ ctx.last_was_terminal_block[0] = code is not None
+ if verbose:
+ if code is None and args:
+ from agent.display import get_tool_preview_max_len
+ pl = get_tool_preview_max_len()
+ args_str = json.dumps(args, ensure_ascii=False, default=str)
+ # tool_preview_length 0 (default) = no truncation in verbose mode; the user asked
+ # for full detail and platform message-length limits handle the rest.
+ if pl > 0 and len(args_str) > pl:
+ args_str = args_str[:pl - 3] + "..."
- code = f"{emoji} {tool_name}({list(args.keys())})\n{args_str}"
++ code = t("gateway.progress.tool_verbose", emoji=emoji, tool=tool_name, keys=list(args.keys()), args=args_str)
+ elif code is None:
- code = f"{emoji} {tool_name}: \"{preview}\"" if preview else f"{emoji} {tool_name}..."
++ code = (t("gateway.progress.tool_preview", emoji=emoji, tool=tool_name, preview=preview) if preview
++ else t("gateway.progress.tool_pending", emoji=emoji, tool=tool_name))
+ ctx.progress_queue.put(code)
+ return None
+ if code is not None:
+ return code
+ if not preview:
- return f"{emoji} {tool_name}..."
++ return t("gateway.progress.tool_pending", emoji=emoji, tool=tool_name)
+ from agent.display import get_tool_verb, prepare_tool_preview, tool_verb_connector, verb_drops_preview
+ prepared = prepare_tool_preview(tool_name, args, fallback=preview, max_len=self._preview_cap())
+ preview = adapter.format_tool_preview(prepared) if adapter is not None else prepared.text
+ # Friendly labels: human-phrased line for built-in tools ("🔍 Searching the web for ...")
+ # by prefixing the verb onto the computed preview, so the command/url/query is kept.
+ verb = get_tool_verb(tool_name)
+ if not verb:
- return f"{emoji} {tool_name}: \"{preview}\""
++ return t("gateway.progress.tool_preview", emoji=emoji, tool=tool_name, preview=preview)
+ return f"{emoji} {verb}" if verb_drops_preview(tool_name) else f"{emoji} {verb}{tool_verb_connector(tool_name)}{preview}"
+
+ def _progress_emit(self, msg: str) -> None:
+ """Dedup consecutive identical lines (execute_code boilerplate), then route to the native
+ stream bubble when the consumer accepts tool progress, else the progress queue."""
+ ctx = self._ctx
+ sc = self._stream_consumer()
+ native = sc is not None and getattr(sc, "accepts_tool_progress", False)
+ if msg == ctx.last_progress_msg[0]:
+ ctx.repeat_count[0] += 1
+ if native:
+ sc.on_tool_progress(f"{msg} (×{ctx.repeat_count[0] + 1})")
+ else:
+ ctx.progress_queue.put(("__dedup__", msg, ctx.repeat_count[0]))
+ return
+ ctx.last_progress_msg[0], ctx.repeat_count[0] = msg, 0
+ if native:
+ sc.on_tool_progress(msg)
+ else:
+ ctx.progress_queue.put(msg)
+
+ # ── Slack-native task cards (progress-queue drain) ──────────────────────────────────────
+
+ @dataclasses.dataclass
+ class _TaskCardState:
+ """Task-card rail state for ``_send_native_task_card_progress``."""
+ adapter: Any
+ tasks: Dict[str, Dict[str, str]] = dataclasses.field(default_factory=dict)
+ task_order: List[str] = dataclasses.field(default_factory=list)
+ fallback_msg_id: Optional[str] = None
+ native_failed: bool = False
+ # TERMINAL for the turn, distinct from native_failed: no later publication
+ # in this turn may deliver task text through the native lane OR the text
+ # fallback. Two causes, both properties of the destination rather than of
+ # one attempt: the connector's egress guard refused the chat, or the chat
+ # cannot host a card (no thread anchor). Declared rather than set
+ # dynamically so the state is visible where it lives.
+ publication_suppressed: bool = False
+ anonymous_seq: int = 0
+
+ @staticmethod
+ def _compact(value: Any, limit: int = 120) -> str:
+ text = re.sub(r"\s+", " ", str(value or "")).strip()
+ return text if len(text) <= limit else text[: limit - 3].rstrip() + "..."
+
+ def visible_tasks(self) -> List[Dict[str, str]]:
+ return [self.tasks[task_id] for task_id in self.task_order[-8:]]
+
+ def fallback_text(self) -> str:
- labels = {"in_progress": "running", "complete": "complete", "error": "error"}
- lines = [f"- {t['title']} - {labels.get(t['status'], t['status'])}" for t in self.visible_tasks()]
- return "Hermes is working\n" + "\n".join(lines)
++ labels = {"in_progress": t("gateway.progress.task_status_running"),
++ "complete": t("gateway.progress.task_status_complete"),
++ "error": t("gateway.progress.task_status_error")}
++ lines = [t("gateway.progress.task_line", title=task["title"], status=labels.get(task["status"], task["status"]))
++ for task in self.visible_tasks()]
++ return t("gateway.progress.task_card_title") + "\n" + "\n".join(lines)
+
+ def _upsert(self, call_id: str, title: str) -> Dict[str, str]:
+ if call_id not in self.tasks:
+ self.task_order.append(call_id)
+ self.tasks[call_id] = {"id": call_id, "title": self._compact(title), "status": "in_progress"}
+ return self.tasks[call_id]
+
+ def apply_event(self, raw: Any) -> bool:
+ event_type = raw.get("type") if isinstance(raw, dict) else None
+ if event_type not in {"tool.started", "tool.completed"}:
+ return False
+ call_id = str(raw.get("tool_call_id") or "")
+ if not call_id:
+ self.anonymous_seq += 1
+ call_id = f"anonymous_{self.anonymous_seq}"
+ tool_name = str(raw.get("tool_name") or "tool")
+ if event_type == "tool.started":
+ preview = self._compact(raw.get("preview"), 64)
+ self._upsert(call_id, f"{tool_name} - {preview}" if preview else tool_name)
+ return True
+ # Completion-only events are rare but valid on some runtimes; keep their real ID instead
+ # of guessing a same-name pending call.
+ task = self.tasks.get(call_id) or self._upsert(call_id, tool_name)
+ task["status"] = "error" if raw.get("is_error") else "complete"
+ return True
+
+ async def _task_card_send_or_edit_fallback(self, st) -> None:
+ ctx = self._ctx
+ text = st.fallback_text()
+ from gateway.relay.egress import declined_send
+
+ if st.publication_suppressed:
+ return
+ if st.fallback_msg_id:
+ result = await st.adapter.edit_message(
+ chat_id=ctx.source.chat_id, message_id=st.fallback_msg_id, content=text, metadata=ctx._progress_metadata,
+ )
+ if getattr(result, "success", False):
+ return
+ # P5(b): R5-4 made a declined native CARD terminal but left this
+ # editable-text fallback: a declined edit fell through to
+ # _send_progress_text and re-sent the same task text to the refused
+ # chat. The decline must set the terminal state here too.
+ if declined_send(result):
+ logger.warning(
+ "Task-card fallback edit DECLINED by the connector's egress "
+ "guard; suppressing progress delivery for the rest of this "
+ "turn (the destination is not approved)"
+ )
+ st.publication_suppressed = True
+ return
+ result = await self._send_progress_text(st, text)
+ if getattr(result, "success", False) and getattr(result, "message_id", None):
+ st.fallback_msg_id = str(result.message_id)
+
+ async def _task_card_publish(self, st) -> None:
+ ctx = self._ctx
+ if not st.tasks:
+ return
+ if st.publication_suppressed:
+ # Publication was suppressed earlier in the turn (egress refusal or a chat
+ # that cannot host a card); every later publication would re-deliver the
+ # same task text there.
+ return
+ # Resolve eligibility in the owning adapter BEFORE transport I/O: a first
+ # timeout/disconnect must not turn an un-cardable chat into text fallback.
+ # Optional for older adapters; only an explicit False refuses publication.
+ destination_supported = getattr(st.adapter, "native_task_card_destination_supported", None)
+ if callable(destination_supported) and destination_supported(
+ ctx.source.chat_id, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,
+ ) is False:
+ self._task_card_uncardable_destination(st)
+ if st.publication_suppressed:
+ return
+ if not st.native_failed:
+ result = await st.adapter.send_native_task_card_progress(
- chat_id=ctx.source.chat_id, tasks=st.visible_tasks(), title="Hermes is working",
++ chat_id=ctx.source.chat_id, tasks=st.visible_tasks(), title=t("gateway.progress.task_card_title"),
+ reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata, fallback_text=st.fallback_text(),
+ )
+ if getattr(result, "success", False):
+ return
+ # P5(b): an AUTHORIZATION decline is not a broken card lane. The
+ # fallback below sends the same task text to the same chat, which
+ # turns a refused card into delivered plain text. Stop the lane
+ # without re-delivering; the refusal is already logged.
+ from gateway.relay.egress import declined_send
+
+ if declined_send(result):
+ # TERMINAL, and stored SEPARATELY from native_failed. Reusing
+ # native_failed suppressed exactly ONE update: the next progress
+ # event skipped this branch (the lane is already "failed") and
+ # went straight to the text fallback. A refusal does not expire
+ # after one tick.
+ st.publication_suppressed = True
+ st.native_failed = True
+ logger.warning(
+ "Slack native task-card progress DECLINED by the connector's "
+ "egress guard — suppressing the text fallback for the rest "
+ "of this turn (the destination is not approved)"
+ )
+ return
+ st.native_failed = True
+ from gateway.run_turn_runner import _CARD_DESTINATION_REFUSALS
+ if getattr(result, "error", None) in _CARD_DESTINATION_REFUSALS:
+ self._task_card_uncardable_destination(st, getattr(result, "error", "unknown error"))
+ if st.publication_suppressed:
+ return
+ else:
+ logger.warning(
+ "Slack native task-card progress failed; falling back "
+ "to an editable text update: %s", getattr(result, "error", "unknown error"),
+ )
+ # Once the native rail fails, every later lifecycle event edits the same fallback message.
+ await self._task_card_send_or_edit_fallback(st)
+
+ def _task_card_uncardable_destination(self, st, reason: str = "no thread anchor") -> None:
+ """The chat cannot host a card (flat DM: no thread anchor) — a property of the destination,
+ not a transient outage. The text fallback exists to keep a WORKING card lane live through a
+ transient failure, not to invent text bubbles the operator never asked for: with Slack's tier
+ default (``tool_progress: off``) the lane goes silent for the turn. An operator who WROTE
+ ``new``/``all`` asked for text progress, so the editable fallback carries it instead."""
+ if self._ctx.tool_progress_enabled:
+ st.native_failed = True
+ logger.info(
+ "Slack native task cards are unsupported for this destination (%s); "
+ "tool progress continues as an editable text update", reason,
+ )
+ return
+ st.publication_suppressed = True
+ logger.info(
+ "Slack native task cards are unsupported for this destination (%s); "
+ "tool progress stays off for this turn", reason,
+ )
+
+ def _task_card_drain(self, st) -> bool:
+ changed = False
+ try:
+ while True:
+ changed = st.apply_event(self._ctx.progress_queue.get_nowait()) or changed
+ except queue.Empty:
+ pass
+ except Exception:
+ logger.debug("Slack native progress queue drain failed", exc_info=True)
+ return changed
+
+ async def _send_native_task_card_progress(self, adapter) -> None:
+ """Drain progress into native cards; supported destinations retain editable fallback.
+ Unsupported destinations and egress refusals suppress publication, never finalization.
+
+ See #29483.
+ """
+ ctx = self._ctx
+ st = self._TaskCardState(adapter)
+ try:
+ while ctx._run_still_current():
+ try:
+ raw = ctx.progress_queue.get_nowait()
+ except queue.Empty:
+ await asyncio.sleep(0.1)
+ continue
+ if not self._agent_interrupted() and st.apply_event(raw):
+ await self._task_card_publish(st)
+ except asyncio.CancelledError:
+ if self._task_card_drain(st) and ctx._run_still_current() and not self._agent_interrupted():
+ await self._task_card_publish(st)
+ finally:
+ if hasattr(adapter, "stop_native_task_card_progress"):
+ # Best-effort on the turn-cleanup path: an escaping transport exception would skip
+ # final-delivery logic (cleanup awaits catch only CancelledError).
+ try:
+ await adapter.stop_native_task_card_progress(
+ ctx.source.chat_id, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.debug("task-card stop failed during turn cleanup", exc_info=True)
+
+ # ── editable progress bubbles (progress-queue drain) ────────────────────────────────────
+
+ @dataclasses.dataclass
+ class _ProgressEditState:
+ """Mutable editable-bubble state shared by ``send_progress_messages`` and its helpers."""
+ adapter: Any
+ progress_lines: list
+ progress_msg_id: Any
+ can_edit: bool
+ _progress_len_fn: Any
+ _PROGRESS_TEXT_LIMIT: int
+ _edit_accepts_metadata: bool
+
+ def _progress_edit_state(self, adapter) -> "TurnRunner._ProgressEditState":
+ ctx = self._ctx
+ len_fn = adapter.message_len_fn if isinstance(adapter, BasePlatformAdapter) else len
+ try:
+ raw_limit = int(getattr(adapter, "MAX_MESSAGE_LENGTH", 4000) or 4000)
+ except Exception:
+ raw_limit = 4000
+ # Per-chat resolution (relay adapter fronting N platforms): cap and length unit follow the
+ # chat's underlying platform; native adapters return their scalar/property unchanged.
+ if isinstance(adapter, BasePlatformAdapter):
+ with suppress(Exception):
+ raw_limit = int(adapter.max_message_length_for_chat(ctx.source.chat_id) or 4000)
+ len_fn = adapter.message_len_fn_for_chat(ctx.source.chat_id)
+ return self._ProgressEditState(
+ adapter=adapter, progress_lines=[], progress_msg_id=None,
+ # "separate" = one message per tool (pre-v0.9 behavior)
+ can_edit=ctx.progress_grouping != "separate",
+ _progress_len_fn=len_fn,
+ # Leave room for platform quirks / formatting; tiny test adapters keep a usable limit.
+ _PROGRESS_TEXT_LIMIT=max(1, raw_limit - (64 if raw_limit > 128 else 0)),
+ # Overflow edits pass metadata (Telegram topic/thread routing) only when edit_message takes it.
+ _edit_accepts_metadata=bool(ctx._progress_metadata) and _accepts_keyword(adapter.edit_message, "metadata"),
+ )
+
+ async def _edit_progress_message(self, st, message_id: str, content: str):
+ ctx = self._ctx
+ kwargs = {"chat_id": ctx.source.chat_id, "message_id": message_id, "content": content}
+ if getattr(st.adapter, "REQUIRES_EDIT_FINALIZE", False):
+ kwargs["finalize"] = True
+ if st._edit_accepts_metadata:
+ kwargs["metadata"] = ctx._progress_metadata
+ return await st.adapter.edit_message(**kwargs)
+
+ @staticmethod
+ def _progress_text(lines: list) -> str:
+ return "\n".join(str(line) for line in lines)
+
+ def _split_progress_groups(self, st, lines: list) -> list[list]:
+ """Partition progress lines into platform-sized editable bubbles."""
+ groups: list[list] = []
+ current: list = []
+ for line in lines:
+ candidate = current + [line]
+ if current and st._progress_len_fn(self._progress_text(candidate)) > st._PROGRESS_TEXT_LIMIT:
+ groups.append(current)
+ candidate = [line]
+ current = candidate
+ return groups + ([current] if current else [])
+
+ async def _send_progress_text(self, st, text: str):
+ ctx = self._ctx
+ result = await st.adapter.send(
+ chat_id=ctx.source.chat_id, content=text, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,
+ )
+ self._track_progress_result(result)
+ return result
+
+ async def _roll_progress_overflow_if_needed(self, st) -> bool:
+ """Start fresh editable progress bubbles before a bubble exceeds limit.
+
+ Returns True when it delivered/split the buffer or a transient edit failure left it
+ intact for retry — either way the caller skips the normal send/edit path this tick.
+ """
+ if not st.progress_lines or not st.can_edit:
+ return False
+ groups = self._split_progress_groups(st, st.progress_lines)
+ if len(groups) <= 1:
+ return False
+ if st.progress_msg_id is not None:
+ result = await self._edit_progress_message(st, st.progress_msg_id, self._progress_text(groups[0]))
+ if not result.success:
+ if getattr(result, "retryable", False):
+ logger.debug("[%s] Transient overflow edit failure — keeping can_edit=True", st.adapter.name)
+ return True
+ st.can_edit = False
+ # Fall back to the existing non-edit behavior.
+ return False
+ groups = groups[1:]
+ for group in groups:
+ result = await self._send_progress_text(st, self._progress_text(group))
+ if result.success and result.message_id:
+ st.progress_msg_id = result.message_id
+ # The newest continuation is the only mutable bubble: keep just its lines so later
+ # edits update it instead of replaying the full transcript into new messages.
+ st.progress_lines = groups[-1]
+ return True
+
+ @staticmethod
+ def _is_reset_marker(raw) -> bool:
+ return isinstance(raw, tuple) and len(raw) >= 1 and raw[0] == "__reset__"
+
+ def _reset_progress_bubble(self, st) -> None:
+ """Content bubble landed — close the tool-progress bubble so the next tool starts fresh
+ below it; else tool edits hit the ORIGINAL message above (out of order)."""
+ st.progress_msg_id, st.progress_lines = None, []
+ self._ctx.last_progress_msg[0], self._ctx.repeat_count[0] = None, 0
+
+ def _progress_absorb(self, st, raw) -> Any:
+ """Fold a queue item into the bubble buffer; returns the line to render this tick."""
+ if isinstance(raw, tuple) and len(raw) == 3 and raw[0] == "__dedup__":
+ _, base_msg, count = raw
+ if not st.progress_lines:
+ return base_msg
+ st.progress_lines[-1] = f"{base_msg} (×{count + 1})"
+ return st.progress_lines[-1]
+ st.progress_lines.append(raw)
+ return raw
+
+ async def _flush_progress_edit(self, st) -> None:
+ if st.can_edit and st.progress_lines and st.progress_msg_id:
+ with suppress(Exception):
+ await self._edit_progress_message(st, st.progress_msg_id, self._progress_text(st.progress_lines))
+
+ async def _drain_progress_on_cancel(self, st) -> None:
+ ctx = self._ctx
+ with suppress(Exception):
+ while not ctx.progress_queue.empty():
+ raw = ctx.progress_queue.get_nowait()
+ if self._is_reset_marker(raw):
+ # Content-bubble marker during drain: close the current progress bubble
+ # and start a fresh one for tool lines that arrived after.
+ await self._roll_progress_overflow_if_needed(st)
+ await self._flush_progress_edit(st)
+ self._reset_progress_bubble(st)
+ else:
+ self._progress_absorb(st, raw)
+ await self._roll_progress_overflow_if_needed(st)
+ # Final edit with all remaining tools (only if editing works)
+ if st.can_edit and st.progress_lines and st.progress_msg_id:
+ await self._roll_progress_overflow_if_needed(st)
+ await self._flush_progress_edit(st)
+
+ async def _progress_restore_typing(self, st) -> None:
+ ctx = self._ctx
+ await asyncio.sleep(0.3)
+ if ctx._run_still_current():
+ await st.adapter.send_typing(ctx.source.chat_id, metadata=ctx._progress_metadata)
+
+ async def _progress_send_or_edit(self, st, msg) -> bool:
+ """Deliver this tick's bubble. Returns False on a transient edit failure (retry next tick).
+
+ Transient network errors (ConnectError, timeouts) must not disable editing; only permanent
+ failures (not found, permissions) set can_edit=False. Flood control backs off but keeps editing.
+ """
+ if st.can_edit and st.progress_msg_id is not None:
+ result = await self._edit_progress_message(st, st.progress_msg_id, "\n".join(st.progress_lines))
+ if result.success:
+ return True
+ if getattr(result, "retryable", False):
+ logger.debug("[%s] Transient edit failure — keeping can_edit=True", st.adapter.name)
+ return False
+ if any(w in (getattr(result, "error", "") or "").lower() for w in ("flood", "retry after")):
+ logger.info("[%s] Progress edit flood control, backing off", st.adapter.name)
+ else:
+ st.can_edit = False
+ await self._send_progress_text(st, msg)
+ return True
+ # First tool: send all accumulated text as a new message; editing unsupported: just this line.
+ result = await self._send_progress_text(st, "\n".join(st.progress_lines) if st.can_edit else msg)
+ if result.success and result.message_id:
+ st.progress_msg_id = result.message_id
+ return True
+
+ async def send_progress_messages(self):
+ ctx = self._ctx
+ adapter = self._runner._delivery_adapter_for(ctx.source) if ctx.progress_queue else None
+ if not adapter:
+ return
+ if ctx._native_slack_task_cards and hasattr(adapter, "send_native_task_card_progress"):
+ await self._send_native_task_card_progress(adapter)
+ return
+ # Skip tool progress for platforms that can't edit messages (e.g. iMessage/BlueBubbles):
+ # each update would be a separate bubble. getattr, not attribute access: duck-typed
+ # adapters (test fakes, minimal plugins) may lack edit_message — treated as "can't edit".
+ adapter_edit = getattr(type(adapter), "edit_message", None)
+ if adapter_edit is None or adapter_edit is BasePlatformAdapter.edit_message:
+ self._drain_progress_queue()
+ return
+ st = self._progress_edit_state(adapter)
+ last_edit_ts = 0.0
+ EDIT_INTERVAL = 1.5 # Minimum seconds between edits (Telegram flood control)
+ while True:
+ try:
+ if not ctx._run_still_current():
+ self._drain_progress_queue()
+ return
+ raw = ctx.progress_queue.get_nowait()
+ # Drain silently when interrupted: events queued in the window between tool parse
+ # and interrupt processing should not render as bubbles.
+ if self._agent_interrupted():
+ await asyncio.sleep(0)
+ continue
+ if self._is_reset_marker(raw):
+ self._reset_progress_bubble(st)
+ continue
+ msg = self._progress_absorb(st, raw)
+ if not await self._roll_progress_overflow_if_needed(st):
+ # Throttle edits: batch rapid tool updates into fewer API calls (grammY pattern:
+ # proactively rate-limit rather than react to 429s). Loop back to drain further
+ # queued messages before sending a single batched edit.
+ remaining = EDIT_INTERVAL - (time.monotonic() - last_edit_ts)
+ if remaining > 0:
+ await asyncio.sleep(remaining)
+ continue
+ if not ctx._run_still_current():
+ return
+ if not await self._progress_send_or_edit(st, msg):
+ continue
+ last_edit_ts = time.monotonic()
+ await self._progress_restore_typing(st)
+ except queue.Empty:
+ await asyncio.sleep(0.3)
+ except asyncio.CancelledError:
+ await self._drain_progress_on_cancel(st)
+ return
+ except Exception as e:
+ logger.error("Progress message error: %s", e)
+ await asyncio.sleep(1)
+
+ # ── ID-bearing lifecycle callbacks (agent thread) ───────────────────────────────────────
+
+ def voice_ack_callback(self, call_id, tool_name, args):
+ """tool_start_callback: speak a one-time ack in the voice channel."""
+ ctx = self._ctx
+ if ctx._voice_ack_fired[0] or ctx._voice_ack_guild[0] is None or not ctx._run_still_current():
+ return
+ ctx._voice_ack_fired[0] = True
+ adapter = self._runner.adapters.get(Platform.DISCORD)
+ if adapter is None or not hasattr(adapter, "play_ack_in_voice"):
+ return
+ try:
+ self._schedule(
+ adapter.play_ack_in_voice(ctx._voice_ack_guild[0]), "voice ack scheduling error", loop=ctx._voice_ack_loop,
+ )
+ except Exception as err:
+ logger.debug("voice ack schedule failed: %s", err)
+
+ # Slack-native task cards ride agent.tool_start_callback / tool_complete_callback so start and
+ # completion correlate by the REAL tool-call id; name-correlated progress_callback text events
+ # would duplicate cards and mispair concurrent calls.
+
+ def _native_card_gate(self) -> bool:
+ ctx = self._ctx
+ return bool(ctx.progress_queue) and ctx._run_still_current() and not self._agent_interrupted()
+
+ # ── Slack-native task cards: ID-bearing lifecycle callbacks (#29483) ── These ride
+ # agent.tool_start_callback / agent.tool_complete_callback so start/completion events correlate by the
+ # REAL tool-call id — the name-correlated text events in progress_callback would duplicate cards and
+ # mispair concurrent calls to the same tool.
+ def native_tool_start_callback(self, call_id, tool_name, args):
+ """Queue an ID-correlated native progress start from the agent thread."""
+ if not self._native_card_gate():
+ return
+ from agent.display import build_tool_preview
+ name = str(tool_name or "tool")
+ self._ctx.progress_queue.put({
+ "type": "tool.started", "tool_call_id": str(call_id or ""), "tool_name": name,
+ "preview": build_tool_preview(name, args or {}, max_len=64) or "",
+ })
+
+ def native_tool_complete_callback(self, call_id, tool_name, args, result):
+ """Queue the matching native completion using the real tool-call ID."""
+ if not self._native_card_gate():
+ return
+ from agent.display import _detect_tool_failure
+ name = str(tool_name or "tool")
+ is_error, _ = _detect_tool_failure(name, result)
+ self._ctx.progress_queue.put({
+ "type": "tool.completed", "tool_call_id": str(call_id or ""), "tool_name": name, "is_error": bool(is_error),
+ })
+
+ def combined_tool_start_callback(self, call_id, tool_name, args):
+ """Compose the voice ack + native task-card start consumers."""
+ self._publish_execution("tool.start", _tool_lifecycle_payload(call_id, tool_name, args))
+ self._publish_api_tool("tool.start", call_id, tool_name, args)
+ if self._ctx._voice_ack_guild[0] is not None:
+ self.voice_ack_callback(call_id, tool_name, args)
+ if self._ctx._native_slack_task_cards:
+ self.native_tool_start_callback(call_id, tool_name, args)
+
+ def combined_tool_complete_callback(self, call_id, tool_name, args, result):
+ from agent.display import _detect_tool_failure
+ is_error, _ = _detect_tool_failure(tool_name, result)
+ payload = {**_tool_lifecycle_payload(call_id, tool_name, args), "is_error": bool(is_error),
+ "result": result if isinstance(result, str) else str(result)}
+ owner = self._approval_owner
+ live = owner[0].sessions.get(owner[1]) if owner is not None else None
+ # A session's /verbose (gateway/session_busy_controls.py) ships the Result block text.
+ if live is not None and (getattr(live, "tool_progress_mode", None) or self._ctx.progress_mode) == "verbose":
+ from tui_gateway.tool_progress import _tool_result_text
+ payload["result_text"] = _tool_result_text(result)
+ self._publish_execution("tool.complete", payload)
+ self._publish_api_tool("tool.complete", call_id, tool_name, args, result)
+ if self._ctx._native_slack_task_cards:
+ self.native_tool_complete_callback(call_id, tool_name, args, result)
+
+ # ── hook / status bridges (agent thread → gateway loop) ────────────────────────────────
+
+ def _step_callback_sync(self, iteration: int, prev_tools: list) -> None:
+ ctx = self._ctx
+ if not ctx._run_still_current():
+ return
+ self._publish_execution("agent.step", {"iteration": iteration})
+ if not ctx._hooks_ref.loaded_hooks:
+ return
+ # prev_tools may be list[str] or list[dict] with "name"/"result" keys. Normalise so
+ # "tool_names" stays backward-compatible for user hooks that do ', '.join(tool_names).
+ names = [(t.get("name") or "") if isinstance(t, dict) else str(t) for t in (prev_tools or [])]
+ self._schedule(
+ ctx._hooks_ref.emit("agent:step", {
+ "platform": ctx.source.platform.value if ctx.source.platform else "",
+ "user_id": ctx.source.user_id, "session_id": ctx.session_id,
+ "iteration": iteration, "tool_names": names, "tools": prev_tools,
+ }),
+ "agent:step hook scheduling error",
+ )
+
+ def _event_callback_sync(self, event_type: str, context: dict) -> None:
+ ctx = self._ctx
+ try:
+ asyncio.run_coroutine_threadsafe(ctx._hooks_ref.emit(event_type, context), ctx._loop_for_step)
+ except Exception as e:
+ logger.debug("event_callback hook error: %s", e)
+
+ def _status_live(self) -> bool:
+ """Status adapter present and this run is still the current generation."""
+ return bool(self._ctx._status_adapter) and self._ctx._run_still_current()
+
+ def _send_status_text(self, text: str, metadata, log_message: str) -> None:
+ ctx = self._ctx
+ self._schedule(ctx._status_adapter.send(ctx._status_chat_id, text, metadata=metadata), log_message)
+
+ def _attach_session_title_callback(self, agent, ctx) -> None:
+ """Wire the platform thread-rename lane onto the agent as `_on_session_title`.
+
+ The titler runs in the turn prologue, so attach before the run, not after it.
+ """
+ try:
+ # Gateway auto-title failures are not user-actionable, so never surface them as messages;
+ # overriding the failure sink keeps CLI on _emit_auxiliary_failure while gateway logs debug.
+ agent._title_failure_callback = lambda task, exc: logger.debug(
+ "Gateway auto-title failure suppressed (not user-visible): %s: %s", task, exc,
+ )
+ session_id = getattr(agent, "session_id", None)
- source = ctx.source
+ runner = self._runner
++ source = runner._recover_discord_auto_thread_source(ctx.source, ctx.session_key)
+ # Both lanes spend a rate-limited platform call per title, so they use the model's title
+ # only (TitleCallback); renaming twice burns Discord's 2-per-10-min budget on a throwaway.
+ # Relay Discord predicate is shape-only: whether the connector auto-threaded our reply is
+ # only knowable AFTER delivery, so register eagerly and let the rename lane look up the
+ # cache at fire time — gating registration on the cache read meant it never registered.
+ if runner._is_telegram_topic_lane(source):
+ lane = "_schedule_telegram_topic_title_rename"
+ elif runner._is_discord_auto_thread_lane(source) or runner._is_relay_discord_channel_lane(source):
+ lane = "_schedule_discord_semantic_thread_rename"
+ else:
+ return
+ agent._on_session_title = lambda title, title_source: (
+ title_source == "llm" and getattr(runner, lane)(source, session_id, title)
+ )
+ except Exception:
+ logger.debug("Failed to attach session title callback", exc_info=True)
+
+ def _status_callback_sync(self, event_type: str, message: str) -> None:
+ from gateway.run import _prepare_gateway_status_message, _redact_gateway_user_facing_secrets, _send_or_update_status_coro
+ from gateway.warning_notifications import is_warning_status, render_notification
+ ctx = self._ctx
+ if ctx.mute_notification_reply or not self._status_live():
+ return
+ prepared = _prepare_gateway_status_message(ctx.source.platform, event_type, message)
+ if prepared is None:
+ logger.debug(
+ "status_callback suppressed for %s/%s: %s",
+ ctx.source.platform.value if ctx.source.platform else "unknown", event_type,
+ _redact_gateway_user_facing_secrets(str(message or ""))[:160],
+ )
+ return
+ def present():
+ fut = self._schedule(
+ _send_or_update_status_coro(ctx._status_adapter, ctx._status_chat_id, event_type, prepared, ctx._status_thread_metadata),
+ f"status_callback ({event_type}) scheduling error",
+ )
+ if fut is not None and ctx._cleanup_progress:
+ fut.add_done_callback(self._track_future_cleanup_id)
+ render_notification(present, platform=ctx.source.platform, user_config=ctx.user_config,
+ diagnostic=is_warning_status(event_type, message))
diff --cc gateway/run_turn_runner.py
index f4843d89bc2,9b8c663fd0c..0ead6438e85
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@@ -59,25 -61,10 +61,28 @@@ def _renders_exec_approval_buttons(adap
# Rendered on a native clarify card whose wait ended without a click (mirrors the notice the
# Slack click handler shows on a dead entry).
- _CLARIFY_EXPIRED_NOTICE = "⏳ This prompt expired — please send a new request."
+ def _clarify_expired_notice() -> str:
+ return t("gateway.clarify.expired")
+
+
+# run_conversation result keys the gateway projection carries verbatim so a finite viewer's
+# `-z --usage-file` ledger (hermes_cli/oneshot._USAGE_KEYS) reads what the in-process path did.
+_LEDGER_PASSTHROUGH_KEYS = (
+ "estimated_cost_usd", "cost_status", "cost_source", "cache_read_tokens", "cache_write_tokens",
+ "reasoning_tokens", "total_tokens", "provider", "turn_exit_reason", "service_tier",
+)
+
+
+def _finite_viewer_turn() -> bool:
+ from gateway.session_finite import finite_turn_required
+ return finite_turn_required() is True
+
+
+class _NoStreamConsumer(RuntimeError):
+ """Raised by the delta callback when nothing consumed the text; ``_call_quietly`` turns it into
+ 'not delivered' so the agent's partial-delivery accounting matches what the user saw."""
+
+
class _ExecApprovalDeclined(RuntimeError):
"""The connector refused the approval card's destination.
@@@ -416,40 -1345,22 +421,29 @@@ class TurnRunner(GatewayTurnProgressMix
logger.warning("%s boundary timed out or failed: %s", reason, err)
return False
+ async def _send_shared_clarify(self, entry, **kwargs):
+ result = await self._ctx._status_adapter.send_clarify(**kwargs)
+ if self._approval_owner is not None and result.success:
+ authority, session_id, generation = self._approval_owner
+ authority.register_clarify(session_id, generation, entry)
+ return result
+
- def _clarify_callback_sync(self, question: str, choices, multi_select: bool = False,
- questions=None) -> str:
- """Present a clarify prompt and block on a response (clarify_tool's synchronous contract):
- schedule send_clarify on the gateway loop, block on the primitive's threading.Event with a
- timeout. Returns the response string, or a sentinel when none arrived.
-
- ``questions`` (clarify_tool's batch form) is answered here, one card per question, because
- this surface knows whether an answer arrived: the loop that would otherwise call this
- callback once per question can only recognize "no answer" from the returned sentinel text,
- and treated that text as the question's answer.
- """
- if questions:
- return self._clarify_batch_sync(questions)
- response, _answered = self._ask_clarify_question(question, choices, multi_select)
- return response
-
- def _clarify_batch_sync(self, questions) -> str:
- """Answer a batch: one card per question, stop at the first the user never answers.
- Returns the JSON shape clarify_tool's batch path reads. The stream/typing re-arm waits for
- the last question — between two cards it only opens a bubble the next boundary closes."""
+ def _clarify_callback_sync(self, questions) -> dict:
+ """Answer the clarify tool's questions (clarify_tool's synchronous contract): one card per
+ question, stop at the first the user never answers. The stream/typing re-arm waits for the
+ last question — between two cards it only opens a bubble the next boundary closes."""
+ from gateway.run_turn_runner_clarify_delivery import UNDELIVERED, UNDELIVERED_DECLINED, UNDELIVERED_NO_SURFACE
+ from tools.clarify_gateway import CANCELLED, SKIPPED
answers: Dict[str, Any] = {}
- payload: Dict[str, Any] = {"answers": answers, "timed_out": False}
+ reply: Dict[str, Any] = {"answers": answers, "outcome": "submitted"}
last = len(questions) - 1
for index, entry in enumerate(questions):
+ question = f"{entry['question']}\n{t('gateway.clarify.skip_hint')}"
raw, answered = self._ask_clarify_question(
- entry.get("question", ""), entry.get("choices"), bool(entry.get("multi_select")),
- rearm=index == last)
+ question, entry["choices"], bool(entry["multi_select"]), rearm=index == last)
+ if raw == CANCELLED:
+ reply["outcome"] = "cancelled"
+ break
if not answered:
# The surface's own no-answer text ("could not be delivered", "did not respond
# within Nm") rides along as ``notice``: blank answers alone read as user
@@@ -808,12 -1698,10 +803,14 @@@
kwargs = {"conversation_history": agent_history, "task_id": ctx.session_id}
if _accepts_keyword(agent.run_conversation, "turn_author"):
# Sent on every transport: a provider gating durable writes needs the bot flag in a DM too.
- kwargs["turn_author"] = {"id": ctx.source.user_id or None, "name": ctx.source.user_name or None,
- "is_bot": bool(getattr(ctx.source, "is_bot", False))}
+ from gateway.session_api_turn import api_execution
+ from gateway.session_ingress import admission_author
+ api = api_execution.get()
+ kwargs["turn_author"] = (api.get('turn_author') if api is not None else
+ admission_author.get() or {"id": ctx.source.user_id or None, "name": ctx.source.user_name or None,
+ "is_bot": bool(getattr(ctx.source, "is_bot", False))})
+ if ctx.title_user_message is not None:
+ kwargs["title_user_message"] = ctx.title_user_message
if persist_user_message_override is not None:
kwargs["persist_user_message"] = persist_user_message_override
elif observed_group_context:
@@@ -1097,30 -1926,16 +1094,27 @@@
if is_rate_limited_auth_error(exc.__cause__):
# Quota cap with valid credentials: /login cannot help; name the reset window (#89401).
from gateway.run import _gateway_provider_error_reply
- return {"final_response": _gateway_provider_error_reply(str(exc)),
- "messages": [], "api_calls": 0, "tools": []}
- return {
- "final_response": t("gateway.errors.no_credentials"),
- "messages": [], "api_calls": 0, "tools": [],
- }
+ return _unresolved(_gateway_provider_error_reply(str(exc)))
+ if ctx.source.platform == Platform.LOCAL:
+ # The local operator reads the terminal: the resolver's own sentence ("provider
+ # 'custom' resolved without credentials ...") is the diagnosis; /login is not.
+ return _unresolved(f"⚠️ {exc}")
- return _unresolved(
- "⚠️ I couldn't connect to the AI model service, so this message wasn't processed. "
- "Use /login to sign in again, or /model to pick a different model. If it keeps "
- "failing, run `hermes doctor` on the host.")
++ return _unresolved(t("gateway.errors.no_credentials"))
pr = runner._provider_routing
- reasoning_config = runner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model)
- runner._reasoning_config = reasoning_config
+ reasoning_config = (policy.reasoning_config if policy else
+ runner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model))
runner._service_tier = runner._resolve_session_service_tier(source=ctx.source, session_key=ctx.session_key)
+ from gateway.session_api_turn import api_execution
+ api = api_execution.get()
+ if api is not None:
+ from gateway.platforms.api_server import _request_reasoning_config, _request_service_tier, _REQUEST_OPTION_MISSING
+ requested_reasoning = _request_reasoning_config(api['settings'].get('model_options'))
+ if requested_reasoning is not None:
+ reasoning_config = requested_reasoning
+ tier = _request_service_tier(api['settings'].get('model_options'))
+ if tier is not _REQUEST_OPTION_MISSING:
+ runner._service_tier = tier
+ runner._reasoning_config = reasoning_config
stream_consumer, stream_delta_cb, interim_cb, want_interim = self._setup_stream_consumer(platform_key)
turn_route = runner._resolve_turn_agent_config(ctx.message, model, runtime_kwargs)
agent, reused_cached_agent = self._resolve_turn_agent(
diff --cc gateway/session_execution.py
index 3167452b80f,00000000000..cf006094c1f
mode 100644,000000..100644
--- a/gateway/session_execution.py
+++ b/gateway/session_execution.py
@@@ -1,218 -1,0 +1,220 @@@
+"""Extracted gateway session_execution responsibility; consumed by TurnRunner."""
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import json
+import logging
+import queue
+import re
+import threading
+import time
+from contextlib import suppress
+from datetime import datetime
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
+
+from agent.interrupt_compat import _accepts_keyword
+from agent.replay_cleanup import strip_stale_dangerous_confirmations
+from gateway.config import Platform
+from gateway.media_repair import repair_explicit_computer_use_media_paths
+from gateway.platforms.base import BasePlatformAdapter
+from gateway.turn_context import TurnContext
+from hermes_cli.config import cfg_get
+from utils import is_truthy_value
+
+if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
+ from gateway.run import GatewayRunner # noqa: F401
+
+# Log-record parity with the origin module.
+logger = logging.getLogger("gateway.run")
+
+
+class GatewaySessionAgentMixin:
+ # ── agent resolution (cache reuse vs fresh build) ───────────────────────────────────────
+
+ @dataclasses.dataclass
+ class _CachedAgentLookup:
+ agent: Any = None
+ reused: bool = False
+ evicted: Any = None # agent evicted under the lock; released off-lock on a daemon thread
+
+ def _skip_context_files(self, platform_key) -> bool:
+ """gateway.platforms.<plat>.skip_context_files: messaging platforms may opt out of
+ filesystem-heavy context-file discovery (SOUL.md, AGENTS.md, .cursorrules)."""
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(self._runner, self._ctx.source)
+ if policy:
+ return policy.ignore_rules
+ platforms_cfg = (self._ctx.user_config.get("gateway") or {}).get("platforms") or {}
+ # ``hermes gateway setup`` writes ``gateway.platforms`` as a LIST of enabled platform names,
+ # not a dict; treat any non-dict shape as "no per-platform overrides" rather than crashing.
+ if not isinstance(platforms_cfg, dict):
+ return False
+ return bool((platforms_cfg.get(platform_key) or {}).get("skip_context_files"))
+
+ def _cached_sid_is_dead(self, cache_lock, cache) -> tuple:
+ """(peeked cached session_id, is_dead) — checked OUTSIDE the cache lock. "cached sid != current
+ sid" normally means an intentional switch (reuse), but the routing-key self-heal yields the same
+ shape with an agent bound to a DEAD session; reusing it re-binds the dead sid and loops."""
+ ctx = self._ctx
+ peek_sid = None
+ if cache_lock and cache is not None:
+ with cache_lock:
+ entry = cache.get(ctx.session_key)
+ if entry and len(entry) > 3:
+ peek_sid = entry[3]
+ dead = False
+ if peek_sid is not None and ctx.session_id is not None and peek_sid != ctx.session_id:
++ # The cache is keyed by session_key, so the snapshot's row lives in that key's profile
++ # store; its id is no longer in the routing index once the self-heal moved the key on.
+ with suppress(Exception):
- dead = self._runner.session_store._is_session_ended_in_db(peek_sid)
++ dead = self._runner.session_store._is_session_ended_in_db(peek_sid, session_key=ctx.session_key)
+ return peek_sid, dead
+
+ def _current_message_count(self):
+ """Cross-process write guard input: the session's current DB message_count (or None)."""
+ ctx = self._ctx
+ if self._runner._session_db is None or not ctx.session_id:
+ return None
+ count = None
+ with suppress(Exception):
+ # run_sync is off-loop (executor); sync DB is fine.
+ row = self._runner._session_db._db.get_session(ctx.session_id)
+ if row:
+ count = row.get("message_count", 0)
+ return count
+
+ def _pop_cached_agent_for_eviction(self):
+ """Evict under the lock but DEFER release (release_clients can block on memory-provider /
+ socket teardown while the idle sweeper waits on this lock). The turn rebuilds a fresh agent, so
+ the caller does a SOFT release that keeps sandbox / browser / bg processes."""
+ from gateway.run import _AGENT_PENDING_SENTINEL
+ evicted = self._runner._agent_cache.pop(self._ctx.session_key, None)
+ agent = evicted[0] if isinstance(evicted, tuple) and evicted else None
+ return agent if agent and agent is not _AGENT_PENDING_SENTINEL else None
+
+ def _lookup_cached_agent(self, sig, cache_lock, cache, max_iterations, peek_sid, dead, msg_count):
+ ctx = self._ctx
+ out = self._CachedAgentLookup()
+ if not (cache_lock and cache is not None):
+ return out
+ with cache_lock:
+ cached = cache.get(ctx.session_key)
+ if not (cached and cached[1] == sig):
+ return out
+ # cached[2] = message_count at cache time (stale when a second process appended rows);
+ # cached[3] = the session_id the snapshot was taken for.
+ cached_mc = cached[2] if len(cached) > 2 else None
+ cached_sid = cached[3] if len(cached) > 3 else None
+ # Same session_key, other conversation: the counts track DIFFERENT DB rows, so the
+ # comparison is meaningless — REUSE rather than bust the prompt cache on every switch.
+ sid_mismatch = cached_sid is not None and ctx.session_id is not None and cached_sid != ctx.session_id
+ # Re-validate the outside-lock dead-session peek against the tuple read under THIS lock:
+ # a stale "dead" verdict must never be applied to a different (possibly live) agent.
+ if sid_mismatch and dead and cached_sid == peek_sid:
+ logger.info(
+ "Agent cache invalidated for session %s: "
+ "cached agent's session_id %s is ended in "
+ "state.db (stale self-heal artifact, "
+ "#54878 x #54947) — discarding instead of "
+ "reusing across the routing recovery", ctx.session_key, cached_sid,
+ )
+ elif not sid_mismatch and cached_mc is not None and msg_count is not None and msg_count != cached_mc:
+ logger.info(
+ "Agent cache invalidated for session %s: "
+ "message_count changed (%s -> %s), "
+ "possible cross-process write", ctx.session_key, cached_mc, msg_count,
+ )
+ else:
+ out.agent = cached[0]
+ # Refresh LRU order so cap enforcement evicts truly-oldest entries.
+ if hasattr(cache, "move_to_end"):
+ with suppress(KeyError):
+ cache.move_to_end(ctx.session_key)
+ self._runner._init_cached_agent_for_turn(out.agent, ctx._interrupt_depth)
+ # Cached agent may have been created with old config.
+ out.agent.max_iterations = max_iterations
+ logger.debug("Reusing cached agent for session %s", ctx.session_key)
+ out.reused = True
+ return out
+ out.evicted = self._pop_cached_agent_for_eviction()
+ return out
+
+ def _release_evicted_agent(self, agent) -> None:
+ """Off-lock soft release on a daemon thread so teardown never blocks the gateway loop."""
+ self._runner._spawn_release_thread(
+ self._runner._release_evicted_agent_soft, (agent,), f"agent-xproc-evict-{str(self._ctx.session_key)[:24]}",
+ inline_fallback=True,
+ )
+
+ def _build_fresh_agent(self, turn_route, platform_key, combined_ephemeral, max_iterations,
+ reasoning_config, pr, skip_context_files):
+ from gateway.run import _checkpoint_agent_kwargs
+ ctx = self._ctx
+ runner = self._runner
+ src = ctx.source
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(runner, src)
+ return ctx.AIAgent(
+ model=turn_route["model"], **turn_route["runtime"], **_checkpoint_agent_kwargs(ctx.user_config),
+ max_iterations=max_iterations, quiet_mode=True, verbose_logging=False,
+ enabled_toolsets=ctx.enabled_toolsets, disabled_toolsets=ctx.disabled_toolsets,
+ ephemeral_system_prompt=combined_ephemeral or None,
+ prefill_messages=runner._prefill_messages or None,
+ reasoning_config=reasoning_config, service_tier=runner._service_tier,
+ request_overrides=turn_route.get("request_overrides"),
+ 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"),
+ session_id=ctx.session_id, platform=platform_key,
+ user_id=src.user_id, user_id_alt=src.user_id_alt, user_name=src.user_name,
+ chat_id=src.chat_id, chat_name=src.chat_name, chat_type=src.chat_type, thread_id=src.thread_id,
+ gateway_session_key=ctx.session_key,
+ session_db=getattr(runner._session_db, "_db", runner._session_db),
+ # Reload from disk — do not reuse the startup snapshot.
+ # See #60955.
+ fallback_model=self._runner._refresh_fallback_model(),
+ skip_context_files=skip_context_files,
+ # Keep the persona even with minimal context: soul identity is one small file.
+ load_soul_identity=not bool(policy and policy.ignore_rules),
+ skip_memory=bool(policy and policy.ignore_rules),
+ )
+
+ def _resolve_turn_agent(self, turn_route, platform_key, combined_ephemeral, max_iterations, reasoning_config, pr):
+ """Reuse this session's cached AIAgent (frozen system prompt + tool schemas → prompt cache
+ hits) or build a fresh one. Returns (agent, reused_cached_agent)."""
+ ctx = self._ctx
+ runner = self._runner
+ skip_context_files = self._skip_context_files(platform_key)
+ sig = runner._agent_config_signature(
+ turn_route["model"], turn_route["runtime"], ctx.enabled_toolsets, combined_ephemeral,
+ cache_keys=runner._extract_cache_busting_config(ctx.user_config),
+ user_id=getattr(ctx.source, "user_id", None),
+ user_id_alt=getattr(ctx.source, "user_id_alt", None),
+ skip_context_files=skip_context_files,
+ )
+ cache_lock = getattr(runner, "_agent_cache_lock", None)
+ cache = getattr(runner, "_agent_cache", None)
+ peek_sid, dead = self._cached_sid_is_dead(cache_lock, cache)
+ msg_count = self._current_message_count()
+ found = self._lookup_cached_agent(sig, cache_lock, cache, max_iterations, peek_sid, dead, msg_count)
+ agent = found.agent
+ # Lock released — refresh the reused agent's fallback chain from disk OUTSIDE the cache lock
+ # (disk I/O under the lock stalls the idle-sweep watcher and Discord heartbeats). A chain
+ # configured after caching must reach the next turn; per-session serialization keeps it safe.
+ if found.reused and agent is not None:
+ self._runner._apply_fallback_chain_to_agent(agent, runner._refresh_fallback_model())
+ if found.evicted is not None:
+ self._release_evicted_agent(found.evicted)
+ if agent is None:
+ agent = self._build_fresh_agent(
+ turn_route, platform_key, combined_ephemeral, max_iterations, reasoning_config, pr, skip_context_files,
+ )
+ if cache_lock and cache is not None:
+ with cache_lock:
+ # Record the snapshot's session_id with message_count so the cross-process guard
+ # can skip the meaningless count comparison if the active session_id switches.
+ cache[ctx.session_key] = (agent, sig, msg_count, ctx.session_id)
+ runner._enforce_agent_cache_cap()
+ logger.debug("Created new agent for session %s (sig=%s)", ctx.session_key, sig)
+ return agent, found.reused
diff --cc gateway/status.py
index e3ea815ea41,3275cf5cfab..bcfbd455a7d
--- a/gateway/status.py
+++ b/gateway/status.py
@@@ -1004,8 -899,11 +904,12 @@@ def _file_cache_signature(path: Path) -
return (True, st.st_mtime_ns, st.st_size)
- def _cleanup_invalid_pid_path(pid_path: Path, *, cleanup_stale: bool) -> None:
- """Force-unlink a stale PID file + sibling lock (lock confirmed inactive, so no pid check)."""
+ def _cleanup_invalid_pid_path(
+ pid_path: Path, *, cleanup_stale: bool, unlink_lock: bool = True
+ ) -> None:
- """Force-unlink a stale PID file + sibling lock (lock confirmed inactive, so no pid check).
- ``unlink_lock=False`` drops only the PID file: the caller saw the lock HELD."""
++ """Force-unlink a stale PID file (lock confirmed inactive, so no pid check). The sibling lock
++ file is never unlinked, held or not (``unlink_lock`` is therefore moot): another contender may
++ already have opened that inode, and a fresh one would let two processes each hold "the" lock."""
if not cleanup_stale:
return
_clear_running_pid_cache()
@@@ -2059,19 -2050,22 +2029,25 @@@ def get_running_pid
record, pid, expected_home=expected_home
):
return pid
- # Scoped only: a live record we could not adopt may still be a real gateway;
- # unlinking its identity files would break that home's double-run protection
- # while the PID is alive. Unscoped keeps the #89315 poison-file cleanup.
- saw_live_pid = True
- if expected_home is None or not saw_live_pid:
- _cleanup_invalid_pid_path(resolved_pid_path, cleanup_stale=cleanup_stale)
+ # A same-home record the matcher could not adopt may still be a real gateway (an
+ # identity matcher that lags a new launcher shape, a record written by an older
+ # version): that rejection is not stale-file authority while the PID is alive and the
+ # lock held. A scoped poll never unlinks the other home's files either (#106406).
+ if home_ok or expected_home is not None:
+ saw_live_pid = True
+ else:
+ foreign_live_pid = True
+ if not saw_live_pid:
+ _cleanup_invalid_pid_path(
+ resolved_pid_path, cleanup_stale=cleanup_stale, unlink_lock=not foreign_live_pid
+ )
return get_runtime_status_running_pid() if pid_path is None else None
- # Lock inactive: the runtime-status fallback runs BEFORE cleanup here.
+ # Lock inactive: the runtime-status fallback runs BEFORE cleanup here. A record naming THIS
+ # process is one we wrote earlier in our own boot (the multiplex verdict is persisted before
+ # the PID claim), not a rival: treating it as live skipped the stale gateway.pid cleanup after
+ # a SIGKILLed owner and the O_EXCL claim then lost the "PID file race" to itself.
runtime_pid = get_runtime_status_running_pid() if pid_path is None else None
- if runtime_pid is None:
+ if runtime_pid is None or runtime_pid == os.getpid():
_cleanup_invalid_pid_path(resolved_pid_path, cleanup_stale=cleanup_stale)
return runtime_pid
diff --cc hermes_cli/backup.py
index ce8b5c912d1,3ee30a82601..0ec40ade176
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@@ -35,7 -36,7 +36,8 @@@ from hermes_cli.backup_restore import
_detect_prefix,
_extract_member_atomically,
_import_db_member,
+ _restore_auth_json,
+ _restore_destination_epoch,
_safe_restore_db,
_validate_backup_zip,
)
@@@ -1542,24 -1499,13 +1530,25 @@@ def restore_quick_snapshot
snapshot_id: str,
hermes_home: Optional[Path] = None,
) -> bool:
- """Restore state from a quick snapshot.
+ """Restore the whole snapshot offline, or refuse before changing any file.
Overwrites current state files with the snapshot's copies.
- Returns True if at least one file was restored.
+ Returns True if at least one file was restored and the listed auth.json
+ was not refused or skipped.
"""
+ from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance
home = hermes_home or get_hermes_home()
+ try:
+ with exclusive_maintenance([home]):
+ return _restore_quick_snapshot_exclusive(snapshot_id, home)
+ except OwnershipConflict as exc:
+ logger.error("%s", exc)
+ return False
+
+
+def _restore_quick_snapshot_exclusive(snapshot_id: str, home: Path) -> bool:
+ """Restore state from a quick snapshot while ``home`` is reserved."""
+ from gateway.runtime_ownership import exclusive_maintenance
root = _quick_snapshot_root(home)
# Security: reject snapshot_id values that contain path separators or
@@@ -1587,63 -1533,70 +1576,86 @@@
with open(manifest_path, encoding="utf-8-sig") as f:
meta = json.load(f)
- restored = 0
- auth_restore_failed = False
- for rel in meta.get("files", {}):
- # Security: reject absolute paths and traversals in manifest entries
- src = snap_dir / rel
- try:
- src.resolve().relative_to(snap_dir.resolve())
- except ValueError:
- logger.error("Manifest path traversal blocked: %s", rel)
- if rel == "auth.json":
- auth_restore_failed = True
- continue
+ snap_res, home_res = snap_dir.resolve(), home.resolve()
- dst = home / rel
- try:
- dst.resolve().relative_to(home.resolve())
- except ValueError:
+ def _entry_paths(rel: str) -> Optional[Tuple[Path, Path]]:
+ # Security: reject absolute paths and traversals in manifest entries
+ src, dst = snap_dir / rel, home / rel
- if not (src.resolve().is_relative_to(snap_res) and dst.resolve().is_relative_to(home_res)):
++ if not src.resolve().is_relative_to(snap_res):
+ return None
++ if not dst.resolve().is_relative_to(home_res):
+ # Named profiles may deliberately share the machine-root auth store via an
+ # auth.json symlink. Let only that exact trusted alias reach _restore_auth_json;
+ # every other manifest destination outside the profile remains a traversal.
+ if rel != "auth.json" or not _is_trusted_root_auth_alias(dst, home):
++ return None
+ return src, dst
+
+ homes = {home}
+ for rel in meta.get("files", {}):
+ entry = _entry_paths(rel)
+ if entry and entry[1].suffix == ".db":
+ homes.update([entry[1].absolute().parent, entry[1].resolve().parent])
+ with exclusive_maintenance(homes):
+ # Epoch safety is a whole-profile preflight: copying config first would
+ # both partially roll back the profile and report a refused DB as success.
+ for rel in meta.get("files", {}):
+ entry = _entry_paths(rel)
+ if entry and entry[0].exists() and "state.db" in (entry[1].name, entry[1].resolve().name):
+ try:
+ _restore_destination_epoch(entry[1])
+ except OSError as exc:
+ logger.error("%s", exc)
+ return False
+
+ restored = 0
++ auth_restore_failed = False
+ for rel in meta.get("files", {}):
+ entry = _entry_paths(rel)
+ if entry is None:
logger.error("Manifest path traversal blocked: %s", rel)
+ if rel == "auth.json":
+ auth_restore_failed = True
continue
+ src, dst = entry
+ if not src.exists():
++ if rel == "auth.json":
++ logger.error("Snapshot auth.json listed in manifest is missing: %s", src)
++ auth_restore_failed = True
+ continue
- if not src.exists():
- if rel == "auth.json":
- logger.error("Snapshot auth.json listed in manifest is missing: %s", src)
- auth_restore_failed = True
- continue
-
- dst.parent.mkdir(parents=True, exist_ok=True)
+ dst.parent.mkdir(parents=True, exist_ok=True)
- try:
- if dst.suffix == ".db":
- # Restore through SQLite backup API so live connections
- # (gateway, dashboard, another CLI session) see the
- # restored data instead of continuing to serve stale
- # cached pages from a replaced inode (issue #65942).
- if not _safe_restore_db(src, dst):
- # Refused, failed, or source failed its integrity check:
- # dst left as it was. Count as a failure, not a restore.
- logger.error("Failed to restore %s: refused or source integrity check failed (see previous log)", rel)
- continue
- elif rel == "auth.json":
- # Refresh tokens for these OAuth providers rotate on use. A historical
- # snapshot can therefore contain a spent pair even though the current
- # auth.json has the live successor. Restore the historical auth state
- # while retaining that live single-use grant under the auth-store lock.
- if not _restore_auth_json(src, dst):
- logger.error("Failed to restore %s safely", rel)
+ try:
+ if dst.suffix == ".db":
+ # Restore through SQLite backup API so live connections
+ # (gateway, dashboard, another CLI session) see the
+ # restored data instead of continuing to serve stale
+ # cached pages from a replaced inode (issue #65942).
+ if not _safe_restore_db(src, dst):
+ # Refused, failed, or source failed its integrity check:
+ # dst left as it was. Count as a failure, not a restore.
+ logger.error("Failed to restore %s: refused or source integrity check failed (see previous log)", rel)
+ continue
++ elif rel == "auth.json":
++ # Refresh tokens for these OAuth providers rotate on use. A historical
++ # snapshot can therefore contain a spent pair even though the current
++ # auth.json has the live successor. Restore the historical auth state
++ # while retaining that live single-use grant under the auth-store lock.
++ if not _restore_auth_json(src, dst):
++ logger.error("Failed to restore %s safely", rel)
++ auth_restore_failed = True
++ continue
+ else:
+ shutil.copy2(src, dst)
+ restored += 1
+ except (OSError, PermissionError) as exc:
+ logger.error("Failed to restore %s: %s", rel, exc)
++ if rel == "auth.json":
+ auth_restore_failed = True
- continue
- else:
- shutil.copy2(src, dst)
- restored += 1
- except (OSError, PermissionError) as exc:
- logger.error("Failed to restore %s: %s", rel, exc)
- if rel == "auth.json":
- auth_restore_failed = True
logger.info("Restored %d files from snapshot %s", restored, snapshot_id)
- return restored > 0
+ return restored > 0 and not auth_restore_failed
def _count_cron_jobs(path: Path) -> Optional[int]:
diff --cc hermes_cli/backup_restore.py
index ab149df99f0,e54dd44e5f5..bf47224534a
--- a/hermes_cli/backup_restore.py
+++ b/hermes_cli/backup_restore.py
@@@ -20,9 -20,9 +21,10 @@@ from pathlib import Pat
from typing import List, Optional, Tuple
from hermes_state_holders import read_only_db_uri
+from hermes_cli.backup_sqlite import _safe_copy_db
from utils import (
_preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace,
+ mkstemp_beside,
)
logger = logging.getLogger(__name__)
@@@ -73,88 -73,89 +75,170 @@@ def _foreign_db_holder_pids(db_path: Pa
return pids
+ def _auth_restore_target(dst: Path) -> Optional[Path]:
+ """Writable auth-store path whose lock and publish name the same underlying file.
+
+ A file symlink is resolved so refresh writers and restore take the same auth.lock. A hard-linked
+ auth.json cannot be atomically replaced without splitting a deliberately shared store into two
+ inodes, so that topology fails closed instead of silently breaking credential sharing.
+ """
+ try:
+ if dst.exists():
+ links = dst.stat().st_nlink
+ if links > 1:
+ logger.error(
+ "Refusing auth.json restore to %s: it has %d hard links; atomic replacement "
+ "would split a shared auth store",
+ dst,
+ links,
+ )
+ return None
+ return dst.resolve(strict=False) if dst.is_symlink() else dst
+ except (OSError, RuntimeError) as exc:
+ logger.error("Refusing auth.json restore to %s: cannot resolve store identity: %s", dst, exc)
+ return None
+
+
+ def _restore_auth_json(src: Path, dst: Path) -> bool:
+ """Restore auth.json without rolling back a live single-use OAuth generation.
+
+ The live read and final write share the canonical auth-store lock, so a concurrent refresh
+ cannot land between preservation and publish.
+ """
+ try:
+ snapshot_store = json.loads(src.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError, UnicodeError) as exc:
+ logger.error("Refusing auth.json restore from %s: %s", src, exc)
+ return False
+ if not isinstance(snapshot_store, dict):
+ logger.error("Refusing auth.json restore from %s: top level is not an object", src)
+ return False
+ if not (
+ isinstance(snapshot_store.get("providers"), dict)
+ or isinstance(snapshot_store.get("credential_pool"), dict)
+ or isinstance(snapshot_store.get("systems"), dict)
+ ):
+ logger.error("Refusing auth.json restore from %s: unrecognized auth-store shape", src)
+ return False
+ # Legacy "systems" stores are still valid snapshot input. Mirror auth._load_auth_store's
+ # migration without asking that loader to create a .corrupt sidecar inside the snapshot.
+ if (
+ not isinstance(snapshot_store.get("providers"), dict)
+ and not isinstance(snapshot_store.get("credential_pool"), dict)
+ and isinstance(snapshot_store.get("systems"), dict)
+ ):
+ systems = snapshot_store["systems"]
+ providers = {"nous": systems["nous_portal"]} if "nous_portal" in systems else {}
+ # Match auth._load_auth_store's migration shape exactly: the legacy
+ # "systems" container itself is obsolete and must not be written back.
+ snapshot_store = {
+ "providers": providers,
+ "active_provider": "nous" if providers else None,
+ }
+
+ try:
+ from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store
+ from hermes_cli.auth_oauth_grants import (
+ merge_snapshot_auth_preserving_live_single_use_grants,
+ )
+
+ target = _auth_restore_target(dst)
+ if target is None:
+ return False
+ with _auth_store_lock(target_path=target):
+ live_store = _load_auth_store(target)
+ restored = merge_snapshot_auth_preserving_live_single_use_grants(
+ snapshot_store, live_store
+ )
+ _save_auth_store(restored, target_path=target)
+ return True
+ except Exception as exc:
+ logger.error("Failed to restore %s safely: %s", dst, exc)
+ return False
+
+
def _safe_restore_db(src: Path, dst: Path) -> bool:
+ """Restore only while holding the destination authority's maintenance reservation.
+
+ Returns ``False``, without touching *dst*, when *src* fails the SQLite
+ integrity check, when the runtime owns the profile, or when a canonical
+ ``state.db`` epoch floor cannot be proven.
+ """
+ from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance
+ from hermes_cli.backup import verify_sqlite_integrity
+
+ # backup() copies pages without validating their contents; its fallback
+ # copies bytes even when SQLite rejected the source. Neither may touch the
+ # destination until the snapshot passes the existing bounded integrity policy.
+ source_check = verify_sqlite_integrity(src)
+ if not source_check["valid"]:
+ logger.error("Refusing SQLite restore from %s: %s", src, source_check["message"])
+ return False
+ try:
+ with exclusive_maintenance([dst.absolute().parent, dst.resolve().parent]):
+ with _restore_epoch_source(src, dst) as prepared:
+ return _restore_db_pages(prepared, dst)
+ except (OwnershipConflict, OSError, sqlite3.Error) as exc:
+ logger.error("%s", exc)
+ return False
+
+
+def _restore_epoch(path: Path) -> int:
+ if not path.exists():
+ return 0
+ with closing(sqlite3.connect(read_only_db_uri(path), uri=True)) as conn:
+ if not conn.execute("SELECT 1 FROM sqlite_master WHERE name='runtime_epoch'").fetchone():
+ return 0
+ row = conn.execute("SELECT epoch FROM runtime_epoch WHERE singleton=1").fetchone()
+ return int(row[0]) if row else 0
+
+
+def _restore_destination_epoch(dst: Path) -> int:
+ try:
+ return _restore_epoch(dst)
+ except (OSError, sqlite3.Error, ValueError) as exc:
+ raise OSError(
+ f"Cannot read the canonical runtime epoch at {dst}; refusing in-place restore. "
+ "Use `hermes sessions recover --source <snapshot> --output <separate-path>` "
+ "to salvage transcripts into a separate output."
+ ) from exc
+
+
+@contextmanager
+def _restore_epoch_source(src: Path, dst: Path):
+ """Stage an epoch floor into the image BEFORE publishing it atomically.
+
+ Updating the destination after backup() would leave a crash window that
+ reuses an older worker epoch. Never modify the user's source snapshot.
+ Full restores retain all admissions/worker receipts; normal startup advances
+ this floor and reconciles started work to unknown, not replayable queued work.
+ An unreadable destination cannot prove its epoch floor: use transcript salvage
+ into a separate output rather than silently restoring with a recycled epoch.
+ """
+ if dst.name != 'state.db' and dst.resolve().name != 'state.db':
+ yield src
+ return
+ floor = _restore_destination_epoch(dst)
+ if floor <= _restore_epoch(src):
+ yield src
+ return
+ with tempfile.TemporaryDirectory(prefix='.restore-epoch-', dir=dst.parent) as work:
+ prepared = Path(work) / 'state.db'
+ if not _safe_copy_db(src, prepared):
+ raise OSError('Unable to stage a restore with a safe runtime epoch')
+ with closing(sqlite3.connect(prepared)) as conn:
+ conn.execute("""CREATE TABLE IF NOT EXISTS runtime_epoch (
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
+ epoch INTEGER NOT NULL CHECK (epoch > 0), instance_id TEXT NOT NULL)""")
+ conn.execute("""INSERT INTO runtime_epoch VALUES(1,?, 'offline-restore')
+ ON CONFLICT(singleton) DO UPDATE SET epoch=excluded.epoch,
+ instance_id=excluded.instance_id""", (floor,))
+ conn.commit()
+ prepared.chmod(src.stat().st_mode)
+ yield prepared
+
+
+def _restore_db_pages(src: Path, dst: Path) -> bool:
"""Restore a SQLite database from snapshot *src* into live *dst*.
Uses SQLite's backup() API to write snapshot pages into the live
diff --cc hermes_cli/cli_single_query.py
index 246ae3301fd,4a18e80ee8c..b3d686b593a
--- a/hermes_cli/cli_single_query.py
+++ b/hermes_cli/cli_single_query.py
@@@ -135,10 -144,13 +142,11 @@@ from hermes_cli.turn_exit import TRANSI
# ``kanban.failure_limit`` is spent. ``billing`` stays transient: credit comes back.
# ``upstream_blocked`` (a WAF/CDN refusing the SDK's User-Agent) is terminal too: only a
# header change heals it, never a retry.
-_TERMINAL_PROVIDER_REASONS = frozenset({
- "auth", "auth_permanent", "model_not_found", "ssl_cert_verification", "upstream_blocked",
-})
+from hermes_cli.turn_exit import TERMINAL_PROVIDER_REASONS as _TERMINAL_PROVIDER_REASONS
- def _single_query_exit_code(result, *, credentials_rate_limited: bool = False) -> int:
+ def _single_query_exit_code(result, *, credentials_rate_limited: bool = False,
+ credentials_terminal: bool = False) -> int:
"""Map a one-shot turn result onto a process exit code, for both `-q` and `-Q`.
0 only when the turn completed; 130 when it was interrupted; 1 when it failed, stopped
@@@ -150,16 -162,38 +158,24 @@@
The same sentinel applies when credential resolution itself is a quota/rate-limit
AuthError (no turn result object is produced). One that failed on a terminal provider
error (credential revoked, model gone) exits ``KANBAN_TERMINAL_PROVIDER_EXIT_CODE``
- (EX_CONFIG): the dispatcher blocks the card at once.
+ (EX_CONFIG): the dispatcher blocks the card at once. The same code applies
+ before a turn when credential resolution explicitly requires re-authentication;
+ unknown startup failures retain exit 1.
+
+ The worker predicate is the STRIPPED ``kanban_task_id()`` (from
+ ``agent.kanban_turn_recovery``) so a whitespace-only value is not a worker here
+ either — the exit mapping and the recovery gate must agree on what a worker is.
"""
from cli import _TERMINAL_PROVIDER_REASONS, _TRANSIENT_PROVIDER_REASONS
+ from agent.kanban_turn_recovery import kanban_task_id
-
- if not isinstance(result, dict):
- if credentials_rate_limited and kanban_task_id():
- from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
- return KANBAN_RATE_LIMIT_EXIT_CODE
- if credentials_terminal and kanban_task_id():
- from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
- return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
- return 1
- if result.get("interrupted"):
- return 130
- if not (result.get("failed") or result.get("partial") or result.get("completed") is False):
- return 0
- if kanban_task_id():
- reason = result.get("failure_reason")
- if reason in _TRANSIENT_PROVIDER_REASONS:
- from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
- return KANBAN_RATE_LIMIT_EXIT_CODE
- if reason in _TERMINAL_PROVIDER_REASONS:
- from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
- return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
- return 1
+ from hermes_cli.turn_exit import turn_exit_code
+ return turn_exit_code(
- result, kanban_worker=bool(os.environ.get("HERMES_KANBAN_TASK")),
++ result, kanban_worker=kanban_task_id() is not None,
+ credentials_rate_limited=credentials_rate_limited,
++ credentials_terminal=credentials_terminal,
+ transient_reasons=_TRANSIENT_PROVIDER_REASONS,
+ terminal_reasons=_TERMINAL_PROVIDER_REASONS,
+ )
def _run_quiet_single_query(cli, effective_query, emitter=None):
diff --cc hermes_cli/config.py
index a2415e91a47,4b839755a9c..395fe105a6a
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@@ -3979,122 -4091,184 +4120,189 @@@ def _inject_profile_env_vars() -> None
_inject_profile_env_vars()
- def _platform_plugin_manifests():
- """Yield ``(dir_name, manifest_dict)`` for every platform plugin manifest: bundled
- ``plugins/platforms/*``, the user's ``<HERMES_HOME>/plugins/platforms/*`` category dir, and flat
- user installs ``<HERMES_HOME>/plugins/*`` that declare ``kind: platform`` (#46600)."""
- from agent.safe_worker_policy import safe_worker_enabled
+ PlatformManifestSource = Literal["all", "bundled", "user"]
- if safe_worker_enabled():
- return
- user_plugins = get_hermes_home() / "plugins"
- roots = (
- (get_project_root() / "plugins" / "platforms", False),
- (user_plugins / "platforms", False),
- (user_plugins, True), # flat layout: only manifests that say they are platforms
- )
+
+ def _is_plugin_dir_name(name: str) -> bool:
+ # Same rule as plugins_discovery.scan_directory: __pycache__-style dunders aren't plugins; a dot
+ # dir can be, so its secrets are declared too.
+ return not (name.startswith("__") and name.endswith("__"))
+
+
+ def _platform_manifest_paths(home: Optional[Path] = None, source: PlatformManifestSource = "all"):
+ """Yield ``(dir_name, manifest_path, require_kind, stat)`` for every platform plugin manifest.
+ ``source`` is ``"bundled"`` (shipped ``plugins/platforms/*``), ``"user"`` (``<home>/plugins/
+ platforms/*`` plus flat ``<home>/plugins/*`` installs, which must declare ``kind: platform``,
+ #46600) or ``"all"``. ``home`` defaults to the bound Hermes home. A directory that cannot be
+ listed or searched yields ``(name, None, require_kind, error)``: a plugin there can't load
+ either, so callers skip it. One ``scandir`` per root and one ``stat`` per candidate, because
+ the child-env scrub stamps these on every spawn."""
+ roots = []
+ if source in ("all", "bundled"):
+ roots.append((get_project_root() / "plugins" / "platforms", False))
+ if source in ("all", "user"):
+ user_plugins = (home if home is not None else get_hermes_home()) / "plugins"
+ roots += [(user_plugins / "platforms", False), (user_plugins, True)]
for root, require_kind in roots:
- if not root.is_dir():
+ try:
+ with os.scandir(root) as it:
+ entries = [e for e in it if _is_plugin_dir_name(e.name)]
+ except (FileNotFoundError, NotADirectoryError):
continue
- for child in root.iterdir():
- manifest_path = next(
- (p for p in (child / "plugin.yaml", child / "plugin.yml") if child.is_dir() and p.exists()), None)
- if manifest_path is None:
- continue
+ except OSError as exc:
+ yield str(root), None, require_kind, exc
+ continue
+ for entry in entries:
try:
- with open(manifest_path, "r", encoding="utf-8-sig") as f:
- manifest = fast_safe_load(f) or {}
- except Exception:
- continue
- if not isinstance(manifest, dict) or (require_kind and manifest.get("kind") != "platform"):
+ if not entry.is_dir():
+ continue
+ except OSError:
continue
- yield child.name, manifest
+ for file_name in ("plugin.yaml", "plugin.yml"):
+ path = Path(entry.path) / file_name
+ try:
+ st = os.stat(path)
+ except PermissionError as exc: # the dir itself is not searchable
+ yield entry.name, None, require_kind, exc
+ break
+ except OSError: # missing, a symlink loop: discovery's exists() is False too
+ continue
+ if not stat.S_ISREG(st.st_mode):
+ continue
+ yield entry.name, path, require_kind, st
+ break
+
+
+ def platform_manifest_stamp(home: Optional[Path] = None) -> tuple:
+ """Change-detection key over every user platform plugin manifest of ``home`` (path plus
+ :func:`utils.file_signature`): it changes when one is added, removed, replaced or edited in
+ place, so a cache keyed on it never serves a stale declaration."""
+ return tuple((name, str(path), file_signature(st) if path is not None else type(st).__name__)
+ for name, path, _kind, st in _platform_manifest_paths(home, "user"))
+
+
+ def _platform_plugin_manifests(home: Optional[Path] = None, source: PlatformManifestSource = "all", *,
+ strict: bool = False, skipped: "list | None" = None):
+ """Yield ``(dir_name, manifest_dict)`` for every platform plugin manifest (see
+ :func:`_platform_manifest_paths`). ``strict`` raises when a manifest cannot be read instead of
+ skipping it: the child-env scrub must not lose a declared secret to an I/O error. Only a
+ manifest known to be a platform's counts (the bundled and ``plugins/platforms/`` dirs); a
+ flat ``plugins/*`` manifest proves it is one only by its content, so an unreadable one is
+ skipped with a warning, as is an unsearchable plugin directory. A manifest that does not
+ parse declares nothing (its adapter cannot load either) and is skipped. Every skip is appended
- to ``skipped``, so a caller can tell a complete scan from a partial one."""
++ to ``skipped``, so a caller can tell a complete scan from a partial one. A safe worker reads
++ no plugin manifest at all."""
++ from agent.safe_worker_policy import safe_worker_enabled
+
++ if safe_worker_enabled():
++ return
+ for dir_name, manifest_path, require_kind, st in _platform_manifest_paths(home, source):
+ if manifest_path is None:
+ logger.warning("Skipping unreadable plugin directory %s: %s", dir_name, st)
+ if skipped is not None:
+ skipped.append(dir_name)
+ continue
+ try:
+ with open(manifest_path, "r", encoding="utf-8-sig") as f:
+ manifest = fast_safe_load(f) or {}
+ except OSError as exc:
+ if strict and not require_kind:
+ raise
+ logger.warning("Skipping unreadable plugin manifest %s: %s", manifest_path, exc)
+ if skipped is not None:
+ skipped.append(str(manifest_path))
+ continue
+ except Exception:
+ if skipped is not None:
+ skipped.append(str(manifest_path))
+ continue
+ if not isinstance(manifest, dict) or (require_kind and manifest.get("kind") != "platform"):
+ continue
+ yield dir_name, manifest
- def _inject_platform_plugin_env_vars() -> None:
- """Populate OPTIONAL_ENV_VARS from platform plugin manifests (bundled AND user-installed) so
- Teams / IRC / Google Chat and third-party platforms are configurable in the ``hermes config`` /
- Desktop Gateway form without the core knowing they exist.
- ``requires_env`` / ``optional_env`` entries are a bare name or a dict with ``name`` plus
- optional ``description``/``url``/``password``/``prompt``/``category``. Failures are swallowed
- so a malformed plugin.yaml can't break CLI import.
- """
- try:
- for dir_name, manifest in _platform_plugin_manifests():
- label = manifest.get("label") or manifest.get("name") or dir_name
- for entry in [*(manifest.get("requires_env") or []), *(manifest.get("optional_env") or [])]:
- meta = {"name": entry} if isinstance(entry, str) else entry if isinstance(entry, dict) else {}
- name = meta.get("name")
- if not name or name in OPTIONAL_ENV_VARS:
- continue # hardcoded entry wins (back-compat)
- # *TOKEN / *SECRET / *KEY / *PASSWORD / *JSON are password fields unless overridden.
- is_secret = bool(meta.get("password") or meta.get("secret"))
- if not is_secret and not meta.get("password") is False:
- is_secret = name.upper().endswith(("_TOKEN", "_SECRET", "_KEY", "_PASSWORD", "_JSON"))
- OPTIONAL_ENV_VARS[name] = {
- "description": meta.get("description") or f"{label} configuration",
- "prompt": meta.get("prompt") or name,
- "url": meta.get("url") or None,
- "password": is_secret,
- "category": meta.get("category") or "messaging"}
- except Exception:
- pass
+ # Env-name suffixes that make a platform variable a secret unless its declaration says otherwise.
+ PLATFORM_SECRET_ENV_SUFFIXES = ("_TOKEN", "_SECRET", "_KEY", "_PASSWORD", "_JSON")
- _inject_platform_plugin_env_vars()
+ def _platform_manifest_env_entries(manifest: dict, *, optional: bool = True):
+ """Yield ``(name, is_secret, meta)`` for a manifest's ``requires_env`` (and, unless
+ ``optional=False``, ``optional_env``) entries (a bare name or a dict with ``name`` plus optional
+ ``description``/``url``/``password``/``prompt``/``category``). A name ending in
+ PLATFORM_SECRET_ENV_SUFFIXES is a password field unless the entry says ``password: false``."""
+ for entry in [*(manifest.get("requires_env") or []), *((manifest.get("optional_env") or []) if optional else [])]:
+ meta = {"name": entry} if isinstance(entry, str) else entry if isinstance(entry, dict) else {}
+ name = meta.get("name")
+ if not name or not isinstance(name, str):
+ continue
+ is_secret = bool(meta.get("password") or meta.get("secret"))
+ if not is_secret and not meta.get("password") is False:
+ is_secret = name.upper().endswith(PLATFORM_SECRET_ENV_SUFFIXES)
+ yield name, is_secret, meta
- # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
- # Names external plugins imported from this module before the Sep 2026 decomposition.
- # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
- # The whole block is removed by reverting the commit that added it.
+ def _manifest_secret_envs(manifests) -> frozenset[str]:
+ """Upper-cased secret messaging env names the given manifests declare, minus core-declared
+ names: a manifest never reclassifies a core variable such as OPENAI_API_KEY."""
+ names = {name.upper() for _dir, manifest in manifests
+ for name, is_secret, meta in _platform_manifest_env_entries(manifest)
+ if is_secret and (meta.get("category") or "messaging") == "messaging"}
+ return frozenset(names - {n.upper() for n in CORE_DECLARED_ENV_NAMES})
- def _install_method_project_root(project_root: Optional[Path] = None) -> Path:
- """Resolve the directory that holds the *running code* (the install tree).
- This is the parent of ``hermes_cli/`` — i.e. the git checkout for source
- installs, ``/opt/hermes`` inside the published image. It is a property of
- the running interpreter, NOT of ``$HERMES_HOME``, which is why a
- code-scoped stamp here is immune to two installs sharing one data
- directory.
- """
- if project_root is not None:
- return project_root
- return Path(__file__).parent.parent.resolve()
+ def platform_manifest_secret_envs(home: Optional[Path] = None, source: PlatformManifestSource = "user", *,
+ strict: bool = False) -> frozenset[str]:
+ """Secret env names declared by one source's platform plugin manifests: ``"user"`` reads only
+ ``home``'s user-installed plugins, which belong to that profile alone; ``"bundled"`` returns
+ the set read once at import (re-read strictly if that read hit an I/O error)."""
+ if source == "bundled" and BUNDLED_PLATFORM_SECRET_ENVS is not None:
+ return BUNDLED_PLATFORM_SECRET_ENVS
+ return _manifest_secret_envs(_platform_plugin_manifests(home, source, strict=strict))
- def stamp_install_method(method: str, project_root: Optional[Path] = None) -> None:
- """Write the install method next to the running code (code-scoped stamp).
- The stamp lives in the install tree (``<install tree>/.install_method``),
- not in ``$HERMES_HOME``, so that two installs sharing one data directory
- do not overwrite each other's marker. See ``detect_install_method`` for
- the full rationale.
+ def platform_manifest_secret_scan(home: Optional[Path] = None) -> "tuple[frozenset[str], bool]":
+ """``home``'s user-installed platform plugin secrets, strictly read, and whether the scan was
+ complete: False when a plugin dir or flat manifest could not be read or parsed, so the caller
+ keeps the denials it already knew instead of releasing them on a failed discovery."""
+ skipped: list = []
+ names = _manifest_secret_envs(_platform_plugin_manifests(home, "user", strict=True, skipped=skipped))
+ return names, not skipped
- Best-effort: if the install tree is read-only (e.g. the immutable
- ``/opt/hermes`` in the published image, which instead bakes the stamp at
- build time) the write silently no-ops and detection falls back to its
- other signals.
+
+ def _inject_platform_plugin_env_vars() -> "frozenset[str] | None":
+ """Populate OPTIONAL_ENV_VARS from platform plugin manifests (bundled AND user-installed) so
+ Teams / IRC / Google Chat and third-party platforms are configurable in the ``hermes config`` /
+ Desktop Gateway form without the core knowing they exist. Failures are swallowed so a
+ malformed plugin.yaml can't break CLI import. Returns the bundled manifests' secret names, or
+ None when a bundled manifest could not be read (the policy then re-reads strictly).
"""
- root = _install_method_project_root(project_root)
+ bundled: "list | None" = []
try:
- root.mkdir(parents=True, exist_ok=True)
- (root / ".install_method").write_text(method + "\n", encoding="utf-8")
+ bundled = list(_platform_plugin_manifests(source="bundled", strict=True))
except OSError:
- pass
-
-
- _PLUGIN_COMPAT_LAZY = {
- 'normalize_route_base_url': ('hermes_cli.route_identity', 'normalize_route_base_url'),
- }
-
-
- def __getattr__(name): # PEP 562 — lazy so no import cycles
- target = _PLUGIN_COMPAT_LAZY.get(name)
- if target is None:
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
- import importlib
- from hermes_cli.plugin_compat import warn_once
- warn_once(__name__, name, *target)
- return getattr(importlib.import_module(target[0]), target[1])
- # ---- END PLUGIN-COMPAT ----
+ bundled = None
+ manifests = list(bundled or [])
+ for source in ("bundled", "user") if bundled is None else ("user",):
+ try:
+ manifests += list(_platform_plugin_manifests(source=source))
+ except Exception:
+ pass
+ for dir_name, manifest in manifests:
+ label = manifest.get("label") or manifest.get("name") or dir_name
+ for name, is_secret, meta in _platform_manifest_env_entries(manifest):
+ if name in OPTIONAL_ENV_VARS:
+ continue # hardcoded entry wins (back-compat)
+ OPTIONAL_ENV_VARS[name] = {
+ "description": meta.get("description") or f"{label} configuration",
+ "prompt": meta.get("prompt") or name,
+ "url": meta.get("url") or None,
+ "password": is_secret,
+ "category": meta.get("category") or "messaging"}
+ return _manifest_secret_envs(bundled) if bundled is not None else None
+
+
+ # Names declared in core, before any platform manifest is read. A manifest never reclassifies
+ # one: the config form keeps the core entry, and the child-env scrub keeps a plugin that lists
+ # OPENAI_API_KEY from turning a provider key into an adapter secret.
+ CORE_DECLARED_ENV_NAMES: frozenset[str] = frozenset(OPTIONAL_ENV_VARS)
+ BUNDLED_PLATFORM_SECRET_ENVS: "frozenset[str] | None" = _inject_platform_plugin_env_vars()
diff --cc hermes_cli/config_defaults.py
index 18956ebc740,fa682523a13..674352b46a4
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@@ -2682,7 -2724,7 +2725,7 @@@ DEFAULT_CONFIG =
# Extra ports detection probes for an external llama-server (besides 8080).
"detect_ports": [],
},
- "_config_version": 47, # Config schema version - bump this when adding new required fields
- "_config_version": 49, # Config schema version - bump this when adding new required fields
++ "_config_version": 50, # Config schema version - bump this when adding new required fields
}
diff --cc hermes_cli/config_migrations.py
index f46e174c4ca,0c620842c4f..62b1c4dc785
--- a/hermes_cli/config_migrations.py
+++ b/hermes_cli/config_migrations.py
@@@ -754,18 -799,21 +799,33 @@@ MIGRATIONS: Tuple[Tuple[int, Callable[[
(45, _migrate_to_45),
# 45 → 46: legacy editor `disabled: true` on MCP servers becomes `enabled: false` (see _migrate_to_46).
(46, _migrate_to_46),
- # 46 → 47: cron.bot_chat_delivery_timeout_seconds is gone with the local `hermes chat`
+ # 46 → 47: compression.threshold_tokens defaults back to null (ratio-only). The briefly shipped
+ # 256000 default was copied into config.yaml by the template seeder and `doctor --fix`, where it
+ # reads as a user choice and keeps capping 1M-window models at 256K. Drop only that exact value;
+ # any other explicit cap, and an explicit null, are preserved.
+ (47, _rewrite_stale_default(
+ section="compression", key="threshold_tokens", old=256000, new=None,
+ added="removed compression.threshold_tokens: 256000 (the old default)",
+ message=(
+ " ✓ Removed compression.threshold_tokens: 256000 — the old default. Compaction "
+ "follows compression.threshold (50% of the window) again. Set threshold_tokens "
+ "to a token count to cap it on purpose."))),
+ # 47 → 48: a saved old-default sandbox image is dropped so the file follows the new default (see _migrate_to_48).
+ (48, _migrate_to_48),
+ # 48 → 49: the seeded Vercel runtime pin is dropped so fresh sandboxes use the managed image (see _migrate_to_49).
+ (49, _migrate_to_49),
++ # 49 → 50: cron.bot_chat_delivery_timeout_seconds is gone with the local `hermes chat`
+ # fallback lane it bounded. Bot Chat deliveries are admitted to the running gateway and
+ # settle on its durable receipt; there is no cron-side turn left to time out.
- (47, functools.partial(
++ (50, functools.partial(
+ _rewrite_key, section="cron", key="bot_chat_delivery_timeout_seconds", new=None,
+ match=lambda _cur: True,
+ added="removed cron.bot_chat_delivery_timeout_seconds",
+ message=(
+ " ✓ Removed cron.bot_chat_delivery_timeout_seconds — bot-chat deliveries are now "
+ "admitted to the target profile's running gateway and tracked by receipt, so cron no "
+ "longer runs (or times out) a Bot Chat turn of its own."),
+ extra_guard=lambda raw: "bot_chat_delivery_timeout_seconds" in raw)),
)
#: Steps triggered by a legacy key or identifier (a renamed or retired key, a removed plugin or
diff --cc hermes_cli/cron.py
index c1b8d892709,f1403a40289..c86ab8e7437
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@@ -288,13 -309,13 +309,16 @@@ def _job_warnings(job: Dict[str, Any])
def cron_tick():
- """Run due jobs once and exit."""
+ """Run due jobs once and exit (external-scheduler mode: a system crontab calls this).
+
+ No gateway runs here by definition, and none is started: agent jobs are skipped with a logged
+ reason until the gateway is up (headless surfaces refuse rather than spawn)."""
from cron.scheduler import CronTickYielded, tick
+ from hermes_cli.observability.shared_metrics_process import begin_process
+
+ begin_process("cron")
try:
- tick(verbose=True)
+ tick(verbose=True, headless=True)
except CronTickYielded as exc:
# Inert for a one-shot CLI (no boot fingerprint); report cleanly rather than traceback.
print(color(f"✗ {exc}", Colors.YELLOW))
diff --cc hermes_cli/main_agent_cmds.py
index f03cdebf8cd,5f27641239e..04c861f8dca
--- a/hermes_cli/main_agent_cmds.py
+++ b/hermes_cli/main_agent_cmds.py
@@@ -122,7 -119,7 +122,9 @@@ def cmd_insights(args)
report = engine.generate(days=args.days, source=args.source)
print(engine.format_terminal(report))
except Exception as e:
-- print(f"Error generating insights: {e}")
++ # Interactive /insights delegates here, so keep main's localized error line.
++ from agent.i18n import t
++ print(t("gateway.insights.error", error=str(e)))
finally:
if db is not None:
try:
diff --cc hermes_cli/plugins.py
index abdae788852,50615143a47..84c220ea10f
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@@ -1302,10 -1279,8 +1279,12 @@@ class PluginManager(PluginLoaderMixin,
def discover_and_load(self, force: bool = False) -> None:
"""Scan all plugin sources and load each plugin found; ``force`` unloads first so config
changes / new bundled backends become visible in long-lived sessions."""
- if plugin_discovery_suppressed():
- return # a config-only read of a profile this process must not load plugins for
+ from agent.safe_worker_policy import safe_worker_enabled
+
- if safe_worker_enabled():
++ if safe_worker_enabled() or plugin_discovery_suppressed():
++ # Safe workers never discover; a config-only read of a profile this process must not
++ # load plugins for is suppressed too.
+ return
if self._discovered and not force and in_plugin_load_worker():
# A plugin whose register() re-enters discovery (importing model_tools does) runs on a
# deadline worker that cannot re-acquire the sweep's RLock; the flag is already set for the
diff --cc hermes_cli/plugins_dispatch.py
index b7c0e523ea4,9c303f12f03..c98219890d7
--- a/hermes_cli/plugins_dispatch.py
+++ b/hermes_cli/plugins_dispatch.py
@@@ -602,24 -588,32 +604,39 @@@ class PluginDispatchMixin
def has_middleware(self, kind: str) -> bool:
"""Return True when at least one callback is registered for middleware."""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return False
return bool(self._middleware.get(kind))
- def invoke_middleware(self, kind: str, **kwargs: Any) -> List[Any]:
- """Call middleware callbacks for *kind* (each isolated); return non-``None`` results."""
+ def invoke_middleware(
+ self, kind: str, *, _payload_key: Optional[str] = None, **kwargs: Any
+ ) -> List[Any]:
+ """Call middleware callbacks for *kind* (each isolated); return non-``None`` results.
+
+ Request middleware passes ``_payload_key``: a dict returned under it becomes the payload the
+ next callback sees, so rewrites compose, and each callback gets its own copy of the payload and
+ of ``original_<key>`` so an in-place edit cannot leak.
+ """
+ from agent.safe_worker_policy import safe_worker_enabled
+ from hermes_cli.middleware import _safe_copy
+ if safe_worker_enabled():
+ return []
results: List[Any] = []
for cb in self._middleware.get(kind, []):
+ call_kwargs = kwargs
+ if _payload_key:
+ original_key = "original_" + _payload_key
+ call_kwargs = {**kwargs, _payload_key: _safe_copy(kwargs[_payload_key]),
+ original_key: _safe_copy(kwargs[original_key])}
try:
- ret = cb(**kwargs)
+ ret = cb(**call_kwargs)
if ret is not None:
results.append(ret)
+ if _payload_key and isinstance(ret, dict) and isinstance(ret.get(_payload_key), dict):
+ kwargs[_payload_key] = ret[_payload_key]
except (Exception, SystemExit) as exc:
# Runs once per tool call like a hook, so a mis-declared callback floods identically.
self._report_hook_failure(kind, cb, kwargs, exc, surface="Middleware")
diff --cc hermes_cli/profiles.py
index 9827f01dd19,77ebe934e4e..edd0a3664e2
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@@ -1250,23 -1328,43 +1328,60 @@@ def _clone_all_into(source_dir: Path, p
)
+def _strip_multiplex_flag(config_path: Path) -> None:
+ """Multiplexing belongs to the default profile; a clone that keeps the flag would start its
+ own multiplexer (or be refused at boot) the first time it runs a gateway."""
+ if not config_path.is_file():
+ return
+ with contextlib.suppress(Exception): # creation must not fail over an unreadable copy
+ from hermes_cli.config import atomic_config_write, read_user_config_raw
+ cfg = read_user_config_raw(config_path)
+ gateway = cfg.get("gateway") if isinstance(cfg.get("gateway"), dict) else {}
+ if "multiplex_profiles" not in cfg and "multiplex_profiles" not in gateway:
+ return
+ cfg.pop("multiplex_profiles", None)
+ gateway.pop("multiplex_profiles", None)
+ if not gateway and "gateway" in cfg:
+ cfg.pop("gateway")
+ # Absent keys are deleted by the round-trip writer; the clone's comments survive.
+ atomic_config_write(config_path, cfg)
+ def _clone_plugins_ignore(plugins_root: Path):
+ """copytree ignore for a cloned ``plugins/``: :func:`_non_exportable_entries` everywhere, plus
+ the installer's in-flight ``.install-*`` / ``.update-*`` staging dirs at the root."""
+ root = str(plugins_root)
+
+ def _ignore(directory: str, names: List[str]) -> set:
+ ignored = _non_exportable_entries(directory, names)
+ if directory == root:
+ # Directories only: ``.install-metadata.json`` shares the prefix and must travel.
+ ignored.update(n for n in names if n.startswith((".install-", ".update-"))
+ and os.path.isdir(os.path.join(directory, n)))
+ return ignored
+ return _ignore
+
+
+ def _clone_plugins(source_dir: Path, profile_dir: Path) -> None:
+ """Copy the source's user-installed plugins (``plugins/`` with ``.install-metadata.json``).
+
+ ``config.yaml`` already carries ``plugins.enabled`` and ``memory.provider``; without the code a
+ catalog-installed memory provider resolves nowhere in the clone, so the clone silently runs
+ without its memory (or, with lazy installs on, re-fetches the latest catalog pin instead of the
+ revision the source runs). The copy keeps each plugin's tree, revision and catalog provenance
+ (the install record). Python dependencies live in the shared venv, where the source's
+ selection of the same plugin already put them."""
+ source_plugins = source_dir / "plugins"
+ if source_plugins.is_dir():
+ _copytree_keep_junctions(source_plugins, profile_dir / "plugins",
+ _clone_plugins_ignore(source_plugins), dirs_exist_ok=True)
+
+
+ def cloned_plugin_names(profile_dir: Path) -> List[str]:
+ """Plugins a clone now carries in ``plugins/``, for the CLI notice."""
+ try:
+ return sorted(p.name for p in (profile_dir / "plugins").iterdir()
+ if not p.name.startswith(".") and (p.is_dir() or p.is_symlink()))
+ except OSError:
+ return []
def _bootstrap_profile_dir(profile_dir: Path, source_dir: Optional[Path],
diff --cc hermes_cli/session_schema_history.py
index fb17853b6f4,cc8943e9bca..3c8ea56511d
--- a/hermes_cli/session_schema_history.py
+++ b/hermes_cli/session_schema_history.py
@@@ -206,12 -206,7 +206,13 @@@ SCHEMA_HISTORY: dict[str, _TableHistory
('27 2026-09-19T00:10Z 922a0c3c87', (('+', 'transport_profile', 'profile_name'),)),
('28 2026-09-25T23:25Z 2941aadffa', (('+', 'compression_overload_streak', 'compression_recovery_deadline'),)),
('29 2026-09-27T00:29Z d75f29934b', (('+', 'created_source', 'source'),)),
+ ('30 2026-09-28T00:00Z #117713', (('+', 'auto_archived', 'archived'),)),
+ # Runtime-authority columns (unified gateway runtime, PR #106742): appended after main's
- # 27-29 because they ship after them on main.
- ('30 2026-09-08T18:45Z 0695b12b4c', (
++ # 27-30 because they ship after them on main.
++ ('31 2026-09-08T18:45Z 0695b12b4c', (
+ ('+', 'runtime_revision', 'id'),
+ ('+', 'runtime_generation', 'runtime_revision'),
+ )),
),
),
"messages": _TableHistory(
diff --cc hermes_cli/turn_exit.py
index 56fdb40efe4,00000000000..fc775926f74
mode 100644,000000..100644
--- a/hermes_cli/turn_exit.py
+++ b/hermes_cli/turn_exit.py
@@@ -1,38 -1,0 +1,42 @@@
+"""Turn-result exit policy shared by CLI views and authority-owned workers.
+
+Worker identity is supplied by the caller, not inferred from a daemon's environment.
+"""
+
+# Provider walls do not spend a Kanban task's retry budget.
+TRANSIENT_PROVIDER_REASONS = frozenset({
+ "rate_limit", "upstream_rate_limit", "billing", "overloaded", "server_error", "timeout",
+})
+# These failures need an operator change; the dispatcher parks the task immediately.
+TERMINAL_PROVIDER_REASONS = frozenset({
+ "auth", "auth_permanent", "model_not_found", "ssl_cert_verification", "upstream_blocked",
+})
+
+
+def turn_exit_code(
+ result, *, kanban_worker: bool, credentials_rate_limited: bool = False,
++ credentials_terminal: bool = False,
+ transient_reasons=TRANSIENT_PROVIDER_REASONS, terminal_reasons=TERMINAL_PROVIDER_REASONS,
+) -> int:
+ """Preserve completion, interruption and retryable/terminal provider outcomes."""
+ if not isinstance(result, dict):
+ if credentials_rate_limited and kanban_worker:
+ from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
+ return KANBAN_RATE_LIMIT_EXIT_CODE
++ if credentials_terminal and kanban_worker:
++ from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
++ return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
+ return 1
+ if result.get("interrupted"):
+ return 130
+ if not (result.get("failed") or result.get("partial") or result.get("completed") is False):
+ return 0
+ if kanban_worker:
+ reason = result.get("failure_reason")
+ if reason in transient_reasons:
+ from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
+ return KANBAN_RATE_LIMIT_EXIT_CODE
+ if reason in terminal_reasons:
+ from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
+ return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
+ return 1
diff --cc hermes_cli/update_cmd.py
index 36f54011d81,48a98e6039d..839f4bfb1be
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@@ -93,10 -100,10 +100,10 @@@ from hermes_cli.update_cmd_git import
_has_upstream_remote, _is_fork, _locate_real_git, _mark_skip_upstream_prompt,
_normalize_managed_eol, _park_detached_head, _portable_git_candidates, _print_fetch_failure,
_print_parked_branch_kept_notice, _print_parked_branch_skip_warning,
- _prune_orphan_rescue_refs, _should_skip_upstream_prompt, _sync_fork_with_upstream,
- _sync_with_upstream_if_needed)
+ _prune_orphan_rescue_refs, _push_synced_fork, _should_skip_upstream_prompt, _sync_fork_with_upstream,
+ _sync_with_upstream_if_needed, UpstreamTargetBroken)
from hermes_cli.update_cmd_maint import ( # noqa: F401
- _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE, _clear_stale_sqlite_sidecars,
+ _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,
_checkout_version, _ensure_acp_launcher, _ensure_fhs_path_guard, _finish_dashboard_update_cleanup,
_format_time_ago, _post_update_sqlite_runtime_status, _print_bundled_skills_sync_report,
_print_curator_first_run_notice, _print_curator_recent_run_notice,
diff --cc hermes_cli/web_models.py
index 5a7e97ef35e,25bab5fb15c..07650189686
--- a/hermes_cli/web_models.py
+++ b/hermes_cli/web_models.py
@@@ -3,9 -3,9 +3,9 @@@
from __future__ import annotations
import math
- from typing import Any, Dict, List, Literal, Optional
+ from typing import Any, Dict, List, Literal, Optional, Union
-from pydantic import BaseModel, SecretStr, StrictBool, field_validator
+from pydantic import BaseModel, Field, SecretStr, StrictBool, StrictInt, field_validator
class ConfigUpdate(BaseModel):
diff --cc hermes_cli/web_routers/sessions.py
index 3bda3ce5229,35918598d9a..d6599d43915
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@@ -744,21 -828,26 +838,29 @@@ async def get_session_messages_around
@manage_router.delete("/api/sessions/{session_id}")
-async def delete_session_endpoint(session_id: str, profile: Optional[str] = None):
- def _delete(db):
- # Already-absent is an idempotent success: the desktop optimistically
- # removes the row and RESTORES it on any error, so a 404 resurrected
- # ghost rows (transient empties racing the sidebar snapshot).
- sid = _resolve_session_id(db, session_id)
- if not sid:
+async def delete_session_endpoint(session_id: str, request: Request, profile: Optional[str] = None,
+ request_id: Optional[str] = None, expected_revision: Optional[int] = None,
+ expected_generation: Optional[int] = None):
+ from hermes_cli.web_server_sessions import _mutate_session_request
+ from hermes_state import SessionDB
- result = await _mutate_session_request(request, profile, session_id,
- request_id=request_id, expected_revision=expected_revision,
- expected_generation=expected_generation, operation='delete', payload={})
++ try:
++ result = await _mutate_session_request(request, profile, session_id,
++ request_id=request_id, expected_revision=expected_revision,
++ expected_generation=expected_generation, operation='delete', payload={})
++ except HTTPException as exc:
++ # Already-absent is an idempotent success: the desktop optimistically removes the row
++ # and RESTORES it on any error, so a 404 resurrected ghost rows (a row deleted by
++ # another client between the sidebar snapshot and this DELETE).
++ if exc.status_code == 404 and exc.detail == 'not_found':
+ return {"ok": True, "already_absent": True}
- try:
- # Chain-aware like bulk-delete: the list row the user clicked represents the
- # whole compression chain (and carries the tip's id), so deleting just this
- # physical row would resurface the conversation as the previous chain link
- # on reload (#57543).
- db.delete_session(sid, sessions_dir=_session_files_dir(profile),
- exclude_active_write_guards=True, include_compression_chain=True)
- except SessionActiveWriteGuardError as exc:
- raise HTTPException(status_code=409, detail=str(exc))
- return {"ok": True}
-
- return await asyncio.to_thread(_with_db, profile, _delete, read_only=False)
++ raise
+ # The canonical delete retires rows only: scrub each deleted session's on-disk artifacts
+ # (secret-bearing ``session_<id>.json`` snapshots, ``request_dump_<id>_*.json``) as the CLI
+ # delete path does (#60207). Idempotent, so an exact retry of the receipt repeats it safely.
+ sessions_dir = _session_files_dir(profile)
+ for sid in result.get('deleted_ids') or ():
+ await asyncio.to_thread(SessionDB._remove_session_files, sessions_dir, str(sid))
+ return result
@manage_router.post("/api/sessions/owner-backfill")
@@@ -845,21 -965,9 +947,11 @@@ async def export_session_endpoint(sessi
@manage_router.post("/api/sessions/prune")
async def prune_sessions_endpoint(body: SessionPrune):
"""Delete ended sessions matching filters without blocking the event loop."""
- if not body.dry_run:
- # Same destructive rule as the rest of the family; a dry run deletes nothing, so it
- # keeps working unnamed (it is the preview the confirm dialog reads).
- body = body.model_copy(update={
- "profile": destructive_profile(body.profile, "POST /api/sessions/prune")})
- return await asyncio.to_thread(_prune_sessions, body)
+ if body.dry_run:
+ return await asyncio.to_thread(_prune_sessions, body)
+ # Same destructive rule as the rest of the family; a dry run deletes nothing, so it
+ # keeps working unnamed (it is the preview the confirm dialog reads).
+ body = body.model_copy(update={
+ "profile": destructive_profile(body.profile, "POST /api/sessions/prune")})
+ from hermes_cli.web_server_sessions import _with_session_maintenance
+ return await asyncio.to_thread(_with_session_maintenance, body.profile, _prune_sessions, body)
-
-
- # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
- # Names external plugins imported from this module before the Sep 2026 decomposition.
- # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
- # The whole block is removed by reverting the commit that added it.
- from typing import Any # noqa: F401,E402
- from typing import Dict # noqa: F401,E402
- import logging # noqa: F401,E402
- # ---- END PLUGIN-COMPAT ----
diff --cc hermes_cli/web_server.py
index 5465896d132,55640470736..928c31330bc
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@@ -187,8 -363,13 +201,13 @@@ def _get_pty_active_session_files(app:
return _app_state_default(app, "pty_active_session_files", dict)
-app = FastAPI(title="Hermes Agent", version=get_version_info().base_version, lifespan=_lifespan)
+app = FastAPI(title="Hermes Agent", version=get_version_info().base_version, lifespan=app_lifespan)
+ from hermes_cli.dashboard_auth.body_limit import AuthBodyLimitMiddleware # noqa: E402
+
+ # Register first (innermost): auth gates run before this, JSON parsing after it.
+ app.add_middleware(AuthBodyLimitMiddleware)
+
# Memory-provider OAuth connect routes live in the memory layer, not here.
from hermes_cli.memory_oauth import router as _memory_oauth_router # noqa: E402
diff --cc hermes_cli/web_server_app.py
index 69fc44ca52b,00000000000..74f4e3445ae
mode 100644,000000..100644
--- a/hermes_cli/web_server_app.py
+++ b/hermes_cli/web_server_app.py
@@@ -1,201 -1,0 +1,225 @@@
+"""HTTP lifespan composition; standalone backend services remain opt-in owners."""
+
+from contextlib import asynccontextmanager
+import asyncio
+import logging
+import os
+import threading
+
+from fastapi import FastAPI
+from hermes_cli.pty_session import run_reaper
+
+_log = logging.getLogger("hermes_cli.web_server")
+
+
++def _unlink_pty_markers(app: FastAPI) -> None:
++ """Second pass after ``PTY_REGISTRY.close_all()``: drop channel markers left in app state,
++ including stale paths from sessions reaped earlier (``PtySession.close()`` only removes
++ markers owned by live registry sessions)."""
++ from hermes_cli.web_server import _get_pty_active_session_files
++
++ for marker in set(_get_pty_active_session_files(app).values()):
++ try:
++ marker.unlink(missing_ok=True)
++ except OSError:
++ pass
++
++
+@asynccontextmanager
+async def standalone_lifespan(app: "FastAPI"):
+ from hermes_cli.web_server import (
+ _eager_reconcile_own_session_db, _warm_gateway_module,
+ _start_desktop_cron_ticker, _dashboard_selftest_loop,
+ _auto_archive_ticker_loop, _terminate_desktop_managed_gateway,
+ )
+ from hermes_cli.web_server_chat import PTY_REGISTRY
+
+ app.state.event_channels = {} # dict[str, set]
+ app.state.event_lock = asyncio.Lock()
+ app.state.pty_active_session_files = {} # dict[str, Path]
+ # Serializes chat-argv resolution so concurrent /api/pty connections don't
+ # overlap ``npm install`` / ``npm run build``. Locks live on app.state (not
+ # module globals) so they bind to the running loop, not the import-time one.
+ app.state.chat_argv_lock = asyncio.Lock()
+
+ # Bring state.db schema current BEFORE the first session-list poll
+ # (#79531/#80037): a store left behind by `hermes update` otherwise 500s
+ # every poll until its owner completes schema reconciliation.
+ # Off-thread so a locked store never delays the socket (Desktop
+ # ready-probe times out at 10s, GH-73083). NOT a daemon, and joined at
+ # shutdown: its sqlite connection must be closed by the thread that is
+ # stepping it. A daemon copy that outlived the lifespan had its
+ # connection closed from the main thread mid-probe (pytest's leaked-DB
+ # sweep) and segfaulted the interpreter. The worker is time-bounded by
+ # SessionDB's lock patience, so the join cannot hang shutdown.
+ eager_reconcile_thread = threading.Thread(
+ target=_eager_reconcile_own_session_db,
+ name="statedb-eager-reconcile",
+ )
+ eager_reconcile_thread.start()
+
+ # Import hermes_cli.gateway *before* the yield: on Windows + 3.11 the
+ # import holds the GIL, so run_in_executor still froze the loop 15-22s and
+ # the Desktop's 10s ready-probe timed out (GH-73083).
+ _warm_gateway_module()
+
+ # Snapshot the checkout revision so lazy-import paths (model picker) can
+ # refuse with "restart required" after `hermes update` replaced the code
+ # (#86207); the update flow does not reliably restart the dashboard.
+ from gateway.code_skew import record_boot_fingerprint
+
+ record_boot_fingerprint()
+
+ # Hosted Bot rooms belong to the backend process. Recovery may need a
+ # contended state.db migration, so keep it off the pre-yield path: Group
+ # Chat must degrade on its own rather than block every Desktop feature.
+ from tui_gateway import methods_groups as _hosted_groups
+ import tui_gateway.server # noqa: F401
+
+ try:
+ tui_gateway.server.install_tui_message_injector()
+ except Exception:
+ _log.warning("TUI message injector did not install", exc_info=True)
+
+ hosted_room_start_cancel = threading.Event()
+
+ def _start_hosted_rooms() -> None:
+ try:
+ _hosted_groups.start_hosted_room_service()
+ except Exception:
+ _log.exception("Hosted Group Chat recovery failed during backend startup")
+ finally:
+ if hosted_room_start_cancel.is_set():
+ _hosted_groups.stop_hosted_room_service(timeout=1.0)
+
+ hosted_room_start_thread = threading.Thread(
+ target=_start_hosted_rooms,
+ daemon=True,
+ name="hosted-room-startup",
+ )
+ hosted_room_start_thread.start()
+
+ # Desktop-spawned backends fire cron jobs themselves, since the app has no
+ # gateway running the scheduler. Server `hermes dashboard` is unaffected —
+ # it relies on its own gateway.
+ from hermes_cli.process_identity import is_desktop_owned_backend
+ cron_stop: "threading.Event | None" = None
+ cron_thread: "threading.Thread | None" = None
+ desktop_owned = is_desktop_owned_backend()
+ if desktop_owned:
+ # Reap an orphaned gateway from an abnormal previous exit (reparented to
+ # launchd, still holding the platform WebSocket) before forking a fresh
+ # one that would race the same credential (#77276). Runs
+ # unconditionally; protection of a healthy standalone gateway lives
+ # INSIDE the reaper (registration probed with cleanup_stale=False).
+ # Startup grace: spare a gateway still claiming gateway.pid/lock (#122533).
+ try:
+ from hermes_cli.dashboard_procs import _REAP_MIN_AGE_SECONDS
+ from hermes_cli.gateway import _reap_unsupervised_gateway_orphans
+
+ _reap_unsupervised_gateway_orphans(min_age_s=_REAP_MIN_AGE_SECONDS)
+ except Exception:
+ _log.exception("Desktop startup: orphan gateway reap failed")
+
+ cron_stop = threading.Event()
+ cron_thread = threading.Thread(
+ target=_start_desktop_cron_ticker,
+ args=(cron_stop,),
+ daemon=True,
+ name="desktop-cron-ticker",
+ )
+ cron_thread.start()
+
+ # Reap idle/dead keep-alive PTY sessions (30-min TTL).
+ pty_reaper_task = asyncio.create_task(run_reaper(PTY_REGISTRY))
+ # Periodic authenticated self-test feeding the ``dashboard`` component on /api/status.
+ selftest_task = asyncio.create_task(_dashboard_selftest_loop())
+ # Live auto-archive timer, independent of list requests.
+ auto_archive_task = asyncio.create_task(_auto_archive_ticker_loop())
+
+ # Managed local runtime (local_runtime.enabled): bring llama-server back so a
+ # restart doesn't strand a llamacpp main model. Off-thread and best-effort;
+ # failure falls back to cloud providers like a cold start. Server only —
+ # models load on first inference (an empty router holds no VRAM).
+ def _boot_local_runtime():
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.local_runtime.bootstrap import ensure_local_runtime
+
+ ensure_local_runtime(load_config())
+ except Exception as exc: # noqa: BLE001
+ logging.getLogger(__name__).warning("local runtime boot failed: %s", exc)
+
+ threading.Thread(target=_boot_local_runtime, daemon=True, name="local-runtime-boot").start()
+
++ # Nous free tier: the ONE place its identity is created. Inventories credentials, mints only
++ # when HERMES_GUEST_ONBOARDING=1, records the answer for setup.status / free_tier.status and
++ # broadcasts `setup.ready`. Off-thread so a slow portal never delays the socket; the desktop's
++ # first setup.status waits on the record (bounded) instead.
+ from hermes_cli.free_tier_bootstrap import start_background_bootstrap
+
+ start_background_bootstrap()
+
+ try:
+ yield
+ finally:
+ try:
+ tui_gateway.server.clear_tui_message_injector()
+ except Exception:
+ _log.debug("TUI message injector clear skipped", exc_info=True)
+ hosted_room_start_cancel.set()
+ _hosted_groups.stop_hosted_room_service(timeout=5.0)
+ hosted_room_start_thread.join(timeout=1.0)
+ if cron_stop is not None:
+ cron_stop.set()
+ pty_reaper_task.cancel()
+ selftest_task.cancel()
+ auto_archive_task.cancel()
+ eager_reconcile_thread.join()
+ await PTY_REGISTRY.close_all()
++
++ # PtySession.close() removes markers owned by live registry sessions.
++ # This second pass cleans any channel markers left in app state,
++ # including stale paths from sessions reaped earlier.
++ _unlink_pty_markers(app)
++
+ # Stop the managed llama-server with its parent (an orphan pins VRAM).
+ try:
+ from hermes_cli.local_runtime.bootstrap import shutdown_local_runtime
+
+ shutdown_local_runtime()
+ except Exception: # noqa: BLE001
+ pass
+ if desktop_owned:
+ _terminate_desktop_managed_gateway()
+
+
+@asynccontextmanager
+async def http_lifespan(app: FastAPI):
+ """The gateway already owns schema, rooms, scheduler and model services."""
+ from hermes_cli.web_server import _dashboard_selftest_loop
+ from hermes_cli.web_server_chat import PTY_REGISTRY
+
+ app.state.event_channels = {}
+ app.state.event_lock = asyncio.Lock()
+ app.state.pty_active_session_files = {}
+ app.state.chat_argv_lock = asyncio.Lock()
+ tasks = [
+ asyncio.create_task(run_reaper(PTY_REGISTRY), name="gateway-api-pty-reaper"),
+ asyncio.create_task(_dashboard_selftest_loop(), name="gateway-api-selftest"),
+ ]
+ try:
+ yield
+ finally:
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ await PTY_REGISTRY.close_all()
++ _unlink_pty_markers(app)
+
+
+@asynccontextmanager
+async def app_lifespan(app: FastAPI):
+ lifespan = http_lifespan if getattr(app.state, "gateway_runner", None) is not None else standalone_lifespan
+ async with lifespan(app):
+ yield
diff --cc hermes_state_compression.py
index f9d80d68648,dc53551d2f8..09d58a4f0c0
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@@ -208,6 -218,6 +218,9 @@@ class SessionCompressionMixin
_insert_session_row's compression-fork backfill: the child stays on the parent's profile and keeps
gateway routing/origin columns; no owner on either side -> this store's profile."""
system_prompt_hash = self._store_system_prompt(conn, system_prompt)
++ # Pin/archive are compression-lineage flags; canonical branch/reset verbs also publish through
++ # here, and their child is its own conversation, so it starts unpinned and visible.
++ continuation = not any(k in (model_config or {}) for k in ("_branched_from", "_reset_from"))
# The child continues the parent's tools[] pin (the compaction refresh re-pinned it just
# before publish), or its first hop to another surface re-derives the array.
conn.execute(
@@@ -224,7 -235,12 +238,13 @@@
parent["git_repo_root"],
profile_name or parent["profile_name"] or self._own_profile_name(),
parent["user_id"], parent["session_key"], parent["chat_id"], parent["chat_type"],
- parent["thread_id"], parent["display_name"], parent["origin_json"], time.time()),
+ parent["thread_id"], parent["display_name"], parent["origin_json"],
+ # The pin is lineage-wide (set_session_pinned); a segment published after it joins it.
- int(parent["pinned"] or 0), time.time(),
++ int(parent["pinned"] or 0) if continuation else 0, time.time(),
+ # Inherit the lineage's archive state so a manually archived chat stays uniformly
+ # archived (a mixed lineage let the sweep re-stamp its fresh tip as auto-archived).
- parent["archived"] or 0, parent["auto_archived"] or 0),
++ (parent["archived"] or 0) if continuation else 0,
++ (parent["auto_archived"] or 0) if continuation else 0),
)
def publish_compression_child(
@@@ -247,70 -265,77 +269,93 @@@
See #75316.
``None`` = unbounded (no internal flush happened). See #47202.
"""
++ self._execute_transcript_write(lambda conn: self._publish_compression_child_on_conn(
++ conn, parent_session_id=parent_session_id, child_session_id=child_session_id, source=source,
++ messages=messages, model=model, model_config=model_config, system_prompt=system_prompt,
++ cwd=cwd, profile_name=profile_name, compression_lock_holder=compression_lock_holder,
++ require_compression_lease=require_compression_lease, require_lease_refresh=require_lease_refresh,
++ lease_ttl_seconds=lease_ttl_seconds, watermark=watermark, watermark_ceiling=watermark_ceiling), messages)
++
++ def _publish_compression_child_on_conn(
++ self, conn, *, parent_session_id: str, child_session_id: str, source: str,
++ messages: List[Dict[str, Any]], model: str = None, model_config: Dict[str, Any] = None,
++ system_prompt: str = None, cwd: str = None, profile_name: str = None,
++ compression_lock_holder: str = None, require_compression_lease: bool = True,
++ require_lease_refresh: bool = False, lease_ttl_seconds: float = 300.0,
++ watermark: Optional[int] = None, watermark_ceiling: Optional[int] = None) -> None:
++ """:meth:`publish_compression_child` on the caller's write transaction (never commits). The
++ owner and the worker/canonical-mutation verbs share this one body so they cannot drift."""
from hermes_state_errors import CompressionSessionBusyError
-- def _do(conn):
-- if require_lease_refresh and compression_lock_holder:
-- conn.execute(
-- "UPDATE compression_locks SET expires_at = ? WHERE session_id = ? AND holder = ?",
-- (time.time() + lease_ttl_seconds, parent_session_id, compression_lock_holder))
-- lock_row = conn.execute(_LOCK_ROW_SQL, (parent_session_id,)).fetchone()
-- if require_compression_lease and (
-- lock_row is None or not compression_lock_holder
-- or lock_row["holder"] != compression_lock_holder
-- or float(lock_row["expires_at"]) <= time.time()
-- ):
-- raise CompressionSessionBusyError(
-- f"Compression lease lost before publication: {parent_session_id}")
-- parent = conn.execute(
-- """SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,
-- user_id, session_key, chat_id, chat_type,
- thread_id, display_name, origin_json, profile_name, tool_names
- thread_id, display_name, origin_json, profile_name, tool_names,
- archived, auto_archived, pinned
-- FROM sessions WHERE id = ?""",
-- (parent_session_id,),
-- ).fetchone()
-- if parent is None:
-- raise RuntimeError(f"Compression parent not found: {parent_session_id}")
-- if parent["ended_at"] is not None:
-- # An AUTOMATIC end stamp (tui_shutdown, ws_disconnect, orphan reap, idle/LRU
-- # evict) is stale by construction — this lease holder is still continuing the
-- # conversation, and left alone it wedges rotation forever. Clear it; the closure
-- # UPDATE below re-stamps end_reason='compression'. Deliberate boundaries fail closed.
-- if not is_automatic_end_reason(parent["end_reason"]):
-- raise RuntimeError(f"Compression parent already ended: {parent_session_id}")
-- conn.execute(
-- "UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?",
-- (parent_session_id,))
-- if not messages:
-- raise RuntimeError("Compression child handoff must not be empty")
-- self._publish_child_session_row(
-- conn, parent, parent_session_id=parent_session_id, child_session_id=child_session_id,
-- source=source, model=model, model_config=model_config, system_prompt=system_prompt,
-- cwd=cwd, profile_name=profile_name)
- # Carried handoff tail rows arrive without a timestamp and would otherwise be stamped
- # `now`, breaking their _display_dedupe_key identity with the parent's durable originals
- # and duplicating them in the lineage display read (#59661).
- self._carry_parent_timestamps(conn, parent_session_id, messages)
-- total_messages, total_tool_calls = self._insert_message_rows(conn, child_session_id, messages)
-- if watermark is not None:
-- # Clone the parent's concurrent tail into the child after the handoff;
-- # originals stay in the closed parent for lineage recovery.
-- bounded = watermark_ceiling is not None
-- tail_ids, tail_tool_calls = self._tail_rows_after_watermark(
-- conn, "SELECT id, tool_calls FROM messages "
-- "WHERE session_id = ? AND active = 1 AND id > ?"
-- f"{' AND id <= ?' if bounded else ''} ORDER BY id",
-- [parent_session_id, int(watermark), *([int(watermark_ceiling)] if bounded else [])])
-- if tail_ids:
-- self._clone_message_rows(conn, tail_ids, session_id=child_session_id)
-- total_messages += len(tail_ids)
-- total_tool_calls += tail_tool_calls
++ if require_lease_refresh and compression_lock_holder:
conn.execute(
-- "UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?",
-- (total_messages, total_tool_calls, child_session_id))
-- updated = conn.execute(
-- "UPDATE sessions SET ended_at = ?, end_reason = 'compression' "
-- "WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id))
-- if updated.rowcount != 1:
-- raise RuntimeError(f"Compression parent changed during publication: {parent_session_id}")
- from hermes_state_local_lineage import advance_local_target
- advance_local_target(conn, parent_session_id, child_session_id)
- if parent["archived"]:
- # A live continuation under an idle-sweep archive re-activates the chat; after the
- # closure above the child is linked into the lineage walk (#117713).
- self._unarchive_auto_archived_lineage(conn, child_session_id)
-- self._execute_transcript_write(_do, messages)
++ "UPDATE compression_locks SET expires_at = ? WHERE session_id = ? AND holder = ?",
++ (time.time() + lease_ttl_seconds, parent_session_id, compression_lock_holder))
++ lock_row = conn.execute(_LOCK_ROW_SQL, (parent_session_id,)).fetchone()
++ if require_compression_lease and (
++ lock_row is None or not compression_lock_holder
++ or lock_row["holder"] != compression_lock_holder
++ or float(lock_row["expires_at"]) <= time.time()
++ ):
++ raise CompressionSessionBusyError(
++ f"Compression lease lost before publication: {parent_session_id}")
++ parent = conn.execute(
++ """SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,
++ user_id, session_key, chat_id, chat_type,
++ thread_id, display_name, origin_json, profile_name, tool_names,
++ archived, auto_archived, pinned
++ FROM sessions WHERE id = ?""",
++ (parent_session_id,),
++ ).fetchone()
++ if parent is None:
++ raise RuntimeError(f"Compression parent not found: {parent_session_id}")
++ if parent["ended_at"] is not None:
++ # An AUTOMATIC end stamp (tui_shutdown, ws_disconnect, orphan reap, idle/LRU
++ # evict) is stale by construction — this lease holder is still continuing the
++ # conversation, and left alone it wedges rotation forever. Clear it; the closure
++ # UPDATE below re-stamps end_reason='compression'. Deliberate boundaries fail closed.
++ if not is_automatic_end_reason(parent["end_reason"]):
++ raise RuntimeError(f"Compression parent already ended: {parent_session_id}")
++ conn.execute(
++ "UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?",
++ (parent_session_id,))
++ if not messages:
++ raise RuntimeError("Compression child handoff must not be empty")
++ self._publish_child_session_row(
++ conn, parent, parent_session_id=parent_session_id, child_session_id=child_session_id,
++ source=source, model=model, model_config=model_config, system_prompt=system_prompt,
++ cwd=cwd, profile_name=profile_name)
++ # Carried handoff tail rows arrive without a timestamp and would otherwise be stamped
++ # `now`, breaking their _display_dedupe_key identity with the parent's durable originals
++ # and duplicating them in the lineage display read (#59661).
++ self._carry_parent_timestamps(conn, parent_session_id, messages)
++ total_messages, total_tool_calls = self._insert_message_rows(conn, child_session_id, messages)
++ if watermark is not None:
++ # Clone the parent's concurrent tail into the child after the handoff;
++ # originals stay in the closed parent for lineage recovery.
++ bounded = watermark_ceiling is not None
++ tail_ids, tail_tool_calls = self._tail_rows_after_watermark(
++ conn, "SELECT id, tool_calls FROM messages "
++ "WHERE session_id = ? AND active = 1 AND id > ?"
++ f"{' AND id <= ?' if bounded else ''} ORDER BY id",
++ [parent_session_id, int(watermark), *([int(watermark_ceiling)] if bounded else [])])
++ if tail_ids:
++ self._clone_message_rows(conn, tail_ids, session_id=child_session_id)
++ total_messages += len(tail_ids)
++ total_tool_calls += tail_tool_calls
++ conn.execute(
++ "UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?",
++ (total_messages, total_tool_calls, child_session_id))
++ updated = conn.execute(
++ "UPDATE sessions SET ended_at = ?, end_reason = 'compression' "
++ "WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id))
++ if updated.rowcount != 1:
++ raise RuntimeError(f"Compression parent changed during publication: {parent_session_id}")
++ from hermes_state_local_lineage import advance_local_target
++ advance_local_target(conn, parent_session_id, child_session_id)
++ if parent["archived"]:
++ # A live continuation under an idle-sweep archive re-activates the chat; after the
++ # closure above the child is linked into the lineage walk (#117713).
++ self._unarchive_auto_archived_lineage(conn, child_session_id)
def _write_sql_logged(self, op: str, session_id: str, sql: str, params) -> None:
"""``_write_sql`` that logs (never raises) on ``sqlite3.Error``."""
diff --cc hermes_state_gateway.py
index 89097b756b7,70c01d47423..125d365311b
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@@ -372,37 -378,46 +380,57 @@@ class SessionGatewayMixin
return entry
return None
-- def _delete_routing_entries_for_sessions(self, session_ids: Set[str]) -> int:
-- """Drop ``gateway_routing`` rows pointing at any of *session_ids*; the target id
-- lives only inside ``entry_json``, so matching is done in Python over all scopes."""
++ def _routing_entries_for_sessions(self, session_ids: Set[str]) -> List[Tuple[str, str, str]]:
++ """``(scope, session_key, session_id)`` of ``gateway_routing`` rows pointing at any of
++ *session_ids*; the target id lives only inside ``entry_json``, so matching is in Python."""
++ found: List[Tuple[str, str, str]] = []
if not session_ids:
-- return 0
-- doomed: List[Tuple[str, str]] = []
++ return found
for row in self._read_all("SELECT scope, session_key, entry_json FROM gateway_routing"):
try:
entry = json.loads(row["entry_json"] or "{}")
except Exception:
continue
if isinstance(entry, dict) and entry.get("session_id") in session_ids:
-- doomed.append((row["scope"], row["session_key"]))
++ found.append((row["scope"], row["session_key"], entry["session_id"]))
++ return found
++
++ def _delete_routing_entries_for_sessions(self, session_ids: Set[str]) -> int:
++ """Drop ``gateway_routing`` rows pointing at any of *session_ids*."""
++ doomed = [(scope, key) for scope, key, _ in self._routing_entries_for_sessions(session_ids)]
if not doomed:
return 0
self._write_sql("DELETE FROM gateway_routing WHERE scope = ? AND session_key = ?", doomed, many=True)
return len(doomed)
def prune_never_active_keyed_sessions(
- self, *, older_than_days: float, sessions_dir: Optional[Path] = None) -> Tuple[int, int]:
+ self, *, older_than_days: float, sessions_dir: Optional[Path] = None) -> Tuple[int, int, int]:
"""Delete never-active keyed rows and the routing entries naming them; returns
- ``(sessions_deleted, routing_entries_deleted)``. Routing entries go first: a stale
- entry outliving its target would have the gateway resume a nonexistent id.
- Deletion goes through :meth:`delete_session` (delegate cascade, FTS, transcripts)."""
+ ``(sessions_deleted, routing_entries_deleted, sessions_skipped)``. Deletion goes through
+ :meth:`delete_sessions` (one transaction; delegate cascade, FTS, transcripts).
+ Rows under a live turn lease or compression lock are skipped (#123583): the
+ never-active predicate reads committed state, so a keyed row whose first turn lease
+ is already held — its messages not yet flushed — would otherwise be deleted
+ mid-turn. Routing entries are dropped only after the rows commit, for every
+ candidate except the guarded ones: rows that vanished concurrently are gone too,
+ and a stale entry outliving its target would have the gateway resume a
+ nonexistent id. The row sweep is one transaction; routing entries are dropped in a
+ second write after it commits. ``sessions_skipped`` counts only the guarded rows."""
candidates = self.list_never_active_keyed_sessions(older_than_days=older_than_days)
if not candidates:
- return (0, 0)
+ return (0, 0, 0)
ids = {str(row["id"]) for row in candidates}
- routing_deleted = self._delete_routing_entries_for_sessions(ids)
- deleted = sum(1 for sid in ids if self.delete_session(sid, sessions_dir=sessions_dir))
- return (deleted, routing_deleted)
+ skipped: List[str] = []
++ # ``delete_sessions`` retires the deleted rows' routing entries inside its own transaction
++ # (``retire_routes``), so count what pointed at the candidates before it commits; the
++ # follow-up sweep then only catches entries a concurrent writer re-added.
++ routed_before = self._routing_entries_for_sessions(ids)
+ deleted = self.delete_sessions(
+ list(ids), sessions_dir=sessions_dir, exclude_active_write_guards=True, skipped_ids=skipped)
- routing_deleted = self._delete_routing_entries_for_sessions(ids - set(skipped))
++ kept = set(skipped)
++ self._delete_routing_entries_for_sessions(ids - kept)
++ routing_deleted = sum(1 for _, _, sid in routed_before if sid not in kept)
+ return (deleted, routing_deleted, len(skipped))
def list_gateway_sessions(
self, *, platform: Optional[str] = None, active_only: bool = True) -> List[Dict[str, Any]]:
diff --cc hermes_state_messages.py
index 826b69b3bcb,3abd3ac1dfd..57d82c83423
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@@ -1030,56 -1013,62 +1018,74 @@@ class SessionMessagesMixin
index the clones naturally), and the originals are archived. NOTE: re-sequencing assigns the tail
rows fresh ids; consumers that reference durable row ids re-resolve by content (see 3e8ab0610).
"""
++ return self._execute_transcript_write(lambda conn: self._archive_and_compact_on_conn(
++ conn, session_id, compacted_messages, model_config_patch=model_config_patch,
++ watermark=watermark, lock_holder=lock_holder, tail_count=tail_count,
++ carried_messages=carried_messages, covered_ids=covered_ids, unresolved_held=unresolved_held), compacted_messages)
++
++ def _archive_and_compact_on_conn(
++ self, conn, session_id: str, compacted_messages: List[Dict[str, Any]], *,
++ model_config_patch: Optional[Dict[str, Any]] = None, watermark: Optional[int] = None,
++ lock_holder: Optional[str] = None, tail_count: int = 0,
++ carried_messages: Optional[List[Dict[str, Any]]] = None,
++ covered_ids: Optional[List[int]] = None,
++ unresolved_held: Optional[List[Dict[str, Any]]] = None) -> int:
++ """:meth:`archive_and_compact` on the caller's write transaction (never commits). The owner
++ and the worker/canonical-mutation verbs share this one body so they cannot drift."""
from hermes_state import SessionCompressionInProgressError
-- def _do(conn):
-- if lock_holder is not None:
-- lock_row = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone()
-- if lock_row is None or lock_row["holder"] != lock_holder or float(lock_row["expires_at"]) <= time.time():
-- raise SessionCompressionInProgressError(
-- f"Compression lease for {session_id!r} lost before commit; refusing to publish a stale compaction")
-- patch = model_config_patch is not None
-- # on_missing="raise": never commit against a vanished session row (caller keeps the original).
-- patched_model_config = self._merge_model_config_json(
-- conn, session_id, model_config_patch, on_missing="raise") if patch else None
- proved = self._proved_coverage(conn, session_id, covered_ids, unresolved_held)
- proved = self._proved_coverage(conn, session_id, covered_ids, unresolved_held, watermark)
-- if proved is not None:
-- return self._archive_named_rows(
- conn, session_id, compacted_messages, proved, tail_count=tail_count,
- carried_messages=carried_messages, patched_model_config=patched_model_config, patch=patch)
- conn, session_id, compacted_messages, proved[0], tail_count=tail_count,
- carried_messages=carried_messages, patched_model_config=patched_model_config, patch=patch,
- merged_away=proved[1])
-- tail_ids, tail_tool_calls = ([], 0) if watermark is None else self._tail_rows_after_watermark(
-- conn, "SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ? ORDER BY id",
-- (session_id, int(watermark)))
-- # Rewind targets sit AT/BELOW the watermark (all the compressor saw); unbounded, a
-- # concurrent append would steal a LIMIT slot.
-- rewind_ids: list[int] = self._resolve_carried_row_ids(
-- conn, session_id, carried_messages or [])
-- if tail_count > 0:
-- bound = watermark is not None
-- rewind_ids += [int(row["id"]) for row in conn.execute(
-- f"SELECT id FROM messages WHERE session_id = ? AND active = 1{' AND id <= ?' if bound else ''} "
-- "ORDER BY id DESC LIMIT ?",
- (session_id, *((int(watermark),) if bound else ()), int(tail_count))).fetchall()]
- (session_id, *((int(watermark),) if bound else ()),
- int(tail_count) + self._uncounted_merged_rows(compacted_messages[-int(tail_count):]))).fetchall()]
-- rewind_ids += tail_ids
-- rewind_ids = list(dict.fromkeys(rewind_ids))
-- if rewind_ids:
-- placeholders = _placeholders(rewind_ids)
-- conn.execute("UPDATE messages SET active = 0, compacted = 0 "
-- f"WHERE session_id = ? AND id IN ({placeholders})", [session_id, *rewind_ids])
-- conn.execute(f"{_ARCHIVE_ACTIVE_SQL} AND id NOT IN ({placeholders})", [session_id, *rewind_ids])
-- else:
-- conn.execute(_ARCHIVE_ACTIVE_SQL, (session_id,))
- # Same identity carry as publish_compression_child (#59661): carried tail copies keep the
- # durable row's timestamp so display dedupe still collapses generations. Donors are active-only;
- # the rewound/archived originals above never donate, so this is a no-op for a clean compaction.
- self._carry_parent_timestamps(conn, session_id, compacted_messages)
-- inserted, tool_calls_total = self._insert_message_rows(conn, session_id, compacted_messages)
-- if tail_ids:
-- self._clone_message_rows(conn, tail_ids)
-- inserted += len(tail_ids)
-- tool_calls_total += tail_tool_calls
-- # A carried copy whose stored identity was computed differently lands in its own
-- # display_order group and would project twice; re-fold before publishing (#122167).
-- self._reconcile_display_orders(conn, session_id)
-- conn.execute(f"{_SET_COUNTERS_SQL}{', model_config = ?' if patch else ''} WHERE id = ?",
-- (inserted, tool_calls_total, *((patched_model_config,) if patch else ()), session_id))
-- return inserted
-- return self._execute_transcript_write(_do, compacted_messages)
++ if lock_holder is not None:
++ lock_row = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone()
++ if lock_row is None or lock_row["holder"] != lock_holder or float(lock_row["expires_at"]) <= time.time():
++ raise SessionCompressionInProgressError(
++ f"Compression lease for {session_id!r} lost before commit; refusing to publish a stale compaction")
++ patch = model_config_patch is not None
++ # on_missing="raise": never commit against a vanished session row (caller keeps the original).
++ patched_model_config = self._merge_model_config_json(
++ conn, session_id, model_config_patch, on_missing="raise") if patch else None
++ proved = self._proved_coverage(conn, session_id, covered_ids, unresolved_held, watermark)
++ if proved is not None:
++ return self._archive_named_rows(
++ conn, session_id, compacted_messages, proved[0], tail_count=tail_count,
++ carried_messages=carried_messages, patched_model_config=patched_model_config, patch=patch,
++ merged_away=proved[1])
++ tail_ids, tail_tool_calls = ([], 0) if watermark is None else self._tail_rows_after_watermark(
++ conn, "SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ? ORDER BY id",
++ (session_id, int(watermark)))
++ # Rewind targets sit AT/BELOW the watermark (all the compressor saw); unbounded, a
++ # concurrent append would steal a LIMIT slot.
++ rewind_ids: list[int] = self._resolve_carried_row_ids(
++ conn, session_id, carried_messages or [])
++ if tail_count > 0:
++ bound = watermark is not None
++ rewind_ids += [int(row["id"]) for row in conn.execute(
++ f"SELECT id FROM messages WHERE session_id = ? AND active = 1{' AND id <= ?' if bound else ''} "
++ "ORDER BY id DESC LIMIT ?",
++ (session_id, *((int(watermark),) if bound else ()),
++ int(tail_count) + self._uncounted_merged_rows(compacted_messages[-int(tail_count):]))).fetchall()]
++ rewind_ids += tail_ids
++ rewind_ids = list(dict.fromkeys(rewind_ids))
++ if rewind_ids:
++ placeholders = _placeholders(rewind_ids)
++ conn.execute("UPDATE messages SET active = 0, compacted = 0 "
++ f"WHERE session_id = ? AND id IN ({placeholders})", [session_id, *rewind_ids])
++ conn.execute(f"{_ARCHIVE_ACTIVE_SQL} AND id NOT IN ({placeholders})", [session_id, *rewind_ids])
++ else:
++ conn.execute(_ARCHIVE_ACTIVE_SQL, (session_id,))
++ # Same identity carry as publish_compression_child (#59661): carried tail copies keep the
++ # durable row's timestamp so display dedupe still collapses generations. Donors are active-only;
++ # the rewound/archived originals above never donate, so this is a no-op for a clean compaction.
++ self._carry_parent_timestamps(conn, session_id, compacted_messages)
++ inserted, tool_calls_total = self._insert_message_rows(conn, session_id, compacted_messages)
++ if tail_ids:
++ self._clone_message_rows(conn, tail_ids)
++ inserted += len(tail_ids)
++ tool_calls_total += tail_tool_calls
++ # A carried copy whose stored identity was computed differently lands in its own
++ # display_order group and would project twice; re-fold before publishing (#122167).
++ self._reconcile_display_orders(conn, session_id)
++ conn.execute(f"{_SET_COUNTERS_SQL}{', model_config = ?' if patch else ''} WHERE id = ?",
++ (inserted, tool_calls_total, *((patched_model_config,) if patch else ()), session_id))
++ return inserted
def _message_column_names(self, conn) -> List[str]:
"""Column names of the messages table, cached per-connection era."""
@@@ -1744,16 -1842,44 +1863,24 @@@
``expected_active_ids`` / ``expected_target_content`` pin the active set and canonical live payload
in-txn before any mutation (presentation-only metadata changes don't invalidate a rewind). A live turn
lease refuses; expired/dead holders are reclaimed. ``rewind_count`` always increments."""
+ from hermes_state_mutation_transcript import rewind_in_transaction
def _do(conn):
- return rewind_in_transaction(self, conn, session_id, target_message_id,
- self._check_transcript_write_guards(
- conn, session_id, None, reject_active_turn_lease=True, reject_active_compression_lock=True)
- if expected_active_ids is not None:
- active_rows = conn.execute(_ACTIVE_IDS_SQL, (session_id,)).fetchall()
- if [int(r[0]) for r in active_rows] != expected_active_ids:
- raise RuntimeError("active transcript changed before the rewind could be persisted")
- row = conn.execute(
- "SELECT * FROM messages WHERE id = ? AND session_id = ?", (target_message_id, session_id)).fetchone()
- if row is None:
- raise ValueError(f"message {target_message_id} not found in session {session_id}")
- target_row = dict(row)
- if target_row.get("role") != "user":
- raise ValueError(
- f"rewind target must be a 'user' message (got role={target_row.get('role')!r}, id={target_message_id})")
- replacement = None
- if preserve_compaction_handoff or expected_target_content is not None:
- replacement = self._split_rewind_target(target_row, expected_target_content, preserve_compaction_handoff)
- ids = [r[0] for r in conn.execute("SELECT id FROM messages WHERE session_id = ? AND id >= ? AND active = 1",
- (session_id, target_message_id)).fetchall()]
- if ids:
- conn.execute(f"UPDATE messages SET active = 0 WHERE id IN ({_placeholders(ids)})", ids)
- if replacement is not None:
- self._insert_message_rows(conn, session_id, [replacement]) # stamps _row_id and message_uid
- conn.execute(
- "UPDATE sessions SET rewind_count = COALESCE(rewind_count, 0) + 1 WHERE id = ?", (session_id,))
- message_count, tool_call_count = self._active_transcript_counts(conn, session_id)
- conn.execute(f"{_SET_COUNTERS_SQL} WHERE id = ?", (message_count, tool_call_count, session_id))
- head_id = conn.execute(
- "SELECT MAX(id) FROM messages WHERE session_id = ? AND active = 1", (session_id,)).fetchone()[0]
- return target_row, ids, head_id, replacement
- target_row, rewound, new_head_id, replacement = self._execute_write(_do)
++ target_row, ids, head_id, replacement_id = rewind_in_transaction(
++ self, conn, session_id, target_message_id,
+ preserve_compaction_handoff=preserve_compaction_handoff,
+ expected_active_ids=expected_active_ids, expected_target_content=expected_target_content)
- target_row, rewound, new_head_id, replacement_message_id = self._execute_write(_do)
++ # The scaffold insert stamped a ``message_uid``; read it back in the same txn so the
++ # caller can address the new head by its durable identity.
++ replacement_uid = replacement_id and conn.execute(
++ "SELECT message_uid FROM messages WHERE id = ?", (replacement_id,)).fetchone()[0]
++ return target_row, ids, head_id, replacement_id, replacement_uid
++ target_row, rewound, new_head_id, replacement_message_id, replacement_message_uid = self._execute_write(_do)
# Decode for the prompt-buffer prefill without a second fallible DB operation.
target_row["content"] = self._decode_content(target_row.get("content"))
return {"rewound_count": len(rewound), "target_message": target_row, "new_head_id": new_head_id,
- **({"replacement_message_id": replacement_message_id} if preserve_compaction_handoff else {})}
- **({"replacement_message_id": replacement and replacement["_row_id"],
- "replacement_message_uid": replacement and message_uid_or_none(replacement)}
++ **({"replacement_message_id": replacement_message_id,
++ "replacement_message_uid": replacement_message_uid}
+ if preserve_compaction_handoff else {})}
def message_count(self, session_id: str = None) -> int:
"""Count messages, optionally for a specific session."""
diff --cc hermes_state_runtime.py
index 6237b14888b,00000000000..f85a43d28f2
mode 100644,000000..100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@@ -1,697 -1,0 +1,700 @@@
+"""Canonical runtime transactions; callers authorize and resolve session identity.
+
+No execution, transport, or authority objects live here. Every mutation uses the
+SessionDB transaction owner, including its inode guard and SQLite retry policy.
+"""
+import json
+import uuid
+
- from agent.message_metadata import CANONICAL_ROW, DB_ROW_SNAPSHOT
++from agent.conversation_compression_archive import ABSORBED_ROW_IDS
++from agent.message_metadata import CANONICAL_ROW, DB_ROW_SNAPSHOT, PERSISTENCE_ONLY_MESSAGE_FIELDS
+from gateway.session_admission import admission_fingerprint
+
+
+class RuntimeStoreError(ValueError):
+ def __init__(self, reason: str):
+ self.reason = reason
+ super().__init__(reason)
+
+
+def _text(value):
+ if not isinstance(value, str) or not value or len(value) > 1024:
+ raise RuntimeStoreError('invalid_params')
+ return value
+
+
+def _json(value):
+ if not isinstance(value, dict):
+ raise RuntimeStoreError('invalid_params')
+ try:
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)
+ except (TypeError, ValueError, UnicodeError) as exc:
+ raise RuntimeStoreError('invalid_params') from exc
+
+
+def _epoch(conn, epoch):
+ row = conn.execute('SELECT epoch FROM runtime_epoch WHERE singleton=1').fetchone()
+ if type(epoch) is not int or row is None or row[0] != epoch:
+ raise RuntimeStoreError('stale_epoch')
+
+
+def _session(conn, session_id):
+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ return row
+
+
+def _admission(conn, admission_id):
+ row = conn.execute('SELECT * FROM session_admissions WHERE admission_id=?', (admission_id,)).fetchone()
+ if row is None:
+ from hermes_state_terminal import terminal_admission
+ row = terminal_admission(conn, admission_id)
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ return row
+
+
+def _retire_admission_workers(conn, row, owner_epoch):
+ """Retire the worker rows this admission's generation owns on BOTH the logical
+ FIFO owner and its current physical transcript (reset/compression move the private
+ worker assignment to the child while target_session_id stays the logical ID)."""
+ lineage = json.loads(row['lineage_json'])
+ targets = list({row['target_session_id'], lineage[-1] if lineage else row['target_session_id']})
+ conn.execute(f"UPDATE worker_executions SET status='terminal' WHERE session_id IN ({','.join('?' * len(targets))}) "
+ "AND generation=? AND owner_epoch=?", (*targets, row['generation'], owner_epoch))
+
+
+def _row(row):
+ if row is None:
+ return None
+ result = dict(row)
+ result['payload'] = json.loads(result.pop('payload_json'))
+ result.pop('payload_digest')
+ result.pop('lineage_json')
+ return result
+
+
+def begin_runtime_epoch(db, *, instance_id: str) -> int:
+ """Caller MUST hold the profile ownership lock, not merely an endpoint ticket."""
+ _text(instance_id)
+ def write(conn):
+ conn.execute('''INSERT INTO runtime_epoch(singleton,epoch,instance_id) VALUES(1,1,?)
+ ON CONFLICT(singleton) DO UPDATE SET epoch=runtime_epoch.epoch+1, instance_id=excluded.instance_id''', (instance_id,))
+ return conn.execute('SELECT epoch FROM runtime_epoch WHERE singleton=1').fetchone()[0]
+ return db._execute_write(write)
+
+
+def admit_session_input(db, *, epoch: int, principal_id: str, session_id: str,
+ request_id: str, payload: dict, intent: str = 'queue',
+ _authorize_write=None) -> dict:
+ """Admit input; the trusted private guard raises to refuse a NEW write.
+
+ The guard receives the owning transaction connection, must not commit it or
+ perform external effects, and may run again on SQLite retry. Exact existing
+ and terminal replays bypass it: they cannot create or change accepted work.
+ """
+ for value in (principal_id, session_id, request_id):
+ _text(value)
+ if intent not in ('queue', 'steer', 'redirect'):
+ raise RuntimeStoreError('invalid_params')
+ encoded = _json(payload)
+ from hermes_state_terminal import retry_terminal_admission
+ retired = retry_terminal_admission(db, epoch=epoch, principal_id=principal_id, session_id=session_id,
+ request_id=request_id, payload=payload, intent=intent)
+ if retired is not None:
+ return retired
+ digest = admission_fingerprint(canonical_target=session_id, payload={'input': json.loads(encoded), 'intent': intent})
+ def write(conn):
+ _epoch(conn, epoch)
+ _session(conn, session_id)
+ old = conn.execute('''SELECT * FROM session_admissions
+ WHERE principal_id=? AND target_session_id=? AND request_id=?''', (principal_id, session_id, request_id)).fetchone()
+ if old is not None:
+ if old['payload_digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return _row(old)
+ if _authorize_write is not None:
+ _authorize_write(conn)
+ admission_id = uuid.uuid4().hex
+ conn.execute('''INSERT INTO session_admissions(admission_id,request_id,principal_id,
+ target_session_id,lineage_json,payload_json,payload_digest,intent,status,owner_epoch)
+ VALUES(?,?,?,?,?,?,?,?,'queued',?)''',
+ (admission_id, request_id, principal_id, session_id, json.dumps([session_id]), encoded, digest, intent, epoch))
+ return _row(_admission(conn, admission_id))
+ return db._execute_write(write)
+
+
+def get_session_admission(db, *, admission_id: str) -> dict | None:
+ with db._read_ctx() as conn:
+ from hermes_state_terminal import terminal_admission
+ row = conn.execute('SELECT * FROM session_admissions WHERE admission_id=?', (admission_id,)).fetchone()
+ return _row(row if row is not None else terminal_admission(conn, admission_id))
+
+
+def list_session_admissions(db, *, session_id: str, pending_only: bool = True) -> list[dict]:
+ with db._read_ctx() as conn:
+ return [_row(row) for row in conn.execute('''SELECT * FROM session_admissions
+ WHERE target_session_id=? AND (?=0 OR status!='terminal') ORDER BY seq''', (session_id, int(pending_only)))]
+
+
+def claim_session_input(db, *, epoch: int, session_id: str) -> dict | None:
+ def write(conn):
+ _epoch(conn, epoch)
+ session = _session(conn, session_id)
+ blocked = conn.execute("SELECT status FROM session_admissions WHERE target_session_id=? AND status IN ('started','unknown')", (session_id,)).fetchall()
+ if any(row[0] == 'unknown' for row in blocked):
+ raise RuntimeStoreError('unknown_execution')
+ if conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status='unknown'", (session_id,)).fetchone():
+ raise RuntimeStoreError('unknown_execution')
+ if blocked or conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status IN ('registered','running')", (session_id,)).fetchone():
+ return None
+ row = conn.execute("SELECT * FROM session_admissions WHERE target_session_id=? AND status='queued' ORDER BY seq LIMIT 1", (session_id,)).fetchone()
+ if row is None:
+ return None
+ generation = session['runtime_generation'] + 1
+ conn.execute('UPDATE sessions SET runtime_generation=? WHERE id=?', (generation, session_id))
+ changed = conn.execute("UPDATE session_admissions SET status='started',owner_epoch=?,generation=? WHERE admission_id=? AND status='queued'", (epoch, generation, row['admission_id']))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ return _row(_admission(conn, row['admission_id']))
+ return db._execute_write(write)
+
+
+def settle_session_input(db, *, epoch: int, admission_id: str, generation: int, outcome: str,
+ result: dict | None = None) -> dict:
+ if outcome not in ('completed', 'interrupted', 'rejected', 'failed'):
+ raise RuntimeStoreError('invalid_params')
+ encoded = _json(result) if result is not None else None
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _admission(conn, admission_id)
+ session = _session(conn, row['target_session_id'])
+ if (row['status'] != 'started' or row['owner_epoch'] != epoch
+ or type(generation) is not int or row['generation'] != generation
+ or session['runtime_generation'] != generation):
+ raise RuntimeStoreError('stale_generation')
+ _retire_admission_workers(conn, row, epoch)
+ if encoded is not None:
+ from hermes_state_terminal import RESULT_PREFIX
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) '
+ 'ON CONFLICT(key) DO UPDATE SET value=excluded.value',
+ (RESULT_PREFIX + admission_id, encoded))
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome=? WHERE admission_id=?", (outcome, admission_id))
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))
+ return _row(_admission(conn, admission_id))
+ return db._execute_write(write)
+
+
+def cancel_session_input(db, *, epoch: int, admission_id: str) -> dict:
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _admission(conn, admission_id)
+ if row['status'] == 'unknown':
+ raise RuntimeStoreError('unknown_execution')
+ if row['status'] == 'started':
+ raise RuntimeStoreError('stale_generation')
+ if row['status'] == 'queued':
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome='cancelled' WHERE admission_id=?", (admission_id,))
+ return _row(_admission(conn, admission_id))
+ return db._execute_write(write)
+
+
+def recover_session_inputs(db, *, epoch: int) -> int:
+ """Never replay started work. Live worker adoption is a separate explicit operation."""
+ def write(conn):
+ _epoch(conn, epoch)
+ conn.execute("UPDATE worker_executions SET status='unknown' WHERE status IN ('registered','running') AND owner_epoch!=?", (epoch,))
+ return conn.execute("UPDATE session_admissions SET status='unknown' WHERE status='started' AND owner_epoch!=?", (epoch,)).rowcount
+ return db._execute_write(write)
+
+
+def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str,
+ request_id: str, expected_revision: int,
+ operation: str, payload: dict, expected_generation: int | None = None,
+ _live_guard=None, _authorize_write=None, _prepare_only=False, _prepared=None) -> dict:
+ """Commit a closed metadata edit and its retry receipt in the same transaction.
+
+ Caller authorizes the principal and resolves the canonical session. These
+ metadata edits do not stop execution. Existing direct writers must migrate
+ before this seam can provide universal revision fencing.
+ """
+ for value in (principal_id, session_id, request_id):
+ _text(value)
+ if type(expected_revision) is not int or expected_revision < 0:
+ raise RuntimeStoreError('invalid_params')
+ from hermes_state_mutations import validate_action, apply_action
+ validate_action(operation, payload)
+ if expected_generation is not None and (type(expected_generation) is not int or expected_generation < 0):
+ raise RuntimeStoreError('invalid_params')
+ if operation in {'delete', 'rewind', 'reset', 'branch', 'model', 'compress'} and expected_generation is None:
+ raise RuntimeStoreError('invalid_params')
+ # Snapshot caller data before waiting for the writer lock.
+ payload = json.loads(_json(payload))
+ key = 'gateway.mutation.v1.' + admission_fingerprint(
+ canonical_target=session_id, payload={'principal': principal_id, 'request': request_id})
+ fingerprint = {'operation': operation, 'payload': payload, 'expected_revision': expected_revision}
+ if expected_generation is not None:
+ fingerprint['expected_generation'] = expected_generation
+ digest = admission_fingerprint(canonical_target=session_id, payload=fingerprint)
+
+ def write(conn):
+ _epoch(conn, epoch)
+ old = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
+ if old is not None:
+ receipt = json.loads(old[0])
+ if receipt['digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return receipt['result']
+ session = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
+ if session is None and operation != 'import':
+ raise RuntimeStoreError('not_found')
+ revision = session['runtime_revision'] if session else 0
+ if revision != expected_revision:
+ raise RuntimeStoreError('revision_conflict')
+ if expected_generation is not None and (session is None or session['runtime_generation'] != expected_generation):
+ raise RuntimeStoreError('stale_generation')
+ if _live_guard is not None:
+ from hermes_state_mutation_guards import delete_targets
+ targets = delete_targets(conn, session_id) if operation == 'delete' else [session_id]
+ _live_guard(targets)
+ if _authorize_write is not None:
+ _authorize_write(conn)
+ if _prepare_only:
+ from hermes_state_mutation_prepared import local_snapshot
+ return {'snapshot': local_snapshot(db, conn, session_id)}
+ affected, projection = apply_action(db, conn, session_id, operation, payload, prepared=_prepared)
+ conn.executemany('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',
+ [(target,) for target in affected])
+ updated = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
+ result = {'session_id': session_id, 'revision': updated['runtime_revision'] if updated else expected_revision + 1,
+ 'operation': operation, **projection}
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
+ (key, _json({'digest': digest, 'result': result})))
+ return result
+ return db._execute_write(write)
+
+
+_IMPORT_KEY = 'gateway.prompt_admissions_import.v1'
+
+
+def _canonical_chain(conn, session_id):
+ # Same selector as SessionDB.get_compression_chain, on OUR transaction connection.
+ from hermes_state_compression import _CHAIN_STEP_SQL
+ _session(conn, session_id)
+ chain = [session_id]
+ for _ in range(100):
+ child = conn.execute(_CHAIN_STEP_SQL, (chain[-1],)).fetchone()
+ if child is None:
+ return chain
+ if child['id'] in chain:
+ raise RuntimeStoreError('admission_conflict')
+ chain.append(child['id'])
+ raise RuntimeStoreError('admission_conflict')
+
+
+def _import_legacy_row(conn, row, epoch, principal_id):
+ for field in ('admission_id', 'target_session_id', 'root'):
+ _text(row[field])
+ lineage = json.loads(row['lineage'])
+ if not isinstance(lineage, list) or row['target_session_id'] not in lineage:
+ raise RuntimeStoreError('invalid_params')
+ payload = json.loads(row['payload'])
+ encoded = _json(payload)
+ intent = payload.get('intent', 'queue')
+ intent = 'redirect' if intent == 'interrupt' else intent
+ if intent not in ('queue', 'steer', 'redirect') or row['status'] not in ('queued', 'started', 'unknown', 'terminal'):
+ raise RuntimeStoreError('invalid_params')
+ chain = _canonical_chain(conn, row['target_session_id'])
+ target = chain[-1]
+ status = 'unknown' if row['status'] == 'started' else row['status']
+ generation = row['generation']
+ if generation is None and status == 'unknown':
+ generation = _session(conn, target)['runtime_generation'] + 1
+ if generation is not None and (type(generation) is not int or generation < 0):
+ raise RuntimeStoreError('invalid_params')
+ digest = admission_fingerprint(canonical_target=target, payload={'input': payload, 'intent': intent})
+ conn.execute("""INSERT INTO session_admissions(admission_id,request_id,principal_id,
+ target_session_id,lineage_json,payload_json,payload_digest,intent,status,outcome,owner_epoch,generation)
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""", (row['admission_id'], row['admission_id'], principal_id,
+ target, json.dumps(chain), encoded, digest, intent, status, row['outcome'], epoch, generation))
+ if generation is not None:
+ conn.execute('UPDATE sessions SET runtime_generation=MAX(runtime_generation,?) WHERE id=?', (generation, target))
+
+
+def import_legacy_session_admissions(db, *, epoch: int, source_path, principal_id: str,
+ writers_drained: bool) -> int:
+ """Import a frozen legacy snapshot; original file remains rollback evidence.
+
+ The caller proves the old writers are drained before invoking this function.
+ Fingerprinting uses SQL snapshot data, never a raw open/close on a live inode.
+ """
+ from contextlib import closing
+ from pathlib import Path
+ import hashlib
+ import sqlite3
+ from hermes_cli.sqlite_safe_read import connect_tracked
+ if writers_drained is not True:
+ raise RuntimeStoreError('invalid_params')
+ _text(principal_id)
+ source_path = Path(source_path).resolve(strict=True)
+ with closing(connect_tracked(source_path.as_uri() + '?mode=ro', uri=True)) as source:
+ source.row_factory = sqlite3.Row
+ source.execute('PRAGMA query_only=ON')
+ source.execute('BEGIN')
+ rows = [dict(r) for r in source.execute('SELECT * FROM admissions ORDER BY seq')]
+ executions = []
+ if source.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='executions'").fetchone():
+ executions = [dict(r) for r in source.execute('SELECT * FROM executions ORDER BY root')]
+ fingerprint = hashlib.sha256(_json({'rows': rows, 'executions': executions}).encode('utf-8')).hexdigest()
+ marker = _json({'source': str(source_path), 'fingerprint': fingerprint, 'imported_id_count': len(rows), 'principal_id': principal_id})
+ def write(conn):
+ _epoch(conn, epoch)
+ old = conn.execute('SELECT value FROM state_meta WHERE key=?', (_IMPORT_KEY,)).fetchone()
+ if old is not None:
+ if old[0] != marker:
+ raise RuntimeStoreError('admission_conflict')
+ return 0
+ for execution in executions:
+ generation = execution['generation']
+ if type(generation) is not int or generation < 0:
+ raise RuntimeStoreError('invalid_params')
+ target = _canonical_chain(conn, _text(execution['root']))[-1]
+ conn.execute('UPDATE sessions SET runtime_generation=MAX(runtime_generation,?) WHERE id=?', (generation, target))
+ for row in rows:
+ _import_legacy_row(conn, row, epoch, principal_id)
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (_IMPORT_KEY, marker))
+ return len(rows)
+ return db._execute_write(write)
+
+
+def resolve_unknown_session_input(db, *, epoch: int, admission_id: str, generation: int) -> dict:
+ """Explicit operator acknowledgement; resolves uncertainty, never requeues it."""
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _admission(conn, admission_id)
+ if type(generation) is not int or row['status'] != 'unknown' or row['generation'] != generation:
+ raise RuntimeStoreError('stale_generation')
+ _retire_admission_workers(conn, row, row['owner_epoch'])
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome='interrupted' WHERE admission_id=?", (admission_id,))
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))
+ return _row(_admission(conn, admission_id))
+ return db._execute_write(write)
+
+
+def _worker_public(row):
+ result = dict(row)
+ result.pop('adoption_digest')
+ return result
+
+
+def _worker_assignment(conn, execution_id, session_id, generation):
+ row = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ if row['session_id'] != session_id:
+ raise RuntimeStoreError('permission_denied')
+ if (type(generation) is not int or row['generation'] != generation
+ or _session(conn, session_id)['runtime_generation'] != generation):
+ raise RuntimeStoreError('stale_generation')
+ return row
+
+
+def _linked_worker_admission(conn, session_id, generation, owner_epoch, statuses):
+ placeholders = ','.join('?' for _ in statuses)
+ rows = conn.execute(f"""SELECT * FROM session_admissions
+ WHERE generation=? AND owner_epoch=? AND status IN ({placeholders})
+ AND (target_session_id=? OR EXISTS (
+ SELECT 1 FROM json_each(session_admissions.lineage_json) WHERE value=?
+ )) ORDER BY seq""",
+ (generation, owner_epoch, *statuses, session_id, session_id)).fetchall()
+ if len(rows) > 1:
+ raise RuntimeStoreError('admission_conflict')
+ return rows[0] if rows else None
+
+
+def _secret_digest(secret):
+ import hashlib
+ _text(secret)
+ return hashlib.sha256(secret.encode('utf-8')).hexdigest()
+
+
+def register_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,
+ generation: int, kind: str, adoption_secret: str, require_idle: bool = False) -> dict:
+ for value in (execution_id, session_id):
+ _text(value)
+ if kind not in ('cron', 'child', 'compute', 'kanban'):
+ raise RuntimeStoreError('invalid_params')
+ digest = _secret_digest(adoption_secret)
+ def write(conn):
+ _epoch(conn, epoch)
+ session = _session(conn, session_id)
+ if type(generation) is not int or session['runtime_generation'] != generation:
+ raise RuntimeStoreError('stale_generation')
+ old = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()
+ if old is not None:
+ if (old['session_id'], old['generation'], old['kind'], old['owner_epoch'], old['adoption_digest']) != (session_id, generation, kind, epoch, digest):
+ raise RuntimeStoreError('admission_conflict')
+ return _worker_public(old)
+ if require_idle and conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status!='terminal'", (session_id,)).fetchone():
+ raise RuntimeStoreError('stale_generation')
+ if conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status!='terminal'", (session_id,)).fetchone():
+ raise RuntimeStoreError('stale_generation')
+ if conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status='unknown'", (session_id,)).fetchone():
+ raise RuntimeStoreError('unknown_execution')
+ conn.execute("""INSERT INTO worker_executions(execution_id,session_id,kind,owner_epoch,generation,status,adoption_digest)
+ VALUES(?,?,?,?,?,'registered',?)""", (execution_id, session_id, kind, epoch, generation, digest))
+ return _worker_public(_worker_assignment(conn, execution_id, session_id, generation))
+ return db._execute_write(write)
+
+
+def adopt_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,
+ generation: int, adoption_secret: str) -> dict:
+ """Authority first verifies the original producer claim and live worker proof."""
+ import hmac
+ digest = _secret_digest(adoption_secret)
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _worker_assignment(conn, execution_id, session_id, generation)
+ if row['status'] == 'terminal':
+ raise RuntimeStoreError('stale_generation')
+ if not hmac.compare_digest(row['adoption_digest'], digest):
+ raise RuntimeStoreError('permission_denied')
+ linked = _linked_worker_admission(
+ conn, session_id, generation, row['owner_epoch'], ('started', 'unknown'))
+ if linked is not None:
+ changed = conn.execute("""UPDATE session_admissions SET owner_epoch=?,status='started'
+ WHERE admission_id=? AND generation=? AND owner_epoch=?
+ AND status IN ('started','unknown')""",
+ (epoch, linked['admission_id'], generation, row['owner_epoch']))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ changed = conn.execute(
+ "UPDATE worker_executions SET owner_epoch=?,status='running' WHERE execution_id=?",
+ (epoch, execution_id))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ return _worker_public(_worker_assignment(conn, execution_id, session_id, generation))
+ return db._execute_write(write)
+
+
+def persist_worker_message(db, *, epoch: int, execution_id: str, session_id: str,
+ generation: int, sequence: int, role: str, content: str) -> dict:
+ """Typed text append primitive, NOT a general remote SessionDB implementation.
+
+ Structured tools/reasoning/usage/compression require their own typed operations.
+ No caller-supplied callable can commit inside this transaction.
+ """
+ import time
+ if type(sequence) is not int or sequence < 1 or role not in ('user', 'assistant', 'system') or not isinstance(content, str):
+ raise RuntimeStoreError('invalid_params')
+ digest = admission_fingerprint(canonical_target=session_id, payload={'operation': 'append_text', 'role': role, 'content': content})
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _worker_assignment(conn, execution_id, session_id, generation)
+ if row['owner_epoch'] != epoch:
+ raise RuntimeStoreError('stale_epoch')
+ old = conn.execute('SELECT * FROM worker_receipts WHERE execution_id=? AND sequence=?', (execution_id, sequence)).fetchone()
+ if old is not None:
+ if old['payload_digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return json.loads(old['result_json'])
+ if row['status'] == 'terminal':
+ raise RuntimeStoreError('stale_generation')
+ if sequence != row['last_sequence'] + 1:
+ raise RuntimeStoreError('invalid_params')
+ db._check_transcript_write_guards(conn, session_id, None)
+ now = time.time()
+ message = conn.execute('INSERT INTO messages(session_id,role,content,timestamp) VALUES(?,?,?,?)', (session_id, role, db._encode_content(content), now))
+ conn.execute('UPDATE sessions SET message_count=message_count+1,last_activity_at=?,runtime_revision=runtime_revision+1 WHERE id=?', (now, session_id))
+ result = {'message_id': message.lastrowid}
+ conn.execute('INSERT INTO worker_receipts(execution_id,sequence,payload_digest,result_json) VALUES(?,?,?,?)', (execution_id, sequence, digest, json.dumps(result, ensure_ascii=True, allow_nan=False)))
+ conn.execute("UPDATE worker_executions SET last_sequence=?,status='running' WHERE execution_id=?", (sequence, execution_id))
+ return result
+ return db._execute_write(write)
+
+
+
+
+_MESSAGE_FIELDS = frozenset({
+ 'role', 'content', 'tool_name', 'tool_calls', 'tool_call_id', 'token_count',
+ 'finish_reason', 'reasoning', 'reasoning_content', 'reasoning_details',
+ 'codex_reasoning_items', 'codex_message_items', 'platform_message_id', 'message_id',
+ 'observed', 'effect_disposition', '_compressed_summary', 'timestamp', 'api_content',
+ 'display_kind', 'display_metadata', '_row_id', '_canonical_content', DB_ROW_SNAPSHOT, CANONICAL_ROW,
- })
++ # Main's durable message identity (message_uid / merge witness / tool-call uids) and the alternation
++ # repair's row counts ride every persisted dict; the owner's insert and coverage read them.
++}) | PERSISTENCE_ONLY_MESSAGE_FIELDS | {ABSORBED_ROW_IDS}
+# Row state the owner's transcript repair stamps on each message (main mutates the caller's dict
+# in place; a worker gets it back as an annotation). None = absent, so a stale adoption is cleared.
+_ROW_ANNOTATION_KEYS = ('_row_id', 'timestamp', DB_ROW_SNAPSHOT, CANONICAL_ROW)
+
+
+def row_annotations(messages):
+ return [{key: msg.get(key) for key in _ROW_ANNOTATION_KEYS} for msg in messages]
+
+
+def _worker_append(db, conn, session_id, payload):
+ if set(payload) - {'messages', 'turn_lease_holder'} or 'messages' not in payload:
+ raise RuntimeStoreError('invalid_params')
+ messages = payload['messages']
+ if not isinstance(messages, list) or len(messages) > 1000:
+ raise RuntimeStoreError('invalid_params')
+ for msg in messages:
+ if (not isinstance(msg, dict) or set(msg) - _MESSAGE_FIELDS
+ or msg.get('role') not in ('user', 'assistant', 'system', 'tool')):
+ raise RuntimeStoreError('invalid_params')
+ # Existing row annotations can adopt only rows in THIS transcript.
+ if '_row_id' in msg and not conn.execute(
+ 'SELECT 1 FROM messages WHERE id=? AND session_id=?',
+ (msg['_row_id'], session_id)).fetchone():
+ raise RuntimeStoreError('permission_denied')
+ holder = payload.get('turn_lease_holder')
+ if holder is not None:
+ _text(holder)
+ count = db._append_messages_in_transaction(conn, session_id, messages, turn_lease_holder=holder)
+ return {'count': count, 'annotations': row_annotations(messages)}
+
+
+def _worker_turn(db, conn, session_id, payload, operation):
+ import time
+ from hermes_state_compression import _claim_lease_row
+ from hermes_state import _compression_lock_holder_process_is_dead
+ allowed = {'holder'} if operation == 'turn.release' else {'holder', 'ttl_seconds'}
+ if set(payload) != allowed:
+ raise RuntimeStoreError('invalid_params')
+ holder = _text(payload['holder'])
+ ttl = payload.get('ttl_seconds', 300)
+ if type(ttl) not in (float, int) or not 0.1 <= ttl <= 3600:
+ raise RuntimeStoreError('invalid_params')
+ key = db._session_turn_lease_key_on_conn(conn, session_id)
+ now = time.time()
+ if operation == 'turn.acquire':
+ value = _claim_lease_row(conn, 'session_turn_leases', 'conversation_id', key,
+ holder, now, now + ttl,
+ lambda h, e: float(e) <= now or _compression_lock_holder_process_is_dead(h))[0]
+ elif operation == 'turn.renew':
+ value = conn.execute('UPDATE session_turn_leases SET expires_at=? WHERE conversation_id=? AND holder=?',
+ (now + ttl, key, holder)).rowcount > 0
+ else:
+ conn.execute('DELETE FROM session_turn_leases WHERE conversation_id=? AND holder=?', (key, holder))
+ value = None
+ return {'value': value}
+
+
+def _worker_usage(db, conn, session_id, payload, *, auxiliary=False):
+ from hermes_state_usage import _MODEL_USAGE_FIELDS, _TOKEN_COUNTERS
+ if not auxiliary:
+ # ``source`` feeds the legacy path's row-existence guard (#111999); an authority-owned
+ # session row was minted with its real surface at admission, so nothing to repair here.
+ payload = {k: v for k, v in payload.items() if k != 'source'}
+ allowed = (_MODEL_USAGE_FIELDS - {'billing_mode', 'actual_cost_usd', 'cost_status', 'cost_source'} | {'task'}) if auxiliary else (_MODEL_USAGE_FIELDS | {'pricing_version', 'absolute'})
+ if set(payload) - allowed:
+ raise RuntimeStoreError('invalid_params')
+ for key, value in payload.items():
+ if key in (*_TOKEN_COUNTERS, 'api_call_count'):
+ valid = type(value) is int and 0 <= value <= 2**53
+ elif key in ('estimated_cost_usd', 'actual_cost_usd'):
+ valid = value is None or (type(value) in (int, float) and 0 <= value <= 1e12)
+ elif key == 'absolute':
+ valid = type(value) is bool
+ else:
+ valid = value is None or (isinstance(value, str) and len(value) <= 4096)
+ if not valid:
+ raise RuntimeStoreError('invalid_params')
+ if auxiliary:
+ if not payload.get('task'):
+ raise RuntimeStoreError('invalid_params')
+ db._record_model_usage(conn, session_id, **({'api_call_count': 1} | payload))
+ else:
+ db._update_token_counts_in_transaction(conn, session_id, **payload)
+ return {'value': None}
+
+
+def _worker_finish(db, conn, session_id, payload):
+ if payload:
+ raise RuntimeStoreError('invalid_params')
+ return {'status': 'terminal'}
+
+
+def mutate_worker_execution(db, *, epoch, execution_id, session_id, generation,
+ sequence, operation, payload):
+ """One closed durable mutation and receipt; never call a self-committing API here."""
+ from hermes_state_worker_context import worker_context, worker_prompt, worker_sidecars, worker_tool_names
+ from hermes_state_worker_compression import WORKER_COMPRESSION_HANDLERS, worker_receipt_assignment
+ from hermes_state_worker_lifecycle import WORKER_LIFECYCLE_HANDLERS
+ handlers = {
+ **WORKER_LIFECYCLE_HANDLERS,
+ **WORKER_COMPRESSION_HANDLERS,
+ 'session.context': worker_context,
+ 'session.prompt': worker_prompt,
+ 'session.sidecars': worker_sidecars,
+ 'session.tools': worker_tool_names,
+ 'transcript.append': _worker_append,
+ 'execution.finish': _worker_finish,
+ 'usage.main': _worker_usage,
+ 'usage.auxiliary': lambda db, conn, sid, p: _worker_usage(db, conn, sid, p, auxiliary=True),
+ **{name: (lambda db, conn, sid, p, op=name: _worker_turn(db, conn, sid, p, op))
+ for name in ('turn.acquire', 'turn.renew', 'turn.release')},
+ }
+ if type(sequence) is not int or sequence < 1 or not isinstance(operation, str) or operation not in handlers:
+ raise RuntimeStoreError('invalid_params')
+ encoded = _json(payload)
+ if len(encoded.encode('utf-8', errors='surrogatepass')) > 4 * 1024 * 1024:
+ raise RuntimeStoreError('invalid_params')
+ digest = admission_fingerprint(canonical_target=session_id,
+ payload={'operation': operation, 'payload': json.loads(encoded)})
+ def write(conn):
+ _epoch(conn, epoch)
+ row = worker_receipt_assignment(conn, execution_id, session_id, generation, sequence, digest)
+ if row['owner_epoch'] != epoch:
+ raise RuntimeStoreError('stale_epoch')
+ old = conn.execute('SELECT * FROM worker_receipts WHERE execution_id=? AND sequence=?',
+ (execution_id, sequence)).fetchone()
+ if old is not None:
+ if old['payload_digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return json.loads(old['result_json'])
+ if row['status'] not in ('registered', 'running'):
+ raise RuntimeStoreError('stale_generation')
+ if sequence != row['last_sequence'] + 1:
+ raise RuntimeStoreError('invalid_params')
+ # Each SQLite retry gets fresh rows; rolled-back annotations must not escape.
+ result = handlers[operation](db, conn, session_id, json.loads(encoded))
+ conn.execute('INSERT INTO worker_receipts(execution_id,sequence,payload_digest,result_json) VALUES(?,?,?,?)',
+ (execution_id, sequence, digest, json.dumps(result, ensure_ascii=True, allow_nan=False)))
+ conn.execute("UPDATE worker_executions SET last_sequence=?,status=? WHERE execution_id=?",
+ (sequence, 'terminal' if operation == 'execution.finish' else 'running', execution_id))
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (session_id,))
+ return result
+ return db._execute_write(write, patience_s=db._TRANSCRIPT_WRITE_PATIENCE_S)
+
+
+def finish_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,
+ generation: int) -> dict:
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _worker_assignment(conn, execution_id, session_id, generation)
+ if row['owner_epoch'] != epoch:
+ raise RuntimeStoreError('stale_epoch')
+ if row['status'] == 'terminal':
+ return _worker_public(row)
+ linked = _linked_worker_admission(conn, session_id, generation, epoch, ('started',))
+ changed = conn.execute(
+ "UPDATE worker_executions SET status='terminal' WHERE execution_id=? AND status!='terminal'",
+ (execution_id,))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ if linked is not None:
+ changed = conn.execute("""UPDATE session_admissions
+ SET status='terminal',outcome='completed'
+ WHERE admission_id=? AND status='started' AND owner_epoch=? AND generation=?""",
+ (linked['admission_id'], epoch, generation))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',
+ (linked['target_session_id'],))
+ result = _worker_public(row)
+ result['status'] = 'terminal'
+ return result
+ return db._execute_write(write)
diff --cc hermes_state_sessions.py
index 90e6d5f57d1,488d2718775..85ff7dc77c2
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@@ -813,52 -946,57 +895,70 @@@ class SessionSessionsMixin
(),
) or 0)
- def _set_lineage_column(self, column: str, session_id: str, value: Any) -> bool:
+ def _set_lineage_column(self, column: str, session_id: str, value: Any, *,
+ extra_set_sql: str = "") -> bool:
"""Set one ``sessions`` column across a whole compression lineage: Desktop projects roots
- forward to their tip, so updating only the tip would let the root resurrect it on refresh."""
+ forward to their tip, so updating only the tip would let the root resurrect it on refresh.
+ *extra_set_sql* (trusted literal, ``, col = expr``) rides the same UPDATE."""
- return self._write_rowcount(
+ return bool(self._execute_write(
- lambda conn: self._set_lineage_column_in_transaction(conn, column, session_id, value)
++ lambda conn: self._set_lineage_column_in_transaction(
++ conn, column, session_id, value, extra_set_sql=extra_set_sql)
+ ))
+
- def _set_lineage_column_in_transaction(self, conn, column: str, session_id: str, value: Any):
- """Return affected IDs so authority revisions share this exact lineage selector."""
++ def _set_lineage_column_in_transaction(self, conn, column: str, session_id: str, value: Any, *,
++ extra_set_sql: str = ""):
++ """Return affected IDs so authority revisions share this exact lineage selector. A plain
++ ``archived`` write (canonical mutation, user/CLI/API) is the DELIBERATE archive and clears
++ the idle sweep's ``auto_archived`` provenance, same as :meth:`set_session_archived`."""
++ if column == "archived" and not extra_set_sql:
++ extra_set_sql = ", auto_archived = 0"
+ return [row[0] for row in conn.execute(
- f"""
- WITH RECURSIVE
- ancestors(id) AS (
- SELECT ?
- UNION
- SELECT parent.id
- FROM ancestors a
- JOIN sessions child ON child.id = a.id
- JOIN sessions parent ON parent.id = child.parent_session_id
- WHERE parent.end_reason = 'compression'
- ),
- descendants(id) AS (
- SELECT ?
- UNION
- SELECT child.id
- FROM descendants d
- JOIN sessions parent ON parent.id = d.id
- JOIN sessions child ON child.parent_session_id = parent.id
- WHERE parent.end_reason = 'compression'
- ),
- lineage(id) AS (
- SELECT id FROM ancestors
- UNION
- SELECT id FROM descendants
- )
+ _LINEAGE_CTE_SQL + f"""
UPDATE sessions
- SET {column} = ?
+ SET {column} = ?{extra_set_sql}
WHERE id IN (SELECT id FROM lineage)
+ RETURNING id
""",
(session_id, session_id, value),
- ) > 0
+ ).fetchall()]
def set_session_archived(self, session_id: str, archived: bool) -> bool:
- """Soft-hide (or unhide) a session and its compression lineage; messages are kept."""
- return self._set_lineage_column("archived", session_id, int(archived))
+ """Soft-hide (or unhide) a session and its compression lineage; messages are kept.
+ This is the DELIBERATE archive (user, CLI, API): it clears the ``auto_archived``
+ provenance, so re-activation never un-hides it on the user's behalf."""
+ return self._set_lineage_column(
+ "archived", session_id, int(archived), extra_set_sql=", auto_archived = 0")
+
+ def _auto_archive_lineage(self, session_id: str) -> bool:
+ """The idle sweep's archive: like :meth:`set_session_archived` but stamps
+ ``auto_archived`` on the rows IT hides. A row already archived keeps its provenance, so a
+ deliberately archived ancestor is never relabelled as sweep-owned (SQLite evaluates every
+ SET expression against the pre-update row)."""
+ return self._set_lineage_column(
+ "archived", session_id, 1,
+ extra_set_sql=", auto_archived = CASE WHEN archived = 0 THEN 1 ELSE auto_archived END")
+
+ @staticmethod
+ def _unarchive_auto_archived_lineage(conn, session_id: str) -> bool:
+ """Un-hide a lineage the idle sweep archived, on *conn* (caller's write txn). A tip that is
+ published (compression) or reopened (resume) under it is live again, and the listing admits
+ a lineage by its ROOT's flag, so leaving the sweep's stamp would hide an active chat (#117713).
+ A lineage with ANY deliberately archived row (``archived = 1 AND auto_archived = 0``) is left
+ alone: a manual archive stays until the user un-archives it. True when rows were un-hidden."""
+ params = (session_id, session_id)
+ manual = conn.execute(
+ _LINEAGE_CTE_SQL + """
+ SELECT 1 FROM sessions
+ WHERE id IN (SELECT id FROM lineage) AND archived <> 0 AND COALESCE(auto_archived, 0) = 0
+ LIMIT 1
+ """, params).fetchone()
+ if manual is not None:
+ return False
+ return conn.execute(
+ _LINEAGE_CTE_SQL + """
+ UPDATE sessions SET archived = 0, auto_archived = 0
+ WHERE id IN (SELECT id FROM lineage) AND archived <> 0
+ """, params).rowcount > 0
# Accidental end reasons recovery treats as resumable (also interpolated into
# the recovery/promotion SQL so literals cannot drift).
@@@ -1564,31 -1749,18 +1713,36 @@@
self._remove_session_files(sessions_dir, sid)
return bool(deleted)
+ def discard_unadmitted_session(self, session_id: str) -> bool:
+ """Abort a row this same flow just created and nobody has been admitted against (seed-copy
+ compensation): remove it WITHOUT the retirement fence so the id can be lazily recreated.
+ A row with any admission or worker receipt is a real session and takes the fenced
+ :meth:`delete_session` path instead."""
+ def _do(conn):
+ if conn.execute(
+ "SELECT 1 FROM session_admissions WHERE target_session_id=? UNION ALL "
+ "SELECT 1 FROM worker_executions WHERE session_id=? LIMIT 1", (session_id, session_id)).fetchone():
+ return None
+ conn.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))
+ cur = conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,))
+ return cur.rowcount > 0
+ result = self._execute_write(_do)
+ if result is None:
+ return self.delete_session(session_id)
+ return bool(result)
+
def delete_session_if_empty(self, session_id: str, sessions_dir: Optional[Path] = None) -> bool:
"""Delete *session_id* only if it has no messages, no title and no children; check and delete
- share one transaction so a concurrent flush can't be lost."""
+ share one transaction so a concurrent flush can't be lost. A row under an active turn lease
+ or compression lock is never a candidate: the emptiness predicate reads committed state, so a
+ row whose first turn is already leased but not yet flushed would be deleted mid-turn
+ (#123583). A guarded row is simply not deleted (returns ``False``), like any non-empty row."""
def _do(conn):
+ if self._guarded_ids(conn, [session_id]):
+ return False
- cursor = conn.execute(
+ eligible = conn.execute(
"""
- DELETE FROM sessions
+ SELECT 1 FROM sessions
WHERE id = ?
AND title IS NULL
AND NOT EXISTS (
@@@ -1648,10 -1839,12 +1827,14 @@@
skipped_ids.extend(sorted(active_ids))
if not existing:
return 0
+ if include_compression_chain:
+ expanded = self._expand_compression_lineage(conn, existing)
+ else:
+ expanded = existing
+ from hermes_state_mutation_retirement import retire_sessions
- retire_sessions(conn, existing)
- removed_ids.extend(_delete_delegate_children(conn, existing))
- for chunk in _id_chunks(existing):
++ retire_sessions(conn, expanded)
+ removed_ids.extend(_delete_delegate_children(conn, expanded))
+ for chunk in _id_chunks(expanded):
ph = _session_ids_placeholders(chunk)
conn.execute( # orphan children whose parent is in the kill list (FK)
f"UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id IN ({ph})", chunk,
diff --cc hermes_state_titles.py
index 11faff4c80f,a8d176a59de..9eda0116fe9
--- a/hermes_state_titles.py
+++ b/hermes_state_titles.py
@@@ -81,58 -90,69 +96,72 @@@ class SessionTitlesMixin
title = self.sanitize_title(title)
is_user = source == self.TITLE_SOURCE_USER
new_rank = self._title_rank(source) if not is_user else None
+ affected = []
- def _do(conn):
- current = conn.execute(
- "SELECT title, title_source, hidden FROM sessions WHERE id = ?", (session_id,),
- ).fetchone()
- if current is None:
- return 0
- # The canonical Bot Chat's NAME is its identity (Bot Mode resolves it by
- # exact-title lookup on every open), so a rename orphans the conversation. Hidden
- # is the discriminator: canonical chats are born hidden; a visible session merely
- # named "Bot Chat" stays renameable. Provenance-blind.
- if ((current["title"] or "") == self.CANONICAL_BOT_CHAT_TITLE and bool(current["hidden"])
- and title != self.CANONICAL_BOT_CHAT_TITLE):
- if is_user:
- raise ValueError("This is the bot's canonical Bot Chat — its name is its "
- "identity, and renaming it would orphan the conversation. "
- "To start fresh, create a new bot instead.")
- return 0
- if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:
- return 0
- if title:
- self._resolve_title_conflict(conn, session_id, title)
- # CAS on the values just read (``IS`` is NULL-safe): a concurrent write between
- # the SELECT and here loses instead of being overwritten.
- return conn.execute(
- "UPDATE sessions SET title = ?, title_source = ? WHERE id = ? AND title IS ? AND title_source IS ?",
- (title, source if title else None, session_id, current["title"], current["title_source"]),
- ).rowcount
-
- return self._execute_write(_do) > 0
-
- def _resolve_title_conflict(self, conn, session_id: str, title: str) -> None:
+ current = conn.execute(
+ "SELECT title, title_source, hidden FROM sessions WHERE id = ?", (session_id,),
+ ).fetchone()
+ if current is None:
+ return []
+ # The canonical Bot Chat's NAME is its identity (Bot Mode resolves it by
+ # exact-title lookup on every open), so a rename orphans the conversation. Hidden
+ # is the discriminator: canonical chats are born hidden; a visible session merely
+ # named "Bot Chat" stays renameable. Provenance-blind.
+ if ((current["title"] or "") == self.CANONICAL_BOT_CHAT_TITLE and bool(current["hidden"])
+ and title != self.CANONICAL_BOT_CHAT_TITLE):
+ if is_user:
+ raise ValueError("This is the bot's canonical Bot Chat — its name is its "
+ "identity, and renaming it would orphan the conversation. "
+ "To start fresh, create a new bot instead.")
+ return []
+ if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:
+ return []
+ if title:
- conflict = conn.execute(
- "SELECT id, archived, hidden FROM sessions WHERE title = ? AND id != ?", (title, session_id),
- ).fetchone()
- if conflict:
- conflict_id = conflict["id"]
- # A hidden compressed ancestor holding the title cannot be freed by the
- # user, so transfer it onto the tip (uniqueness + lineage kept).
- if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):
- conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))
- affected.append(conflict_id)
- # A deliberately archived hidden Bot Chat is a retired registry
- # entry, not a live identity. Retire its name in the same title
- # transaction so a replacement can become the sole canonical row;
- # the old session remains archived and otherwise untouched.
- elif (title == self.CANONICAL_BOT_CHAT_TITLE and bool(conflict["archived"])
- and bool(conflict["hidden"])):
- conn.execute(
- "UPDATE sessions SET title = NULL, title_source = NULL WHERE id = ?",
- (conflict_id,),
- )
- affected.append(conflict_id)
- else:
- raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")
++ cleared = self._resolve_title_conflict(conn, session_id, title)
++ if cleared:
++ affected.append(cleared)
+ # CAS on the values just read (``IS`` is NULL-safe): a concurrent write between
+ # the SELECT and here loses instead of being overwritten.
+ changed = conn.execute(
+ "UPDATE sessions SET title = ?, title_source = ? WHERE id = ? AND title IS ? AND title_source IS ?",
+ (title, source if title else None, session_id, current["title"], current["title_source"]),
+ ).rowcount
+ return [*affected, session_id] if changed else affected
+
++ def _resolve_title_conflict(self, conn, session_id: str, title: str) -> Optional[str]:
+ """Free ``title`` for ``session_id`` inside the caller's write transaction, or raise
+ ValueError when another session legitimately holds it. The one place the uniqueness
- rule lives, shared by renames and the API server's create-with-title."""
++ rule lives, shared by renames and the API server's create-with-title. Returns the id
++ whose title was cleared (an affected row for mutation receipts), else None."""
+ conflict = conn.execute(
+ f"SELECT id, archived, hidden, {self._EMPTY_SESSION_WHERE} AS ghost "
+ "FROM sessions WHERE title = ? AND id != ?", (title, session_id),
+ ).fetchone()
+ if not conflict:
- return
++ return None
+ conflict_id = conflict["id"]
+ # A hidden compressed ancestor holding the title cannot be freed by the
+ # user, so transfer it onto the tip (uniqueness + lineage kept).
+ if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):
+ conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))
++ return conflict_id
+ # A deliberately archived hidden Bot Chat is a retired registry
+ # entry, not a live identity. Retire its name in the same title
+ # transaction so a replacement can become the sole canonical row;
+ # the old session remains archived and otherwise untouched.
+ # An ended, empty, visible ghost (abandoned new chat that listings filter
+ # out, so the user cannot find it to free the name) yields too (#81888).
+ # The full index stays: a ``message_count > 0`` partial index would make
+ # the ghost's first append_message fail with IntegrityError.
- elif (title == self.CANONICAL_BOT_CHAT_TITLE and bool(conflict["archived"])
++ if (title == self.CANONICAL_BOT_CHAT_TITLE and bool(conflict["archived"])
+ and bool(conflict["hidden"])) or (conflict["ghost"] and not conflict["hidden"]):
+ conn.execute(
+ "UPDATE sessions SET title = NULL, title_source = NULL WHERE id = ?",
+ (conflict_id,),
+ )
- else:
- raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")
++ return conflict_id
++ raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")
+
def set_session_title(self, session_id: str, title: str) -> bool:
"""Set a title on the user's behalf (``user`` provenance). Empty clears it. Raises
ValueError on conflict or validation failure."""
@@@ -191,28 -211,5 +220,11 @@@
return numbered[0]["id"] if numbered else (exact["id"] if exact else None)
def get_next_title_in_lineage(self, base_title: str) -> str:
- """Next title in a lineage ("my session" -> "my session #2"): strip any " #N" suffix,
- then increment the highest existing number."""
- base, sql, args = _lineage_title_query(base_title)
- return _next_lineage_title(base, self._read_all(sql, args))
-
-
- def _lineage_title_query(base_title: str):
- match = _NUMBERED_TITLE_RE.match(base_title)
- base = match.group(1) if match else base_title
- return base, "SELECT title FROM sessions WHERE title = ? OR title LIKE ? ESCAPE '\\'", (base, f"{_escape_like(base)} #%")
-
-
- def _next_lineage_title(base: str, rows) -> str:
- if not rows:
- return base
- # The unnumbered original counts as #1.
- numbers = [int(m.group(2)) for m in (_NUMBERED_TITLE_RE.match(row["title"]) for row in rows) if m]
- return f"{base} #{max([1, *numbers]) + 1}"
+ """Next title in a lineage ("my session" -> "my session #2")."""
+ return self._read_retrying_ioerr(lambda conn: next_title_in_lineage(conn, base_title))
+
+
+def lineage_title_on_conn(conn, base_title: str) -> str:
+ """``get_next_title_in_lineage`` inside an authority-owned transaction (same connection, so a
+ sibling branch committed in this transaction is counted)."""
- base, sql, args = _lineage_title_query(base_title)
- return _next_lineage_title(base, conn.execute(sql, args).fetchall())
++ return next_title_in_lineage(conn, base_title)
diff --cc hermes_state_worker_compression.py
index 5811b9635ad,00000000000..c8040f31766
mode 100644,000000..100644
--- a/hermes_state_worker_compression.py
+++ b/hermes_state_worker_compression.py
@@@ -1,518 -1,0 +1,465 @@@
+"""Closed compression operations on the worker receipt's connection.
+
+No handler opens a connection or invokes a self-committing SessionDB method.
+"""
+from typing import Any, Dict, List, Optional
+import json
+from functools import partial
+import math
+import time
+
+from hermes_state_runtime import RuntimeStoreError, _text
+from hermes_state_compression import _claim_lease_row
+
+
+def _fields(payload, required, optional=()):
+ if not isinstance(payload, dict) or set(payload) - set(required) - set(optional) or set(required) - set(payload):
+ raise RuntimeStoreError('invalid_params')
+
+
+def _number(value):
+ if type(value) not in (int, float) or not math.isfinite(value):
+ raise RuntimeStoreError('invalid_params')
+ return value
+
+
+def worker_compression_lock(db, conn, sid, payload, *, action):
+ if action == 'holder':
+ _fields(payload, ())
+ row = conn.execute('SELECT holder FROM compression_locks WHERE session_id=? AND expires_at>?',
+ (sid, time.time())).fetchone()
+ return {'value': row[0] if row else None}
+ _fields(payload, ('holder',), () if action == 'release' else ('ttl_seconds',))
+ holder = _text(payload['holder'])
+ now = time.time()
+ ttl = _number(payload.get('ttl_seconds', 300.0))
+ if not 0.1 <= ttl <= 3600:
+ raise RuntimeStoreError('invalid_params')
+ if action == 'acquire':
+ from hermes_state import _compression_lock_holder_process_is_dead
+ value = _claim_lease_row(conn, 'compression_locks', 'session_id', sid, holder, now, now + ttl,
+ lambda h, e: e < now or _compression_lock_holder_process_is_dead(h))[0]
+ elif action == 'renew':
+ value = conn.execute('UPDATE compression_locks SET expires_at=? WHERE session_id=? AND holder=?',
+ (now + ttl, sid, holder)).rowcount > 0
+ else:
+ conn.execute('DELETE FROM compression_locks WHERE session_id=? AND holder=?', (sid, holder))
+ value = None
+ return {'value': value}
+
+
+def worker_cooldown_record(db, conn, sid, payload):
+ _fields(payload, ('cooldown_until', 'error'))
+ deadline = _number(payload['cooldown_until'])
+ error = payload['error']
+ if error is not None and not isinstance(error, str):
+ raise RuntimeStoreError('invalid_params')
+ conn.execute('UPDATE sessions SET compression_failure_cooldown_until = CASE '
+ 'WHEN compression_failure_cooldown_until IS NOT NULL AND compression_failure_cooldown_until > ? '
+ 'THEN compression_failure_cooldown_until ELSE ? END, compression_failure_error=? WHERE id=?',
+ (deadline, deadline, error, sid))
+ return {'value': None}
+
+
+def worker_cooldown_restore(db, conn, sid, payload):
+ _fields(payload, ('snapshot',))
+ snapshot = payload['snapshot']
+ _fields(snapshot, ('session_exists', 'cooldown_until', 'error'))
+ if type(snapshot['session_exists']) is not bool:
+ raise RuntimeStoreError('invalid_params')
+ if not snapshot['session_exists']:
+ raise RuntimeError('cannot restore absent compression cooldown row: session now exists')
+ deadline, error = snapshot['cooldown_until'], snapshot['error']
+ if deadline is not None:
+ _number(deadline)
+ if error is not None and not isinstance(error, str):
+ raise RuntimeStoreError('invalid_params')
+ conn.execute('UPDATE sessions SET compression_failure_cooldown_until=?, compression_failure_error=? WHERE id=?',
+ (deadline, error, sid))
+ actual = conn.execute('SELECT compression_failure_cooldown_until,compression_failure_error FROM sessions WHERE id=?',
+ (sid,)).fetchone()
+ if actual is None or tuple(actual) != (deadline, error):
+ raise RuntimeError('compression cooldown rollback verification failed')
+ return {'value': None}
+
+
+def worker_cooldown_clear(db, conn, sid, payload):
+ _fields(payload, ())
+ return worker_cooldown_restore(db, conn, sid, {'snapshot': {
+ 'session_exists': True, 'cooldown_until': None, 'error': None}})
+
+
+def worker_compression_counter(db, conn, sid, payload, *, column):
+ _fields(payload, ('value',))
+ value = payload['value']
+ if value is not None:
+ _number(value)
+ if column != 'compression_recovery_deadline' and (type(value) is not int or value < 0):
+ raise RuntimeStoreError('invalid_params')
+ conn.execute(f'UPDATE sessions SET {column}=? WHERE id=?', (value, sid))
+ return {'value': None}
+
+
+class CompressionSnapshot:
+ """Reuse production read algorithms on the receipt connection, never a second handle.
+
+ Only read primitives are provided; this object cannot start/commit a write.
+ Wire handlers below select concrete projections, not caller-named methods.
+ """
+ from hermes_state_compression import SessionCompressionMixin as _C
+ from hermes_state_messages import SessionMessagesMixin as _M
+ from hermes_state_sessions import SessionSessionsMixin as _S
+
+ get_compression_chain = _C.get_compression_chain
+ get_compression_tip = _C.get_compression_tip
+ get_compression_lineage = _C.get_compression_lineage
+ _is_compression_child_row = _C._is_compression_child_row
+ _session_lineage_root_to_tip = _S._session_lineage_root_to_tip
+ _is_explicit_branch_session = _S._is_explicit_branch_session
+ declared_scope_identity = _S.declared_scope_identity
+ _resume_lineage_ids = _M._resume_lineage_ids
+ get_conversation_root = _M.get_conversation_root
+ resolve_resume_session_id = _M.resolve_resume_session_id
+ latest_conversation_boundary = _M.latest_conversation_boundary
+ _is_explicit_fork_child_row = _M._is_explicit_fork_child_row
+
+ def __init__(self, db, conn):
+ self.db, self.conn = db, conn
+
+ def _read_ctx(self):
+ from contextlib import nullcontext
+ return nullcontext(self.conn)
+
+ def _read_one(self, sql, params=()):
+ return self.conn.execute(sql, params).fetchone()
+
+ def _read_all(self, sql, params=()):
+ return self.conn.execute(sql, params).fetchall()
+
+ def get_session(self, sid):
+ from hermes_state_worker_context import worker_context
+ return worker_context(self.db, self.conn, sid, {})['session']
+
+ def authorize(self, assigned, target):
+ _text(target)
+ # Attribution ancestry is readable; unrelated siblings and foreign trees are not.
+ allowed = self._session_lineage_root_to_tip(assigned)
+ allowed += self.get_compression_chain(assigned)
+ if target not in allowed:
+ raise RuntimeStoreError('permission_denied')
+
+
+def worker_lineage_context(db, conn, sid, payload):
+ _fields(payload, ('target',))
+ view = CompressionSnapshot(db, conn)
+ target = payload['target']
+ view.authorize(sid, target)
+ return {'session': view.get_session(target)}
+
+
+def worker_lineage(db, conn, sid, payload):
+ _fields(payload, ('target',))
+ view = CompressionSnapshot(db, conn)
+ target = payload['target']
+ view.authorize(sid, target)
+ return {'readable_ids': view._session_lineage_root_to_tip(sid) + view.get_compression_chain(sid),
+ 'lineage': view.get_compression_lineage(target),
+ 'root': view.get_conversation_root(target),
+ 'tip': view.get_compression_tip(target),
+ 'resume': view.resolve_resume_session_id(target),
+ 'identity': view.declared_scope_identity(target)}
+
+
+def worker_boundary(db, conn, sid, payload):
+ _fields(payload, ('session_key', 'source'))
+ view = CompressionSnapshot(db, conn)
+ row = view.get_session(sid)
+ if (row['session_key'], row['source']) != (payload['session_key'], payload['source']):
+ raise RuntimeStoreError('permission_denied')
+ return {'value': view.latest_conversation_boundary(payload['session_key'], payload['source'])}
+
+
+def worker_history(db, conn, sid, payload):
+ _fields(payload, ('target', 'include_ancestors', 'include_inactive', 'repair_alternation',
+ 'include_row_ids', 'include_compacted'))
+ if any(type(v) is not bool for k, v in payload.items() if k != 'target'):
+ raise RuntimeStoreError('invalid_params')
+ view = CompressionSnapshot(db, conn)
+ target = payload['target']
+ view.authorize(sid, target)
+ ids = view._resume_lineage_ids(target) if payload['include_ancestors'] else [target]
+ active = db._active_clause(payload['include_inactive'], payload['include_compacted'])
+ rows = conn.execute(f'SELECT {db._CONVERSATION_ROW_COLUMNS} FROM messages '
+ f'WHERE session_id IN ({",".join("?" for _ in ids)}){active} ORDER BY id', ids).fetchall()
+ if payload['include_compacted']:
+ rows = db._dedupe_display_generations(rows)
+ return {'messages': db._rows_to_conversation(rows, session_id=target,
+ include_ancestors=payload['include_ancestors'], repair_alternation=payload['repair_alternation'],
+ include_row_ids=payload['include_row_ids'])}
+
+
+
- from hermes_state_common import _COMPRESSION_LOCK_ROW_SQL, is_automatic_end_reason, _placeholders
- from hermes_state_messages import _ARCHIVE_ACTIVE_SQL, _SET_COUNTERS_SQL
- from hermes_state_errors import CompressionSessionBusyError, SessionCompressionInProgressError
- _LOCK_ROW_SQL = _COMPRESSION_LOCK_ROW_SQL
+
+
+def archive_on_connection(db, conn, session_id: str, compacted_messages: List[Dict[str, Any]], model_config_patch: Optional[Dict[str, Any]]=None, watermark: Optional[int]=None, lock_holder: Optional[str]=None, tail_count: int=0, carried_messages: Optional[List[Dict[str, Any]]]=None, covered_ids: Optional[List[int]]=None, unresolved_held: Optional[List[Dict[str, Any]]]=None):
- if lock_holder is not None:
- lock_row = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone()
- if lock_row is None or lock_row['holder'] != lock_holder or float(lock_row['expires_at']) <= time.time():
- raise SessionCompressionInProgressError(f'Compression lease for {session_id!r} lost before commit; refusing to publish a stale compaction')
- patch = model_config_patch is not None
- patched_model_config = db._merge_model_config_json(conn, session_id, model_config_patch, on_missing='raise') if patch else None
- # Same held-row coverage rule as SessionDB.archive_and_compact: when the compressor named the
- # rows it held, archive exactly those and clone the rest instead of trusting the watermark.
- proved = db._proved_coverage(conn, session_id, covered_ids, unresolved_held)
- if proved is not None:
- return db._archive_named_rows(conn, session_id, compacted_messages, proved, tail_count=tail_count,
- carried_messages=carried_messages, patched_model_config=patched_model_config, patch=patch)
- tail_ids, tail_tool_calls = ([], 0) if watermark is None else db._tail_rows_after_watermark(conn, 'SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ? ORDER BY id', (session_id, int(watermark)))
- # Same rewind set as SessionDB.archive_and_compact: carried originals (#118900), then the tail.
- rewind_ids: list[int] = db._resolve_carried_row_ids(conn, session_id, carried_messages or [])
- if tail_count > 0:
- bound = watermark is not None
- rewind_ids += [int(row['id']) for row in conn.execute(f"SELECT id FROM messages WHERE session_id = ? AND active = 1{(' AND id <= ?' if bound else '')} ORDER BY id DESC LIMIT ?", (session_id, *((int(watermark),) if bound else ()), int(tail_count))).fetchall()]
- rewind_ids += tail_ids
- rewind_ids = list(dict.fromkeys(rewind_ids))
- if rewind_ids:
- placeholders = _placeholders(rewind_ids)
- conn.execute(f'UPDATE messages SET active = 0, compacted = 0 WHERE session_id = ? AND id IN ({placeholders})', [session_id, *rewind_ids])
- conn.execute(f'{_ARCHIVE_ACTIVE_SQL} AND id NOT IN ({placeholders})', [session_id, *rewind_ids])
- else:
- conn.execute(_ARCHIVE_ACTIVE_SQL, (session_id,))
- inserted, tool_calls_total = db._insert_message_rows(conn, session_id, compacted_messages)
- if tail_ids:
- db._clone_message_rows(conn, tail_ids)
- inserted += len(tail_ids)
- tool_calls_total += tail_tool_calls
- conn.execute(f"{_SET_COUNTERS_SQL}{(', model_config = ?' if patch else '')} WHERE id = ?", (inserted, tool_calls_total, *((patched_model_config,) if patch else ()), session_id))
- return inserted
++ # The owner's in-place compaction body, on this receipt's connection: one implementation, so
++ # main's coverage/merge/timestamp/display-order fixes reach worker and mutation verbs too.
++ return db._archive_and_compact_on_conn(conn, session_id, compacted_messages,
++ model_config_patch=model_config_patch, watermark=watermark, lock_holder=lock_holder,
++ tail_count=tail_count, carried_messages=carried_messages, covered_ids=covered_ids,
++ unresolved_held=unresolved_held)
+
+def publish_on_connection(db, conn, *, parent_session_id: str, child_session_id: str, source: str, messages: List[Dict[str, Any]], model: str=None, model_config: Dict[str, Any]=None, system_prompt: str=None, cwd: str=None, profile_name: str=None, compression_lock_holder: str=None, require_compression_lease: bool=True, require_lease_refresh: bool=False, lease_ttl_seconds: float=300.0, watermark: Optional[int]=None, watermark_ceiling: Optional[int]=None):
- if require_lease_refresh and compression_lock_holder:
- conn.execute('UPDATE compression_locks SET expires_at = ? WHERE session_id = ? AND holder = ?', (time.time() + lease_ttl_seconds, parent_session_id, compression_lock_holder))
- lock_row = conn.execute(_LOCK_ROW_SQL, (parent_session_id,)).fetchone()
- if require_compression_lease and (lock_row is None or not compression_lock_holder or lock_row['holder'] != compression_lock_holder or (float(lock_row['expires_at']) <= time.time())):
- raise CompressionSessionBusyError(f'Compression lease lost before publication: {parent_session_id}')
- parent = conn.execute('SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,\n user_id, session_key, chat_id, chat_type,\n thread_id, display_name, origin_json, profile_name, tool_names\n FROM sessions WHERE id = ?', (parent_session_id,)).fetchone()
- if parent is None:
- raise RuntimeError(f'Compression parent not found: {parent_session_id}')
- if parent['ended_at'] is not None:
- if not is_automatic_end_reason(parent['end_reason']):
- raise RuntimeError(f'Compression parent already ended: {parent_session_id}')
- conn.execute('UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?', (parent_session_id,))
- if not messages:
- raise RuntimeError('Compression child handoff must not be empty')
- db._publish_child_session_row(conn, parent, parent_session_id=parent_session_id, child_session_id=child_session_id, source=source, model=model, model_config=model_config, system_prompt=system_prompt, cwd=cwd, profile_name=profile_name)
- total_messages, total_tool_calls = db._insert_message_rows(conn, child_session_id, messages)
- if watermark is not None:
- bounded = watermark_ceiling is not None
- tail_ids, tail_tool_calls = db._tail_rows_after_watermark(conn, f"SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ?{(' AND id <= ?' if bounded else '')} ORDER BY id", [parent_session_id, int(watermark), *([int(watermark_ceiling)] if bounded else [])])
- if tail_ids:
- db._clone_message_rows(conn, tail_ids, session_id=child_session_id)
- total_messages += len(tail_ids)
- total_tool_calls += tail_tool_calls
- conn.execute('UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?', (total_messages, total_tool_calls, child_session_id))
- updated = conn.execute("UPDATE sessions SET ended_at = ?, end_reason = 'compression' WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id))
- if updated.rowcount != 1:
- raise RuntimeError(f'Compression parent changed during publication: {parent_session_id}')
- from hermes_state_local_lineage import advance_local_target
- advance_local_target(conn, parent_session_id, child_session_id)
-
++ # The owner's rotation body (lease, closure, child row, timestamps, tail clone, local target,
++ # auto-archive lift) on this receipt's connection, so the two paths cannot drift.
++ db._publish_compression_child_on_conn(conn, parent_session_id=parent_session_id,
++ child_session_id=child_session_id, source=source, messages=messages, model=model,
++ model_config=model_config, system_prompt=system_prompt, cwd=cwd, profile_name=profile_name,
++ compression_lock_holder=compression_lock_holder, require_compression_lease=require_compression_lease,
++ require_lease_refresh=require_lease_refresh, lease_ttl_seconds=lease_ttl_seconds,
++ watermark=watermark, watermark_ceiling=watermark_ceiling)
+
+def worker_watermark(db, conn, sid, payload):
+ _fields(payload, ())
+ return {'value': conn.execute('SELECT COALESCE(MAX(id),0) FROM messages WHERE session_id=? AND active=1',
+ (sid,)).fetchone()[0]}
+
+
+def _handoff_messages(conn, sid, messages):
+ from hermes_state_runtime import _MESSAGE_FIELDS
+ if not isinstance(messages, list) or len(messages) > 1000:
+ raise RuntimeStoreError('invalid_params')
+ for msg in messages:
+ if not isinstance(msg, dict) or set(msg) - _MESSAGE_FIELDS - {'_compressed_summary_has_user_turn'} or msg.get('role') not in ('user', 'assistant', 'system', 'tool'):
+ raise RuntimeStoreError('invalid_params')
+ if '_row_id' in msg and not conn.execute('SELECT 1 FROM messages WHERE session_id=? AND id=?',
+ (sid, msg['_row_id'])).fetchone():
+ raise RuntimeStoreError('permission_denied')
+
+
+def _watermarks(payload):
+ for field in ('watermark', 'watermark_ceiling'):
+ value = payload.get(field)
+ if value is not None and (type(value) is not int or value < 0):
+ raise RuntimeStoreError('invalid_params')
+
+
+def worker_archive(db, conn, sid, payload):
+ from hermes_state_worker_context import SIDECAR_KEYS
+ _fields(payload, ('messages', 'model_config_patch', 'watermark', 'lock_holder', 'tail_count'),
+ optional=('carried_messages', 'covered_ids', 'unresolved_held'))
+ _handoff_messages(conn, sid, payload['messages'])
+ carried = payload.get('carried_messages') or []
+ if not isinstance(carried, list) or any(not isinstance(m, dict) for m in carried):
+ raise RuntimeStoreError('invalid_params')
+ covered = payload.get('covered_ids')
+ if covered is not None and (not isinstance(covered, list)
+ or any(type(i) is not int or i <= 0 for i in covered)):
+ raise RuntimeStoreError('invalid_params')
+ unresolved = payload.get('unresolved_held')
+ if unresolved is not None and (not isinstance(unresolved, list)
+ or any(not isinstance(m, dict) for m in unresolved)):
+ raise RuntimeStoreError('invalid_params')
+ _watermarks(payload)
+ # Micro-compaction and proactive prune archive in place without a lease, like the owner path.
+ if payload['lock_holder'] is not None:
+ _text(payload['lock_holder'])
+ patch = payload['model_config_patch']
+ if patch is not None and (not isinstance(patch, dict) or set(patch) - SIDECAR_KEYS):
+ raise RuntimeStoreError('invalid_params')
+ if type(payload['tail_count']) is not int or payload['tail_count'] < 0:
+ raise RuntimeStoreError('invalid_params')
+ value = archive_on_connection(db, conn, sid, payload['messages'], model_config_patch=patch,
+ watermark=payload['watermark'], lock_holder=payload['lock_holder'], tail_count=payload['tail_count'],
+ carried_messages=carried, covered_ids=covered, unresolved_held=unresolved)
+ return {'value': value, 'row_ids': [message['_row_id'] for message in payload['messages']]}
+
+
+def _migrate_worker_automation(db, conn, parent, child):
+ from hermes_cli.goals import GoalState
+ from hermes_cli.heartbeat import HeartbeatState
+ from hermes_cli.loops import LoopState
+ for family, state_type in (('goal', GoalState), ('heartbeat', HeartbeatState), ('loop', LoopState)):
+ old_key, new_key = f'{family}:{parent}', f'{family}:{child}'
+ row = conn.execute('SELECT value FROM state_meta WHERE key=?', (old_key,)).fetchone()
+ if row is None:
+ continue
+ state = state_type.from_json(row[0])
+ if state.status == 'cleared':
+ continue
+ prior = conn.execute('SELECT value FROM state_meta WHERE key=?', (new_key,)).fetchone()
+ if prior is not None and (family != 'heartbeat' or state_type.from_json(prior[0]).status != 'cleared'):
+ continue
+ db.set_meta(new_key, state.to_json(), cursor=conn)
+ state.status = 'cleared'
+ db.set_meta(old_key, state.to_json(), cursor=conn)
+
+
+def worker_publish(db, conn, sid, payload):
+ from hermes_state_sessions import _parse_model_config
+ _fields(payload, ('child_session_id', 'source', 'messages', 'model', 'model_config', 'system_prompt',
+ 'cwd', 'profile_name', 'compression_lock_holder', 'require_compression_lease',
+ 'require_lease_refresh', 'lease_ttl_seconds', 'watermark', 'watermark_ceiling'))
+ child = _text(payload['child_session_id'])
+ _text(payload['compression_lock_holder'])
+ _watermarks(payload)
+ if payload['require_compression_lease'] is not True or type(payload['require_lease_refresh']) is not bool:
+ raise RuntimeStoreError('invalid_params')
+ if not 0.1 <= _number(payload['lease_ttl_seconds']) <= 3600:
+ raise RuntimeStoreError('invalid_params')
+ _handoff_messages(conn, sid, payload['messages'])
+ parent = CompressionSnapshot(db, conn).get_session(sid)
+ for key in ('source', 'cwd', 'profile_name'):
+ if payload[key] is not None and payload[key] != parent[key]:
+ raise RuntimeStoreError('permission_denied')
+ for key in ('model', 'system_prompt'):
+ if payload[key] is not None and not isinstance(payload[key], str):
+ raise RuntimeStoreError('invalid_params')
+ cfg = payload['model_config']
+ if cfg is not None and not isinstance(cfg, dict):
+ raise RuntimeStoreError('invalid_params')
+ cfg = dict(cfg or {})
+ prior = _parse_model_config(parent['model_config'])
+ for key in ('_branched_from', '_delegate_from', '_reset_from'):
+ if key in cfg and cfg[key] != prior.get(key):
+ raise RuntimeStoreError('permission_denied')
+ if key in prior:
+ cfg[key] = prior[key]
+ if conn.execute('SELECT 1 FROM sessions WHERE id=?', (child,)).fetchone():
+ raise RuntimeStoreError('permission_denied')
+ worker = conn.execute("SELECT * FROM worker_executions WHERE session_id=? AND status IN ('registered','running')", (sid,)).fetchone()
+ if worker is None:
+ raise RuntimeStoreError('stale_generation')
+ publish_on_connection(db, conn, parent_session_id=sid, **dict(payload, model_config=cfg))
+ _migrate_worker_automation(db, conn, sid, child)
+ conn.execute('UPDATE sessions SET runtime_generation=? WHERE id=?', (worker['generation'], child))
+ conn.execute('UPDATE worker_executions SET session_id=? WHERE execution_id=?', (child, worker['execution_id']))
+ # The FIFO/retry key is immutable; only physical lineage follows rotation.
+ conn.execute("UPDATE session_admissions SET lineage_json=json_insert(lineage_json,'$[#]',?) "
+ "WHERE json_extract(lineage_json,'$[#-1]')=? AND generation=? AND owner_epoch=? "
+ "AND status IN ('started','unknown')",
+ (child, sid, worker['generation'], worker['owner_epoch']))
+ return {'value': None, 'worker_assignment': {'parent': sid, 'session_id': child},
+ 'row_ids': [message['_row_id'] for message in payload['messages']]}
+
+
+def worker_receipt_assignment(conn, execution_id, session_id, generation, sequence, digest):
+ """Only an identical already-committed publication can retry its old assignment."""
+ from hermes_state_runtime import _worker_assignment
+ receipt = conn.execute('SELECT payload_digest,result_json FROM worker_receipts WHERE execution_id=? AND sequence=?',
+ (execution_id, sequence)).fetchone()
+ if receipt and receipt['payload_digest'] == digest:
+ assignment = json.loads(receipt['result_json']).get('worker_assignment')
+ if assignment and assignment['parent'] == session_id:
+ current = conn.execute('SELECT session_id FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()
+ return _worker_assignment(conn, execution_id, current['session_id'], generation)
+ return _worker_assignment(conn, execution_id, session_id, generation)
+
+
+def worker_claim_origin(db, params):
+ """Keep the producer claim bound to its original identity after physical rotation."""
+ with db._read_ctx() as conn:
+ row = conn.execute("SELECT result_json FROM worker_receipts WHERE execution_id=? "
+ "AND json_extract(result_json,'$.worker_assignment.parent') IS NOT NULL ORDER BY sequence LIMIT 1",
+ (params['execution_id'],)).fetchone()
+ return json.loads(row[0])['worker_assignment']['parent'] if row else params['session_id']
+
+
+def worker_retry_target(db, params):
+ """Transport verification accepts old targets only for exact publication replay."""
+ from gateway.session_admission import admission_fingerprint
+ if params.get('operation') != 'compression.publish':
+ return params['session_id']
+ digest = admission_fingerprint(canonical_target=params['session_id'],
+ payload={'operation': params['operation'], 'payload': params['payload']})
+ with db._read_ctx() as conn:
+ row = worker_receipt_assignment(conn, params['execution_id'], params['session_id'],
+ params['generation'], params['sequence'], digest)
+ return row['session_id']
+
+
- from hermes_state_common import _ENDED_ROW_SQL, _ended_by_compression
++from hermes_state_common import _COMPRESSION_LOCK_ROW_SQL as _LOCK_ROW_SQL, _ENDED_ROW_SQL, _ended_by_compression
+
+def reopen_on_connection(db, conn, session_id):
+ if not _ended_by_compression(conn.execute(_ENDED_ROW_SQL, (session_id,)).fetchone()):
+ return False
+ child = conn.execute('\n SELECT 1\n FROM sessions\n WHERE parent_session_id = ?\n ' + db._NON_CONTINUATION_CHILD_FILTER_SQL.format(alias='') + '\n LIMIT 1\n ', (session_id,) * 4).fetchone()
+ if child is not None:
+ return False
+ now = time.time()
+ lock_row = conn.execute(_LOCK_ROW_SQL, (session_id,)).fetchone()
+ if lock_row is not None:
+ expires_at = lock_row['expires_at']
+ if expires_at is None or float(expires_at) >= now:
+ return False
+ deleted = conn.execute('DELETE FROM compression_locks WHERE session_id = ? AND holder = ? AND expires_at = ?', (session_id, lock_row['holder'], expires_at))
+ if deleted.rowcount != 1:
+ return False
+ updated = conn.execute("UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ? AND ended_at IS NOT NULL AND end_reason = 'compression'", (session_id,))
+ return updated.rowcount == 1
+
+
+def worker_reopen(db, conn, sid, payload):
+ _fields(payload, ())
+ return {'value': reopen_on_connection(db, conn, sid)}
+
+
+def worker_compression_cleanup(db, conn, sid, payload):
+ _fields(payload, ('target', 'holder'))
+ target = _text(payload['target'])
+ holder = _text(payload['holder'])
+ view = CompressionSnapshot(db, conn)
+ view.authorize(sid, target)
+ if db._session_turn_lease_key_on_conn(conn, sid) != db._session_turn_lease_key_on_conn(conn, target):
+ raise RuntimeStoreError('permission_denied')
+ conn.execute('DELETE FROM compression_locks WHERE session_id=? AND holder=?', (target, holder))
+ return {'value': None}
+
+
+def worker_compression_append(db, conn, sid, payload):
+ _fields(payload, ('messages', 'compression_lock_holder', 'turn_lease_holder', 'turn_lease_ttl_seconds'))
+ _handoff_messages(conn, sid, payload['messages'])
+ for key in ('compression_lock_holder', 'turn_lease_holder'):
+ if payload[key] is not None:
+ _text(payload[key])
+ if not 0.1 <= _number(payload['turn_lease_ttl_seconds']) <= 3600:
+ raise RuntimeStoreError('invalid_params')
+ count = db._append_messages_in_transaction(conn, sid, **payload)
+ from hermes_state_runtime import row_annotations
+ return {'count': count, 'annotations': row_annotations(payload['messages'])}
+
+
+def worker_turn_cleanup(db, conn, sid, payload):
+ _fields(payload, ('target', 'holder'))
+ target = _text(payload['target'])
+ holder = _text(payload['holder'])
+ CompressionSnapshot(db, conn).authorize(sid, target)
+ key = db._session_turn_lease_key_on_conn(conn, sid)
+ if key != db._session_turn_lease_key_on_conn(conn, target):
+ raise RuntimeStoreError('permission_denied')
+ conn.execute('DELETE FROM session_turn_leases WHERE conversation_id=? AND holder=?', (key, holder))
+ return {'released': True}
+
+
+WORKER_COMPRESSION_HANDLERS = {
+ 'turn.cleanup': worker_turn_cleanup,
+ 'compression.append': worker_compression_append,
+ 'compression.reopen': worker_reopen,
+ 'compression.cleanup': worker_compression_cleanup,
+ 'compression.watermark': worker_watermark,
+ 'compression.archive': worker_archive,
+ 'compression.publish': worker_publish,
+ 'compression.context': worker_lineage_context,
+ 'compression.lineage': worker_lineage,
+ 'compression.boundary': worker_boundary,
+ 'compression.history': worker_history,
+ **{'compression.lock.' + action: partial(worker_compression_lock, action=action)
+ for action in ('acquire', 'renew', 'release', 'holder')},
+ 'compression.cooldown.record': worker_cooldown_record,
+ 'compression.cooldown.restore': worker_cooldown_restore,
+ 'compression.cooldown.clear': worker_cooldown_clear,
+ **{'compression.' + name: partial(worker_compression_counter, column=column)
+ for name, column in (('fallback', 'compression_fallback_streak'),
+ ('ineffective', 'compression_ineffective_count'),
+ ('recovery', 'compression_recovery_deadline'))},
+}
diff --cc hermes_state_worker_context.py
index f679a4f8d4f,00000000000..4fc72322590
mode 100644,000000..100644
--- a/hermes_state_worker_context.py
+++ b/hermes_state_worker_context.py
@@@ -1,65 -1,0 +1,68 @@@
+"""Closed constructor-context operations inside the worker receipt transaction.
+
+Identity and lineage remain owner-reserved. This is not arbitrary SessionDB RPC.
+"""
+import json
+
+from hermes_state_runtime import RuntimeStoreError
+
+
- SIDECAR_KEYS = frozenset({'_usage_anchor', '_proactive_prune_rearm_tokens'})
++# model_config sidecars a worker may patch: every key the agent persists via
++# ``patch_session_model_config`` (``_anthropic_rejected_thinking``: main's rejected-signature
++# fingerprints, agent/anthropic_thinking_replay.py) or a compaction ``model_config_patch``.
++SIDECAR_KEYS = frozenset({'_usage_anchor', '_proactive_prune_rearm_tokens', '_anthropic_rejected_thinking'})
+
+
+def worker_context(db, conn, session_id, payload):
+ if payload:
+ raise RuntimeStoreError('invalid_params')
+ row = conn.execute(
+ 'SELECT s.*, COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved, '
+ 'COALESCE(tp.prompt, s.tool_names) AS _tool_names_resolved '
+ 'FROM sessions s LEFT JOIN system_prompts sp ON sp.hash=s.system_prompt_hash '
+ 'LEFT JOIN system_prompts tp ON tp.hash=s.tool_names WHERE s.id=?',
+ (session_id,),
+ ).fetchone()
+ return {'session': db._session_row_dict(row)}
+
+
+def worker_prompt(db, conn, session_id, payload):
+ if set(payload) != {'system_prompt'} or not (
+ payload['system_prompt'] is None or isinstance(payload['system_prompt'], str)):
+ raise RuntimeStoreError('invalid_params')
+ conn.execute('UPDATE sessions SET system_prompt_hash=?, system_prompt=NULL WHERE id=?',
+ (db._store_system_prompt(conn, payload['system_prompt']), session_id))
+ db._delete_unreferenced_system_prompts(conn)
+ return {'value': None}
+
+
+def worker_sidecars(db, conn, session_id, payload):
+ if set(payload) != {'patch'} or not isinstance(payload['patch'], dict) or set(payload['patch']) - SIDECAR_KEYS:
+ raise RuntimeStoreError('invalid_params')
+ merged = db._merge_model_config_json(conn, session_id, payload['patch'], on_missing='raise')
+ conn.execute('UPDATE sessions SET model_config=? WHERE id=?', (merged, session_id))
+ return {'value': None}
+
+
+def worker_tool_names(db, conn, session_id, payload):
+ """The tools[] pin, same contract as ``SessionDB.update_session_tool_names``: any JSON pin
+ (``{"version", "tools"}`` today; a legacy name list) content-addressed through ``system_prompts``,
+ ``None`` clears. Bounded so a worker cannot write an unbounded blob into the shared table."""
+ if set(payload) != {'tool_names'}:
+ raise RuntimeStoreError('invalid_params')
+ pin = payload['tool_names']
+ if pin is not None:
+ if not isinstance(pin, (list, dict)):
+ raise RuntimeStoreError('invalid_params')
+ if isinstance(pin, list) and not all(isinstance(n, str) and 0 < len(n) <= 256 for n in pin):
+ raise RuntimeStoreError('invalid_params')
+ if isinstance(pin, dict) and (set(pin) != {'version', 'tools'} or not isinstance(pin['version'], str)
+ or not isinstance(pin['tools'], list)):
+ raise RuntimeStoreError('invalid_params')
+ encoded = None if pin is None else json.dumps(pin)
+ if encoded is not None and len(encoded) > 4 * 1024 * 1024:
+ raise RuntimeStoreError('invalid_params')
+ conn.execute('UPDATE sessions SET tool_names=? WHERE id=?',
+ (db._store_system_prompt(conn, encoded), session_id))
+ db._delete_unreferenced_system_prompts(conn)
+ return {'value': None}
diff --cc locales/_keys.desktop.json
index 00000000000,a533a9dde43..601f6fe7273
mode 000000,100644..100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@@ -1,0 -1,4959 +1,4964 @@@
+ {
+ "surface": "desktop",
+ "keys": [
+ "agents.activeCount",
+ "agents.ageDays",
+ "agents.ageHours",
+ "agents.ageMinutes",
+ "agents.ageNow",
+ "agents.ageSeconds",
+ "agents.agentsCount",
+ "agents.close",
+ "agents.delegation",
+ "agents.done",
+ "agents.durationMinutes",
+ "agents.durationSeconds",
+ "agents.emptyDesc",
+ "agents.emptyTitle",
+ "agents.extendedTranscript",
+ "agents.failed",
+ "agents.failedCount",
+ "agents.files",
+ "agents.filesCount",
+ "agents.moreAgents",
+ "agents.moreFiles",
+ "agents.queued",
+ "agents.requestRejected",
+ "agents.running",
+ "agents.steer",
+ "agents.steerPlaceholder",
+ "agents.steerQueued",
+ "agents.stopRequested",
+ "agents.streaming",
+ "agents.subtitle",
+ "agents.title",
+ "agents.tokens",
+ "agents.toolsCount",
+ "agents.transcriptTruncated",
+ "agents.transcriptUnavailable",
+ "agents.updatedAgo",
+ "agents.waitingActivity",
+ "agents.workers",
+ "agents.workersActive",
+ "artifactCard.generating",
+ "artifactCard.kind.code",
+ "artifactCard.kind.html",
+ "artifactCard.kind.svg",
+ "artifactCard.open",
+ "artifactCard.versionBadge",
+ "artifactPreview.copyContent",
+ "artifactPreview.download",
+ "artifactPreview.latest",
+ "artifactPreview.missingBody",
+ "artifactPreview.missingTitle",
+ "artifactPreview.newerVersion",
+ "artifactPreview.olderVersion",
+ "artifactPreview.openInBrowser",
+ "artifactPreview.openInBrowserFailed",
+ "artifactPreview.versionOf",
+ "artifacts.chat",
+ "artifacts.colLocationDefault",
+ "artifacts.colLocationFile",
+ "artifacts.colLocationLink",
+ "artifacts.colSession",
+ "artifacts.colTitleDefault",
+ "artifacts.colTitleFile",
+ "artifacts.colTitleLink",
+ "artifacts.copyPath",
+ "artifacts.copyUrl",
+ "artifacts.failedLoad",
+ "artifacts.goToPage",
+ "artifacts.indexing",
+ "artifacts.itemsFile",
+ "artifacts.itemsGeneric",
+ "artifacts.itemsImage",
+ "artifacts.itemsLink",
+ "artifacts.kindFile",
+ "artifacts.kindImage",
+ "artifacts.kindLink",
+ "artifacts.noArtifactsDesc",
+ "artifacts.noArtifactsTitle",
+ "artifacts.openFailed",
+ "artifacts.rangeOf",
+ "artifacts.refresh",
+ "artifacts.refreshing",
+ "artifacts.search",
+ "artifacts.tabAll",
+ "artifacts.tabFiles",
+ "artifacts.tabImages",
+ "artifacts.tabLinks",
+ "artifacts.zero",
+ "assistant.approval.allowSession",
+ "assistant.approval.alwaysAllow",
+ "assistant.approval.alwaysAllowMenu",
+ "assistant.approval.alwaysDescription",
+ "assistant.approval.alwaysTitle",
+ "assistant.approval.command",
+ "assistant.approval.commandDetails",
+ "assistant.approval.gatewayDisconnected",
+ "assistant.approval.jumpToApproval",
+ "assistant.approval.moreOptions",
+ "assistant.approval.openSafetySettings",
+ "assistant.approval.reconnect",
+ "assistant.approval.reject",
+ "assistant.approval.run",
+ "assistant.approval.sendFailed",
+ "assistant.approval.timedOutSystemLine",
+ "assistant.catalogInstall.advanced",
+ "assistant.catalogInstall.commitLabel",
+ "assistant.catalogInstall.credentialsHeading",
+ "assistant.catalogInstall.failed",
+ "assistant.catalogInstall.hideNames",
+ "assistant.catalogInstall.install",
+ "assistant.catalogInstall.installed",
+ "assistant.catalogInstall.installing",
+ "assistant.catalogInstall.kind.plugin",
+ "assistant.catalogInstall.kind.skill",
+ "assistant.catalogInstall.notInstalled",
+ "assistant.catalogInstall.preparing",
+ "assistant.catalogInstall.requirementsLabel",
+ "assistant.catalogInstall.scan.failed",
+ "assistant.catalogInstall.scan.passed",
+ "assistant.catalogInstall.scan.warnings",
+ "assistant.catalogInstall.securityHeading",
+ "assistant.catalogInstall.sendFailed",
+ "assistant.catalogInstall.showNames",
+ "assistant.catalogInstall.skill",
+ "assistant.catalogInstall.skip",
+ "assistant.catalogInstall.subdirLabel",
+ "assistant.catalogInstall.targetProfile",
+ "assistant.catalogInstall.tier.community",
+ "assistant.catalogInstall.tier.official",
+ "assistant.clarify.confirmAndContinueLabel",
+ "assistant.clarify.gatewayDisconnected",
+ "assistant.clarify.loadingQuestion",
+ "assistant.clarify.multiSelectHint",
+ "assistant.clarify.noAnswer",
+ "assistant.clarify.notDelivered",
+ "assistant.clarify.notReady",
+ "assistant.clarify.other",
+ "assistant.clarify.placeholder",
+ "assistant.clarify.questionProgress",
+ "assistant.clarify.sendFailed",
+ "assistant.clarify.singleSelectHint",
+ "assistant.clarify.skip",
+ "assistant.clarify.skipped",
+ "assistant.mcpSetup.authorizeAction",
+ "assistant.mcpSetup.authorizeTitle",
+ "assistant.mcpSetup.authorized",
+ "assistant.mcpSetup.enableAction",
+ "assistant.mcpSetup.enableTitle",
+ "assistant.mcpSetup.enabled",
+ "assistant.mcpSetup.envRequired",
+ "assistant.mcpSetup.failed",
+ "assistant.mcpSetup.gatewayDisconnected",
+ "assistant.mcpSetup.installAction",
+ "assistant.mcpSetup.installTitle",
+ "assistant.mcpSetup.installed",
+ "assistant.mcpSetup.reloadFailed",
+ "assistant.mcpSetup.sendFailed",
+ "assistant.mcpSetup.toolCount",
+ "assistant.thread.attachingFile",
+ "assistant.thread.branchNewChat",
+ "assistant.thread.copy",
+ "assistant.thread.copyFullResponse",
+ "assistant.thread.dismissError",
+ "assistant.thread.editMessage",
+ "assistant.thread.errorAuthKinds.api_key.body",
+ "assistant.thread.errorAuthKinds.api_key.title",
+ "assistant.thread.errorAuthKinds.oauth.title",
+ "assistant.thread.errorChooseModel",
+ "assistant.thread.errorCodes.SESSION_NOT_OWNED.body",
+ "assistant.thread.errorCodes.SESSION_NOT_OWNED.title",
+ "assistant.thread.errorCodes.auth.body",
+ "assistant.thread.errorCodes.auth.title",
+ "assistant.thread.errorCodes.auth_permanent.body",
+ "assistant.thread.errorCodes.auth_permanent.title",
+ "assistant.thread.errorCodes.billing.body",
+ "assistant.thread.errorCodes.billing.title",
+ "assistant.thread.errorCodes.content_policy_blocked.body",
+ "assistant.thread.errorCodes.content_policy_blocked.title",
+ "assistant.thread.errorCodes.context_overflow.body",
+ "assistant.thread.errorCodes.context_overflow.title",
+ "assistant.thread.errorCodes.disk_full.body",
+ "assistant.thread.errorCodes.disk_full.title",
+ "assistant.thread.errorCodes.empty_response.body",
+ "assistant.thread.errorCodes.empty_response.title",
+ "assistant.thread.errorCodes.format_error.body",
+ "assistant.thread.errorCodes.format_error.title",
+ "assistant.thread.errorCodes.free_tier_at_capacity.body",
+ "assistant.thread.errorCodes.free_tier_at_capacity.title",
+ "assistant.thread.errorCodes.free_tier_disabled.body",
+ "assistant.thread.errorCodes.free_tier_disabled.title",
+ "assistant.thread.errorCodes.free_tier_model_not_free.body",
+ "assistant.thread.errorCodes.free_tier_model_not_free.title",
+ "assistant.thread.errorCodes.free_tier_outage.body",
+ "assistant.thread.errorCodes.free_tier_outage.title",
+ "assistant.thread.errorCodes.free_tier_rate_limited.body",
+ "assistant.thread.errorCodes.free_tier_rate_limited.title",
+ "assistant.thread.errorCodes.free_tier_refused.body",
+ "assistant.thread.errorCodes.free_tier_refused.title",
+ "assistant.thread.errorCodes.free_tier_route.body",
+ "assistant.thread.errorCodes.free_tier_route.title",
+ "assistant.thread.errorCodes.invalid_response.body",
+ "assistant.thread.errorCodes.invalid_response.title",
+ "assistant.thread.errorCodes.loop_error.body",
+ "assistant.thread.errorCodes.loop_error.title",
+ "assistant.thread.errorCodes.model_not_found.body",
+ "assistant.thread.errorCodes.model_not_found.title",
+ "assistant.thread.errorCodes.no_reply.body",
+ "assistant.thread.errorCodes.no_reply.title",
+ "assistant.thread.errorCodes.overloaded.body",
+ "assistant.thread.errorCodes.overloaded.title",
+ "assistant.thread.errorCodes.payload_too_large.body",
+ "assistant.thread.errorCodes.payload_too_large.title",
+ "assistant.thread.errorCodes.provider_policy_blocked.body",
+ "assistant.thread.errorCodes.provider_policy_blocked.title",
+ "assistant.thread.errorCodes.rate_limit.body",
+ "assistant.thread.errorCodes.rate_limit.title",
+ "assistant.thread.errorCodes.server_error.body",
+ "assistant.thread.errorCodes.server_error.title",
+ "assistant.thread.errorCodes.ssl_cert_verification.body",
+ "assistant.thread.errorCodes.ssl_cert_verification.title",
+ "assistant.thread.errorCodes.stream_drop.body",
+ "assistant.thread.errorCodes.stream_drop.title",
+ "assistant.thread.errorCodes.timeout.body",
+ "assistant.thread.errorCodes.timeout.title",
+ "assistant.thread.errorCodes.truncated.body",
+ "assistant.thread.errorCodes.truncated.title",
+ "assistant.thread.errorCodes.upstream_blocked.body",
+ "assistant.thread.errorCodes.upstream_blocked.title",
+ "assistant.thread.errorCodes.upstream_rate_limit.body",
+ "assistant.thread.errorCodes.upstream_rate_limit.title",
+ "assistant.thread.errorCompressConversation",
+ "assistant.thread.errorCompressFailed",
+ "assistant.thread.errorCopyDiagnostics",
+ "assistant.thread.errorDetails",
+ "assistant.thread.errorGenericProvider",
+ "assistant.thread.errorLayerBodies.auth",
+ "assistant.thread.errorLayerBodies.billing",
+ "assistant.thread.errorLayerBodies.disk",
+ "assistant.thread.errorLayerBodies.endpoint",
+ "assistant.thread.errorLayerBodies.gateway",
+ "assistant.thread.errorLayerBodies.generic",
+ "assistant.thread.errorLayerBodies.provider",
+ "assistant.thread.errorLayerBodies.runtime",
+ "assistant.thread.errorLayerBodies.streaming",
+ "assistant.thread.errorLayers.auth",
+ "assistant.thread.errorLayers.billing",
+ "assistant.thread.errorLayers.disk",
+ "assistant.thread.errorLayers.endpoint",
+ "assistant.thread.errorLayers.gateway",
+ "assistant.thread.errorLayers.generic",
+ "assistant.thread.errorLayers.provider",
+ "assistant.thread.errorLayers.runtime",
+ "assistant.thread.errorLayers.streaming",
+ "assistant.thread.errorLimitResets",
+ "assistant.thread.errorOauthExpired",
+ "assistant.thread.errorOpenDesktopLogs",
+ "assistant.thread.errorOpenHermesFolder",
+ "assistant.thread.errorOpenHermesFolderFailed",
+ "assistant.thread.errorOpenLogs",
+ "assistant.thread.errorOpenLogsFailed",
+ "assistant.thread.errorRetry",
+ "assistant.thread.errorRetryAtReset",
+ "assistant.thread.errorRetryScheduled",
+ "assistant.thread.errorRetryScheduledCancel",
+ "assistant.thread.errorSendDiagnostics",
+ "assistant.thread.errorSignInAgain",
+ "assistant.thread.errorSignInFreeTier",
+ "assistant.thread.errorStartNewSession",
+ "assistant.thread.errorSwitchProvider",
+ "assistant.thread.errorToastTitle",
+ "assistant.thread.errorUpdateApiKey",
+ "assistant.thread.expandMessage",
+ "assistant.thread.filesChanged",
+ "assistant.thread.goForward",
+ "assistant.thread.loadingLocalModel",
+ "assistant.thread.loadingResponse",
+ "assistant.thread.loadingSession",
+ "assistant.thread.moreActions",
+ "assistant.thread.preparingAudio",
+ "assistant.thread.processingPrompt",
+ "assistant.thread.react",
+ "assistant.thread.readAloud",
+ "assistant.thread.readAloudFailed",
+ "assistant.thread.readAloudFullResponseHint",
+ "assistant.thread.refresh",
+ "assistant.thread.responseStopped",
+ "assistant.thread.restoreBody",
+ "assistant.thread.restoreCheckpoint",
+ "assistant.thread.restoreConfirm",
+ "assistant.thread.restoreFromHere",
+ "assistant.thread.restoreNext",
+ "assistant.thread.restorePrevious",
+ "assistant.thread.restoreTitle",
+ "assistant.thread.resumeWhenBackgroundDone",
+ "assistant.thread.reviewChanges",
+ "assistant.thread.scrollToBottom",
+ "assistant.thread.sendEdited",
+ "assistant.thread.showEarlier",
+ "assistant.thread.stop",
+ "assistant.thread.stopReading",
+ "assistant.thread.thinking",
+ "assistant.thread.thought",
+ "assistant.thread.thoughtBriefly",
+ "assistant.thread.thoughtFor",
+ "assistant.thread.today",
+ "assistant.thread.turnDuration",
+ "assistant.thread.yesterday",
+ "assistant.tool.actions.failedToOpen",
+ "assistant.tool.actions.opened",
+ "assistant.tool.actions.opening",
+ "assistant.tool.actions.ran",
+ "assistant.tool.actions.ranCode",
+ "assistant.tool.actions.read",
+ "assistant.tool.actions.reading",
+ "assistant.tool.actions.running",
+ "assistant.tool.actions.runningCode",
+ "assistant.tool.actions.searched",
+ "assistant.tool.actions.searching",
+ "assistant.tool.copyActivity",
+ "assistant.tool.copyCode",
+ "assistant.tool.copyCommand",
+ "assistant.tool.copyContent",
+ "assistant.tool.copyFile",
+ "assistant.tool.copyOutput",
+ "assistant.tool.copyPath",
+ "assistant.tool.copyQuery",
+ "assistant.tool.copyResults",
+ "assistant.tool.copyUrl",
+ "assistant.tool.failedCalls",
+ "assistant.tool.failedMany",
+ "assistant.tool.failedOne",
+ "assistant.tool.memoryWriteNoted",
+ "assistant.tool.outputAlt",
+ "assistant.tool.prefixes.browser",
+ "assistant.tool.prefixes.web",
+ "assistant.tool.rawResponse",
+ "assistant.tool.recoveredMany",
+ "assistant.tool.recoveredOne",
+ "assistant.tool.renderingImage",
+ "assistant.tool.resultInterrupted",
+ "assistant.tool.resultUnavailable",
+ "assistant.tool.skillActivity.listFailed",
+ "assistant.tool.skillActivity.listed",
+ "assistant.tool.skillActivity.listing",
+ "assistant.tool.skillActivity.loadFailed",
+ "assistant.tool.skillActivity.loaded",
+ "assistant.tool.skillActivity.loading",
+ "assistant.tool.skillActivity.readResource",
+ "assistant.tool.skillActivity.readingResource",
+ "assistant.tool.skillActivity.resourceFailed",
+ "assistant.tool.skillActivity.unavailable",
+ "assistant.tool.statusDone",
+ "assistant.tool.statusError",
+ "assistant.tool.statusRecovered",
+ "assistant.tool.statusRunning",
+ "assistant.tool.titleTemplates.actionCommand",
+ "assistant.tool.titleTemplates.actionQuoted",
+ "assistant.tool.titleTemplates.actionTarget",
+ "assistant.tool.titleTemplates.prefixedDone",
+ "assistant.tool.titleTemplates.runningPrefixedTool",
+ "assistant.tool.titleTemplates.runningTool",
+ "assistant.tool.titles.browser_click.done",
+ "assistant.tool.titles.browser_click.pending",
+ "assistant.tool.titles.browser_click.pendingAction",
+ "assistant.tool.titles.browser_fill.done",
+ "assistant.tool.titles.browser_fill.pending",
+ "assistant.tool.titles.browser_fill.pendingAction",
+ "assistant.tool.titles.browser_navigate.done",
+ "assistant.tool.titles.browser_navigate.pending",
+ "assistant.tool.titles.browser_navigate.pendingAction",
+ "assistant.tool.titles.browser_snapshot.done",
+ "assistant.tool.titles.browser_snapshot.pending",
+ "assistant.tool.titles.browser_snapshot.pendingAction",
+ "assistant.tool.titles.browser_take_screenshot.done",
+ "assistant.tool.titles.browser_take_screenshot.pending",
+ "assistant.tool.titles.browser_take_screenshot.pendingAction",
+ "assistant.tool.titles.browser_type.done",
+ "assistant.tool.titles.browser_type.pending",
+ "assistant.tool.titles.browser_type.pendingAction",
+ "assistant.tool.titles.clarify.done",
+ "assistant.tool.titles.clarify.pending",
+ "assistant.tool.titles.clarify.pendingAction",
+ "assistant.tool.titles.cronjob.done",
+ "assistant.tool.titles.cronjob.pending",
+ "assistant.tool.titles.cronjob.pendingAction",
+ "assistant.tool.titles.edit_file.done",
+ "assistant.tool.titles.edit_file.pending",
+ "assistant.tool.titles.edit_file.pendingAction",
+ "assistant.tool.titles.execute_code.done",
+ "assistant.tool.titles.execute_code.pending",
+ "assistant.tool.titles.execute_code.pendingAction",
+ "assistant.tool.titles.image_generate.done",
+ "assistant.tool.titles.image_generate.pending",
+ "assistant.tool.titles.image_generate.pendingAction",
+ "assistant.tool.titles.list_files.done",
+ "assistant.tool.titles.list_files.pending",
+ "assistant.tool.titles.list_files.pendingAction",
+ "assistant.tool.titles.memory.done",
+ "assistant.tool.titles.memory.pending",
+ "assistant.tool.titles.memory.pendingAction",
+ "assistant.tool.titles.patch.done",
+ "assistant.tool.titles.patch.pending",
+ "assistant.tool.titles.patch.pendingAction",
+ "assistant.tool.titles.read_file.done",
+ "assistant.tool.titles.read_file.pending",
+ "assistant.tool.titles.read_file.pendingAction",
+ "assistant.tool.titles.search_files.done",
+ "assistant.tool.titles.search_files.pending",
+ "assistant.tool.titles.search_files.pendingAction",
+ "assistant.tool.titles.session_search_recall.done",
+ "assistant.tool.titles.session_search_recall.pending",
+ "assistant.tool.titles.session_search_recall.pendingAction",
+ "assistant.tool.titles.terminal.done",
+ "assistant.tool.titles.terminal.pending",
+ "assistant.tool.titles.terminal.pendingAction",
+ "assistant.tool.titles.todo.done",
+ "assistant.tool.titles.todo.pending",
+ "assistant.tool.titles.todo.pendingAction",
+ "assistant.tool.titles.vision_analyze.done",
+ "assistant.tool.titles.vision_analyze.pending",
+ "assistant.tool.titles.vision_analyze.pendingAction",
+ "assistant.tool.titles.web_extract.done",
+ "assistant.tool.titles.web_extract.pending",
+ "assistant.tool.titles.web_extract.pendingAction",
+ "assistant.tool.titles.web_search.done",
+ "assistant.tool.titles.web_search.pending",
+ "assistant.tool.titles.web_search.pendingAction",
+ "assistant.tool.titles.write_file.done",
+ "assistant.tool.titles.write_file.pending",
+ "assistant.tool.titles.write_file.pendingAction",
+ "billingBlock.addCredits",
+ "billingBlock.dismiss",
+ "billingBlock.fallbackMessage",
+ "billingBlock.openBilling",
+ "billingBlock.titleNous",
+ "billingBlock.titleProvider",
+ "boot.causes.diskFull",
+ "boot.causes.exitedEarly",
+ "boot.causes.installMissing",
+ "boot.causes.permission",
+ "boot.causes.portInUse",
+ "boot.causes.timedOut",
+ "boot.desktopBootFailedWithMessage",
+ "boot.errors.backendStopped",
+ "boot.errors.backgroundExited",
+ "boot.errors.backgroundExitedDuringStartup",
+ "boot.errors.connectionSettings",
+ "boot.errors.desktopBootFailed",
+ "boot.errors.gatewayConnectionLost",
+ "boot.errors.gatewayConnectionLostDetail",
+ "boot.errors.gatewaySignInRequired",
+ "boot.errors.gatewaySignInRequiredDetail",
+ "boot.errors.ipcBridgeUnavailable",
+ "boot.errors.openLogs",
+ "boot.errors.reconnectNow",
+ "boot.errors.restartHermes",
+ "boot.errors.signInAgain",
+ "boot.failure.back",
+ "boot.failure.bundledReinstallHint",
+ "boot.failure.cloudDownCheckPortal",
+ "boot.failure.cloudDownDescription",
+ "boot.failure.cloudDownDiscord",
+ "boot.failure.cloudDownHint",
+ "boot.failure.cloudDownTitle",
+ "boot.failure.description",
+ "boot.failure.details",
+ "boot.failure.gatewaySettings",
+ "boot.failure.hideRecentLogs",
+ "boot.failure.identityProvider",
+ "boot.failure.openLogs",
+ "boot.failure.reinstallApp",
+ "boot.failure.remoteDescription",
+ "boot.failure.remoteFailureHint",
+ "boot.failure.remoteSignInHint",
+ "boot.failure.remoteTitle",
+ "boot.failure.repairHint",
+ "boot.failure.repairInstall",
+ "boot.failure.retry",
+ "boot.failure.showRecentLogs",
+ "boot.failure.signInFailed",
+ "boot.failure.signInIncompleteMessage",
+ "boot.failure.signInIncompleteTitle",
+ "boot.failure.signInToRemoteGateway",
+ "boot.failure.signInWithProvider",
+ "boot.failure.signOutAndSignIn",
+ "boot.failure.signedInMessage",
+ "boot.failure.signedInTitle",
+ "boot.failure.title",
+ "boot.failure.useLocalGateway",
+ "boot.ready",
+ "boot.steps.connectingGateway",
+ "boot.steps.loadingSessions",
+ "boot.steps.loadingSettings",
+ "boot.steps.retryingRemoteBackend",
+ "boot.steps.startingDesktopConnection",
+ "boot.steps.startingHermesDesktop",
+ "boot.updateHold.checkAgain",
+ "boot.updateHold.confirmBody",
+ "boot.updateHold.confirmKeepWaiting",
+ "boot.updateHold.confirmStart",
+ "boot.updateHold.confirmTitle",
+ "boot.updateHold.description",
+ "boot.updateHold.heldByProcess",
+ "boot.updateHold.heldUnknown",
+ "boot.updateHold.lastChecked",
+ "boot.updateHold.openLogs",
+ "boot.updateHold.quit",
+ "boot.updateHold.recoveryHint",
+ "boot.updateHold.since",
+ "boot.updateHold.startAnyway",
+ "boot.updateHold.startAnywayRefused",
+ "boot.updateHold.title",
+ "boot.updateHold.titleUnverified",
+ "boot.updateHold.unverified",
+ "butterbar.goTo",
+ "commandCenter.actionDone",
+ "commandCenter.actionFailed",
+ "commandCenter.actionRunning",
+ "commandCenter.actionStartedWaiting",
+ "commandCenter.actions",
+ "commandCenter.actualCost",
+ "commandCenter.appearance",
+ "commandCenter.archivedChats",
+ "commandCenter.back",
+ "commandCenter.branches",
+ "commandCenter.changeColorMode",
+ "commandCenter.changeTheme",
+ "commandCenter.close",
+ "commandCenter.commandCenter",
+ "commandCenter.commands",
+ "commandCenter.dailyTokens",
+ "commandCenter.days",
+ "commandCenter.deleteSession",
+ "commandCenter.exportSession",
+ "commandCenter.gatewayRestartFailed",
+ "commandCenter.gatewayRunning",
+ "commandCenter.gatewayStopped",
+ "commandCenter.generatePet.adopt",
+ "commandCenter.generatePet.backgroundHint",
+ "commandCenter.generatePet.generate",
+ "commandCenter.generatePet.generating",
+ "commandCenter.generatePet.genericError",
+ "commandCenter.generatePet.hatch",
+ "commandCenter.generatePet.hatchComposing",
+ "commandCenter.generatePet.hatchRow",
+ "commandCenter.generatePet.hatchSaving",
+ "commandCenter.generatePet.hatched",
+ "commandCenter.generatePet.hatching",
+ "commandCenter.generatePet.hatchingSub",
+ "commandCenter.generatePet.namePlaceholder",
+ "commandCenter.generatePet.placeholder",
+ "commandCenter.generatePet.promptHint",
+ "commandCenter.generatePet.readyHint",
+ "commandCenter.generatePet.referenceImageInvalid",
+ "commandCenter.generatePet.referenceImageTooLarge",
+ "commandCenter.generatePet.remix",
+ "commandCenter.generatePet.remixConfirmBody",
+ "commandCenter.generatePet.remixConfirmTitle",
+ "commandCenter.generatePet.retry",
+ "commandCenter.generatePet.slowProviderHint",
+ "commandCenter.generatePet.spawning",
+ "commandCenter.generatePet.staleBackend",
+ "commandCenter.generatePet.startOver",
+ "commandCenter.generatePet.title",
+ "commandCenter.goTo",
+ "commandCenter.goToSession",
+ "commandCenter.hermesActiveSessions",
+ "commandCenter.input",
+ "commandCenter.installTheme.empty",
+ "commandCenter.installTheme.error",
+ "commandCenter.installTheme.install",
+ "commandCenter.installTheme.installed",
+ "commandCenter.installTheme.installing",
+ "commandCenter.installTheme.installs",
+ "commandCenter.installTheme.loading",
+ "commandCenter.installTheme.pageTitle",
+ "commandCenter.installTheme.placeholder",
+ "commandCenter.installTheme.title",
+ "commandCenter.loadingStatus",
+ "commandCenter.loadingUsage",
+ "commandCenter.logFile",
+ "commandCenter.logLevel",
+ "commandCenter.logSearchPlaceholder",
+ "commandCenter.maintenance.actionFailed",
+ "commandCenter.maintenance.actionStarted",
+ "commandCenter.maintenance.backup",
+ "commandCenter.maintenance.backupDesc",
+ "commandCenter.maintenance.builtinMemory",
+ "commandCenter.maintenance.bytes",
+ "commandCenter.maintenance.copyLink",
+ "commandCenter.maintenance.curator",
+ "commandCenter.maintenance.curatorActive",
+ "commandCenter.maintenance.curatorDesc",
+ "commandCenter.maintenance.curatorDisabled",
+ "commandCenter.maintenance.curatorLastRun",
+ "commandCenter.maintenance.curatorNeverRan",
+ "commandCenter.maintenance.curatorPaused",
+ "commandCenter.maintenance.debugShare",
+ "commandCenter.maintenance.debugShareDesc",
+ "commandCenter.maintenance.debugShareFailed",
+ "commandCenter.maintenance.debugShareLinks",
+ "commandCenter.maintenance.debugShareRunning",
+ "commandCenter.maintenance.doctor",
+ "commandCenter.maintenance.doctorDesc",
+ "commandCenter.maintenance.empty",
+ "commandCenter.maintenance.linkCopied",
+ "commandCenter.maintenance.memoryData",
+ "commandCenter.maintenance.memoryDataDesc",
+ "commandCenter.maintenance.memoryFile",
+ "commandCenter.maintenance.memoryProvider",
+ "commandCenter.maintenance.pause",
+ "commandCenter.maintenance.resetAll",
+ "commandCenter.maintenance.resetConfirm",
+ "commandCenter.maintenance.resetDone",
+ "commandCenter.maintenance.resetFailed",
+ "commandCenter.maintenance.resetMemory",
+ "commandCenter.maintenance.resetUser",
+ "commandCenter.maintenance.resume",
+ "commandCenter.maintenance.runNow",
+ "commandCenter.maintenance.runOps",
+ "commandCenter.maintenance.running",
+ "commandCenter.maintenance.securityAudit",
+ "commandCenter.maintenance.securityAuditDesc",
+ "commandCenter.maintenance.userFile",
+ "commandCenter.maintenance.viewLog",
+ "commandCenter.mcpServers",
+ "commandCenter.nav.artifacts.detail",
+ "commandCenter.nav.artifacts.title",
+ "commandCenter.nav.capabilities.detail",
+ "commandCenter.nav.capabilities.title",
+ "commandCenter.nav.messaging.detail",
+ "commandCenter.nav.messaging.title",
+ "commandCenter.nav.newChat.detail",
+ "commandCenter.nav.newChat.title",
+ "commandCenter.nav.settings.detail",
+ "commandCenter.nav.settings.title",
+ "commandCenter.newSessionInProject",
+ "commandCenter.noDailyActivity",
+ "commandCenter.noLogs",
+ "commandCenter.noModelUsage",
+ "commandCenter.noResults",
+ "commandCenter.noSessions",
+ "commandCenter.noSkillActivity",
+ "commandCenter.noUsage",
+ "commandCenter.openBrowser",
+ "commandCenter.openFolder",
+ "commandCenter.openFolderAt",
+ "commandCenter.output",
+ "commandCenter.paletteTitle",
+ "commandCenter.pets.adoptFailed",
+ "commandCenter.pets.empty",
+ "commandCenter.pets.error",
+ "commandCenter.pets.generatedTag",
+ "commandCenter.pets.installed",
+ "commandCenter.pets.loading",
+ "commandCenter.pets.noneAvailable",
+ "commandCenter.pets.placeholder",
+ "commandCenter.pets.staleBackend",
+ "commandCenter.pets.title",
+ "commandCenter.pets.toggleFailed",
+ "commandCenter.pets.turnOff",
+ "commandCenter.pets.turnOn",
+ "commandCenter.pinSession",
+ "commandCenter.projects",
+ "commandCenter.providerNavigate",
+ "commandCenter.providerSessions",
+ "commandCenter.recentLogs",
+ "commandCenter.refresh",
+ "commandCenter.refreshing",
+ "commandCenter.reloadWindow",
+ "commandCenter.restartGateway",
+ "commandCenter.retry",
+ "commandCenter.searchPlaceholder",
+ "commandCenter.sectionEntries.sessions.detail",
+ "commandCenter.sectionEntries.sessions.title",
+ "commandCenter.sectionEntries.system.detail",
+ "commandCenter.sectionEntries.system.title",
+ "commandCenter.sectionEntries.usage.detail",
+ "commandCenter.sectionEntries.usage.title",
+ "commandCenter.sections.maintenance",
+ "commandCenter.sections.sessions",
+ "commandCenter.sections.system",
+ "commandCenter.sections.usage",
+ "commandCenter.settings",
+ "commandCenter.settingsFields",
+ "commandCenter.sharedGatewayRestartConfirm",
+ "commandCenter.sharedGatewayRestartDescription",
+ "commandCenter.sharedGatewayRestartTitle",
+ "commandCenter.sharedGatewayRestarted",
+ "commandCenter.startInBranch",
+ "commandCenter.statApiCalls",
+ "commandCenter.statCost",
+ "commandCenter.statSessions",
+ "commandCenter.statTokens",
+ "commandCenter.toggleBrowser",
+ "commandCenter.topModels",
+ "commandCenter.topSkills",
+ "commandCenter.unpinSession",
+ "commandCenter.updateHermes",
+ "common.apply",
+ "common.back",
+ "common.bots",
+ "common.cancel",
+ "common.change",
+ "common.choose",
+ "common.clear",
+ "common.close",
+ "common.collapse",
+ "common.confirm",
+ "common.connect",
+ "common.connecting",
+ "common.continue",
+ "common.copied",
+ "common.copy",
+ "common.copyFailed",
+ "common.delete",
+ "common.docs",
+ "common.done",
+ "common.error",
+ "common.expand",
+ "common.failed",
+ "common.formatJson",
+ "common.free",
+ "common.loading",
+ "common.notSet",
+ "common.off",
+ "common.on",
+ "common.refresh",
+ "common.remove",
+ "common.replace",
+ "common.retry",
+ "common.run",
+ "common.save",
+ "common.saving",
+ "common.send",
+ "common.set",
+ "common.skip",
+ "common.tryHint",
+ "common.update",
+ "composer.attach",
+ "composer.attachLabel",
+ "composer.attachUrlDesc",
+ "composer.attachUrlTitle",
+ "composer.attachmentOnly",
+ "composer.attachments",
+ "composer.commandDescs./agents",
+ "composer.commandDescs./approvals",
+ "composer.commandDescs./battery",
+ "composer.commandDescs./bg",
+ "composer.commandDescs./blueprint",
+ "composer.commandDescs./branch",
+ "composer.commandDescs./browser",
+ "composer.commandDescs./btw",
+ "composer.commandDescs./bundles",
+ "composer.commandDescs./clear",
+ "composer.commandDescs./codex-runtime",
+ "composer.commandDescs./compress",
+ "composer.commandDescs./context",
+ "composer.commandDescs./copy",
+ "composer.commandDescs./debug",
+ "composer.commandDescs./details",
+ "composer.commandDescs./diff",
+ "composer.commandDescs./egress",
+ "composer.commandDescs./export",
+ "composer.commandDescs./focus",
+ "composer.commandDescs./goal",
+ "composer.commandDescs./handoff",
+ "composer.commandDescs./hatch",
+ "composer.commandDescs./heartbeat",
+ "composer.commandDescs./help",
+ "composer.commandDescs./import",
+ "composer.commandDescs./init",
+ "composer.commandDescs./journey",
+ "composer.commandDescs./learn",
+ "composer.commandDescs./loop",
+ "composer.commandDescs./memory",
+ "composer.commandDescs./moa",
+ "composer.commandDescs./model",
+ "composer.commandDescs./new",
+ "composer.commandDescs./palette",
+ "composer.commandDescs./pause",
+ "composer.commandDescs./personality",
+ "composer.commandDescs./pet",
+ "composer.commandDescs./plan",
+ "composer.commandDescs./platform",
+ "composer.commandDescs./profile",
+ "composer.commandDescs./prompt",
+ "composer.commandDescs./queue",
+ "composer.commandDescs./quit",
+ "composer.commandDescs./reasoning",
+ "composer.commandDescs./refine",
+ "composer.commandDescs./resume",
+ "composer.commandDescs./retry",
+ "composer.commandDescs./review",
+ "composer.commandDescs./rollback",
+ "composer.commandDescs./save",
+ "composer.commandDescs./skin",
+ "composer.commandDescs./start",
+ "composer.commandDescs./status",
+ "composer.commandDescs./steer",
+ "composer.commandDescs./stop",
+ "composer.commandDescs./subgoal",
+ "composer.commandDescs./subscription",
+ "composer.commandDescs./suggestions",
+ "composer.commandDescs./timestamps",
+ "composer.commandDescs./title",
+ "composer.commandDescs./tools",
+ "composer.commandDescs./topic",
+ "composer.commandDescs./topup",
+ "composer.commandDescs./undo",
+ "composer.commandDescs./usage",
+ "composer.commandDescs./version",
+ "composer.commandDescs./wake",
+ "composer.commandDescs./whoami",
+ "composer.commandDescs./worktree",
+ "composer.commandDescs./yolo",
+ "composer.commonCommands",
+ "composer.couldNotPreview",
+ "composer.cronSuggestions.done",
+ "composer.cronSuggestions.doneTip",
+ "composer.cronSuggestions.label",
+ "composer.cronSuggestions.prefix",
+ "composer.cronSuggestions.tip",
+ "composer.dictating",
+ "composer.dropFiles",
+ "composer.dropSession",
+ "composer.editingInComposer",
+ "composer.editingQueuedInComposer",
+ "composer.emptyTurn",
+ "composer.endConversation",
+ "composer.endShort",
+ "composer.files",
+ "composer.folder",
+ "composer.followUpPlaceholders",
+ "composer.githubSuggestions.done",
+ "composer.githubSuggestions.doneTip",
+ "composer.githubSuggestions.label",
+ "composer.githubSuggestions.tip",
+ "composer.helpFooter",
+ "composer.hiddenQueued",
+ "composer.hotkeyDescs.composer.cancel",
+ "composer.hotkeyDescs.composer.help",
+ "composer.hotkeyDescs.composer.history",
+ "composer.hotkeyDescs.composer.mention",
+ "composer.hotkeyDescs.composer.sendNewline",
+ "composer.hotkeyDescs.composer.sendQueued",
+ "composer.hotkeyDescs.composer.slash",
+ "composer.hotkeyDescs.keybinds.openPanel",
+ "composer.hotkeys",
+ "composer.images",
+ "composer.listening",
+ "composer.lookupLoading",
+ "composer.lookupNoMatches",
+ "composer.lookupOr",
+ "composer.lookupTry",
+ "composer.mcpSuggestions.added",
+ "composer.mcpSuggestions.addedTip",
+ "composer.mcpSuggestions.cancelTip",
+ "composer.mcpSuggestions.connectFailed",
+ "composer.mcpSuggestions.connecting",
+ "composer.mcpSuggestions.label",
+ "composer.mcpSuggestions.tip",
+ "composer.message",
+ "composer.muteMic",
+ "composer.muted",
+ "composer.newSessionPlaceholders",
+ "composer.noMatchingThemes",
+ "composer.openDirective",
+ "composer.pasteImage",
+ "composer.placeholderFollowUp",
+ "composer.placeholderReconnecting",
+ "composer.placeholderStarting",
+ "composer.preparingAudio",
+ "composer.previewLabel",
+ "composer.previewUnavailable",
+ "composer.promptSnippets",
+ "composer.queueCollapse",
+ "composer.queueDelete",
+ "composer.queueDroppedBody",
+ "composer.queueDroppedTitle",
+ "composer.queueEdit",
+ "composer.queueExpand",
++ "composer.queueLostDiscard",
++ "composer.queueLostDiscardTip",
++ "composer.queueLostNote",
+ "composer.queueMessage",
+ "composer.queueResume",
+ "composer.queueResumeTip",
+ "composer.queueSend",
+ "composer.queueSendNext",
+ "composer.queueSteer",
+ "composer.queueStuckBody",
+ "composer.queueStuckTitle",
+ "composer.queued",
+ "composer.queuedPaused",
+ "composer.queuedTerminalSelectionExpiredBody",
+ "composer.readingAloud",
++ "composer.redirect",
+ "composer.removeAttachment",
+ "composer.repairSuggestions.done",
+ "composer.repairSuggestions.doneTip",
+ "composer.repairSuggestions.failed",
+ "composer.repairSuggestions.label",
+ "composer.repairSuggestions.tip",
+ "composer.repairSuggestions.working",
+ "composer.repairSuggestions.workingTip",
++ "composer.restoreImageDraft",
+ "composer.restoredDraftNotice",
+ "composer.restoredDraftUndo",
+ "composer.send",
+ "composer.skillSuggestions.done",
+ "composer.skillSuggestions.doneTip",
+ "composer.skillSuggestions.label",
+ "composer.skillSuggestions.tip",
+ "composer.snippets.codeReview.description",
+ "composer.snippets.codeReview.label",
+ "composer.snippets.codeReview.text",
+ "composer.snippets.explainThis.description",
+ "composer.snippets.explainThis.label",
+ "composer.snippets.explainThis.text",
+ "composer.snippets.implementationPlan.description",
+ "composer.snippets.implementationPlan.label",
+ "composer.snippets.implementationPlan.text",
+ "composer.snippetsDesc",
+ "composer.snippetsTitle",
+ "composer.speakReplies",
+ "composer.speaking",
+ "composer.speakingResponse",
+ "composer.startVoice",
+ "composer.steer",
+ "composer.stop",
+ "composer.stopDictation",
+ "composer.stopListening",
+ "composer.stopShort",
+ "composer.stopSpeakingReplies",
+ "composer.terminalSelectionMissingBody",
+ "composer.terminalSelectionMissingTitle",
+ "composer.themeSuggestions",
+ "composer.themeTryPost",
+ "composer.themeTryPre",
+ "composer.thinking",
+ "composer.tipPost",
+ "composer.tipPre",
+ "composer.transcribing",
+ "composer.transcribingDictation",
+ "composer.unmuteMic",
+ "composer.url",
+ "composer.urlHintPre",
+ "composer.urlPlaceholder",
+ "composer.voiceControls",
+ "composer.voiceDictation",
+ "composer.voiceEngine",
+ "composer.voiceEngineChained",
+ "composer.voiceEngineChainedShort",
+ "composer.voiceEngineChangeFailed",
+ "composer.voiceEngineLive",
+ "composer.voiceEngineLiveNeedsKey",
+ "composer.voiceEngineLiveShort",
+ "composer.wakeWord",
+ "composer.wakeWordListening",
+ "composer.wakeWordOff",
+ "composer.wakeWordPausedVoice",
+ "composer.wakingProfile",
+ "connectors.authorizedToolsUnavailable",
+ "connectors.cancel",
+ "connectors.checking",
+ "connectors.connect",
+ "connectors.connectError",
+ "connectors.connectErrorFor",
+ "connectors.connected",
+ "connectors.disabled",
+ "connectors.disclaimer",
+ "connectors.empty",
+ "connectors.execution",
+ "connectors.failed",
+ "connectors.grant",
+ "connectors.needsAuth",
+ "connectors.notConnected",
+ "connectors.openInBrowser",
+ "connectors.opening",
+ "connectors.ownerMissing",
+ "connectors.refresh",
+ "connectors.required",
+ "connectors.retry",
+ "connectors.search",
+ "connectors.setup",
+ "connectors.setupCancel",
+ "connectors.skip",
+ "connectors.skipped",
+ "connectors.timeout",
+ "connectors.title",
+ "connectors.unavailable",
+ "connectors.waiting",
+ "connectorsPage.add.action",
+ "connectorsPage.add.addArg",
+ "connectorsPage.add.addEnvVar",
+ "connectorsPage.add.addHeader",
+ "connectorsPage.add.addPassthrough",
+ "connectorsPage.add.args",
+ "connectorsPage.add.auth",
+ "connectorsPage.add.authBearer",
+ "connectorsPage.add.authNone",
+ "connectorsPage.add.authOauth",
+ "connectorsPage.add.command",
+ "connectorsPage.add.cwd",
+ "connectorsPage.add.editJson",
+ "connectorsPage.add.envVars",
+ "connectorsPage.add.headers",
+ "connectorsPage.add.hint",
+ "connectorsPage.add.keyPlaceholder",
+ "connectorsPage.add.name",
+ "connectorsPage.add.nameTaken",
+ "connectorsPage.add.passthrough",
+ "connectorsPage.add.pasteLabel",
+ "connectorsPage.add.pasteNoMatch",
+ "connectorsPage.add.pastePlaceholder",
+ "connectorsPage.add.removeRow",
+ "connectorsPage.add.saveFailed",
+ "connectorsPage.add.title",
+ "connectorsPage.add.type",
+ "connectorsPage.add.typeHttp",
+ "connectorsPage.add.typeStdio",
+ "connectorsPage.add.url",
+ "connectorsPage.add.valuePlaceholder",
+ "connectorsPage.card.alsoLocal",
+ "connectorsPage.card.fact.tools",
+ "connectorsPage.card.fact.toolsOff",
+ "connectorsPage.card.fact.toolsOn",
+ "connectorsPage.card.fact.toolsSomeOn",
+ "connectorsPage.card.hostedTwin",
+ "connectorsPage.card.inCatalog",
+ "connectorsPage.card.kindCatalog",
+ "connectorsPage.card.kindCustom",
+ "connectorsPage.card.kindManaged",
+ "connectorsPage.card.kindPlugin",
+ "connectorsPage.card.open",
+ "connectorsPage.card.reason.finishSignIn",
+ "connectorsPage.card.reason.reconnect",
+ "connectorsPage.card.reason.serverError",
+ "connectorsPage.card.reason.serverNeedsAuth",
+ "connectorsPage.card.state.accessExpired",
+ "connectorsPage.card.state.available",
+ "connectorsPage.card.state.connected",
+ "connectorsPage.card.state.connecting",
+ "connectorsPage.card.state.connectionUnknown",
+ "connectorsPage.card.state.couldNotConnect",
+ "connectorsPage.card.state.offByYourOrganisation",
+ "connectorsPage.card.state.offForYou",
+ "connectorsPage.card.state.serverConnecting",
+ "connectorsPage.card.state.serverError",
+ "connectorsPage.card.state.serverNeedsAuth",
+ "connectorsPage.card.state.serverOff",
+ "connectorsPage.card.state.serverOn",
+ "connectorsPage.card.state.serverOnUnused",
+ "connectorsPage.card.turnServerOff",
+ "connectorsPage.card.turnServerOn",
+ "connectorsPage.card.verb.authenticate",
+ "connectorsPage.card.verb.connect",
+ "connectorsPage.card.verb.install",
+ "connectorsPage.card.verb.openLogs",
+ "connectorsPage.card.verb.reconnect",
+ "connectorsPage.card.verb.stopWaiting",
+ "connectorsPage.card.verb.tryAgain",
+ "connectorsPage.card.verb.turnBackOn",
+ "connectorsPage.categoryAll",
+ "connectorsPage.dialog.advanced",
+ "connectorsPage.dialog.advancedHint",
+ "connectorsPage.dialog.appSwitch",
+ "connectorsPage.dialog.bothOn",
+ "connectorsPage.dialog.connectEnded",
+ "connectorsPage.dialog.connectOpenAgain",
+ "connectorsPage.dialog.disconnect",
+ "connectorsPage.dialog.disconnectBody",
+ "connectorsPage.dialog.disconnectTitle",
+ "connectorsPage.dialog.menuRefreshTools",
+ "connectorsPage.dialog.moreActions",
+ "connectorsPage.dialog.nousLine",
+ "connectorsPage.dialog.openPlugins",
+ "connectorsPage.dialog.orgLink",
+ "connectorsPage.dialog.orgNote",
+ "connectorsPage.dialog.providedByPlugin",
+ "connectorsPage.dialog.removeServerBody",
+ "connectorsPage.dialog.removeServerTitle",
+ "connectorsPage.dialog.rulesAppOff",
+ "connectorsPage.dialog.rulesReadOnly",
+ "connectorsPage.dialog.rulesSignIn",
+ "connectorsPage.dialog.tokensPerCall",
+ "connectorsPage.dialog.turnOffLocal",
+ "connectorsPage.dialog.usesPerMonth",
+ "connectorsPage.dialog.wayHosted",
+ "connectorsPage.dialog.wayNotConnected",
+ "connectorsPage.dialog.waysTitle",
+ "connectorsPage.filterCategory",
+ "connectorsPage.group.available",
+ "connectorsPage.group.connected",
+ "connectorsPage.group.connectedNote",
+ "connectorsPage.group.off",
+ "connectorsPage.group.offNote",
+ "connectorsPage.page.clearSearch",
+ "connectorsPage.page.disconnectNoAccount",
+ "connectorsPage.page.disconnectRefused",
+ "connectorsPage.page.emptyTitle",
+ "connectorsPage.page.freeTierNote",
+ "connectorsPage.page.hostedFailedBody",
+ "connectorsPage.page.hostedFailedTitle",
+ "connectorsPage.page.loading",
+ "connectorsPage.page.managedUnavailable",
+ "connectorsPage.page.matchesElsewhere",
+ "connectorsPage.page.noMatchBody",
+ "connectorsPage.page.noMatchTitle",
+ "connectorsPage.page.refreshFailed",
+ "connectorsPage.page.retry",
+ "connectorsPage.page.segmentNoMatch",
+ "connectorsPage.page.showAllMatches",
+ "connectorsPage.page.signIn",
+ "connectorsPage.page.signInLine",
+ "connectorsPage.page.writeFailed",
+ "connectorsPage.residencyLocal",
+ "connectorsPage.searchPlaceholder",
+ "connectorsPage.segment.all",
+ "connectorsPage.segment.available",
+ "connectorsPage.segment.connected",
+ "connectorsPage.segment.off",
+ "connectorsPage.title",
+ "connectorsPage.tools.allToolsSwitch",
+ "connectorsPage.tools.categorySelect",
+ "connectorsPage.tools.conflictBody",
+ "connectorsPage.tools.conflictReload",
+ "connectorsPage.tools.conflictSave",
+ "connectorsPage.tools.conflictTitle",
+ "connectorsPage.tools.discard",
+ "connectorsPage.tools.facetSwitch",
+ "connectorsPage.tools.footerDirty",
+ "connectorsPage.tools.goneBody",
+ "connectorsPage.tools.goneTitle",
+ "connectorsPage.tools.hideDeprecated",
+ "connectorsPage.tools.hideDetails",
+ "connectorsPage.tools.loading",
+ "connectorsPage.tools.lockedHint",
+ "connectorsPage.tools.moreHints",
+ "connectorsPage.tools.needsAuthBody",
+ "connectorsPage.tools.needsAuthTitle",
+ "connectorsPage.tools.noMatch",
+ "connectorsPage.tools.notInstalledBody",
+ "connectorsPage.tools.offBody",
+ "connectorsPage.tools.offTitle",
+ "connectorsPage.tools.quickEverythingOn",
+ "connectorsPage.tools.quickNoDestructive",
+ "connectorsPage.tools.quickReadOnly",
+ "connectorsPage.tools.remove",
+ "connectorsPage.tools.retry",
+ "connectorsPage.tools.save",
+ "connectorsPage.tools.saveFailed",
+ "connectorsPage.tools.saving",
+ "connectorsPage.tools.searchCountPlaceholder",
+ "connectorsPage.tools.showAllTools",
+ "connectorsPage.tools.showDeprecated",
+ "connectorsPage.tools.showDetails",
+ "connectorsPage.tools.showSummary",
+ "connectorsPage.tools.signedOutBody",
+ "connectorsPage.tools.signedOutTitle",
+ "connectorsPage.tools.staleSignIn",
+ "connectorsPage.tools.summaryAllOn",
+ "connectorsPage.tools.summaryAllTools",
+ "connectorsPage.tools.summaryCount",
+ "connectorsPage.tools.summaryOff",
+ "connectorsPage.tools.summaryOther",
+ "connectorsPage.tools.summaryPreviewTitle",
+ "connectorsPage.tools.summarySomeOn",
+ "connectorsPage.tools.summaryTitle",
+ "connectorsPage.tools.title",
+ "connectorsPage.tools.toolList",
+ "connectorsPage.tools.turnToolOff",
+ "connectorsPage.tools.turnToolOn",
+ "connectorsPage.tools.unavailableLine",
+ "connectorsPage.uncategorised",
+ "connectorsPage.vocabulary.facetDestructive.label",
+ "connectorsPage.vocabulary.facetDestructive.long",
+ "connectorsPage.vocabulary.facetRead.label",
+ "connectorsPage.vocabulary.facetRead.long",
+ "connectorsPage.vocabulary.facetUnclassified.label",
+ "connectorsPage.vocabulary.facetUnclassified.long",
+ "connectorsPage.vocabulary.facetWrite.label",
+ "connectorsPage.vocabulary.facetWrite.long",
+ "connectorsPage.vocabulary.hintCreate.label",
+ "connectorsPage.vocabulary.hintCreate.long",
+ "connectorsPage.vocabulary.hintDelete.label",
+ "connectorsPage.vocabulary.hintDelete.long",
+ "connectorsPage.vocabulary.hintDestructive.label",
+ "connectorsPage.vocabulary.hintDestructive.long",
+ "connectorsPage.vocabulary.hintIdempotent.label",
+ "connectorsPage.vocabulary.hintIdempotent.long",
+ "connectorsPage.vocabulary.hintOpenWorld.label",
+ "connectorsPage.vocabulary.hintOpenWorld.long",
+ "connectorsPage.vocabulary.hintReadOnly.label",
+ "connectorsPage.vocabulary.hintReadOnly.long",
+ "connectorsPage.vocabulary.hintUpdate.label",
+ "connectorsPage.vocabulary.hintUpdate.long",
+ "contextMenu.edit.addToDictionary",
+ "contextMenu.edit.cut",
+ "contextMenu.edit.paste",
+ "contextMenu.edit.selectAll",
+ "contextMenu.image.copyImage",
+ "contextMenu.image.copyImageAddress",
+ "contextMenu.image.saveImageAs",
+ "contextMenu.link.copyResolvedUrl",
+ "contextMenu.link.copyUrl",
+ "contextMenu.link.openExternal",
+ "contextMenu.link.openInApp",
+ "contextMenu.page.copyPageUrl",
+ "contextMenu.page.inspectElement",
+ "cron.actionsTitle",
+ "cron.blueprints.custom",
+ "cron.blueprints.dialogDesc",
+ "cron.blueprints.emptyDesc",
+ "cron.blueprints.emptyTitle",
+ "cron.blueprints.failedLoad",
+ "cron.blueprints.loading",
+ "cron.blueprints.scheduleIt",
+ "cron.blueprints.scheduled",
+ "cron.blueprints.scheduling",
+ "cron.blueprints.startFrom",
+ "cron.blueprints.subtitle",
+ "cron.blueprints.tab",
+ "cron.close",
+ "cron.count",
+ "cron.createAction",
+ "cron.createDesc",
+ "cron.createTitle",
+ "cron.created",
+ "cron.customHint",
+ "cron.customPlaceholder",
+ "cron.customScheduleLabel",
+ "cron.dayFallback",
+ "cron.days.0",
+ "cron.days.1",
+ "cron.days.2",
+ "cron.days.3",
+ "cron.days.4",
+ "cron.days.5",
+ "cron.days.6",
+ "cron.days.7",
+ "cron.deleteDescPrefix",
+ "cron.deleteDescSuffix",
+ "cron.deleteTitle",
+ "cron.deleted",
+ "cron.deleting",
+ "cron.deliverLabel",
+ "cron.deliverNeedsHomeChannel",
+ "cron.deliveryLabels.discord",
+ "cron.deliveryLabels.email",
+ "cron.deliveryLabels.local",
+ "cron.deliveryLabels.slack",
+ "cron.deliveryLabels.telegram",
+ "cron.edit",
+ "cron.editDesc",
+ "cron.editJob",
+ "cron.editTitle",
+ "cron.emptyDescNew",
+ "cron.emptyDescSearch",
+ "cron.emptyTitleNew",
+ "cron.emptyTitleSearch",
+ "cron.everyDayAt",
+ "cron.everyDayOfWeekAt",
+ "cron.everyHourAt",
+ "cron.failedDelete",
+ "cron.failedLoad",
+ "cron.failedSave",
+ "cron.failedTrigger",
+ "cron.failedUpdate",
+ "cron.frequencyLabel",
+ "cron.hideRuns",
+ "cron.last",
+ "cron.lastRunFailed",
+ "cron.loading",
+ "cron.manage",
+ "cron.modelDefault",
+ "cron.modelLabel",
+ "cron.monthlyOnDayAt",
+ "cron.nameLabel",
+ "cron.namePlaceholder",
+ "cron.newCron",
+ "cron.next",
+ "cron.noRuns",
+ "cron.optional",
+ "cron.overdueSince",
+ "cron.pause",
+ "cron.pauseTitle",
+ "cron.paused",
+ "cron.promptLabel",
+ "cron.promptPlaceholder",
+ "cron.promptRequired",
+ "cron.promptScheduleRequired",
+ "cron.resume",
+ "cron.resumeTitle",
+ "cron.resumed",
+ "cron.runAgain",
+ "cron.runHistory",
+ "cron.saveChanges",
+ "cron.scheduleHints.custom",
+ "cron.scheduleHints.daily",
+ "cron.scheduleHints.every-15-minutes",
+ "cron.scheduleHints.hourly",
+ "cron.scheduleHints.monthly",
+ "cron.scheduleHints.weekdays",
+ "cron.scheduleHints.weekly",
+ "cron.scheduleLabels.custom",
+ "cron.scheduleLabels.daily",
+ "cron.scheduleLabels.every-15-minutes",
+ "cron.scheduleLabels.hourly",
+ "cron.scheduleLabels.monthly",
+ "cron.scheduleLabels.weekdays",
+ "cron.scheduleLabels.weekly",
+ "cron.scheduleRequired",
+ "cron.scriptBadge",
+ "cron.scriptLabel",
+ "cron.scriptOnlyEditHint",
+ "cron.search",
+ "cron.showRuns",
+ "cron.states.completed",
+ "cron.states.disabled",
+ "cron.states.enabled",
+ "cron.states.error",
+ "cron.states.paused",
+ "cron.states.running",
+ "cron.states.scheduled",
+ "cron.tabs.blueprints",
+ "cron.tabs.jobs",
+ "cron.title",
+ "cron.topOfHour",
+ "cron.triggerNow",
+ "cron.triggered",
+ "cron.updated",
+ "cron.weekdaysAt",
+ "desktop.archiveFailed",
+ "desktop.archived",
+ "desktop.attachImages",
+ "desktop.audioReadFailed",
+ "desktop.branchFailed",
+ "desktop.branchNeedsChat",
+ "desktop.branchNoText",
+ "desktop.branchStopCurrent",
+ "desktop.branchTitle",
+ "desktop.clipboard",
+ "desktop.clipboardPasteFailed",
+ "desktop.createSessionFailed",
+ "desktop.cwdChangeFailed",
+ "desktop.cwdStagedMessage",
+ "desktop.cwdStagedTitle",
+ "desktop.deleteFailed",
+ "desktop.desktopCommands",
+ "desktop.downloadImage",
+ "desktop.downloadStarted",
+ "desktop.dropFiles",
+ "desktop.editFailed",
+ "desktop.editTurnUnavailable",
+ "desktop.emptySlashCommand",
+ "desktop.handoff.failed",
+ "desktop.handoff.pickPlatform",
+ "desktop.handoff.startMessaging",
+ "desktop.handoff.success",
+ "desktop.handoff.systemNote",
+ "desktop.handoff.timedOut",
+ "desktop.hydrationSyncing",
+ "desktop.imageAttach",
+ "desktop.imageAttachFailed",
+ "desktop.imageDownloadFailed",
+ "desktop.imagePreviewFailed",
+ "desktop.imageSaved",
+ "desktop.imageWriteFailed",
+ "desktop.modelSwitchConfirmBody",
+ "desktop.modelSwitchConfirmLabel",
+ "desktop.modelSwitchConfirmTitle",
+ "desktop.modelSwitchConfirmTitleFallback",
+ "desktop.modelSwitchFailed",
+ "desktop.modelSwitchKeepLabel",
+ "desktop.modelSwitchStaleNotice",
+ "desktop.newChatsProfile",
+ "desktop.noClipboardImage",
+ "desktop.noProfileNamed",
+ "desktop.nothingToBranch",
+ "desktop.openImage",
+ "desktop.pasteAttachFailed",
+ "desktop.pastedContent",
+ "desktop.poolSlotTimeoutBody",
+ "desktop.poolSlotTimeoutOpenSettings",
+ "desktop.profileStatus",
+ "desktop.promptFailed",
+ "desktop.providerCredentialRequired",
+ "desktop.readOnlyTranscriptBody",
+ "desktop.readOnlyTranscriptSendBlocked",
+ "desktop.readOnlyTranscriptTitle",
+ "desktop.regenerateFailed",
+ "desktop.resetZoom",
+ "desktop.restartToSaveImages",
+ "desktop.restartToUseSaveImage",
+ "desktop.restored",
+ "desktop.resumeFailed",
+ "desktop.resumeRetry",
+ "desktop.resumeStrandedBody",
+ "desktop.resumeStrandedTitle",
+ "desktop.savingImage",
+ "desktop.sessionBusy",
+ "desktop.sessionExportFailed",
+ "desktop.sessionExported",
+ "desktop.sessionUnavailable",
+ "desktop.setProfileFailed",
+ "desktop.skillCommandsAvailable",
+ "desktop.slashCommandIgnoredBody",
+ "desktop.slashCommandIgnoredTitle",
+ "desktop.stopFailed",
+ "desktop.sttDisabled",
+ "desktop.unarchiveFailed",
+ "desktop.unknownProfile",
+ "desktop.warningLine",
+ "desktop.yoloArmed",
+ "desktop.yoloOff",
+ "desktop.yoloSystem",
+ "desktop.yoloTitle",
+ "desktop.yoloToggleFailed",
+ "desktop.zoomIn",
+ "desktop.zoomOut",
+ "errors.boundaryDesc",
+ "errors.boundaryDetails",
+ "errors.boundaryTitle",
+ "errors.genericFailure",
+ "errors.openLogs",
+ "errors.reloadWindow",
+ "errors.sendDiagnostics",
+ "externalOpenFailed.close",
+ "externalOpenFailed.copyUrl",
+ "externalOpenFailed.message",
+ "externalOpenFailed.missing.message",
+ "externalOpenFailed.missing.title",
+ "externalOpenFailed.title",
+ "fileMenu.copyPath",
+ "fileMenu.copyRelativePath",
+ "fileMenu.delete",
+ "fileMenu.deleteBody",
+ "fileMenu.deleteTitle",
+ "fileMenu.download",
+ "fileMenu.downloadFailed",
+ "fileMenu.downloadSaved",
+ "fileMenu.pathCopied",
+ "fileMenu.rename",
+ "fileMenu.renameLabel",
+ "fileMenu.renameTitle",
+ "fileMenu.revealExplorer",
+ "fileMenu.revealFileManager",
+ "fileMenu.revealFinder",
+ "fileMenu.revealInSidebar",
+ "fileMenu.revealMissing",
+ "fileMenu.revealUnavailable",
+ "findInPage.next",
+ "findInPage.previous",
+ "freeTier.alreadySignedInBody",
+ "freeTier.alreadySignedInHeading",
+ "freeTier.begin",
+ "freeTier.busyBody",
+ "freeTier.busyHeading",
+ "freeTier.change",
+ "freeTier.codeBody",
+ "freeTier.completedBody",
+ "freeTier.copyLink",
+ "freeTier.defaultModel",
+ "freeTier.didNotComplete",
+ "freeTier.dismiss",
+ "freeTier.doNotShare",
+ "freeTier.done",
+ "freeTier.errorBody",
+ "freeTier.finishingBody",
+ "freeTier.finishingHeading",
+ "freeTier.notNow",
+ "freeTier.openModelPicker",
+ "freeTier.otherProviders",
+ "freeTier.providerName",
+ "freeTier.providerRowPitch",
+ "freeTier.providerRowTitle",
+ "freeTier.readyCaption",
+ "freeTier.readyTitle",
+ "freeTier.rejectedBody",
+ "freeTier.retiredBody",
+ "freeTier.settingUp",
+ "freeTier.setupFailed.gateClosed",
+ "freeTier.setupFailed.generic",
+ "freeTier.setupFailed.locked",
+ "freeTier.setupFailed.paused",
+ "freeTier.setupFailed.powRequired",
+ "freeTier.setupFailed.rateLimited",
+ "freeTier.setupFailed.retrying",
+ "freeTier.setupFailed.serverError",
+ "freeTier.setupFailed.signInBelow",
+ "freeTier.setupFailed.tryAgain",
+ "freeTier.setupFailed.unreachable",
+ "freeTier.signIn",
+ "freeTier.signInHeading",
+ "freeTier.signInInstead",
+ "freeTier.signedIn",
+ "freeTier.signedInAs",
+ "freeTier.startAgain",
+ "freeTier.statusLabel",
+ "freeTier.stripBody",
+ "freeTier.stripTitle",
+ "freeTier.supersededBody",
+ "freeTier.timedOutBody",
+ "freeTier.timedOutHeading",
+ "freeTier.tryAgain",
+ "freeTier.unreachableBody",
+ "freeTier.waiting",
+ "guidedGreeting.line",
+ "guidedGreeting.nameSuggestion",
+ "handoffTour.profileText",
+ "handoffTour.profileTitle",
+ "handoffTour.sessionsText",
+ "handoffTour.sessionsTitle",
+ "handoffTour.stayText",
+ "handoffTour.stayTitle",
+ "install.activeDesc",
+ "install.applyRemote",
+ "install.authNeedsOauth",
+ "install.authSignedIn",
+ "install.authTitle",
+ "install.backToSetup",
+ "install.bundledLocalDesc",
+ "install.cancelInstall",
+ "install.cancelling",
+ "install.connectExistingDesc",
+ "install.connectExistingShort",
+ "install.connectExistingTitle",
+ "install.connected",
+ "install.copiedOutput",
+ "install.copyCommand",
+ "install.copyOutput",
+ "install.currentStage",
+ "install.enterUrlFirst",
+ "install.error",
+ "install.failedDesc",
+ "install.failedTitle",
+ "install.fetchingManifest",
+ "install.finishingTitle",
+ "install.hideOutput",
+ "install.identityProvider",
+ "install.incompleteSignInTest",
+ "install.incompleteTokenTest",
+ "install.installCommand",
+ "install.installLocalDesc",
+ "install.installLocalTitle",
+ "install.installTo",
+ "install.lines",
+ "install.localStartUnavailable",
+ "install.noOutput",
+ "install.oneTimeTitle",
+ "install.openLogs",
+ "install.pasteSessionToken",
+ "install.probeError",
+ "install.probeErrorDetails",
+ "install.probing",
+ "install.progress",
+ "install.reloadRetry",
+ "install.remoteSetupDesc",
+ "install.remoteSetupTitle",
+ "install.remoteUrlDesc",
+ "install.remoteUrlPlaceholder",
+ "install.remoteUrlTitle",
+ "install.retryAfterRun",
+ "install.settingUpTitle",
+ "install.setupChoiceDesc",
+ "install.setupChoiceDescLocal",
+ "install.setupChoiceTitle",
+ "install.showOutput",
+ "install.signIn",
+ "install.signInIncomplete",
+ "install.signInWith",
+ "install.stageStates.failed",
+ "install.stageStates.pending",
+ "install.stageStates.running",
+ "install.stageStates.skipped",
+ "install.stageStates.succeeded",
+ "install.testConnection",
+ "install.testSucceeded",
+ "install.tokenDesc",
+ "install.tokenTitle",
+ "install.transcriptSaved",
+ "install.unsupportedDesc",
+ "install.useLocalDesc",
+ "install.useLocalTitle",
+ "install.viewDocs",
+ "interfaceMode.advanced.description",
+ "interfaceMode.advanced.label",
+ "interfaceMode.hint",
+ "interfaceMode.sessionNote",
+ "interfaceMode.simple.description",
+ "interfaceMode.simple.label",
+ "interfaceMode.title",
+ "intro.custom",
+ "keybinds.actions.appearance.toggleMode",
+ "keybinds.actions.composer.cancel",
+ "keybinds.actions.composer.dictate",
+ "keybinds.actions.composer.focus",
+ "keybinds.actions.composer.help",
+ "keybinds.actions.composer.history",
+ "keybinds.actions.composer.mention",
+ "keybinds.actions.composer.modelPicker",
+ "keybinds.actions.composer.newline",
+ "keybinds.actions.composer.queue",
+ "keybinds.actions.composer.reasoningDown",
+ "keybinds.actions.composer.reasoningUp",
+ "keybinds.actions.composer.send",
+ "keybinds.actions.composer.sendQueued",
+ "keybinds.actions.composer.slash",
+ "keybinds.actions.composer.steer",
+ "keybinds.actions.composer.voice",
+ "keybinds.actions.conversation.scrollPageDown",
+ "keybinds.actions.conversation.scrollPageUp",
+ "keybinds.actions.hud.snapToPointer",
+ "keybinds.actions.keybinds.openPanel",
+ "keybinds.actions.nav.agents",
+ "keybinds.actions.nav.artifacts",
+ "keybinds.actions.nav.capabilities",
+ "keybinds.actions.nav.commandCenter",
+ "keybinds.actions.nav.commandPalette",
+ "keybinds.actions.nav.cron",
+ "keybinds.actions.nav.messaging",
+ "keybinds.actions.nav.profiles",
+ "keybinds.actions.nav.settings",
+ "keybinds.actions.profile.create",
+ "keybinds.actions.profile.default",
+ "keybinds.actions.profile.next",
+ "keybinds.actions.profile.prev",
+ "keybinds.actions.profile.switch.1",
+ "keybinds.actions.profile.switch.10",
+ "keybinds.actions.profile.switch.11",
+ "keybinds.actions.profile.switch.12",
+ "keybinds.actions.profile.switch.13",
+ "keybinds.actions.profile.switch.14",
+ "keybinds.actions.profile.switch.15",
+ "keybinds.actions.profile.switch.16",
+ "keybinds.actions.profile.switch.17",
+ "keybinds.actions.profile.switch.18",
+ "keybinds.actions.profile.switch.2",
+ "keybinds.actions.profile.switch.3",
+ "keybinds.actions.profile.switch.4",
+ "keybinds.actions.profile.switch.5",
+ "keybinds.actions.profile.switch.6",
+ "keybinds.actions.profile.switch.7",
+ "keybinds.actions.profile.switch.8",
+ "keybinds.actions.profile.switch.9",
+ "keybinds.actions.profile.toggleAll",
+ "keybinds.actions.session.archive",
+ "keybinds.actions.session.focusSearch",
+ "keybinds.actions.session.new",
+ "keybinds.actions.session.newTab",
+ "keybinds.actions.session.newWindow",
+ "keybinds.actions.session.next",
+ "keybinds.actions.session.prev",
+ "keybinds.actions.session.slot.1",
+ "keybinds.actions.session.slot.2",
+ "keybinds.actions.session.slot.3",
+ "keybinds.actions.session.slot.4",
+ "keybinds.actions.session.slot.5",
+ "keybinds.actions.session.slot.6",
+ "keybinds.actions.session.slot.7",
+ "keybinds.actions.session.slot.8",
+ "keybinds.actions.session.slot.9",
+ "keybinds.actions.session.togglePin",
+ "keybinds.actions.view.closeTab",
+ "keybinds.actions.view.closeTerminal",
+ "keybinds.actions.view.cycleSidebarGrouping",
+ "keybinds.actions.view.findInPage",
+ "keybinds.actions.view.findNext",
+ "keybinds.actions.view.findPrevious",
+ "keybinds.actions.view.flipPanes",
+ "keybinds.actions.view.newTerminal",
+ "keybinds.actions.view.nextTerminal",
+ "keybinds.actions.view.prevTerminal",
+ "keybinds.actions.view.reopenTab",
+ "keybinds.actions.view.selectionToComposer",
+ "keybinds.actions.view.showBrowser",
+ "keybinds.actions.view.showFiles",
+ "keybinds.actions.view.showTerminal",
+ "keybinds.actions.view.tabSlot.1",
+ "keybinds.actions.view.tabSlot.2",
+ "keybinds.actions.view.tabSlot.3",
+ "keybinds.actions.view.tabSlot.4",
+ "keybinds.actions.view.tabSlot.5",
+ "keybinds.actions.view.tabSlot.6",
+ "keybinds.actions.view.tabSlot.7",
+ "keybinds.actions.view.tabSlot.8",
+ "keybinds.actions.view.tabSlot.9",
+ "keybinds.actions.view.terminalCopy",
+ "keybinds.actions.view.terminalPaste",
+ "keybinds.actions.view.toggleHud",
+ "keybinds.actions.view.toggleProfileRail",
+ "keybinds.actions.view.toggleReview",
+ "keybinds.actions.view.toggleRightSidebar",
+ "keybinds.actions.view.toggleSidebar",
+ "keybinds.actions.view.toggleSimpleMode",
+ "keybinds.actions.view.toggleStatusbar",
+ "keybinds.actions.view.toggleTabStrip",
+ "keybinds.actions.workspace.newWorktree",
+ "keybinds.actions.workspace.openFolder",
+ "keybinds.categories.composer",
+ "keybinds.categories.navigation",
+ "keybinds.categories.profiles",
+ "keybinds.categories.session",
+ "keybinds.categories.view",
+ "keybinds.clear",
+ "keybinds.conflictWith",
+ "keybinds.pressKey",
+ "keybinds.rebind",
+ "keybinds.reset",
+ "keybinds.resetAll",
+ "keybinds.search",
+ "keybinds.set",
+ "keybinds.subtitle",
+ "keybinds.title",
+ "language.description",
+ "language.label",
+ "language.noResults",
+ "language.saveError",
+ "language.saving",
+ "language.searchPlaceholder",
+ "language.switchTo",
+ "messaging.addListEntry",
+ "messaging.advanced",
+ "messaging.appliedLive",
+ "messaging.approve",
+ "messaging.approvedHint",
+ "messaging.approvedUser",
+ "messaging.approvedUsers",
+ "messaging.approving",
+ "messaging.clearField",
+ "messaging.connectingLive",
+ "messaging.credentialsSet",
+ "messaging.disableAria",
+ "messaging.disabled",
+ "messaging.enableAria",
+ "messaging.enabled",
+ "messaging.failedApprove",
+ "messaging.failedClear",
+ "messaging.failedRevoke",
+ "messaging.failedSave",
+ "messaging.failedUpdate",
+ "messaging.fieldCopy.BLUEBUBBLES_ALLOW_ALL_USERS.help",
+ "messaging.fieldCopy.BLUEBUBBLES_ALLOW_ALL_USERS.label",
+ "messaging.fieldCopy.DISCORD_ALLOWED_USERS.help",
+ "messaging.fieldCopy.DISCORD_ALLOWED_USERS.label",
+ "messaging.fieldCopy.DISCORD_ALLOW_ALL_USERS.help",
+ "messaging.fieldCopy.DISCORD_ALLOW_ALL_USERS.label",
+ "messaging.fieldCopy.DISCORD_BOT_TOKEN.help",
+ "messaging.fieldCopy.DISCORD_BOT_TOKEN.label",
+ "messaging.fieldCopy.DISCORD_HOME_CHANNEL.help",
+ "messaging.fieldCopy.DISCORD_HOME_CHANNEL.label",
+ "messaging.fieldCopy.DISCORD_HOME_CHANNEL_NAME.help",
+ "messaging.fieldCopy.DISCORD_HOME_CHANNEL_NAME.label",
+ "messaging.fieldCopy.DISCORD_REPLY_TO_MODE.help",
+ "messaging.fieldCopy.DISCORD_REPLY_TO_MODE.label",
+ "messaging.fieldCopy.MATRIX_ACCESS_TOKEN.label",
+ "messaging.fieldCopy.MATRIX_ALLOWED_USERS.help",
+ "messaging.fieldCopy.MATRIX_ALLOWED_USERS.label",
+ "messaging.fieldCopy.MATRIX_HOMESERVER.label",
+ "messaging.fieldCopy.MATRIX_HOMESERVER.placeholder",
+ "messaging.fieldCopy.MATRIX_USER_ID.label",
+ "messaging.fieldCopy.MATRIX_USER_ID.placeholder",
+ "messaging.fieldCopy.MATTERMOST_ALLOWED_USERS.help",
+ "messaging.fieldCopy.MATTERMOST_ALLOWED_USERS.label",
+ "messaging.fieldCopy.MATTERMOST_ALLOW_ALL_USERS.label",
+ "messaging.fieldCopy.MATTERMOST_HOME_CHANNEL.label",
+ "messaging.fieldCopy.MATTERMOST_TOKEN.label",
+ "messaging.fieldCopy.MATTERMOST_URL.label",
+ "messaging.fieldCopy.MATTERMOST_URL.placeholder",
+ "messaging.fieldCopy.QQBOT_HOME_CHANNEL.help",
+ "messaging.fieldCopy.QQBOT_HOME_CHANNEL.label",
+ "messaging.fieldCopy.QQBOT_HOME_CHANNEL_NAME.label",
+ "messaging.fieldCopy.QQ_ALLOW_ALL_USERS.label",
+ "messaging.fieldCopy.SIGNAL_ACCOUNT.help",
+ "messaging.fieldCopy.SIGNAL_ACCOUNT.label",
+ "messaging.fieldCopy.SIGNAL_ALLOWED_USERS.help",
+ "messaging.fieldCopy.SIGNAL_ALLOWED_USERS.label",
+ "messaging.fieldCopy.SIGNAL_HTTP_URL.help",
+ "messaging.fieldCopy.SIGNAL_HTTP_URL.label",
+ "messaging.fieldCopy.SIGNAL_HTTP_URL.placeholder",
+ "messaging.fieldCopy.SLACK_ALLOWED_USERS.help",
+ "messaging.fieldCopy.SLACK_ALLOWED_USERS.label",
+ "messaging.fieldCopy.SLACK_APP_TOKEN.help",
+ "messaging.fieldCopy.SLACK_APP_TOKEN.label",
+ "messaging.fieldCopy.SLACK_APP_TOKEN.placeholder",
+ "messaging.fieldCopy.SLACK_BOT_TOKEN.help",
+ "messaging.fieldCopy.SLACK_BOT_TOKEN.label",
+ "messaging.fieldCopy.SLACK_BOT_TOKEN.placeholder",
+ "messaging.fieldCopy.TELEGRAM_ALLOWED_USERS.help",
+ "messaging.fieldCopy.TELEGRAM_ALLOWED_USERS.label",
+ "messaging.fieldCopy.TELEGRAM_BOT_TOKEN.help",
+ "messaging.fieldCopy.TELEGRAM_BOT_TOKEN.label",
+ "messaging.fieldCopy.TELEGRAM_BOT_TOKEN.placeholder",
+ "messaging.fieldCopy.TELEGRAM_PROXY.help",
+ "messaging.fieldCopy.TELEGRAM_PROXY.label",
+ "messaging.fieldCopy.WHATSAPP_ALLOWED_USERS.help",
+ "messaging.fieldCopy.WHATSAPP_ALLOWED_USERS.label",
+ "messaging.fieldCopy.WHATSAPP_ENABLED.help",
+ "messaging.fieldCopy.WHATSAPP_ENABLED.label",
+ "messaging.fieldCopy.WHATSAPP_MODE.label",
+ "messaging.gatewayStopped",
+ "messaging.getCredentials",
+ "messaging.hintGatewayStopped",
+ "messaging.hintPendingRestart",
+ "messaging.keyCleared",
+ "messaging.listEntryPlaceholder",
+ "messaging.loadFailed",
+ "messaging.loading",
+ "messaging.needsSetup",
+ "messaging.noTokenNeeded",
+ "messaging.openDocs",
+ "messaging.openLogs",
+ "messaging.openSetupGuide",
+ "messaging.pairingLockedOut",
+ "messaging.pendingAria",
+ "messaging.pendingRequests",
+ "messaging.platformDisabled",
+ "messaging.platformEnabled",
+ "messaging.recommended",
+ "messaging.removeListEntry",
+ "messaging.replaceValue",
+ "messaging.required",
+ "messaging.restartAgain",
+ "messaging.restartFailedManual",
+ "messaging.restartFailedManualDetail",
+ "messaging.restartNeeded",
+ "messaging.restartNow",
+ "messaging.restartToApply",
+ "messaging.restartToReconnect",
+ "messaging.restarting",
+ "messaging.revoke",
+ "messaging.revokeAria",
+ "messaging.revokeDesc",
+ "messaging.revokeTitle",
+ "messaging.revokedUser",
+ "messaging.revoking",
+ "messaging.saveChanges",
+ "messaging.saved",
+ "messaging.saving",
+ "messaging.search",
+ "messaging.setupSaved",
+ "messaging.setupUpdated",
+ "messaging.sharedListenerUrl",
+ "messaging.states.connected",
+ "messaging.states.connecting",
+ "messaging.states.disabled",
+ "messaging.states.fatal",
+ "messaging.states.gateway_stopped",
+ "messaging.states.not_configured",
+ "messaging.states.pending_restart",
+ "messaging.states.retrying",
+ "messaging.states.startup_failed",
+ "messaging.statusFilter.all",
+ "messaging.statusFilter.bad",
+ "messaging.statusFilter.good",
+ "messaging.statusFilter.muted",
+ "messaging.statusFilter.warn",
+ "messaging.telegramQr.add",
+ "messaging.telegramQr.addAtLeastOne",
+ "messaging.telegramQr.allowedUsers",
+ "messaging.telegramQr.applying",
+ "messaging.telegramQr.createWithQr",
+ "messaging.telegramQr.expired",
+ "messaging.telegramQr.expiresIn",
+ "messaging.telegramQr.numericOnly",
+ "messaging.telegramQr.openTelegram",
+ "messaging.telegramQr.ownerDetected",
+ "messaging.telegramQr.pairingExpired",
+ "messaging.telegramQr.quickHelp",
+ "messaging.telegramQr.quickSetup",
+ "messaging.telegramQr.ready",
+ "messaging.telegramQr.recommended",
+ "messaging.telegramQr.replaceWarning",
+ "messaging.telegramQr.saveAndRestart",
+ "messaging.telegramQr.savedRestartFailed",
+ "messaging.telegramQr.savedRestarting",
+ "messaging.telegramQr.scanHint",
+ "messaging.telegramQr.starting",
+ "messaging.telegramQr.stillWaiting",
+ "messaging.telegramQr.subtitle",
+ "messaging.telegramQr.title",
+ "messaging.telegramQr.userIdPlaceholder",
+ "messaging.telegramQr.waiting",
+ "messaging.unknown",
+ "messaging.unsavedChanges",
+ "messaging.waitingSince",
+ "modelAssignment.confirmAction",
+ "modelAssignment.confirmDetail",
+ "modelAssignment.confirmTitle",
+ "modelAssignment.declined",
+ "modelAssignment.saveFailed",
+ "modelPicker.addCustomModelAction",
+ "modelPicker.addProvider",
+ "modelPicker.current",
+ "modelPicker.customModel",
+ "modelPicker.customModelPlaceholder",
+ "modelPicker.downloading",
+ "modelPicker.free",
+ "modelPicker.freeTier",
+ "modelPicker.loadFailed",
+ "modelPicker.loadingIntoMemory",
+ "modelPicker.localDownloadsHeading",
+ "modelPicker.noAuthenticatedProviders",
+ "modelPicker.noModels",
+ "modelPicker.priceTitle",
+ "modelPicker.pro",
+ "modelPicker.proNeedsSubscription",
+ "modelPicker.search",
+ "modelPicker.title",
+ "modelPicker.unknown",
+ "modelPicker.wasPrice",
+ "modelVisibility.addCustomModel",
+ "modelVisibility.addProvider",
+ "modelVisibility.noAuthenticatedProviders",
+ "modelVisibility.removeCustomModel",
+ "modelVisibility.resetAction",
+ "modelVisibility.resetConfirm",
+ "modelVisibility.resetDescription",
+ "modelVisibility.resetToDefaults",
+ "modelVisibility.search",
+ "modelVisibility.title",
+ "notifications.actions.openGateways",
+ "notifications.actions.openKeys",
+ "notifications.actions.openMaintenance",
+ "notifications.actions.restartHermes",
+ "notifications.backendOutOfDateMessage",
+ "notifications.backendOutOfDateTitle",
+ "notifications.clearAll",
+ "notifications.compressDeferredDone",
+ "notifications.copyDetail",
+ "notifications.copyDetailFailed",
+ "notifications.desktopOutOfDateMessage",
+ "notifications.desktopOutOfDateTitle",
+ "notifications.details",
+ "notifications.dismiss",
+ "notifications.errors.codeSkewRestartRequired",
+ "notifications.errors.diskFull",
+ "notifications.errors.elevenLabsNeedsKey",
+ "notifications.errors.elevenLabsRejectedKey",
+ "notifications.errors.gatewayAuthFailed",
+ "notifications.errors.methodNotAllowed",
+ "notifications.errors.microphonePermission",
+ "notifications.errors.openaiRejectedApiKey",
+ "notifications.errors.openaiTtsNeedsKey",
+ "notifications.errors.restartHermesFailed",
+ "notifications.errors.rpcOutOfSync",
+ "notifications.errors.storageFailure",
+ "notifications.hide",
+ "notifications.installMethodUnsupportedTitle",
+ "notifications.mcp.disable",
+ "notifications.mcp.disableFailed",
+ "notifications.mcp.disabledMessage",
+ "notifications.mcp.errorMessage",
+ "notifications.mcp.errorTitle",
+ "notifications.mcp.needsAuthMessage",
+ "notifications.mcp.needsAuthTitle",
+ "notifications.mcp.signIn",
+ "notifications.mcp.view",
+ "notifications.more",
+ "notifications.native.approvalTitle",
+ "notifications.native.approvalTitleNamed",
+ "notifications.native.approveAction",
+ "notifications.native.backgroundDoneTitle",
+ "notifications.native.backgroundFailedTitle",
+ "notifications.native.creditsTitle",
+ "notifications.native.inputBody",
+ "notifications.native.inputTitle",
+ "notifications.native.inputTitleNamed",
+ "notifications.native.rejectAction",
+ "notifications.native.turnDoneBody",
+ "notifications.native.turnDoneTitle",
+ "notifications.native.turnErrorTitle",
+ "notifications.region",
+ "notifications.seeWhatsNew",
+ "notifications.sharedProfileWarning",
+ "notifications.show",
+ "notifications.updateDesktopApp",
+ "notifications.updateHermes",
+ "notifications.updateReadyMessage",
+ "notifications.updateReadyMessageAppInstaller",
+ "notifications.updateReadyMessageUnknown",
+ "notifications.updateReadyTitle",
+ "notifications.voice.configureSpeechToText",
+ "notifications.voice.couldNotStartSession",
+ "notifications.voice.liveDelegationFailed",
+ "notifications.voice.liveEnded",
+ "notifications.voice.liveEndedClosed",
+ "notifications.voice.liveEndedConnectionLost",
+ "notifications.voice.liveError",
+ "notifications.voice.liveUnavailable",
+ "notifications.voice.microphoneAccessDenied",
+ "notifications.voice.microphoneConstraintsUnsupported",
+ "notifications.voice.microphoneFailed",
+ "notifications.voice.microphoneInUse",
+ "notifications.voice.microphonePermissionDenied",
+ "notifications.voice.microphoneStartFailed",
+ "notifications.voice.microphoneUnsupported",
+ "notifications.voice.noMicrophone",
+ "notifications.voice.noSpeechDetected",
+ "notifications.voice.playbackFailed",
+ "notifications.voice.recordingFailed",
+ "notifications.voice.sayStopToEnd",
+ "notifications.voice.transcriptionFailed",
+ "notifications.voice.transcriptionUnavailable",
+ "notifications.voice.tryRecordingAgain",
+ "notifications.voice.unavailable",
+ "onboarding.apiKeyOptions.fireworks.description",
+ "onboarding.apiKeyOptions.fireworks.short",
+ "onboarding.apiKeyOptions.gemini.description",
+ "onboarding.apiKeyOptions.gemini.short",
+ "onboarding.apiKeyOptions.local.description",
+ "onboarding.apiKeyOptions.local.short",
+ "onboarding.apiKeyOptions.openai.description",
+ "onboarding.apiKeyOptions.openai.short",
+ "onboarding.apiKeyOptions.openrouter.description",
+ "onboarding.apiKeyOptions.openrouter.short",
+ "onboarding.apiKeyOptions.xai.description",
+ "onboarding.apiKeyOptions.xai.short",
+ "onboarding.authorizeThere",
+ "onboarding.autoBrowser",
+ "onboarding.backToSignIn",
+ "onboarding.change",
+ "onboarding.chooseLater",
+ "onboarding.collapse",
+ "onboarding.connected",
+ "onboarding.connectedPicking",
+ "onboarding.connectedProvider",
+ "onboarding.connecting",
+ "onboarding.copy",
+ "onboarding.copyAuthCode",
+ "onboarding.couldNotSave",
+ "onboarding.defaultModel",
+ "onboarding.deviceCodeOpened",
+ "onboarding.docs",
+ "onboarding.errorDetails",
+ "onboarding.externalPending",
+ "onboarding.featuredPitch",
+ "onboarding.fireworksPitch",
+ "onboarding.flowSubtitles.device_code",
+ "onboarding.flowSubtitles.external",
+ "onboarding.flowSubtitles.pkce",
+ "onboarding.free",
+ "onboarding.freeTier",
+ "onboarding.getKey",
+ "onboarding.haveApiKey",
+ "onboarding.headerDesc",
+ "onboarding.headerTitle",
+ "onboarding.localApiKeyPlaceholder",
+ "onboarding.localModelNamePlaceholder",
+ "onboarding.localModelsPitch",
+ "onboarding.localModelsTitle",
+ "onboarding.lookingUpProviders",
+ "onboarding.openRouterPitch",
+ "onboarding.openedBrowser",
+ "onboarding.otherProviders",
+ "onboarding.pasteApiKey",
+ "onboarding.pasteAuthCode",
+ "onboarding.pickDifferentProvider",
+ "onboarding.preparingInstall",
+ "onboarding.price",
+ "onboarding.pro",
+ "onboarding.recommended",
+ "onboarding.reopenAuthPage",
+ "onboarding.reopenSignInPage",
+ "onboarding.reopenVerification",
+ "onboarding.replaceCurrent",
+ "onboarding.signInDidNotFinish",
+ "onboarding.signInExpired",
+ "onboarding.signInFailed",
+ "onboarding.signInWith",
+ "onboarding.signedIn",
+ "onboarding.startChatting",
+ "onboarding.starting",
+ "onboarding.startingSignIn",
+ "onboarding.tryAgain",
+ "onboarding.update",
+ "onboarding.useApiKeyInstead",
+ "onboarding.verifyingCode",
+ "onboarding.waitingAuthorize",
+ "preview.binaryBody",
+ "preview.binaryTitle",
+ "preview.closePane",
+ "preview.console.clear",
+ "preview.console.copy",
+ "preview.console.copyAll",
+ "preview.console.copyEntry",
+ "preview.console.copyFailed",
+ "preview.console.copySelected",
+ "preview.console.deselect",
+ "preview.console.empty",
+ "preview.console.messages",
+ "preview.console.promptHeader",
+ "preview.console.resize",
+ "preview.console.select",
+ "preview.console.selected",
+ "preview.console.sendEntry",
+ "preview.console.sendToChat",
+ "preview.console.sentMessage",
+ "preview.console.sentTitle",
+ "preview.console.title",
+ "preview.diff",
+ "preview.discardReload",
+ "preview.diskChangedBody",
+ "preview.diskChangedTitle",
+ "preview.edit",
+ "preview.editing",
+ "preview.hide",
+ "preview.largeBody",
+ "preview.largeTitle",
+ "preview.linkHint",
+ "preview.loading",
+ "preview.missingBody",
+ "preview.missingTarget",
+ "preview.missingTitle",
+ "preview.noInlineBody",
+ "preview.noInlineTitle",
+ "preview.openInBrowser",
+ "preview.openInExternal",
+ "preview.openPreview",
+ "preview.opening",
+ "preview.overwrite",
+ "preview.pin",
+ "preview.popIn",
+ "preview.popOut",
+ "preview.previewAnyway",
+ "preview.renderedPreview",
+ "preview.saveFailed",
+ "preview.saveScopeChanged",
+ "preview.source",
+ "preview.sourceLineTitle",
+ "preview.tab",
+ "preview.truncated",
+ "preview.unavailable",
+ "preview.unknownSize",
+ "preview.unpin",
+ "preview.unsavedChanges",
+ "preview.web.addComments",
+ "preview.web.address",
+ "preview.web.addressPlaceholder",
+ "preview.web.annotate",
+ "preview.web.annotateFailed",
+ "preview.web.annotateNeedPage",
+ "preview.web.annotateOn",
+ "preview.web.appFailedToBoot",
+ "preview.web.askRestart",
+ "preview.web.blankPageBody",
+ "preview.web.cancelComment",
+ "preview.web.commentPlaceholder",
+ "preview.web.commentTitle",
+ "preview.web.commenting",
+ "preview.web.failedRestarting",
+ "preview.web.failedToLoad",
+ "preview.web.fallbackTitle",
+ "preview.web.fileChanged",
+ "preview.web.filesChanged",
+ "preview.web.finishedRestarting",
+ "preview.web.goBack",
+ "preview.web.goForward",
+ "preview.web.hideConsole",
+ "preview.web.hideDevTools",
+ "preview.web.loadFailedConsole",
+ "preview.web.lookingRestart",
+ "preview.web.moduleMimeDescription",
+ "preview.web.openDevTools",
+ "preview.web.openTarget",
+ "preview.web.reload",
+ "preview.web.reloadingNow",
+ "preview.web.remoteLoopback",
+ "preview.web.restartFailed",
+ "preview.web.restartFailedMessage",
+ "preview.web.restartFailedTitle",
+ "preview.web.restartedTitle",
+ "preview.web.restarting",
+ "preview.web.restartingMessage",
+ "preview.web.restartingTitle",
+ "preview.web.saveComment",
+ "preview.web.serverNotFound",
+ "preview.web.showConsole",
+ "preview.web.startRestartFailed",
+ "preview.web.stillWorking",
+ "preview.web.tryAgain",
+ "preview.web.unknownError",
+ "preview.web.unreachableDescription",
+ "preview.web.watchFailed",
+ "preview.web.workspaceReloading",
+ "profiles.actions",
+ "profiles.allProfiles",
+ "profiles.autoColor",
+ "profiles.cloneFrom",
+ "profiles.cloneFromDefault",
+ "profiles.cloneFromDefaultDesc",
+ "profiles.cloneFromDesc",
+ "profiles.cloneFromNone",
+ "profiles.close",
+ "profiles.color",
+ "profiles.colorFor",
+ "profiles.connectGateway",
+ "profiles.copySetup",
+ "profiles.copying",
+ "profiles.count",
+ "profiles.createAction",
+ "profiles.createDesc",
+ "profiles.created",
+ "profiles.creating",
+ "profiles.default",
+ "profiles.defaultBadge",
+ "profiles.defaultDescription",
+ "profiles.defaultProfile",
+ "profiles.defaultSet",
+ "profiles.deleteDescMid",
+ "profiles.deleteDescPrefix",
+ "profiles.deleteDescSuffix",
+ "profiles.deleteTitle",
+ "profiles.deleted",
+ "profiles.deleting",
+ "profiles.displayNameDesc",
+ "profiles.displayNameLabel",
+ "profiles.displayNameTitle",
+ "profiles.editSoul",
+ "profiles.emptySoul",
+ "profiles.env",
+ "profiles.exportMenu",
+ "profiles.exportProfile",
+ "profiles.exported",
+ "profiles.failedCopy",
+ "profiles.failedCreate",
+ "profiles.failedDelete",
+ "profiles.failedExport",
+ "profiles.failedImport",
+ "profiles.failedLoad",
+ "profiles.failedLoadSoul",
+ "profiles.failedRename",
+ "profiles.failedSaveSoul",
+ "profiles.failedSetDefault",
+ "profiles.fleet.allOnGateway",
+ "profiles.fleet.connectExistingInstead",
+ "profiles.fleet.deleteOn",
+ "profiles.fleet.gateway",
+ "profiles.fleet.gatewayUnreachable",
+ "profiles.fleet.installDeviceConfirm",
+ "profiles.fleet.installDeviceDesc",
+ "profiles.fleet.installDeviceTitle",
+ "profiles.fleet.localDevice",
+ "profiles.fleet.onGateway",
+ "profiles.fleet.switchDeviceConfirm",
+ "profiles.fleet.switchDeviceDesc",
+ "profiles.fleet.switchDeviceTitle",
+ "profiles.fleet.switchTo",
+ "profiles.importProfile",
+ "profiles.imported",
+ "profiles.invalidName",
+ "profiles.loading",
+ "profiles.loadingSoul",
+ "profiles.manageProfiles",
+ "profiles.modelLabel",
+ "profiles.nameHint",
+ "profiles.nameLabel",
+ "profiles.nameRequired",
+ "profiles.newNameLabel",
+ "profiles.newProfile",
+ "profiles.noProfiles",
+ "profiles.notSet",
+ "profiles.openInNewWindow",
+ "profiles.refresh",
+ "profiles.refreshing",
+ "profiles.remoteOverride.authFailedMessage",
+ "profiles.remoteOverride.authFailedTitle",
+ "profiles.remoteOverride.badge",
+ "profiles.remoteOverride.collisionWarning",
+ "profiles.remoteOverride.confirmBack",
+ "profiles.remoteOverride.confirmNote",
+ "profiles.remoteOverride.confirmTitle",
+ "profiles.remoteOverride.connect",
+ "profiles.remoteOverride.connecting",
+ "profiles.remoteOverride.description",
+ "profiles.remoteOverride.disconnect",
+ "profiles.remoteOverride.menuItem",
+ "profiles.remoteOverride.plainTextOptIn",
+ "profiles.remoteOverride.removeFailed",
+ "profiles.remoteOverride.removedMessage",
+ "profiles.remoteOverride.removedTitle",
+ "profiles.remoteOverride.savedMessage",
+ "profiles.remoteOverride.savedTitle",
+ "profiles.remoteOverride.title",
+ "profiles.remoteOverride.tokenLabel",
+ "profiles.remoteOverride.tokenPlaceholder",
+ "profiles.remoteOverride.tokenSavedHint",
+ "profiles.remoteOverride.updateToken",
+ "profiles.remoteOverride.urlInvalid",
+ "profiles.remoteOverride.urlLabel",
+ "profiles.remoteOverride.urlPlaceholder",
+ "profiles.rename",
+ "profiles.renameDescPrefix",
+ "profiles.renameDescSuffix",
+ "profiles.renameMenu",
+ "profiles.renameTitle",
+ "profiles.renamed",
+ "profiles.renaming",
+ "profiles.saveSoul",
+ "profiles.saving",
+ "profiles.search",
+ "profiles.selectPrompt",
+ "profiles.setAsDefault",
+ "profiles.setColor",
+ "profiles.setupCopied",
+ "profiles.showAllProfiles",
+ "profiles.skills",
+ "profiles.skillsLabel",
+ "profiles.soulDesc",
+ "profiles.soulMissing",
+ "profiles.soulOptional",
+ "profiles.soulPlaceholder",
+ "profiles.soulPlaceholderCloned",
+ "profiles.soulPlaceholderEmpty",
+ "profiles.soulSaved",
+ "profiles.status.needsInput",
+ "profiles.status.unread",
+ "profiles.status.working",
+ "profiles.switchConnectionFailed",
+ "profiles.switchToConnection",
+ "profiles.switchToProfile",
+ "profiles.title",
+ "profiles.unsavedChanges",
+ "prompts.gatewayDisconnected",
+ "prompts.reconnect",
+ "prompts.secretDesc",
+ "prompts.secretPlaceholder",
+ "prompts.secretSendFailed",
+ "prompts.secretTitle",
+ "prompts.sudoCommandUnavailable",
+ "prompts.sudoDesc",
+ "prompts.sudoInstallDesc",
+ "prompts.sudoPlaceholder",
+ "prompts.sudoSendFailed",
+ "prompts.sudoTitle",
+ "prompts.vaultCodeConfirm",
+ "prompts.vaultCodeDesc",
+ "prompts.vaultCodeFootnote",
+ "prompts.vaultCodeLabel",
+ "prompts.vaultCodeSendFailed",
+ "prompts.vaultCodeSkip",
+ "prompts.vaultCodeTitle",
+ "prompts.vaultSaveConfirm",
+ "prompts.vaultSaveDecline",
+ "prompts.vaultSaveDesc",
+ "prompts.vaultSaveFootnote",
+ "prompts.vaultSaveIdentifierLabel",
+ "prompts.vaultSaveIdentifierPlaceholder",
+ "prompts.vaultSavePasswordPlaceholder",
+ "prompts.vaultSaveSendFailed",
+ "prompts.vaultSaveTitle",
+ "prompts.vaultUnlockConfirm",
+ "prompts.vaultUnlockDesc",
+ "prompts.vaultUnlockKeepLocked",
+ "prompts.vaultUnlockPlaceholder",
+ "prompts.vaultUnlockSendFailed",
+ "prompts.vaultUnlockTitle",
+ "remoteDisplayBanner.message",
+ "rightSidebar.addToChat",
+ "rightSidebar.aria",
+ "rightSidebar.changeCwdTitle",
+ "rightSidebar.collapseAll",
+ "rightSidebar.couldNotPreview",
+ "rightSidebar.emptyBody",
+ "rightSidebar.emptyTitle",
+ "rightSidebar.files",
+ "rightSidebar.folderTip",
+ "rightSidebar.hideIgnored",
+ "rightSidebar.loadingFiles",
+ "rightSidebar.loadingTree",
+ "rightSidebar.noDiffs",
+ "rightSidebar.noFolderSelected",
+ "rightSidebar.noProjectBody",
+ "rightSidebar.noProjectOpen",
+ "rightSidebar.noProjectTitle",
+ "rightSidebar.openFolder",
+ "rightSidebar.panelsAria",
+ "rightSidebar.previewUnavailable",
+ "rightSidebar.refreshTree",
+ "rightSidebar.remotePickerCreateFolder",
+ "rightSidebar.remotePickerCreateFolderFailed",
+ "rightSidebar.remotePickerDescription",
+ "rightSidebar.remotePickerFolderName",
+ "rightSidebar.remotePickerInvalidFolderName",
+ "rightSidebar.remotePickerNewFolder",
+ "rightSidebar.remotePickerSelect",
+ "rightSidebar.remotePickerTitle",
+ "rightSidebar.showIgnored",
+ "rightSidebar.terminal",
+ "rightSidebar.terminalCloseAll",
+ "rightSidebar.terminalCloseOthers",
+ "rightSidebar.terminalHide",
+ "rightSidebar.terminalNew",
+ "rightSidebar.terminalOpenInteractive",
+ "rightSidebar.terminalReadOnly",
+ "rightSidebar.terminalReadOnlyHelp",
+ "rightSidebar.terminalsAria",
+ "rightSidebar.treeErrorBody",
+ "rightSidebar.treeErrorTitle",
+ "rightSidebar.tryAgain",
+ "rightSidebar.unreadableBody",
+ "rightSidebar.unreadableTitle",
+ "sendDiagnostics.cancel",
+ "sendDiagnostics.close",
+ "sendDiagnostics.copyLink",
+ "sendDiagnostics.doneDescription",
+ "sendDiagnostics.doneTitle",
+ "sendDiagnostics.failedHint",
+ "sendDiagnostics.failedTitle",
+ "sendDiagnostics.handoffLead",
+ "sendDiagnostics.links.discord",
+ "sendDiagnostics.links.github",
+ "sendDiagnostics.links.portal",
+ "sendDiagnostics.privacyNotice",
+ "sendDiagnostics.title",
+ "sendDiagnostics.upload",
+ "sendDiagnostics.uploadIdFallback",
+ "sendDiagnostics.uploading",
+ "sessionImport.action",
+ "sessionImport.all",
+ "sessionImport.choose",
+ "sessionImport.chooseHelp",
+ "sessionImport.connectedComputer",
+ "sessionImport.continue",
+ "sessionImport.copyNotice",
+ "sessionImport.destination",
+ "sessionImport.empty",
+ "sessionImport.emptyHelp",
+ "sessionImport.importError",
+ "sessionImport.importing",
+ "sessionImport.messages",
+ "sessionImport.more",
+ "sessionImport.noMatches",
+ "sessionImport.open",
+ "sessionImport.previewError",
+ "sessionImport.previewHelp",
+ "sessionImport.previewLimit",
+ "sessionImport.previewLoading",
+ "sessionImport.readingFrom",
+ "sessionImport.scanError",
+ "sessionImport.scanHelp",
+ "sessionImport.scanning",
+ "sessionImport.search",
+ "sessionImport.searchHelp",
+ "sessionImport.skipped",
+ "sessionImport.snapshot",
+ "sessionImport.subtitle",
+ "sessionImport.title",
+ "sessionImport.you",
+ "settings.about.updates",
+ "settings.appearance.appActionsDesc",
+ "settings.appearance.appActionsLeft",
+ "settings.appearance.appActionsRight",
+ "settings.appearance.appActionsTitle",
+ "settings.appearance.backdropDesc",
+ "settings.appearance.backdropTitle",
+ "settings.appearance.chatFontDesc",
+ "settings.appearance.chatFontPlaceholder",
+ "settings.appearance.chatFontPreview",
+ "settings.appearance.chatFontReset",
+ "settings.appearance.chatFontSample",
+ "settings.appearance.chatFontTitle",
+ "settings.appearance.chatTextScaleDesc",
+ "settings.appearance.chatTextScaleTitle",
+ "settings.appearance.colorMode",
+ "settings.appearance.colorModeDesc",
+ "settings.appearance.composerPopoutDesc",
+ "settings.appearance.composerPopoutTitle",
+ "settings.appearance.embedsAlways",
+ "settings.appearance.embedsAsk",
+ "settings.appearance.embedsDesc",
+ "settings.appearance.embedsOff",
+ "settings.appearance.embedsReset",
+ "settings.appearance.embedsTitle",
+ "settings.appearance.fileBrowserDesc",
+ "settings.appearance.fileBrowserTitle",
+ "settings.appearance.hideCodeDiffsDesc",
+ "settings.appearance.hideCodeDiffsTitle",
+ "settings.appearance.hideThreadTimelineDesc",
+ "settings.appearance.hideThreadTimelineTitle",
+ "settings.appearance.importedBadge",
+ "settings.appearance.installButton",
+ "settings.appearance.installDesc",
+ "settings.appearance.installError",
+ "settings.appearance.installPlaceholder",
+ "settings.appearance.installTitle",
+ "settings.appearance.installed",
+ "settings.appearance.installing",
+ "settings.appearance.intro",
+ "settings.appearance.introSplashDesc",
+ "settings.appearance.introSplashTitle",
+ "settings.appearance.modelPricingDesc",
+ "settings.appearance.modelPricingTitle",
+ "settings.appearance.pet.adoptFailed",
+ "settings.appearance.pet.chooseDesc",
+ "settings.appearance.pet.chooseTitle",
+ "settings.appearance.pet.count",
+ "settings.appearance.pet.countCapped",
+ "settings.appearance.pet.delete",
+ "settings.appearance.pet.deleteBody",
+ "settings.appearance.pet.deleteConfirm",
+ "settings.appearance.pet.deleteTitle",
+ "settings.appearance.pet.exportFailed",
+ "settings.appearance.pet.exportPet",
+ "settings.appearance.pet.generatedTag",
+ "settings.appearance.pet.installedTag",
+ "settings.appearance.pet.intro",
+ "settings.appearance.pet.noMatch",
+ "settings.appearance.pet.noneAvailable",
+ "settings.appearance.pet.rename",
+ "settings.appearance.pet.renameFailed",
+ "settings.appearance.pet.renamePlaceholder",
+ "settings.appearance.pet.renameSave",
+ "settings.appearance.pet.renameTitle",
+ "settings.appearance.pet.restartHint",
+ "settings.appearance.pet.roamDesc",
+ "settings.appearance.pet.roamTitle",
+ "settings.appearance.pet.scaleDesc",
+ "settings.appearance.pet.scaleTitle",
+ "settings.appearance.pet.searchPlaceholder",
+ "settings.appearance.pet.title",
+ "settings.appearance.pet.turnOffFailed",
+ "settings.appearance.pet.turnOnFailed",
+ "settings.appearance.pet.uninstall",
+ "settings.appearance.pet.uninstallFailed",
+ "settings.appearance.pet.unreachable",
+ "settings.appearance.product",
+ "settings.appearance.productDesc",
+ "settings.appearance.reactionsDesc",
+ "settings.appearance.reactionsTitle",
+ "settings.appearance.reasoningCollapsedDesc",
+ "settings.appearance.reasoningCollapsedTitle",
+ "settings.appearance.removeTheme",
+ "settings.appearance.resumeLastSessionDesc",
+ "settings.appearance.resumeLastSessionTitle",
+ "settings.appearance.sessionDensityComfortable",
+ "settings.appearance.sessionDensityCompact",
+ "settings.appearance.sessionDensityDesc",
+ "settings.appearance.sessionDensityDetailed",
+ "settings.appearance.sessionDensityTitle",
+ "settings.appearance.tabStripAlways",
+ "settings.appearance.tabStripAuto",
+ "settings.appearance.tabStripDesc",
+ "settings.appearance.tabStripNever",
+ "settings.appearance.tabStripTitle",
+ "settings.appearance.technical",
+ "settings.appearance.technicalDesc",
+ "settings.appearance.terminalFontDesc",
+ "settings.appearance.terminalFontPlaceholder",
+ "settings.appearance.terminalFontPreview",
+ "settings.appearance.terminalFontReset",
+ "settings.appearance.terminalFontTitle",
+ "settings.appearance.textDirection.auto",
+ "settings.appearance.textDirection.ltr",
+ "settings.appearance.textDirection.rtl",
+ "settings.appearance.textDirectionDesc",
+ "settings.appearance.textDirectionTitle",
+ "settings.appearance.themeDesc",
+ "settings.appearance.themeProfileNote",
+ "settings.appearance.themeSearchPlaceholder",
+ "settings.appearance.themeTitle",
+ "settings.appearance.tipsDesc",
+ "settings.appearance.tipsReset",
+ "settings.appearance.tipsTitle",
+ "settings.appearance.title",
+ "settings.appearance.toolViewDesc",
+ "settings.appearance.toolViewTitle",
+ "settings.appearance.toursDesc",
+ "settings.appearance.toursTitle",
+ "settings.appearance.translucencyDesc",
+ "settings.appearance.translucencyFadeTitle",
+ "settings.appearance.translucencyFrost.header",
+ "settings.appearance.translucencyFrost.popover",
+ "settings.appearance.translucencyFrost.titlebar",
+ "settings.appearance.translucencyFrost.under-window",
+ "settings.appearance.translucencyFrostTitle",
+ "settings.appearance.translucencyGlassDesc",
+ "settings.appearance.translucencyModeClear",
+ "settings.appearance.translucencyModeGlass",
+ "settings.appearance.translucencyScope.sidebar",
+ "settings.appearance.translucencyScope.window",
+ "settings.appearance.translucencyScopeTitle",
+ "settings.appearance.translucencyTintTitle",
+ "settings.appearance.translucencyTitle",
+ "settings.appearance.uiScaleDesc",
+ "settings.appearance.uiScaleTitle",
+ "settings.appearance.userBubbleDesc",
+ "settings.appearance.userBubbleTitle",
+ "settings.appearance.vibeHeartsDesc",
+ "settings.appearance.vibeHeartsTitle",
+ "settings.billing.amountValidation.decimal",
+ "settings.billing.amountValidation.greaterThanThreshold",
+ "settings.billing.amountValidation.maximum",
+ "settings.billing.amountValidation.minimum",
+ "settings.billing.amountValidation.positive",
+ "settings.billing.amountValidation.reloadTo",
+ "settings.billing.autoReload.cancel",
+ "settings.billing.autoReload.disable",
+ "settings.billing.autoReload.manage",
+ "settings.billing.autoReload.reloadTo",
+ "settings.billing.autoReload.reloadToAria",
+ "settings.billing.autoReload.save",
+ "settings.billing.autoReload.saving",
+ "settings.billing.autoReload.threshold",
+ "settings.billing.autoReload.thresholdAria",
+ "settings.billing.autoReload.turnOff",
+ "settings.billing.autoReload.turnOffConfirm",
+ "settings.billing.autoReload.turnedOff",
+ "settings.billing.autoReload.updated",
+ "settings.billing.buyCredits.added",
+ "settings.billing.buyCredits.buyButton",
+ "settings.billing.buyCredits.customAmount",
+ "settings.billing.buyCredits.openPortal",
+ "settings.billing.buyCredits.processing",
+ "settings.billing.buyCredits.retry",
+ "settings.billing.buyCredits.title",
+ "settings.billing.charge.added",
+ "settings.billing.charge.authenticationRequired",
+ "settings.billing.charge.checkBody",
+ "settings.billing.charge.checkTitle",
+ "settings.billing.charge.declined",
+ "settings.billing.charge.expired",
+ "settings.billing.charge.failedBody",
+ "settings.billing.charge.failedTitle",
+ "settings.billing.charge.timeoutBody",
+ "settings.billing.charge.timeoutTitle",
+ "settings.billing.charge.unconfirmedBody",
+ "settings.billing.charge.unconfirmedTitle",
+ "settings.billing.charge.untrackedBody",
+ "settings.billing.charge.untrackedTitle",
+ "settings.billing.creditsPerMonth",
+ "settings.billing.errors.cliBillingDisabled.message",
+ "settings.billing.errors.cliBillingDisabled.title",
+ "settings.billing.errors.consentRequired.message",
+ "settings.billing.errors.consentRequired.title",
+ "settings.billing.errors.default.message",
+ "settings.billing.errors.default.title",
+ "settings.billing.errors.endpointUnavailable.message",
+ "settings.billing.errors.endpointUnavailable.title",
+ "settings.billing.errors.idempotencyConflict.message",
+ "settings.billing.errors.idempotencyConflict.title",
+ "settings.billing.errors.insufficientScope.message",
+ "settings.billing.errors.insufficientScope.title",
+ "settings.billing.errors.monthlyCapExceeded.messageHeadroom",
+ "settings.billing.errors.monthlyCapExceeded.messageReached",
+ "settings.billing.errors.monthlyCapExceeded.title",
+ "settings.billing.errors.noPaymentMethod.message",
+ "settings.billing.errors.noPaymentMethod.title",
+ "settings.billing.errors.orgAccessDenied.message",
+ "settings.billing.errors.orgAccessDenied.title",
+ "settings.billing.errors.rateLimited.message",
+ "settings.billing.errors.rateLimited.title",
+ "settings.billing.errors.remoteSpendingReconnect",
+ "settings.billing.errors.remoteSpendingRevoked.messageByAdmin",
+ "settings.billing.errors.remoteSpendingRevoked.messageBySelf",
+ "settings.billing.errors.remoteSpendingRevoked.title",
+ "settings.billing.errors.roleRequired.message",
+ "settings.billing.errors.roleRequired.title",
+ "settings.billing.errors.sessionRevoked.message",
+ "settings.billing.errors.sessionRevoked.title",
+ "settings.billing.errors.stripeUnavailable.message",
+ "settings.billing.errors.stripeUnavailable.title",
+ "settings.billing.errors.timeout.message",
+ "settings.billing.errors.timeout.title",
+ "settings.billing.errors.transport.message",
+ "settings.billing.errors.transport.title",
+ "settings.billing.errors.upgradeCapExceeded.message",
+ "settings.billing.errors.upgradeCapExceeded.title",
+ "settings.billing.freeTier.caption",
+ "settings.billing.freeTier.connectors",
+ "settings.billing.freeTier.footnote",
+ "settings.billing.freeTier.included",
+ "settings.billing.freeTier.message",
+ "settings.billing.freeTier.model",
+ "settings.billing.freeTier.name",
+ "settings.billing.freeTier.plan",
+ "settings.billing.freeTier.signIn",
+ "settings.billing.freeTier.title",
+ "settings.billing.perMonth",
+ "settings.billing.plan.alreadyOn",
+ "settings.billing.plan.backAria",
+ "settings.billing.plan.cancel",
+ "settings.billing.plan.cannotChange",
+ "settings.billing.plan.changePlan",
+ "settings.billing.plan.checkingChange",
+ "settings.billing.plan.confirmDowngrade",
+ "settings.billing.plan.current",
+ "settings.billing.plan.downgrade",
+ "settings.billing.plan.effectScheduled",
+ "settings.billing.plan.empty",
+ "settings.billing.plan.notScheduleable",
+ "settings.billing.plan.scheduled",
+ "settings.billing.plan.scheduling",
+ "settings.billing.plan.title",
+ "settings.billing.plan.tryAgain",
+ "settings.billing.plan.undo",
+ "settings.billing.plan.undoing",
+ "settings.billing.plan.viewPlans",
+ "settings.billing.preview",
+ "settings.billing.sections.invoices",
+ "settings.billing.sections.paymentAndCredits",
+ "settings.billing.sections.plan",
+ "settings.billing.sections.usage",
+ "settings.billing.state.autoRefill.chargesDescription",
+ "settings.billing.state.autoRefill.distinctCardCaption",
+ "settings.billing.state.autoRefill.distinctCardFallback",
+ "settings.billing.state.autoRefill.enabledPill",
+ "settings.billing.state.autoRefill.genericDescription",
+ "settings.billing.state.autoRefill.manageCaption",
+ "settings.billing.state.autoRefill.notAvailablePill",
+ "settings.billing.state.autoRefill.offPill",
+ "settings.billing.state.autoRefill.reconcileAction",
+ "settings.billing.state.autoRefill.title",
+ "settings.billing.state.autoRefill.turnOnCaption",
+ "settings.billing.state.buyCredits.description",
+ "settings.billing.state.notice.loggedOut.action",
+ "settings.billing.state.notice.loggedOut.message",
+ "settings.billing.state.notice.loggedOut.title",
+ "settings.billing.state.notice.noCard.action",
+ "settings.billing.state.notice.noCard.message",
+ "settings.billing.state.notice.noCard.title",
+ "settings.billing.state.notice.openPortal",
+ "settings.billing.state.paymentMethod.addAction",
+ "settings.billing.state.paymentMethod.description",
+ "settings.billing.state.paymentMethod.provenance.autoRefill",
+ "settings.billing.state.paymentMethod.provenance.customerDefault",
+ "settings.billing.state.paymentMethod.provenance.subPin",
+ "settings.billing.state.paymentMethod.provenance.suffix",
+ "settings.billing.state.paymentMethod.title",
+ "settings.billing.state.paymentMethod.updateAction",
+ "settings.billing.state.planCard.adjustPlanAction",
+ "settings.billing.state.planCard.cancellationCaption",
+ "settings.billing.state.planCard.chooseAction",
+ "settings.billing.state.planCard.downgradeCaption",
+ "settings.billing.state.planCard.freeTier",
+ "settings.billing.state.planCard.noSubscriptionCaption",
+ "settings.billing.state.planCard.renewsCaption",
+ "settings.billing.state.planCard.unavailableCaption",
+ "settings.billing.state.usage.monthlyCap.barLabel",
+ "settings.billing.state.usage.monthlyCap.captionDefault",
+ "settings.billing.state.usage.monthlyCap.captionSpending",
+ "settings.billing.state.usage.monthlyCap.title",
+ "settings.billing.state.usage.monthlyCap.valueUsed",
+ "settings.billing.state.usage.subscriptionCredits.barLabel",
+ "settings.billing.state.usage.subscriptionCredits.captionResets",
+ "settings.billing.state.usage.subscriptionCredits.title",
+ "settings.billing.state.usage.subscriptionCredits.valueOf",
+ "settings.billing.state.usage.subscriptionCredits.valueOver",
+ "settings.billing.state.usage.topupCredits.caption",
+ "settings.billing.state.usage.topupCredits.title",
+ "settings.billing.stepUp.deniedBody",
+ "settings.billing.stepUp.deniedTitle",
+ "settings.billing.stepUp.dismiss",
+ "settings.billing.stepUp.openVerification",
+ "settings.billing.stepUp.successBody",
+ "settings.billing.stepUp.successTitle",
+ "settings.billing.stepUp.verify",
+ "settings.billing.stepUp.waiting",
+ "settings.billing.summary.autoRefill",
+ "settings.billing.summary.balance",
+ "settings.billing.summary.plan",
+ "settings.billing.title",
+ "settings.billing.usage.title",
+ "settings.billing.usageLabel",
+ "settings.closeSettings",
+ "settings.computerUse.accessibility",
+ "settings.computerUse.driverHealth",
+ "settings.computerUse.screenRecording",
+ "settings.config.alwaysExternalLinksDesc",
+ "settings.config.alwaysExternalLinksTitle",
+ "settings.config.attachmentSizeDesc",
+ "settings.config.attachmentSizeLabel",
+ "settings.config.attachmentSizeTitle",
+ "settings.config.attachmentSizeUnit",
+ "settings.config.autosaveFailed",
+ "settings.config.builtinOnly",
+ "settings.config.commaSeparated",
+ "settings.config.disableF12Desc",
+ "settings.config.disableF12Title",
+ "settings.config.emptyDesc",
+ "settings.config.emptyTitle",
+ "settings.config.failedLoad",
+ "settings.config.imported",
+ "settings.config.invalidJson",
+ "settings.config.keepAwakeAlways",
+ "settings.config.keepAwakeDesc",
+ "settings.config.keepAwakeOff",
+ "settings.config.keepAwakeTitle",
+ "settings.config.keepAwakeWhileWorking",
+ "settings.config.loading",
+ "settings.config.minimizeToTrayDesc",
+ "settings.config.minimizeToTrayTitle",
+ "settings.config.minimizeToTrayUnavailable",
+ "settings.config.noResults",
+ "settings.config.none",
+ "settings.config.noneParen",
+ "settings.config.notSet",
+ "settings.config.searchPlaceholder",
+ "settings.config.showOptions",
+ "settings.config.systemDefault",
+ "settings.config.toolsetsWipeConfirm",
+ "settings.config.voiceShortcutHintDesc",
+ "settings.config.voiceShortcutHintTitle",
+ "settings.connections.addConnection",
+ "settings.connections.cancel",
+ "settings.connections.cloudAddHint",
+ "settings.connections.currentPill",
+ "settings.connections.duplicateLocal",
+ "settings.connections.duplicateSsh",
+ "settings.connections.duplicateUrl",
+ "settings.connections.editConnection",
+ "settings.connections.empty",
+ "settings.connections.headerAdd",
+ "settings.connections.headerRemove",
+ "settings.connections.headerValuePlaceholder",
+ "settings.connections.headerValueSaved",
+ "settings.connections.headersDesc",
+ "settings.connections.headersTitle",
+ "settings.connections.intro",
+ "settings.connections.kindCloud",
+ "settings.connections.kindCloudDesc",
+ "settings.connections.kindLocal",
+ "settings.connections.kindLocalDesc",
+ "settings.connections.kindRemote",
+ "settings.connections.kindRemoteDesc",
+ "settings.connections.kindSsh",
+ "settings.connections.kindSshDesc",
+ "settings.connections.labelDesc",
+ "settings.connections.labelPlaceholder",
+ "settings.connections.labelTitle",
+ "settings.connections.launchModeDesc",
+ "settings.connections.launchModeTitle",
+ "settings.connections.loadFailed",
+ "settings.connections.localAddHint",
+ "settings.connections.makePrimary",
+ "settings.connections.managedPill",
+ "settings.connections.noSearchResults",
+ "settings.connections.primaryPill",
+ "settings.connections.removeConfirmDesc",
+ "settings.connections.removeConfirmTitle",
+ "settings.connections.removeConnection",
+ "settings.connections.removeFailed",
+ "settings.connections.sameBackendHint",
+ "settings.connections.save",
+ "settings.connections.saveFailed",
+ "settings.connections.saving",
+ "settings.connections.searchPlaceholder",
+ "settings.connections.sshHostTitle",
+ "settings.connections.stagedNote",
+ "settings.connections.testConnection",
+ "settings.connections.testFailed",
+ "settings.connections.testOk",
+ "settings.connections.title",
+ "settings.connections.updateAll",
+ "settings.connections.updateAllDone",
+ "settings.connections.updateAllFailed",
+ "settings.connections.updateAllRunning",
+ "settings.connections.updateSkippedCloud",
+ "settings.connections.urlTitle",
+ "settings.credentials.couldNotSave",
+ "settings.credentials.enterValueFirst",
+ "settings.credentials.getKey",
+ "settings.credentials.optional",
+ "settings.credentials.pasteKey",
+ "settings.credentials.pasteLabelKey",
+ "settings.credentials.remove",
+ "settings.credentials.saving",
+ "settings.customEndpoints.activationFailed",
+ "settings.customEndpoints.active",
+ "settings.customEndpoints.addTitle",
+ "settings.customEndpoints.apiKeySet",
+ "settings.customEndpoints.apiMode",
+ "settings.customEndpoints.autoDetect",
+ "settings.customEndpoints.contextPlaceholder",
+ "settings.customEndpoints.couldNotLoad",
+ "settings.customEndpoints.deleteConfirm",
+ "settings.customEndpoints.deleteEndpoint",
+ "settings.customEndpoints.deleteFailed",
+ "settings.customEndpoints.editTitle",
+ "settings.customEndpoints.emptyDescription",
+ "settings.customEndpoints.emptyTitle",
+ "settings.customEndpoints.endpointReachable",
+ "settings.customEndpoints.endpointReachableModels",
+ "settings.customEndpoints.endpointReachableTransport",
+ "settings.customEndpoints.endpointSaved",
+ "settings.customEndpoints.endpointValidationFailed",
+ "settings.customEndpoints.fields.apiKey",
+ "settings.customEndpoints.fields.apiKeyNewPlaceholder",
+ "settings.customEndpoints.fields.apiKeyPlaceholder",
+ "settings.customEndpoints.fields.context",
+ "settings.customEndpoints.fields.defaultModel",
+ "settings.customEndpoints.fields.discoverModels",
+ "settings.customEndpoints.fields.endpointUrl",
+ "settings.customEndpoints.fields.name",
+ "settings.customEndpoints.fields.providerId",
+ "settings.customEndpoints.fields.useNewChats",
+ "settings.customEndpoints.namePlaceholder",
+ "settings.customEndpoints.newEndpoint",
+ "settings.customEndpoints.save",
+ "settings.customEndpoints.saveFailed",
+ "settings.customEndpoints.test",
+ "settings.customEndpoints.title",
+ "settings.customEndpoints.use",
+ "settings.customEndpoints.validationFailed",
+ "settings.envActions.actions",
+ "settings.envActions.clear",
+ "settings.envActions.docs",
+ "settings.envActions.hideValue",
+ "settings.envActions.manageInKeys",
+ "settings.envActions.replace",
+ "settings.envActions.revealValue",
+ "settings.envActions.set",
+ "settings.exportConfig",
+ "settings.exportFailed",
+ "settings.fieldDescriptions.agent.imageInputMode",
+ "settings.fieldDescriptions.agent.maxTurns",
+ "settings.fieldDescriptions.approvals.mode",
+ "settings.fieldDescriptions.approvals.timeout",
+ "settings.fieldDescriptions.auxiliary.compression.timeout",
+ "settings.fieldDescriptions.browser.useRealProfile",
+ "settings.fieldDescriptions.checkpoints.enabled",
+ "settings.fieldDescriptions.codeExecution.mode",
+ "settings.fieldDescriptions.compression.codexGpt55Autoraise",
+ "settings.fieldDescriptions.compression.enabled",
+ "settings.fieldDescriptions.context.engine",
+ "settings.fieldDescriptions.desktop.repoScanEnabled",
+ "settings.fieldDescriptions.desktop.repoScanExcludePaths",
+ "settings.fieldDescriptions.desktop.repoScanRoots",
+ "settings.fieldDescriptions.display.personality",
+ "settings.fieldDescriptions.display.showReasoning",
+ "settings.fieldDescriptions.fallbackProviders",
+ "settings.fieldDescriptions.fileReadMaxChars",
+ "settings.fieldDescriptions.memory.memoryEnabled",
+ "settings.fieldDescriptions.memory.userProfileEnabled",
+ "settings.fieldDescriptions.model",
+ "settings.fieldDescriptions.modelContextLength",
+ "settings.fieldDescriptions.security.redactSecrets",
+ "settings.fieldDescriptions.stt.echoTranscripts",
+ "settings.fieldDescriptions.stt.elevenlabs.languageCode",
+ "settings.fieldDescriptions.stt.enabled",
+ "settings.fieldDescriptions.terminal.cwd",
+ "settings.fieldDescriptions.terminal.daytonaImage",
+ "settings.fieldDescriptions.terminal.dockerImage",
+ "settings.fieldDescriptions.terminal.envPassthrough",
+ "settings.fieldDescriptions.terminal.modalImage",
+ "settings.fieldDescriptions.terminal.persistentShell",
+ "settings.fieldDescriptions.terminal.singularityImage",
+ "settings.fieldDescriptions.timezone",
+ "settings.fieldDescriptions.tts.neutts.device",
+ "settings.fieldDescriptions.tts.xai.autoSpeechTags",
+ "settings.fieldDescriptions.tts.xai.bitRate",
+ "settings.fieldDescriptions.tts.xai.language",
+ "settings.fieldDescriptions.tts.xai.optimizeStreamingLatency",
+ "settings.fieldDescriptions.tts.xai.sampleRate",
+ "settings.fieldDescriptions.tts.xai.speed",
+ "settings.fieldDescriptions.tts.xai.voiceId",
+ "settings.fieldDescriptions.updates.nonInteractiveLocalChanges",
+ "settings.fieldDescriptions.voice.autoTts",
+ "settings.fieldDescriptions.voice.gptLive.instructions",
+ "settings.fieldDescriptions.voice.gptLive.voice",
+ "settings.fieldDescriptions.voice.voiceChatMode",
+ "settings.fieldLabels.agent.apiMaxRetries",
+ "settings.fieldLabels.agent.imageInputMode",
+ "settings.fieldLabels.agent.maxTurns",
+ "settings.fieldLabels.agent.serviceTier",
+ "settings.fieldLabels.agent.toolUseEnforcement",
+ "settings.fieldLabels.approvals.mcpReloadConfirm",
+ "settings.fieldLabels.approvals.mode",
+ "settings.fieldLabels.approvals.timeout",
+ "settings.fieldLabels.auxiliary.compression.timeout",
+ "settings.fieldLabels.browser.allowPrivateUrls",
+ "settings.fieldLabels.browser.autoLocalForPrivateUrls",
+ "settings.fieldLabels.browser.useRealProfile",
+ "settings.fieldLabels.checkpoints.enabled",
+ "settings.fieldLabels.checkpoints.maxSnapshots",
+ "settings.fieldLabels.codeExecution.mode",
+ "settings.fieldLabels.commandAllowlist",
+ "settings.fieldLabels.compression.codexGpt55Autoraise",
+ "settings.fieldLabels.compression.enabled",
+ "settings.fieldLabels.compression.protectLastN",
+ "settings.fieldLabels.compression.targetRatio",
+ "settings.fieldLabels.compression.threshold",
+ "settings.fieldLabels.context.engine",
+ "settings.fieldLabels.delegation.childTimeoutSeconds",
+ "settings.fieldLabels.delegation.maxConcurrentChildren",
+ "settings.fieldLabels.delegation.maxIterations",
+ "settings.fieldLabels.delegation.model",
+ "settings.fieldLabels.delegation.provider",
+ "settings.fieldLabels.delegation.reasoningEffort",
+ "settings.fieldLabels.desktop.repoScanEnabled",
+ "settings.fieldLabels.desktop.repoScanExcludePaths",
+ "settings.fieldLabels.desktop.repoScanRoots",
+ "settings.fieldLabels.display.personality",
+ "settings.fieldLabels.display.showReasoning",
+ "settings.fieldLabels.fallbackProviders",
+ "settings.fieldLabels.fileReadMaxChars",
+ "settings.fieldLabels.memory.memoryCharLimit",
+ "settings.fieldLabels.memory.memoryEnabled",
+ "settings.fieldLabels.memory.provider",
+ "settings.fieldLabels.memory.userCharLimit",
+ "settings.fieldLabels.memory.userProfileEnabled",
+ "settings.fieldLabels.model",
+ "settings.fieldLabels.modelContextLength",
+ "settings.fieldLabels.security.allowPrivateUrls",
+ "settings.fieldLabels.security.redactSecrets",
+ "settings.fieldLabels.stt.echoTranscripts",
+ "settings.fieldLabels.stt.elevenlabs.diarize",
+ "settings.fieldLabels.stt.elevenlabs.languageCode",
+ "settings.fieldLabels.stt.elevenlabs.modelId",
+ "settings.fieldLabels.stt.elevenlabs.tagAudioEvents",
+ "settings.fieldLabels.stt.enabled",
+ "settings.fieldLabels.stt.groq.model",
+ "settings.fieldLabels.stt.local.language",
+ "settings.fieldLabels.stt.local.model",
+ "settings.fieldLabels.stt.mistral.model",
+ "settings.fieldLabels.stt.openai.model",
+ "settings.fieldLabels.stt.provider",
+ "settings.fieldLabels.terminal.backend",
+ "settings.fieldLabels.terminal.cwd",
+ "settings.fieldLabels.terminal.daytonaImage",
+ "settings.fieldLabels.terminal.dockerImage",
+ "settings.fieldLabels.terminal.envPassthrough",
+ "settings.fieldLabels.terminal.modalImage",
+ "settings.fieldLabels.terminal.persistentShell",
+ "settings.fieldLabels.terminal.singularityImage",
+ "settings.fieldLabels.terminal.timeout",
+ "settings.fieldLabels.timezone",
+ "settings.fieldLabels.toolOutput.maxBytes",
+ "settings.fieldLabels.toolOutput.maxLineLength",
+ "settings.fieldLabels.toolOutput.maxLines",
+ "settings.fieldLabels.toolsets",
+ "settings.fieldLabels.tts.deepinfra.model",
+ "settings.fieldLabels.tts.deepinfra.voice",
+ "settings.fieldLabels.tts.edge.voice",
+ "settings.fieldLabels.tts.elevenlabs.modelId",
+ "settings.fieldLabels.tts.elevenlabs.voiceId",
+ "settings.fieldLabels.tts.gemini.model",
+ "settings.fieldLabels.tts.gemini.voice",
+ "settings.fieldLabels.tts.kittentts.model",
+ "settings.fieldLabels.tts.kittentts.voice",
+ "settings.fieldLabels.tts.minimax.model",
+ "settings.fieldLabels.tts.minimax.voiceId",
+ "settings.fieldLabels.tts.mistral.model",
+ "settings.fieldLabels.tts.mistral.voiceId",
+ "settings.fieldLabels.tts.neutts.device",
+ "settings.fieldLabels.tts.neutts.model",
+ "settings.fieldLabels.tts.openai.model",
+ "settings.fieldLabels.tts.openai.voice",
+ "settings.fieldLabels.tts.piper.voice",
+ "settings.fieldLabels.tts.provider",
+ "settings.fieldLabels.tts.xai.autoSpeechTags",
+ "settings.fieldLabels.tts.xai.bitRate",
+ "settings.fieldLabels.tts.xai.language",
+ "settings.fieldLabels.tts.xai.optimizeStreamingLatency",
+ "settings.fieldLabels.tts.xai.sampleRate",
+ "settings.fieldLabels.tts.xai.speed",
+ "settings.fieldLabels.tts.xai.voiceId",
+ "settings.fieldLabels.updates.nonInteractiveLocalChanges",
+ "settings.fieldLabels.voice.autoTts",
+ "settings.fieldLabels.voice.gptLive.instructions",
+ "settings.fieldLabels.voice.gptLive.voice",
+ "settings.fieldLabels.voice.maxRecordingSeconds",
+ "settings.fieldLabels.voice.voiceChatMode",
+ "settings.gateway.applyFailed",
+ "settings.gateway.authNeedsOauth",
+ "settings.gateway.authNeedsPassword",
+ "settings.gateway.authSignedInOauth",
+ "settings.gateway.authSignedInPassword",
+ "settings.gateway.authTitle",
+ "settings.gateway.cloudActive",
+ "settings.gateway.cloudAgentProvisioning",
+ "settings.gateway.cloudAgentsTitle",
+ "settings.gateway.cloudConnect",
+ "settings.gateway.cloudConnectFailed",
+ "settings.gateway.cloudConnectedPill",
+ "settings.gateway.cloudConnectedTitle",
+ "settings.gateway.cloudConnectedTo",
+ "settings.gateway.cloudConnecting",
+ "settings.gateway.cloudDesc",
+ "settings.gateway.cloudDiscoverFailed",
+ "settings.gateway.cloudLoadingAgents",
+ "settings.gateway.cloudNeedsSignIn",
+ "settings.gateway.cloudNoAgents.after",
+ "settings.gateway.cloudNoAgents.before",
+ "settings.gateway.cloudNoAgents.linkText",
+ "settings.gateway.cloudOrgChange",
+ "settings.gateway.cloudOrgPickerTitle",
+ "settings.gateway.cloudOrgRole",
+ "settings.gateway.cloudOrgSelect",
+ "settings.gateway.cloudRefresh",
+ "settings.gateway.cloudSavedDesc",
+ "settings.gateway.cloudSavedTitle",
+ "settings.gateway.cloudSignIn",
+ "settings.gateway.cloudSignInFailed",
+ "settings.gateway.cloudSignInTitle",
+ "settings.gateway.cloudSignedIn",
+ "settings.gateway.cloudSignedInDesc",
+ "settings.gateway.cloudSignedOutMessage",
+ "settings.gateway.cloudSignedOutTitle",
+ "settings.gateway.cloudStatusLabel",
+ "settings.gateway.cloudTitle",
+ "settings.gateway.cloudUseSaved",
+ "settings.gateway.connectedTo",
+ "settings.gateway.diagnostics",
+ "settings.gateway.diagnosticsDesc",
+ "settings.gateway.enterUrlFirst",
+ "settings.gateway.envOverride",
+ "settings.gateway.envOverrideDesc",
+ "settings.gateway.envOverrideTitle",
+ "settings.gateway.existingToken",
+ "settings.gateway.failedLoad",
+ "settings.gateway.incompleteSignIn",
+ "settings.gateway.incompleteSignInTest",
+ "settings.gateway.incompleteTitle",
+ "settings.gateway.incompleteToken",
+ "settings.gateway.incompleteTokenTest",
+ "settings.gateway.intro",
+ "settings.gateway.keychainEncryptionDesc",
+ "settings.gateway.keychainEncryptionFailed",
+ "settings.gateway.keychainEncryptionTitle",
+ "settings.gateway.loading",
+ "settings.gateway.localDesc",
+ "settings.gateway.localTitle",
+ "settings.gateway.modeTitle",
+ "settings.gateway.openLogs",
+ "settings.gateway.pasteSessionToken",
+ "settings.gateway.plainTextConfirmAction",
+ "settings.gateway.plainTextConfirmDesc",
+ "settings.gateway.plainTextConfirmTitle",
+ "settings.gateway.plainTextStoredDesc",
+ "settings.gateway.plainTextStoredTitle",
+ "settings.gateway.probeError",
+ "settings.gateway.probing",
+ "settings.gateway.reachableTitle",
+ "settings.gateway.remoteAuthHint",
+ "settings.gateway.remoteDesc",
+ "settings.gateway.remoteTitle",
+ "settings.gateway.remoteUrlDesc",
+ "settings.gateway.remoteUrlTitle",
+ "settings.gateway.restartingMessage",
+ "settings.gateway.restartingTitle",
+ "settings.gateway.saveAndReconnect",
+ "settings.gateway.saveFailed",
+ "settings.gateway.saveForRestart",
+ "settings.gateway.savedMessage",
+ "settings.gateway.savedTitle",
+ "settings.gateway.savedToken",
+ "settings.gateway.signIn",
+ "settings.gateway.signInFailed",
+ "settings.gateway.signInWith",
+ "settings.gateway.signOut",
+ "settings.gateway.signOutFailed",
+ "settings.gateway.signedIn",
+ "settings.gateway.signedOutMessage",
+ "settings.gateway.signedOutTitle",
+ "settings.gateway.sshButtonsHint",
+ "settings.gateway.sshConnect",
+ "settings.gateway.sshDesc",
+ "settings.gateway.sshErrAuth",
+ "settings.gateway.sshErrHostKey",
+ "settings.gateway.sshErrInteractiveAuth",
+ "settings.gateway.sshErrNotInstalled",
+ "settings.gateway.sshErrPlatform",
+ "settings.gateway.sshErrTimeout",
+ "settings.gateway.sshErrUnknown",
+ "settings.gateway.sshErrUnreachable",
+ "settings.gateway.sshErrUpdateRequired",
+ "settings.gateway.sshHermesPathDesc",
+ "settings.gateway.sshHermesPathPlaceholder",
+ "settings.gateway.sshHermesPathTitle",
+ "settings.gateway.sshHostCustom",
+ "settings.gateway.sshHostDesc",
+ "settings.gateway.sshHostPick",
+ "settings.gateway.sshHostPickDesc",
+ "settings.gateway.sshHostPickTitle",
+ "settings.gateway.sshHostTitle",
+ "settings.gateway.sshIncompleteHost",
+ "settings.gateway.sshKeyDesc",
+ "settings.gateway.sshKeyTitle",
+ "settings.gateway.sshPortDesc",
+ "settings.gateway.sshPortTitle",
+ "settings.gateway.sshReachable",
+ "settings.gateway.sshTestConnection",
+ "settings.gateway.sshTitle",
+ "settings.gateway.sshTrustHint",
+ "settings.gateway.sshUserDesc",
+ "settings.gateway.sshUserPlaceholder",
+ "settings.gateway.sshUserTitle",
+ "settings.gateway.testFailed",
+ "settings.gateway.testRemote",
+ "settings.gateway.title",
+ "settings.gateway.tokenDesc",
+ "settings.gateway.tokenTitle",
+ "settings.gateway.unavailableDesc",
+ "settings.gateway.unavailableTitle",
+ "settings.hudModifier.description",
+ "settings.hudModifier.missingHelper",
+ "settings.hudModifier.permission",
+ "settings.hudModifier.title",
+ "settings.hudModifier.unavailable",
+ "settings.hudModifier.unsupportedSession",
+ "settings.importConfig",
+ "settings.keys.empty",
+ "settings.keys.failedLoad",
+ "settings.keys.loading",
+ "settings.localModels.activateDoneToast",
+ "settings.localModels.activateFailed",
+ "settings.localModels.activating",
+ "settings.localModels.activeDetail",
+ "settings.localModels.activeNotLoaded",
+ "settings.localModels.activePill",
+ "settings.localModels.addedByYou",
+ "settings.localModels.browseAlreadyDownloaded",
+ "settings.localModels.browseDownloadAria",
+ "settings.localModels.browseDownloadStarted",
+ "settings.localModels.browseDownloads",
+ "settings.localModels.browseFitUnknown",
+ "settings.localModels.browseGated",
+ "settings.localModels.browseHint",
+ "settings.localModels.browseLikes",
+ "settings.localModels.browseListing",
+ "settings.localModels.browseNoGguf",
+ "settings.localModels.browsePlaceholder",
+ "settings.localModels.browseRefresh",
+ "settings.localModels.browseSearching",
+ "settings.localModels.browseShowFiles",
+ "settings.localModels.browseTitle",
+ "settings.localModels.connectionChanged",
+ "settings.localModels.deleteAction",
+ "settings.localModels.deleteConfirm",
+ "settings.localModels.deleteFailed",
+ "settings.localModels.deleted",
+ "settings.localModels.downloadAction",
+ "settings.localModels.downloadDoneToast",
+ "settings.localModels.downloadEta",
+ "settings.localModels.downloadEtaHours",
+ "settings.localModels.downloadEtaMinutes",
+ "settings.localModels.downloadEtaSeconds",
+ "settings.localModels.downloadFailed",
+ "settings.localModels.downloadPauseAction",
+ "settings.localModels.downloadPauseFailed",
+ "settings.localModels.downloadPausedLabel",
+ "settings.localModels.downloadProgress",
+ "settings.localModels.downloadResumeAction",
+ "settings.localModels.downloadResumeFailed",
+ "settings.localModels.downloadSpeed",
+ "settings.localModels.downloadStatusRunning",
+ "settings.localModels.downloaded",
+ "settings.localModels.ejectFailed",
+ "settings.localModels.ejectTip",
+ "settings.localModels.ejected",
+ "settings.localModels.hardwareLoading",
+ "settings.localModels.hardwareTitle",
+ "settings.localModels.installAction",
+ "settings.localModels.installDetail",
+ "settings.localModels.installDoneToast",
+ "settings.localModels.installFailed",
+ "settings.localModels.installTitle",
+ "settings.localModels.installing",
+ "settings.localModels.loadedPill",
+ "settings.localModels.loadingPill",
+ "settings.localModels.modelsTitle",
+ "settings.localModels.noRecommendationAction",
+ "settings.localModels.noRecommendationDetail",
+ "settings.localModels.noRecommendationTitle",
+ "settings.localModels.pillFitsGpu",
+ "settings.localModels.pillFullContext",
+ "settings.localModels.pillFullContextTip",
+ "settings.localModels.pillGrowsTip",
+ "settings.localModels.pillTooBig",
+ "settings.localModels.pillUpTo",
+ "settings.localModels.pillUsesRam",
+ "settings.localModels.pillVision",
+ "settings.localModels.placementResident",
+ "settings.localModels.placementResidentTip",
+ "settings.localModels.placementSpilled",
+ "settings.localModels.placementSpilledTip",
+ "settings.localModels.quickstartAction",
+ "settings.localModels.quickstartConfigure",
+ "settings.localModels.quickstartDetail",
+ "settings.localModels.quickstartDetailReady",
+ "settings.localModels.quickstartDoneToast",
+ "settings.localModels.quickstartFailed",
+ "settings.localModels.quickstartStageEngine",
+ "settings.localModels.quickstartStageFinish",
+ "settings.localModels.quickstartStageModel",
+ "settings.localModels.quickstartTitle",
+ "settings.localModels.ram",
+ "settings.localModels.recommended",
+ "settings.localModels.recommendedReason.best-quality-resident",
+ "settings.localModels.recommendedReason.fastest-resident",
+ "settings.localModels.recommendedReason.speed-gated-quality",
+ "settings.localModels.runtimeInstalled",
+ "settings.localModels.runtimeInstalledDetail",
+ "settings.localModels.runtimeReady",
+ "settings.localModels.runtimeRunningDetail",
+ "settings.localModels.runtimeTitle",
+ "settings.localModels.serverRunning",
+ "settings.localModels.serverStartFailed",
+ "settings.localModels.serverStarted",
+ "settings.localModels.serverStopFailed",
+ "settings.localModels.serverStopped",
+ "settings.localModels.sideloadAlreadyPresent",
+ "settings.localModels.sideloadButton",
+ "settings.localModels.sideloadDone",
+ "settings.localModels.sideloadTitle",
+ "settings.localModels.startServer",
+ "settings.localModels.stopServer",
+ "settings.localModels.title",
+ "settings.localModels.unifiedMemory",
+ "settings.localModels.upToDateDetail",
+ "settings.localModels.upToDateTitle",
+ "settings.localModels.updateAction",
+ "settings.localModels.updateDetail",
+ "settings.localModels.updateTitle",
+ "settings.localModels.updating",
+ "settings.localModels.useAction",
+ "settings.localModels.vram",
+ "settings.managedUpdates.alreadyRunning",
+ "settings.managedUpdates.failed",
+ "settings.managedUpdates.intro",
+ "settings.managedUpdates.partial",
+ "settings.managedUpdates.progress",
+ "settings.managedUpdates.receipt",
+ "settings.managedUpdates.receiptVersions",
+ "settings.managedUpdates.refused",
+ "settings.managedUpdates.scopeNotRestored",
+ "settings.managedUpdates.scopesRestored",
+ "settings.managedUpdates.sshConnection",
+ "settings.managedUpdates.title",
+ "settings.managedUpdates.update",
+ "settings.managedUpdates.updated",
+ "settings.managedUpdates.updating",
+ "settings.mcp.allServers",
+ "settings.mcp.authenticate",
+ "settings.mcp.authenticatedMessage",
+ "settings.mcp.authenticatedTitle",
+ "settings.mcp.capabilitySummary",
+ "settings.mcp.catalogEnvRequired",
+ "settings.mcp.catalogInstallFailed",
+ "settings.mcp.catalogLoading",
+ "settings.mcp.costTokens",
+ "settings.mcp.deepLinkConfirm",
+ "settings.mcp.deepLinkDescription",
+ "settings.mcp.deepLinkErrorConfig",
+ "settings.mcp.deepLinkErrorName",
+ "settings.mcp.deepLinkErrorShape",
+ "settings.mcp.deepLinkErrorTitle",
+ "settings.mcp.deepLinkErrorTooLarge",
+ "settings.mcp.deepLinkErrorUrl",
+ "settings.mcp.deepLinkNameConflict",
+ "settings.mcp.deepLinkNameInvalid",
+ "settings.mcp.deepLinkStdioWarning",
+ "settings.mcp.deepLinkTitle",
+ "settings.mcp.disabled",
+ "settings.mcp.invalidJson",
+ "settings.mcp.loading",
+ "settings.mcp.name",
+ "settings.mcp.noOutput",
+ "settings.mcp.reloadFailed",
+ "settings.mcp.remove",
+ "settings.mcp.removeFailed",
+ "settings.mcp.saveFailed",
+ "settings.mcp.savedMessage",
+ "settings.mcp.savedTitle",
+ "settings.mcp.serverJson",
+ "settings.mcp.statusConnecting",
+ "settings.mcp.statusError",
+ "settings.mcp.statusNeedsAuth",
+ "settings.mcp.statusOff",
+ "settings.mcp.test",
+ "settings.mcp.usage30d",
+ "settings.modeOptions.dark.description",
+ "settings.modeOptions.dark.label",
+ "settings.modeOptions.light.description",
+ "settings.modeOptions.light.label",
+ "settings.modeOptions.system.description",
+ "settings.modeOptions.system.label",
+ "settings.model.appliesDesc",
+ "settings.model.applying",
+ "settings.model.autoUseMain",
+ "settings.model.auxiliaryDesc",
+ "settings.model.auxiliaryTitle",
+ "settings.model.change",
+ "settings.model.chooseFromList",
+ "settings.model.customModel",
+ "settings.model.customModelPlaceholder",
+ "settings.model.defaultsFailed",
+ "settings.model.defaultsLabel",
+ "settings.model.fallbackAdd",
+ "settings.model.fallbackEmpty",
+ "settings.model.followTask",
+ "settings.model.inheritMainEffort",
+ "settings.model.inheritsFrom",
+ "settings.model.loadFailed",
+ "settings.model.loading",
+ "settings.model.mainAppliedMessage",
+ "settings.model.mainAppliedTitle",
+ "settings.model.moaAddPreset",
+ "settings.model.moaAddReference",
+ "settings.model.moaAggregator",
+ "settings.model.moaAggregatorBilled",
+ "settings.model.moaDefault",
+ "settings.model.moaDescription",
+ "settings.model.moaEnabled",
+ "settings.model.moaNewPresetPlaceholder",
+ "settings.model.moaPreset",
+ "settings.model.moaReferenceHint",
+ "settings.model.moaReferenceTitle",
+ "settings.model.moaReferenceToggle",
+ "settings.model.moaSetDefault",
+ "settings.model.moaTitle",
+ "settings.model.model",
+ "settings.model.notInCatalog",
+ "settings.model.provider",
+ "settings.model.providerDefault",
+ "settings.model.reasoning",
+ "settings.model.reasoningOff",
+ "settings.model.resetAllToMain",
+ "settings.model.restartBackend",
+ "settings.model.restartFailed",
+ "settings.model.restartRequired",
+ "settings.model.restartingBackend",
+ "settings.model.setToMain",
+ "settings.model.setUpProvider",
+ "settings.model.setupProviderFallback",
+ "settings.model.speed",
+ "settings.model.speedStandard",
+ "settings.model.staleAuxAfter",
+ "settings.model.staleAuxBefore",
+ "settings.model.staleAuxDismiss",
+ "settings.model.staleAuxOtherProviders",
+ "settings.model.tasks.approval.hint",
+ "settings.model.tasks.approval.label",
+ "settings.model.tasks.compression.hint",
+ "settings.model.tasks.compression.label",
+ "settings.model.tasks.curator.hint",
+ "settings.model.tasks.curator.label",
+ "settings.model.tasks.kanban_decomposer.hint",
+ "settings.model.tasks.kanban_decomposer.label",
+ "settings.model.tasks.mcp.hint",
+ "settings.model.tasks.mcp.label",
+ "settings.model.tasks.profile_describer.hint",
+ "settings.model.tasks.profile_describer.label",
+ "settings.model.tasks.review.hint",
+ "settings.model.tasks.review.label",
+ "settings.model.tasks.skills_hub.hint",
+ "settings.model.tasks.skills_hub.label",
+ "settings.model.tasks.title_generation.hint",
+ "settings.model.tasks.title_generation.label",
+ "settings.model.tasks.triage_specifier.hint",
+ "settings.model.tasks.triage_specifier.label",
+ "settings.model.tasks.vision.hint",
+ "settings.model.tasks.vision.label",
+ "settings.nav.about",
+ "settings.nav.apiKeys",
+ "settings.nav.archivedChats",
+ "settings.nav.billing",
+ "settings.nav.gateway",
+ "settings.nav.keybinds",
+ "settings.nav.keysSettings",
+ "settings.nav.keysTools",
+ "settings.nav.mcp",
+ "settings.nav.notifications",
+ "settings.nav.plugins",
+ "settings.nav.providerAccounts",
+ "settings.nav.providerApiKeys",
+ "settings.nav.providerCustomEndpoints",
+ "settings.nav.providerLocalModels",
+ "settings.nav.providers",
+ "settings.nav.sessions",
+ "settings.nav.vault",
+ "settings.notifications.completionSoundDesc",
+ "settings.notifications.completionSoundPreview",
+ "settings.notifications.completionSoundTitle",
+ "settings.notifications.enableAll",
+ "settings.notifications.enableAllDesc",
+ "settings.notifications.focusedHint",
+ "settings.notifications.intro",
+ "settings.notifications.kinds.approval.description",
+ "settings.notifications.kinds.approval.label",
+ "settings.notifications.kinds.backgroundDone.description",
+ "settings.notifications.kinds.backgroundDone.label",
+ "settings.notifications.kinds.credits.description",
+ "settings.notifications.kinds.credits.label",
+ "settings.notifications.kinds.input.description",
+ "settings.notifications.kinds.input.label",
+ "settings.notifications.kinds.plugin.description",
+ "settings.notifications.kinds.plugin.label",
+ "settings.notifications.kinds.turnDone.description",
+ "settings.notifications.kinds.turnDone.label",
+ "settings.notifications.kinds.turnError.description",
+ "settings.notifications.kinds.turnError.label",
+ "settings.notifications.test",
+ "settings.notifications.testBody",
+ "settings.notifications.testSent",
+ "settings.notifications.testTitle",
+ "settings.notifications.testUnsupported",
+ "settings.notifications.title",
+ "settings.pluginPages.agentSettings",
+ "settings.pluginPages.blurb",
+ "settings.pluginPages.empty",
+ "settings.pluginPages.manage",
+ "settings.pluginPages.missing",
+ "settings.pluginPages.pageCount",
+ "settings.plugins.failed",
+ "settings.plugins.installModal.agentFailed",
+ "settings.plugins.installModal.agentLabel",
+ "settings.plugins.installModal.agentSuccess",
+ "settings.plugins.installModal.agentTargetLocal",
+ "settings.plugins.installModal.agentTargetRemote",
+ "settings.plugins.installModal.alreadyInstalled",
+ "settings.plugins.installModal.catalogPinned",
+ "settings.plugins.installModal.description",
+ "settings.plugins.installModal.desktopFailed",
+ "settings.plugins.installModal.desktopLabel",
+ "settings.plugins.installModal.desktopOnlyNote",
+ "settings.plugins.installModal.desktopSuccess",
+ "settings.plugins.installModal.desktopTarget",
+ "settings.plugins.installModal.desktopTargetFromPackage",
+ "settings.plugins.installModal.desktopUnavailable",
+ "settings.plugins.installModal.enableAgent",
+ "settings.plugins.installModal.forceReinstall",
+ "settings.plugins.installModal.gitCloneLabel",
+ "settings.plugins.installModal.includesHeading",
+ "settings.plugins.installModal.insecureWarning",
+ "settings.plugins.installModal.install",
+ "settings.plugins.installModal.installFromGit",
+ "settings.plugins.installModal.installUncertain",
+ "settings.plugins.installModal.installing",
+ "settings.plugins.installModal.missingEnv",
+ "settings.plugins.installModal.missingEnvAction",
+ "settings.plugins.installModal.nextChat",
+ "settings.plugins.installModal.pinToCommit",
+ "settings.plugins.installModal.pinToCommitHint",
+ "settings.plugins.installModal.pinToCommitInvalid",
+ "settings.plugins.installModal.pinToCommitPlaceholder",
+ "settings.plugins.installModal.probeUnavailable",
+ "settings.plugins.installModal.probing",
+ "settings.plugins.installModal.profileLabel",
+ "settings.plugins.installModal.repoLabel",
+ "settings.plugins.installModal.repoPlaceholder",
+ "settings.plugins.installModal.reviewRepository",
+ "settings.plugins.installModal.reviewedHeading",
+ "settings.plugins.installModal.reviewedIntro",
+ "settings.plugins.installModal.securityHeading",
+ "settings.plugins.installModal.securityIntro",
+ "settings.plugins.installModal.selectComponent",
+ "settings.plugins.installModal.serverNotConnected",
+ "settings.plugins.installModal.skillsReady",
+ "settings.plugins.installModal.sourceHeading",
+ "settings.plugins.installModal.title",
+ "settings.plugins.installModal.toolsConnected",
+ "settings.plugins.installModal.viewPluginFiles",
+ "settings.plugins.installModal.viewRepository",
+ "settings.plugins.kinds.bundled",
+ "settings.plugins.kinds.disk",
+ "settings.plugins.kinds.runtime",
+ "settings.plugins.openFolder",
+ "settings.plugins.rescan",
+ "settings.plugins.reveal",
+ "settings.plugins.title",
+ "settings.poolLimits.backendIdleTimeoutAria",
+ "settings.poolLimits.backendIdleTimeoutTitle",
+ "settings.poolLimits.warmBotBackendsAria",
+ "settings.poolLimits.warmBotBackendsTitle",
+ "settings.profileScope.appliesTo",
+ "settings.profileScope.editsProfile",
+ "settings.providers.collapse",
+ "settings.providers.connectAccount",
+ "settings.providers.connectAnother",
+ "settings.providers.connected",
+ "settings.providers.disconnect",
+ "settings.providers.disconnectInTerminal",
+ "settings.providers.failedRemove",
+ "settings.providers.haveApiKey",
+ "settings.providers.intro",
+ "settings.providers.loading",
+ "settings.providers.localEndpoint.description",
+ "settings.providers.localEndpoint.title",
+ "settings.providers.noKeysMatch",
+ "settings.providers.noProviderKeys",
+ "settings.providers.otherProviders",
+ "settings.providers.removeConfirm",
+ "settings.providers.removeExternalGeneric",
+ "settings.providers.removeKeyManaged",
+ "settings.providers.removeTerminalConfirm",
+ "settings.providers.removeTerminalRunning",
+ "settings.providers.removedMessage",
+ "settings.providers.removedTitle",
+ "settings.providers.searchKeys",
+ "settings.quickEntry.active",
+ "settings.quickEntry.enabledDesc",
+ "settings.quickEntry.enabledTitle",
+ "settings.quickEntry.invalidShortcut",
+ "settings.quickEntry.shortcutDesc",
+ "settings.quickEntry.shortcutTitle",
+ "settings.quickEntry.takenBy",
+ "settings.resetConfirm",
+ "settings.resetFailed",
+ "settings.resetToDefaults",
+ "settings.screenshot.captureFailed",
+ "settings.screenshot.checking",
+ "settings.screenshot.contextChanged",
+ "settings.screenshot.disabled",
+ "settings.screenshot.enabledDesc",
+ "settings.screenshot.enabledTitle",
+ "settings.screenshot.errorTitle",
+ "settings.screenshot.inputPermission",
+ "settings.screenshot.loadFailed",
+ "settings.screenshot.openSettings",
+ "settings.screenshot.permissionFailed",
+ "settings.screenshot.ready",
+ "settings.screenshot.retry",
+ "settings.screenshot.saveFailed",
+ "settings.screenshot.screenPermission",
+ "settings.screenshot.starting",
+ "settings.screenshot.statusTitle",
+ "settings.screenshot.unavailable",
+ "settings.search.pill",
+ "settings.search.placeholder",
+ "settings.searchPlaceholder.about",
+ "settings.searchPlaceholder.config",
+ "settings.searchPlaceholder.gateway",
+ "settings.searchPlaceholder.keys",
+ "settings.searchPlaceholder.mcp",
+ "settings.searchPlaceholder.sessions",
+ "settings.sections.advanced",
+ "settings.sections.appearance",
+ "settings.sections.chat",
+ "settings.sections.memory",
+ "settings.sections.model",
+ "settings.sections.safety",
+ "settings.sections.voice",
+ "settings.sections.workspace",
+ "settings.sessions.archivedIntro",
+ "settings.sessions.archivedTitle",
+ "settings.sessions.autoArchiveDaysLabel",
+ "settings.sessions.autoArchiveDaysUnit",
+ "settings.sessions.autoArchiveDesc",
+ "settings.sessions.autoArchiveFailed",
+ "settings.sessions.autoArchiveTitle",
+ "settings.sessions.change",
+ "settings.sessions.choose",
+ "settings.sessions.clear",
+ "settings.sessions.clearDirFailed",
+ "settings.sessions.defaultDirDesc",
+ "settings.sessions.defaultDirTitle",
+ "settings.sessions.defaultDirUpdated",
+ "settings.sessions.defaultsTo",
+ "settings.sessions.deleteConfirm",
+ "settings.sessions.deleteFailed",
+ "settings.sessions.deletePermanently",
+ "settings.sessions.emptyArchivedDesc",
+ "settings.sessions.emptyArchivedTitle",
+ "settings.sessions.failedLoad",
+ "settings.sessions.loading",
+ "settings.sessions.messages",
+ "settings.sessions.notSet",
+ "settings.sessions.restored",
+ "settings.sessions.unarchive",
+ "settings.sessions.unarchiveFailed",
+ "settings.sessions.updateDirFailed",
+ "settings.subpages.advancedDelegation",
+ "settings.subpages.advancedDesktop",
+ "settings.subpages.advancedOutput",
+ "settings.subpages.advancedRuntime",
+ "settings.subpages.advancedTerminal",
+ "settings.subpages.advancedTools",
+ "settings.subpages.appUpdates",
+ "settings.subpages.appearanceChatDisplay",
+ "settings.subpages.appearanceGeneral",
+ "settings.subpages.appearancePet",
+ "settings.subpages.appearanceTheme",
+ "settings.subpages.appearanceTypography",
+ "settings.subpages.appearanceWindowLayout",
+ "settings.subpages.archivedSessions",
+ "settings.subpages.billingOverview",
+ "settings.subpages.billingPlans",
+ "settings.subpages.browserNetwork",
+ "settings.subpages.browserProfile",
+ "settings.subpages.chatAttachments",
+ "settings.subpages.chatBehavior",
+ "settings.subpages.defaultDirectory",
+ "settings.subpages.gatewayConnection",
+ "settings.subpages.gatewayDevices",
+ "settings.subpages.gatewayManagedUpdates",
+ "settings.subpages.gatewayManagedUpdatesEmpty",
+ "settings.subpages.gatewayManagedUpdatesUnavailable",
+ "settings.subpages.hudGesture",
+ "settings.subpages.keyboardShortcuts",
+ "settings.subpages.memoryContext",
+ "settings.subpages.memoryPersistent",
+ "settings.subpages.modelAuxiliary",
+ "settings.subpages.modelFallbacks",
+ "settings.subpages.modelMain",
+ "settings.subpages.modelMoa",
+ "settings.subpages.notificationAlerts",
+ "settings.subpages.notificationSounds",
+ "settings.subpages.safetyApprovals",
+ "settings.subpages.safetyCheckpoints",
+ "settings.subpages.safetyPrivacy",
+ "settings.subpages.screenCapture",
+ "settings.subpages.uninstall",
+ "settings.subpages.vaultCredentials",
+ "settings.subpages.vaultSources",
+ "settings.subpages.voiceConversation",
+ "settings.subpages.voiceSpeech",
+ "settings.subpages.voiceTranscription",
+ "settings.subpages.workspaceFiles",
+ "settings.subpages.workspaceProjects",
+ "settings.subpages.workspaceShell",
+ "settings.toolsets.activeBackend",
+ "settings.toolsets.activeBackendHint",
+ "settings.toolsets.browserRealProfile.description",
+ "settings.toolsets.browserRealProfile.disabledMessage",
+ "settings.toolsets.browserRealProfile.disabledTitle",
+ "settings.toolsets.browserRealProfile.enabledMessage",
+ "settings.toolsets.browserRealProfile.enabledTitle",
+ "settings.toolsets.browserRealProfile.failedSave",
+ "settings.toolsets.browserRealProfile.label",
+ "settings.toolsets.browserRealProfile.prompt.body",
+ "settings.toolsets.browserRealProfile.prompt.bulletLiveProfile",
+ "settings.toolsets.browserRealProfile.prompt.bulletLocal",
+ "settings.toolsets.browserRealProfile.prompt.bulletSnapshot",
+ "settings.toolsets.browserRealProfile.prompt.dontShowAgain",
+ "settings.toolsets.browserRealProfile.prompt.enable",
+ "settings.toolsets.browserRealProfile.prompt.notNow",
+ "settings.toolsets.browserRealProfile.prompt.title",
+ "settings.toolsets.failedLoad",
+ "settings.toolsets.failedRemove",
+ "settings.toolsets.failedReveal",
+ "settings.toolsets.failedSave",
+ "settings.toolsets.failedSelect",
+ "settings.toolsets.failedSelectCapability",
+ "settings.toolsets.failedSelectModel",
+ "settings.toolsets.loadingConfig",
+ "settings.toolsets.loadingModels",
+ "settings.toolsets.modelCount",
+ "settings.toolsets.modelDefault",
+ "settings.toolsets.modelInUse",
+ "settings.toolsets.modelInactiveHint",
+ "settings.toolsets.modelSectionTitle",
+ "settings.toolsets.modelSelectedMessage",
+ "settings.toolsets.modelSelectedTitle",
+ "settings.toolsets.needsSetup",
+ "settings.toolsets.needsSignIn",
+ "settings.toolsets.noApiKeyRequired",
+ "settings.toolsets.noProviderOptions",
+ "settings.toolsets.noProviders",
+ "settings.toolsets.notSet",
+ "settings.toolsets.nousAuthDoneMessage",
+ "settings.toolsets.nousAuthDoneTitle",
+ "settings.toolsets.nousAuthFailed",
+ "settings.toolsets.nousAuthFailedMessage",
+ "settings.toolsets.nousAuthNeededMessage",
+ "settings.toolsets.nousAuthNeededTitle",
+ "settings.toolsets.nousAuthSignIn",
+ "settings.toolsets.nousAuthTryAgain",
+ "settings.toolsets.nousIncluded",
+ "settings.toolsets.postSetupCompleteMessage",
+ "settings.toolsets.postSetupCompleteTitle",
+ "settings.toolsets.postSetupErrorMessage",
+ "settings.toolsets.postSetupErrorTitle",
+ "settings.toolsets.postSetupFailed",
+ "settings.toolsets.postSetupHint",
+ "settings.toolsets.postSetupInstalled",
+ "settings.toolsets.postSetupInstalledHint",
+ "settings.toolsets.postSetupOpenLogs",
+ "settings.toolsets.postSetupRerun",
+ "settings.toolsets.postSetupRun",
+ "settings.toolsets.postSetupRunAgain",
+ "settings.toolsets.postSetupRunning",
+ "settings.toolsets.postSetupStarting",
+ "settings.toolsets.ready",
+ "settings.toolsets.removeConfirm",
+ "settings.toolsets.removedMessage",
+ "settings.toolsets.removedTitle",
+ "settings.toolsets.savedMessage",
+ "settings.toolsets.savedTitle",
+ "settings.toolsets.selectedMessage",
+ "settings.toolsets.selectedTitle",
+ "settings.toolsets.set",
+ "settings.toolsets.terminalBackend.failedLoad",
+ "settings.toolsets.terminalBackend.failedSelect",
+ "settings.toolsets.terminalBackend.inUse",
+ "settings.toolsets.terminalBackend.loading",
+ "settings.toolsets.terminalBackend.needsSetup",
+ "settings.toolsets.terminalBackend.needsSetupConfirmAction",
+ "settings.toolsets.terminalBackend.needsSetupConfirmDescription",
+ "settings.toolsets.terminalBackend.needsSetupConfirmDescriptionGeneric",
+ "settings.toolsets.terminalBackend.needsSetupConfirmTitle",
+ "settings.toolsets.terminalBackend.needsSetupHint",
+ "settings.toolsets.terminalBackend.openBackendSettings",
+ "settings.toolsets.terminalBackend.ready",
+ "settings.toolsets.terminalBackend.sectionTitle",
+ "settings.toolsets.terminalBackend.selectedMessage",
+ "settings.toolsets.terminalBackend.selectedTitle",
+ "settings.toolsets.terminalBackend.switchedToLocal",
+ "settings.toolsets.terminalBackend.unavailable",
+ "settings.toolsets.terminalBackend.unavailableMessage",
+ "settings.toolsets.terminalBackend.unavailableTitle",
+ "settings.toolsets.terminalBackend.useLocal",
+ "settings.toolsets.useBackend",
+ "settings.toolsets.webCapabilitySelectedMessage",
+ "settings.toolsets.webCapabilityUnset",
+ "settings.toolsets.webExtractActive",
+ "settings.toolsets.webSearchActive",
+ "settings.toolsets.webUseForExtract",
+ "settings.toolsets.webUseForSearch",
+ "settings.toolsets.webUsedForExtract",
+ "settings.toolsets.webUsedForSearch",
+ "settings.uninstallSection.appLabel",
+ "settings.uninstallSection.checkingInstalled",
+ "settings.uninstallSection.chooseHowMuch",
+ "settings.uninstallSection.confirmBody",
+ "settings.uninstallSection.confirmUninstall",
+ "settings.uninstallSection.couldNotStart",
+ "settings.uninstallSection.dangerZone",
+ "settings.uninstallSection.options.full.consequence",
+ "settings.uninstallSection.options.full.description",
+ "settings.uninstallSection.options.full.title",
+ "settings.uninstallSection.options.gui.consequence",
+ "settings.uninstallSection.options.gui.description",
+ "settings.uninstallSection.options.gui.title",
+ "settings.uninstallSection.options.lite.consequence",
+ "settings.uninstallSection.options.lite.description",
+ "settings.uninstallSection.options.lite.title",
+ "settings.uninstallSection.uninstallHermes",
+ "settings.uninstallSection.uninstalling",
+ "settings.uninstallSection.yesUninstall",
+ "settings.vault.add",
+ "settings.vault.addConfirm",
+ "settings.vault.addDescription",
+ "settings.vault.addTitle",
+ "settings.vault.added",
+ "settings.vault.adding",
+ "settings.vault.addressLine1Field",
+ "settings.vault.addressLine2Field",
+ "settings.vault.blurb",
+ "settings.vault.cardNameField",
+ "settings.vault.cardNumberField",
+ "settings.vault.cityField",
+ "settings.vault.count",
+ "settings.vault.countryField",
+ "settings.vault.createdOn",
+ "settings.vault.cvcField",
+ "settings.vault.deleteAction",
+ "settings.vault.deleteConfirm",
+ "settings.vault.deleteDescription",
+ "settings.vault.deleteTitle",
+ "settings.vault.empty",
+ "settings.vault.emptyDesc",
+ "settings.vault.expMonthField",
+ "settings.vault.expYearField",
+ "settings.vault.identifierField",
+ "settings.vault.identifierShown",
+ "settings.vault.identifierTypeField",
+ "settings.vault.identifierTypes.email",
+ "settings.vault.identifierTypes.phone",
+ "settings.vault.identifierTypes.username",
+ "settings.vault.kindField",
+ "settings.vault.kinds.address",
+ "settings.vault.kinds.login",
+ "settings.vault.kinds.payment",
+ "settings.vault.labelField",
+ "settings.vault.labelPlaceholder",
+ "settings.vault.labelRequired",
+ "settings.vault.loadFailed",
+ "settings.vault.loginFieldsRequired",
+ "settings.vault.optional",
+ "settings.vault.originField",
+ "settings.vault.originInvalid",
+ "settings.vault.originPlaceholder",
+ "settings.vault.originPlaceholderCheckout",
+ "settings.vault.otpField",
+ "settings.vault.otpHint",
+ "settings.vault.otpPlaceholder",
+ "settings.vault.passwordField",
+ "settings.vault.postalField",
+ "settings.vault.sources.blurb",
+ "settings.vault.sources.disabledDesc",
+ "settings.vault.sources.lock",
+ "settings.vault.sources.lockedDesc",
+ "settings.vault.sources.masterPasswordPlaceholder",
+ "settings.vault.sources.notInstalled",
+ "settings.vault.sources.statusLocked",
+ "settings.vault.sources.statusNotDetected",
+ "settings.vault.sources.statusOff",
+ "settings.vault.sources.statusUnlocked",
+ "settings.vault.sources.title",
+ "settings.vault.sources.toggleFailed",
+ "settings.vault.sources.unlock",
+ "settings.vault.sources.unlockDescription",
+ "settings.vault.sources.unlockTitle",
+ "settings.vault.sources.unlocked",
+ "settings.vault.sources.unlockedDesc",
+ "settings.vault.sources.unlocking",
+ "settings.vault.stateField",
+ "settings.vault.title",
+ "settings.vault.twoFactorBadge",
+ "sharedMetrics.changeLater",
+ "sharedMetrics.collectDesc",
+ "sharedMetrics.collectLabel",
+ "sharedMetrics.collectedActivity",
+ "sharedMetrics.collectedIntro",
+ "sharedMetrics.collectedMachine",
+ "sharedMetrics.collectedMilestones",
+ "sharedMetrics.collectedModels",
+ "sharedMetrics.collectedNames",
+ "sharedMetrics.collectedReliability",
+ "sharedMetrics.collectedUsage",
+ "sharedMetrics.consentBody",
+ "sharedMetrics.consentTitle",
+ "sharedMetrics.consentWindow",
+ "sharedMetrics.installId",
+ "sharedMetrics.local",
+ "sharedMetrics.off",
+ "sharedMetrics.readDocs",
+ "sharedMetrics.saveFailed",
+ "sharedMetrics.sendDesc",
+ "sharedMetrics.sendLabel",
+ "sharedMetrics.share",
+ "sharedMetrics.stripBody",
+ "sharedMetrics.stripChoices.local",
+ "sharedMetrics.stripChoices.off",
+ "sharedMetrics.stripChoices.share",
+ "sharedMetrics.stripDetails",
+ "sharedMetrics.stripReaskBody",
+ "sharedMetrics.unavailable",
+ "sharedMetrics.whatIsCollected",
+ "shell.appControls",
+ "shell.approvalMode.ariaLabel",
+ "shell.approvalMode.manual",
+ "shell.approvalMode.manualDescription",
+ "shell.approvalMode.off",
+ "shell.approvalMode.offDescription",
+ "shell.approvalMode.smart",
+ "shell.approvalMode.smartDescription",
+ "shell.approvalMode.title",
+ "shell.gatewayMenu.checkingInference",
+ "shell.gatewayMenu.connected",
+ "shell.gatewayMenu.connecting",
+ "shell.gatewayMenu.connection",
+ "shell.gatewayMenu.disconnected",
+ "shell.gatewayMenu.gateway",
+ "shell.gatewayMenu.inferenceNotReady",
+ "shell.gatewayMenu.inferenceReady",
+ "shell.gatewayMenu.messagingPlatforms",
+ "shell.gatewayMenu.offline",
+ "shell.gatewayMenu.openSystem",
+ "shell.gatewayMenu.recentActivity",
+ "shell.gatewayMenu.reconnectGateway",
+ "shell.gatewayMenu.viewAllLogs",
+ "shell.modelMenu.addFavorite",
+ "shell.modelMenu.cacheRead",
+ "shell.modelMenu.editModels",
+ "shell.modelMenu.fast",
+ "shell.modelMenu.favoriteShortcut",
+ "shell.modelMenu.favorites",
+ "shell.modelMenu.followDefault",
+ "shell.modelMenu.free",
+ "shell.modelMenu.limited",
+ "shell.modelMenu.limitedTip",
+ "shell.modelMenu.limitedUntil",
+ "shell.modelMenu.modelLimitedTip",
+ "shell.modelMenu.modelResets",
+ "shell.modelMenu.noModels",
+ "shell.modelMenu.poolAccount",
+ "shell.modelMenu.poolAccounts",
+ "shell.modelMenu.poolLimited",
+ "shell.modelMenu.poolUnavailable",
+ "shell.modelMenu.poolUnknown",
+ "shell.modelMenu.priceTitle",
+ "shell.modelMenu.refreshModels",
+ "shell.modelMenu.removeFavorite",
+ "shell.modelMenu.search",
+ "shell.modelMenu.usageLeft",
+ "shell.modelMenu.usageTip",
+ "shell.modelMenu.usageWindow",
+ "shell.modelOptions.effort",
+ "shell.modelOptions.fast",
+ "shell.modelOptions.fastFailed",
+ "shell.modelOptions.high",
+ "shell.modelOptions.low",
+ "shell.modelOptions.max",
+ "shell.modelOptions.medium",
+ "shell.modelOptions.minimal",
+ "shell.modelOptions.noOptions",
+ "shell.modelOptions.options",
+ "shell.modelOptions.sendsOnRoute",
+ "shell.modelOptions.thinking",
+ "shell.modelOptions.ultra",
+ "shell.modelOptions.ultrafast",
+ "shell.modelOptions.updateFailed",
+ "shell.modelOptions.useStandardSpeed",
+ "shell.modelOptions.xhigh",
+ "shell.paneControls",
+ "shell.statusbar.agents",
+ "shell.statusbar.backend",
+ "shell.statusbar.backendLabel",
+ "shell.statusbar.backendVersion",
+ "shell.statusbar.branch",
+ "shell.statusbar.cacheHitRateTitle",
+ "shell.statusbar.clientLabel",
+ "shell.statusbar.closeAgents",
+ "shell.statusbar.closeCommandCenter",
+ "shell.statusbar.commit",
+ "shell.statusbar.commitsBehind",
+ "shell.statusbar.compressions",
+ "shell.statusbar.connectionCloud",
+ "shell.statusbar.connectionCloudTooltip",
+ "shell.statusbar.connectionRemote",
+ "shell.statusbar.connectionRemoteTooltip",
+ "shell.statusbar.connectionSsh",
+ "shell.statusbar.connectionSshTooltip",
+ "shell.statusbar.contextUsage",
+ "shell.statusbar.contextUsagePanel.categories.conversation",
+ "shell.statusbar.contextUsagePanel.categories.mcp",
+ "shell.statusbar.contextUsagePanel.categories.memory",
+ "shell.statusbar.contextUsagePanel.categories.rules",
+ "shell.statusbar.contextUsagePanel.categories.skills",
+ "shell.statusbar.contextUsagePanel.categories.subagent_definitions",
+ "shell.statusbar.contextUsagePanel.categories.system_prompt",
+ "shell.statusbar.contextUsagePanel.categories.tool_definitions",
+ "shell.statusbar.contextUsagePanel.empty",
+ "shell.statusbar.contextUsagePanel.loading",
+ "shell.statusbar.contextUsagePanel.percentFull",
+ "shell.statusbar.contextUsagePanel.title",
+ "shell.statusbar.contextUsagePanel.tokenSummary",
+ "shell.statusbar.cron",
+ "shell.statusbar.customizeTitle",
+ "shell.statusbar.desktopVersion",
+ "shell.statusbar.failed",
+ "shell.statusbar.focusedSince",
+ "shell.statusbar.focusedSinceTitle",
+ "shell.statusbar.gateway",
+ "shell.statusbar.gatewayChecking",
+ "shell.statusbar.gatewayConnecting",
+ "shell.statusbar.gatewayNeedsSetup",
+ "shell.statusbar.gatewayOffline",
+ "shell.statusbar.gatewayReady",
+ "shell.statusbar.gatewayRestarting",
+ "shell.statusbar.gatewayTitle",
+ "shell.statusbar.gatewayUnavailable",
+ "shell.statusbar.hideStatusbar",
+ "shell.statusbar.hideTerminal",
+ "shell.statusbar.messagingDegraded",
+ "shell.statusbar.messagingStopped",
+ "shell.statusbar.modelNone",
+ "shell.statusbar.modelPinned",
+ "shell.statusbar.modelTitle",
+ "shell.statusbar.noModel",
+ "shell.statusbar.openAgents",
+ "shell.statusbar.openCommandCenter",
+ "shell.statusbar.openCron",
+ "shell.statusbar.openModelPicker",
+ "shell.statusbar.openStarmap",
+ "shell.statusbar.openWebhooks",
+ "shell.statusbar.providerModelTitle",
+ "shell.statusbar.releaseAvailable",
+ "shell.statusbar.resetStatusbar",
+ "shell.statusbar.restart",
+ "shell.statusbar.running",
+ "shell.statusbar.showTerminal",
+ "shell.statusbar.starmap",
+ "shell.statusbar.subagents",
+ "shell.statusbar.switchModel",
+ "shell.statusbar.systemResources.gpuMemory",
+ "shell.statusbar.systemResources.gpuUtilization",
+ "shell.statusbar.systemResources.loading",
+ "shell.statusbar.systemResources.ram",
+ "shell.statusbar.systemResources.title",
+ "shell.statusbar.systemResources.toggle",
+ "shell.statusbar.systemResources.unifiedNote",
+ "shell.statusbar.toggleApprovalMode",
+ "shell.statusbar.toggleBackendVersion",
+ "shell.statusbar.toggleCacheHitRate",
+ "shell.statusbar.toggleCommandCenter",
+ "shell.statusbar.toggleContextUsage",
+ "shell.statusbar.toggleFreeTier",
+ "shell.statusbar.toggleRunningTimer",
+ "shell.statusbar.toggleSessionTimer",
+ "shell.statusbar.toggleTerminal",
+ "shell.statusbar.toggleTokensPerSecond",
+ "shell.statusbar.toggleVersion",
+ "shell.statusbar.toggleWorkspace",
+ "shell.statusbar.tokensPerSecondTitle",
+ "shell.statusbar.turnRunning",
+ "shell.statusbar.unknown",
+ "shell.statusbar.update",
+ "shell.statusbar.updateInProgress",
+ "shell.statusbar.webhooks",
+ "shell.statusbar.yoloOff",
+ "shell.statusbar.yoloOn",
+ "shell.windowControls",
+ "sidebar.allPinned",
+ "sidebar.clearSearch",
+ "sidebar.cronJobs",
+ "sidebar.dateDivider.lastWeek",
+ "sidebar.dateDivider.thisMonth",
+ "sidebar.dateDivider.thisWeek",
+ "sidebar.dateDivider.today",
+ "sidebar.dateDivider.yesterday",
+ "sidebar.files",
+ "sidebar.filter.archived",
+ "sidebar.filter.closed",
+ "sidebar.filter.collapseAll",
+ "sidebar.filter.cost",
+ "sidebar.filter.created",
+ "sidebar.filter.draft",
+ "sidebar.filter.expandAll",
+ "sidebar.filter.filters",
+ "sidebar.filter.grouping",
+ "sidebar.filter.idle",
+ "sidebar.filter.inboxStyle",
+ "sidebar.filter.manual",
+ "sidebar.filter.merged",
+ "sidebar.filter.needsInput",
+ "sidebar.filter.noPR",
+ "sidebar.filter.open",
+ "sidebar.filter.ordering",
+ "sidebar.filter.pr",
+ "sidebar.filter.preview",
+ "sidebar.filter.profile",
+ "sidebar.filter.project",
+ "sidebar.filter.pullRequest",
+ "sidebar.filter.resetToDefaults",
+ "sidebar.filter.show",
+ "sidebar.filter.status",
+ "sidebar.filter.tokens",
+ "sidebar.filter.unread",
+ "sidebar.filter.updated",
+ "sidebar.filter.working",
+ "sidebar.gatewayGroups.actions",
+ "sidebar.gatewayGroups.aliasHint",
+ "sidebar.gatewayGroups.aliasLabel",
+ "sidebar.gatewayGroups.grouping",
+ "sidebar.gatewayGroups.moveDown",
+ "sidebar.gatewayGroups.moveUp",
+ "sidebar.gatewayGroups.rename",
+ "sidebar.gatewayGroups.reorder",
+ "sidebar.gatewayGroups.resetName",
+ "sidebar.groupAriaGrouped",
+ "sidebar.groupAriaUngrouped",
+ "sidebar.groupTitleGrouped",
+ "sidebar.groupTitleUngrouped",
+ "sidebar.loadCount",
+ "sidebar.loadMore",
+ "sidebar.loading",
+ "sidebar.logs",
+ "sidebar.markAllRead",
+ "sidebar.messageCount",
+ "sidebar.nav.artifacts",
+ "sidebar.nav.capabilities",
+ "sidebar.nav.cron",
+ "sidebar.nav.messaging",
+ "sidebar.nav.new-session",
+ "sidebar.newSessionIn",
+ "sidebar.noFilterMatches",
+ "sidebar.noMatch",
+ "sidebar.noSessions",
+ "sidebar.noWorkspace",
+ "sidebar.pinned",
+ "sidebar.profileRail",
+ "sidebar.projectEmpty",
+ "sidebar.projectLoadFailed",
+ "sidebar.projects.addFolder",
+ "sidebar.projects.addFolderTitle",
+ "sidebar.projects.autoDiscovered",
+ "sidebar.projects.back",
+ "sidebar.projects.baseBranchNone",
+ "sidebar.projects.baseBranchPlaceholder",
+ "sidebar.projects.branchCreateWorktree",
+ "sidebar.projects.branchOff",
+ "sidebar.projects.branchOpenExisting",
+ "sidebar.projects.branchPlaceholder",
+ "sidebar.projects.branchSwitchHome",
+ "sidebar.projects.branchTrackRemote",
+ "sidebar.projects.branchesLoading",
+ "sidebar.projects.convertBranch",
+ "sidebar.projects.convertBranchDesc",
+ "sidebar.projects.convertBranchInstead",
+ "sidebar.projects.convertBranchPlaceholder",
+ "sidebar.projects.convertBranchTitle",
+ "sidebar.projects.copyPath",
+ "sidebar.projects.create",
+ "sidebar.projects.createDesc",
+ "sidebar.projects.createFailed",
+ "sidebar.projects.createTitle",
+ "sidebar.projects.createdInPreviousContext",
+ "sidebar.projects.deleteConfirm",
+ "sidebar.projects.enter",
+ "sidebar.projects.foldersLabel",
+ "sidebar.projects.forceRemove",
+ "sidebar.projects.home",
+ "sidebar.projects.ideaGenerate",
+ "sidebar.projects.ideaGenerating",
+ "sidebar.projects.ideaLabel",
+ "sidebar.projects.ideaPlaceholder",
+ "sidebar.projects.ideaShuffle",
+ "sidebar.projects.menu",
+ "sidebar.projects.menuAddFolder",
+ "sidebar.projects.menuAppearance",
+ "sidebar.projects.menuDelete",
+ "sidebar.projects.menuRename",
+ "sidebar.projects.menuSetActive",
+ "sidebar.projects.moveFailed",
+ "sidebar.projects.moveNoFolder",
+ "sidebar.projects.moveNoProjects",
+ "sidebar.projects.moveToProject",
+ "sidebar.projects.movedTo",
+ "sidebar.projects.namePlaceholder",
+ "sidebar.projects.newButton",
+ "sidebar.projects.newWorktreeDesc",
+ "sidebar.projects.newWorktreeTitle",
+ "sidebar.projects.noBranches",
+ "sidebar.projects.noColor",
+ "sidebar.projects.noFolders",
+ "sidebar.projects.primaryBadge",
+ "sidebar.projects.removeFolder",
+ "sidebar.projects.removeFromSidebar",
+ "sidebar.projects.removeWorktree",
+ "sidebar.projects.removeWorktreeConfirm",
+ "sidebar.projects.removeWorktreeDirty",
+ "sidebar.projects.removeWorktreeFailed",
+ "sidebar.projects.renameTitle",
+ "sidebar.projects.reorder",
+ "sidebar.projects.reveal",
+ "sidebar.projects.sectionLabel",
+ "sidebar.projects.showAllCount",
+ "sidebar.projects.showAllSessions",
+ "sidebar.projects.staleBackend",
+ "sidebar.projects.startWork",
+ "sidebar.projects.startWorkFailed",
+ "sidebar.projects.toggle",
+ "sidebar.projects.worktreeProjectLabel",
+ "sidebar.projects.worktreeProjectNone",
+ "sidebar.projects.worktreeProjectPlaceholder",
+ "sidebar.projects.worktreeStaleBackend",
+ "sidebar.results",
+ "sidebar.review",
+ "sidebar.row.ageDay",
+ "sidebar.row.ageHour",
+ "sidebar.row.ageMin",
+ "sidebar.row.ageNow",
+ "sidebar.row.archive",
+ "sidebar.row.backgroundRunning",
+ "sidebar.row.branchFrom",
+ "sidebar.row.continuationOrigin",
+ "sidebar.row.copyId",
+ "sidebar.row.copyIdFailed",
+ "sidebar.row.deleteDesc",
+ "sidebar.row.deleteTitle",
+ "sidebar.row.deleted",
+ "sidebar.row.deleting",
+ "sidebar.row.draftSession",
+ "sidebar.row.export",
+ "sidebar.row.finishedUnread",
+ "sidebar.row.handoffOrigin",
+ "sidebar.row.hideTabBar",
+ "sidebar.row.markRead",
+ "sidebar.row.markUnread",
+ "sidebar.row.messageCount",
+ "sidebar.row.needsInput",
+ "sidebar.row.newWindow",
+ "sidebar.row.openInNewTab",
+ "sidebar.row.openInSplit",
+ "sidebar.row.openInTerminal",
+ "sidebar.row.ownedByProfile",
+ "sidebar.row.pin",
+ "sidebar.row.rename",
+ "sidebar.row.renameDesc",
+ "sidebar.row.renameFailed",
+ "sidebar.row.renameTitle",
+ "sidebar.row.renamed",
+ "sidebar.row.sessionActions",
+ "sidebar.row.sessionRunning",
+ "sidebar.row.todoProgress",
+ "sidebar.row.unarchive",
+ "sidebar.row.unpin",
+ "sidebar.row.unreadFailed",
+ "sidebar.row.untitledChat",
+ "sidebar.row.untitledPlaceholder",
+ "sidebar.row.waitingForAnswer",
+ "sidebar.searchAria",
+ "sidebar.searchPlaceholder",
+ "sidebar.sessions",
+ "sidebar.shiftClickHint",
+ "sidebar.showMoreIn",
+ "sidebar.showProjects",
+ "sidebar.showSessions",
+ "sidebar.statusDivider.done",
+ "sidebar.statusDivider.working",
+ "sidebar.storageCorrupt.action",
+ "sidebar.storageCorrupt.body",
+ "sidebar.storageCorrupt.guide",
+ "sidebar.storageCorrupt.title",
+ "sidebar.terminal",
+ "sidebar.toolCallCount",
+ "skillDeepLink.destinationChanged",
+ "skillDeepLink.installComplete",
+ "skillDeepLink.installDescription",
+ "skillDeepLink.installTitle",
+ "skillDeepLink.installTo",
+ "skillDeepLink.installed",
+ "skillDeepLink.installing",
+ "skillDeepLink.source",
+ "skillDeepLink.thisComputer",
+ "skills.all",
+ "skills.appliesToNewSessions",
+ "skills.archive",
+ "skills.bulkNoChange",
+ "skills.bulkUpdated",
+ "skills.changesApplyNewSessions",
+ "skills.configureToolset",
+ "skills.configured",
+ "skills.configuringProfile",
+ "skills.disableAll",
+ "skills.disableUnused",
+ "skills.edit",
+ "skills.emptyNoneAvailable",
+ "skills.emptyNoneFound",
+ "skills.emptyNothingMatches",
+ "skills.enableAll",
+ "skills.failedToUpdate",
+ "skills.hub.actionFailed",
+ "skills.hub.actionLog",
+ "skills.hub.alreadyInstalled",
+ "skills.hub.close",
+ "skills.hub.connectedHubs",
+ "skills.hub.connectingHubs",
+ "skills.hub.featured",
+ "skills.hub.files",
+ "skills.hub.findings",
+ "skills.hub.install",
+ "skills.hub.installBlockedMessage",
+ "skills.hub.installBlockedTitle",
+ "skills.hub.installStarted",
+ "skills.hub.installed",
+ "skills.hub.installing",
+ "skills.hub.landingHint",
+ "skills.hub.loadFailed",
+ "skills.hub.noFindings",
+ "skills.hub.noReadme",
+ "skills.hub.noResults",
+ "skills.hub.openLog",
+ "skills.hub.pickerBrowse",
+ "skills.hub.pickerHide",
+ "skills.hub.pickerHint",
+ "skills.hub.pickerTitle",
+ "skills.hub.policyAllow",
+ "skills.hub.policyAsk",
+ "skills.hub.policyBlock",
+ "skills.hub.preview",
+ "skills.hub.previewFailed",
+ "skills.hub.resultCount",
+ "skills.hub.scan",
+ "skills.hub.scanFailed",
+ "skills.hub.scanning",
+ "skills.hub.search",
+ "skills.hub.searchFailed",
+ "skills.hub.searchPlaceholder",
+ "skills.hub.searching",
+ "skills.hub.timedOut",
+ "skills.hub.trust.builtin",
+ "skills.hub.trust.community",
+ "skills.hub.trust.trusted",
+ "skills.hub.uninstall",
+ "skills.hub.uninstallStarted",
+ "skills.hub.uninstalling",
+ "skills.hub.updateAll",
+ "skills.hub.updateStarted",
+ "skills.hub.updating",
+ "skills.hub.verdictCaution",
+ "skills.hub.verdictDangerous",
+ "skills.hub.verdictSafe",
+ "skills.hub.viewScan",
+ "skills.loading",
+ "skills.needsKeys",
+ "skills.noDescription",
+ "skills.noSkillsDesc",
+ "skills.noSkillsTitle",
+ "skills.noToolsetsDesc",
+ "skills.noToolsetsTitle",
+ "skills.officialCatalog",
+ "skills.officialPill",
+ "skills.plugins.agentBlurb",
+ "skills.plugins.agentTitle",
+ "skills.plugins.alreadyInstalled",
+ "skills.plugins.catalogBrowse",
+ "skills.plugins.catalogHide",
+ "skills.plugins.catalogHint",
+ "skills.plugins.catalogProvenance",
+ "skills.plugins.catalogTitle",
+ "skills.plugins.deepLinkCatalogInvalidName",
+ "skills.plugins.deepLinkCatalogUnavailable",
+ "skills.plugins.deepLinkCatalogUnknown",
+ "skills.plugins.deepLinkErrorTitle",
+ "skills.plugins.defaultProfile",
+ "skills.plugins.desktopHalfPending",
+ "skills.plugins.desktopHalfPendingTip",
+ "skills.plugins.desktopHalfRemote",
+ "skills.plugins.desktopHalfRemoteTip",
+ "skills.plugins.empty",
+ "skills.plugins.emptyAll",
+ "skills.plugins.emptyHint",
+ "skills.plugins.halfAgent",
+ "skills.plugins.halfAgentIn",
+ "skills.plugins.halfDesktop",
+ "skills.plugins.halfDesktopHint",
+ "skills.plugins.installAgentHere",
+ "skills.plugins.installAgentHereNoOrigin",
+ "skills.plugins.installAgentHereTip",
+ "skills.plugins.kindAgent",
+ "skills.plugins.kindBoth",
+ "skills.plugins.kindDesktop",
+ "skills.plugins.legacyBackend",
+ "skills.plugins.loadFailed",
+ "skills.plugins.pageBlurb",
+ "skills.plugins.pinnedBadge",
+ "skills.plugins.pinnedProvenance",
+ "skills.plugins.portableBadge",
+ "skills.plugins.serverStates.app_not_running",
+ "skills.plugins.serverStates.connected",
+ "skills.plugins.serverStates.endpoint_unavailable",
+ "skills.plugins.serverStates.hermes_not_connected",
+ "skills.plugins.serverStates.missing_app",
+ "skills.plugins.serverStates.no_interactive_session",
+ "skills.plugins.serverStates.unknown",
+ "skills.plugins.serverStates.unsupported_gpu",
+ "skills.plugins.serverStates.version_too_old",
+ "skills.plugins.settingsForm.required",
+ "skills.plugins.settingsForm.save",
+ "skills.plugins.settingsForm.saveFailed",
+ "skills.plugins.settingsForm.saved",
+ "skills.plugins.settingsForm.secretSet",
+ "skills.plugins.settingsForm.secretStoredAs",
+ "skills.plugins.settingsToggle",
+ "skills.plugins.tierCommunity",
+ "skills.plugins.tierOfficial",
+ "skills.plugins.toggleFailed",
+ "skills.plugins.toolsetOff",
+ "skills.plugins.toolsetOn",
+ "skills.plugins.toolsetToggleFailed",
+ "skills.plugins.uninstall",
+ "skills.plugins.uninstallConfirmBody",
+ "skills.plugins.uninstallConfirmTitle",
+ "skills.plugins.uninstallDesktopConfirmBody",
+ "skills.plugins.uninstallDesktopTip",
+ "skills.plugins.uninstallFailed",
+ "skills.plugins.uninstallTip",
+ "skills.plugins.uninstalled",
+ "skills.plugins.uninstalledDesktop",
+ "skills.plugins.updateConsentBody",
+ "skills.plugins.updateConsentConfirm",
+ "skills.plugins.updateConsentTitle",
+ "skills.plugins.updateFailed",
+ "skills.plugins.updateToPin",
+ "skills.plugins.updated",
+ "skills.provenance.agent",
+ "skills.provenance.bundled",
+ "skills.provenance.hub",
+ "skills.refresh",
+ "skills.refreshing",
+ "skills.searchSkills",
+ "skills.searchToolsets",
+ "skills.skillArchivedMessage",
+ "skills.skillArchivedTitle",
+ "skills.skillDisabled",
+ "skills.skillEnabled",
+ "skills.skillUpdated",
+ "skills.skillsLoadFailed",
+ "skills.sortAlpha",
+ "skills.sortLeastUsedAsc",
+ "skills.sortMostUsed",
+ "skills.sortMostUsedDesc",
+ "skills.tabPlugins",
+ "skills.tabSkills",
+ "skills.tabToolsets",
+ "skills.toggleToolset",
+ "skills.toolsetDisabled",
+ "skills.toolsetEnabled",
+ "skills.toolsetsEnabled",
+ "skills.toolsetsRefreshFailed",
+ "skills.usageCount",
+ "skills.visionModelHint",
+ "skills.visionModelLink",
+ "starmap.close",
+ "starmap.copied",
+ "starmap.copy",
+ "starmap.emptyDesc",
+ "starmap.emptyTitle",
+ "starmap.filterAll",
+ "starmap.filterLearned",
+ "starmap.filterUsed",
+ "starmap.importBtn",
+ "starmap.importEmpty",
+ "starmap.importMap",
+ "starmap.importSuccess",
+ "starmap.importedBadge",
+ "starmap.loadFailed",
+ "starmap.loading",
+ "starmap.memory",
+ "starmap.refresh",
+ "starmap.resetToMine",
+ "starmap.share",
+ "starmap.shareHint",
+ "starmap.sharePlaceholder",
+ "starmap.shareTitle",
+ "starmap.subtitle",
+ "starmap.title",
+ "starmap.viewGraph",
+ "statusStack.agents",
+ "statusStack.background",
+ "statusStack.coding.agentShip",
+ "statusStack.coding.agentShipPrompt",
+ "statusStack.coding.agentShipUnavailable",
+ "statusStack.coding.ahead",
+ "statusStack.coding.behind",
+ "statusStack.coding.branchOffFrom",
+ "statusStack.coding.changed",
+ "statusStack.coding.clean",
+ "statusStack.coding.close",
+ "statusStack.coding.commit",
+ "statusStack.coding.commitAndPush",
+ "statusStack.coding.commitPlaceholder",
+ "statusStack.coding.createPr",
+ "statusStack.coding.detached",
+ "statusStack.coding.generateCommitMessage",
+ "statusStack.coding.ghMissing",
+ "statusStack.coding.newBranch",
+ "statusStack.coding.noBranch",
+ "statusStack.coding.noChanges",
+ "statusStack.coding.noDiff",
+ "statusStack.coding.notRepo",
+ "statusStack.coding.openChanges",
+ "statusStack.coding.openFile",
+ "statusStack.coding.openPr",
+ "statusStack.coding.readOnlyScope",
+ "statusStack.coding.revert",
+ "statusStack.coding.revertAll",
+ "statusStack.coding.revertAllConfirm",
+ "statusStack.coding.revertConfirm",
+ "statusStack.coding.review",
+ "statusStack.coding.scopeBranch",
+ "statusStack.coding.scopeLastTurn",
+ "statusStack.coding.scopeUncommitted",
+ "statusStack.coding.stage",
+ "statusStack.coding.stageAll",
+ "statusStack.coding.staged",
+ "statusStack.coding.stopGenerating",
+ "statusStack.coding.switchFailed",
+ "statusStack.coding.switchTo",
+ "statusStack.coding.title",
+ "statusStack.coding.unstage",
+ "statusStack.coding.viewAsList",
+ "statusStack.coding.viewAsTree",
+ "statusStack.coding.worktrees",
+ "statusStack.control.actionFailed",
+ "statusStack.control.actionSucceeded",
+ "statusStack.control.add",
+ "statusStack.control.addCriterion",
+ "statusStack.control.addCriterionDialogTitle",
+ "statusStack.control.addCriterionPlaceholder",
+ "statusStack.control.clearCriteria",
+ "statusStack.control.clearCriteriaConfirmBody",
+ "statusStack.control.clearCriteriaConfirmTitle",
+ "statusStack.control.clearGoal",
+ "statusStack.control.clearGoalConfirmBody",
+ "statusStack.control.clearGoalConfirmTitle",
+ "statusStack.control.clearHeartbeat",
+ "statusStack.control.clearHeartbeatConfirmBody",
+ "statusStack.control.clearHeartbeatConfirmTitle",
+ "statusStack.control.continuationBusy",
+ "statusStack.control.continuationFailed",
+ "statusStack.control.continuationQueued",
+ "statusStack.control.contractBoundaries",
+ "statusStack.control.contractConstraints",
+ "statusStack.control.contractOutcome",
+ "statusStack.control.contractStopWhen",
+ "statusStack.control.contractVerification",
+ "statusStack.control.controlUnavailable",
+ "statusStack.control.copyCriterion",
+ "statusStack.control.copyFailure",
+ "statusStack.control.copySuccess",
+ "statusStack.control.criteriaHeader",
+ "statusStack.control.criterionLabel",
+ "statusStack.control.dismissError",
+ "statusStack.control.dismissLoop",
+ "statusStack.control.gateAttempts",
+ "statusStack.control.gateCommand",
+ "statusStack.control.gateLastExit",
+ "statusStack.control.gateTimeout",
+ "statusStack.control.goalActions",
+ "statusStack.control.goalActiveTurns",
+ "statusStack.control.goalDetailsTitle",
+ "statusStack.control.goalDoneTurns",
+ "statusStack.control.goalTurn",
+ "statusStack.control.heartbeatActions",
+ "statusStack.control.heartbeatActive",
+ "statusStack.control.heartbeatDueWaitingForIdle",
+ "statusStack.control.heartbeatEveryHours",
+ "statusStack.control.heartbeatEveryMinutes",
+ "statusStack.control.heartbeatEverySeconds",
+ "statusStack.control.heartbeatFiredCount",
+ "statusStack.control.heartbeatNext",
+ "statusStack.control.heartbeatPaused",
+ "statusStack.control.loopActions",
+ "statusStack.control.loopActive",
+ "statusStack.control.loopAwaitingResponse",
+ "statusStack.control.loopCadenceLabel",
+ "statusStack.control.loopDeferred",
+ "statusStack.control.loopDeferredNotice",
+ "statusStack.control.loopEveryHours",
+ "statusStack.control.loopEveryMinutes",
+ "statusStack.control.loopEverySeconds",
+ "statusStack.control.loopFinished",
+ "statusStack.control.loopNext",
+ "statusStack.control.loopPaused",
+ "statusStack.control.loopPromptLabel",
+ "statusStack.control.loopRunCount",
+ "statusStack.control.loopRuns",
+ "statusStack.control.loopSelfPaced",
+ "statusStack.control.loopUntilLabel",
+ "statusStack.control.noCriteria",
+ "statusStack.control.objectiveLabel",
+ "statusStack.control.pauseGoal",
+ "statusStack.control.pauseHeartbeat",
+ "statusStack.control.pauseLoop",
+ "statusStack.control.qualityGatesTitle",
+ "statusStack.control.removeCriterion",
+ "statusStack.control.removeCriterionConfirmBody",
+ "statusStack.control.removeCriterionConfirmTitle",
+ "statusStack.control.resumeGoal",
+ "statusStack.control.resumeHeartbeat",
+ "statusStack.control.resumeLoop",
+ "statusStack.control.resumeNow",
+ "statusStack.control.stopLoop",
+ "statusStack.control.stopLoopConfirmBody",
+ "statusStack.control.stopLoopConfirmTitle",
+ "statusStack.control.viewDetails",
+ "statusStack.control.waitBarrierTitle",
+ "statusStack.control.waitPid",
+ "statusStack.control.waitSession",
+ "statusStack.control.waitUntil",
+ "statusStack.dismiss",
+ "statusStack.exit",
+ "statusStack.goalActive",
+ "statusStack.goalBlocked",
+ "statusStack.goalDone",
+ "statusStack.goalPaused",
+ "statusStack.goalWaiting",
+ "statusStack.hideStack",
+ "statusStack.previousTodos",
+ "statusStack.running",
+ "statusStack.showStack",
+ "statusStack.stop",
+ "statusStack.subagents",
+ "statusStack.todos",
+ "tips.close",
+ "tips.items.artifacts.text",
+ "tips.items.artifacts.title",
+ "tips.items.command-palette.text",
+ "tips.items.command-palette.title",
+ "tips.items.composer-mentions.text",
+ "tips.items.composer-mentions.title",
+ "tips.items.cron.text",
+ "tips.items.cron.title",
+ "tips.items.local-runtime-update.action",
+ "tips.items.local-runtime-update.text",
+ "tips.items.local-runtime-update.title",
+ "tips.items.local-setup.action",
+ "tips.items.local-setup.text",
+ "tips.items.local-setup.title",
+ "tips.items.messaging.text",
+ "tips.items.messaging.title",
+ "tips.items.new-session.text",
+ "tips.items.new-session.title",
+ "tips.items.profiles.text",
+ "tips.items.profiles.title",
+ "tips.items.right-pane.text",
+ "tips.items.right-pane.title",
+ "tips.items.skills.text",
+ "tips.items.skills.title",
+ "titlebar.enterHud",
+ "titlebar.exitHud",
+ "titlebar.hideRightSidebar",
+ "titlebar.hideSidebar",
+ "titlebar.layoutEditor",
+ "titlebar.layoutEditorTitle",
+ "titlebar.muteHaptics",
+ "titlebar.openSettings",
+ "titlebar.openStarmap",
+ "titlebar.resetHudLayout",
+ "titlebar.search",
+ "titlebar.searchTitle",
+ "titlebar.showRightSidebar",
+ "titlebar.showSidebar",
+ "titlebar.swapSidebarSides",
+ "titlebar.unmuteHaptics",
+ "titlebar.unreadSessions",
+ "ui.logs.bottom",
+ "ui.logs.search",
+ "ui.logs.top",
+ "ui.pagination.label",
+ "ui.pagination.next",
+ "ui.pagination.nextAria",
+ "ui.pagination.previous",
+ "ui.pagination.previousAria",
+ "ui.search.clear",
+ "ui.sidebar.description",
+ "ui.sidebar.title",
+ "ui.sidebar.toggle",
+ "updates.allSetTitle",
+ "updates.appName",
+ "updates.applyStatus.failed",
+ "updates.applyStatus.noReturn",
+ "updates.applyStatus.notAvailable",
+ "updates.applyStatus.owed",
+ "updates.applyStatus.preparing",
+ "updates.applyStatus.pulling",
+ "updates.applyStatus.restarting",
+ "updates.applyingBody",
+ "updates.applyingBodyAppInstaller",
+ "updates.applyingBodyBackend",
+ "updates.applyingClose",
+ "updates.applyingCloseAppInstaller",
+ "updates.availableBody",
+ "updates.availableBodyAppInstaller",
+ "updates.availableBodyBackend",
+ "updates.availableBodyNoChangelog",
+ "updates.availableBodyRelease",
+ "updates.availableTitle",
+ "updates.availableTitleBackend",
+ "updates.blockerBody",
+ "updates.blockerTitle",
+ "updates.bundleOutOfSync",
+ "updates.bundleOutOfSyncAction",
+ "updates.bundleOutOfSyncDesc",
+ "updates.bundleSwapPending",
+ "updates.bundleSwapPendingAction",
+ "updates.bundleSwapPendingDesc",
+ "updates.cantReach",
+ "updates.changeLogFallbackItem",
+ "updates.changeLogFallbackLabel",
+ "updates.changeLogFaster",
+ "updates.changeLogFixed",
+ "updates.changeLogImproved",
+ "updates.changeLogNew",
+ "updates.changeLogOther",
+ "updates.channels.canary",
+ "updates.channels.stable",
+ "updates.checkFailedTitle",
+ "updates.checkNow",
+ "updates.checkUnknownBodyAppInstaller",
+ "updates.checkUnknownTitleAppInstaller",
+ "updates.checking",
+ "updates.checkingShort",
+ "updates.clientAlsoBehindAction",
+ "updates.clientAlsoBehindMessage",
+ "updates.clientAlsoBehindTitle",
+ "updates.closePreviewsAndCheckAgain",
+ "updates.closePreviewsAndUpdate",
+ "updates.connectionRetry",
+ "updates.connectionSettings",
+ "updates.copied",
+ "updates.copy",
+ "updates.copyFullLog",
+ "updates.daysAgo",
+ "updates.discontinuedBody",
+ "updates.discontinuedTitle",
+ "updates.done",
+ "updates.errorBody",
+ "updates.errorTitle",
+ "updates.everythingDispatched",
+ "updates.everythingFanoutFailedTitle",
+ "updates.everythingRowFailed",
+ "updates.everythingSkipped",
+ "updates.foreignBlockerBody",
+ "updates.foreignBlockerTitle",
+ "updates.gitUnusable",
+ "updates.guiSkewBody",
+ "updates.guiSkewTitle",
+ "updates.hoursAgo",
+ "updates.installing",
+ "updates.justNow",
+ "updates.justNowSuffix",
+ "updates.lastChecked",
+ "updates.latestBody",
+ "updates.latestBodyBackend",
+ "updates.localPreview",
+ "updates.manualBody",
+ "updates.manualBodyBackend",
+ "updates.manualPickedUp",
+ "updates.manualPickedUpBackend",
+ "updates.manualTitle",
+ "updates.manualUnavailableTitle",
+ "updates.maybeLater",
+ "updates.minAgo",
+ "updates.mixedBlockerBody",
+ "updates.moreChanges",
+ "updates.never",
+ "updates.notAvailableTitle",
+ "updates.notNow",
+ "updates.onLatest",
+ "updates.openDownloadPage",
+ "updates.pidLabel",
+ "updates.portLabel",
+ "updates.releaseAvailable",
+ "updates.releaseNotes",
+ "updates.seeWhatsNew",
+ "updates.stages.done",
+ "updates.stages.error",
+ "updates.stages.fetch",
+ "updates.stages.guiSkew",
+ "updates.stages.idle",
+ "updates.stages.manual",
+ "updates.stages.prepare",
+ "updates.stages.pull",
+ "updates.stages.pydeps",
+ "updates.stages.rebuild",
+ "updates.stages.restart",
+ "updates.stages.update",
+ "updates.tapCheck",
+ "updates.technicalDetails",
+ "updates.tryAgain",
+ "updates.unsupportedMessage",
+ "updates.updateNow",
+ "updates.updateReady",
+ "updates.updateReadyUnknown",
+ "updates.version",
+ "updates.versionDetailsBody",
+ "updates.versionDetailsBuildOrigin",
+ "updates.versionDetailsCommit",
+ "updates.versionDetailsDistribution",
+ "updates.versionDetailsDistributionDesktop",
+ "updates.versionDetailsDistributionDesktopInstaller",
+ "updates.versionDetailsDistributionDesktopMsix",
+ "updates.versionDetailsDistributionSource",
+ "updates.versionDetailsDistributionSourceDesktop",
+ "updates.versionDetailsDistributionSourceInstaller",
+ "updates.versionDetailsDistributionSourceInstallerDesktop",
+ "updates.versionDetailsDistributionStore",
+ "updates.versionDetailsInstallId",
+ "updates.versionDetailsRuntime",
+ "updates.versionDetailsRuntimeEmbedded",
+ "updates.versionDetailsRuntimeExternal",
+ "updates.versionDetailsTitle",
+ "updates.versionDetailsUncommittedChanges",
+ "updates.versionDetailsVersion",
+ "updates.versionUnavailable",
+ "webhooks.all",
+ "webhooks.copy",
+ "webhooks.create",
+ "webhooks.createFailed",
+ "webhooks.created",
+ "webhooks.createdSecretHint",
+ "webhooks.createdTitle",
+ "webhooks.creating",
+ "webhooks.delete",
+ "webhooks.deleteDescPrefix",
+ "webhooks.deleteDescSuffix",
+ "webhooks.deleteFailed",
+ "webhooks.deleteTitle",
+ "webhooks.deleted",
+ "webhooks.deleting",
+ "webhooks.deliverOnly",
+ "webhooks.deliverOptions.discord",
+ "webhooks.deliverOptions.email",
+ "webhooks.deliverOptions.github_comment",
+ "webhooks.deliverOptions.log",
+ "webhooks.deliverOptions.slack",
+ "webhooks.deliverOptions.telegram",
+ "webhooks.disableRow",
+ "webhooks.disabled",
+ "webhooks.disabledBody",
+ "webhooks.disabledTitle",
+ "webhooks.done",
+ "webhooks.empty",
+ "webhooks.enable",
+ "webhooks.enableRow",
+ "webhooks.enabled",
+ "webhooks.enabledRestarting",
+ "webhooks.enabling",
+ "webhooks.fieldDeliver",
+ "webhooks.fieldDeliverOnly",
+ "webhooks.fieldDescription",
+ "webhooks.fieldDescriptionPlaceholder",
+ "webhooks.fieldEvents",
+ "webhooks.fieldEventsPlaceholder",
+ "webhooks.fieldName",
+ "webhooks.fieldNamePlaceholder",
+ "webhooks.fieldPrompt",
+ "webhooks.fieldPromptPlaceholder",
+ "webhooks.fieldSkills",
+ "webhooks.fieldSkillsPlaceholder",
+ "webhooks.hint",
+ "webhooks.loadFailed",
+ "webhooks.loading",
+ "webhooks.nameRequired",
+ "webhooks.newSubscription",
+ "webhooks.restartFailed",
+ "webhooks.restartGateway",
+ "webhooks.restartNeeded",
+ "webhooks.restarting",
+ "webhooks.restartingGateway",
+ "webhooks.search",
+ "webhooks.secretOnce",
+ "webhooks.subscriptions",
+ "webhooks.toggleFailed",
+ "webhooks.webhookUrl",
+ "zones.closeAll",
+ "zones.closeOthers",
+ "zones.closeRunningBody",
+ "zones.closeRunningConfirm",
+ "zones.closeRunningTitle",
+ "zones.closeToRight",
+ "zones.custom",
+ "zones.customZoneName",
+ "zones.deletePreset",
+ "zones.editHint",
+ "zones.editTitle",
+ "zones.editorHintPost",
+ "zones.editorHintPre",
+ "zones.hideStripTab",
+ "zones.hideTabStrip",
+ "zones.lastTabKeptBody",
+ "zones.lastTabKeptTitle",
+ "zones.layoutNamePlaceholder",
+ "zones.mergeZones",
+ "zones.minimize",
+ "zones.missingPane",
+ "zones.nameLayoutPlaceholder",
+ "zones.newGridLayout",
+ "zones.newSessionTab",
+ "zones.newTab",
+ "zones.notExpressible",
+ "zones.pluginDisabled",
+ "zones.pluginDisabledBody",
+ "zones.reload",
+ "zones.reset",
+ "zones.restore",
+ "zones.saveApply",
+ "zones.saveCurrentAs",
+ "zones.showStripTab",
+ "zones.showTabStrip",
+ "zones.tabCount",
+ "zones.templateColumns",
+ "zones.templateGrid",
+ "zones.templatePriority",
+ "zones.templateRows",
+ "zones.templates",
+ "zones.toggleStripTab",
+ "zones.zoneCount",
+ "zones.zoneEditorTitle",
+ "zones.zoneMenuLabel",
+ "zones.zoneTag"
+ ]
+ }
diff --cc plugins/dashboard_auth/_shared.py
index 0c80431a9db,3414e176aa1..6cb8421c498
--- a/plugins/dashboard_auth/_shared.py
+++ b/plugins/dashboard_auth/_shared.py
@@@ -216,10 -294,11 +295,15 @@@ def verify_jwt
options={"require": ["exp", "iat", "aud", "iss", "sub"]})
except jwt.ExpiredSignatureError as exc:
raise InvalidCodeError(f"{label} expired: {exc}") from exc
+ except jwt.InvalidSignatureError as exc:
+ # A forged/tampered bearer is "not my token", never an IDP outage: a 503 here would let a
+ # remote caller with garbage credentials look like a provider incident (and keep cookies).
+ raise InvalidCodeError(f"{label} signature invalid: {exc}") from exc
+ except jwt.ImmatureSignatureError as exc:
+ # iat/nbf ahead of now beyond the leeway = clock skew or a bad token — the
+ # provider is *reachable*, so this must NOT surface as ProviderError/503
+ # (which discarded rotated refresh tokens and forced re-login, #47815).
+ raise InvalidCodeError(f"{label} not yet valid: {exc}") from exc
except jwt.InvalidTokenError as exc:
# Decoding without verification is safe here: verification already failed and
# these values are surfaced for diagnostics only, never trusted.
diff --cc plugins/platforms/discord/adapter.py
index 49400fa3e75,94dca131e85..68e802a127c
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@@ -1002,10 -1258,13 +1258,14 @@@ def _read_discord_prompt_timeout() -> i
from plugins.platforms.discord.adapter_media import DiscordMediaMixin
+from plugins.platforms.discord.adapter_authorization import DiscordAuthorizationMixin
+ from plugins.platforms.discord.adapter_slash_auth import DiscordSlashAuthMixin
+ from plugins.platforms.discord.adapter_thread_titles import DiscordThreadTitlesMixin, SemanticThreadRenames
+ from plugins.platforms.discord.adapter_voice_info import DiscordVoiceInfoMixin
- class DiscordAdapter(DiscordAuthorizationMixin, DiscordMediaMixin, BasePlatformAdapter):
-class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInfoMixin, DiscordSlashAuthMixin,
- BasePlatformAdapter):
++class DiscordAdapter(DiscordAuthorizationMixin, DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInfoMixin,
++ DiscordSlashAuthMixin, BasePlatformAdapter):
"""Discord bot adapter: guild/DM messages, threads, slash commands, button approvals, reactions."""
MAX_MESSAGE_LENGTH = 2000
diff --cc tests/cron/test_cron_incidents.py
index e4b1d03e426,cc027325e5a..bab6049cb98
--- a/tests/cron/test_cron_incidents.py
+++ b/tests/cron/test_cron_incidents.py
@@@ -291,6 -305,26 +310,26 @@@ def test_ack_suppresses_alert_until_sig
assert inc.count_incidents() == 2
-def test_ack_holds_when_only_a_measured_duration_differs(monkeypatch, tmp_path):
++def test_ack_holds_when_only_a_measured_duration_differs(monkeypatch, tmp_path, cron_owner):
+ """The inactivity watchdog polls every few seconds, so the same stall reports a slightly
+ different idle time each run. That is the same failure: the ack must keep it silent."""
+ inc = _point_db(monkeypatch, tmp_path)
+ deliveries = []
+ job = _job()
+ stall = "Cron job 'x' idle for {}s (limit 600s) — last activity: waiting for tool"
+ with cron_jobs.use_cron_store(tmp_path):
+ cron_jobs.save_jobs([job])
+ _tick_failing(job, tmp_path, deliveries, error=stall.format(601))
+ assert len(deliveries) == 1
+ (first,) = inc.list_incidents()
+ assert inc.ack_incident(first["id"]) is True
+
+ _tick_failing(job, tmp_path, deliveries, error=stall.format(604))
+
+ assert len(deliveries) == 1, "acked stall must not re-ping on a new idle reading"
+ assert [row["id"] for row in inc.list_incidents()] == [first["id"]]
+
+
def test_mark_incident_alerted_sets_state_never_resurrects(monkeypatch, tmp_path):
"""The post-delivery 'alerted' transition records that a ping went out,
and is a no-op on a closed (acked) incident — it can never resurrect one."""
diff --cc tests/gateway/test_control_socket.py
index f6663d1c2b2,6e5f585a438..a490e41182f
--- a/tests/gateway/test_control_socket.py
+++ b/tests/gateway/test_control_socket.py
@@@ -452,3 -452,32 +452,25 @@@ def test_runtime_inventory_prefers_sock
# supervisor comes from the gateway's own declaration, not a PID scan
assert gws[0].supervisor == "systemd"
assert gws[0].code_sha == "SHA555"
+
+
+ def test_windows_pipe_query_is_bounded_when_the_peer_never_answers(home: Path, monkeypatch):
+ """#132547: a pipe handle read cannot time out on its own; the query must still return None at its bound."""
+ import threading
+ import time
+
+ from gateway import control_socket
+
+ released = threading.Event()
+
- class _SilentPipe: # accepts the request, never answers
- def write(self, _data):
- return None
++ def _silent_native_client(_home, _request, _timeout): # accepts the request, never answers
++ released.wait(10)
++ return b""
+
- def read(self, _n):
- released.wait(10)
- return b""
-
- def close(self):
- return None
-
- monkeypatch.setattr(control_socket, "open", lambda *_a, **_k: _SilentPipe(), raising=False)
++ monkeypatch.setattr("gateway.runtime_bootstrap_windows.query_runtime_control", _silent_native_client)
+ start = time.monotonic()
+ try:
+ assert control_socket._query_windows_pipe(home, b"{}\n", 0.3) is None
+ assert time.monotonic() - start < 2.0
+ finally:
+ released.set()
diff --cc tests/gateway/test_webhook_adapter.py
index 27b6cfedb9c,443f2d0cd87..b7e39f1ed17
--- a/tests/gateway/test_webhook_adapter.py
+++ b/tests/gateway/test_webhook_adapter.py
@@@ -660,6 -689,43 +691,47 @@@ class TestSessionIsolation
ids = {ev.source.chat_id for ev in captured_events}
assert len(ids) == 2, "Each delivery must have a unique session chat_id"
+ @pytest.mark.asyncio
- async def test_delivery_tuple_is_an_unambiguous_session_identity(self):
- """Route, provider delivery ID, and profile form one collision-free identity."""
++ async def test_delivery_tuple_is_an_unambiguous_session_identity(self, monkeypatch):
++ """Route, provider delivery ID, and profile form one collision-free identity (captured at the
++ durable admission seam; the HTTP ack itself waits for that admission)."""
++ from gateway.platforms import webhook_ingress
+ adapter = _make_adapter()
+ captured_events = []
+
- async def _capture(event):
++ async def _capture(_adapter, event):
+ captured_events.append(event)
++ raise RuntimeError("captured before admission")
++
++ monkeypatch.setattr(webhook_ingress, "admit_producer", _capture)
+
- def _spawn(prompt, delivery_id, route, profile, deliver, chat_id, now):
- return adapter._spawn_agent_run(
++ def _admit(prompt, delivery_id, route, profile, deliver, chat_id, now):
++ return adapter._admit_agent_run(
+ {},
+ prompt,
+ delivery_id,
+ now,
+ route_config={"deliver": deliver, "deliver_extra": {"chat_id": chat_id}},
+ route_name=route,
+ profile=profile,
+ event_type="push",
+ )
+
- adapter.handle_message = _capture
+ await asyncio.gather(
- _spawn("high prompt", "external:d1", "build", "shared-profile", "telegram", "high-chat", 100.0),
- _spawn("low prompt", "d1", "build:external", "shared-profile", "discord", "low-chat", 101.0),
- _spawn("other prompt", "external:d1", "build", "other-profile", "slack", "other-chat", 102.0),
++ _admit("high prompt", "external:d1", "build", "shared-profile", "telegram", "high-chat", 100.0),
++ _admit("low prompt", "d1", "build:external", "shared-profile", "discord", "low-chat", 101.0),
++ _admit("other prompt", "external:d1", "build", "other-profile", "slack", "other-chat", 102.0),
+ )
+
+ events = {event.text: event for event in captured_events}
+ high, low, other = (events[prompt] for prompt in ("high prompt", "low prompt", "other prompt"))
+ assert len({high.source.chat_id, low.source.chat_id, other.source.chat_id}) == 3
+ assert (high.source.profile, high.source.user_id) == ("shared-profile", "webhook:build")
+ assert (low.source.profile, low.source.user_id) == ("shared-profile", "webhook:build:external")
+ assert (other.source.profile, other.source.user_id) == ("other-profile", "webhook:build")
+ assert [adapter._delivery_info[e.source.chat_id]["deliver_extra"]["chat_id"] for e in (high, low, other)] == [
+ "high-chat", "low-chat", "other-chat"]
+
# ===================================================================
# Silence-marker suppression
diff --cc tests/gateway/test_webhook_durable_destination.py
index c458a6cff20,00000000000..4b51897767f
mode 100644,000000..100644
--- a/tests/gateway/test_webhook_durable_destination.py
+++ b/tests/gateway/test_webhook_durable_destination.py
@@@ -1,195 -1,0 +1,198 @@@
+"""Admission owns the exact destination, never process-local send state."""
+import hashlib
+import hmac
+import json
+
+import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+
+from gateway.config import PlatformConfig
+from gateway.platforms.webhook import WebhookAdapter
+from tests.gateway.fixtures.webhook_route_authority import mount_authority
+
+
+async def test_destination_commits_with_input_and_survives_adapter_restart():
+ config = PlatformConfig(enabled=True, extra={'secret': 'owned-secret', 'routes': {
+ 'fixture': {'prompt': '{text}', 'deliver': 'github_comment',
+ 'deliver_extra': {'repo': '{repo}', 'pr_number': '{number}', 'token': 'private-secret'}}}})
+ adapter = WebhookAdapter(config)
+ app = web.Application()
+ mount_authority(app, adapter)
+ app.router.add_post('/webhooks/{route_name}', adapter._handle_webhook)
+ async with TestClient(TestServer(app)) as client:
+ payload = {'text': 'hello', 'repo': 'owned/repo', 'number': 7,
+ 'webhook_delivery': {'deliver': 'log'}, 'provenance': {'connector': 'forged'}}
+ body = json.dumps(payload).encode()
+ headers = {'X-GitHub-Delivery': 'durable-one', 'X-Hub-Signature-256':
+ 'sha256=' + hmac.new(b'owned-secret', body, hashlib.sha256).hexdigest()}
+ response = await client.post('/webhooks/fixture', data=body, headers=headers)
+ assert response.status == 202, await response.text()
+ runner = adapter._message_handler.__self__
+ row = runner.session_authority.db._read_one('SELECT payload_json FROM session_admissions')
+ retained = json.loads(row['payload_json'])['native_text_v1']['webhook_delivery']
+ assert retained['deliver'] == 'github_comment'
+ assert retained['deliver_extra'] == {'repo': 'owned/repo', 'pr_number': '7'}
+ # A fresh adapter must recover from SQLite, not a copied delivery cache.
+ replacement = WebhookAdapter(config)
+ runner.adapters[adapter.platform] = replacement
+ runner._wire_adapter_handlers(replacement)
+ replacement.gateway_runner = runner
+ calls = []
+ async def sink(content, delivery):
+ from gateway.platforms.base import SendResult
+ calls.append((content, delivery))
+ return SendResult(success=True)
+ replacement._deliver_github_comment = sink
- result = await replacement.send('webhook:fixture:durable-one', 'completed answer')
++ from gateway.platforms.webhook import _WebhookDeliveryIdentity
++ chat_id = _WebhookDeliveryIdentity.from_parts(None, 'fixture', 'durable-one').session_chat_id
++ result = await replacement.send(chat_id, 'completed answer')
+ assert result.success and calls[0][1] == retained
+ replacement._global_secret = 'rotated-secret'
- assert not (await replacement.send('webhook:fixture:durable-one', 'completed answer')).success
++ assert not (await replacement.send(chat_id, 'completed answer')).success
+ assert len(calls) == 1
+
+
+async def test_later_automation_completion_keeps_original_destination_resolvable():
+ """F28: a process/watch completion admitted for the same webhook chat never competes with the signed origin."""
+ config = PlatformConfig(enabled=True, extra={'secret': 'owned-secret', 'routes': {
+ 'fixture': {'prompt': '{text}', 'deliver': 'github_comment',
+ 'deliver_extra': {'repo': '{repo}', 'pr_number': '{number}'}}}})
+ adapter = WebhookAdapter(config)
+ app = web.Application()
+ mount_authority(app, adapter)
+ app.router.add_post('/webhooks/{route_name}', adapter._handle_webhook)
+ async with TestClient(TestServer(app)) as client:
+ body = json.dumps({'text': 'hello', 'repo': 'owned/repo', 'number': 7}).encode()
+ headers = {'X-GitHub-Delivery': 'automation-one', 'X-Hub-Signature-256':
+ 'sha256=' + hmac.new(b'owned-secret', body, hashlib.sha256).hexdigest()}
+ assert (await client.post('/webhooks/fixture', data=body, headers=headers)).status == 202
+ runner = adapter._message_handler.__self__
+ authority = runner.session_authority
+ calls = []
+ async def sink(content, delivery):
+ from gateway.platforms.base import SendResult
+ calls.append((content, delivery))
+ return SendResult(success=True)
+ adapter._deliver_github_comment = sink
- chat_id = 'webhook:fixture:automation-one'
++ from gateway.platforms.webhook import _WebhookDeliveryIdentity
++ chat_id = _WebhookDeliveryIdentity.from_parts(None, 'fixture', 'automation-one').session_chat_id
+ assert (await adapter.send(chat_id, 'first reply')).success
+ # The production completion path: an internal native_text_v1 admission on the original chat.
+ from gateway.platforms.event import MessageEvent
+ from gateway.session_envelope import restore_native
+ origin = restore_native(json.loads(authority.db._read_one(
+ 'SELECT payload_json FROM session_admissions')['payload_json']), runner)
+ entry = runner.session_store.lookup_by_session_key(runner.session_store._generate_session_key(origin.source))
+ completion = MessageEvent(text='[process finished]', source=origin.source, internal=True,
+ metadata={'gateway_session_key': entry.session_key,
+ 'gateway_session_id': entry.session_id})
+ await authority.admit_automation(adapter, completion, 'process:abc:1')
+ assert len(authority.db._read_all('SELECT admission_id FROM session_admissions')) == 2
+ assert (await adapter.send(chat_id, 'second reply')).success
+ assert [content for content, _ in calls] == ['first reply', 'second reply']
+ assert calls[0][1] == calls[1][1] == {'deliver': 'github_comment',
+ 'deliver_extra': {'repo': 'owned/repo', 'pr_number': '7'}}
+
+
+async def test_missing_destination_never_counts_as_log_delivery():
+ adapter = WebhookAdapter(PlatformConfig(enabled=True, extra={}))
+ assert not (await adapter.send('webhook:missing:receipt', 'completed answer')).success
+ adapter._delivery_info['explicit-log'] = {'deliver': 'log', 'deliver_extra': {}}
+ assert (await adapter.send('explicit-log', 'completed answer')).success
+
+
+def test_destination_retains_only_fields_consumed_by_sender():
+ from gateway.platforms.webhook_delivery import validate_destination
+ for target, fields in [('log', {}), ('github_comment', {'repo': 'owned/repo', 'pr_number': '7'}),
+ ('telegram', {'chat_id': '7', 'thread_id': '8', 'message_thread_id': '9'})]:
+ original = {'deliver': target, 'deliver_extra': {**fields, 'token': 'private-secret', 'unused': 'private-payload'}}
+ assert validate_destination(original) == {'deliver': target, 'deliver_extra': fields}
+ assert original['deliver_extra']['token'] == 'private-secret'
+
+
+async def test_exact_legacy_webhook_retry_keeps_receipt_without_inference():
+ config = PlatformConfig(enabled=True, extra={'secret': 'owned-secret', 'routes': {
+ 'fixture': {'prompt': '{text}', 'deliver': 'log'}}})
+ adapter = WebhookAdapter(config)
+ app = web.Application()
+ mount_authority(app, adapter)
+ app.router.add_post('/webhooks/{route_name}', adapter._handle_webhook)
+ async with TestClient(TestServer(app)) as client:
+ body = json.dumps({'text': 'legacy'}).encode()
+ headers = {'X-GitHub-Delivery': 'legacy-one', 'X-Hub-Signature-256':
+ 'sha256=' + hmac.new(b'owned-secret', body, hashlib.sha256).hexdigest()}
+ assert (await client.post('/webhooks/fixture', data=body, headers=headers)).status == 202
+ authority = adapter._message_handler.__self__.session_authority
+ row = authority.db._read_one('SELECT admission_id,payload_json FROM session_admissions')
+ legacy = json.loads(row['payload_json'])
+ legacy['native_text_v1'].pop('webhook_delivery')
+ legacy['native_text_v1'].pop('webhook_route')
+ encoded = json.dumps(legacy, sort_keys=True, separators=(',', ':'))
+ authority.db._execute_write(lambda conn: conn.execute(
+ 'UPDATE session_admissions SET payload_json=?, payload_digest=? WHERE admission_id=?',
+ (encoded, hashlib.sha256(encoded.encode()).hexdigest(), row['admission_id'])))
+ adapter._seen_deliveries.clear()
+ retry = await client.post('/webhooks/fixture', data=body, headers=headers)
+ assert retry.status == 200, await retry.text()
+ assert authority.db._read_one('SELECT payload_json FROM session_admissions')['payload_json'] == encoded
+ assert len(authority.db._read_all('SELECT admission_id FROM session_admissions')) == 1
+ # Receipt compatibility cannot authorize an invented destination or changed input.
+ from gateway.session_envelope import check_native_route, restore_native
+ from hermes_state_runtime import RuntimeStoreError
+ event = restore_native(legacy)
+ with pytest.raises(RuntimeStoreError):
+ await check_native_route(authority.runner, legacy,
+ authority.db._read_one('SELECT target_session_id FROM session_admissions')['target_session_id'],
+ event.source, adapter)
+ adapter._seen_deliveries.clear()
+ changed = json.dumps({'text': 'changed'}).encode()
+ headers['X-Hub-Signature-256'] = 'sha256=' + hmac.new(b'owned-secret', changed, hashlib.sha256).hexdigest()
+ assert (await client.post('/webhooks/fixture', data=changed, headers=headers)).status == 503
+
+
[email protected]('fence', ['draining', 'epoch'])
+async def test_fenced_webhook_retry_only_observes_existing_receipt(fence):
+ config = PlatformConfig(enabled=True, extra={'secret': 'owned-secret', 'routes': {
+ 'fixture': {'prompt': '{text}', 'deliver': 'log'}}})
+ adapter = WebhookAdapter(config)
+ app = web.Application()
+ mount_authority(app, adapter)
+ app.router.add_post('/webhooks/{route_name}', adapter._handle_webhook)
+ async with TestClient(TestServer(app)) as client:
+ body = json.dumps({'text': 'already committed'}).encode()
+ headers = {'X-GitHub-Delivery': 'observed-one', 'X-Hub-Signature-256':
+ 'sha256=' + hmac.new(b'owned-secret', body, hashlib.sha256).hexdigest()}
+ assert (await client.post('/webhooks/fixture', data=body, headers=headers)).status == 202
+ authority = adapter._message_handler.__self__.session_authority
+ if fence == 'draining':
+ authority.runner._draining = True
+ else:
+ from hermes_state_runtime import begin_runtime_epoch
+ begin_runtime_epoch(authority.db, instance_id='replacement-owner')
+ schedules = []
+ authority._schedule = schedules.append
+ async def forbidden_admission(event):
+ pytest.fail('observing a receipt must not admit new work')
+ original_admit = authority.admit_native
+ authority.admit_native = forbidden_admission
+ with authority.db._read_ctx() as conn:
+ before = tuple(conn.iterdump())
+ adapter._seen_deliveries.clear()
+ response = await client.post('/webhooks/fixture', data=body, headers=headers)
+ assert response.status == 200, await response.text()
+ with authority.db._read_ctx() as conn:
+ assert tuple(conn.iterdump()) == before
+ assert schedules == []
+ row = authority.db._read_one('SELECT status FROM session_admissions')
+ assert row['status'] == 'queued'
+ authority.admit_native = original_admit
+ headers['X-GitHub-Delivery'] = 'never-accepted'
+ assert (await client.post('/webhooks/fixture', data=body, headers=headers)).status == 503
+ assert len(authority.db._read_all('SELECT admission_id FROM session_admissions')) == 1
+ assert schedules == []
diff --cc tests/gateway/test_webhook_integration.py
index ae3048bff99,7e1cccf9310..0478d3bcced
--- a/tests/gateway/test_webhook_integration.py
+++ b/tests/gateway/test_webhook_integration.py
@@@ -187,11 -185,13 +188,13 @@@ class TestCrossPlatformDelivery
headers={"X-GitHub-Delivery": "alert-001"},
)
assert resp.status == 202
-
- # The adapter should have stored delivery info under the event's opaque session identity.
- assert len(adapter._delivery_info) == 1
- chat_id = next(iter(adapter._delivery_info))
-
- # Now call send() as if the agent has finished
- result = await adapter.send(chat_id, "I've acknowledged the alert.")
+ runner = adapter._message_handler.__self__
+ runner.adapters[Platform.TELEGRAM] = mock_tg_adapter
+ adapter.gateway_runner = runner
- chat_id = "webhook:alerts:alert-001"
++ # The adapter stored delivery info under the event's opaque session identity.
++ assert len(adapter._delivery_info) == 1
++ chat_id = next(iter(adapter._delivery_info))
+ result = await adapter.send(chat_id, "I've acknowledged the alert.")
assert result.success is True
mock_tg_adapter.send.assert_awaited_once_with(
diff --cc tests/hermes_cli/test_config.py
index 0e117b57798,ff609c9879b..bef77431e79
--- a/tests/hermes_cli/test_config.py
+++ b/tests/hermes_cli/test_config.py
@@@ -996,28 -1039,6 +1039,28 @@@ class TestCuratorFasterPrune
assert raw["curator"]["archive_after_days"] == 180
+class TestRetiredBotChatDeliveryTimeout:
- def test_v45_drops_bot_chat_delivery_timeout_with_a_note(self, tmp_path, monkeypatch):
++ def test_v50_drops_bot_chat_delivery_timeout_with_a_note(self, tmp_path, monkeypatch):
+ """The removed cron knob is dropped from existing configs with a one-time note;
+ sibling cron settings and the rest of the file survive untouched."""
+ from hermes_cli.config import DEFAULT_CONFIG
+ from hermes_cli.config_migrations import run_migrations
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(yaml.safe_dump({
- "_config_version": 45,
++ "_config_version": 49,
+ "cron": {"bot_chat_delivery_timeout_seconds": 900, "max_parallel_jobs": 2},
+ }), encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ results = {"env_added": [], "config_added": [], "warnings": []}
- run_migrations(45, results, quiet=True)
++ run_migrations(49, results, quiet=True)
+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+ assert "bot_chat_delivery_timeout_seconds" not in raw["cron"]
+ assert raw["cron"]["max_parallel_jobs"] == 2
+ assert any("bot_chat_delivery_timeout_seconds" in note for note in results["config_added"])
+ assert "bot_chat_delivery_timeout_seconds" not in DEFAULT_CONFIG["cron"]
+
+
class TestCustomProviderCompatibility:
"""Custom provider compatibility across legacy and v12+ config schemas.
diff --cc tests/hermes_cli/test_single_query_session_finalize.py
index 1199664939a,d1825952775..9c72fd9830d
--- a/tests/hermes_cli/test_single_query_session_finalize.py
+++ b/tests/hermes_cli/test_single_query_session_finalize.py
@@@ -50,9 -55,71 +55,69 @@@ def test_finalize_single_query_runs_cle
cli._finalize_single_query(fake_cli)
- assert calls == ["finalize", "cleanup", "release"]
+ assert calls == ["finalize", "release", "cleanup"]
+
+
+ def test_finalize_settles_session_before_a_successor_can_take_over(tmp_path, monkeypatch):
+ """P1 handoff race: a successor that acquires the session DURING the
+ predecessor's exit linger must never receive the predecessor's stale
+ ``cli_close`` end-stamp — settlement (flush incl. end_session) must complete
+ before the lease is released.
+
+ Exercises the real seam with a real SessionDB and a real lease: the linger is
+ patched to play the successor (acquire the freed lease, reopen the row), and
+ the final assertion is that the successor's open interval survives the
+ predecessor's whole finalize. On the unsafe order (release → linger → flush)
+ the flush's unconditional ``end_session`` stamps the successor's interval and
+ this test fails."""
+ from hermes_cli import active_sessions
+ from hermes_state import SessionDB
+
+ home = tmp_path / ".hermes"
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid = "s1"
+ db.create_session(sid, "cli")
+ lease_a, message = active_sessions.try_acquire_active_session(
+ session_id=sid, surface="cli", config={}, metadata={"live_session_id": sid}
+ )
+ assert lease_a is not None, message
+
+ agent_a = SimpleNamespace(
+ session_id=sid, _session_db=db, _session_messages=[],
+ _persist_disabled=False, _persist_session=lambda *a, **k: None,
+ )
+ cli_a = SimpleNamespace(
+ agent=agent_a, session_id=sid, conversation_history=[], _session_db=db,
+ _release_active_session=lease_a.release,
+ )
+
+ taken_over: dict[str, Any] = {}
+
+ def linger_with_takeover(_cli):
+ # The successor arrives mid-linger. Early admission must hold (the point of
+ # the PR)…
+ lease_b, msg_b = active_sessions.try_acquire_active_session(
+ session_id=sid, surface="cli", config={}, metadata={"live_session_id": sid}
+ )
+ assert lease_b is not None, f"successor could not acquire during the linger: {msg_b}"
+ taken_over["lease_b"] = lease_b
+ # …and it resumes the row (the predecessor's settlement already ended it).
+ db.reopen_session(sid)
+
+ monkeypatch.setattr(cli, "_wait_for_oneshot_background_completions", linger_with_takeover)
+ monkeypatch.setattr(cli, "_notify_single_query_session_finalize", lambda _c: None)
+ monkeypatch.setattr(cli, "_run_cleanup", lambda **_k: None)
+
+ cli._finalize_single_query(cli_a)
+
+ row = db.get_session(sid)
+ assert row is not None and row["ended_at"] is None, (
+ "successor's open interval was end-stamped by the predecessor's finalize"
+ )
+ taken_over["lease_b"].release()
-
-
def test_notify_single_query_session_finalize_uses_agent_session(monkeypatch):
calls = []
fake_agent = SimpleNamespace(session_id="agent-session", platform="cli")
diff --cc tests/hermes_cli/test_status.py
index 10d00e6284f,320138dd318..432d6f97b52
--- a/tests/hermes_cli/test_status.py
+++ b/tests/hermes_cli/test_status.py
@@@ -205,24 -205,67 +205,68 @@@ def test_show_status_reports_gateway_se
monkeypatch.setattr(auth_mod, "get_xai_oauth_auth_status", lambda: {}, raising=False)
monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda exclude_pids=None: [], raising=False)
- class _FakeDB:
- def __init__(self, **_kwargs):
- pass
-
- def list_gateway_sessions(self, active_only=True):
- return [
- {"id": "gw-old", "last_active": time.time() - 7200},
- {"id": "gw-new", "last_active": time.time() - 90},
- ]
-
- def close(self):
- return None
-
- monkeypatch.setattr(hermes_state, "SessionDB", _FakeDB)
+ import sqlite3
+ from contextlib import closing
+
+ path = tmp_path / "state.db"
+ db = hermes_state.SessionDB(db_path=path)
+ for sid in ("gw-old", "gw-new"):
+ db.create_session(sid, "telegram")
+ db.close()
+ with closing(sqlite3.connect(path)) as conn:
+ for sid, age in (("gw-old", 7200), ("gw-new", 90)):
+ conn.execute("UPDATE sessions SET session_key=?, started_at=?, last_activity_at=? WHERE id=?",
+ (sid, time.time() - age, time.time() - age, sid))
+ conn.commit()
+ before = path.read_bytes()
- status_mod.show_status(SimpleNamespace(all=False, deep=False))
+ status_mod.show_status(SimpleNamespace(full=True, deep=False))
output = capsys.readouterr().out
assert "Active: 2 session(s)" in output
assert "Last activity:" in output
assert "1m ago" in output
+ assert path.read_bytes() == before
+
+
+ def _status_args(*argv):
+ import argparse
+ from hermes_cli.subcommands.status import build_status_parser
+
+ parser = argparse.ArgumentParser()
+ build_status_parser(parser.add_subparsers(), cmd_status=None)
+ return parser.parse_args(["status", *argv])
+
+
+ def test_status_defaults_to_summary_and_full_or_all_prints_every_section(monkeypatch, capsys, tmp_path):
+ import hermes_cli.model_switch as model_switch
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(model_switch, "list_authenticated_providers", lambda **_: [{"name": "Acme AI"}])
+
+ show_status(_status_args())
+ summary = capsys.readouterr().out
+ assert "Providers: Acme AI" in summary
+ assert "◆ Environment" not in summary
+ for flag in ("--full", "--all"):
+ show_status(_status_args(flag))
+ assert "◆ Environment" in capsys.readouterr().out
+
+
+ def test_platform_rows_follow_the_gateway_verdict_not_check_fn(monkeypatch, capsys, tmp_path):
+ """check_fn only says the SDK imports; each platform gets ONE row, judged like the summary line."""
+ import gateway.config as gateway_config
+ from gateway.platform_registry import platform_registry
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ entries = [SimpleNamespace(name=n, label=n.title(), check_fn=lambda: True) for n in ("telegram", "discord")]
+ monkeypatch.setattr(platform_registry, "plugin_entries", lambda: entries)
+ monkeypatch.setattr(gateway_config, "load_gateway_config", lambda: SimpleNamespace(
+ platforms={}, get_connected_platforms=lambda: [SimpleNamespace(value="telegram")]))
+
+ show_status(SimpleNamespace(full=True, deep=False))
+ out = capsys.readouterr().out
+ rows = {name: [line for line in out.splitlines() if line.strip().startswith(name)] for name in ("Telegram", "Discord")}
+ assert [("not configured" in line) for line in rows["Discord"]] == [True]
+ assert [("not configured" in line) for line in rows["Telegram"]] == [False]
+ show_status(SimpleNamespace())
+ assert "Platforms: Telegram\n" in capsys.readouterr().out
diff --cc tests/hermes_state/test_fts_trigram_cron_exclusion.py
index e9490319b44,3243c8771f1..560ada92c82
--- a/tests/hermes_state/test_fts_trigram_cron_exclusion.py
+++ b/tests/hermes_state/test_fts_trigram_cron_exclusion.py
@@@ -7,8 -7,12 +7,12 @@@ import sqlite
import pytest
from hermes_state import SessionDB
-from hermes_state_common import FTS_TRIGRAM_SQL
+from hermes_state_common import FTS_TRIGRAM_SQL, SCHEMA_VERSION
+ # The trigram cron-exclusion rebuild is the v30 data migration: a store one version behind IT, not one
+ # behind the current SCHEMA_VERSION (later migrations do not re-run it).
+ _PRE_TRIGRAM_EXCLUSION_VERSION = 29
+
@pytest.fixture
def db(tmp_path):
@@@ -136,13 -136,12 +140,19 @@@ def test_existing_external_layout_rebui
migrated = SessionDB(db_path=db_path)
try:
assert _trigram_rowids(migrated) == {cli_id}
+ view_sql = migrated._conn.execute(
+ "SELECT sql FROM sqlite_master "
+ "WHERE type = 'view' AND name = 'messages_fts_trigram_src'"
+ ).fetchone()[0]
+ assert "sessions" in view_sql
+ assert "cron" in view_sql
+ assert [row["id"] for row in migrated.search_messages("互迁移")] == [cli_id]
+ assert [row["id"] for row in migrated.search_messages(
+ "定时迁移内容", source_filter=["cron"]
+ )] == [cron_id]
+ new_cron_id = migrated.append_message("cron", role="user", content="新增定时内容")
+ assert new_cron_id not in _trigram_rowids(migrated)
+ assert migrated._conn.execute("SELECT version FROM schema_version").fetchone()[0] == SCHEMA_VERSION
migrated._conn.execute(
"INSERT INTO messages_fts_trigram(messages_fts_trigram) VALUES('integrity-check')"
)
diff --cc tests/tools/test_bot_live_owner_delivery.py
index 5a772adc46a,8eba4a77358..5836755f218
--- a/tests/tools/test_bot_live_owner_delivery.py
+++ b/tests/tools/test_bot_live_owner_delivery.py
@@@ -63,14 -55,40 +63,34 @@@ def test_same_envelope_id_admits_once_a
assert path.stat().st_mode & 0o077 == 0
-def test_cancel_queued_delivery_fences_claim_and_preserves_terminal_result(tmp_path):
- from tools import bot_live_delivery as mailbox
++def test_cancel_queued_delivery_cancels_only_an_unadmitted_receipt(tmp_path, monkeypatch):
++ """main's cancel fence on the owner seam: a legacy unadmitted queued receipt is cancelled
++ once (idempotent); an authority admission is never cancelled from the mailbox."""
++ key = "3" * 32
++ with mailbox._locked(tmp_path) as root:
++ mailbox._write(root / f"{key}.json", dict(
++ delivery_id=key, id=key, status="queued", message="first", created_at=1, sequence=1,
++ owner=_owner(tmp_path), **_owner(tmp_path)))
++ cancelled = mailbox.cancel_queued_delivery(tmp_path, key, error="owner closed", reason="runtime_offline")
++ assert cancelled["status"] == "cancelled" and cancelled["error"] == "owner closed"
++ assert mailbox.cancel_queued_delivery(tmp_path, key, error="again", reason="runtime_offline") == cancelled
+
- 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, "first", delivery_id="3" * 32)
- cancelled = mailbox.cancel_queued_delivery(
- tmp_path, queued["delivery_id"], error="owner closed", reason="runtime_offline")
- assert cancelled is not None
- assert cancelled["status"] == "cancelled"
- assert cancelled["error"] == "owner closed"
- assert mailbox.claim_pending_delivery(tmp_path, owner) is None
- assert mailbox.deliver_to_live_owner(tmp_path, owner, "first", delivery_id="3" * 32) == cancelled
- assert mailbox.cancel_queued_delivery(
- tmp_path, queued["delivery_id"], error="owner closed", reason="runtime_offline") == cancelled
-
- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "second", delivery_id="4" * 32)
- claimed = mailbox.claim_pending_delivery(tmp_path, owner)
- assert claimed is not None
- assert claimed["delivery_id"] == queued["delivery_id"]
- assert mailbox.cancel_queued_delivery(
- tmp_path, queued["delivery_id"], error="owner closed", reason="runtime_offline") == claimed
- settled = mailbox.complete_delivery(tmp_path, queued["delivery_id"], status="settled", reply="PONG")
- assert mailbox.cancel_queued_delivery(
- tmp_path, queued["delivery_id"], error="owner closed", reason="runtime_offline") == settled
++ authority = _FakeAuthority()
++ monkeypatch.setattr(mailbox, "authority_delivery", authority)
++ admitted = mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "second", delivery_id="4" * 32)
++ kept = mailbox.cancel_queued_delivery(tmp_path, admitted["delivery_id"], error="x", reason="runtime_offline")
++ assert kept["status"] != "cancelled"
++ assert mailbox.read_delivery_result(tmp_path, admitted["delivery_id"])["status"] == "queued"
+
+
@pytest.mark.parametrize("intent_state", ["new", "existing", "raced"])
def test_live_dm_bom_readers_preserve_pinned_intent(tmp_path, monkeypatch, intent_state):
- from pathlib import Path
-
- from hermes_cli.active_sessions import try_acquire_active_session
+ """Main 61dc26cd7d9 on the canonical door: a BOM-prefixed DM payload and a BOM-prefixed pinned
+ intent read back intact, a pinned intent is never replaced by a rewritten payload, and a
+ damaged intent retains its evidence instead of retrying a transport."""
+ import hermes_cli.gateway_runtime as runtime
from hermes_state import SessionDB
- from tools import bot_live_delivery as mailbox, bot_mode_dm
+ from tools import bot_mode_dm
db = SessionDB(db_path=tmp_path / "state.db")
db.create_session(session_id="chat", source="cli")
diff --cc tests/tools/test_bot_mode_dm.py
index 9321b8852fc,c888b94ec41..e3bd2e95418
--- a/tests/tools/test_bot_mode_dm.py
+++ b/tests/tools/test_bot_mode_dm.py
@@@ -710,8 -615,11 +711,10 @@@ def test_live_dm_runner_retry_never_ree
home = _managed_home(tmp_path)
target = home / "profiles" / "researcher"
monkeypatch.setenv("HERMES_HOME", str(home))
- owner = dict(profile_home=str(target), session_id="bot", lease_id="lease", live_session_id="live")
- live_owner = {"owner": owner}
- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: live_owner["owner"])
+ authority = _canonical_target(monkeypatch, target)
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0)
++ # The authority still holds the admission, so the runner waits to its absolute deadline.
+ monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
++ monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_MAX_SECONDS", 0.05)
monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("must not launch a model turn"))
dm_file = tmp_path / "message.txt"
dm_file.write_text("hello", encoding="utf-8")
@@@ -732,16 -658,174 +735,61 @@@
assert dm_file.read_text(encoding="utf-8") == "hello"
-def test_live_dm_wait_reports_reply_after_initial_wait_budget(tmp_path, monkeypatch, capsys):
- """A retained live receipt must still deliver its reply after the old 300 s boundary."""
++def _admitted_live_dm(tmp_path, monkeypatch, delivery_id):
++ """One DM admitted to a ready (fake) authority, with the wait loop sped up."""
+ from tools import bot_live_delivery as live
+
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="a" * 32)
++ authority = _canonical_target(monkeypatch, tmp_path)
++ owner = live.find_canonical_live_owner(tmp_path)
++ record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id=delivery_id)
+ monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
+ monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: owner)
++ return live, authority, record
+
- def settle_later():
- time.sleep(0.05)
- claimed = live.claim_pending_delivery(tmp_path, owner)
- assert claimed is not None
- live.complete_delivery(tmp_path, claimed["delivery_id"], status="settled", reply="PONG")
+
- settling = threading.Thread(target=settle_later)
++def test_live_dm_wait_reports_reply_after_initial_wait_budget(tmp_path, monkeypatch, capsys):
++ """A retained admission still delivers its reply after the first wait window (main a94b9758313)."""
++ live, authority, record = _admitted_live_dm(tmp_path, monkeypatch, "a" * 32)
++ settling = threading.Timer(0.05, lambda: authority.records[record["delivery_id"]].update(
++ status="settled", reply="PONG"))
+ settling.start()
+ try:
+ exit_code = bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"])
+ finally:
+ settling.join(timeout=2)
-
+ notice = json.loads(capsys.readouterr().out)
+ assert exit_code == 0
- assert notice["status"] == "settled"
- assert notice["reply"] == "PONG"
-
-
-def test_live_dm_wait_releases_queued_runner_when_pinned_owner_is_gone(tmp_path, monkeypatch, capsys):
- from tools import bot_live_delivery as live
-
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="c" * 32)
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: None)
-
- assert bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"]) == 1
- notice = json.loads(capsys.readouterr().out)
- assert notice["status"] == "cancelled"
- final = live.read_delivery_result(tmp_path, record["delivery_id"])
- assert final is not None and final["status"] == "cancelled"
-
-
-def test_live_dm_wait_rechecks_receipt_when_owner_disappears_at_claim(tmp_path, monkeypatch, capsys):
- from tools import bot_live_delivery as live
-
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="f" * 32)
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
-
- def settle_during_owner_check(_home):
- claimed = live.claim_pending_delivery(tmp_path, owner)
- assert claimed is not None
- live.complete_delivery(tmp_path, claimed["delivery_id"], status="settled", reply="PONG")
- return None
-
- monkeypatch.setattr(live, "find_canonical_live_owner", settle_during_owner_check)
- assert bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"]) == 0
- notice = json.loads(capsys.readouterr().out)
- assert notice["status"] == "settled"
- assert notice["reply"] == "PONG"
-
-
-def test_live_dm_wait_keeps_claimed_turn_until_it_settles(tmp_path, monkeypatch, capsys):
- """An owner gone after its claim still gets one more window to settle the in-flight turn."""
- from tools import bot_live_delivery as live
-
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="d" * 32)
- assert live.claim_pending_delivery(tmp_path, owner) is not None
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.5)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
- settling = threading.Timer(0.02, lambda: live.complete_delivery(
- tmp_path, record["delivery_id"], status="settled", reply="PONG"))
-
- def owner_gone_then_settle(_home):
- settling.start()
- return None
-
- monkeypatch.setattr(live, "find_canonical_live_owner", owner_gone_then_settle)
- try:
- exit_code = bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"])
- finally:
- settling.join(timeout=2)
-
- assert exit_code == 0
- notice = json.loads(capsys.readouterr().out)
- assert notice["status"] == "settled"
- assert notice["reply"] == "PONG"
-
-
-def test_live_dm_wait_releases_claimed_runner_after_owner_is_gone(tmp_path, monkeypatch, capsys):
- from tools import bot_live_delivery as live
-
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="1" * 32)
- assert live.claim_pending_delivery(tmp_path, owner) is not None
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: None)
-
- outcomes = []
- waiting = threading.Thread(target=lambda: outcomes.append(bot_mode_dm._wait_live_dm(
- str(tmp_path), record["delivery_id"])), daemon=True)
- waiting.start()
- waiting.join(timeout=1)
- stopped_with_unknown_outcome = not waiting.is_alive()
- if not stopped_with_unknown_outcome:
- live.complete_delivery(tmp_path, record["delivery_id"], status="failed", error="test cleanup")
- waiting.join(timeout=2)
-
- assert stopped_with_unknown_outcome, "a vanished owner must not retain the runner indefinitely"
- assert outcomes == [0]
- notice = json.loads(capsys.readouterr().out)
- assert notice["status"] == "claimed"
- final = live.read_delivery_result(tmp_path, record["delivery_id"])
- assert final is not None and final["status"] == "claimed"
-
-
[email protected]("status", ["queued", "claimed"])
-def test_live_dm_wait_releases_runner_when_owner_lookup_keeps_failing(tmp_path, monkeypatch, capsys, status):
- """A lookup that always raises is an owner that cannot be confirmed: bounded, never cancelled."""
- from tools import bot_live_delivery as live
-
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="2" * 32)
- if status == "claimed":
- assert live.claim_pending_delivery(tmp_path, owner) is not None
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
-
- def lookup_fails(_home):
- raise OSError("registry locked")
++ assert (notice["status"], notice["reply"]) == ("settled", "PONG")
+
- monkeypatch.setattr(live, "find_canonical_live_owner", lookup_fails)
- assert bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"]) == 0
- notice = json.loads(capsys.readouterr().out)
- assert notice["status"] == status
- assert "Do not resend" in notice["detail"]
- assert live.read_delivery_result(tmp_path, record["delivery_id"])["status"] == status
-
-
-def test_live_dm_wait_stops_at_its_deadline_while_the_owner_holds_the_receipt(tmp_path, monkeypatch, capsys):
- """A live owner that never claims (stalled consumer) or never settles still releases the runner."""
- from tools import bot_live_delivery as live
+
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="3" * 32)
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
[email protected]("lookup", ["raises", "holds"])
++def test_live_dm_wait_is_bounded_and_never_cancels_an_admission(tmp_path, monkeypatch, capsys, lookup):
++ """An authority that cannot be confirmed, or one that never settles, releases the runner with a
++ do-not-resend pending notice; the admitted receipt is never cancelled (main a6509d6b8fd)."""
++ live, _authority, record = _admitted_live_dm(tmp_path, monkeypatch, "2" * 32)
+ monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_MAX_SECONDS", 0.1)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: owner)
++ if lookup == "raises":
++ def lookup_fails(_home):
++ raise ValueError("profile authority is not ready")
+
++ monkeypatch.setattr(live, "find_canonical_live_owner", lookup_fails)
+ assert bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"]) == 0
+ notice = json.loads(capsys.readouterr().out)
+ assert notice["status"] == "queued"
+ assert "Do not resend" in notice["detail"]
++ assert live.read_delivery_result(tmp_path, record["delivery_id"])["status"] == "queued"
+
+
-# ── plaintext tempfile lifecycle ─────────────────────────────────────────────
+# ── plaintext tempfile lifecycle (peer stdin transport) ─────────────────────
[email protected]("stdin_file", [False, True])
@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"])
-def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file, encoding):
+def test_peer_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, encoding):
+ # Main 61dc26cd7d9 also ran the local query-file transport here; that lane has no local
+ # child any more (a local delivery without a canonical owner is refused and retained,
+ # see test_local_delivery_runner_surfaces_refusal_and_retains_payload), so only the peer
+ # stdin transport keeps the file for the child.
+ stdin_file = True
dm_file = tmp_path / "message with spaces.txt"
dm_file.write_bytes("secret λ $(not shell)".encode(encoding))
observed = tmp_path / "observed.txt"
@@@ -1112,21 -1233,32 +1160,24 @@@ def test_cleanup_sweeps_stale_live_inte
def test_settled_live_wait_unlinks_the_intent_but_a_pending_one_keeps_it(tmp_path, monkeypatch, capsys):
-- from tools import bot_live_delivery as live
--
dm_file = tmp_path / "dm-x.txt"
dm_file.write_text("secret plaintext", encoding="utf-8")
intent = tmp_path / "dm-x.txt.live.json"
intent.write_text("{}", encoding="utf-8")
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0)
-
- monkeypatch.setattr(live, "read_delivery_result", lambda home, did: {"status": "queued"})
- assert bot_mode_dm._wait_live_dm(str(tmp_path), "d1", dm_file=dm_file) == 0
- assert intent.exists(), "a pending delivery may still be retried from the same intent"
- assert dm_file.exists()
-
- monkeypatch.setattr(live, "read_delivery_result", lambda home, did: {"status": "settled", "reply": "ok"})
- assert bot_mode_dm._wait_live_dm(str(tmp_path), "d1", dm_file=dm_file) == 0
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="b" * 32)
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: owner)
++ _live, authority, record = _admitted_live_dm(tmp_path, monkeypatch, "b" * 32)
+
+ outcomes = []
+ waiting = threading.Thread(target=lambda: outcomes.append(bot_mode_dm._wait_live_dm(
+ str(tmp_path), record["delivery_id"], dm_file=dm_file)), daemon=True)
+ waiting.start()
+ time.sleep(0.05)
+ pending_kept = waiting.is_alive() and intent.exists() and dm_file.exists()
- claimed = live.claim_pending_delivery(tmp_path, owner)
- assert claimed is not None
- live.complete_delivery(tmp_path, claimed["delivery_id"], status="settled", reply="ok")
++ authority.records[record["delivery_id"]].update(status="settled", reply="ok")
+ waiting.join(timeout=2)
+
+ assert pending_kept, "a pending delivery keeps its intent while the runner waits"
+ assert not waiting.is_alive()
+ assert outcomes == [0]
assert not intent.exists()
assert not dm_file.exists(), "the dm .txt holds the same plaintext as the settled intent"
diff --cc tests/tui_gateway/test_notification_turn_release.py
index 5ef162ad972,248d610bf0b..d8db3411630
--- a/tests/tui_gateway/test_notification_turn_release.py
+++ b/tests/tui_gateway/test_notification_turn_release.py
@@@ -108,8 -108,10 +108,9 @@@ def test_the_poller_thread_survives_a_d
mailbox; an exception out of one event's dispatch used to end the thread for good."""
events: queue.Queue = queue.Queue()
events.put({"type": "completion", "session_id": "proc_a"})
- monkeypatch.setattr("tools.process_registry.process_registry", SimpleNamespace(completion_queue=events))
+ monkeypatch.setattr("tools.process_registry.process_registry",
+ SimpleNamespace(completion_queue=events, restore_completions=lambda: 0))
- for name in ("_poll_bot_live_delivery_guarded", "_maybe_fire_tui_loop_tick",
- "_maybe_fire_tui_heartbeat_tick", "_notif_poll_kanban"):
+ for name in ("_maybe_fire_tui_loop_tick", "_maybe_fire_tui_heartbeat_tick", "_notif_poll_kanban"):
monkeypatch.setattr(server, name, lambda *a, **k: None)
stop = threading.Event()
handled: list = []
diff --cc tools/async_delegation.py
index 0be0098e060,643a890c6e2..3ba87095961
--- a/tools/async_delegation.py
+++ b/tools/async_delegation.py
@@@ -331,11 -321,8 +333,13 @@@ def restore_undelivered_completions(tar
ownership, otherwise a brand-new session adopts a dead session's delegation results seconds after boot
(#64484).
"""
+ from agent.runtime_session_store import is_worker_process
+ if is_worker_process():
+ # The ordinary owner restores delivery-only results; a compute import
+ # must neither reap that owner's ledger nor steal its delivery queue.
+ return 0
+ if not _db_path().exists():
+ return 0 # nothing to replay; a replay must not create (or migrate) the ledger (#123265)
recover_abandoned_delegations()
now = time.time()
with _DB_LOCK, _transaction() as conn:
@@@ -362,6 -349,6 +366,11 @@@ def _replay_pending(conn, rows, target_
"(cap %.1fh); terminally dropping the replay (result remains queryable).",
delegation_id, (now - age_basis) / 3600.0, _MAX_COMPLETION_REPLAY_AGE_S / 3600.0)
continue
++ with _orphan_lock:
++ if (home, delegation_id) in _offered:
++ # The owner's explicit startup replay and the first-consume replay
++ # (process_registry.restore_completions) may both run: offer once.
++ continue
evt = json.loads(payload)
if isinstance(evt, dict):
evt["restored"] = True
diff --cc tools/bot_live_delivery.py
index 9f02b3d4ff9,2fac2a9c183..ef84980d3b5
--- a/tools/bot_live_delivery.py
+++ b/tools/bot_live_delivery.py
@@@ -236,23 -207,70 +236,36 @@@ def deliver_to_live_owner
pinned = _owner(profile_home, owner)
if not isinstance(message, str):
raise ValueError("message must be a string")
- key = _delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex)
- with _locked(profile_home) as root:
- path = root / f"{key}.json"
- existing = _read(path)
- if existing is not None:
- if (existing["owner"] != pinned or existing["message"] != message or existing.get("author") != author
- or existing.get("notification_category", "result") != notification_category):
- raise ValueError("delivery id already belongs to a different payload")
- return existing
- record = dict(delivery_id=key, id=key, owner=pinned, **pinned,
- message=message, status="queued", created_at=time.time_ns(),
- sequence=_next_sequence(root), **({"author": dict(author)} if author else {}))
- if notification_category == "diagnostic":
- record["notification_category"] = notification_category
- _write(path, record)
- return record
-
-
-def _matches(home: Path | str, record: dict, owner: dict) -> bool:
- pinned = record["owner"]
- if any(pinned[key] != owner[key] for key in ("profile_home", "lease_id", "live_session_id")):
- return False
- if pinned["session_id"] == owner["session_id"]:
- return True
- from hermes_state import SessionDB
-
- db = SessionDB(db_path=Path(home) / "state.db", read_only=True)
- try:
- return db.get_compression_tip(pinned["session_id"]) == owner["session_id"]
- finally:
- db.close()
+ if notification_category not in ('result', 'diagnostic'):
+ raise ValueError("invalid notification category")
+ home = Path(profile_home).resolve()
- return authority_delivery(home, dict(id=_delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex),
++ category = {"notification_category": "diagnostic"} if notification_category == "diagnostic" else {}
++ # The authority refuses a category-changing replay (admission_conflict), so the admitted
++ # category is the producer's; echo it so callers can check the receipt's identity.
++ return {**authority_delivery(home, dict(id=_delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex),
+ profile=home.name if home.parent.name == "profiles" else "default",
+ message=message, **({"session_id": pinned["session_id"]} if pinned["session_id"] else {}),
- **({"author": dict(author)} if author else {}),
- **({"notification_category": "diagnostic"} if notification_category == "diagnostic" else {})))
++ **({"author": dict(author)} if author else {}), **category)), **category}
+
+
+ def owner_holds_delivery(profile_home: Path | str, record: dict) -> bool:
- """Whether the canonical live owner is still one that could claim ``record``."""
- owner = find_canonical_live_owner(profile_home)
- return owner is not None and _matches(profile_home, record, owner)
++ """Whether the profile authority still holds ``record`` (main's bounded DM wait asks this).
++
++ An admission lives in the authority's durable FIFO, so it is held while the authority is
++ reachable; an unreachable one raises (outcome unknown, never cancelled). Only an unadmitted
++ legacy record whose profile has no store is provably ownerless.
++ """
++ owner = find_canonical_live_owner(profile_home) # raises while the authority is unreachable
++ return owner is not None or bool(record.get("admission_id"))
-def claim_pending_delivery(
- profile_home: Path | str, owner: dict[str, Any],
-) -> dict[str, Any] | None:
- """Claim oldest matching input exactly once; caller supplies its current lease.
+def claim_pending_delivery(profile_home, owner):
+ """Retired UI poller: only session_bot may migrate and admit queued records.
- A lease transfer across compression is accepted only along the original
- stored session's compression chain. A new lease/live session cannot steal it.
- Caller must hold its normal turn-admission guard before invoking this.
+ Keep this refusal until the legacy notification poller's call site is removed.
+ A previously claimed record can still publish its terminal receipt below.
"""
- current = _owner(profile_home, owner)
- if not _root(profile_home).is_dir():
- return None
- with _locked(profile_home) as root:
- pending = []
- for path in root.glob("*.json"):
- record = _scan_read(path)
- if record is not None and record["status"] == "queued" and _matches(profile_home, record, current):
- pending.append(record)
- if not pending:
- return None
- record = min(pending, key=lambda item: (
- item.get("sequence", item["created_at"]), item["delivery_id"]))
- record.update(status="claimed", claimed_at=time.time_ns())
- _write(root / f"{record['delivery_id']}.json", record)
- return record
+ return None
def complete_delivery(
@@@ -280,18 -298,28 +293,39 @@@
return record
+ def cancel_queued_delivery(
+ profile_home: Path | str, delivery_id: str, *, error: str, reason: str,
+ ) -> dict[str, Any] | None:
+ """Cancel an ownerless queued receipt without racing a consumer's claim.
+
+ A claim or terminal result that won the mailbox lock is returned unchanged.
+ """
+ key = _delivery_id(delivery_id)
+ with _locked(profile_home) as root:
+ path = root / f"{key}.json"
+ record = _read(path)
- if record is None or record["status"] != "queued":
++ # An authority admission lives in its FIFO: only the authority may settle it.
++ if record is None or record["status"] != "queued" or record.get("admission_id"):
+ return record
+ record.update(status="cancelled", reply="", error=error, reason=reason,
+ completed_at=time.time_ns())
+ _write(path, record)
+ return record
+
+
def read_delivery_result(profile_home: Path | str, delivery_id: str) -> dict[str, Any] | None:
"""Read admission/claim/terminal state without waiting or deleting its receipt."""
- return _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")
+ record = _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")
+ if record is not None and record.get('admission_id'):
+ home = Path(profile_home).resolve()
+ # Readback replays the immutable envelope; dropping category or author conflicts.
- return authority_delivery(home, dict(id=delivery_id,
++ category = ({'notification_category': record['notification_category']}
++ if 'notification_category' in record else {})
++ # The receipt carries the envelope's category so a producer can detect a changed retry.
++ return {**authority_delivery(home, dict(id=delivery_id,
+ profile=home.name if home.parent.name == 'profiles' else 'default', message=record['message'],
- **({'author': dict(record['author'])} if record.get('author') else {}),
- **({'notification_category': record['notification_category']}
- if 'notification_category' in record else {})))
++ **({'author': dict(record['author'])} if record.get('author') else {}), **category)), **category}
+ return record
_PENDING = ("queued", "claimed")
diff --cc tools/bot_mode_dm.py
index 5b0dd78434a,e807596a9a7..c7bd5bae0c9
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@@ -417,6 -420,65 +422,11 @@@ def _delivery_lock(argv: list[str], *,
return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2])
-def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, str]] = None) -> int:
- """One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits
- the transport's streams and returns its exit code. Transient failures re-run the
- same session; a context_overflow re-run lets the retried turn's pre-API compaction
- compact the transcript first (no fresh session is ever minted). Auth/quota/config never retry."""
-
- def _turn(turn_env=env):
- return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,
- capture_output=True, text=True, encoding="utf-8", errors="replace", env=turn_env)
-
- proc = _turn()
- if proc.returncode != 0:
- from tools.bot_failure_reasons import RETRY_NONE, classify_agent_error, retry_action, turn_failure_text
- from tools.bot_relay import retry_turn_env
-
- # The re-run replays the same session and payload; the failed attempt already persisted the
- # user row, so the retried process is told to resume it (RESUME_UNANSWERED_TURN_ENV).
- if retry_action(classify_agent_error(turn_failure_text(proc.stdout, proc.stderr))) != RETRY_NONE:
- proc = _turn(retry_turn_env(env))
- stderr_text = proc.stderr or ""
- reason = next((line.removeprefix("hermes-refusal-reason: ").strip()
- for line in stderr_text.splitlines()
- if line.startswith("hermes-refusal-reason: ")), None)
- # A code wins over prose, including unknown codes from newer CLIs.
- # Only older CLIs without a marker need the historical wording fallback.
- refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None
- else "already has a live owner" in stderr_text)
- if proc.returncode != 0 and refused_not_owned:
- # The target's Bot Chat is held live by another surface (Desktop); the turn
- # never ran — tell the sender plainly instead of leaking a raw lease error.
- # See #100523.
- who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate"
- print(json.dumps({
- "error": f"Delivery failed: @{who}'s Bot Chat is open on another "
- "surface right now, so your message was NOT delivered. Try again later.",
- "reason": "target_busy",
- }))
- return 1
- # Re-emit the transport's streams: stdout is the reply text the
- # completion notification carries back to the sending agent. A successful bare
- # silence marker is a delivery decision (same rule as the gateway and the live
- # Bot Chat completion): the turn stays in the target's transcript, the sender
- # never sees the marker as prose.
- from gateway.response_filters import is_intentional_silence_response
- reply = proc.stdout or ""
- if proc.returncode == 0 and is_intentional_silence_response(reply):
- reply = ""
- for stream, text in ((sys.stdout, reply), (sys.stderr, proc.stderr)):
- if text:
- stream.write(text)
- stream.flush()
- return proc.returncode
-
-
+ def _live_intent_file(dm_file: "str | os.PathLike") -> str:
+ """The pinned live-delivery intent beside a DM file (the cache sweep globs ``*.live.json``)."""
+ return f"{os.fspath(dm_file)}.live.json"
+
+
def _dm_delivery_id(dm_file: "str | os.PathLike") -> str:
"""One delivery id per DM file: the dispatch ack, the live-owner intent and every retry
of the runner derive it the same way, so the sender can correlate all of them."""
@@@ -486,12 -577,42 +525,35 @@@ def _local_delivery_home(argv: list[str
return dict(_roster(_hermes_root(Path(_default_home())))).get(argv[2])
+ def _live_outcome_unknown(dm_file: str, cause: object) -> str:
+ """The runner's stdout when a live admission may have happened but its outcome is unknown."""
+ return json.dumps({"status": "ambiguous", "delivery_id": _dm_delivery_id(dm_file),
+ "error": f"Live admission outcome unknown: {cause}. Do not resend.",
+ "evidence_file": dm_file})
+
+
+ def _runner_argv(args: list[str]) -> tuple[Optional[str], str, str, list[str]] | None:
+ """Split ``--run-delivery [--author <json>] <mode> <dm_file> <argv…>`` into
+ ``(author_json, mode, dm_file, argv)``; None when malformed. Stdlib only: the boot-failure
+ report runs it when no Hermes import is available."""
+ if args[:1] != ["--run-delivery"]:
+ return None
+ rest, author = args[1:], None
+ if rest[:1] == ["--author"]:
+ if len(rest) < 2:
+ return None
+ author, rest = rest[1], rest[2:]
+ if len(rest) < 2 or rest[0] not in ("stdin", "query-file"):
+ return None
+ return author, rest[0], rest[1], rest[2:]
+
+
def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,
profile_home: Path | None = None, author: Optional[dict] = None) -> int:
- """Route to the live owner before attempting a CLI transport. Live deliveries
- retain their intent/payload and immutable receipt; only CLI/peer payloads are
- removed after consumption. The CLI turn window holds the profile lock, so two
- deliveries into one profile queue; a bounded wait ends in a 'target_busy' refusal.
- ``author`` rides to the child as HERMES_TURN_AUTHOR; ``hermes peer dm`` forwards it in the request body.
-
- Local (query-file) turns get one policy-gated retry (#93091 item 5): transient failures re-run the same
- session; a context_overflow re-run lets the retried turn's pre-API compaction pass compact the Bot Chat
- transcript first (agent/conversation_loop.py) — the sanctioned compression lever; no fresh session is
- ever minted. Auth/quota/config failures never retry. Peer transports (stdin mode) retry on their own
- gateway's deliver path, not here.
+ """Admit local DMs only through the profile authority; retain uncertain intent.
+
+ The optional peer stdin transport remains an explicit remote route, never a
+ fallback after local admission. Background processes wait for delivery only.
"""
# The live consumer owns turn admission; never compete for its CLI lease.
if not stdin_file:
diff --cc tools/process_registry.py
index 30dd7b385c2,43a4fbf4a0c..17a17c6eca8
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@@ -641,11 -718,11 +718,13 @@@ class ProcessRegistry(ProcessTerminatio
# process_loop and the gateway drain it after each agent turn to trigger new turns.
import queue as _queue_mod
self.completion_queue: _queue_mod.Queue = _queue_mod.Queue()
- # Durable delegation completions are rehydrated by restore_completions(), NOT here: the
- # module-level singleton runs __init__ on `import model_tools`, and the replay opens
- # (creates, migrates) the launch profile's state.db (#123265). Importing the module is
+ # Durable delegation completions are NOT rehydrated here: this constructor runs at
+ # import time in every process that touches the tools graph (cron clients, `hermes
- # sessions list`, workers), and restoring means writing the canonical ledger. Only
- # the runtime that owns delegation state calls restore_undelivered_completions,
- # explicitly (GatewayRunner._start_recover_previous_run).
++ # sessions list`, workers), and restoring means writing the canonical ledger. The
++ # owner replays them explicitly (GatewayRunner._start_recover_previous_run) and the
++ # first consumer through restore_completions() (#123265). Importing the module is
+ # side-effect free and keeps its import-order contract for later completion writers.
+ import tools.async_delegation # noqa: F401
# Completions the agent already consumed via wait()/read_log() (output in
# hand): drain loops AND gateway/tui watchers skip them.
self._completion_consumed: set = set()
diff --cc tools/terminal_scope.py
index 1b5136644da,98af29360d4..48bd15375fe
--- a/tools/terminal_scope.py
+++ b/tools/terminal_scope.py
@@@ -127,8 -102,26 +127,9 @@@ def build_profile_terminal_scope
closes. It sits where the process env sits in the standalone bridge — explicit YAML keys
still win (``apply_terminal_config_to_env``).
"""
- from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP, _terminal_env_value
- from hermes_cli.config_defaults import DEFAULT_CONFIG
-
home = Path(hermes_home)
- scope: Dict[str, str] = {}
-
- def _apply(mapping: Dict[str, Any]) -> None:
- for cfg_key, value in mapping.items():
- # cwd placeholders are resolved per-surface later; not a policy value.
- if value is None or (cfg_key == "cwd" and str(value).strip() in {".", "auto", "cwd"}):
- continue
- env_var = TERMINAL_CONFIG_ENV_MAP.get(cfg_key)
- if env_var:
- # List/dict config values must be JSON (same contract as
- # apply_terminal_config_to_env). str() yields Python repr, which
- # json.loads in terminal_tool rejects.
- scope[env_var] = _terminal_env_value(value)
-
- _apply({**_TOOL_LEVEL_DEFAULTS, **(DEFAULT_CONFIG.get("terminal") or {})})
+ scope = default_terminal_scope()
+ default_image = scope.get("TERMINAL_DOCKER_IMAGE")
env_path = home / ".env"
if env_path.exists():
# load_env_file swallows OSError by design (secret scope fails soft); an unreadable
@@@ -160,7 -164,9 +172,9 @@@
raise TerminalPolicyUnavailable(f"cannot parse {config_path}: {exc}") from exc
raw_terminal = raw.get("terminal") if isinstance(raw, dict) else None
if isinstance(raw_terminal, dict):
- _apply(raw_terminal)
+ _apply_terminal_mapping(scope, raw_terminal)
+ image_pinned = image_pinned or "docker_image" in raw_terminal
+ scope["TERMINAL_DOCKER_IMAGE_PINNED"] = "1" if image_pinned else "0"
_resolve_scope_cwd_placeholder(scope)
return scope
diff --cc tui_gateway/agent_factory.py
index d7b628ba3fa,00000000000..ce894fac339
mode 100644,000000..100644
--- a/tui_gateway/agent_factory.py
+++ b/tui_gateway/agent_factory.py
@@@ -1,699 -1,0 +1,693 @@@
+"""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")
++ # Canonical route reader shared with CLI --resume: nested ``gateway_runtime`` (the route the messaging
++ # gateway last ran) before the TUI's top-level keys, then a routable ``billing_provider`` (#125942).
++ from hermes_state import SessionDB
++ route = SessionDB.session_gateway_runtime(row)
++ provider, base_url, api_mode = (str(route.get(k) or "").strip() for k in ("provider", "base_url", "api_mode"))
++ service_tier = str(model_config.get("service_tier") or "").strip()
+ 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)
++ from agent.fast_mode import parse_service_tier
++
++ return parse_service_tier((_load_cfg().get("agent") or {}).get("service_tier", ""))
+
+
+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)."""
+ from toolsets import CLIENT_SURFACE_TOOLSETS
+ return set(CLIENT_SURFACE_TOOLSETS) 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.
+
+ The fold-in happens after ``_get_platform_tools`` already subtracted ``agent.disabled_toolsets``,
+ so the same subtraction is applied to the fold-in itself — otherwise ``disabled_toolsets:
+ [project]`` is a no-op on desktop/TUI, the only surfaces where the client toolsets exist
+ (#54433). ``desktop_ui`` is kept regardless: it is the client's own control surface, not a
+ model toolset."""
+ 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]
+ fold_in = (surface | granted) - set(kept)
+ disabled = set(_load_disabled_toolsets() or [])
+ if disabled:
+ fold_in -= disabled - {"desktop_ui"}
+ return [*kept, *sorted(fold_in)]
+
+
+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."""
++ else the configured CLI toolsets. Client-surface toolsets fold in here — only this surface can answer them.
++ An explicitly saved EMPTY list (``platform_toolsets.cli: []`` that resolves to nothing) is a
++ zero-tool state and returns [] — never None, which would mean unrestricted (#82010)."""
+ 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
++ from hermes_cli.tools_config import _get_platform_tools, _platform_toolsets_explicitly_saved
+ 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
++ if enabled:
++ return sorted(_with_session_toolsets(enabled, session_platform))
++ # An explicitly saved list that resolves to nothing (``platform_toolsets.cli: []`` with no
++ # enabled MCP servers) is an explicit zero-tool state, not "no filter": fail closed with []
++ # instead of None (#82010). The client-surface fold-in must not resurrect tools the user
++ # explicitly switched off, so [] is returned bare. Only an ABSENT/unset key keeps the
++ # None = "no restriction" default below.
++ if _platform_toolsets_explicitly_saved(cfg, "cli"):
++ return []
++ return 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 _load_disabled_toolsets() -> list[str] | None:
+ """``agent.disabled_toolsets`` from config.yaml, or ``None``.
+
+ The classic CLI (``cli_init_mixin``) and the messaging gateway both forward this list to
+ AIAgent, where ``get_tool_definitions`` strips the named toolsets even out of composite
+ defaults like ``hermes-cli`` (#17309). The desktop/TUI gateway historically dropped it, so
+ e.g. ``disabled_toolsets: [browser]`` silently had no effect on Desktop — the only consumer
+ was ``_get_platform_tools``'s name-level subtraction, which can't reach inside a composite
+ default toolset (#44499).
+ """
+ try:
+ from agent.skill_utils import parse_config_string_list
+
+ from hermes_cli.config import load_config
+
+ agent_cfg = load_config().get("agent") or {}
+ disabled = parse_config_string_list(agent_cfg.get("disabled_toolsets"))
+ return [str(ts) for ts in disabled] or None
+ except Exception:
+ 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 _session_show_reasoning(sid: str) -> bool:
+ """Session display flag. Missing means the config default, not hidden."""
+ session = _sessions.get(sid) or {}
+ if "show_reasoning" in session:
+ return bool(session["show_reasoning"])
+ return _load_show_reasoning()
+
+
- def _process_tool_chrome_enabled(sid: str) -> bool:
- """Non-essential tool rows follow display.show_reasoning, not reasoning_effort."""
- return _session_show_reasoning(sid) and _tool_progress_enabled(sid)
-
-
+def _tool_progress_enabled(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) != "off"
+
+
+_TOOL_LIFECYCLE_UI_TOOLS = frozenset({
+ "clarify", "manage_connections", "setup_mcp",
+ "image_generate", "manage_catalog", "delegate_task",
+ # File edits are the turn's deliverable — the diff card the user reviews.
+ "edit_file", "patch", "write_file",
+})
+
+
+def _tool_lifecycle_required_for_ui(name: str) -> bool:
+ """Interactive UI / card surfaces, not optional chrome.
+
+ Desktop renders these from the tool-call part itself, so suppressing the
+ lifecycle hides the turn's deliverable entirely (`isCardTool` /
+ `isFileEditTool` in apps/desktop/src/lib/tool-render-class.ts must stay in
+ sync with `_TOOL_LIFECYCLE_UI_TOOLS`): clarify / connection cards are
+ consent surfaces, image_generate / manage_catalog / delegate_task draw the
+ thing the user asked for, and file edits are the diff the user reviews.
+ The start and complete guards both consult this set, so a card's
+ `tool.complete` can never arrive without its `tool.start`.
+ """
+ return name in _TOOL_LIFECYCLE_UI_TOOLS
+
+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;
+ # ``model: <id>`` (string shorthand) names no provider.
+ cfg_model = _load_cfg().get("model")
+ primary_provider = requested_provider or (cfg_model.get("provider") if isinstance(cfg_model, dict) else None)
+ 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
++ from agent.skill_commands import build_preloaded_skills_prompt, format_missing_skills
+ 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))
++ raise ValueError(format_missing_skills(missing_skills))
++ logger.warning("Skipping %s. Continuing with: %s. List available skills with `hermes skills list`.",
++ format_missing_skills(missing_skills), ", ".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),
+ disabled_toolsets=_load_disabled_toolsets(),
+ # 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")),
++ checkpoints_enabled=_resolve_checkpoints_enabled(cfg),
+ 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(),
++ # The resolved provider's request body (a custom entry's extra_body), as the CLI/cron/gateway pass it.
++ request_overrides=runtime.get("request_overrides"),
+ prefill_messages=_load_prefill_messages() or None, **_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 tui_gateway/command_discovery.py
index 631858f7c7c,00000000000..da8ccb318b4
mode 100644,000000..100644
--- a/tui_gateway/command_discovery.py
+++ b/tui_gateway/command_discovery.py
@@@ -1,276 -1,0 +1,291 @@@
+"""Shared slash discovery data; no server import or session execution runtime.
+
+Transport wrappers own authentication and profile binding before calling these
+builders. Keep the legacy catalog and completion semantics identical here.
+"""
+import contextlib
+from importlib import import_module
+import logging
+
+logger = logging.getLogger(__name__)
+
+_TUI_HIDDEN: frozenset[str] = frozenset({"sethome", "set-home", "commands", "approve", "deny"})
+
+_TUI_EXTRA: list[tuple[str, str, str]] = [
+ ("/density", "Toggle compact display mode", "TUI"),
+ ("/logs", "Show recent gateway log lines", "TUI"),
+ ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]", "TUI"),
+ ("/sessions", "Switch between live TUI sessions", "TUI"),
+]
+
+_SLASH_EXTRAS = [
+ ("/density", "Toggle compact display mode"), ("/details", "Control agent detail visibility"),
+ ("/logs", "Show recent gateway log lines"),
+ ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]")]
+
+
+def _item(text: str, meta: str, display: str | None = None) -> dict:
+ return {"text": text, "display": display if display is not None else text, "meta": meta}
+
+
+def _skill_usage_lookup():
+ """``(usage, origin)`` callables for the skill catalog: activity count (use + view + patch) and
+ "hub" / "bundled" / "local" (``/api/skills`` ``provenance``, "local" spelled "agent"). Failure → 0 / "local"."""
+ try:
+ from tools.skill_usage import (
+ _read_bundled_names, _read_hub_installed_names, activity_count, load_usage)
+ records, bundled, hub = load_usage(), _read_bundled_names(), _read_hub_installed_names()
+ except Exception as e:
+ logger.debug("skill usage lookup unavailable: %s", e)
+ return (lambda _name: 0), (lambda _name: "local")
+
+ def usage(name: str) -> int:
+ with contextlib.suppress(Exception):
+ return activity_count(records.get(name) or {})
+ return 0
+
+ def origin(name: str) -> str:
+ return "hub" if name in hub else "bundled" if name in bundled else "local"
+ return usage, origin
+
+
+_SLASH_COMPLETION_LIMIT = 30
+
+
- def _rank_slash_completions(items: list[dict], usage, origin_of, *, browsing: bool, score_of=None) -> list[dict]:
++def _rank_slash_completions(items: list[dict], usage, origin_of, *, browsing: bool, score_of=None,
++ registry_command_names: frozenset[str] | None = None) -> list[dict]:
+ """Registry commands keep their order; only skills reorder: fuzzy ``score_of`` first, then most-used, then
+ A-Z. The limit is spent PER KIND (a flat cut on a large install offered no skill at all). ``browsing``
- (bare ``/``) drops never-used bundled skills as noise; a typed query is SEARCHING — nothing pruned, only reordered."""
++ (bare ``/``) drops never-used bundled skills as noise; a typed query is SEARCHING — nothing pruned, only reordered.
++ While browsing, only names in ``registry_command_names`` (default ``GATEWAY_KNOWN_COMMANDS``) skip the cap:
++ plugin-registered commands are also ``kind != "skill"`` but unbounded, so they stay capped like skills."""
+ def name_of(item: dict) -> str:
+ return str(item.get("text", "")).strip().lstrip("/").lower()
+ commands = [item for item in items if item.get("kind") != "skill"]
+ skills = [item for item in items if item.get("kind") == "skill"]
+ if browsing:
+ skills = [item for item in skills if origin_of(name_of(item)) != "bundled" or usage(name_of(item)) > 0]
+ skills.sort(key=lambda item: (
+ *(() if score_of is None else (score_of(item),)), -usage(name_of(item)), name_of(item)))
- return commands[:_SLASH_COMPLETION_LIMIT] + skills[:_SLASH_COMPLETION_LIMIT]
++ if browsing:
++ if registry_command_names is None:
++ from hermes_cli.commands import GATEWAY_KNOWN_COMMANDS
++ registry_command_names = GATEWAY_KNOWN_COMMANDS
++ fixed = [c for c in commands if name_of(c) in registry_command_names]
++ other = [c for c in commands if name_of(c) not in registry_command_names]
++ ranked_commands = fixed + other[:_SLASH_COMPLETION_LIMIT]
++ else:
++ ranked_commands = commands[:_SLASH_COMPLETION_LIMIT]
++ return ranked_commands + skills[:_SLASH_COMPLETION_LIMIT]
+
+
+_DETAILS_SECTIONS = ("thinking", "tools", "subagents", "activity")
+_DETAILS_MODES = ("hidden", "collapsed", "expanded")
+
+
+def _details_root_meta(candidate: str) -> str:
+ if candidate in _DETAILS_SECTIONS:
+ return "section override"
+ return "cycle global mode" if candidate == "cycle" else "global mode"
+
+
+def _details_completions(text: str) -> list[dict] | None:
+ """Argument completions for ``/details [section] [mode]``; None when ``text`` is not that command."""
+ if not text.lower().startswith("/details"):
+ return None
+ stripped = text.strip()
+ if stripped and not "/details".startswith(stripped.lower().split()[0]):
+ return None
+ body = text[len("/details") :].removeprefix(" ")
+ parts = body.split()
+ trailing = text.endswith(" ")
+ root_candidates = (*_DETAILS_MODES, "cycle", *_DETAILS_SECTIONS)
+ if not body or (not parts and trailing):
+ lead = "" if trailing else " "
+ return [_item(f"{lead}{c}", _details_root_meta(c)) for c in root_candidates]
+ if len(parts) == 1 and not trailing:
+ prefix = parts[0].lower()
+ return [_item(c, _details_root_meta(c)) for c in root_candidates if c.startswith(prefix) and c != prefix]
+ section = parts[0].lower() if parts else ""
+ if section not in _DETAILS_SECTIONS:
+ return []
+
+ def section_meta(candidate: str) -> str:
+ return f"clear {section} override" if candidate == "reset" else f"set {section}"
+ mode_candidates = (*_DETAILS_MODES, "reset")
+ if len(parts) == 1: # trailing space after the section
+ return [_item(c, section_meta(c)) for c in mode_candidates]
+ if len(parts) == 2 and not trailing:
+ prefix = parts[1].lower()
+ return [_item(c, section_meta(c)) for c in mode_candidates if c.startswith(prefix) and c != prefix]
+ return []
+
+
+class _Catalog:
+ """Accumulator for commands.catalog: ``pairs`` (every [key, desc]), ``canon`` (lowercase
+ key/alias → canonical key), ``commands`` (key → desktop meta) and ordered categories."""
+
+ def __init__(self) -> None:
+ self.pairs: list[list[str]] = []
+ self.canon: dict[str, str] = {}
+ self.commands: dict[str, dict[str, str | None]] = {}
+ self.cat_map: dict[str, list[list[str]]] = {} # insertion order = category order
+
+ def add(self, key: str, desc: str, cat: str) -> None:
+ self.canon[key.lower()] = key
+ self.pairs.append([key, desc])
+ self.cat_map.setdefault(cat, []).append([key, desc])
+
+
+def _catalog_registry(cat: _Catalog, module_loader) -> None:
+ commands = module_loader("hermes_cli.commands")
+ for cmd in commands.COMMAND_REGISTRY:
+ meta = commands.command_desktop_meta(cmd)
+ cat.commands.update({f"/{key}": dict(meta) for key in (cmd.name, *cmd.aliases)})
+ if cmd.name in _TUI_HIDDEN or cmd.gateway_only:
+ continue
+ cat.add(f"/{cmd.name}", commands._build_description(cmd), cmd.category)
+ for a in cmd.aliases:
+ cat.canon[f"/{a}".lower()] = f"/{cmd.name}"
+ for name, desc, category in _TUI_EXTRA:
+ # Registry command/alias wins over a colliding TUI extra (e.g. /compact, /sessions).
+ if name.lower() not in cat.canon:
+ cat.add(name, desc, category)
+
+
+def _catalog_quick_commands(cat: _Catalog, load_cfg) -> None:
+ qcmds = load_cfg().get("quick_commands", {}) or {}
+ if not (isinstance(qcmds, dict) and qcmds):
+ return
+ cat.cat_map.setdefault("User commands", []) # category exists even when every entry is malformed
+ for qname, qc in sorted(qcmds.items()):
+ if not isinstance(qc, dict):
+ continue
+ qtype = qc.get("type", "")
+ default_desc = {"exec": f"exec: {qc.get('command', '')}", "alias": f"alias → {qc.get('target', '')}"}
+ desc = str(qc.get("description") or default_desc.get(qtype, qtype or "quick command"))
+ cat.add(f"/{qname}", desc, "User commands")
+
+
+def _catalog_plugin_commands(cat: _Catalog, module_loader) -> None:
+ plugin_cmds = module_loader("hermes_cli.plugins").get_plugin_commands() or {}
+ if plugin_cmds:
+ cat.cat_map.setdefault("Plugin commands", [])
+ for pname, info in sorted(plugin_cmds.items()):
+ key = f"/{pname}"
+ if not isinstance(info, dict) or key.lower() in cat.canon:
+ continue
+ cat.add(key, str(info.get("description") or "Plugin command"), "Plugin commands")
+ mode = info.get("argument_mode")
+ if mode not in {"options", "text", "mixed"}:
+ mode = "text" if str(info.get("args_hint") or "").strip() else None
+ cat.commands[key] = {"argument_mode": mode, "desktop": None}
+
+
+def _catalog_skills(cat: _Catalog, skills: dict[str, dict], module_loader) -> str:
+ """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them).
+ Returns the one-line notice for skills whose name is a built-in command (no ``/<name>`` entry;
+ ``agent.skill_commands`` guard), ``""`` when none."""
+ usage, origin_of = _skill_usage_lookup()
+ sc = module_loader("agent.skill_commands")
- for k, info in sorted(sc.scan_skill_commands().items()):
++ for k, info in sorted(sc.get_interactive_skill_commands().items()):
+ cat.pairs.append([k, str(info.get("description", "Skill"))])
+ name = str(info.get("name") or k.lstrip("/"))
+ skills[k] = {"usage": usage(name), "origin": origin_of(name)}
+ collision_note = getattr(sc, "skill_command_collision_note", None)
+ if collision_note is None:
+ return ""
+ names = sorted(s["name"] for s in module_loader("tools.skills_tool")._find_all_skills())
+ return "; ".join(filter(None, map(collision_note, names)))
+
+
+def command_catalog(load_cfg=None, module_loader=import_module, scope=None) -> dict:
+ """Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``
+ (skills' message wins, then quick commands', then plugins'); only with no failure does it carry
- the built-in-name collision notice for skills that have no ``/<name>`` (empty when none). ``scope``
- is a context manager binding the calling session's profile home and workspace around skill
- discovery so project-local skills register for the repo the session is actually in (#114359)."""
++ the built-in-name collision notice for skills that have no ``/<name>`` (empty when none). Quick
++ command, plugin command and skill discovery are all home-keyed, so ``scope`` (a context manager
++ binding the calling session's profile home and workspace) wraps every loader: project-local skills
++ register for the repo the session is actually in (#114359), and a profile-routed palette never
++ lists the launch profile's quick/plugin commands. A scope that cannot bind (unknown profile)
++ raises out of here — the caller maps it to 4064 like ``complete.slash`` (#124651)."""
+ if load_cfg is None:
+ from hermes_cli.config import load_config_readonly
+ load_cfg = load_config_readonly
+ cat = _Catalog()
+ _catalog_registry(cat, module_loader)
+ warning = ""
- try:
- _catalog_quick_commands(cat, load_cfg)
- except Exception as e:
- warning = f"quick_commands discovery unavailable: {e}"
- try:
- _catalog_plugin_commands(cat, module_loader)
- except Exception as e:
- warning = warning or f"plugin command discovery unavailable: {e}"
+ skills: dict[str, dict] = {}
- try:
- with scope if scope is not None else contextlib.nullcontext():
++ with scope if scope is not None else contextlib.nullcontext():
++ try:
++ _catalog_quick_commands(cat, load_cfg)
++ except Exception as e:
++ warning = f"quick_commands discovery unavailable: {e}"
++ try:
++ _catalog_plugin_commands(cat, module_loader)
++ except Exception as e:
++ warning = warning or f"plugin command discovery unavailable: {e}"
++ try:
+ collision_note = _catalog_skills(cat, skills, module_loader) # always runs: skills must list even when a loader failed
- warning = warning or collision_note
- except Exception as e:
- warning = f"skill discovery unavailable: {e}"
++ warning = warning or collision_note
++ except Exception as e:
++ warning = f"skill discovery unavailable: {e}"
+ return {
+ "pairs": cat.pairs, "sub": {k: v[:] for k, v in module_loader("hermes_cli.commands").SUBCOMMANDS.items()},
+ "canon": cat.canon,
+ "commands": cat.commands,
+ "categories": [{"name": c, "pairs": rows} for c, rows in cat.cat_map.items()],
+ "skills": skills, "skill_count": len(skills), "warning": warning}
+
+
+def slash_completions(text: str = "", scope=None) -> dict:
+ """``scope`` binds the calling session's profile and workspace around the skill/bundle lookups
+ (home- and cwd-keyed) so the popup offers the project-local skills ``command.dispatch`` accepts
+ for that session (#114359)."""
+ if not text.startswith("/"):
+ return {"items": []}
+ from hermes_cli.commands_completion import SlashCommandCompleter
+ from prompt_toolkit.document import Document
+ from prompt_toolkit.formatted_text import to_plain_text
- from agent.skill_commands import get_skill_commands
++ from agent.skill_commands import get_interactive_skill_commands
+ from agent.skill_bundles import get_skill_bundles
+ with scope if scope is not None else contextlib.nullcontext():
- skill_commands, skill_bundles = dict(get_skill_commands()), dict(get_skill_bundles())
++ skill_commands, skill_bundles = dict(get_interactive_skill_commands()), dict(get_skill_bundles())
+ completer = SlashCommandCompleter(
+ skill_commands_provider=lambda: skill_commands, skill_bundles_provider=lambda: skill_bundles)
+ # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):
+ # skills/bundles are the only completions for an inline `/skill` typed mid-message.
+ skill_names = {key.lstrip("/").lower() for key in (*skill_commands, *skill_bundles)}
+
+ def to_items(doc: Document) -> list[dict]:
+ # display/display_meta are FormattedText; the TUI contract is a plain string
+ # (the raw list trips Ink's row layout into 1-char truncation).
+ return [
+ {
+ "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,
+ "meta": to_plain_text(c.display_meta) if c.display_meta else "",
+ "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}
+ for c in completer.get_completions(doc, None)]
+ items = to_items(Document(text, len(text)))
+ # Rank + bound while a `/token` is under the cursor (the one stage skills are
+ # offered at); an argument stage (`/personality `) keeps its command's order.
+ if text.rsplit(" ", 1)[-1].startswith("/"):
+ score_of = None
+ # Command-token stage: the completer only emits name-prefix matches, so merge in
+ # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).
+ if " " not in text and len(text) > 1:
+ from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query
+ items, score_of = fuzzy_rank_slash_items(
+ items, to_items(Document("/", 1)), normalize_slash_search_query(text))
+ usage, origin_of = _skill_usage_lookup()
+ items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)
+ else:
+ items = items[:_SLASH_COMPLETION_LIMIT]
+ text_lower = text.lower()
+ for extra_text, extra_meta in _SLASH_EXTRAS:
+ if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):
+ items.append({**_item(extra_text, extra_meta), "kind": "command"})
+ if (details_items := _details_completions(text)) is not None:
+ return {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)}
+ return {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1}
+
+
diff --cc tui_gateway/methods_bot_relay.py
index 71086581cfb,4262b811fa6..f9fbba85b89
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@@ -6,8 -6,16 +6,9 @@@ Chat delivery on the TARGET gateway, re
the SENDER gateway for its waiter). Plumbing: ``tools/bot_relay.py``; handlers are rebound onto
server.py's globals (method_ctx.py) and reference ``_ok``/``_err`` bare."""
-import contextlib
+ import logging
-import os
-import subprocess
from pathlib import Path
-# Defined beside the sender-side waiter budget so the two Python sides cannot drift (#93911).
-from tools.bot_failure_reasons import delivery_failure_reason
-from tools.bot_relay import TURN_ATTEMPT_TIMEOUT_SECONDS
-
from .method_ctx import HandlerRegistry
_registry = HandlerRegistry()
diff --cc tui_gateway/methods_complete.py
index 35b902c78ef,91a4f96eeb9..ca6b1b092fb
--- a/tui_gateway/methods_complete.py
+++ b/tui_gateway/methods_complete.py
@@@ -270,11 -278,57 +272,13 @@@ def _(rid, params: dict) -> dict
@method("complete.slash")
@_catch(5020)
def _(rid, params: dict) -> dict:
- text = params.get("text", "")
- if not text.startswith("/"):
- return _ok(rid, {"items": []})
- from hermes_cli.commands_completion import SlashCommandCompleter
- from prompt_toolkit.document import Document
- from prompt_toolkit.formatted_text import to_plain_text
- from agent.skill_commands import get_interactive_skill_commands
- from agent.skill_bundles import get_skill_bundles
+ from tui_gateway.command_discovery import slash_completions
# Skill/bundle lookups are home- and cwd-keyed: bind the calling session's profile and workspace so
# the popup offers the project-local skills ``command.dispatch`` accepts for that session (#114359).
- scope = _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params))
+ # A new-chat draft has no session yet: it names its rail-selected ``profile`` instead (#124651).
- with _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params),
- profile=params.get("profile")):
- skill_commands, skill_bundles = dict(get_interactive_skill_commands()), dict(get_skill_bundles())
- completer = SlashCommandCompleter(
- skill_commands_provider=lambda: skill_commands, skill_bundles_provider=lambda: skill_bundles)
- # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):
- # skills/bundles are the only completions for an inline `/skill` typed mid-message.
- skill_names = {key.lstrip("/").lower() for key in (*skill_commands, *skill_bundles)}
-
- def to_items(doc: Document) -> list[dict]:
- # display/display_meta are FormattedText; the TUI contract is a plain string
- # (the raw list trips Ink's row layout into 1-char truncation).
- return [
- {
- "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,
- "meta": to_plain_text(c.display_meta) if c.display_meta else "",
- "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}
- for c in completer.get_completions(doc, None)]
- items = to_items(Document(text, len(text)))
- # Rank + bound while a `/token` is under the cursor (the one stage skills are
- # offered at); an argument stage (`/personality `) keeps its command's order.
- if text.rsplit(" ", 1)[-1].startswith("/"):
- score_of = None
- # Command-token stage: the completer only emits name-prefix matches, so merge in
- # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).
- if " " not in text and len(text) > 1:
- from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query
- items, score_of = fuzzy_rank_slash_items(
- items, to_items(Document("/", 1)), normalize_slash_search_query(text))
- usage, origin_of = _skill_usage_lookup()
- items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)
- else:
- items = items[:_SLASH_COMPLETION_LIMIT]
- text_lower = text.lower()
- for extra_text, extra_meta in _SLASH_EXTRAS:
- if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):
- items.append({**_item(extra_text, extra_meta), "kind": "command"})
- if (details_items := _details_completions(text)) is not None:
- return _ok(rid, {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)})
- return _ok(rid, {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1})
++ scope = _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params),
++ profile=params.get("profile"))
+ return _ok(rid, slash_completions(params.get("text", ""), scope=scope))
def _session_agent(params: dict):
diff --cc tui_gateway/methods_tools.py
index b50ce9059af,9d4cd10e499..1a1fb43190e
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@@ -409,15 -425,116 +425,18 @@@ def _(rid, params: dict) -> dict
# ─── Command catalog / dispatch ──────────────────────────────────────────────
-class _Catalog:
- """Accumulator for commands.catalog: ``pairs`` (every [key, desc]), ``canon`` (lowercase
- key/alias → canonical key), ``commands`` (key → desktop meta) and ordered categories."""
-
- def __init__(self) -> None:
- self.pairs: list[list[str]] = []
- self.canon: dict[str, str] = {}
- self.commands: dict[str, dict[str, str | None]] = {}
- self.cat_map: dict[str, list[list[str]]] = {} # insertion order = category order
-
- def add(self, key: str, desc: str, cat: str) -> None:
- self.canon[key.lower()] = key
- self.pairs.append([key, desc])
- self.cat_map.setdefault(cat, []).append([key, desc])
-
-
-def _catalog_registry(cat: _Catalog) -> None:
- commands = _tools_mod("hermes_cli.commands")
- for cmd in commands.COMMAND_REGISTRY:
- meta = commands.command_desktop_meta(cmd)
- cat.commands.update({f"/{key}": dict(meta) for key in (cmd.name, *cmd.aliases)})
- if cmd.name in _TUI_HIDDEN or cmd.gateway_only:
- continue
- cat.add(f"/{cmd.name}", commands._build_description(cmd), cmd.category)
- for a in cmd.aliases:
- cat.canon[f"/{a}".lower()] = f"/{cmd.name}"
- for name, desc, category in _TUI_EXTRA:
- # Registry command/alias wins over a colliding TUI extra (e.g. /compact, /sessions).
- if name.lower() not in cat.canon:
- cat.add(name, desc, category)
-
-
-def _catalog_quick_commands(cat: _Catalog) -> None:
- qcmds = _load_cfg().get("quick_commands", {}) or {}
- if not (isinstance(qcmds, dict) and qcmds):
- return
- cat.cat_map.setdefault("User commands", []) # category exists even when every entry is malformed
- for qname, qc in sorted(qcmds.items()):
- if not isinstance(qc, dict):
- continue
- qtype = qc.get("type", "")
- default_desc = {"exec": f"exec: {qc.get('command', '')}", "alias": f"alias → {qc.get('target', '')}"}
- desc = str(qc.get("description") or default_desc.get(qtype, qtype or "quick command"))
- cat.add(f"/{qname}", desc, "User commands")
-
-
-def _catalog_plugin_commands(cat: _Catalog) -> None:
- plugin_cmds = _tools_mod("hermes_cli.plugins").get_plugin_commands() or {}
- if plugin_cmds:
- cat.cat_map.setdefault("Plugin commands", [])
- for pname, info in sorted(plugin_cmds.items()):
- key = f"/{pname}"
- if not isinstance(info, dict) or key.lower() in cat.canon:
- continue
- cat.add(key, str(info.get("description") or "Plugin command"), "Plugin commands")
- mode = info.get("argument_mode")
- if mode not in {"options", "text", "mixed"}:
- mode = "text" if str(info.get("args_hint") or "").strip() else None
- cat.commands[key] = {"argument_mode": mode, "desktop": None}
-
-
-def _catalog_skills(cat: _Catalog, skills: dict[str, dict]) -> str:
- """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them).
- Returns the one-line notice for skills whose name is a built-in command (no ``/<name>`` entry;
- ``agent.skill_commands`` guard), ``""`` when none."""
- usage, origin_of = _skill_usage_lookup()
- sc = _tools_mod("agent.skill_commands")
- for k, info in sorted(sc.get_interactive_skill_commands().items()):
- cat.pairs.append([k, str(info.get("description", "Skill"))])
- name = str(info.get("name") or k.lstrip("/"))
- skills[k] = {"usage": usage(name), "origin": origin_of(name)}
- names = sorted(s["name"] for s in _tools_mod("tools.skills_tool")._find_all_skills())
- return "; ".join(filter(None, map(sc.skill_command_collision_note, names)))
-
-
@_rpc("commands.catalog", 5020)
def _(rid, params: dict) -> dict:
- """Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``
- (skills' message wins, then quick commands', then plugins'); only with no failure does it carry
- the built-in-name collision notice for skills that have no ``/<name>`` (empty when none). Quick
- command, plugin command and skill discovery are all home-keyed, so every loader runs bound to the
- calling session's profile and workspace (``_completion_cwd``: its record, else the cwd a new
- session would be seeded with) so project-local skills register for the repo the session is
- actually in (#114359); a session-less draft is bound to ``params['profile']`` (#124651), and an
- unknown profile is 4064 like ``complete.slash`` — never a launch-profile palette."""
- cat = _Catalog()
- _catalog_registry(cat)
- warning = ""
- skills: dict[str, dict] = {}
- with _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params),
- profile=params.get("profile")):
- try:
- _catalog_quick_commands(cat)
- except Exception as e:
- warning = f"quick_commands discovery unavailable: {e}"
- try:
- _catalog_plugin_commands(cat)
- except Exception as e:
- warning = warning or f"plugin command discovery unavailable: {e}"
- try:
- collision_note = _catalog_skills(cat, skills) # always runs: skills must list even when a loader failed
- warning = warning or collision_note
- except Exception as e:
- warning = f"skill discovery unavailable: {e}"
- return _ok(rid, {
- "pairs": cat.pairs, "sub": {k: v[:] for k, v in _tools_mod("hermes_cli.commands").SUBCOMMANDS.items()},
- "canon": cat.canon,
- "commands": cat.commands,
- "categories": [{"name": c, "pairs": rows} for c, rows in cat.cat_map.items()],
- "skills": skills, "skill_count": len(skills), "warning": warning})
+ """Registry-backed slash metadata, categorized, no aliases (shared builder in command_discovery). Skill
+ discovery is bound to the calling session's profile and workspace (``_completion_cwd``: its record,
+ else the cwd a new session would be seeded with) so project-local skills register for the repo the
- session is actually in (#114359)."""
++ session is actually in (#114359); a session-less draft is bound to ``params['profile']`` (#124651) and
++ an unknown profile is 4064 like ``complete.slash`` — never a launch-profile palette.
++ Every loader (quick, plugin, skill) runs inside the scope."""
+ from tui_gateway.command_discovery import command_catalog
- scope = _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params))
++ scope = _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params),
++ profile=params.get("profile"))
+ return _ok(rid, command_catalog(load_cfg=_load_cfg, module_loader=_tools_mod, scope=scope))
@method("cli.exec")
diff --cc tui_gateway/prompt_attachments.py
index 6e4704aa622,5c612ee82cc..01cf6cda398
--- a/tui_gateway/prompt_attachments.py
+++ b/tui_gateway/prompt_attachments.py
@@@ -135,37 -134,29 +135,39 @@@ def _session_images_dir(session: dict)
return _session_home_dir(session, "images")
+def stage_image_bytes(directory, img_bytes: bytes, ext: str, *, prefix: str):
+ """Private, collision-free staging shared by local and canonical byte uploads."""
+ import os
+ from pathlib import Path
+ import tempfile
+ directory = Path(directory)
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
+ fd, name = tempfile.mkstemp(dir=directory, prefix=prefix + "_", suffix=ext)
+ path = Path(name)
+ try:
+ with os.fdopen(fd, "wb") as output:
+ output.write(img_bytes)
+ output.flush()
+ os.fsync(output.fileno())
+ except BaseException:
+ path.unlink(missing_ok=True)
+ raise
+ return path
+
+
def _queue_attached_image(session: dict, img_bytes: bytes, ext: str, *, prefix: str) -> Path:
"""Write image bytes into the session images dir and queue them for the next submit."""
+ session["image_counter"] = session.get("image_counter", 0) + 1
img_dir = _session_images_dir(session)
- img_dir.mkdir(parents=True, exist_ok=True)
- ts = datetime.now().strftime("%Y%m%d_%H%M%S")
- counter = session.get("image_counter", 0) + 1
- while True:
- candidate = img_dir / f"{prefix}_{ts}_{counter}{ext}"
- try:
- upload = candidate.open("xb")
- except FileExistsError:
- counter += 1
- else:
- break
- session["image_counter"] = counter
try:
- with upload:
- upload.write(img_bytes)
++ # mkstemp allocation is atomic across sessions sharing the profile images dir (main #b4faf6587e9's
++ # cross-session collision fix holds without the counter-named xb probe loop).
+ img_path = stage_image_bytes(img_dir, img_bytes, ext, prefix=prefix)
except Exception:
- candidate.unlink(missing_ok=True)
+ session["image_counter"] = max(0, session["image_counter"] - 1)
raise
- session.setdefault("attached_images", []).append(str(candidate))
- return candidate
+ session.setdefault("attached_images", []).append(str(img_path))
+ return img_path
def _format_ref_value(value: str) -> str:
diff --cc tui_gateway/server.py
index 6a04ed158dc,ed5bf22e2b5..bf946cba91e
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@@ -2042,10 -3666,10 +2157,11 @@@ from . import ( # noqa: E40
methods_vault as _methods_vault, methods_free_tier as _methods_free_tier,
methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account,
methods_display as _methods_display, methods_display_watch as _methods_display_watch,
- methods_onboarding as _methods_onboarding)
+ methods_onboarding as _methods_onboarding, methods_i18n as _methods_i18n,
+ methods_shared_metrics as _methods_shared_metrics)
for _m in (
+ _session_registry, _agent_factory,
_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
_session_compression, _change_watcher, _tool_progress, _session_notifications,
_prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue, _plugin_inject, _rpc_dispatch,
diff --cc tui_gateway/session_notifications.py
index 6d44dc73159,b17807be8c6..dc55f8a71fb
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@@ -764,11 -839,22 +767,21 @@@ def _start_notification_poller(sid: str
def _hud_surface_note(session: dict) -> str:
- """The per-surface note for this turn ("" for the plain app window): HUD → the read-the-window-below
- prior; voice-live → the spoken-delegation contract (transcript in, speakable prose out)."""
- surface = session.get("client_surface")
+ """The per-surface note for this turn ("" for the plain app window): HUD -> the read-the-window-below
+ prior; voice-live -> the spoken-delegation contract with the recent transcript."""
+ from gateway.session_surface import surface_note
- committed = {"surface": session.get("client_surface"), "voice_context": session.get("voice_live_context")}
- return surface_note(committed, getattr(session.get("agent"), "valid_tool_names", None))
++ surface, agent = session.get("client_surface"), session.get("agent")
++ direct = getattr(agent, "valid_tool_names", None) or set()
+ if surface == "hud":
- from agent.prompt_builder import hud_surface_note
+ from tools.tool_search_catalog import TOOL_CALL_NAME
- agent = session.get("agent")
- direct = getattr(agent, "valid_tool_names", None) or set()
- if TOOL_CALL_NAME not in direct:
- return hud_surface_note(direct)
- from agent.tool_executor import _tool_search_scoped_names
- return hud_surface_note(direct, _tool_search_scoped_names(agent))
- if surface == "voice-live":
- from tools.voice_live import voice_live_turn_note
- return voice_live_turn_note(session.get("voice_live_context") or "")
- return ""
++ if TOOL_CALL_NAME in direct:
++ # Tool search defers the desktop tools by default: they stay callable through the
++ # tool_call bridge, so the HUD note must count them and name the bridge (main 312f6bc2fd6).
++ from agent.prompt_builder import hud_surface_note
++ from agent.tool_executor import _tool_search_scoped_names
++ return hud_surface_note(direct, _tool_search_scoped_names(agent))
++ committed = {"surface": surface, "voice_context": session.get("voice_live_context")}
++ return surface_note(committed, direct)
def _prepend_note(run_message: Any, note: str) -> Any:
diff --cc tui_gateway/session_registry.py
index 87a781f1dc9,00000000000..72d9cdad33a
mode 100644,000000..100644
--- a/tui_gateway/session_registry.py
+++ b/tui_gateway/session_registry.py
@@@ -1,725 -1,0 +1,787 @@@
+"""TUI session_registry seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
++import re
++
+from .method_ctx import bind_module
+
+def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None:
+ ready = session.get("agent_ready")
+ if ready is not None and not ready.wait(timeout=timeout):
+ return _err(rid, 5032, AGENT_STILL_STARTING)
+ return _err(rid, 5032, err) if (err := session.get("agent_error")) else None
+
+
+# The deferred prompt path waits in short slices so a cancel is honored promptly and a slow
+# build is reported to the client exactly once.
+_AGENT_BUILD_WAIT_SLICE = 5.0
+_AGENT_BUILD_SLOW_NOTICE_AFTER = 30.0
+_AGENT_BUILD_SLOW_NOTICE_KEY = "agent-build-slow"
+
+
+def _agent_build_wait_cap() -> float:
+ """Seconds a submitted prompt waits for the deferred build before failing; ``agent.build_wait_timeout``
+ overrides the 600s default (raise it for many slow MCP servers / high-latency provider metadata)."""
+ with contextlib.suppress(Exception):
+ raw = (_load_cfg().get("agent") or {}).get("build_wait_timeout")
+ if raw is not None and float(raw) > 0:
+ return float(raw)
+ return 600.0
+
+
+def _wait_agent_for_prompt(session: dict, rid: str, sid: str) -> dict | None:
+ """Patient ``_wait_agent`` for deferred prompt.submit: the client already got ``streaming`` and the
+ first message IS the turn, while a cold build routinely outlives the flat 30s ceiling (timing out
+ silently discarded it). Waits in short slices (cancel honored promptly), notifies once (keyed) past
+ ``_AGENT_BUILD_SLOW_NOTICE_AFTER``, fails only on a dead build thread or the bounded cap.
+ Returns None on success OR cancel mid-wait (the caller's cancel branch owns that messaging).
+
+ The flat 30s ``_wait_agent`` ceiling was a message-eating cliff (#63078): ``prompt.submit`` has already
+ returned ``{"status": "streaming"}``, the user's first message IS the turn in flight, and the deferred
+ agent build (MCP discovery with per-server retry backoff, synchronous model-metadata HTTP, skills
+ scanning) routinely outlives 30 seconds on cold starts. On timeout the old path emitted an error EVENT
+ and returned without ever calling ``_run_prompt_submit`` — the first message was permanently discarded
+ while the build finished successfully in the background, leaving the blank first session.
+ """
+ ready = session.get("agent_ready")
+ if ready is None:
+ return None
+ start, cap, notified_slow = time.monotonic(), _agent_build_wait_cap(), False
+ while not ready.wait(timeout=_AGENT_BUILD_WAIT_SLICE):
+ with session["history_lock"]:
+ cancelled = session.get("_turn_cancel_requested") or not session.get("running")
+ if cancelled:
+ return None
+ waited = time.monotonic() - start
+ if waited >= cap:
+ return _err(rid, 5032, f"agent initialization timed out after {int(waited)}s — "
+ "your message was not sent; retry once the session is ready")
+ build_thread = session.get("_agent_build_thread")
+ if build_thread is not None and not build_thread.is_alive() and not ready.is_set():
+ # _build's finally guarantees ready.set(); dead thread + unset ready = died hard.
+ return _err(rid, 5032, session.get("agent_error") or "agent initialization failed before completing")
+ if not notified_slow and waited >= _AGENT_BUILD_SLOW_NOTICE_AFTER:
+ notified_slow = True # one keyed, replace-in-place notice (toast / status bar)
+ _emit("notification.show", sid, {
+ "text": "Still starting the agent (tool discovery / model setup) — your message will be sent as soon as it's ready.",
+ "level": "info", "kind": "agent", "ttl_ms": None,
+ "key": _AGENT_BUILD_SLOW_NOTICE_KEY, "id": _AGENT_BUILD_SLOW_NOTICE_KEY})
+ if notified_slow:
+ _emit("notification.clear", sid, {"key": _AGENT_BUILD_SLOW_NOTICE_KEY})
+ return _err(rid, 5032, err) if (err := session.get("agent_error")) else None
+
+
+def _bind_build_profile_scopes(profile_home: "str | None") -> "_TurnScopes | None":
+ """Bind a session profile's HERMES_HOME / secret / terminal scopes for an agent build. ``None`` is the
+ launch profile: its own launch-env secret scope (live env while single-profile, frozen once
+ multiplexing is active — a hosted-room turn for a default member otherwise died at build with
+ ``UnscopedSecretError`` because the launch profile was treated as "no scope"). Fail-open per scope (the build must not die on
+ a scope helper); the terminal installer itself fails closed (malformed policy → refusal scope) so
+ _make_agent's terminal probing / cwd hints resolve the routed profile."""
+ scopes = _TurnScopes()
+ with contextlib.suppress(Exception):
+ return _profile_runtime_scope_tokens(profile_home)
+ if profile_home: # secret/terminal helper failed: keep at least the home + terminal refusal scope
+ scopes.home = set_hermes_home_override(profile_home)
+ with contextlib.suppress(Exception):
+ from tools.terminal_scope import install_profile_terminal_scope
+ scopes.terminal = install_profile_terminal_scope(Path(profile_home))
+ return scopes
+
+
+def _release_build_profile_scopes(scopes: "_TurnScopes | None") -> None:
+ with contextlib.suppress(Exception):
+ _release_profile_runtime_scope_tokens(scopes)
+
+
+def _deferred_build_agent_kwargs(current: dict, session_db) -> dict:
+ """_make_agent kwargs for a deferred (first-prompt) build. A lazy-resumed (watch) session carries the
+ stored conversation id so the upgrade continues it; a cold deferred resume restores the full persisted
+ runtime identity (like the eager resume's overrides splat) so the build can't drop the provider. No
+ stored runtime, or an unroutable provider → this session's picked model/effort/tier, else the default."""
+ kw = {"session_db": session_db, "context_cwd_is_launch_artifact": _context_cwd_is_launch_artifact(current),
+ "platform_override": _session_source(current), "cwd_override": _session_cwd(current)}
+ if resume_sid := current.get("resume_session_id"):
+ kw["session_id"] = resume_sid
+ resume_overrides = current.get("resume_runtime_overrides")
+ if isinstance(resume_overrides, dict) and resume_overrides and _overrides_have_routable_provider(resume_overrides):
+ kw.update(resume_overrides)
+ else:
+ if override := current.get("model_override"):
+ kw["model_override"] = override
+ kw.update({k: v for k, v in (("reasoning_config_override", current.get("create_reasoning_override")),
+ ("service_tier_override", current.get("create_service_tier_override")))
+ if v is not None})
+ return kw
+
+
+def _wire_session_agent(sid: str, key: str, agent) -> bool:
+ """Post-build wiring; returns whether the approval notify got registered. Approval prompts route to the
+ client; the self-improvement "💾 …" summary is emitted as review.summary (no print surface), honoring
+ display.memory_notifications."""
+ notify_registered = False
+ with contextlib.suppress(Exception):
+ from tools.approval import load_permanent_allowlist, register_gateway_notify
+ register_gateway_notify(key, lambda data: _emit_approval_request(sid, data))
+ notify_registered = True
+ load_permanent_allowlist()
+ _wire_callbacks(sid)
+ with contextlib.suppress(Exception): # bare agents without the attribute must not break startup
+ agent.background_review_callback = lambda message, _sid=sid: _emit("review.summary", _sid, {"text": str(message)})
+ agent.memory_notifications = _load_memory_notifications()
+ return notify_registered
+
+
+def _start_session_services(sid: str, key: str, current: dict) -> None:
+ """Start the notification poller and fire the session-reset boundary hook."""
+ with _sessions_lock:
+ if (rec := _sessions.get(sid)) is not None:
+ rec["_notif_stop"] = _start_notification_poller(sid, rec)
+ _notify_session_boundary("on_session_reset", key, _session_source(current))
+
+
+def _await_resume_history(sid: str, current: dict) -> bool:
+ """Block on a cold resume's transcript hydration; False when this record was replaced meanwhile."""
+ history_ready = current.get("resume_history_ready")
+ if history_ready is None:
+ return True
+ if not history_ready.wait(timeout=300.0):
+ raise TimeoutError("session history hydration timed out")
+ if history_error := current.get("resume_history_error"):
+ raise RuntimeError(str(history_error))
+ with _sessions_lock:
+ return _sessions.get(sid) is current
+
+
- def _attach_built_agent(current: dict, agent) -> None:
- """Attach a freshly built agent to its live record (session DB row deferred to first run_conversation())."""
++def _attach_built_agent(sid: str, current: dict, agent) -> bool:
++ """Attach a freshly built agent to its live record (session DB row deferred to first run_conversation()).
++ False when ``session.close`` popped this record mid-build: teardown saw ``agent=None`` and closed
++ nothing, so the caller owns closing the orphan (#49852)."""
+ # Bot Mode gate hint: the DB title lands post-first-turn but the system prompt builds at turn START.
+ if _title_hint := str(current.get("pending_title") or "").strip():
+ agent._session_title_hint = _title_hint
- current["agent"] = agent
++ # Under the same lock session.close takes to pop the record: no window between "still live" and "attached".
++ with _sessions_lock:
++ if _sessions.get(sid) is not current:
++ return False
++ current["agent"] = agent
+ # A workspace move can land while construction is still in flight.
+ _register_session_cwd(current)
+ _session_todo_state(current)
+ # Baseline for the per-turn config sync (profile home override still active).
+ current["config_model_seen"] = _config_model_target()
++ return True
+
+
+def _announce_built_agent(sid: str, key: str, current: dict, agent) -> None:
+ """Post-wiring tail of a build: credits seed, session services, session.info, late MCP catch-up."""
+ # Credits notices at session OPEN (notice_callback already wired) so depletion warnings show at "ready".
+ with contextlib.suppress(Exception):
+ from agent.credits_tracker import seed_credits_at_session_start
+ seed_credits_at_session_start(agent)
+ _start_session_services(sid, key, current)
+ info = _session_info(agent, current)
+ if cfg_warn := _probe_config_health(_load_cfg()):
+ info["config_warning"] = cfg_warn
+ logger.warning(cfg_warn)
+ _emit("session.info", sid, info)
+ _schedule_mcp_late_refresh(sid, agent) # servers slower than the bounded discovery wait land here
+
+
+def _finish_agent_build(sid: str, key: str, current: dict, *, notify_registered: bool, scopes, session_db) -> None:
+ """Release build scopes and settle ownership of the late notify registration + dedicated db handle."""
+ if scopes is not None:
+ _release_build_profile_scopes(scopes)
- # Reaped mid-build: _attach_worker closed the worker; only a late notify registration can still
- # leak (session.close unregistered before _build registered).
++ # Reaped after the agent was attached: _attach_worker closed the worker; only a late notify
++ # registration can still leak (session.close unregistered before _build registered).
+ with _sessions_lock:
+ replaced = _sessions.get(sid) is not current
+ if replaced and notify_registered:
+ with contextlib.suppress(Exception):
+ from tools.approval import unregister_gateway_notify
+ unregister_gateway_notify(key)
+ # Dedicated profile handle: hand it to the agent that will be torn down, else close it (build
+ # failed, or `replaced`: this agent is discarded and _teardown_session never reaches it).
+ if session_db is not None and not _transfer_db_to_agent(None if replaced else current.get("agent"), session_db):
+ with contextlib.suppress(Exception):
+ session_db.close()
+
+
+def _start_agent_build(sid: str, session: dict) -> None:
+ """Start building the real AIAgent for a TUI session, once. Deferred until the first prompt (or any
+ command needing the agent) so the composer isn't blocked on tool discovery / model metadata;
+ the ready/error event contract is unchanged."""
+ ready = session.get("agent_ready")
+ if ready is None:
+ return
+ # A lazy watch session spectating an in-flight child must stay lazy so the subagent live-mirror keeps
+ # flowing (it bails once agent is set); incidental RPCs via _sess() would upgrade it mid-stream.
- if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):
++ if session.get("lazy") and _child_run_active(
++ str(session.get("session_key") or ""), session.get("profile_home") or None):
+ return
+ with session.setdefault("agent_build_lock", threading.Lock()):
+ if ready.is_set() or session.get("agent_build_started"):
+ return
+ session["agent_build_started"] = True
+ session.pop("lazy", None) # now genuinely mid-construction: restore the "still starting" eviction exemption
+ key = session["session_key"]
+
+ def _build() -> None:
+ with _sessions_lock:
+ current = _sessions.get(sid)
+ if current is None:
+ # Closed/reaped before the build started: nothing will ever attach an agent to this
+ # record, yet ``agent_ready`` must be set so a prompt waiting on it fails instead of hanging.
+ session["agent_error"] = AGENT_BUILD_ABANDONED
+ ready.set()
+ return
+ notify_registered, scopes, session_db = False, None, None
+ profile_home = current.get("profile_home")
+ try:
+ if not _await_resume_history(sid, current):
+ # Replaced mid-build: the finally still sets ``agent_ready`` with ``agent`` None, so record
+ # why — a turn admitted against this record refuses with the real reason (#111531).
+ current["agent_error"] = AGENT_BUILD_ABANDONED
+ return
+ tokens = _set_session_context(key, cwd=_session_cwd(current))
+ # Global-remote: bind the session profile's HERMES_HOME and hand the agent that profile's db —
+ # DEDICATED and ours until _transfer_db_to_agent in the finally; FAIL CLOSED rather than
+ # binding the launch DB and bleeding rows into the wrong state.db.
+ scopes = _bind_build_profile_scopes(profile_home)
+ if profile_home:
+ session_db = _open_profile_session_db(profile_home)
+ try:
+ from tui_gateway.entry import ensure_mcp_discovery_started
+ ensure_mcp_discovery_started()
+ except Exception:
+ logger.warning("MCP discovery startup failed", exc_info=True)
+ try:
+ agent = _make_agent(sid, key, **_deferred_build_agent_kwargs(current, session_db))
+ finally:
+ _clear_session_context(tokens)
- _attach_built_agent(current, agent)
++ # Attach atomically against session teardown: ``session.close`` may have popped this
++ # session while the expensive build was in flight, in which case teardown could not close
++ # an agent that did not exist yet. Release the orphan immediately and do not keep wiring
++ # workers/callbacks for a dead session (#49852).
++ if not _attach_built_agent(sid, current, agent):
++ # Same contract as the replaced-before-attach exit above: a turn admitted against
++ # this record must refuse with the real reason rather than a generic missing agent.
++ current["agent_error"] = AGENT_BUILD_ABANDONED
++ with contextlib.suppress(Exception):
++ if hasattr(agent, "close"):
++ agent.close()
++ return
+ # No eager slash-worker pre-warm (slash.exec spawns on demand): each worker forks the full stdio
+ # MCP fleet, and live-transport sessions are never reaped, so fleets would accumulate.
+ notify_registered = _wire_session_agent(sid, key, agent)
+ _announce_built_agent(sid, key, current, agent)
+ except Exception as e:
++ from agent.auxiliary_unavailable import ProviderNotConfiguredError
+ current["agent_error"] = str(e)
- _emit("error", sid, {"message": agent_init_failed_message(e)})
++ # A client can route "no provider is set up" to its setup flow instead of a dead-end
++ # error toast — but only if it can tell. The sentence is for the reader, the code is
++ # for the client; older clients keep matching the text.
++ _emit("error", sid, {
++ "message": agent_init_failed_message(e),
++ **({"code": "provider_not_configured"} if isinstance(e, ProviderNotConfiguredError) else {})})
+ finally:
+ _finish_agent_build(
+ sid, key, current, notify_registered=notify_registered, scopes=scopes, session_db=session_db)
+ ready.set()
+
+ build_thread = threading.Thread(target=_build, daemon=True)
+ # _wait_agent_for_prompt handle: dead thread + unset agent_ready = died hard; waiters must not sit out the cap.
+ session["_agent_build_thread"] = build_thread
+ build_thread.start()
+
+
+def _sess_nowait(params, rid):
+ sid = params.get("session_id") or ""
+ s = _sessions.get(sid)
+ if s:
+ return (s, None)
+ # Stale runtime id (reaped/evicted/TTL): the client should session.resume the STORED id. Logged so
+ # "message vanished" reads as "arrived and was rejected".
+ logger.warning("session-scoped RPC rejected: method=%s session_id=%r not in memory "
+ # A session-scoped RPC hit a runtime id the gateway no longer holds (detached on WS
+ # disconnect and orphan-reaped, LRU-evicted, or torn down after an idle TTL). The client
+ # is expected to recover via session.resume on the STORED session id, but a plain
+ # stale-id send leaves no trace anywhere when the resume never fires — every RPC in this
+ # class returned a silent 4001. Log it so a "message vanished" report is diagnosable as
+ # "request arrived and was rejected" instead of "request never arrived" (see #90428).
+ "(detached/reaped runtime; client should resume the stored session), rid=%r",
+ _current_rpc_method.get() or "?", sid, rid)
+ return (None, _err(rid, 4001, "session not found"))
+
+
+def _sess(params, rid):
+ s, err = _sess_building(params, rid)
+ return (None, err) if err else (s, _wait_agent(s, rid))
+
+
+def _sess_building(params, rid):
+ """Resolve a session and warm its agent build WITHOUT waiting — for the attach RPCs (image/file/pdf,
+ clipboard.paste, image.detach), which only touch creation-time fields and run inline on the socket
+ reader thread, where waiting on a cold build stalled every RPC behind it ("text is instant, images hang")."""
+ s, err = _sess_nowait(params, rid)
+ if not err:
+ _start_agent_build(params.get("session_id") or "", s)
+ return (None, err) if err else (s, None)
+
+def _init_session(
+ sid: str, key: str, agent, history: list, cols: int = 80, cwd: str | None = None,
+ session_db=None, source: str | None = None, profile_home: str | None = None,
+ explicit_cwd: bool = False):
+ now = time.time()
+ with _sessions_lock:
+ _sessions[sid] = {
+ "agent": agent, "session_key": key, "history": history, "history_lock": threading.Lock(),
+ "history_version": 0, "inflight_turn": None, "created_at": now, "last_active": now,
+ "running": False, "attached_images": [], "image_counter": 0, "cwd": cwd or _completion_cwd(),
+ "explicit_cwd": bool(explicit_cwd), "cols": cols, "slash_worker": None,
+ "show_reasoning": _load_show_reasoning(), "source": _resolve_session_source(source),
+ "tool_progress_mode": _load_tool_progress_mode(), "edit_snapshots": {}, "tool_started_at": {},
+ # Profile-scoped HERMES_HOME (None = launch); SessionBranch copies the parent's (same state.db).
+ "profile_home": profile_home,
+ # In-session /model switch, honored on rebuild (/new, resume) — never leaks to siblings via env vars.
+ "model_override": None,
+ # Async events go to the transport that created the session (stdio for Ink, WS for the dashboard).
+ "transport": current_transport() or _stdio_transport,
+ "auth_user_id": _transport_auth_user_id(current_transport()),
+ }
+ _session_todo_state(_sessions[sid])
+ _hydrate_session_cwd(sid, key, session_db, profile_home)
+ _register_session_cwd(_sessions[sid])
+ _wire_session_agent(sid, key, agent) # no eager slash-worker pre-warm (see _start_agent_build)
+ _start_session_services(sid, key, _sessions.get(sid, {}))
+ _emit("session.info", sid, _session_info(agent, _sessions.get(sid, {})))
+ _schedule_mcp_late_refresh(sid, agent)
+
+
+def _new_session_key() -> str:
+ return new_session_id()
+
+
++# Server-minted session keys are ``%Y%m%d_%H%M%S_`` + 6 hex chars (see
++# ``_new_session_key``). session.resume uses this shape as the fail-closed gate
++# for materializing a row for a minted-but-never-persisted key: only keys the
++# server itself could have produced qualify — arbitrary strings and 8-hex
++# runtime session ids (``uuid4().hex[:8]``) are rejected.
++_MINTED_SESSION_KEY_RE = re.compile(r"^\d{8}_\d{6}_[0-9a-f]{6}$")
++
++
++def _is_server_minted_key(value: str | None) -> bool:
++ return bool(value and _MINTED_SESSION_KEY_RE.fullmatch(value))
++
++
++def _any_live_session_claims_key(target: str) -> bool:
++ """True if any live registry record claims this stored key (any profile).
++
++ Fail-closed gate for minted-key materialization: a key claimed by a live
++ session — even one scoped to a different profile — is owned, so an
++ unscoped resume must not mint a phantom row in the launch store (#93296
++ cross-profile rule: routing guesses are forbidden).
++ """
++ for record in list(_sessions.values()):
++ if not isinstance(record, dict):
++ continue
++ if str(record.get("session_key") or "") == target:
++ return True
++ return False
++
++
+def _with_checkpoints(session, fn):
+ return fn(session["agent"]._checkpoint_mgr, _session_cwd(session))
+
+
+def _resolve_checkpoint_hash(mgr, cwd: str, ref: str) -> str:
+ try:
+ checkpoints = mgr.list_checkpoints(cwd)
+ idx = int(ref) - 1
+ except ValueError:
+ return ref
+ if 0 <= idx < len(checkpoints):
+ return checkpoints[idx].get("hash", ref)
+ raise ValueError(f"Invalid checkpoint number. Use 1-{len(checkpoints)}.")
+
+
+# ── Methods: session ─────────────────────────────────────────────────
+
+
+def _lazy_resume_info(cwd: str, *, model: str = "", provider: str = "", profile: str | None = None) -> dict:
+ """session.info for a not-yet-built session (session.create's shape); tools/skills land with the deferred build."""
+ return {
+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd),
+ "model": model or _session_default_model({"profile_home": _profile_home(profile)}),
+ "tools": {}, "skills": {}, "lazy": True,
+ "desktop_contract": DESKTOP_BACKEND_CONTRACT, "profile_name": _response_profile_name(profile),
+ **({"provider": provider} if provider else {}),
+ }
+
+
+def _deferred_session_record(
+ session_key: str, *, cols: int, cwd: str, history: list, lease, source: str = "tui",
+ close_on_disconnect: bool = False, display_history_prefix: list | None = None,
+ profile_home: Path | None = None, lazy: bool = False, model_override=None,
+ resume_runtime_overrides: dict | None = None, todo_state: dict | None = None,
+ explicit_cwd: bool = False) -> dict:
+ """A live-session record whose AIAgent is built later (lazy watch / cold resume) — _init_session's shape minus the agent."""
+ now = time.time()
+ return {
+ "agent": None, "agent_error": None, "agent_ready": threading.Event(), "attached_images": [],
+ "close_on_disconnect": close_on_disconnect, "active_session_lease": lease, "cols": cols,
+ "created_at": now, "cwd": cwd, "display_history_prefix": display_history_prefix or [],
+ "edit_snapshots": {}, "explicit_cwd": bool(explicit_cwd), "history": history,
+ "history_lock": threading.Lock(), "history_version": 0, "image_counter": 0,
+ "inflight_turn": None, "last_active": now, "lazy": lazy, "model_override": model_override,
+ "pending_title": None,
+ "profile_home": str(profile_home) if profile_home is not None else None,
+ "resume_runtime_overrides": resume_runtime_overrides, "resume_session_id": session_key,
+ "running": False, "session_key": session_key, "show_reasoning": _load_show_reasoning(),
+ "slash_worker": None, "source": source, "tool_progress_mode": _load_tool_progress_mode(),
+ "tool_started_at": {}, "todo_state": todo_state,
+ "transport": current_transport() or _stdio_transport,
+ "auth_user_id": _transport_auth_user_id(current_transport()),
+ }
+
+
+_ANY_PROFILE = object() # default: match a live session regardless of profile
+
+
+def _live_profile_matches(session: dict, profile_home) -> bool:
+ """True when ``session`` belongs to ``profile_home`` (None = launch profile; a record with no
+ ``profile_home`` is the launch profile's). ``_ANY_PROFILE`` disables the check."""
+ if profile_home is _ANY_PROFILE:
+ return True
+ return (session.get("profile_home") or None) == (str(profile_home) if profile_home else None)
+
+
+def _claim_or_reuse_live(sid: str, session_key: str, record: dict, lease) -> tuple[str, dict] | None:
+ """Register ``record`` as the live session for ``session_key`` under the resume lock, or — if a
+ concurrent resume already won — release ``lease`` and return the winner for the caller to reuse."""
+ # A live runtime of the same stored id under ANOTHER profile is not a winner to reuse.
+ # See #100029.
+ profile_home = record.get("profile_home")
+ with _session_resume_lock:
+ live = _find_live_session_by_key(session_key, profile_home)
+ if live is not None:
+ if lease is not None:
+ lease.release()
+ # The reap is cancelled by the guarded reuse (_reattach_refusal), not here: a rejected
+ # reattach must leave an in-flight orphan interrupt polling.
+ return live
+ with _sessions_lock:
+ _sessions[sid] = record
+ _register_session_cwd(_sessions[sid])
+ # A PRIOR runtime for this stored id may still be sentinel-parked with a reap Timer armed; cancel +
+ # finalize it quietly so the reap doesn't broadcast session.reclaimed (storm).
+ _cancel_ws_orphan_reap(sid)
+ stale = _claim_parked_runtimes(session_key, keep_sid=sid, profile_home=profile_home)
+ _finalize_superseded_runtimes(stale) # slow finalization stays OUTSIDE _session_resume_lock
+ return None
+
+
+def _claim_parked_runtimes(session_key: str, *, keep_sid: str, profile_home=_ANY_PROFILE) -> list[tuple[str, dict]]:
+ """Claim sentinel-parked stale runtimes of ``session_key`` for supersession: cancel their orphan-reap
+ Timer and pop them here (under the caller's _session_resume_lock); the caller finalizes after release."""
+ stale: list[tuple[str, dict]] = []
+ with _sessions_lock:
+ candidates = [
+ (old_sid, old) for old_sid, old in list(_sessions.items())
+ if old_sid != keep_sid and not old.get("_finalized")
+ and _session_lookup_key(old, fallback=old_sid) == session_key
+ and _live_profile_matches(old, profile_home) and old.get("transport") is _detached_ws_transport]
+ for old_sid, _old in candidates:
+ _cancel_ws_orphan_reap(old_sid)
+ if (popped := _pop_session_by_id(old_sid)) is not None:
+ stale.append((old_sid, popped))
+ return stale
+
+
+def _finalize_superseded_runtimes(stale: list[tuple[str, dict]]) -> None:
+ """end_reason ``superseded_by_resume`` is deliberately NOT in _RECLAIM_END_REASONS (no ``session.reclaimed``
+ broadcast → no reap->broadcast->resume loop) but IN _RECOVERABLE_END_REASONS (Bot Chat resurrection applies)."""
+ for old_sid, popped in stale:
+ try:
+ _teardown_popped_session(popped, end_reason="superseded_by_resume")
+ except Exception:
+ logger.exception("superseded runtime teardown failed sid=%s", old_sid)
+
+
+def _schedule_agent_build(sid: str, delay: float = 0.05) -> None:
+ """Pre-warm a deferred session's agent off the response path (session.create + cold resume; _sess() also builds on demand)."""
+
+ def _run():
+ if (session := _sessions.get(sid)) is not None:
+ _start_agent_build(sid, session)
+ timer = threading.Timer(delay, _run)
+ timer.daemon = True
+ timer.start()
+
+
+def _load_resume_transcript(db, stored_id: str, *, model_history_only: bool = False) -> tuple[list, list, list]:
+ """(raw_history, display_history, ancestor_prefix) for a cold resume. The full lineage is materialized
+ only while it fits sessions.max_resume_messages (the transcript is REST-paginated), else the tip alone."""
+ from hermes_state import SessionResumeTooLargeError
+ if model_history_only:
+ raw_history = db.get_messages_as_conversation(
+ stored_id, repair_alternation=True, include_row_ids=True)
+ return raw_history, [], []
+ prefix_fits = True
+ guard = getattr(db, "assert_resume_safe", None)
+ if callable(guard):
+ try:
+ guard(stored_id)
+ except SessionResumeTooLargeError as exc:
+ prefix_fits = False
+ logger.info("resume %s: compression lineage exceeds the resume limit (%s); hydrating the tip segment only",
+ stored_id, exc)
+ except Exception:
+ logger.debug("resume lineage guard failed; loading full lineage", exc_info=True)
+ if prefix_fits:
+ raw_history, display_history = db.get_resume_conversations(stored_id)
+ return raw_history, display_history, db.get_ancestor_display_prefix(stored_id)
+ raw_history = db.get_messages_as_conversation(stored_id, repair_alternation=True, include_row_ids=True)
+ return raw_history, raw_history, []
+
+
+def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool = False,
+ model_history_only: bool = False) -> None:
+ """Load a cold resume's transcript off the JSON-RPC response path."""
+
+ def _run() -> None:
+ session = _sessions.get(sid)
+ try:
+ if session is None:
+ return
+ _emit("session.resume_progress", sid, {"phase": "history", "status": "loading"})
- db.reopen_session(stored_id)
++ # Read-only mount (#85303): hydration is a read; an ended row stays ended —
++ # the first real turn (prompt.submit) reopens it. But a restart discarded the
++ # busy-queue, so retire never-drained accept rows (#125577) before the read —
++ # with #128508 the reopen (and its retire) no longer runs on this path.
++ # Best-effort like the resume guard: a handle without the method skips it.
++ retire = getattr(db, "retire_undrained_queue_rows", None)
++ if callable(retire):
++ retire(stored_id)
+ raw_history, display_history, prefix = _load_resume_transcript(
+ db, stored_id, model_history_only=model_history_only)
+ # Display keeps the full transcript; the model-fed history uses the
+ # same canonicalization as gateway resume and the send path.
+ history = canonicalize_replay_history(raw_history)
+ if _sessions.get(sid) is not session:
+ return
+ with session["history_lock"]:
+ session.update(history=history, display_history_prefix=prefix, resume_hydrating=False)
+ if not model_history_only:
+ session["resume_message_count"] = len(display_history)
+ # Deferred resumes answered before the transcript existed; cache the derived todo snapshot now.
+ todo_state = _todo_state_from_history(history)
+ if todo_state is not None and session.get("todo_state") is None:
+ session["todo_state"] = todo_state
+ session["resume_history_ready"].set()
+ _emit("session.resume_progress", sid,
+ {"message_count": session["resume_message_count"], "phase": "history", "status": "complete"})
+ _maybe_schedule_auto_continue(sid, session, stored_id)
+ _start_agent_build(sid, session)
+ except Exception as exc:
+ if _sessions.get(sid) is not session:
+ return
+ message = resume_failed_message(exc)
+ session.update(resume_hydrating=False, resume_history_error=message, agent_error=message)
+ session["resume_history_ready"].set()
+ session["agent_ready"].set()
+ _emit("session.resume_progress", sid, {"message": message, "phase": "history", "status": "failed"})
+ _emit("error", sid, {"message": message})
+ with _sessions_lock:
+ discarded = _sessions.pop(sid, None) if _sessions.get(sid) is session else None
+ if (lease := (discarded or {}).get("active_session_lease")) is not None:
+ lease.release()
+ finally:
+ if close_db and hasattr(db, "close"):
+ try:
+ db.close()
+ except Exception:
+ logger.debug("failed to close resume db for %s", sid, exc_info=True)
+ threading.Thread(target=_run, daemon=True).start()
+
+
+def _session_pending_kind(sid: str) -> str:
+ """Method of the server→client request *sid* is blocked on ("" when none)."""
+ from tui_gateway import server_requests
+ return server_requests.pending_kind(sid)
+
+
+def _session_live_status(sid: str, session: dict) -> str:
+ if _session_pending_kind(sid):
+ return "waiting"
+ ready = session.get("agent_ready")
+ # Unset + build never started = a lazy watch session idling, not one stuck mid-construction.
+ if ready is not None and not ready.is_set() and session.get("agent_build_started"):
+ return "starting"
+ return "working" if session.get("running") else "idle"
+
+
+def _session_live_title(session: dict, key: str) -> str:
+ title = str(session.get("pending_title") or "").strip()
+ with contextlib.suppress(Exception), _session_db(session) as db:
+ title = str(db.get_session_title(key) or title or "").strip() if db is not None else title
+ return title
+
+
+def _session_live_item(sid: str, session: dict, current_sid: str = "") -> dict:
+ key = _session_lookup_key(session, fallback=sid)
+ agent = session.get("agent")
+ history = list(session.get("history") or [])
+ status = _session_live_status(sid, session)
+ inflight = _inflight_snapshot(session)
+ queued = _queued_prompt_snapshot(session)
+ preview = next((" ".join(text.split())[:160] for msg in reversed(history)
+ if (text := _content_display_text(msg.get("content", msg.get("text", ""))).strip())), "")
+ if queued:
+ preview = " ".join(str(queued.get("user") or preview).split())[:160]
+ elif inflight:
+ preview = " ".join(str(inflight.get("assistant") or inflight.get("user") or preview).split())[:160]
+ now = time.time()
+ return {
+ "current": sid == current_sid, "id": sid,
+ "last_active": float(session.get("last_active") or session.get("created_at") or now),
+ "message_count": len(history),
+ "model": str(getattr(agent, "model", "") or _resolve_model()), "preview": preview,
+ "session_key": key, "started_at": float(session.get("created_at") or now), "status": status,
+ "title": _session_live_title(session, key),
+ }
+
+
+def _session_lookup_key(session: dict, *, fallback: str = "") -> str:
+ return str(getattr(session.get("agent"), "session_id", None) or session.get("session_key") or fallback or "")
+
+
+def _find_live_session_by_key(session_key: str, profile_home=_ANY_PROFILE) -> tuple[str, dict] | None:
+ # Timestamp-based stored ids can exist in several profiles' stores; a bare-id match would hand
+ # profile B's resume profile A's runtime, so profile-aware callers match on (profile_home, key).
+ # Profile-aware callers pass the home they resolved; the match must then be on (profile_home,
+ # session_key). See #100029.
+ for sid, session in list(_sessions.items()):
+ if (not session.get("_finalized") and _session_lookup_key(session, fallback=sid) == session_key
+ and _live_profile_matches(session, profile_home)):
+ return sid, session
+ return None
+
+
+def _fallback_session_info(session: dict) -> dict:
+ agent = session.get("agent")
+ if agent is not None:
+ return _session_info(agent)
+ # The SESSION's own workspace, not the launch dir (wrong project in the desktop Files pane). `branch` is
+ # always emitted ("" outside git) so a stale label clears; `desktop_contract` missing reads as "out of date".
+ # Reporting `_default_session_cwd()` here told a lazily-resumed session's client that its workspace was
+ # wherever the gateway process happened to start, so the desktop Files pane painted the wrong project
+ # even after the renderer rebound correctly (#71254). `branch` is always emitted ("" outside a git repo)
+ # so a client can clear a stale label instead of retaining it — the same contract `_lazy_session_info`
+ # above already follows.
+ cwd = _session_cwd(session)
+ return {
+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd), "lazy": True,
+ "model": _session_default_model(session), "skills": {}, "tools": {}, "desktop_contract": DESKTOP_BACKEND_CONTRACT,
+ }
+
+
+def _reconcile_display_with_live(db_display: list[dict], in_memory: list[dict]) -> list[dict]:
+ """Merge the persisted DISPLAY lineage with the in-memory live history: ``db_display`` is verbatim and
+ candidate-inclusive (verification rows the model history collapses out) but can lag by a flush;
+ ``in_memory`` is the recency authority but the collapsed *model* projection. Keep the DB display as base,
+ append only the in-memory tail past the last DB row's ``(role, text)`` anchor — the verification answer
+ survives a warm switch AND a not-yet-flushed live turn is kept."""
+ if not db_display:
+ return in_memory
+ if not in_memory:
+ return db_display
+
+ def _key(msg: dict) -> tuple:
+ return (msg.get("role"), _coerce_message_text(msg.get("content")))
+ anchor = _key(db_display[-1])
+ last_shared = max((idx for idx, msg in enumerate(in_memory) if isinstance(msg, dict) and _key(msg) == anchor), default=-1)
+ if last_shared == -1:
+ return db_display # DB tail not in memory (DB ahead, or diverged) — trust it over duplicating
+ return list(db_display) + list(in_memory[last_shared + 1 :])
+
+
+def _live_visible_history(session: dict, db, in_memory_fallback: list[dict]) -> list[dict]:
+ """User-visible DISPLAY projection for a live/warm session: the persisted display lineage (same read as
+ resume/REST so the payloads agree) reconciled with the in-memory tail; in-memory when the DB is unavailable."""
+ key = session.get("session_key")
+ if db is not None and key:
+ try:
+ # include_compacted: a compacted session's archived turns are still the user's
+ # conversation; without them a warm switch repainted the chat as summary + tail only.
+ display = db.get_messages_as_conversation(
+ key, include_ancestors=True, include_row_ids=True, include_compacted=True)
+ # See #92080.
+ return _reconcile_display_with_live(display, in_memory_fallback)
+ except Exception:
+ logger.debug("live display projection read failed", exc_info=True)
+ return in_memory_fallback
+
+
+def _live_session_payload(
+ sid: str, session: dict, *, cols: int | None = None, touch: bool = False,
+ transport: Transport | None = None, omit_messages: bool = False, inline_images: bool = True) -> dict:
+ with session["history_lock"]:
+ if cols is not None:
+ session["cols"] = cols
+ if transport is not None:
+ _rebind_live_transport(sid, session, transport)
+ if touch:
+ # #84417: do not re-fire the live turn's original user text from a stale server-queue
+ # self-duplicate after settle.
+ session["last_active"] = time.time()
+ in_memory_history = list(session.get("display_history_prefix") or []) + list(session.get("history") or [])
+ inflight, queued = _inflight_snapshot(session), _queued_prompt_snapshot(session)
+ running, turn_started_at = bool(session.get("running")), _turn_started_at(session)
+ # Persisted display lineage via the session's profile-aware DB (not the launch ``_get_db()``), read
+ # outside the history lock (the DB has its own). ``omit_messages`` skips the read (fast path).
+ if omit_messages:
+ history = in_memory_history
+ else:
+ with _session_db(session) as db:
+ history = _live_visible_history(session, db, in_memory_history)
+ # message_count follows _resume_response: the stored size when messages are omitted, else the wire count
+ # (a hidden seed row is in ``history`` but never on the wire).
+ messages = ([] if omit_messages else
+ _history_to_messages(history, profile_home=session.get("profile_home"), image_urls=inline_images))
+ payload = {
+ "info": _fallback_session_info(session), "message_count": len(history) if omit_messages else len(messages),
+ "messages": messages,
+ "messages_omitted": omit_messages, "running": running, "turn_started_at": turn_started_at,
+ "session_id": sid, "session_key": _session_lookup_key(session, fallback=sid),
+ "started_at": float(session.get("created_at") or time.time()),
+ "status": _session_live_status(sid, session),
+ }
+ for key, value in (("inflight", inflight), ("queued", queued),
+ ("pending_approval", _pending_approval_request_payload(str(session.get("session_key") or ""))),
+ ("open_requests", _open_requests(sid)),
+ ("pending_connection", _pending_connection_request_payload(sid))):
+ if value:
+ payload[key] = value
+ return _attach_todo_state(payload, session)
+
+
+def _main_runtime_from_agent(agent) -> dict | None:
+ """Aux-client main_runtime override from a live agent, so a one-shot inherits the session's runtime."""
+ if agent is None:
+ return None
+ runtime: dict = {}
+ # ``session_id`` rides along so a session-bound ``llm.oneshot`` (title, approval) on an OpenCode
+ # route sends the conversation's ``x-opencode-session`` like the main turn does (#112717).
+ for field in ("provider", "model", "base_url", "api_key", "api_mode", "auth_mode", "session_id"):
+ value = getattr(agent, field, None)
+ if isinstance(value, str) and value.strip():
+ runtime[field] = value.strip()
+ elif field == "api_key" and callable(value):
+ runtime[field] = value
+ return runtime or None
+
+
+def register(server):
+ bind_module(globals(), server)
diff --cc tui_gateway/ws.py
index 02a3f7a5539,653c1c3b6a9..c1d5490d13b
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@@ -314,6 -312,43 +319,52 @@@ async def handle_ws(ws: Any, *, auth_id
def _error(code: int, message: str, req_id: Any) -> dict:
return {"jsonrpc": "2.0", "error": {"code": code, "message": message}, "id": req_id}
+ pending: asyncio.Queue = asyncio.Queue(maxsize=_WS_DISPATCH_QUEUE_MAX)
+ dispatcher: asyncio.Task | None = None
+ stop = object() # queue sentinel; a JSON ``null`` frame parses to None, so None can't be it
+
+ async def _dispatch_loop() -> None:
+ """Dispatch queued requests one at a time in arrival order until the ``stop`` sentinel."""
+ nonlocal dispatch_crashes
+ while (req := await pending.get()) is not stop:
+ req_id = req.get("id") if isinstance(req, dict) else None
+ req_method = req.get("method") if isinstance(req, dict) else None
+ # dispatch() may schedule long handlers on the pool; it returns None then and the worker
+ # writes the response itself via transport.write (a separate thread, so that is the safe
+ # path). Inline handlers return the response dict, written here from the loop.
+ try:
- resp = await asyncio.to_thread(server.dispatch, req, transport)
++ if authority_connection is not None:
++ resp = await authority_connection.dispatch(req)
++ if _is_unknown_method(resp) and req_method in server._methods:
++ # Session verbs live on the authority; everything else the sidecar still
++ # registers (pet, wake word, active-session list, connectors) keeps its
++ # legacy handler. A real -32601 reaches the client only for methods
++ # neither side knows, which is what its version-skew notice keys on.
++ resp = await asyncio.to_thread(server.dispatch, req, transport)
++ else:
++ resp = await asyncio.to_thread(server.dispatch, req, transport)
+ except Exception:
+ dispatch_crashes += 1
+ _log.exception("ws dispatch crash peer=%s id=%s method=%s", peer, req_id, req_method)
+ await _reply(_error(-32603, "internal error", req_id), "send_failed_after_dispatch_crash",
+ "ws dispatch-crash reply send failed peer=%s id=%s method=%s", peer, req_id, req_method)
+ continue
+ if resp is not None:
+ await _reply(resp, "send_failed_after_response",
+ "ws response send failed peer=%s id=%s method=%s", peer, req_id, req_method)
+
+ async def _unless_dispatch_failed(aw: Any) -> Any:
+ """Await *aw*, or raise _SendFailed once the dispatcher has ended on a reply it could not send."""
+ assert dispatcher is not None
+ step = asyncio.ensure_future(aw)
+ try:
+ await asyncio.wait({step, dispatcher}, return_when=asyncio.FIRST_COMPLETED)
+ if step.done():
+ return step.result()
+ raise _SendFailed
+ finally:
+ step.cancel() # no-op once done
+
try:
await (ws.accept(subprotocol=subprotocol) if subprotocol else ws.accept())
disconnect_reason = "connected"
@@@ -416,8 -426,20 +447,23 @@@
except _SendFailed:
pass
finally:
+ if dispatcher is not None:
+ # Finish the in-flight handler and the frames read before the disconnect (as the serial read loop
+ # did) before the teardown below parks this transport's sessions. A cancelled connection (server
+ # shutdown) stops at once instead, as the read loop's cancelled await did.
+ task = asyncio.current_task()
+ if task is not None and task.cancelling():
+ dispatcher.cancel()
+ else:
+ with contextlib.suppress(_SendFailed):
+ await _unless_dispatch_failed(pending.put(stop))
+ await asyncio.wait({dispatcher})
+ failure = None if dispatcher.cancelled() else dispatcher.exception()
+ if failure is not None and not isinstance(failure, _SendFailed):
+ _log.error("ws dispatcher failed peer=%s", peer, exc_info=failure)
+ if authority_connection is not None:
++ # After the dispatcher drained: an in-flight authority call must not see its connection closed.
+ await authority_connection.close()
reaped_sessions = detached_sessions = 0
if transport is not None:
server.unregister_live_transport(transport)
diff --cc ui-tui/src/__tests__/createGatewayEventHandler.test.ts
index 6ddadfd1ac3,3761d459995..b39aeee70b9
--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
@@@ -2141,6 -1887,6 +2121,23 @@@ describe('createGatewayEventHandler', (
expect(clarify?.answers).toEqual({})
})
++ it('maps a canonical one-card clarify.request onto the one-question card with its shared control', () => {
++ const onEvent = createGatewayEventHandler(buildCtx([]))
++
++ onEvent({
++ payload: { choices: ['a', 'b'], execution_generation: 3, multi_select: true, prompt_id: 'p-9', question: ' Pick? ' },
++ session_id: 'sid-c',
++ type: 'clarify.request'
++ } as any)
++
++ expect(getOverlayState().clarify).toEqual({
++ answers: {},
++ questions: [{ choices: ['a', 'b'], multiSelect: true, qid: 'p-9', question: 'Pick?' }],
++ requestId: 'p-9',
++ sharedControl: { execution_generation: 3, prompt_id: 'p-9', session_id: 'sid-c' }
++ })
++ })
++
it('seeds locked answers from a reconnect-replayed batch clarify request', () => {
serverRequest(
'clarify',
diff --cc ui-tui/src/__tests__/createSlashHandler.test.ts
index 8240f1acf30,f6873b8595c..3f445714a00
--- a/ui-tui/src/__tests__/createSlashHandler.test.ts
+++ b/ui-tui/src/__tests__/createSlashHandler.test.ts
@@@ -34,18 -34,6 +34,21 @@@ describe('createSlashHandler', () =>
envState.dashboardTuiMode = false
})
+ it('does not execute a stale fallback command after switching destinations', async () => {
+ patchUiState({ sid: 'owner' })
+ const ctx = buildCtx()
+ let reject!: (error: unknown) => void
- ctx.gateway.gw.request.mockReturnValueOnce(new Promise((_, fail) => { reject = fail }))
++ const slashExec = new Promise((_, fail) => { reject = fail })
++ ctx.gateway.gw.request.mockImplementation((method: string) =>
++ method === 'slash.exec' ? slashExec : Promise.resolve({})
++ )
+ createSlashHandler(ctx)('/unknown-command')
+ patchUiState({ sid: 'other' })
+ reject(new Error('worker failed'))
+ await new Promise(resolve => setImmediate(resolve))
- expect(ctx.gateway.gw.request).toHaveBeenCalledTimes(1)
++ expect(gatewayWork(ctx)).toHaveLength(1)
+ })
+
it('opens the unified sessions overlay for /resume', () => {
const ctx = buildCtx()
@@@ -475,11 -477,11 +492,11 @@@
createSlashHandler(ctx)('/reset')
getOverlayState().confirm?.onConfirm()
- expect(ctx.session.newSession).toHaveBeenCalledWith('new session started', undefined)
- expect(ctx.gateway.gw.request).not.toHaveBeenCalled()
+ expect(ctx.session.newSession).toHaveBeenCalledWith(t('slashCmd.core.clear.newSessionStarted'), undefined)
+ expect(gatewayWork(ctx)).toEqual([])
})
- 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__/orchestratorPromptSession.test.ts
index 6e3f540d07b,677a4b77edb..5d667e69fc2
--- a/ui-tui/src/__tests__/orchestratorPromptSession.test.ts
+++ b/ui-tui/src/__tests__/orchestratorPromptSession.test.ts
@@@ -1,39 -1,9 +1,40 @@@
import { describe, expect, it } from 'vitest'
+import { patchUiState } from '../app/uiStore.js'
import { startPromptLiveSession } from '../app/useMainApp.js'
+ import { t } from '../i18n/runtime.js'
describe('startPromptLiveSession', () => {
+ it('keeps the created target through a delayed model switch without publishing into the new focus', async () => {
+ patchUiState({ sid: 'created' })
+ let finish!: (value: { model: string }) => void
+ const dispatched: unknown[] = []
+ const notices: string[] = []
+
+ const pending = startPromptLiveSession({
+ dispatchSubmission: (text, destination) => dispatched.push({ text, destination }),
+ maybeWarn: () => notices.push('warn'),
+ modelArg: 'chosen',
+ newLiveSession: async () => 'created',
+ onModelSwitched: () => notices.push('model'),
+ prompt: 'private prompt',
+ rpc: async method =>
+ method === 'session.resume'
+ ? { revision: 8, execution_generation: 4 }
+ : new Promise(resolve => {
+ finish = resolve
+ }),
+ sys: text => notices.push(text)
+ })
+
+ await new Promise(resolve => setImmediate(resolve))
+ patchUiState({ sid: 'other' })
+ finish({ model: 'chosen' })
+ await pending
+ expect(dispatched).toEqual([{ text: 'private prompt', destination: expect.objectContaining({ sid: 'created' }) }])
+ expect(notices).toEqual([])
+ })
+
it('starts a kept-live session with generated id/title, applies selected model, then dispatches the prompt', async () => {
const calls: Array<[string, unknown]> = []
@@@ -62,25 -28,17 +63,25 @@@
expect(sid).toBe('abc123')
expect(calls).toEqual([
- ['new', { message: 'new live session started', title: undefined }],
+ ['new', { message: t('session.lifecycle.newLiveSessionStarted'), title: undefined }],
+ ['rpc', { method: 'session.resume', params: { session_id: 'abc123' } }],
[
'rpc',
{
- method: 'config.set',
- params: { key: 'model', session_id: 'abc123', value: 'kimi-k2.6 --provider ollama-cloud --session' }
+ method: 'session.mutate',
+ params: {
+ session_id: 'abc123',
+ request_id: expect.any(String),
+ expected_revision: 8,
+ expected_generation: 4,
+ operation: 'model',
+ payload: { model: 'kimi-k2.6', provider: 'ollama-cloud' }
+ }
}
],
- ['sys', 'model → kimi-k2.6'],
+ ['sys', t('session.main.modelSwitched', 'kimi-k2.6')],
- ['warn', { value: 'kimi-k2.6', warning: '' }],
- ['model-switched', { result: { value: 'kimi-k2.6', warning: '' }, value: 'kimi-k2.6' }],
+ ['warn', { model: 'kimi-k2.6', value: 'kimi-k2.6', warning: '' }],
+ ['model-switched', { result: { model: 'kimi-k2.6', value: 'kimi-k2.6', warning: '' }, value: 'kimi-k2.6' }],
['dispatch', 'Build the thing']
])
})
diff --cc ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx
index dba2381dd13,00000000000..ec78b885344
mode 100644,000000..100644
--- a/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx
+++ b/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx
@@@ -1,241 -1,0 +1,241 @@@
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { createSlashHandler } from '../app/createSlashHandler.js'
+import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'
+import { useComposerState } from '../app/useComposerState.js'
+import { useSubmission } from '../app/useSubmission.js'
+
+const flush = () => new Promise<void>(resolve => setImmediate(resolve))
+
+function mount(canonical = false, extra: (method: string, params: any) => unknown = () => undefined) {
+ const home = mkdtempSync(join(tmpdir(), 'ink-slash-attachment-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ patchUiState({ sid: 'owner' })
+ const images = new Map<string, string[]>()
+ const pending: Array<{ sid: string; finish: (path: string) => void }> = []
+
+ const request = vi.fn((method: string, params: any) => {
+ const handled = extra(method, params)
+
+ if (handled !== undefined) { return Promise.resolve(handled) }
+
+ if (method === 'prompt.submit' && canonical) { return Promise.resolve({ status: 'started' }) }
+
+ if (method === 'image.attach' || method === 'clipboard.paste') {
+ return new Promise(resolve => {
+ pending.push({ sid: params.session_id, finish(path) {
+ images.set(params.session_id, [...(images.get(params.session_id) ?? []), path])
+ resolve({ attached: true, name: 'image.png', path })
+ } })
+ })
+ }
+
+ if (method === 'image.detach') {
+ images.set(params.session_id, (images.get(params.session_id) ?? []).filter(path => path !== params.path))
- } else if (!method.startsWith('complete.')) {
++ } else if (!method.startsWith('complete.') && method !== 'shared_metrics.slash_command') {
+ throw new Error(`Unexpected RPC: ${method}`)
+ }
+
+ return Promise.resolve({})
+ })
+
+ const gw = { request, isCanonical: canonical } as any
+ const submitRef = { current: (_value: string) => {} }
+ const slashRef = { current: (_value: string) => false }
+ const slashFlightRef = { current: 0 }
+ const sys = vi.fn()
+ let composer!: ReturnType<typeof useComposerState>
+ let submission!: ReturnType<typeof useSubmission>
+ const stdout = Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false })
+ let output = ''
+ stdout.on('data', chunk => { output += chunk.toString() })
+
+ function Harness() {
+ composer = useComposerState({ gw, submitRef, sys })
+ submission = useSubmission({ gw, submitRef, slashRef, sys, composerActions: composer.actions,
+ composerRefs: composer.refs, composerState: composer.state, appendMessage: vi.fn(), setLastUserMsg: vi.fn() })
+ slashRef.current = createSlashHandler({ gateway: { gw }, local: {}, transcript: { sys, send: submission.send },
+ composer: composer.actions, slashFlightRef } as any)
+
+ return <Text>{composer.state.input}</Text>
+ }
+
+ const instance = renderSync(<Harness />, { stdin: new PassThrough() as any, stdout: stdout as any,
+ stderr: new PassThrough() as any, patchConsole: false })
+
+ return {
+ home, images, pending, request,
+ get composer() { return composer },
+ get output() { return output },
+ async submit(command: string) {
+ composer.actions.setInput(command)
+ await flush()
+ submission.submit(command)
+ await flush()
+ },
+ close() {
+ instance.unmount()
+ instance.cleanup()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+ }
+}
+
+it('canonical slash images submit staged bytes and deleting tokens removes payload without RPC detach', async () => {
+ const h = mount(true)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', '')
+ const path = join(h.home, 'shot.png')
+ const bytes = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nL8AAAAASUVORK5CYII=', 'base64')
+ writeFileSync(path, bytes)
+
+ try {
+ await h.submit(`/image ${path}`)
+ await vi.waitFor(() => expect(h.composer.state.input).toContain('[[ Image 1 ]]'))
+ const token = h.composer.refs.tokensRef.current[0]!
+ expect(token).toMatchObject({ mime: 'image/png' })
+ expect(readFileSync(token.path!)).toEqual(bytes)
+ await h.submit('caption [[ Image 1 ]]')
+ await vi.waitFor(() => expect(h.request.mock.calls.some(([method]) => method === 'prompt.submit')).toBe(true))
+ const wire = h.request.mock.calls.find(([method]) => method === 'prompt.submit')![1]
+ expect(wire.attachments).toEqual([{ path: token.path, mime: 'image/png' }])
+ expect(wire.text).toBe('caption')
+ expect(h.request.mock.calls.some(([method]) => method === 'image.attach')).toBe(false)
+ await h.submit(`/image ${path}`)
+ await vi.waitFor(() => expect(h.composer.refs.tokensRef.current).toHaveLength(1))
+ h.composer.actions.syncTokens('')
+ expect(h.composer.refs.tokensRef.current).toEqual([])
+ expect(h.request.mock.calls.some(([method]) => method === 'image.detach')).toBe(false)
+ } finally { h.close() }
+})
+
+it('slash attachment submission leaves a visible removable image in the cleared composer', async () => {
+ for (const command of ['/image /owned.png', '/paste']) {
+ const h = mount()
+
+ try {
+ await h.submit(command)
+ expect(h.pending).toHaveLength(1)
+ // The composer clears only after the pending-input journal write settles (F36).
+ await vi.waitFor(() => expect(h.composer.state.input).toBe(''))
+ h.pending[0]!.finish('/owned.png')
+ await flush()
+ await vi.waitFor(() => expect(h.composer.state.input).toContain('[[ Image 1 ]]'))
+ expect(h.output).toContain('[[ Image 1 ]]')
+ expect(h.composer.refs.tokensRef.current).toEqual([
+ expect.objectContaining({ kind: 'image', path: '/owned.png' })
+ ])
+ expect(h.images.get('owner')).toEqual(['/owned.png'])
+ h.composer.actions.syncTokens('')
+ h.composer.actions.setInput('')
+ await flush()
+ expect(h.images.get('owner')).toEqual([])
+ } finally { h.close() }
+ }
+})
+
+it('stale attachment cleanup uses its captured owner and preserves a concurrent valid image', async () => {
+ for (const command of ['/image /owned.png', '/paste', 'drop']) {
+ for (const navigation of [false, true]) {
+ for (const samePath of [false, true]) {
+ for (const staleFirst of [false, true]) {
+ const h = mount()
+
+ try {
+ if (command === 'drop') {
+ void h.composer.actions.handleTextPaste({ text: '/owned.png', value: '', cursor: 0 })
+ } else {
+ await h.submit(command)
+ }
+
+ h.composer.actions.setInput('user edit')
+
+ if (navigation) {
+ patchUiState({ sid: 'other' })
+ h.composer.actions.clearIn()
+ }
+
+ await h.submit('/image /valid.png')
+ expect(h.pending).toHaveLength(2)
+ const validPath = samePath ? '/owned.png' : '/valid.png'
+ const first = staleFirst ? 0 : 1
+ h.pending[first]!.finish(first === 0 ? '/owned.png' : validPath)
+ await flush()
+ h.pending[1 - first]!.finish(first === 0 ? validPath : '/owned.png')
+ await flush()
+ const sid = getUiState().sid!
+ await vi.waitFor(() => expect(h.composer.state.input).toBe('[[ Image 1 ]]'))
+ expect(h.composer.refs.tokensRef.current).toEqual([
+ expect.objectContaining({ kind: 'image', path: validPath })
+ ])
+ expect(h.images.get(sid)).toContain(validPath)
+ const detach = h.request.mock.calls.filter(([method]) => method === 'image.detach')
+
+ if (samePath && !navigation) {
+ expect(detach).toEqual([])
+ } else {
+ expect(detach).toEqual([['image.detach', { session_id: 'owner', path: '/owned.png' }]])
+ expect(h.images.get('owner')).not.toContain('/owned.png')
+ }
+ } finally { h.close() }
+ }
+ }
+ }
+ }
+})
+
+it('a skill slash command keeps the staged image descriptors through the expanded skill send', async () => {
+ const skill = (method: string, params: any) => method === 'slash.exec'
+ ? { type: 'skill', name: 'review', message: `SKILL BODY\n\nUser request: ${params.command.replace(/^review\s*/, '')}`, display: `/${params.command}` }
+ : undefined
+ const h = mount(true, skill)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', '')
+ const path = join(h.home, 'shot.png')
+ writeFileSync(path, Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nL8AAAAASUVORK5CYII=', 'base64'))
+
+ try {
+ await h.submit(`/image ${path}`)
+ await vi.waitFor(() => expect(h.composer.state.input).toContain('[[ Image 1 ]]'))
+ const token = h.composer.refs.tokensRef.current[0]!
+ await h.submit('/review this screenshot [[ Image 1 ]]')
+ await vi.waitFor(() => expect(h.request.mock.calls.some(([method]) => method === 'prompt.submit')).toBe(true))
+ const wire = h.request.mock.calls.find(([method]) => method === 'prompt.submit')![1]
+ expect(wire.attachments).toEqual([{ path: token.path, mime: 'image/png' }])
+ expect(wire.text).toContain('SKILL BODY')
+ expect(wire.text).not.toContain('[[ Image')
+ expect(h.composer.refs.tokensRef.current).toEqual([])
+ } finally { h.close() }
+})
+
+it('keeps the caption and its image token in the composer when the pending-input journal cannot be written', async () => {
+ const h = mount(true)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', '')
+ const path = join(h.home, 'shot.png')
+ writeFileSync(path, Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nL8AAAAASUVORK5CYII=', 'base64'))
+ const journal = join(h.home, 'tui-pending-inputs')
+ mkdirSync(journal, { recursive: true })
+
+ try {
+ await h.submit(`/image ${path}`)
+ await vi.waitFor(() => expect(h.composer.state.input).toContain('[[ Image 1 ]]'))
+ chmodSync(journal, 0o500)
+ await h.submit('caption [[ Image 1 ]]')
+ expect(h.request.mock.calls.some(([method]) => method === 'prompt.submit')).toBe(false)
+ expect(h.composer.state.input).toBe('caption [[ Image 1 ]]')
+ expect(h.composer.refs.tokensRef.current).toEqual([expect.objectContaining({ kind: 'image', mime: 'image/png' })])
+ expect(getUiState().status).toBe('input not saved')
+ chmodSync(journal, 0o700)
+ await h.submit('caption [[ Image 1 ]]')
+ await vi.waitFor(() => expect(h.request.mock.calls.some(([method]) => method === 'prompt.submit')).toBe(true))
+ expect(h.request.mock.calls.find(([method]) => method === 'prompt.submit')![1].attachments).toHaveLength(1)
+ } finally { chmodSync(journal, 0o700); h.close() }
+})
diff --cc ui-tui/src/__tests__/slashSessionAuthority.test.tsx
index d4c646e929f,00000000000..d975b780c2a
mode 100644,000000..100644
--- a/ui-tui/src/__tests__/slashSessionAuthority.test.tsx
+++ b/ui-tui/src/__tests__/slashSessionAuthority.test.tsx
@@@ -1,85 -1,0 +1,86 @@@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { createSlashHandler } from '../app/createSlashHandler.js'
+import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'
+import { useSessionLifecycle } from '../app/useSessionLifecycle.js'
+
+it('branch hydration replaces source authority only after a successful destination attachment', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-slash-branch-'))
+ vi.stubEnv('HERMES_HOME', home)
+ vi.stubEnv('HERMES_TUI_ACTIVE_SESSION_FILE', join(home, 'active'))
+ resetUiState()
+
+ const source = { model: 'test', skills: {}, tools: {}, stored_session_id: 'stored-source',
+ execution_epoch: 'source-owner', execution_generation: 9, running: true }
+
+ patchUiState({ sid: 'source', info: source, busy: true })
+ const pending: Array<{ method: string; resolve: (value: any) => void }> = []
+
- const request = vi.fn((method: string) => method === 'session.close'
++ // session.close and the fire-and-forget slash metrics answer at once; the rest are held.
++ const request = vi.fn((method: string) => method === 'session.close' || method === 'shared_metrics.slash_command'
+ ? Promise.resolve({}) : new Promise(resolve => pending.push({ method, resolve })))
+
+ const setHistoryItems = vi.fn()
+ const sys = vi.fn()
+ let slash!: (command: string) => boolean
+
+ function Harness() {
+ const lifecycle = useSessionLifecycle({ colsRef: { current: 80 }, composerActions: { setComposerTokens: vi.fn() },
+ gw: { request }, rpc: request, scrollRef: { current: null }, panel: vi.fn(), sys,
+ setHistoryItems, setLastUserMsg: vi.fn(), setSessionStartedAt: vi.fn(), setStickyPrompt: vi.fn(),
+ setVoiceProcessing: vi.fn(), setVoiceRecording: vi.fn() } as any)
+
+ slash = createSlashHandler({ slashFlightRef: { current: 0 }, gateway: { gw: { request }, rpc: request },
+ local: {}, session: { ...lifecycle, setSessionStartedAt: vi.fn() }, transcript: { sys, setHistoryItems } } as any)
+
+ return <Text>branch</Text>
+ }
+
+ const instance = renderSync(<Harness />, { stdin: new PassThrough() as any,
+ stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,
+ stderr: new PassThrough() as any, patchConsole: false })
+
+ const flush = () => new Promise(resolve => setImmediate(resolve))
+
+ try {
+ slash('/branch child')
+ pending.shift()!.resolve({ session_id: 'branch', title: 'child' })
+ await flush()
+ expect(getUiState().sid).toBe('source')
+ expect(request).not.toHaveBeenCalledWith('session.close', expect.anything())
+ expect(pending[0]?.method).toBe('setup.status')
+ pending.shift()!.resolve({ provider_configured: true })
+ await flush()
+ expect(pending[0]?.method).toBe('session.resume')
+ pending.shift()!.resolve({ session_id: 'branch', stored_session_id: 'stored-branch', running: false,
+ info: { ...source, stored_session_id: 'stored-branch', execution_epoch: 'branch-owner', execution_generation: 0, running: false },
+ messages: [{ role: 'user', text: 'inherited history' }] })
+ await flush()
+ expect(getUiState()).toMatchObject({ sid: 'branch', busy: false, info: {
+ stored_session_id: 'stored-branch', execution_epoch: 'branch-owner', execution_generation: 0 } })
+ expect(setHistoryItems).toHaveBeenLastCalledWith(expect.arrayContaining([
+ expect.objectContaining({ role: 'user', text: 'inherited history' })
+ ]))
+ expect(request).toHaveBeenCalledWith('session.close', { session_id: 'source' })
+
+ // A branch response for a destination the user has left must not attach.
+ slash('/branch stale')
+ patchUiState({ sid: 'other' })
+ pending.shift()!.resolve({ session_id: 'late-branch' })
+ await flush()
+ expect(pending).toHaveLength(0)
+ expect(getUiState().sid).toBe('other')
+ } finally {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+})
diff --cc ui-tui/src/app/createGatewayEventHandler.ts
index dfd075bec84,433c944670e..4b9211f0a0e
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@@ -16,8 -16,8 +16,9 @@@ import type
GatewaySkin,
SessionMostRecentResponse
} from '../gatewayTypes.js'
+ import { t } from '../i18n/runtime.js'
import { billingDialogCopy } from '../lib/billingDialog.js'
+import { type ImageAttachment, stageImagePath } from '../lib/imageAttachments.js'
import { isTodoDone } from '../lib/liveProgress.js'
import { openExternalUrl } from '../lib/openExternalUrl.js'
import { rpcErrorMessage } from '../lib/rpc.js'
@@@ -30,13 -30,13 +31,15 @@@ import type { Msg, SessionInfo, Subagen
import { applyConnectionRequest, applyConnectionUpdate } from './connectionOperationStore.js'
import { applyDelegationStatus, getDelegationState } from './delegationStore.js'
+ import { createBillingVerificationPresenter, createFreeTierChallengePresenter } from './gatewayBrowserLinks.js'
import { applyGoalSnapshot } from './goalStatus.js'
import type { GatewayEventHandlerContext, NoticeLevel } from './interfaces.js'
- import { getOverlayState, patchOverlayState } from './overlayStore.js'
+ import { getOverlayState, patchOverlayState, SENSITIVE_PROMPTS } from './overlayStore.js'
+import { markBubbleShown, newlyStartedRows } from './pendingBubbles.js'
import { flashGoodVibes, flashPet } from './petFlashStore.js'
import { forgetServerRequest } from './serverRequestStore.js'
+ import { reportStartupLatency } from './startupLatency.js'
+import { captureDestination, isCurrentDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { getTurnState } from './turnStore.js'
import { getUiState, patchUiState } from './uiStore.js'
@@@ -655,22 -655,14 +658,22 @@@ export function createGatewayEventHandl
}
if (!sid) {
- return sys('startup query skipped: no active session')
+ return sys(t('gatewayMsg.startup.querySkipped'))
}
+ const destination = captureDestination()
+ const attachments: ImageAttachment[] = []
+
if (STARTUP_IMAGE) {
try {
- await rpc('image.attach', { path: STARTUP_IMAGE, session_id: sid })
+ if (gw.isCanonical) {
+ const image = await stageImagePath(STARTUP_IMAGE, gw, destination)
+ attachments.push({ path: image.path, mime: image.mime })
+ } else {
+ await rpc('image.attach', { path: STARTUP_IMAGE, session_id: sid })
+ }
} catch (e) {
- return sys(`startup image attach failed: ${rpcErrorMessage(e)}`)
- sys(t('gatewayMsg.startup.imageAttachFailed', rpcErrorMessage(e)))
++ return sys(t('gatewayMsg.startup.imageAttachFailed', rpcErrorMessage(e)))
}
}
@@@ -871,16 -829,16 +878,21 @@@
applySkin(ev.payload)
}
+ return
+
+ case 'free_tier.challenge':
+ showChallenge(ev.payload)
+
return
case 'session.info': {
- let info = ev.payload as SessionInfo | undefined
+ const current = getUiState().info
+ const incoming = ev.payload as SessionInfo | undefined
+
+ if (!incoming) {
+ return
+ }
- if (!info) {
+ if (incoming.profile_name && current?.profile_name && incoming.profile_name !== current.profile_name) {
return
}
@@@ -1455,67 -1349,6 +1446,87 @@@
return
}
+ // Canonical gateways (`gateway/session_pending_controls.py`) publish
+ // generation-bound shared controls as events carrying `prompt_id`; they
+ // are answered through approval.respond / clarify.respond, never through
+ // a server→client request frame (that is the legacy tui_gateway path in
+ // createServerRequestHandler).
+ case 'clarify.request': {
+ const shared = ev.payload
+
+ if (!shared?.prompt_id || !ev.session_id || typeof shared.execution_generation !== 'number') {
+ return
+ }
+
+ const sharedControl = { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id }
+
+ const batch = (shared.questions ?? [])
+ .filter(q => typeof q?.qid === 'string' && q.qid && typeof q?.question === 'string' && q.question.trim())
+ .map(q => ({
+ choices: q.choices && q.choices.length > 0 ? q.choices : null,
+ multiSelect: q.multi_select === true,
+ qid: q.qid,
+ question: q.question.trim()
+ }))
+
++ // The canonical gateway asks one card per question (question/choices/
++ // multi_select); the Ink card renders the one questions[] shape, so a
++ // single card becomes a one-question set answered via clarify.respond.
++ const single = (shared.question ?? '').trim()
++
++ const questions = batch.length
++ ? batch
++ : single
++ ? [
++ {
++ choices: shared.choices && shared.choices.length > 0 ? shared.choices : null,
++ multiSelect: shared.multi_select === true,
++ qid: shared.prompt_id,
++ question: single
++ }
++ ]
++ : []
++
++ if (!questions.length) {
++ return
++ }
++
+ patchOverlayState({
- clarify: batch.length
- ? { answers: shared.answers ?? {}, choices: null, question: '', questions: batch, requestId: shared.prompt_id, sharedControl }
- : { choices: shared.choices ?? null, question: shared.question ?? '', requestId: shared.prompt_id, sharedControl }
++ clarify: { answers: shared.answers ?? {}, questions, requestId: shared.prompt_id, sharedControl }
+ })
+ setStatus('waiting for input…')
+ ringPromptBell()
+
+ return
+ }
+
+ case 'approval.request': {
+ const shared = ev.payload
+
+ if (!shared?.prompt_id || !ev.session_id || typeof shared.execution_generation !== 'number') {
+ return
+ }
+
+ const sharedControl = { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id }
+
+ patchOverlayState({
+ approval: {
+ // Only an explicit false (tirith warning) drops the permanent-allow option.
+ allowPermanent: shared.allow_permanent !== false,
+ choices: shared.choices,
+ command: String(shared.command ?? ''),
+ description: String(shared.description ?? 'dangerous command'),
+ requestId: shared.prompt_id,
+ sharedControl,
+ smartDenied: shared.smart_denied === true
+ }
+ })
+ setStatus('approval needed')
+ ringPromptBell()
+
+ return
+ }
+
case 'background.complete':
if (!ev.payload) {
return
diff --cc ui-tui/src/app/createSlashHandler.ts
index 3f782e872b8,5b868ba38e6..ee4117e9892
--- a/ui-tui/src/app/createSlashHandler.ts
+++ b/ui-tui/src/app/createSlashHandler.ts
@@@ -13,12 -13,26 +14,26 @@@ import { captureDestination, isCurrentD
import { getUiState } from './uiStore.js'
import { describeSlashExecError, shouldFallbackToDispatch } from './userMessages.js'
+ /** Shared metrics count each user-typed command once, from the client: the gateway no longer
+ * counts slash.exec, so locally handled commands (/resume, /skin, overlays) land too.
+ * Fire-and-forget; the backend canonicalizes the raw name. */
+ export function reportSlashCommand(gw: GatewayClient, name: string, sid: null | string | undefined): void {
+ if (name) {
+ gw.request('shared_metrics.slash_command', { command: name, ...(sid ? { session_id: sid } : {}) }).catch(
+ () => undefined
+ )
+ }
+ }
+
+ /** `typed` is false for programmatic calls (a picker re-issuing `/model <x>`) and for the
+ * backend's alias re-dispatch; prefix/alias expansion keeps it, so a typed `/hea` counts once
+ * as the /heartbeat it resolved to. */
-export function createSlashHandler(ctx: SlashHandlerContext): (cmd: string, typed?: boolean) => boolean {
+export function createSlashHandler(ctx: SlashHandlerContext): SlashHandler {
const { gw } = ctx.gateway
const { catalog } = ctx.local
const { page, send, sys } = ctx.transcript
- const handler = (cmd: string, submission?: SlashSubmission): boolean => {
- const handler = (cmd: string, typed = true): boolean => {
++ const handler = (cmd: string, submission?: SlashSubmission, typed = true): boolean => {
const flight = ++ctx.slashFlightRef.current
const ui = getUiState()
const sid = ui.sid
@@@ -26,7 -39,13 +41,13 @@@
const parsed = parseSlashCommand(cmd)
const argTail = parsed.arg ? ` ${parsed.arg}` : ''
+ const countTyped = () => {
+ if (typed) {
+ reportSlashCommand(gw, parsed.name, sid)
+ }
+ }
+
- const stale = () => flight !== ctx.slashFlightRef.current || getUiState().sid !== sid
+ const stale = () => flight !== ctx.slashFlightRef.current || !isCurrentDestination(destination)
const guarded =
<T>(fn: (r: T) => void) =>
@@@ -71,7 -92,7 +94,7 @@@
if (exact) {
if (exact.toLowerCase() !== needle) {
- return handler(`${exact}${argTail}`, submission)
- return handler(`${exact}${argTail}`, typed)
++ return handler(`${exact}${argTail}`, submission, typed)
}
} else {
// Tiered name scoring (ported from grok-cli's slash menu): prefix
@@@ -89,7 -110,7 +112,7 @@@
const matches = [...new Set(scored.filter(entry => entry.score === best).map(entry => entry.canon))]
if (matches.length === 1 && matches[0]!.toLowerCase() !== needle) {
- return handler(`${matches[0]}${argTail}`, submission)
- return handler(`${matches[0]}${argTail}`, typed)
++ return handler(`${matches[0]}${argTail}`, submission, typed)
}
if (matches.length > 1) {
@@@ -112,7 -133,7 +135,7 @@@
}
if (d.type === 'alias') {
- return void handler(`/${d.target}${argTail}`, submission)
- return void handler(`/${d.target}${argTail}`, false)
++ return void handler(`/${d.target}${argTail}`, submission, false)
}
// A skill/bundle dispatch's `message` is the expanded skill body —
diff --cc ui-tui/src/app/interfaces.ts
index 1db18b80e96,84654655aac..d4f4398ae79
--- a/ui-tui/src/app/interfaces.ts
+++ b/ui-tui/src/app/interfaces.ts
@@@ -449,10 -447,10 +453,10 @@@ export interface UseComposerStateResul
}
export interface InputHandlerActions {
- answerClarify: (answer: string) => void
appendMessage: (msg: Msg) => void
+ cancelClarify: () => void
die: () => void
- dispatchSubmission: (full: string) => void
+ dispatchSubmission: (full: string | QueueItem) => void
guardBusySessionSwitch: (what?: string) => boolean
newSession: (msg?: string, title?: string) => void
sys: (text: string) => void
@@@ -531,19 -528,6 +535,21 @@@ export interface GatewayEventHandlerCon
}
}
+/**
+ * What a slash command's composer held at submit time. A skill or alias
+ * eventually sends ordinary user text, so the staged image descriptors and the
+ * token expander travel with the command instead of dying with the cleared
+ * composer.
+ */
+export interface SlashSubmission {
+ attachments: Array<{ path: string; mime: string }>
+ expand: (text: string) => string
+}
+
- export type SlashHandler = (cmd: string, submission?: SlashSubmission) => boolean
++/** `typed` is false for programmatic calls (a picker re-issuing `/model <x>`, the backend's alias
++ * re-dispatch) so shared metrics count each user-typed command once. */
++export type SlashHandler = (cmd: string, submission?: SlashSubmission, typed?: boolean) => boolean
+
export interface SlashHandlerContext {
composer: {
attachClipboardImage: () => void
diff --cc ui-tui/src/app/slash/commands/session.ts
index 5eaae3a63bf,8296d65348b..72957abc03c
--- a/ui-tui/src/app/slash/commands/session.ts
+++ b/ui-tui/src/app/slash/commands/session.ts
@@@ -18,12 -19,9 +19,10 @@@ import type { PanelSection } from '../.
import { applyConfiguredTuiTheme } from '../../createGatewayEventHandler.js'
import { DEFAULT_INDICATOR_STYLE, INDICATOR_STYLES, type IndicatorStyle } from '../../interfaces.js'
import { patchOverlayState } from '../../overlayStore.js'
-import { patchUiState } from '../../uiStore.js'
+import { getUiState, patchUiState } from '../../uiStore.js'
+import { runCanonicalSessionControl } from '../canonicalSessionControls.js'
import type { SlashCommand } from '../types.js'
- const USAGE_CTA = 'Run /subscription to change plan · /topup to add to your balance'
-
const TUI_SESSION_MODEL_RE = new RegExp(`(?:^|\\s)${TUI_SESSION_MODEL_FLAG}(?:\\s|$)`)
const REASONING_SESSION_FLAGS = new Set(['--session'])
const REASONING_GLOBAL_FLAGS = new Set(['--global'])
@@@ -341,10 -322,10 +360,10 @@@ export const sessionCommands: SlashComm
return
}
- void ctx.session.closeSession(prevSid)
- patchUiState({ sid: r.session_id })
- ctx.session.setSessionStartedAt(Date.now())
+ // Resume hydrates destination authority/history before closing the
+ // source; changing only sid would inherit the source owner's epoch.
+ ctx.session.resumeById(r.session_id)
- ctx.transcript.sys(`branched → ${r.title ?? ''}`)
+ ctx.transcript.sys(t('slashCmd.session.branch.branched', r.title ?? ''))
})
)
}
@@@ -691,12 -682,7 +727,12 @@@
.then(
ctx.guarded<ConfigSetResponse>(r => {
const next = r.value || mode
+
+ if (next === 'queue' || next === 'steer' || next === 'interrupt') {
+ patchUiState({ busyInputMode: next })
+ }
+
- ctx.transcript.sys(`busy input mode: ${next}`)
+ ctx.transcript.sys(t('slashCmd.session.busy.mode', next))
})
)
.catch(ctx.guardedErr)
diff --cc ui-tui/src/app/turnController.ts
index 29791128b9a,ca902e5f210..60a7d05f457
--- a/ui-tui/src/app/turnController.ts
+++ b/ui-tui/src/app/turnController.ts
@@@ -8,9 -8,9 +8,10 @@@ import
STREAM_TYPING_BATCH_MS
} from '../config/timing.js'
import type { SessionInterruptResponse } from '../gatewayTypes.js'
+ import { t } from '../i18n/runtime.js'
import { appendToolShelfMessage, isToolShelfMessage } from '../lib/liveProgress.js'
import { hasReasoningTag, splitReasoning } from '../lib/reasoning.js'
+import { rpcErrorMessage } from '../lib/rpc.js'
import {
boundedLiveRenderText,
estimateTokensRough,
diff --cc ui-tui/src/app/useConfigSync.ts
index e0f7fc32786,7b6c422fe6e..efa758d4913
--- a/ui-tui/src/app/useConfigSync.ts
+++ b/ui-tui/src/app/useConfigSync.ts
@@@ -254,26 -256,17 +256,32 @@@ export async function hydrateFullConfig
gw: GatewayClient,
setBell: (v: boolean) => void,
setVoiceRecordKey?: (v: ParsedVoiceRecordKey) => void,
- setBellOnPrompt?: (v: boolean) => void
+ setBellOnPrompt?: (v: boolean) => void,
+ scope?: { sid: string; isCurrent: () => boolean }
): Promise<ConfigFullResponse | null> {
- const cfg = await quietRpc<ConfigFullResponse>(gw, 'config.get', { key: 'full' })
- applyDisplay(cfg, setBell, setVoiceRecordKey, setBellOnPrompt)
+ const params = scope ? { session_id: scope.sid } : {}
+
+ const [cfg, busy] = await Promise.all([
+ quietRpc<ConfigFullResponse>(gw, 'config.get', { key: 'full', ...params }),
+ gw.isCanonical && scope ? quietRpc(gw, 'config.get', { key: 'busy', ...params }) : null
+ ])
+
+ if (scope && !scope.isCurrent()) {
+ return null
+ }
+
+ applyDisplay(cfg, setBell, setVoiceRecordKey, setBellOnPrompt, !gw.isCanonical)
+
+ if (gw.isCanonical && BUSY_MODES.has(busy?.value)) {
+ patchUiState({ busyInputMode: busy!.value })
+ }
+ // Same fail-safe as the voice key: a null config (transient RPC failure)
+ // keeps the last language rather than snapping back to English.
+ if (cfg) {
+ void syncTuiLocale(gw, cfg.config?.display?.language)
+ }
+
return cfg
}
diff --cc ui-tui/src/app/useInputHandlers.ts
index c096f23d2aa,4a783cc11a8..766620caf38
--- a/ui-tui/src/app/useInputHandlers.ts
+++ b/ui-tui/src/app/useInputHandlers.ts
@@@ -6,7 -5,8 +6,8 @@@ import { sharedControlParams } from '..
import { DASHBOARD_TUI_MODE } from '../config/env.js'
import { DOUBLE_ESC_MS, TYPING_IDLE_MS } from '../config/timing.js'
import { applyCompletion } from '../domain/slash.js'
-import type { ConfigSetResponse, VoiceRecordResponse } from '../gatewayTypes.js'
+import type { ConfigSetResponse, SharedControlRespondResponse, VoiceRecordResponse } from '../gatewayTypes.js'
+ import { t } from '../i18n/runtime.js'
import { isAction, isCopyShortcut, isMac, isMacActionFallback, isVoiceToggleKey } from '../lib/platform.js'
import { computePrecisionWheelStep, initPrecisionWheel } from '../lib/precisionWheel.js'
import { computeWheelStep, initWheelAccelForHost } from '../lib/wheelAccel.js'
@@@ -21,7 -21,7 +22,14 @@@ import
type InputHandlerResult,
type OverlayState
} from './interfaces.js'
- import { $isBlocked, $overlayState, capturePromptResponseGuard, patchOverlayState } from './overlayStore.js'
-import { $isBlocked, $overlayState, hasSensitivePrompt, patchOverlayState, SENSITIVE_PROMPTS } from './overlayStore.js'
++import {
++ $isBlocked,
++ $overlayState,
++ capturePromptResponseGuard,
++ hasSensitivePrompt,
++ patchOverlayState,
++ SENSITIVE_PROMPTS
++} from './overlayStore.js'
import { respondToServerRequest } from './serverRequestStore.js'
import { turnController } from './turnController.js'
import { patchTurnState } from './turnStore.js'
@@@ -256,27 -250,9 +258,27 @@@ export function useInputHandlers(ctx: I
}
if (overlay.approval) {
+ const fresh = capturePromptResponseGuard('approval', overlay.approval)
+
+ if (!fresh()) {
+ return
+ }
+
+ const settle = () => {
+ patchOverlayState({ approval: null })
- patchTurnState({ outcome: 'denied' })
++ patchTurnState({ outcome: t('session.approval.denied') })
+ }
+
+ // Canonical shared controls deny through the generation-bound RPC; a
+ // legacy server→client request resolves its response frame locally.
+ if (overlay.approval.sharedControl) {
+ return gateway
+ .rpc<SharedControlRespondResponse>('approval.respond', { choice: 'deny', ...sharedControlParams(overlay.approval) })
+ .then(r => r && fresh() && settle())
+ }
+
respondToServerRequest(overlay.approval.requestId, { choice: 'deny' })
- patchOverlayState({ approval: null })
- patchTurnState({ outcome: t('session.approval.denied') })
+ settle()
return
}
diff --cc ui-tui/src/app/useMainApp.ts
index bf2e3321db5,7fffb4c8912..d8c73f4e381
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@@ -57,8 -58,8 +59,8 @@@ import { createSlashHandler } from './c
import { planGatewayRecovery } from './gatewayRecovery.js'
import { applyGoalSnapshot } from './goalStatus.js'
import { getInputSelection } from './inputSelectionStore.js'
-import { type GatewayRpc, type StateSetter, type TranscriptRow } from './interfaces.js'
-import { $overlayState, hasSensitivePrompt, patchOverlayState } from './overlayStore.js'
+import { type GatewayRpc, type SlashHandler, type StateSetter, type TranscriptRow } from './interfaces.js'
- import { $overlayState, capturePromptResponseGuard, patchOverlayState } from './overlayStore.js'
++import { $overlayState, capturePromptResponseGuard, hasSensitivePrompt, patchOverlayState } from './overlayStore.js'
import { $goodVibesTick } from './petFlashStore.js'
import { applyProcessSnapshot, type ProcessEntry } from './processRoster.js'
import { scrollWithSelectionBy } from './scroll.js'
@@@ -144,27 -146,23 +149,27 @@@ export async function startPromptLiveSe
return null
}
- const requestedModel = modelArg ? sessionScopedModelArg(modelArg) : ''
+ const destination = Object.freeze({ ...captureDestination(), sid })
+ const requestedModel = modelArg?.trim() ?? ''
if (requestedModel) {
- const result = await rpc<ConfigSetResponse>('config.set', { key: 'model', session_id: sid, value: requestedModel })
+ const mutation = await mutateCanonicalSession({ request: rpc }, sid, 'model', requestedModel)
+ const result = mutation ? { ...mutation.result, value: mutation.result.model } : null
if (!result?.value) {
- sys('error: invalid response: model switch')
+ sys(`error: ${t('session.main.invalidModelSwitchResponse')}`)
return sid
}
- sys(t('session.main.modelSwitched', result.value))
- maybeWarn(result)
- onModelSwitched?.(result.value, result)
+ if (isCurrentDestination(destination)) {
- sys(`model → ${result.value}`)
++ sys(t('session.main.modelSwitched', result.value))
+ maybeWarn(result)
+ onModelSwitched?.(result.value, result)
+ }
}
- dispatchSubmission(trimmed)
+ dispatchSubmission(trimmed, destination)
return sid
}
@@@ -749,70 -738,36 +750,58 @@@ export function useMainApp(gw: GatewayC
clearTimeout(timer)
stdout.off('resize', onResize)
}
- }, [rpc, stdout, ui.sid])
+ }, [gw, rpc, stdout, ui.sid])
- const answerClarify = useCallback(
- (answer: string) => {
- const clarify = overlay.clarify
+ const cancelClarify = useCallback(() => {
+ const clarify = overlay.clarify
- if (!clarify) {
- return
- }
+ if (!clarify) {
+ return
+ }
- const fresh = capturePromptResponseGuard('clarify', clarify)
++ const fresh = capturePromptResponseGuard('clarify', clarify)
+
- if (!fresh()) {
- return
- }
++ if (!fresh()) {
++ return
++ }
+
- const label = toolTrailLabel('clarify')
+ const label = toolTrailLabel('clarify')
- turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
- patchTurnState({ turnTrail: turnController.turnTools })
+ turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
+ patchTurnState({ turnTrail: turnController.turnTools })
- // Canonical shared controls answer through the generation-bound RPC; a
- // legacy server→client request resolves its response frame locally.
- const answered = clarify.sharedControl
- ? rpc<SharedControlRespondResponse>('clarify.respond', { answer, ...sharedControlParams(clarify) }).then(r => Boolean(r) && fresh())
- : Promise.resolve(respondToServerRequest(clarify.requestId, { answer }))
-
- void answered.then(ok => {
- if (!ok) {
- // The request already expired (request.cancel raced the keystroke): nothing to answer.
- if (!clarify.sharedControl) {
- patchOverlayState({ clarify: null })
- }
++ // Esc / Ctrl+C cancel: persist the question as a system line (not a
++ // transient "prompt cancelled" flash) so the prompt survives on screen as
++ // standard output, matching the timeout path.
++ const settleCancelled = () => {
++ appendMessage({
++ role: 'system',
++ text: formatAbandonedClarify(clarify.questions, clarify.answers ?? {}, 'cancelled')
++ })
++ patchOverlayState({ clarify: null })
++ }
+
- return
- }
++ // Canonical shared controls answer through the generation-bound RPC, which
++ // carries one string answer per card: an empty answer releases the card
++ // (the gateway reads it as a skip). A legacy server→client request
++ // resolves its response frame locally; an empty response is cancel-all.
++ if (clarify.sharedControl) {
++ void rpc<SharedControlRespondResponse>('clarify.respond', { answer: '', ...sharedControlParams(clarify) }).then(
++ r => r && fresh() && settleCancelled()
++ )
+
- if (answer) {
- turnController.persistedToolLabels.add(label)
- appendMessage({
- kind: 'trail',
- role: 'system',
- text: '',
- tools: [buildToolTrailLine('clarify', clarify.question)]
- })
- appendMessage({ role: 'user', text: answer })
- patchUiState({ status: 'running…' })
- } else {
- // Esc / Ctrl+C cancel: persist the question + options as a system
- // line (not a transient "prompt cancelled" flash) so the prompt
- // survives on screen as standard output, matching the timeout path.
- appendMessage({
- role: 'system',
- text: clarify.questions?.length
- ? formatAbandonedClarifyBatch(clarify.questions, clarify.answers ?? {}, 'cancelled')
- : formatAbandonedClarify(clarify.question, clarify.choices, 'cancelled')
- })
- }
++ return
++ }
+
- patchOverlayState({ clarify: null })
- })
- },
- [appendMessage, overlay.clarify, rpc]
- )
+ if (!respondToServerRequest(clarify.requestId, {})) {
+ // The request already expired (request.cancel raced the keystroke): nothing to answer.
+ patchOverlayState({ clarify: null })
+
+ return
+ }
+
- // Esc / Ctrl+C cancel: persist the question as a system line (not a
- // transient "prompt cancelled" flash) so the prompt survives on screen as
- // standard output, matching the timeout path.
- appendMessage({
- role: 'system',
- text: formatAbandonedClarify(clarify.questions, clarify.answers ?? {}, 'cancelled')
- })
- patchOverlayState({ clarify: null })
- }, [appendMessage, overlay.clarify])
++ settleCancelled()
++ }, [appendMessage, overlay.clarify, rpc])
// Lock one answer of a batch clarify (`clarify.lock` RPC). The overlay stays
// up until the server reports no remaining questions — the final lock
@@@ -820,19 -775,13 +809,47 @@@
const answerClarifyQuestion = useCallback(
(qid: string, answer: string) => {
const clarify = overlay.clarify
++ const question = clarify?.questions.find(q => q.qid === qid)
+
- if (!clarify?.questions?.length) {
++ if (!clarify || !question) {
+ return
+ }
+
+ const fresh = capturePromptResponseGuard('clarify', clarify)
+
+ if (!fresh()) {
+ return
+ }
+
++ // Canonical shared controls publish one card per question and answer it
++ // through the generation-bound RPC (there is no clarify.lock on that
++ // path); an empty answer is the skip. A multi-question shared set keeps
++ // the per-question lock below.
++ if (clarify.sharedControl && clarify.questions.length === 1) {
++ void rpc<SharedControlRespondResponse>('clarify.respond', { answer, ...sharedControlParams(clarify) }).then(r => {
++ if (!r || !fresh()) {
++ return
++ }
++
++ const label = toolTrailLabel('clarify')
++
++ turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
++ patchTurnState({ turnTrail: turnController.turnTools })
++ turnController.persistedToolLabels.add(label)
++ appendMessage({ kind: 'trail', role: 'system', text: '', tools: [buildToolTrailLine('clarify', question.question)] })
++ appendMessage({
++ role: 'user',
++ text: answer.trim() ? clarifyAnswerText(answer, question.multiSelect) : t('session.main.skipped')
++ })
++ patchUiState({ status: 'running…' })
++ patchOverlayState({ clarify: null })
++ })
+
- if (!clarify) {
+ return
+ }
+
rpc<ClarifyLockResponse>('clarify.lock', {
- answer,
+ answer: answer.trim() ? answer : null,
question_id: qid,
request_id: clarify.requestId
}).then(r => {
@@@ -1026,41 -975,43 +1045,41 @@@
const exitHandler = (code: null | number) => {
turnController.reset()
const state = getUiState()
- const storedSid = state.storedSid
+ // session.resume takes the durable stored id, not the process-local
+ // runtime sid (they coincide on canonical gateways).
+ const storedSid = state.storedSid ?? state.sid
- // Attached socket closed: the backend (and any live turn) is still there —
+ // Socket closed: the backend (and any live turn) is still there —
// GatewayClient owns the backoff reconnect, and the next gateway.ready
// resumes the durable session id. Calling start() here would race that
- // reconnect and reset its backoff.
+ // reconnect and reset its backoff. Keep sid: durable offline input stays
+ // fenced to its destination and drains once `gatewayConnected` returns.
if (gw.attached) {
recoverSidRef.current = storedSid ?? recoverSidRef.current
- patchUiState({ busy: false, compacting: false, gatewayConnected: false, status: 'reconnecting…' })
- patchUiState({ busy: false, compacting: false, sid: null, status: t('session.status.reconnecting') })
++ patchUiState({ busy: false, compacting: false, gatewayConnected: false, status: t('session.status.reconnecting') })
if (state.sid) {
- turnController.pushActivity(CONNECTION_LOST_ACTIVITY, 'warn')
- sys(CONNECTION_LOST)
+ turnController.pushActivity(connectionLostActivity(), 'warn')
+ sys(connectionLost())
}
return
}
- // A still-owned child dying while the TUI is alive is an *unexpected*
- // death — respawn the gateway and resume the persisted session via the
- // next gateway.ready. session.resume takes the durable stored id, not the
- // process-local runtime sid. planGatewayRecovery bounds the attempts so a
- // crash-looping gateway can't spawn-storm.
+ // No socket was ever granted (bootstrap failed): GatewayClient retries
+ // discovery on its backoff without starting a stopped owner; discovery
+ // retries must never silently create a replacement for an ended session.
+ // planGatewayRecovery bounds the resume attempts so a crash-looping
+ // gateway can't storm.
const plan = planGatewayRecovery(storedSid, recoverSidRef.current, recoveryAtRef.current, Date.now())
- // Clear sid immediately: while the gateway is down, sid-guarded effects
- // (session.active_list poll, queue drain) would otherwise fire RPCs at a
- // dead/respawning gateway. recoverSidRef carries the session forward, and
- // resumeById restores sid once the fresh gateway is ready.
recoveryAtRef.current = plan.attempts
- patchUiState({ busy: false, compacting: false, gatewayConnected: false, status: 'gateway exited' })
- patchUiState({ busy: false, compacting: false, sid: null, status: t('session.status.restarting') })
++ patchUiState({ busy: false, compacting: false, gatewayConnected: false, status: t('libText.gateway.exited') })
if (plan.recover && plan.sid) {
recoverSidRef.current = plan.sid
- turnController.pushActivity(BACKEND_RESTARTING_ACTIVITY, 'warn')
- sys(BACKEND_RESTARTING)
+ turnController.pushActivity(backendRestartingActivity(), 'warn')
+ sys(backendRestarting())
- gw.start()
return
}
@@@ -1167,25 -1116,15 +1186,27 @@@
return
}
- respondWith(overlay.approval.requestId, { choice }, () => {
+ const settle = () => {
+ if (!fresh()) {
+ return
+ }
+
patchOverlayState({ approval: null })
- patchTurnState({ outcome: choice === 'deny' ? 'denied' : `approved (${choice})` })
+ patchTurnState({
+ outcome: choice === 'deny' ? t('session.approval.denied') : t('session.approval.approved', choice)
+ })
patchUiState({ status: 'running…' })
- })
+ }
+
+ // Canonical shared controls answer through the generation-bound RPC; a
+ // legacy server→client request resolves its response frame locally.
+ if (overlay.approval.sharedControl) {
+ return rpc<SharedControlRespondResponse>('approval.respond', { choice, ...sharedControlParams(overlay.approval) }).then(r => r && settle())
+ }
+
+ respondWith(overlay.approval.requestId, { choice }, settle)
},
- [overlay.approval, respondWith]
+ [overlay.approval, respondWith, rpc]
)
const answerSudo = useCallback(
@@@ -1268,9 -1187,57 +1289,57 @@@
[overlay.vaultUnlock, respondWith]
)
+ const answerVaultSaveLogin = useCallback(
+ (identifier: string, password: string) => {
+ if (!overlay.vaultSaveLogin) {
+ return
+ }
+
+ const requestId = overlay.vaultSaveLogin.requestId
+
+ // Either step left empty declines (CLI parity): an empty value resolves the
+ // tool's wait now instead of at its 180s deadline. The pair goes only to
+ // the encrypted vault, never to the transcript or the model.
+ if (!identifier || !password) {
+ patchOverlayState({ vaultSaveLogin: null })
+ }
+
+ return respondWith(
+ requestId,
+ { value: identifier && password ? JSON.stringify({ identifier, password }) : '' },
+ () => {
+ patchOverlayState({ vaultSaveLogin: null })
+ patchUiState({ status: 'running…' })
+ }
+ )
+ },
+ [overlay.vaultSaveLogin, respondWith]
+ )
+
+ const answerVaultCode = useCallback(
+ (code: string) => {
+ if (!overlay.vaultCode) {
+ return
+ }
+
+ const requestId = overlay.vaultCode.requestId
+ const value = code.trim()
+
+ if (!value) {
+ patchOverlayState({ vaultCode: null })
+ }
+
+ respondWith(requestId, { value }, () => {
+ patchOverlayState({ vaultCode: null })
+ patchUiState({ status: 'running…' })
+ })
+ },
+ [overlay.vaultCode, respondWith]
+ )
+
const onModelSelect = useCallback((value: string) => {
patchOverlayState({ modelPicker: false })
- slashRef.current(`/model ${value}`)
- slashRef.current(`/model ${value}`, false) // the typed /model that opened the picker already counted
++ slashRef.current(`/model ${value}`, undefined, false) // the typed /model that opened the picker already counted
}, [])
const closeLiveSession = useCallback(
diff --cc ui-tui/src/app/useSessionLifecycle.ts
index 0a8ae0ab964,96531403f4f..37faa887985
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@@ -6,9 -5,8 +6,9 @@@ 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 { buildSetupRequiredSections, setupRequiredTitle } from '../content/setup.js'
import { introMsg, toTranscriptMessages } from '../domain/messages.js'
import { ZERO } from '../domain/usage.js'
import { type GatewayClient } from '../gatewayClient.js'
@@@ -20,7 -17,7 +20,8 @@@ import type
SessionTitleResponse,
SetupStatusResponse
} from '../gatewayTypes.js'
+ import { t } from '../i18n/runtime.js'
+import { migratePendingInputs } from '../lib/pendingInputs.js'
import { asRpcResult } from '../lib/rpc.js'
import type { Msg, PanelSection, SessionInfo } from '../types.js'
@@@ -279,118 -197,96 +280,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(setupRequiredTitle(), buildSetupRequiredSections())
- patchUiState({ status: t('session.status.setupRequired') })
+ 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' })
++ panel(setupRequiredTitle(), buildSetupRequiredSections())
++ patchUiState({ status: t('session.status.setupRequired') })
- 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' : t('session.status.startingAgent'),
- storedSid,
- usage: usageFrom(info)
- })
+ const r = await rpc<SessionCreateResponse>('session.create', gw.isCanonical
+ ? { 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…',
++ status: gw.isCanonical || info?.version ? 'ready' : t('session.status.startingAgent'),
+ storedSid,
+ usage: usageFrom(info)
})
- .then(result => {
- if (!result || getUiState().sid !== r.session_id) {
- return
- }
- const nextTitle = (result.title ?? requestedTitle).trim()
- const suffix = result.pending ? t('session.lifecycle.titleQueuedSuffix') : ''
- patchUiState({ sessionTitle: nextTitle })
- sys(`${t('session.lifecycle.sessionTitleSet', 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: ${t('session.lifecycle.failedToSetTitle', 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)' : ''
++ const suffix = result.pending ? t('session.lifecycle.titleQueuedSuffix') : ''
+ patchUiState({ sessionTitle: nextTitle })
- sys(`session title set: ${nextTitle}${suffix}`)
++ sys(`${t('session.lifecycle.sessionTitleSet', 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}`)
++ sys(`warning: ${t('session.lifecycle.failedToSetTitle', 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(
@@@ -409,12 -305,8 +410,12 @@@
const activateLiveSession = useCallback(
(id: string) => {
+ const flight = ++attachmentFlight.current
+ pendingAttachments.current.add(flight)
+ const previousSid = getUiState().sid
+ const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
patchOverlayState({ sessions: false })
- patchUiState({ status: 'switching session…' })
+ patchUiState({ status: t('session.status.switchingSession') })
// The card belongs to the session being left; the activated one answers with its own.
clearConnectionOperation()
@@@ -429,14 -314,8 +430,14 @@@
.then(raw => {
const r = asRpcResult<SessionActivateResponse>(raw)
+ if (flight !== attachmentFlight.current) {
+ discardStaleAttachment(r)
+
+ return
+ }
+
if (!r) {
- sys('error: invalid response: session.activate')
+ sys(`error: ${t('session.common.invalidResponse', 'session.activate')}`)
return patchUiState({ status: 'ready' })
}
@@@ -486,24 -358,13 +487,24 @@@
const resumeById = useCallback(
(id: string) => {
+ const flight = ++attachmentFlight.current
+ pendingAttachments.current.add(flight)
+ const current = captureDestination()
+ const previousSid = current.sid
+ const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
+
+ const destination = current.sid === id || current.storedSid === id
+ ? current : { ...current, sid: id, storedSid: id }
+
patchOverlayState({ sessions: false })
- patchUiState({ status: 'resuming…' })
+ patchUiState({ status: t('session.status.resuming') })
- return rpc<SetupStatusResponse>('setup.status', {}).then(setup => {
+ return (gw.isCanonical ? Promise.resolve(null) : rpc<SetupStatusResponse>('setup.status', {})).then(setup => {
+ if (flight !== attachmentFlight.current) {return}
+
if (setup?.provider_configured === false) {
- panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())
- patchUiState({ status: 'setup required' })
+ panel(setupRequiredTitle(), buildSetupRequiredSections())
+ patchUiState({ status: t('session.status.setupRequired') })
return
}
@@@ -519,14 -376,8 +520,14 @@@
.then(raw => {
const r = asRpcResult<SessionResumeResult>(raw)
+ if (flight !== attachmentFlight.current) {
+ discardStaleAttachment(r)
+
+ return
+ }
+
if (!r) {
- sys('error: invalid response: session.resume')
+ sys(`error: ${t('session.common.invalidResponse', 'session.resume')}`)
return patchUiState({ status: 'ready' })
}
diff --cc ui-tui/src/app/useSubmission.ts
index 6f84f3ae36d,76fe467e4a8..ec7bab9f16f
--- a/ui-tui/src/app/useSubmission.ts
+++ b/ui-tui/src/app/useSubmission.ts
@@@ -12,9 -11,9 +12,10 @@@ import { asRpcResult } from '../lib/rpc
import { hasInterpolation, INTERPOLATION_RE } from '../protocol/interpolation.js'
import type { Msg } from '../types.js'
+ import { reportSlashCommand } from './createSlashHandler.js'
-import type { ComposerActions, ComposerRefs, ComposerState, ComposerToken } from './interfaces.js'
+import type { BusyInputMode, ComposerActions, ComposerRefs, ComposerState, ComposerToken, SlashHandler } from './interfaces.js'
import { submitPrompt } from './submissionCore.js'
+import { captureDestination, isCurrentDestination, type SubmissionDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { getUiState, patchUiState } from './uiStore.js'
@@@ -341,20 -277,17 +342,22 @@@ export function useSubmission(opts: Use
const queued =
parsed.name === 'queue' || parsed.name === 'q' ? queueItemFromSlash(slash.display, slash.command) : undefined
+ // Attachment commands capture the cleared composer's revision.
+ composerActions.clearIn()
+
if (queued) {
+ // Handled here, before the slash handler, so it is counted here.
+ reportSlashCommand(gw, parsed.name, getUiState().sid)
- composerActions.enqueue(queued.text, queued.display)
+ const retained = composerActions.enqueue(queued.text, queued.display, destination)
+
+ if (retained) { retained.attachments = submission.attachments; savePendingInput(retained) }
sys(`queued: "${queued.display.slice(0, 50)}${queued.display.length > 50 ? '…' : ''}"`)
} else {
- slashRef.current(slash.command)
+ // Image tokens are labels in the command; the descriptors and their
+ // expander ride along so a skill/alias send still carries the image.
+ slashRef.current(slash.command, { attachments: submission.attachments, expand: expandTokens(submissionTokens) })
}
- composerActions.clearIn()
-
return
}
diff --cc ui-tui/src/domain/attachments.ts
index 1a80067066c,c7c98f9d199..cca21f75dca
--- a/ui-tui/src/domain/attachments.ts
+++ b/ui-tui/src/domain/attachments.ts
@@@ -1,5 -1,5 +1,6 @@@
import type { ComposerToken } from '../app/interfaces.js'
+ import { t } from '../i18n/runtime.js'
+import type { ImageAttachment } from '../lib/imageAttachments.js'
import { PASTE_SNIPPET_RE } from '../protocol/paste.js'
/**
@@@ -14,12 -14,8 +15,12 @@@
* - Position in the text is meaningful: the model sees the payload where the
* token sat, not stapled to the front of the turn.
*/
- export const imageToken = (index: number) => `[[ Image ${index} ]]`
+ export const imageToken = (index: number) => t('libText.attachments.imageToken', index)
+export const imageAttachments = (value: string, tokens: ComposerToken[]): ImageAttachment[] =>
+ tokens.flatMap(token => token.kind === 'image' && token.mime && value.includes(token.label)
+ ? [{ path: token.path, mime: token.mime }] : [])
+
/** Highest image token index handed out so far, so a new one never collides. */
export const nextImageIndex = (tokens: ComposerToken[]) =>
tokens.reduce((max, t) => (t.kind === 'image' ? Math.max(max, t.index) : max), 0) + 1
diff --cc ui-tui/src/gatewayClient.ts
index 3c7912cdfd8,5f272900aa5..166026d3c75
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@@ -14,8 -14,8 +14,9 @@@ import
import { reconnectBackoffDelayMs } from '@hermes/shared/reconnect-backoff'
import { WebSocket as UndiciWebSocket } from 'undici'
+import { canonicalEvent, canonicalRequest, canonicalResult, type CreationContract } from './canonicalGateway.js'
import type { AnyGatewayEvent } from './gatewayTypes.js'
+ import { t } from './i18n/runtime.js'
import { CircularBuffer } from './lib/circularBuffer.js'
import { recordParentLifecycle } from './lib/parentLog.js'
@@@ -326,9 -294,9 +327,9 @@@ export class GatewayClient extends Even
// Reject any in-flight RPCs left over from the previous transport
// before we swap. Otherwise the old transport's stale exit/close
// handlers (now identity-gated to ignore unrelated transports)
- // never fire `rejectPending`, leaving callers hanging on promises
+ // never settle the channel's pending RPCs, leaving callers hanging on promises
// attached to a discarded child / socket.
- this.channel.detach(new Error('gateway restarting'))
+ this.channel.detach(new Error(t('libText.gateway.restarting')))
this.ready = false
// `subscribed` is NOT reset here: the renderer drain()s once on mount, so a
// reset would strand every post-reconnect event (gateway.ready included) in
diff --cc ui-tui/src/types.ts
index f8d93d4af78,912d5231988..da557dd516c
--- a/ui-tui/src/types.ts
+++ b/ui-tui/src/types.ts
@@@ -126,12 -123,8 +126,9 @@@ export interface ClarifyQuestion
}
export interface ClarifyReq {
+ sharedControl?: SharedControl
- choices: string[] | null
- question: string
requestId: string
- /** Batch (multi-question) clarify: present instead of question/choices. */
- questions?: ClarifyBatchQuestion[]
+ questions: ClarifyQuestion[]
/** Answers already locked server-side (qid → answer): seeded from the
* reconnect replay, updated as the user locks each question. */
answers?: Record<string, string>
diff --cc web/src/lib/api.ts
index 398a5d011c9,e8dfe43ced9..685bc49af2d
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@@ -3,10 -3,13 +3,16 @@@ import
type ModelOptionProvider,
type ModelOptionsResult,
} from "@hermes/shared";
+import { createDashboardSessionMutations } from "./session-mutations";
+
+const mutateSessionHttp = createDashboardSessionMutations(fetchJSON);
+ import type { AuxiliaryModelsResponse } from "./api-aux";
+ import type {
+ ManagedFileReadResponse,
+ ManagedFilesResponse,
+ ManagedFileWriteResponse,
+ } from "./api-files";
import { dashboardServingProfile } from "./profile-bootstrap";
// The dashboard can be served either at the root of its host (e.g.
diff --cc website/docs/developer-guide/session-storage.md
index 248eb3651e5,ff6206f97ed..f91a5883f7d
--- a/website/docs/developer-guide/session-storage.md
+++ b/website/docs/developer-guide/session-storage.md
@@@ -262,28 -268,9 +268,28 @@@ background FTS rebuild can proceed with
indexed columns — see `SCHEMA_SQL` in `hermes_state_common.py` for the exact SQL.
+## Dashboard browsing and owner maintenance
+
+Session browsing opens `state.db` read-only. GET listing, search, details,
+messages, statistics and export never create an absent database, quarantine a
+zero-byte file, reconcile a stale schema, or trigger auto-archive. Uninitialized
+or incompatible stores return HTTP 503 with owner-start/recovery guidance;
+profile aggregation reports schema failures in its per-profile `errors` list.
+
+The profile's gateway initializes and reconciles its store at startup. The
+standalone `serve` backend retains its existing startup reconciliation worker.
+Configured `sessions.auto_archive` remains active through gateway startup and
+housekeeping, or the standalone backend's maintenance ticker, independently of
+browsing. Explicit mutation endpoints retain their existing write behavior.
+
+SQLite WAL readers still participate in shared-memory coordination: `mode=ro`
+may create empty WAL/SHM sidecars or update SHM read marks. The read-only contract
+forbids canonical schema/data writes, repair and checkpointing; it does not make
+live SQLite coordination files immutable.
+
## Schema Version and Migrations
- Current schema version: **23**
+ Current schema version: **31**
The `schema_version` table stores a single integer. Simple column additions are handled declaratively by `_reconcile_columns()` (which diffs live columns against `SCHEMA_SQL` and ADDs any missing ones). The version-gated chain is reserved for data migrations and index/FTS changes that can't be expressed declaratively:
diff --cc website/docs/reference/cli-commands.md
index 43089a31e1f,c9a07b4b697..1d8fa6ea75e
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@@ -210,20 -208,16 +210,21 @@@ final response before the CLI exits
- **Automatic joining:** no opt-in or background-mode override is needed.
Interactive TTY chat and messaging sessions keep background delegation.
+- **Per-input policy:** the CLI records finite consumption with the admitted prompt,
+ including when resuming an interactive session. It does not change that session's
+ creation policy, sibling viewers, or the daemon environment.
- - **Existing safeguards:** delegation limits, timeouts, and cancellation still apply.
+ - **Existing safeguards:** delegation limits, timeouts, cancellation, and
- `approvals.single_query_mode` still apply. Joining does not auto-approve commands
- or guarantee successful child outcomes. Inspect results and verify artifacts.
-- **Terminal completions:** this does not change background terminal notification
- behavior or the bounded `terminal.oneshot_completion_wait_seconds` exit wait.
- That setting is not a delegation timeout.
-
-Delegation remains process-local. Interrupting or terminating the parent can
-cancel unfinished children. Use a durable scheduler for work that must survive
-the initiating process.
++ `approvals.single_query_mode` (`-q` turns; `hermes -z` turns are unattended) still apply.
+ Joining does not auto-approve commands or guarantee successful child outcomes.
+ Inspect results and verify artifacts. Managed/safe workers still reject child
+ delegation until their child-registration contract is available.
+- **Separate limits:** `--run-budget` remains unsupported by gateway chat; it is not
+ required for joining. `terminal.oneshot_completion_wait_seconds` is not a
+ delegation timeout. Canonical terminal notifications remain gateway-owned.
+
+Closing the CLI detaches rather than terminating its gateway-owned turn. Child
+execution is still process-local to that owner: use a durable scheduler for work
+that must survive an owner restart.
### `hermes -z <prompt>` — scripted one-shot