The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): CLI turns over the daemon keep the classic one-shot contract
teknium156bb627cb60e
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 5357187552e..dfedda18ccc 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -2212,6 +2212,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginself._ineffective_compression_count = 0# Wall-clock probe deadline; 0.0 = unarmed (durable copy re-read via _load_anti_thrash_recovery_deadline).self._anti_thrash_recovery_deadline = self._structural_no_op_backoff_until = 0.0+ self._structural_no_op_len = 0# Observability only; never feeds the strike latch or the fallback streak.self._prellm_skip_count = 0# Only a healthy completed summary resets this; ordinary fitting responses do not.@@ -2366,11 +2367,14 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginself._ineffective_compression_count = countself._persist_ineffective_compression_count()- def _record_structural_no_op(self, reason: str) -> None:+ def _record_structural_no_op(self, reason: str, n_messages: int = 0) -> None:"""Defer retries after a structural no-op WITHOUT striking the anti-thrash breaker.Nothing eligible existed, so nothing was "ineffective"; striking would permanently disarm- auto-compaction on short sessions. The backoff still stops per-turn re-scans."""+ auto-compaction on short sessions. The backoff still stops per-turn re-scans. It is a+ verdict about THIS transcript shape: a serving process that keeps the compressor across+ turns (the gateway daemon) lifts it as soon as the transcript has grown (``compress``)."""self._structural_no_op_backoff_until = time.monotonic() + self._STRUCTURAL_NO_OP_BACKOFF_SECONDS+ self._structural_no_op_len = int(n_messages or 0)if not self.quiet_mode:logger.warning("Compression skipped (%s): retrying in %.0fs (structural no-op backoff)", reason,@@ -5007,11 +5011,17 @@ Write only the summary body. Do not include any preamble or prefix."""self._structural_no_op_backoff_until = 0.0return telemetry- def _structural_no_op_result(self, telemetry: Dict[str, Any], failure_class: str, reason: str) -> None:+ def _structural_no_op_result(self, telemetry: Dict[str, Any], failure_class: str, reason: str,+ n_messages: int = 0) -> None:"""Nothing eligible to compress: transient backoff (#93022), never an ineffectiveness strike."""telemetry["failure_class"] = failure_classself._last_compression_savings_pct = 0.0- self._record_structural_no_op(reason)+ self._record_structural_no_op(reason, n_messages)++ def lift_structural_backoff_if_grown(self, n_messages: int) -> None:+ """A structural no-op said "nothing eligible among N messages"; more messages is new evidence."""+ if self._structural_no_op_backoff_until and n_messages > getattr(self, "_structural_no_op_len", 0):+ self._structural_no_op_backoff_until = 0.0def _drop_blank_echoes(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Remove blank platform echoes trailing the latest actionable user turn."""@@ -5309,6 +5319,7 @@ Write only the summary body. Do not include any preamble or prefix."""if n_messages <= _min_for_compress:self._structural_no_op_result(telemetry, "insufficient_messages", f"only {n_messages} messages (need > {_min_for_compress})",+ n_messages,)return messagesdisplay_tokens = current_tokens if current_tokens else self.last_prompt_tokens or estimate_messages_tokens_rough(messages)@@ -5329,6 +5340,7 @@ Write only the summary body. Do not include any preamble or prefix."""self._structural_no_op_result(telemetry, "no_compressible_window",f"compress_start ({compress_start}) >= compress_end ({compress_end}) - transcript fits within tail budget",+ n_messages,)return messagesturns_to_summarize = messages[compress_start:compress_end]@@ -5347,6 +5359,7 @@ Write only the summary body. Do not include any preamble or prefix."""self._structural_no_op_result(telemetry, "empty_post_handoff_window",f"window {compress_start}-{compress_end} holds only already-summarized handoffs",+ n_messages,)return messagesif not self.quiet_mode:diff --git a/agent/runtime_session_compression.py b/agent/runtime_session_compression.pyindex ef363319632..897c5cb46aa 100644--- a/agent/runtime_session_compression.py+++ b/agent/runtime_session_compression.py@@ -52,14 +52,18 @@ class RuntimeSessionCompressionMixin:return self._apply('compression.watermark', {})['value']def archive_and_compact(self, session_id, compacted_messages, model_config_patch=None,- watermark=None, lock_holder=None, tail_count=0, carried_messages=None):+ watermark=None, lock_holder=None, tail_count=0, carried_messages=None,+ covered_ids=None, unresolved_held=None):self._session(session_id)# A carried message names an exact durable original (its _row_id) to rewind rather than- # archive (#118900); the owner resolves identities against its own store.+ # archive (#118900); the owner resolves identities against its own store. Held-row+ # coverage travels the same way: the owner proves it inside the commit transaction.carried = [dict(m) for m in carried_messages or [] if isinstance(m, dict)]+ unresolved = None if unresolved_held is None else [dict(m) for m in unresolved_held if isinstance(m, dict)]result = self._apply('compression.archive', dict(messages=compacted_messages,model_config_patch=model_config_patch, watermark=watermark, lock_holder=lock_holder,- tail_count=tail_count, carried_messages=carried))+ tail_count=tail_count, carried_messages=carried, covered_ids=covered_ids,+ unresolved_held=unresolved))for message, row_id in zip(compacted_messages, result['row_ids'], strict=True):message['_row_id'] = row_idreturn result['value']diff --git a/agent/turn_context_compaction.py b/agent/turn_context_compaction.pyindex 54678deb4f7..06f28b0c806 100644--- a/agent/turn_context_compaction.py+++ b/agent/turn_context_compaction.py@@ -241,6 +241,11 @@ def _preflight_compression(_rearm_uncompressed_overflow_warn(agent, out.messages, out.active_system_prompt)return_compressor = agent.context_compressor+ # A structural no-op ("nothing eligible among N messages") is a verdict about that transcript;+ # the gateway daemon keeps this compressor across turns, so a grown transcript re-arms it.+ _lift = getattr(_compressor, "lift_structural_backoff_if_grown", None)+ if callable(_lift):+ _lift(len(out.messages))if _tc._review_fork_first_request_pending(agent) or not _tc._should_run_preflight_estimate(out.messages, _compressor.protect_first_n, _compressor.protect_last_n,_compressor.threshold_tokens,diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.pyindex ce9b6509e31..82331aada74 100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@ -388,9 +388,11 @@ class GatewayTurnPersistenceMixin:if is_context_overflow_failure:pass # Skip all transcript writes — don't grow a broken sessionelse:- if not history:+ if not history and source.platform != Platform.LOCAL:# Fresh session: the tool definitions (as sent in the API request) make the transcript- # self-describing.+ # 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 [],diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 5f078750880..c8c4dc5a139 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -53,9 +53,11 @@ class GatewayTurnPrepareMixin:_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 = Nonepolicy = policy_for_source(self, source) if source is not None else Noneif policy is not None:- from hermes_cli.runtime_provider import resolve_runtime_providerfrom gateway.run import _runtime_agent_kwargsfrom gateway.session_policy import launch_keyfrom hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime@@ -70,15 +72,25 @@ class GatewayTurnPrepareMixin:if runtime is None:if key is None:key = frozen.get('model', {}).get('api_key')- runtime = resolve_runtime_provider(requested=policy.provider,- explicit_api_key=key, explicit_base_url=policy.base_url, target_model=policy.model)+ # 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)- # Every exit path starts clean: the /model-override fast path returns before the pop below,- # and hygiene/inbound callers resolve without a turn runner consuming the stash — a stale- # notice must never attach to another session's next turn (#74349).- self._pre_agent_fallback_notice = None-model = _resolve_gateway_model(user_config)if skey:self._rehydrate_session_model_override(skey)@@ -504,6 +516,11 @@ class GatewayTurnPrepareMixin:from gateway.run import _hermes_home, _home_target_env_var, _load_gateway_configif history: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:+ returnif not await self.async_session_store.has_any_sessions():_intro_note = ("[System note: This is the user's very first message ever. "diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex f2bc57245d7..00f820b17b9 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -60,6 +60,22 @@ def _renders_exec_approval_buttons(adapter_cls: type) -> bool:# 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."+# 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):@@ -174,11 +190,19 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):stream_delta_cb = Noneif delta_sinks or self._approval_owner is not None:def stream_delta_cb(text: Optional[str]) -> None:- if ctx._run_still_current():- if text is not None: # None closes only the native stream segment.- self._publish_execution("message.delta", {"text": text})- for sink in delta_sinks:- sink.on_delta(text)+ if not ctx._run_still_current():+ return+ delivered = bool(delta_sinks)+ if text is not None: # None closes only the native stream segment.+ delivered = self._publish_execution("message.delta", {"text": text}) or delivered+ for sink in delta_sinks:+ sink.on_delta(text)+ if text is not None and (not delivered or _finite_viewer_turn()):+ # Nobody the user is looking at saw this text: no live viewer/observer/adapter+ # sink, or a finite (`-z`, `chat -q`) viewer, which prints the terminal reply+ # only. The agent must treat it as undelivered, else a stream that dies here is+ # stitched as a "partial delivery" nobody received (classic -q parity).+ raise _NoStreamConsumer()def interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:if not ctx._run_still_current():@@ -1024,7 +1048,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):runner._pre_agent_fallback_notice = Nonefrom gateway.session_api_turn import prepare_api_runtimemodel, runtime_kwargs = prepare_api_runtime(model, runtime_kwargs)- if policy and policy.model:+ if policy and policy.model and not pending_fallback_notice:+ # The frozen route's model, unless resolution just fell back: the fallback entry's+ # model is the one this agent must send (#112600).model = policy.modellogger.debug("run_agent resolved: model=%s provider=%s session=%s",@@ -1105,6 +1131,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):"output_tokens": getattr(agent, "session_completion_tokens", 0) if has_comp else 0,"model": getattr(agent, "model", None) if agent else None,"context_length": (getattr(comp, "context_length", 0) or 0) if has_comp else 0,+ # The rest of the `-z --usage-file` ledger (hermes_cli/oneshot._USAGE_KEYS): a finite+ # viewer reads the committed result over `prompt.receipt`, so the projection must keep+ # what the in-process one-shot took straight from `run_conversation`.+ **{key: result.get(key) for key in _LEDGER_PASSTHROUGH_KEYS if key in result},}compacted_in_place, effective_session_id, history_offset = self._sync_session_after_run(agent_history)# failure_reason must survive the empty-response path too (TUI billing, transient-failurediff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex f4e6e644781..b5bf150c77d 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -281,20 +281,25 @@ def _api_observers(authority, session_id):def _notify_observers(authority, session_id, key, *args):"""Observer callbacks are request-owned sinks; one that raises (closed socket, torn-down- loop) must not abort canonical execution or starve the other observers."""+ loop) must not abort canonical execution or starve the other observers. Returns whether+ any observer accepted the event."""import logging+ accepted = Falsefor observer in _api_observers(authority, session_id):callback = observer.get(key)if callback:try:callback(*args)+ accepted = Trueexcept Exception:logging.getLogger(__name__).warning('API observer %s failed for %s', key, session_id, exc_info=True)+ return accepteddef publish_api_event(authority, session_id, event_type, payload):if event_type == 'message.delta':- _notify_observers(authority, session_id, 'stream_delta_callback', payload['text'])+ return _notify_observers(authority, session_id, 'stream_delta_callback', payload['text'])+ return Falsedef publish_api_tool_event(authority, session_id, generation, event_type, call_id, tool_name, args, result=None):diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 1c3068e21d2..08844d08d1b 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -397,10 +397,10 @@ class SessionAuthority:self.check_approval_generation(session_id, generation)except RuntimeStoreError:return False- live.event_stream.publish(session_id, payload, event_type=event_type)+ delivered = live.event_stream.publish(session_id, payload, event_type=event_type)from gateway.session_api_turn import publish_api_event- publish_api_event(self, session_id, event_type, payload)- return True+ observed = publish_api_event(self, session_id, event_type, payload)+ return bool(delivered or observed)def register_approval(self, session_id, generation, route, data):live = self.sessions[session_id]diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex abb5aaeca8c..8d7c06a4a09 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -392,7 +392,18 @@ class AuthorityConnection:return resultasync def receipt(self, ref, params):- return asdict(await self.authority.receipt(self.actor, ref, params.get('admission_id')))+ receipt = await self.authority.receipt(self.actor, ref, params.get('admission_id'))+ out = asdict(receipt)+ if params.get('include_result') is True and receipt.status == 'terminal':+ # The exact structured result the turn committed with settlement (`finish_result`):+ # a finite viewer reads its ledger (tokens, cost, model, exit reason) from here, the same+ # dict the in-process one-shot wrote from `run_conversation`.+ from gateway.session_results import admission_result+ saved = admission_result(self.authority.db, receipt.admission_id)+ if saved is not None:+ out['result'] = saved['result']+ out['usage'] = saved.get('usage') or {}+ return outasync def cancel(self, ref, params):return asdict(await self.authority.cancel_queued(self.actor, ref, params.get('admission_id')))diff --git a/gateway/session_events.py b/gateway/session_events.pyindex a001b471fca..3dc150657d3 100644--- a/gateway/session_events.py+++ b/gateway/session_events.py@@ -57,9 +57,12 @@ class SessionEvents:return {'jsonrpc': '2.0', 'method': 'event', 'params': {'type': 'session.replay_gap', 'session_id': session_id,'payload': {'replay_epoch': self.epoch, 'latest_seq': self.sequence}}}- self.fanout.write(frame, overflow=overflow)+ delivered = self.fanout.write(frame, overflow=overflow)for observer in tuple(self.observers):observer(frame)+ # True when a live viewer or observer took the frame; the replay ring alone is not+ # delivery (a detached finite viewer reads nothing until it reattaches).+ return delivered or bool(self.observers)def since(self, epoch, sequence):with self.lock:diff --git a/gateway/session_local.py b/gateway/session_local.pyindex 3c45bd73e42..e0fe53a06a2 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -50,6 +50,11 @@ class LocalSessionAdapter(BasePlatformAdapter):async def edit_message(self, chat_id, message_id, content, *, finalize=False):return SendResult(success=True, message_id=message_id)+ async def _record_delivery_obligation(self, *args, **kwargs):+ # No platform ACK to lose: viewers replay the durable transcript. A ledger row would only+ # park a raw copy of the reply in state.db that no redelivery can ever use.+ return None+async def send_typing(self, chat_id, metadata=None):return None@@ -169,7 +174,13 @@ def local_session_info(authority, ref):agent = authority.agent(ref)from gateway.session_policy import policy_for_sourcepolicy = policy_for_source(authority.runner, live.source)- return {'source': policy.source if policy else live.source.platform.value,+ info = {'source': policy.source if policy else live.source.platform.value,'model': getattr(agent, 'model', policy.model if policy else None), 'lazy': agent is None,'profile_id': authority.profile_id, 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,**({'cwd': policy.cwd} if policy else {})}+ if policy:+ # The creation request the route was frozen with (secrets already extracted), so a+ # resuming client can tell "same flags again" from a real override attempt.+ import json+ info['launch_request'] = json.loads(policy.request_json)+ return infodiff --git a/gateway/session_results.py b/gateway/session_results.pyindex 5add3a03586..0e747cb3d8c 100644--- a/gateway/session_results.py+++ b/gateway/session_results.py@@ -8,9 +8,23 @@ execution_result: ContextVar[dict | None] = ContextVar("execution_result", defaufrom hermes_state_terminal import RESULT_PREFIX as _RESULT_PREFIX+def _redacted(value):+ """The stored result is a state.db copy of the model's answer and history: redacted at this+ storage boundary like every transcript row (``security.redact_secrets``). The live viewer+ prints the completion event, never this copy."""+ if isinstance(value, str):+ from agent.redact import redact_sensitive_text+ return redact_sensitive_text(value)+ if isinstance(value, dict):+ return {k: _redacted(v) for k, v in value.items()}+ if isinstance(value, list):+ return [_redacted(v) for v in value]+ return value++def retain_result(db, *, epoch, row, result):return settle_session_input(db, epoch=epoch, admission_id=row['admission_id'],- generation=row['generation'], outcome='completed', result=result)+ generation=row['generation'], outcome='completed', result=_redacted(result))def finish_result(db, *, epoch, row, response, outcome, result=None):@@ -42,7 +56,7 @@ def finish_result(db, *, epoch, row, response, outcome, result=None):value['failed' if outcome == 'failed' else 'interrupted'] = Truevalue['completed'] = Falsesettled = settle_session_input(db, epoch=epoch, admission_id=row['admission_id'],- generation=row['generation'], outcome=outcome, result=result)+ generation=row['generation'], outcome=outcome, result=_redacted(result))return settled, responsediff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.pyindex ebfc175cdf2..13fc37cafa6 100644--- a/hermes_cli/gateway_chat.py+++ b/hermes_cli/gateway_chat.py@@ -16,7 +16,7 @@ from hermes_cli.gateway_client import GatewayClientError, connect_gateway_UNSUPPORTED = ("image", "skills", "worktree", "w", "checkpoints", "pass_session_id","accept_hooks",- "no_restore_cwd", "usage_file",+ "no_restore_cwd","run_budget", "verbose", "compact","list_tools", "list_toolsets",)@@ -32,7 +32,6 @@ _RELOCATED = {"pass_session_id": "`hermes --tui --pass-session-id`","accept_hooks": "`hooks_auto_accept: true` in config.yaml, or `hermes --tui --accept-hooks`","no_restore_cwd": "`--in <dir>` (the gateway keeps the session's frozen cwd)",- "usage_file": "`hermes sessions stats` / `hermes insights` after the run","run_budget": "`agent.run_budget_seconds` in config.yaml","verbose": "`hermes logs --follow`, or `hermes --tui -v`","compact": "`display.compact: true` in config.yaml",@@ -70,10 +69,8 @@ def validate_options(args):where = "".join(f"\n --{name.replace('_', '-')}: use {_RELOCATED[name]}" for name in unsupported)raise GatewayClientError(f"Unsupported gateway CLI options: {flags}. No local fallback or policy changes were made.{where}")- resuming = getattr(args, "resume", None) or (continue_title(args) and not getattr(args, "create_if_missing", False))- if resuming and (getattr(args, "in_dir", None) or getattr(args, "source", None) or- any(getattr(args, name, None) not in (None, False) for name in _POLICY)):- raise GatewayClientError("Resume retains gateway session policy; creation overrides are unsupported on resume.")+ # Creation flags repeated on resume are checked against the frozen route once the snapshot is+ # back (`check_resume_policy`): the same flags again are fine, a different value is refused.if bypass_launch(args) and not getattr(args, "model", None):raise GatewayClientError("--safe-mode / --ignore-user-config read no profile default: pass --model explicitly."f"\n Example: {_SAFE_MODE_EXAMPLE}")@@ -101,6 +98,7 @@ async def run_gateway_chat(args, emitter=None):raise GatewayClientError(f"No session found matching '{name}'. Use 'hermes sessions list' to see available ""sessions, or pass -c <name> --create-if-missing to start a new session with that title.")+ check_resume_policy(args, snapshot)else:contract = description.get("session_create", {})source = getattr(args, "source", None) or "cli"@@ -133,7 +131,8 @@ async def run_gateway_chat(args, emitter=None):quiet = bool(getattr(args, "quiet", False) or oneshot_prompt or emitter is not None)oneshot = bool(oneshot_prompt or getattr(args, "oneshot_exit", False) or quiet or(query and not (sys.stdin.isatty() and sys.stdout.isatty())))- view = GatewayChatView(client, snapshot, quiet=quiet, emitter=emitter)+ view = GatewayChatView(client, snapshot, quiet=quiet, emitter=emitter,+ usage_file=getattr(args, "usage_file", None))if (getattr(args, "resume", None) or title) and not quiet:for row in snapshot.get("messages", []):if row.get("role") in {"user", "assistant"} and isinstance(row.get("content"), str):@@ -141,6 +140,37 @@ async def run_gateway_chat(args, emitter=None):return await view.run(query, oneshot=oneshot)+_RESUME_POLICY_MISMATCH = "Resume retains gateway session policy; creation overrides are unsupported on resume."+++def _requested_policy(args):+ policy = {key: getattr(args, key) for key in _POLICY if getattr(args, key, None) not in (None, False)}+ if isinstance(policy.get("toolsets"), str):+ policy["toolsets"] = [name.strip() for name in policy["toolsets"].split(",") if name.strip()]+ if getattr(args, "source", None):+ policy["source"] = args.source+ return policy+++def check_resume_policy(args, snapshot):+ """A resume may repeat the flags the session was created with (scripts re-run one command+ line); anything that would CHANGE the frozen route is refused, as before."""+ requested = _requested_policy(args)+ if getattr(args, "in_dir", None):+ requested["cwd"] = str(Path(args.in_dir).expanduser().resolve())+ if not requested:+ return+ info = snapshot.get("info") if isinstance(snapshot, dict) else None+ frozen = dict((info or {}).get("launch_request") or {})+ if info and "cwd" in info:+ frozen["cwd"] = info["cwd"]+ for key, value in requested.items():+ if key == "api_key":+ continue # never durable; a repeated key is not a policy change+ if frozen.get(key) != value:+ raise GatewayClientError(_RESUME_POLICY_MISMATCH)++def launch_from_args(args) -> int:from websockets.exceptions import WebSocketExceptionemitter = Nonediff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex f760be085ab..16d85a11d61 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -8,7 +8,8 @@ from hermes_cli.gateway_client import GatewayClientErrorclass GatewayChatView:- def __init__(self, client, snapshot, *, quiet=False, emitter=None):+ def __init__(self, client, snapshot, *, quiet=False, emitter=None, usage_file=None):+ self.usage_file = usage_fileself.client = clientself.session_id = snapshot["stored_session_id"]self.generation = snapshot.get("execution_generation", 0)@@ -195,6 +196,21 @@ class GatewayChatView:return self.emitter.emit_result({"failed": True, "error": message}, session_id=self.session_id, exit_code=3)return 3+ async def _write_usage_file(self, admission, outcome):+ """``-z --usage-file``: the same JSON ledger the in-process one-shot wrote, read from the+ result the owner committed with this admission's settlement (best-effort, never raises)."""+ from hermes_cli.oneshot import _write_usage_file+ result = {}+ try:+ receipt = await self.client.rpc("prompt.receipt", session_id=self.session_id,+ admission_id=admission, include_result=True)+ result = dict(receipt.get("result") or {})+ except Exception:+ pass+ result.setdefault("session_id", self.session_id)+ failure = None if outcome in ("completed", "cancelled") else (result.get("error") or outcome or "failed")+ _write_usage_file(self.usage_file, result, failure=failure)+async def run(self, query=None, *, oneshot=False):self.quiet = self.quiet or oneshotself.finite = oneshot@@ -223,6 +239,8 @@ class GatewayChatView:await self.changed.wait()terminal = self.completions[admission]outcome = terminal.get("outcome")+ if self.usage_file:+ await self._write_usage_file(admission, outcome)if self.emitter is not None:return self.emitter.emit_result({"final_response": terminal.get("text") or terminal.get("content") or "",diff --git a/hermes_state_worker_compression.py b/hermes_state_worker_compression.pyindex ea56be8aaad..718be3c5a3f 100644--- a/hermes_state_worker_compression.py+++ b/hermes_state_worker_compression.py@@ -205,13 +205,19 @@ from hermes_state_errors import CompressionSessionBusyError, SessionCompressionI_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):+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 Nonepatched_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 [])@@ -294,11 +300,19 @@ def _watermarks(payload):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',))+ 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:@@ -310,7 +324,7 @@ def worker_archive(db, conn, sid, payload):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)+ carried_messages=carried, covered_ids=covered, unresolved_held=unresolved)return {'value': value, 'row_ids': [message['_row_id'] for message in payload['messages']]}diff --git a/tools/approval_context.py b/tools/approval_context.pyindex eac2dcb567c..16ca86dafa2 100644--- a/tools/approval_context.py+++ b/tools/approval_context.py@@ -150,7 +150,15 @@ def _is_single_query_approval_context() -> bool:``HERMES_INTERACTIVE=1`` (so sudo password prompts work) but nobody is waitingto answer approvals; without this marker the gate would wait the full timeout,fail closed and push the agent toward workarounds (e.g. execute_code).- ``approvals.single_query_mode`` makes the path deterministic."""+ ``approvals.single_query_mode`` makes the path deterministic. A gateway-admitted turn+ carries the same fact as the submission's ``finite`` flag (``hermes -z`` / ``chat -q``+ over the daemon): the viewer detaches on the first prompt, so nobody answers there either."""+ try:+ from gateway.session_finite import finite_turn_required+ if finite_turn_required() is True:+ return True+ except Exception:+ passreturn is_truthy_value(_session_env("HERMES_SINGLE_QUERY_SESSION"))