Skip to content

The agent that grows with you

fix(gateway): one durable session keeps one request prefix across TUI, one-shot and gateway hops

teknium1e3fc10b926ba
diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py
index 8f3ae667128..52479c863f5 100644
--- a/agent/transports/chat_completions.py
+++ b/agent/transports/chat_completions.py
@@ -35,7 +35,9 @@ _XAI_TOOL_SEARCH_ALIAS = "hermes_tool_search"
# 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",
+ # ``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",
)
_STRIP_TC_KEYS = ("call_id", "response_item_id")
_HIGH_EFFORTS = {"high", "xhigh", "max", "ultra"}
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index 23d2dbc85ff..5f078750880 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -629,7 +629,13 @@ class GatewayTurnPrepareMixin:
# The context prompt render is pinned per session, keyed by a hash of the renderer inputs, so
# the system prompt cannot drift turn-over-turn; a miss (thread rename, /sethome) re-renders.
- context_prompt = self._pinned_session_context_prompt(context, _redact_pii, session_key)
+ # 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.
+ context_prompt = "" if source.platform == Platform.LOCAL else \
+ self._pinned_session_context_prompt(context, _redact_pii, session_key)
# Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt
# (appending to the ephemeral system prompt forced a full agent rebuild).
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index eb65d2ad1c0..abb5aaeca8c 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -315,6 +315,11 @@ class AuthorityConnection:
self.authority.authorize(self.actor, ref, 'session:control')
from gateway.session_local_mcp import resume_editor_mcp
resume_editor_mcp(self.authority, ref, params['editor'])
+ # A resume by id/title is the user asking for THIS conversation to continue; a stamped
+ # tui_shutdown / ws_disconnect row would otherwise be routed as stale on the next submit.
+ self.authority.authorize(self.actor, ref, 'session:read')
+ from gateway.session_local_recovery import reopen_local_session
+ reopen_local_session(self.authority, ref)
snapshot = await self.authority.attach(self.actor, ref)
self.subscriptions[ref.session_id] = snapshot.subscription_id
# Only local routes have a frozen local launch policy to project.
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index df3874ee05a..eaf258b047c 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -119,6 +119,25 @@ def local_history(authority, ref):
return authority.db.get_messages_as_conversation(target)
+def reopen_local_session(authority, ref):
+ """An explicit resume makes a local session live again.
+
+ A TUI shutdown / WS disconnect / idle eviction stamps ``end_reason`` on the physical row.
+ ``SessionStore`` reads any stamped row as a stale route (#54878) and, since those reasons are
+ not recoverable, answers the next submit with a FRESH session — the resumed client keeps waiting
+ on an id that never emits again. The classic resumes clear the stamp (``oneshot._load_resume_target``,
+ tui_gateway ``_resume_cold``); the authority must too. Only the lineage tip is reopened: a
+ compression parent or reset predecessor is never the physical target.
+ """
+ live = authority.sessions.get(ref.session_id)
+ if live is None or live.source is None or live.source.platform != Platform.LOCAL:
+ return
+ target = local_receipt(authority.db, ref.session_id)['entry']['session_id']
+ row = authority.db.get_session(target)
+ if row is not None and row.get('end_reason') is not None:
+ authority.db.reopen_session(target)
+
+
def reset_local_session(store, old_entry, session_id, now, display_name):
from hermes_state_local_lineage import reset_local_target
entry = SessionEntry(old_entry.session_key, session_id, now, now,
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index b818a329ea8..c658d65c882 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -1288,9 +1288,13 @@ class SessionMessagesMixin:
"""
rows = self._fetch_conversation_rows(
self._resume_lineage_ids(session_id), _DISPLAY_ACTIVE_CLAUSE, with_session_id=True)
- # The model projection stays active-only: it is the compressed working context.
+ # The model projection stays active-only: it is the compressed working context. The gateway's
+ # first-turn ``session_meta`` marker (tools/model/platform bookkeeping) is transcript logging,
+ # never LLM input: a resuming surface that fed it to the agent would count it in the history
+ # and send a prefix the previous process never sent.
model_history = self._rows_to_conversation(
- [r for r in rows if r["session_id"] == session_id and r["active"]], session_id=session_id,
+ [r for r in rows if r["session_id"] == session_id and r["active"] and r["role"] != "session_meta"],
+ session_id=session_id,
include_ancestors=False, repair_alternation=True, include_row_ids=True, include_summary_markers=True)
display_history = self._rows_to_conversation(
self._dedupe_display_generations(rows), session_id=session_id,
diff --git a/tests/agent/transports/test_chat_completions.py b/tests/agent/transports/test_chat_completions.py
index ef4d40458fd..0d5d539f2b7 100644
--- a/tests/agent/transports/test_chat_completions.py
+++ b/tests/agent/transports/test_chat_completions.py
@@ -107,8 +107,16 @@ class TestChatCompletionsBasic:
-
-
+ def test_convert_messages_strips_replayed_platform_message_id(self, transport):
+ """SQLite replay exposes ``platform_message_id`` as ``message_id`` (JSONL transcript compat);
+ the gateway stamps it on every user row from the admission id. It is delivery bookkeeping:
+ the in-process CLI never sent it, so a resuming surface that let it through would send a
+ different prefix for the same durable session and break the cache.
+ """
+ msgs = [{"role": "user", "content": "hi", "message_id": "adm-123"}]
+ result = transport.convert_messages(msgs)
+ assert "message_id" not in result[0]
+ assert result[0]["content"] == "hi"
def test_convert_messages_strips_timestamp(self, transport):
"""Internal per-message ``timestamp`` metadata (stamped by
diff --git a/tests/e2e/core/parity/_drive_acp.py b/tests/e2e/core/parity/_drive_acp.py
index 25bd77afef6..361888c785e 100644
--- a/tests/e2e/core/parity/_drive_acp.py
+++ b/tests/e2e/core/parity/_drive_acp.py
@@ -5,7 +5,9 @@ newline-delimited JSON-RPC 2.0 itself (no SDK client) so the driver controls
every byte and the shutdown path: ``initialize`` -> ``session/new`` (ACP's
documented cwd channel) -> ``session/prompt``, collecting
``agent_message_chunk`` text from ``session/update`` notifications, then stdin
-EOF — the way an editor host closes the server.
+EOF — the way an editor host closes the server. ``hermes acp`` runs the turn in
+the profile's gateway daemon (``acp_adapter/gateway_server.py``), so the surface's
+shutdown ends with ``hermes gateway stop``.
"""
from __future__ import annotations
@@ -17,7 +19,14 @@ import threading
import time
from typing import Any
-from tests.e2e.core.parity._helpers import TURN_TIMEOUT, DriveResult, ParityHome, hermes_argv, terminate
+from tests.e2e.core.parity._helpers import (
+ TURN_TIMEOUT,
+ DriveResult,
+ ParityHome,
+ hermes_argv,
+ stop_profile_gateway,
+ terminate,
+)
from tests.fakes.fake_llm_provider import FakeLLMServer
ACP_TOOLSET = "hermes-acp" # acp_adapter/session.py::_expand_acp_enabled_toolsets default
@@ -108,7 +117,9 @@ def drive_acp(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:
)
client = _AcpClient(proc)
graceful = True
+ gateway_stopped = False
stop_reason = None
+ init = None
try:
init = client.request("initialize", {
"protocolVersion": 1,
@@ -133,6 +144,9 @@ def drive_acp(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:
except subprocess.TimeoutExpired:
graceful = False
terminate(proc)
+ # The daemon that ran the turn outlives the ACP server; stop it the operator way.
+ gateway_stopped = stop_profile_gateway(ph)
+ graceful = graceful and gateway_stopped
return DriveResult(
final_text="".join(client.chunks),
toolset=ACP_TOOLSET,
@@ -141,6 +155,7 @@ def drive_acp(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:
extra={
"stop_reason": stop_reason,
"returncode": proc.returncode,
+ "gateway_stopped": gateway_stopped,
"agent_info": (init or {}).get("agentInfo"),
"server_requests": client.server_requests,
"stray_stdout": client.stray_stdout[:20],
diff --git a/tests/e2e/core/parity/_drive_cli.py b/tests/e2e/core/parity/_drive_cli.py
index 1d87cd4665a..4289c0a8412 100644
--- a/tests/e2e/core/parity/_drive_cli.py
+++ b/tests/e2e/core/parity/_drive_cli.py
@@ -14,13 +14,24 @@ Driver contract (every ``_drive_*.py`` module follows it)::
* stop the entrypoint through its NORMAL shutdown path (exit, stdin EOF,
SIGTERM, RPC) before returning; never SIGKILL except as a last resort after a
bounded graceful wait (and then report it via ``graceful_exit=False``).
+
+``hermes -z`` and ``hermes chat -q`` are thin clients of the unified gateway
+runtime: the turn runs in the profile's ``gateway run`` daemon (spawned on first
+connect), which outlives the client by design. Their normal shutdown is therefore
+client exit + ``hermes gateway stop`` (``stop_profile_gateway``).
"""
from __future__ import annotations
import subprocess
-from tests.e2e.core.parity._helpers import TURN_TIMEOUT, DriveResult, ParityHome, hermes_argv
+from tests.e2e.core.parity._helpers import (
+ TURN_TIMEOUT,
+ DriveResult,
+ ParityHome,
+ hermes_argv,
+ stop_profile_gateway,
+)
from tests.fakes.fake_llm_provider import FakeLLMServer
@@ -31,13 +42,22 @@ def _run_cli(ph: ParityHome, *args: str) -> subprocess.CompletedProcess:
)
+def _client_turn(ph: ParityHome, label: str, *args: str) -> DriveResult:
+ proc = _run_cli(ph, *args)
+ try:
+ assert proc.returncode == 0, f"{label} exited {proc.returncode}: {proc.stderr[-2000:]}"
+ finally:
+ # The daemon is the surface's process; a failed client still leaves it to stop.
+ stopped = stop_profile_gateway(ph)
+ return DriveResult(
+ final_text=proc.stdout.strip(), toolset="hermes-cli", graceful_exit=stopped,
+ extra={"exit_code": proc.returncode, "stderr_tail": proc.stderr[-2000:], "gateway_stopped": stopped},
+ )
+
+
def drive_oneshot(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:
- proc = _run_cli(ph, "-z", prompt)
- assert proc.returncode == 0, f"hermes -z exited {proc.returncode}: {proc.stderr[-2000:]}"
- return DriveResult(final_text=proc.stdout.strip(), toolset="hermes-cli")
+ return _client_turn(ph, "hermes -z", "-z", prompt)
def drive_chat_q(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:
- proc = _run_cli(ph, "chat", "-q", prompt, "-Q")
- assert proc.returncode == 0, f"hermes chat -q exited {proc.returncode}: {proc.stderr[-2000:]}"
- return DriveResult(final_text=proc.stdout.strip(), toolset="hermes-cli")
+ return _client_turn(ph, "hermes chat -q", "chat", "-q", prompt, "-Q")
diff --git a/tests/e2e/core/parity/_drive_cron.py b/tests/e2e/core/parity/_drive_cron.py
index 83bf4faac2b..40c88b088c9 100644
--- a/tests/e2e/core/parity/_drive_cron.py
+++ b/tests/e2e/core/parity/_drive_cron.py
@@ -3,12 +3,14 @@
Follows the driver contract in ``_drive_cli``. ``hermes cron create`` writes the
job (``--deliver local``: no platform; ``--workdir``: cron's documented
per-job cwd/context channel, see ``hermes cron create --help``), then
-``hermes cron run <id>`` executes it. With no gateway owning the store the CLI
-runs the job synchronously through ``cron.scheduler.run_job`` — the same agent
-build the ticker uses (``hermes_cli/cron.py::_job_action`` forces the
-synchronous path) — and prints ``Ran now: succeeded.``. The job's saved output
-file (``cron/output/<id>/<ts>.md``, ``## Response`` section) is what cron
-delivers locally, so that is ``final_text``.
+``hermes cron run <id>`` executes it: the CLI waits synchronously
+(``hermes_cli/cron.py::_job_action`` forces the synchronous path) while the turn
+runs in the profile's gateway daemon (``cron.scheduler_authority.run_canonical_job``
+→ ``connect_gateway``, which spawns the daemon when none owns the profile) — the
+same agent build the ticker uses — and prints ``Ran now: succeeded.``. The job's
+saved output file (``cron/output/<id>/<ts>.md``, ``## Response`` section) is what
+cron delivers locally, so that is ``final_text``. The daemon outlives the CLI, so
+the surface's shutdown ends with ``hermes gateway stop``.
Both CLI calls run from the fake HOME, not the project: a scheduled job's
process cwd is whatever the ticker had, so the workdir is the only channel
@@ -20,7 +22,13 @@ from __future__ import annotations
import re
import subprocess
-from tests.e2e.core.parity._helpers import TURN_TIMEOUT, DriveResult, ParityHome, hermes_argv
+from tests.e2e.core.parity._helpers import (
+ TURN_TIMEOUT,
+ DriveResult,
+ ParityHome,
+ hermes_argv,
+ stop_profile_gateway,
+)
from tests.fakes.fake_llm_provider import FakeLLMServer
# cron/scheduler.py::_resolve_cron_enabled_toolsets -> _get_platform_tools(cfg, "cron") default.
@@ -45,6 +53,7 @@ def drive_cron(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:
job_id = match.group(1)
ran = _cron(ph, "run", job_id)
+ gateway_stopped = stop_profile_gateway(ph)
assert ran.returncode == 0, f"hermes cron run exited {ran.returncode}: {ran.stderr[-2000:]}"
# Anything but a synchronous verdict means the run was handed to a ticker/background
# worker this driver cannot observe — a harness problem, not a parity result.
@@ -60,9 +69,14 @@ def drive_cron(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:
final_text=final_text,
toolset=CRON_TOOLSET,
cwd_channel="job workdir",
- graceful_exit=True, # both CLI invocations exited on their own (subprocess.run, no signal)
+ # Both CLI invocations exited on their own (subprocess.run, no signal); the daemon took
+ # the operator stop.
+ graceful_exit=gateway_stopped,
extra={
"job_id": job_id,
+ "gateway_stopped": gateway_stopped,
+ "exit_code": ran.returncode,
+ "stderr_tail": ran.stderr[-2000:],
"run_stdout": ran.stdout.strip()[-500:],
"run_succeeded": "Ran now: succeeded." in ran.stdout,
"output_file": str(outputs[-1]) if outputs else None,
diff --git a/tests/e2e/core/parity/_helpers.py b/tests/e2e/core/parity/_helpers.py
index db04772e2a7..e92abfbb0ba 100644
--- a/tests/e2e/core/parity/_helpers.py
+++ b/tests/e2e/core/parity/_helpers.py
@@ -50,6 +50,8 @@ _PASSTHROUGH_ENV = frozenset({
TURN_TIMEOUT = 240.0
+# `hermes gateway stop` waits for the daemon's planned exit (MCP teardown included).
+STOP_TIMEOUT = 120.0
@dataclass
@@ -457,6 +459,25 @@ def terminate(proc: subprocess.Popen, timeout: float = 30.0) -> int | None:
return proc.returncode
+def stop_profile_gateway(ph: ParityHome, timeout: float = STOP_TIMEOUT) -> bool:
+ """The normal stop for the profile's ``gateway run`` daemon: ``hermes gateway stop``.
+
+ ``hermes -z``, ``hermes chat -q``, ``hermes acp`` and ``hermes cron run`` are clients of the
+ unified gateway runtime: their first connect spawns the profile's daemon (``ensure_gateway_runtime``
+ → ``spawn_unmanaged_gateway``), the daemon owns the agent — and with it the MCP server tree — and it
+ keeps serving after the client exits (cron, messaging, the next client). So the surface's
+ "normal shutdown" is client exit PLUS the operator stop; only after that may the MCP tree be
+ judged for orphans. Returns True when the stop command reported a stopped gateway (False when
+ none was running, e.g. a client that never reached the daemon).
+ """
+ proc = subprocess.run(
+ hermes_argv("gateway", "stop"), cwd=ph.project, env=ph.env(), capture_output=True, text=True,
+ timeout=timeout, stdin=subprocess.DEVNULL,
+ )
+ assert proc.returncode == 0, f"hermes gateway stop exited {proc.returncode}: {proc.stderr[-2000:]}"
+ return "Stopped gateway" in proc.stdout
+
+
def format_cells(results: Iterable[tuple[str, dict[str, bool]]]) -> str:
rows = list(results)
cols = sorted({k for _, cells in rows for k in cells})
diff --git a/tests/e2e/core/parity/test_entrypoint_parity.py b/tests/e2e/core/parity/test_entrypoint_parity.py
index 7bc0864786a..648769096ea 100644
--- a/tests/e2e/core/parity/test_entrypoint_parity.py
+++ b/tests/e2e/core/parity/test_entrypoint_parity.py
@@ -16,7 +16,10 @@ Desktop/gateway/ACP/cron" class:
* the documented toolset's core feature tools are present, the disabled toolset
is absent;
* the surface delivered the model's answer to its client;
-* after the surface's normal shutdown no MCP server / grandchild survives.
+* after the surface's normal shutdown no MCP server / grandchild survives. For the
+ gateway-client surfaces (``-z``, ``chat -q``, ``acp``, ``cron run``) the turn runs
+ in the profile's ``gateway run`` daemon, which outlives the client by design;
+ their normal shutdown is client exit + ``hermes gateway stop``.
``PARITY_TABLE_OUT=<path>`` appends a markdown row per entrypoint (REPORT.md table).
"""