The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: canonical admission composes with main's chaos matrix, tools[] pin, webhook mirror and fr/de/es
teknium1f3511588795f
diff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.pyindex 89ac68eaee8..57a8c881e3d 100644--- a/agent/runtime_session_store.py+++ b/agent/runtime_session_store.py@@ -305,11 +305,11 @@ class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecyclself._session(session_id)self._apply('session.sidecars', {'patch': patch})- def update_session_tool_names(self, session_id, tool_names):- # The tools[] freeze pin: without it every fresh worker re-probes check_fns and a- # config flip between turns silently forks the cached prefix (in-process stays pinned).+ 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': None if tool_names is None else list(tool_names)})+ self._apply('session.tools', {'tool_names': pin})def finish(self):return self._apply('execution.finish', {})diff --git a/apps/desktop/e2e/core/harness.ts b/apps/desktop/e2e/core/harness.tsindex 1288681d8de..7f87a7c4f73 100644--- a/apps/desktop/e2e/core/harness.ts+++ b/apps/desktop/e2e/core/harness.ts@@ -256,8 +256,11 @@ export function sandboxProcesses(sandbox: CoreSandbox): ProcInfo[] {* dead backend is reparented away and still counted.*/export function backendProcesses(sandbox: CoreSandbox): ProcInfo[] {+ // The local backend is the gateway `hermes gateway ensure` attached to or started+ // (`hermes_cli.main [--profile X] gateway run --quiet`); `serve` covers a pool backend.const serve = sandboxProcesses(sandbox).filter(- proc => / serve( |$)/.test(proc.cmdline) && !/electron/i.test(proc.cmdline.split(' ')[0])+ proc => (/ serve( |$)/.test(proc.cmdline) || / gateway run( |$)/.test(proc.cmdline))+ && !/electron/i.test(proc.cmdline.split(' ')[0]))const pids = new Set(serve.map(proc => proc.pid))diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 23dd50a7e26..7f19df24554 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -16022,7 +16022,7 @@ async function handleHermesApiRequest(request) {let connectiontry {- const connection = await ensureBackend(routeProfile, {+ connection = await ensureBackend(routeProfile, {passive: request?.passive,request: { method: request?.method, path: request?.path }})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/heartbeat-complete-reorder.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/heartbeat-complete-reorder.test.tsxindex 8e1e9b834cf..49db4e9b4d8 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/heartbeat-complete-reorder.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/heartbeat-complete-reorder.test.tsx@@ -18,8 +18,11 @@ const SID = 'race119569-runtime'const STORED = 'race119569-stored'const noop = async () => undefined-const requestGateway = async <T,>(method: string): Promise<T> =>- (method === 'prompt.submit' ? { status: 'started' } : { status: 'redirected' }) as T+// The canonical admission receipt echoes the client's submission id.+const requestGateway = async <T,>(method: string, params?: Record<string, unknown>): Promise<T> =>+ (method === 'prompt.submit'+ ? { admission_id: params?.submission_id, session_id: SID, status: 'started' }+ : { status: 'redirected' }) as Tfunction mount() {const queryClient = new QueryClient()diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-locales.ts b/apps/desktop/src/plugins/hermes-bots/canonical-group-locales.tsindex e39f5c6bdbd..a14e95e3db0 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-locales.ts+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-locales.ts@@ -135,5 +135,69 @@ export const CANONICAL_GROUP_LOCALES = {attachFiles: 'Прикрепить файлы',removeAttachment: 'Удалить вложение',uploadFailed: 'Не удалось загрузить файл'+ },+ fr: {+ refreshGroups: 'Actualiser les groupes de la passerelle',+ loadingGroup: 'Chargement du groupe…',+ loadingGroups: 'Chargement des groupes de la passerelle…',+ emptyGroups: 'Aucun groupe de passerelle trouvé.',+ driverUnavailable:+ 'Pilote de groupe indisponible. Mettez à jour ou reconnectez la passerelle propriétaire.',+ invalidLogCursor: 'Curseur de journal de salon invalide',+ allowOnce: 'Autoriser une fois',+ deny: 'Refuser',+ discardUnknown: 'Abandonner le travail au résultat inconnu',+ discardWarning: 'Des effets de bord ont peut-être déjà eu lieu. Abandonner ne les annule pas.',+ confirmDiscard: "Confirmer l'abandon",+ unconfirmedSend:+ "L'envoi précédent n'est pas confirmé. Réessayez son texte d'origine avant d'envoyer un autre message.",+ restoredPendingSend: 'Un envoi non confirmé a été restauré. Réessayez-le avant d\'envoyer un autre message.',+ groupMessage: 'Message de groupe',+ attachFiles: 'Joindre des fichiers',+ removeAttachment: 'Retirer la pièce jointe',+ uploadFailed: 'Échec du téléversement'+ },+ de: {+ refreshGroups: 'Gateway-Gruppen aktualisieren',+ loadingGroup: 'Gruppe wird geladen…',+ loadingGroups: 'Gateway-Gruppen werden geladen…',+ emptyGroups: 'Keine Gateway-Gruppen gefunden.',+ driverUnavailable:+ 'Gruppentreiber nicht verfügbar. Aktualisieren Sie das zuständige Gateway oder verbinden Sie es neu.',+ invalidLogCursor: 'Ungültiger Raumprotokoll-Cursor',+ allowOnce: 'Einmal erlauben',+ deny: 'Ablehnen',+ discardUnknown: 'Arbeit mit unbekanntem Ergebnis verwerfen',+ discardWarning: 'Nebenwirkungen können bereits eingetreten sein. Verwerfen macht sie nicht rückgängig.',+ confirmDiscard: 'Verwerfen bestätigen',+ unconfirmedSend:+ 'Der vorherige Versand ist unbestätigt. Wiederholen Sie seinen ursprünglichen Text, bevor Sie eine weitere Nachricht senden.',+ restoredPendingSend:+ 'Ein unbestätigter Versand wurde wiederhergestellt. Wiederholen Sie ihn, bevor Sie eine weitere Nachricht senden.',+ groupMessage: 'Gruppennachricht',+ attachFiles: 'Dateien anhängen',+ removeAttachment: 'Anhang entfernen',+ uploadFailed: 'Hochladen fehlgeschlagen'+ },+ es: {+ refreshGroups: 'Actualizar grupos de la pasarela',+ loadingGroup: 'Cargando grupo…',+ loadingGroups: 'Cargando grupos de la pasarela…',+ emptyGroups: 'No se encontraron grupos de la pasarela.',+ driverUnavailable:+ 'Controlador de grupo no disponible. Actualiza o vuelve a conectar la pasarela propietaria.',+ invalidLogCursor: 'Cursor de registro de sala no válido',+ allowOnce: 'Permitir una vez',+ deny: 'Denegar',+ discardUnknown: 'Descartar trabajo con resultado desconocido',+ discardWarning: 'Puede que ya se hayan producido efectos secundarios. Descartar no los deshace.',+ confirmDiscard: 'Confirmar descarte',+ unconfirmedSend:+ 'El envío anterior no está confirmado. Reintenta su texto original antes de enviar otro mensaje.',+ restoredPendingSend: 'Se restauró un envío sin confirmar. Reintántalo antes de enviar otro mensaje.',+ groupMessage: 'Mensaje de grupo',+ attachFiles: 'Adjuntar archivos',+ removeAttachment: 'Quitar adjunto',+ uploadFailed: 'Error al subir'}} satisfies Record<string, CanonicalGroupMessages>diff --git a/apps/desktop/src/plugins/hermes-bots/i18n.ts b/apps/desktop/src/plugins/hermes-bots/i18n.tsindex f7a909d7e32..be2af2f7b2c 100644--- a/apps/desktop/src/plugins/hermes-bots/i18n.ts+++ b/apps/desktop/src/plugins/hermes-bots/i18n.ts@@ -2162,7 +2162,10 @@ export const BOTS_LOCALES: PluginLocaleBundles = {zh,'zh-hant': zhHant,ar: { canonical: CANONICAL_GROUP_LOCALES.ar },- ru: { canonical: CANONICAL_GROUP_LOCALES.ru }+ ru: { canonical: CANONICAL_GROUP_LOCALES.ru },+ fr: { canonical: CANONICAL_GROUP_LOCALES.fr },+ de: { canonical: CANONICAL_GROUP_LOCALES.de },+ es: { canonical: CANONICAL_GROUP_LOCALES.es }}// Bind the message SHAPE to a plugin translator: string leaves resolve now,diff --git a/gateway/platforms/webhook_delivery.py b/gateway/platforms/webhook_delivery.pyindex a339a6351aa..2b092c37bd7 100644--- a/gateway/platforms/webhook_delivery.py+++ b/gateway/platforms/webhook_delivery.py@@ -19,8 +19,10 @@ def validate_destination(delivery):from gateway.platforms.webhook import _is_known_platform, _REPO_REif (not isinstance(delivery, dict)or not {'deliver', 'deliver_extra'} <= set(delivery)- or set(delivery) - {'deliver', 'deliver_extra', 'profile'}- or (delivery.get('profile') is not None and not isinstance(delivery['profile'], str))):+ 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):@@ -36,9 +38,15 @@ def validate_destination(delivery):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 default to preserve pre-profile receipt fingerprints.+ # 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 onlyreturn resultdiff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 715cc4b2b19..5329d778253 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -672,6 +672,43 @@ class GatewayInboundMixin:# — that copy was never consumed and grew unbounded.running_agent.interrupt(_interrupt_text)+ async def _hm_busy_preempt(self, event: "MessageEvent", source: SessionSource, _quick_key: str) -> bool:+ """busy_input_mode for a follow-up the durable FIFO is about to admit. Returns True when the+ text already landed inside the running turn (steer / redirect), so it must NOT also be+ admitted as its own turn; False when the caller should admit it (queue mode, a demotion,+ or an interrupt — the ended turn lets the FIFO run the follow-up next)."""+ from gateway.run import _AGENT_PENDING_SENTINEL+ mode = self._effective_busy_input_mode(source)+ state = self._peek_session_state(_quick_key)+ running_agent = state.turn.agent if state else None+ if (mode == "queue" or self._draining or running_agent is None+ or running_agent is _AGENT_PENDING_SENTINEL or not self._hm_text_only(event)):+ return False+ text = (event.text or "").strip()+ if not text:+ return False+ if mode == "steer":+ if hasattr(running_agent, "steer"):+ try:+ return bool(self._steer_running_agent(running_agent, self._steer_text_with_origin(text, event)))+ except Exception as exc:+ logger.warning("PRIORITY steer failed for session %s: %s", _quick_key, exc)+ return False+ if self._agent_has_active_subagents(running_agent):+ logger.info("PRIORITY interrupt demoted to queue for session %s because the running agent has active subagents (#30170)", _quick_key)+ return False+ if await self._session_has_compression_in_flight(_quick_key):+ logger.info("PRIORITY interrupt demoted to queue for session %s because context compression is in flight (#56391)", _quick_key)+ return False+ if (getattr(running_agent, "_supports_active_turn_redirect", False) is True and hasattr(running_agent, "redirect")+ and self._redirect_active_turn(running_agent, text, _quick_key, event)):+ logger.debug("PRIORITY redirect for session %s", _quick_key)+ return True+ # No redirect: end the running turn; the follow-up is admitted and runs as the next turn.+ logger.debug("PRIORITY interrupt for session %s", _quick_key)+ running_agent.interrupt()+ return False+async def _hm_handle_running_session_message(self, event: "MessageEvent", source: SessionSource, _quick_key: str) -> Optional[str]:@@ -1303,6 +1340,12 @@ class GatewayInboundMixin:if authority is not None and not event.get_command() and not is_internal:from gateway.session_ingress import admit_message, executing_admissionif not executing_admission.get():+ # The durable FIFO only orders turns; busy_input_mode still decides what a follow-up+ # does to the RUNNING one (steer into it, redirect it, or end it so the FIFO advances).+ # Without this, ``interrupt`` degrades to ``queue`` behind a turn that may hang for+ # its whole request timeout.+ if self._is_session_running(_quick_key) and await self._hm_busy_preempt(event, source, _quick_key):+ return Nonereturn await admit_message(authority, event)if (authority is None and not is_internal and not event.get_command()and getattr(self, 'session_authority', None) is not None):diff --git a/gateway/session_ingress_context.py b/gateway/session_ingress_context.pyindex fb672a2fd4f..9538bc99192 100644--- a/gateway/session_ingress_context.py+++ b/gateway/session_ingress_context.py@@ -138,7 +138,12 @@ def _binding(runner, source, profile):if relay:transport, connector = _relay_connector(adapter, source)else:- connector = runner._adapter_credential_fingerprint(adapter)+ # The connector pins "the same credential still serves this route" across a restart. A+ # plugin platform with no discoverable credential (in-memory / socket-only adapters) is+ # still one registered adapter; it binds by platform + owning profile rather than being+ # refused as not_found.+ connector = (runner._adapter_credential_fingerprint(adapter)+ or f'adapter:{source.platform.value}:{profile or ""}')if connector is None:raise RuntimeStoreError('not_found')provenance = {'transport_home': str(home), 'runtime_home': str(runtime_home),diff --git a/hermes_state_worker_context.py b/hermes_state_worker_context.pyindex c9cb1316cb5..f679a4f8d4f 100644--- a/hermes_state_worker_context.py+++ b/hermes_state_worker_context.py@@ -14,8 +14,10 @@ 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 '- 'FROM sessions s LEFT JOIN system_prompts sp ON sp.hash=s.system_prompt_hash WHERE s.id=?',+ '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)}@@ -40,10 +42,24 @@ def worker_sidecars(db, conn, session_id, payload):def worker_tool_names(db, conn, session_id, payload):- names = payload.get('tool_names') if set(payload) == {'tool_names'} else False- if names is False or not (names is None or (isinstance(names, list) and len(names) <= 4096- and all(isinstance(n, str) and 0 < len(n) <= 256 for n in names))):+ """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=?',- (None if names is None else json.dumps(names), session_id))+ (db._store_system_prompt(conn, encoded), session_id))+ db._delete_unreferenced_system_prompts(conn)return {'value': None}diff --git a/tests/agent/test_runtime_session_store.py b/tests/agent/test_runtime_session_store.pyindex 6635c35af96..0ea6c396bb6 100644--- a/tests/agent/test_runtime_session_store.py+++ b/tests/agent/test_runtime_session_store.py@@ -102,8 +102,12 @@ def test_worker_store_persists_and_restores_the_tools_prefix_pin(tmp_path):tools = [{'type': 'function', 'function': {'name': n, 'parameters': {}}}for n in ('terminal', 'tool_search', 'tool_describe', 'tool_call')]persist_agent_tool_names(SimpleNamespace(_session_db=store, session_id='owned', tools=tools))- assert json.loads(db.get_session('owned')['tool_names']) == ['terminal', 'tool_search', 'tool_describe', 'tool_call']- assert json.loads(store.get_session('owned')['tool_names']) == ['terminal', 'tool_search', 'tool_describe', 'tool_call']+ db.create_session('direct', 'cli', system_prompt='prefix')+ persist_agent_tool_names(SimpleNamespace(_session_db=db, session_id='direct', tools=tools))+ # The same pin the direct store writes (the RPC canonicalizes key order for its receipt+ # digest): a worker-pinned session rebuilt in-process reads back version + tools intact.+ assert json.loads(db.get_session('owned')['tool_names']) == json.loads(db.get_session('direct')['tool_names'])+ assert json.loads(store.get_session('owned')['tool_names'])['tools'] == toolswith pytest.raises(WorkerPersistenceError, match='permission_denied'):store.update_session_tool_names('foreign', ['terminal'])with pytest.raises(Exception, match='invalid_params'):diff --git a/tests/gateway/fixtures/webhook_route_authority.py b/tests/gateway/fixtures/webhook_route_authority.pyindex 60fe9d97307..c14e754cb34 100644--- a/tests/gateway/fixtures/webhook_route_authority.py+++ b/tests/gateway/fixtures/webhook_route_authority.py@@ -13,6 +13,9 @@ def mount_authority(app, adapter):from gateway.session import SessionStorefrom hermes_constants import get_hermes_homerunner = GatewayRunner()+ # Route tests mount ONE default-profile authority with no profile reservation; a profiles/+ # directory in the test home must not flip the runner into (unreserved) multiplex mode.+ runner.config.multiplex_profiles = Falserunner.session_store = SessionStore(sessions_dir=get_hermes_home() / "sessions", config=runner.config)from hermes_state import SessionDBrunner.session_store._db = SessionDB(db_path=get_hermes_home() / "state.db")